From 9bbeeba9cf2fca9c10202865c4f72a49932f8a25 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sat, 28 Nov 2026 16:19:50 +0800 Subject: [PATCH 01/97] feat(fs): add writable shared devtmpfs with device lifecycle updates --- .../userspace-api/device-filesystems.rst | 39 +++ Documentation/userspace-api/index.rst | 1 + block/device/registry.c | 15 +- block/partition/partition_gpt.c | 3 + fs/devfs/Kbuild | 2 +- fs/devfs/devtmpfs.c | 88 ++++++ fs/devfs/devtmpfs_internal.h | 31 ++ fs/devfs/devtmpfs_nodes.c | 270 ++++++++++++++++++ fs/proc/procfs.c | 2 +- fs/tmpfs/core.c | 122 +++++--- fs/vfs/file.c | 38 +-- fs/vfs/storage_backend.c | 21 ++ include/reliefnt/devfs.h | 22 ++ include/reliefnt/mount.h | 5 +- include/reliefnt/tmpfs.h | 7 + kernel/device/service.c | 11 +- kernel/device/sound_service.c | 17 +- kernel/syscall/fs/mount.c | 1 + kernel/workqueue/services.c | 7 +- net/socket/netlink.c | 2 + tools/test_mount_backend.py | 4 +- tools/tests/mount_backend_test.c | 138 ++++++++- tools/tests/storage_mkdir_mount_test.c | 6 +- 23 files changed, 778 insertions(+), 74 deletions(-) create mode 100644 Documentation/userspace-api/device-filesystems.rst create mode 100644 fs/devfs/devtmpfs.c create mode 100644 fs/devfs/devtmpfs_internal.h create mode 100644 fs/devfs/devtmpfs_nodes.c diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst new file mode 100644 index 00000000..b6208afa --- /dev/null +++ b/Documentation/userspace-api/device-filesystems.rst @@ -0,0 +1,39 @@ +================== +设备节点与 devtmpfs +================== + +``mount("devtmpfs", target, "devtmpfs", flags, data)`` 挂载内核维护的设备节点。 +所有挂载共享同一内存文件系统及节点元数据,每个挂载分别维护 ``nodev``、 +``nosuid``、``noexec`` 等挂载点策略。普通文件、目录、符号链接及用户创建的 +设备节点使用现有 VFS 权限检查。设备打开按 inode 的类型和 ``st_rdev`` +分派到驱动,``nodev`` 挂载拒绝打开设备。 + +生命周期 +======== + +设备注册、注销及分区变化通知 VFS worker 合并更新。首次挂载同步生成完整 +设备清单。后续更新保留已有设备的 ``chmod``、``chown``,并尊重用户删除、 +替换和占用的名称。设备移除只删除仍由内核持有的原 inode,非空目录保留。 +内存不足时保留已发布节点与待重试状态。最后一个公开挂载卸载后,私有 backing +继续保留,后续挂载可看到原有内容及权限。 + +设备默认归 root,权限为 ``0600``。``null``、``zero``、``full``、``random``、 +``urandom``、``tty`` 和 ``ptmx`` 为 ``0666``。``fd``、``stdin``、``stdout``、 +``stderr`` 使用指向 ``/proc/self/fd`` 及对应描述符的符号链接。 +``pts`` 和 ``shm`` 提供独立文件系统的挂载目录。 + +挂载选项 +======== + +挂载数据使用 tmpfs 的 ``mode``、``uid``、``gid``、``size``、``nr_blocks`` 和 +``nr_inodes`` 语法。私有 backing 初始为 ``mode=0755,size=0,nr_inodes=0``。 +重新配置先验证整个选项集,再原子提交容量和超级块策略。``mode``、``uid``、 +``gid`` 只在首次创建 tmpfs 时设置根 inode。已有无限容量的实例拒绝追溯增加 +容量上限,已有内容也必须容纳在新上限内,与 Linux shmem 的重新配置约束一致。 + +验证范围 +======== + +``tools/test_mount_backend.py`` 覆盖共享挂载、元数据、设备号、符号链接、 +设备增删、用户替换、挂载策略和内存不足重试。目标系统启动与 udev 集成由 +ReliefOS 的系统迁移验证覆盖。 diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst index d483b17c..f11e6e2d 100644 --- a/Documentation/userspace-api/index.rst +++ b/Documentation/userspace-api/index.rst @@ -10,6 +10,7 @@ abi exec descriptors + device-filesystems inotify ipv6 pidfd diff --git a/block/device/registry.c b/block/device/registry.c index 2af8aa2a..c0476a56 100644 --- a/block/device/registry.c +++ b/block/device/registry.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include +#include #include #include #include @@ -103,7 +104,10 @@ static int device_close(void *context) if(device->users){kernel_spin_unlock_irqrestore(&device_lock,flags);return -EBUSY;} bool linked=device->linked;if(linked)device_unlink_locked(device); kernel_spin_unlock_irqrestore(&device_lock,flags); - if(linked)device_put(device); + if(linked) { + device_put(device); + devtmpfs_notify(); + } return 0; } @@ -160,7 +164,9 @@ int register_block_device(const struct block_device_registration *registration) kernel_spin_unlock_irqrestore(&device_lock,flags); if(result)(void)device_close(device); } - device_put(device);return result; + device_put(device); + if(!result)devtmpfs_notify(); + return result; } /** @brief Unpublish only an idle descriptor, preserving active open/mount users. @@ -177,7 +183,9 @@ int unregister_block_device(const struct block_device_registration *registration if(!device){kernel_spin_unlock_irqrestore(&device_lock,flags);return -ENOENT;} if(device->users){kernel_spin_unlock_irqrestore(&device_lock,flags);return -EBUSY;} device_unlink_locked(device);kernel_spin_unlock_irqrestore(&device_lock,flags); - device_put(device);return 0; + device_put(device); + devtmpfs_notify(); + return 0; } /** @brief Close I/O admission for a physically removed exact block registration. @@ -194,6 +202,7 @@ int disconnect_block_device(const struct block_device_registration *registration while(device && device->registration!=registration)device=device->next; if(device){device->active=false;device->revoked=true;} kernel_spin_unlock_irqrestore(&device_lock,flags); + if(device)devtmpfs_notify(); return device ? 0 : -ENOENT; } EXPORT_SYMBOL(disconnect_block_device); diff --git a/block/partition/partition_gpt.c b/block/partition/partition_gpt.c index b0aa12b6..b848ba57 100644 --- a/block/partition/partition_gpt.c +++ b/block/partition/partition_gpt.c @@ -2,6 +2,7 @@ #include #endif #include "internal.h" +#include /** @brief Map a supported public format selector to its registered native type. * @param filesystem Validated RELIEFOS_DISK_FILESYSTEM selector. @@ -143,6 +144,7 @@ static int disk_gpt_write(struct install_disk_state *disk, struct disk_gpt_table * first sector and keep it invalid on every error path; successful writes * are invalidated again below for clarity. */ disk_block_cache_invalidate_disk(disk); + devtmpfs_notify(); table_crc = storage_crc32(storage_cluster_buf, table->table_bytes); table->backup.partition_entries_crc32 = table_crc; table->backup.header_crc32 = 0; @@ -609,6 +611,7 @@ static int storage_disk_initialize_gpt_owned(const struct reliefos_disk_gpt_init * any extents learned from a previous table before clearing sector 0 and * the GPT copies, including when a later write fails. */ disk_block_cache_invalidate_disk(disk); + devtmpfs_notify(); if (sector_count < 655360ULL) { return -28; } diff --git a/fs/devfs/Kbuild b/fs/devfs/Kbuild index be10541f..7e83f508 100644 --- a/fs/devfs/Kbuild +++ b/fs/devfs/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := devfs.o mount.o identity.o device.o +obj-y := devfs.o mount.o identity.o device.o devtmpfs.o devtmpfs_nodes.o include $(srctree)/scripts/Makefile.module diff --git a/fs/devfs/devtmpfs.c b/fs/devfs/devtmpfs.c new file mode 100644 index 00000000..f259fd43 --- /dev/null +++ b/fs/devfs/devtmpfs.c @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "devtmpfs_internal.h" +#include "../vfs/storage_backend.h" +#include "../vfs/mount_internal.h" +#include "../../block/core/storage_internal.h" +#include +#include +#include +#include + +static struct vfs_mount *devtmpfs_backing; +static struct devtmpfs_node *devtmpfs_managed; +static uint64_t devtmpfs_generation=1,devtmpfs_processed; +static bool devtmpfs_ready; + +/** @brief Coalesce device inventory changes without scanning or allocating. + * IRQ/task safe. Enumeration runs later under VFS execution ownership. + */ +void devtmpfs_changed(void) +{ + __atomic_add_fetch(&devtmpfs_generation,1,__ATOMIC_RELEASE); + if(__atomic_load_n(&devtmpfs_ready,__ATOMIC_ACQUIRE)) + kernel_deferred_schedule(DEFERRED_VFS); +} + +/** @brief Report coalesced inventory work after the first devtmpfs mount. + * @return True when a live backing filesystem needs reconciliation. + */ +bool devtmpfs_pending(void) +{ + return __atomic_load_n(&devtmpfs_ready,__ATOMIC_ACQUIRE) && + devtmpfs_processed!=__atomic_load_n(&devtmpfs_generation,__ATOMIC_ACQUIRE); +} + +/** @brief Refresh kernel-managed nodes while preserving user-owned entries. + * @return Zero or negative errno. Execution ownership required. An error or an + * event arriving during enumeration leaves work pending for a later retry. + */ +int devtmpfs_refresh(void) +{ + if(!devtmpfs_pending())return 0; + uint64_t generation=__atomic_load_n(&devtmpfs_generation,__ATOMIC_ACQUIRE); + struct devtmpfs_node *snapshot=NULL; + int rc=devtmpfs_snapshot(&snapshot); + if(rc)return rc; + struct storage_volume *volume=devtmpfs_backing->context; + /* Kernel device publication is independent of a userspace readonly mount. + * No task can observe the temporary backend flag under execution ownership. + */ + tmpfs_set_flags(volume->tmpfs,volume->mount_flags&~MS_RDONLY); + rc=devtmpfs_reconcile(volume->tmpfs,&devtmpfs_managed,snapshot); + tmpfs_set_flags(volume->tmpfs,volume->mount_flags); + if(!rc)devtmpfs_processed=generation; + return rc; +} + +/** @brief Attach the permanent Linux-style shared device memory filesystem. + * @param source Optional mount label. @param flags Linux mount flags. + * @param options Optional tmpfs mount data. @param out Owned detached mount. + * @return Zero or negative errno. Execution ownership serializes construction + * and quota/policy changes. The private reference survives all public unmounts. + */ +int devtmpfs_create_vfs_mount(const char *source,uint64_t flags,const char *options, + struct vfs_mount **out) +{ + if(!out)return -EINVAL; + *out=NULL; + if(flags&~(VFS_MOUNT_POLICY_MASK|VFS_SUPER_POLICY_MASK|MS_STRICTATIME))return -EOPNOTSUPP; + if(!devtmpfs_backing) { + int rc=storage_new_tmpfs_mount("devtmpfs",0,"mode=0755,size=0,nr_inodes=0",0,0,&devtmpfs_backing); + if(rc)return rc; + __atomic_store_n(&devtmpfs_ready,true,__ATOMIC_RELEASE); + } + struct storage_volume *volume=devtmpfs_backing->context; + int rc=tmpfs_reconfigure(volume->tmpfs,options,false); + if(rc)return rc; + rc=devtmpfs_refresh(); + if(rc)return rc; + rc=storage_create_vfs_mount(volume,NULL,out); + if(!rc)rc=vfs_mount_describe(*out,source && source[0] ? source : "devtmpfs", + "devtmpfs",storage_volume_device_number(volume)); + if(!rc)rc=devtmpfs_backing->ops->remount_options(volume,flags&VFS_SUPER_POLICY_MASK,options); + if(rc) { + vfs_mount_put(*out); + *out=NULL; + } + return rc; +} diff --git a/fs/devfs/devtmpfs_internal.h b/fs/devfs/devtmpfs_internal.h new file mode 100644 index 00000000..fce2e9f4 --- /dev/null +++ b/fs/devfs/devtmpfs_internal.h @@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_DEVTMPFS_INTERNAL_H +#define RELIEFNT_DEVTMPFS_INTERNAL_H +#include + +struct devtmpfs_node { + struct devtmpfs_node *next; + uint64_t device; + uint32_t mode, ino; + bool seen; + char target[48]; + char path[RELIEFOS_FS_PATH_LEN]; +}; +/** @brief Snapshot the intrinsic device hierarchy before changing any nodes. + * @param out Owned preorder list, empty on failure. Execution ownership required. + * @return Zero or enumeration/allocation errno. No namespace paths are followed. + */ +int devtmpfs_snapshot(struct devtmpfs_node **out); +/** @brief Release a snapshot and its optional retained tmpfs inode references. + * @param fs Owning filesystem, NULL for an unbound snapshot. @param nodes List. + */ +void devtmpfs_nodes_free(struct tmpfs_super *fs,struct devtmpfs_node *nodes); +/** @brief Reconcile one complete inventory with retained device inode identities. + * @param fs Serialized backing filesystem. @param managed Persistent owned list. + * @param snapshot Complete fresh inventory, consumed on all paths. + * @return Zero or allocation/provider errno. User replacements and metadata + * survive unrelated device changes. Failed snapshots never reach this helper. + */ +int devtmpfs_reconcile(struct tmpfs_super *fs,struct devtmpfs_node **managed, + struct devtmpfs_node *snapshot); +#endif diff --git a/fs/devfs/devtmpfs_nodes.c b/fs/devfs/devtmpfs_nodes.c new file mode 100644 index 00000000..87205ddd --- /dev/null +++ b/fs/devfs/devtmpfs_nodes.c @@ -0,0 +1,270 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "internal.h" +#include "../../block/core/storage_core_api.h" +#include "devtmpfs_internal.h" +#include +#include +#include + +/** @brief Allocate one intrinsic inventory entry with root-owned defaults. + * @param path Absolute intrinsic /dev path. @param native Optional provider node. + * @param target Optional symlink payload. @param out Owned result on success. + * @return Zero or allocation/type errno. No device is opened or retained. + */ +static int devtmpfs_snapshot_node(const char *path,const struct storage_node *native, + const char *target,struct devtmpfs_node **out) +{ + struct devtmpfs_node *node=kernel_malloc(sizeof(*node)); + if(!node)return -ENOMEM; + *node=(struct devtmpfs_node){0}; + __builtin_memcpy(node->path,path,__builtin_strlen(path)+1); + if(target) { + node->mode=LINUX_S_IFLNK|0777; + __builtin_memcpy(node->target,target,__builtin_strlen(target)+1); + } else if(native->type==RELIEFOS_FS_TYPE_DIR) { + node->mode=LINUX_S_IFDIR|0755; + if(!__builtin_strcmp(path,"/dev/shm"))node->mode=LINUX_S_IFDIR|01777; + } else if(native->type==RELIEFOS_FS_TYPE_SYMLINK) { + node->mode=LINUX_S_IFLNK|0777; + int rc=storage_devlink_target(path,node->target); + if(rc){kernel_free(node);return rc;} + } else if(native->type==RELIEFOS_FS_TYPE_DEVICE) { + uint32_t type=native->flags&STORAGE_NODE_FLAG_DEV_BLOCK ? LINUX_S_IFBLK : LINUX_S_IFCHR; + struct linux_stat_abi stat={.st_mode=type}; + devfs_stat_identity(&stat,native); + node->device=stat.st_rdev; + node->mode=type|0600; + if(!__builtin_strcmp(path,"/dev/null") || !__builtin_strcmp(path,"/dev/zero") || + !__builtin_strcmp(path,"/dev/full") || !__builtin_strcmp(path,"/dev/random") || + !__builtin_strcmp(path,"/dev/urandom") || !__builtin_strcmp(path,"/dev/tty") || + !__builtin_strcmp(path,"/dev/ptmx"))node->mode=type|0666; + } else { + kernel_free(node); + return -EOPNOTSUPP; + } + *out=node; + return 0; +} + +/** @brief Collect a provider directory in preorder, with no namespace lookup. + * @param path Intrinsic provider directory. @param directory Borrowed metadata. + * @param tail List tail insertion cursor. @return Zero or negative errno. + * Provider directories have at most two nested levels. pts and shm are writable + * mountpoints whose dynamic contents belong to their own filesystems. + */ +static int devtmpfs_snapshot_directory(const char *path,const struct storage_node *directory, + struct devtmpfs_node ***tail) +{ + uint64_t cursor=0; + struct reliefos_dir_entry entry; + int rc; + while((rc=storage_devfs_readdir_node(directory,&cursor,&entry))>0) { + if(!__builtin_strcmp(entry.name,".") || !__builtin_strcmp(entry.name,".."))continue; + size_t length=0,base=__builtin_strlen(path); + while(lengthsizeof(child))return -ENAMETOOLONG; + __builtin_memcpy(child,path,base); + child[base]='/'; + __builtin_memcpy(child+base+1,entry.name,length+1); + const char *target=NULL; + if(!__builtin_strcmp(child,"/dev/stdin"))target="/proc/self/fd/0"; + if(!__builtin_strcmp(child,"/dev/stdout"))target="/proc/self/fd/1"; + if(!__builtin_strcmp(child,"/dev/stderr"))target="/proc/self/fd/2"; + struct storage_node native={.type=entry.type}; + if(!target && __builtin_strcmp(child,"/dev/shm")) { + rc=storage_devfs_lookup(child,&native); + if(rc==-ENOENT || rc==-ENODEV)continue; + if(rc)return rc; + } + struct devtmpfs_node *node=NULL; + rc=devtmpfs_snapshot_node(child,&native,target,&node); + if(rc==-ENOENT || rc==-ENODEV)continue; + if(rc)return rc; + **tail=node; + *tail=&node->next; + if(native.type==RELIEFOS_FS_TYPE_DIR && __builtin_strcmp(child,"/dev/pts") && + __builtin_strcmp(child,"/dev/shm")) { + rc=devtmpfs_snapshot_directory(child,&native,tail); + if(rc)return rc; + } + } + return rc; +} + +/** @brief Free an inventory list and release each retained backing inode. + * @param fs Owning tmpfs, or NULL for snapshots without inode references. + * @param nodes Owned list, consumed even when empty. Execution ownership held. + */ +void devtmpfs_nodes_free(struct tmpfs_super *fs,struct devtmpfs_node *nodes) +{ + while(nodes) { + struct devtmpfs_node *next=nodes->next; + if(fs && nodes->ino)tmpfs_drop(fs,nodes->ino); + kernel_free(nodes); + nodes=next; + } +} + +/** @brief Collect the complete intrinsic device inventory before publication. + * @param out Owned preorder list on success, NULL on failure. + * @return Zero or negative errno. Execution ownership serializes enumeration. + */ +int devtmpfs_snapshot(struct devtmpfs_node **out) +{ + *out=NULL; + struct storage_node root; + int rc=storage_devfs_lookup("/dev",&root); + struct devtmpfs_node **tail=out; + if(!rc)rc=devtmpfs_snapshot_directory("/dev",&root,&tail); + if(!rc)rc=devtmpfs_snapshot_node("/dev/fd",NULL,"/proc/self/fd",tail); + if(rc){devtmpfs_nodes_free(NULL,*out);*out=NULL;} + return rc; +} + +/** @brief Resolve a parent using only actual tmpfs directory inode identities. + * @param fs Serialized backing. @param path Intrinsic /dev path. + * @param parent Borrowed parent result. @param name Last component output. + * @return Zero or negative errno. User-created parent symlinks are never followed. + */ +static int devtmpfs_parent(struct tmpfs_super *fs,const char *path, + struct storage_node *parent,char name[RELIEFOS_FS_NAME_LEN]) +{ + int rc=tmpfs_lookup(fs,"/",parent); + const char *component=path+5; + while(!rc) { + size_t length=0; + while(component[length] && component[length]!='/')++length; + if(!length || length>=RELIEFOS_FS_NAME_LEN)return -ENAMETOOLONG; + __builtin_memcpy(name,component,length); + name[length]=0; + if(!component[length])return 0; + struct storage_node child; + rc=tmpfs_lookup_child(fs,parent->first_cluster,name,&child); + if(rc)return rc; + if(child.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; + *parent=child; + component+=length+1; + } + return rc; +} + +/** @brief Check kernel ownership by held inode identity, type and device number. + * @param fs Serialized backing. @param owned Managed inventory record. + * @param current Borrowed candidate inode. @return True only for our exact inode. + */ +static bool devtmpfs_matches(struct tmpfs_super *fs,const struct devtmpfs_node *owned, + const struct storage_node *current) +{ + if(!owned->ino || current->first_cluster!=owned->ino)return false; + struct linux_stat_abi stat; + return !tmpfs_stat(fs,owned->ino,&stat) && + (stat.st_mode&LINUX_S_IFMT)==(owned->mode&LINUX_S_IFMT) && + stat.st_rdev==owned->device; +} + +/** @brief Remove a disappeared device only if its owned inode still occupies it. + * @param fs Serialized backing. @param owned Record retaining its inode. + * @return Zero or negative errno. Replacements and nonempty directories survive. + */ +static int devtmpfs_remove(struct tmpfs_super *fs,const struct devtmpfs_node *owned) +{ + struct storage_node parent,current; + char name[RELIEFOS_FS_NAME_LEN]; + int rc=devtmpfs_parent(fs,owned->path,&parent,name); + if(rc==-ENOENT || rc==-ENOTDIR)return 0; + if(rc)return rc; + rc=tmpfs_lookup_child(fs,parent.first_cluster,name,¤t); + if(rc==-ENOENT)return 0; + if(rc)return rc; + if(!devtmpfs_matches(fs,owned,¤t))return 0; + rc=tmpfs_unlink_child(fs,parent.first_cluster,name,(owned->mode&LINUX_S_IFMT)==LINUX_S_IFDIR); + return rc==-ENOTEMPTY ? 0 : rc; +} + +/** @brief Publish a new inventory entry unless userspace owns its name or parent. + * @param fs Serialized backing. @param node New record receiving an inode hold. + * @return Zero or negative errno. Existing names are recorded without ownership. + */ +static int devtmpfs_add(struct tmpfs_super *fs,struct devtmpfs_node *node) +{ + struct storage_node parent,current; + char name[RELIEFOS_FS_NAME_LEN]; + int rc=devtmpfs_parent(fs,node->path,&parent,name); + if(rc==-ENOENT || rc==-ENOTDIR)return 0; + if(rc)return rc; + rc=tmpfs_lookup_child(fs,parent.first_cluster,name,¤t); + if(!rc)return 0; + if(rc!=-ENOENT)return rc; + struct reliefos_permissions permissions={.mode=node->mode&07777,.uid=0,.gid=0}; + uint32_t type=node->mode&LINUX_S_IFMT; + if(type==LINUX_S_IFCHR || type==LINUX_S_IFBLK) + rc=tmpfs_mknod_child(fs,parent.first_cluster,name,node->mode,node->device,&permissions,¤t); + else rc=tmpfs_create_child(fs,parent.first_cluster,name,node->mode, + type==LINUX_S_IFLNK ? node->target : NULL,&permissions,¤t); + if(rc)return rc; + rc=tmpfs_hold(fs,current.first_cluster); + if(!rc)node->ino=current.first_cluster; + return rc; +} + +/** @brief Apply a complete device snapshot to retained backing inode records. + * @param fs Serialized tmpfs backing. @param managed Owned persistent records. + * @param snapshot Complete inventory, consumed on every return path. + * @return Zero or negative errno. User metadata and replacement inodes survive. + * Partial failures retain ownership records so the next refresh can retry. + */ +int devtmpfs_reconcile(struct tmpfs_super *fs,struct devtmpfs_node **managed, + struct devtmpfs_node *snapshot) +{ + for(struct devtmpfs_node *old=*managed;old;old=old->next)old->seen=false; + int rc=0; + while(snapshot) { + struct devtmpfs_node *node=snapshot; + struct devtmpfs_node *old=*managed; + while(old && __builtin_strcmp(old->path,node->path))old=old->next; + if(old && (old->mode&LINUX_S_IFMT)==(node->mode&LINUX_S_IFMT) && old->device==node->device) { + if((node->mode&LINUX_S_IFMT)==LINUX_S_IFLNK && __builtin_strcmp(old->target,node->target)) { + struct storage_node parent,current; + char name[RELIEFOS_FS_NAME_LEN]; + rc=devtmpfs_parent(fs,old->path,&parent,name); + if(!rc)rc=tmpfs_lookup_child(fs,parent.first_cluster,name,¤t); + if(!rc && devtmpfs_matches(fs,old,¤t))rc=tmpfs_rewrite_symlink(fs,old->ino,node->target); + if(rc==-ENOENT || rc==-ENOTDIR)rc=0; + if(rc)break; + __builtin_memcpy(old->target,node->target,__builtin_strlen(node->target)+1); + } + old->seen=true; + } else { + if(old) { + rc=devtmpfs_remove(fs,old); + if(rc)break; + } + rc=devtmpfs_add(fs,node); + if(rc)break; + } + snapshot=node->next; + if(!old || !old->seen) { + node->seen=true; + node->next=*managed; + *managed=node; + } else kernel_free(node); + } + devtmpfs_nodes_free(NULL,snapshot); + if(rc)return rc; + /* Records are prepended as parents/children are created, so children retire + * first. An inode hold prevents reuse from confusing deletion ownership. + */ + struct devtmpfs_node **link=managed; + while(*link) { + struct devtmpfs_node *old=*link; + if(old->seen){link=&old->next;continue;} + rc=devtmpfs_remove(fs,old); + if(rc)return rc; + *link=old->next; + old->next=NULL; + devtmpfs_nodes_free(fs,old); + } + return 0; +} diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 481273d2..68093d4f 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -280,7 +280,7 @@ static int proc_fill_content(const char *path, char *buffer, uint32_t capacity) #ifdef CONFIG_SQUASHFS proc_append_text(buffer, &pos, capacity, "\tsquashfs\n"); #endif - proc_append_text(buffer, &pos, capacity, "nodev\tproc\nnodev\tdevfs\nnodev\tsysfs\nnodev\ttmpfs\n"); + proc_append_text(buffer, &pos, capacity, "nodev\tproc\nnodev\tdevfs\nnodev\tdevtmpfs\nnodev\tsysfs\nnodev\ttmpfs\n"); return 0; } if (proc_text_eq(path, "/proc/asound/cards")) { diff --git a/fs/tmpfs/core.c b/fs/tmpfs/core.c index 5490a93d..501938bd 100644 --- a/fs/tmpfs/core.c +++ b/fs/tmpfs/core.c @@ -233,30 +233,26 @@ int tmpfs_create_anonymous(struct tmpfs_super *fs, uint32_t uid, uint32_t gid, return 0; } -int tmpfs_new(uint32_t volume, uint64_t flags, const char *options, uint32_t uid, uint32_t gid, - struct tmpfs_super **out) +/** @brief Parsed tmpfs policy prepared before mutating any live instance. */ +struct tmpfs_options { + uint64_t max_pages, max_inodes; + uint32_t mode, uid, gid; +}; + +/** @brief Parse Linux tmpfs mount data into caller-owned candidate policy. + * @param options Optional comma-separated mount data. + * @param parsed Candidate initialized with current/default values. + * @return Zero or -EINVAL. Failure never changes a live filesystem. + */ +static int tmpfs_parse_options(const char *options, struct tmpfs_options *parsed) { - if (!out) - return -22; - *out = NULL; - struct tmpfs_super *fs = kernel_malloc(sizeof(*fs)); - if (!fs) - return -12; - __builtin_memset(fs, 0, sizeof(*fs)); - fs->volume = volume; - fs->next_ino = 1; - fs->lookup_generation = 1; - fs->flags = flags; - fs->max_pages = fs->max_inodes = mm_total_memory_kib() / 8; /* Half RAM, in pages. */ - uint32_t mode = 01777; const char *p = options ? options : ""; - int ret = -22; while (*p) { char option[128]; unsigned length = 0; while (*p && *p != ',') { if (length + 1 == sizeof(option)) - goto fail; + return -22; option[length++] = *p++; } if (*p) @@ -268,7 +264,7 @@ int tmpfs_new(uint32_t volume, uint64_t flags, const char *options, uint32_t uid while (*value && *value != '=') ++value; if (!*value) - goto fail; + return -22; *value++ = 0; uint64_t number; bool is_mode = !__builtin_strcmp(option, "mode"); @@ -276,45 +272,91 @@ int tmpfs_new(uint32_t volume, uint64_t flags, const char *options, uint32_t uid bool is_blocks = !__builtin_strcmp(option, "nr_blocks"); bool is_inodes = !__builtin_strcmp(option, "nr_inodes"); if (tmpfs_number(value, &number, is_mode ? 8 : 10, is_size || is_blocks || is_inodes, is_size)) - goto fail; + return -22; if (is_size) { if (number > UINT64_MAX - 4095) - goto fail; - fs->max_pages = (number + 4095) / 4096; + return -22; + parsed->max_pages = (number + 4095) / 4096; } else if (is_blocks) { if (number > INT64_MAX) - goto fail; - fs->max_pages = number; + return -22; + parsed->max_pages = number; } else if (is_inodes) { if (number > UINT32_MAX) - goto fail; - fs->max_inodes = number; + return -22; + parsed->max_inodes = number; } else if (is_mode) { if (number > UINT32_MAX) - goto fail; - mode = number & 07777; + return -22; + parsed->mode = number & 07777; } else if (!__builtin_strcmp(option, "uid")) { if (number >= UINT32_MAX) - goto fail; - uid = number; + return -22; + parsed->uid = number; } else if (!__builtin_strcmp(option, "gid")) { if (number >= UINT32_MAX) - goto fail; - gid = number; + return -22; + parsed->gid = number; } else - goto fail; + return -22; + } + return 0; +} + +/** @brief Validate or commit quota changes without reinitializing root metadata. + * @param fs Live execution-owned filesystem. + * @param options Optional Linux tmpfs mount data. + * @param apply Commit after validation when true, otherwise leave state intact. + * @return Zero or -EINVAL. Unlimited instances cannot become limited, and a + * new limit must contain existing allocations. Mode/uid/gid only apply during + * initial creation, matching Linux shmem reconfiguration semantics. + */ +int tmpfs_reconfigure(struct tmpfs_super *fs, const char *options, bool apply) +{ + if (!fs) return -22; + struct tmpfs_options parsed = { + .max_pages = fs->max_pages, .max_inodes = fs->max_inodes + }; + int rc = tmpfs_parse_options(options, &parsed); + if (rc) return rc; + if ((parsed.max_pages && (!fs->max_pages || parsed.max_pages < fs->used_pages)) || + (parsed.max_inodes && (!fs->max_inodes || parsed.max_inodes < fs->used_inodes))) + return -22; + if (apply) { + fs->max_pages = parsed.max_pages; + fs->max_inodes = parsed.max_inodes; + } + return 0; +} + +int tmpfs_new(uint32_t volume, uint64_t flags, const char *options, uint32_t uid, uint32_t gid, + struct tmpfs_super **out) +{ + if (!out) return -22; + *out = NULL; + struct tmpfs_options parsed = { + .max_pages = mm_total_memory_kib() / 8, + .max_inodes = mm_total_memory_kib() / 8, + .mode = 01777, .uid = uid, .gid = gid + }; + int ret = tmpfs_parse_options(options, &parsed); + if (ret) return ret; + struct tmpfs_super *fs = kernel_malloc(sizeof(*fs)); + if (!fs) return -12; + *fs = (struct tmpfs_super){ + .volume = volume, .next_ino = 1, .lookup_generation = 1, + .flags = flags, .max_pages = parsed.max_pages, .max_inodes = parsed.max_inodes + }; + ret = tmpfs_alloc_inode(fs, LINUX_S_IFDIR | parsed.mode, &fs->root); + if (ret) { + tmpfs_destroy(fs); + return ret; } - ret = tmpfs_alloc_inode(fs, LINUX_S_IFDIR | mode, &fs->root); - if (ret) - goto fail; fs->root->parent = fs->root; - fs->root->stat.st_uid = uid; - fs->root->stat.st_gid = gid; + fs->root->stat.st_uid = parsed.uid; + fs->root->stat.st_gid = parsed.gid; *out = fs; return 0; -fail: - tmpfs_destroy(fs); - return ret; } static struct tmpfs_entry **tmpfs_find(struct tmpfs_inode *dir, const char *name) { diff --git a/fs/vfs/file.c b/fs/vfs/file.c index ccdf373e..0944b882 100644 --- a/fs/vfs/file.c +++ b/fs/vfs/file.c @@ -147,7 +147,7 @@ int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags) * lock spans the optional shared-policy callback. Strictatime clears noatime * and relatime. All other attachment policy changes affect this mount alone. */ -int vfs_path_remount(const struct vfs_path *path,uint64_t flags) +static int vfs_remount(const struct vfs_path *path,uint64_t flags,const char *options) { if(!vfs_path_valid(path) || !path->mount->ns || path->dentry!=path->mount->root)return -EINVAL; if(flags&~(VFS_MOUNT_POLICY_MASK|VFS_SUPER_POLICY_MASK|MS_STRICTATIME))return -EOPNOTSUPP; @@ -156,27 +156,33 @@ int vfs_path_remount(const struct vfs_path *path,uint64_t flags) uint64_t policy=vfs_policy_bits(flags),shared=flags&VFS_SUPER_POLICY_MASK; if(!(flags&(atime|MS_STRICTATIME)))policy|=mount->policy&atime; int rc=0; - if(mount->ops->remount)rc=mount->ops->remount(mount->context,shared); + if(mount->ops->remount_options) + rc=mount->ops->remount_options(mount->context,shared,options); + else if(options && options[0])rc=-EOPNOTSUPP; + else if(mount->ops->remount)rc=mount->ops->remount(mount->context,shared); else if(shared!=vfs_super_flags(mount))rc=(vfs_super_flags(mount)&MS_RDONLY) && !(shared&MS_RDONLY) ? -EROFS : -EOPNOTSUPP; - if(!rc)mount->policy=policy;return rc; + if(!rc)mount->policy=policy; + return rc; +} + +/** @brief Remount an attached filesystem without filesystem-specific options. + * @param path Retained mounted root. @param flags Requested Linux mount policy. + * @return Zero or negative errno, preserving policy on failure. + */ +int vfs_path_remount(const struct vfs_path *path,uint64_t flags) +{ + return vfs_remount(path,flags,NULL); } -/** @brief Accept an unchanged ext3 ordered mode on the actual selected mount. - * @param path Retained mounted filesystem root, required. - * @param flags Requested final mount and filesystem policy. - * @param options Optional copied filesystem data, empty or data=ordered. - * @return Zero or negative option/type/provider errno. Option validation occurs - * before policy changes. Execution ownership retains metadata and provider code. +/** @brief Reconfigure backend options and mount policy in one transaction. + * @param path Retained mounted root. @param flags Requested Linux mount policy. + * @param options Optional filesystem-specific data, validated by its backend. + * @return Zero or negative errno, preserving options and policy on failure. + * Execution ownership retains the provider and serializes validation/commit. */ int vfs_path_remount_options(const struct vfs_path *path,uint64_t flags,const char *options) { - if (!vfs_path_valid(path)) return -EINVAL; - if (options && options[0]) { - const char *filesystem=path->mount->filesystem; - if (!filesystem || __builtin_strcmp(filesystem,"ext3") || - __builtin_strcmp(options,"data=ordered")) return -EOPNOTSUPP; - } - return vfs_path_remount(path,flags); + return vfs_remount(path,flags,options); } int vfs_path_dirent_stat(const struct vfs_path *directory,const char *name,struct linux_stat_abi *out) diff --git a/fs/vfs/storage_backend.c b/fs/vfs/storage_backend.c index 356f5ab6..6bffb12d 100644 --- a/fs/vfs/storage_backend.c +++ b/fs/vfs/storage_backend.c @@ -191,6 +191,26 @@ static int storage_vfs_remount(void *context,uint64_t flags) (storage_inode_volume_writers(volume->volume_id) || storage_inode_volume_swap_active(volume->volume_id)))return -EBUSY; volume->mount_flags=flags;if(volume->tmpfs)tmpfs_set_flags(volume->tmpfs,flags);return 0; } +/** @brief Validate backend mount data before committing shared policy. + * @param context Retained storage volume under execution ownership. + * @param flags Shared superblock flags. @param options Optional mount data. + * @return Zero or negative errno. A failed validation or readonly transition + * leaves flags and quotas unchanged. Quota commit cannot allocate or fail + * after its validation in this execution transaction. + */ +static int storage_vfs_remount_options(void *context,uint64_t flags,const char *options) +{ + struct storage_volume *volume=context; + int rc=0; + if(volume->tmpfs)rc=tmpfs_reconfigure(volume->tmpfs,options,false); + else if(options && options[0] && + (volume->filesystem!=STORAGE_FILESYSTEM_EXT3 || __builtin_strcmp(options,"data=ordered"))) + rc=-EOPNOTSUPP; + if(rc)return rc; + rc=storage_vfs_remount(context,flags); + if(!rc && volume->tmpfs)rc=tmpfs_reconfigure(volume->tmpfs,options,true); + return rc; +} static int storage_vfs_can_unmount(void *context,void *pin) { struct storage_volume *volume=context; @@ -266,6 +286,7 @@ static const struct vfs_backend_ops storage_vfs_ops={ .lookup=storage_backend_lookup_vfs,.retain=storage_vfs_retain,.release=storage_vfs_release, .same_node=storage_backend_same_node,.readlink=storage_vfs_readlink, .finish=storage_vfs_finish,.destroy=storage_vfs_destroy,.can_unmount=storage_vfs_can_unmount,.remount=storage_vfs_remount, + .remount_options=storage_vfs_remount_options, .read=storage_vfs_read,.read_cursor=storage_vfs_read_cursor,.readdir=storage_vfs_readdir,.permissions=storage_backend_permissions, .mount_flags=storage_vfs_flags,.create_node=storage_backend_create_node, .getattr=storage_backend_getattr,.statfs=storage_backend_statfs, diff --git a/include/reliefnt/devfs.h b/include/reliefnt/devfs.h index b91fba53..a372838a 100644 --- a/include/reliefnt/devfs.h +++ b/include/reliefnt/devfs.h @@ -29,4 +29,26 @@ void devfs_stat_identity(struct linux_stat_abi *out,const struct storage_node *n * references transfer and no graph/module lock spans provider metadata I/O. */ int devfs_lookup_rdev(uint32_t type,uint64_t device,struct storage_node *out); +/** @brief Create a shared writable device filesystem mount. + * @param source Diagnostic mount source. @param flags Linux mount flags. + * @param options Optional tmpfs mount data. @param out Owned detached mount. + * @return Zero or negative errno. Requires execution ownership. + */ +int devtmpfs_create_vfs_mount(const char *source,uint64_t flags,const char *options, + struct vfs_mount **out); +/** @brief Mark the device inventory dirty without allocation or hardware I/O. + * IRQ/task safe. Standalone device fixtures may omit devtmpfs entirely. + */ +void devtmpfs_changed(void) __attribute__((weak)); +/** @brief Notify mounted devtmpfs instances after releasing device registry locks. */ +static inline void devtmpfs_notify(void) +{ + if(devtmpfs_changed)devtmpfs_changed(); +} +/** @brief Query deferred inventory work. Execution ownership required. */ +bool devtmpfs_pending(void); +/** @brief Reconcile coalesced device changes. Execution ownership required. + * @return Zero or negative errno, retaining pending work on failure. + */ +int devtmpfs_refresh(void); #endif diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index f467a253..b75435aa 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -98,6 +98,9 @@ struct vfs_backend_ops { * preserve old flags. Attachment policy belongs to VFS, not context. * Caller separately authorizes and owns this mount. */ int (*remount)(void *context,uint64_t flags); + /* Optional atomic filesystem option/shared-policy reconfiguration. Failure + * preserves both options and flags. Execution ownership is held. */ + int (*remount_options)(void *context,uint64_t flags,const char *options); /* Optional positional I/O through the retained backend inode. Callers * retain the mount/provider while these callbacks run without graph locks. * mount_flags is the current attachment policy plus shared superblock @@ -239,7 +242,7 @@ int vfs_path_remount(const struct vfs_path *path,uint64_t flags); /** @brief Validate filesystem-specific options before changing remount policy. * @param path Retained mounted filesystem root, required. * @param flags Final policy excluding MS_REMOUNT. - * @param options Optional copied data, empty or ext3 data=ordered. + * @param options Optional copied filesystem-specific data validated by its backend. * @return Zero or negative option/type/provider errno. Unsupported data leaves * the attachment unchanged. The retained mount determines the filesystem type. * Caller holds execution ownership and has checked CAP_SYS_ADMIN. diff --git a/include/reliefnt/tmpfs.h b/include/reliefnt/tmpfs.h index 0d8fb1e7..3b1ba8b7 100644 --- a/include/reliefnt/tmpfs.h +++ b/include/reliefnt/tmpfs.h @@ -11,6 +11,13 @@ struct tmpfs_super; uint64_t tmpfs_lookup_generation(const struct tmpfs_super *fs); int tmpfs_new(uint32_t volume, uint64_t flags, const char *options, uint32_t uid, uint32_t gid, struct tmpfs_super **out); +/** @brief Validate or apply Linux tmpfs quota reconfiguration atomically. + * @param fs Live filesystem under execution ownership. @param options Mount data. + * @param apply Commit quotas when true, validate without mutation when false. + * @return Zero or -EINVAL, preserving root mode/ownership and all inode data. + * Unlimited quotas cannot become limited. New limits must contain allocations. + */ +int tmpfs_reconfigure(struct tmpfs_super *fs, const char *options, bool apply); void tmpfs_destroy(struct tmpfs_super *fs); /** * @brief Create an unlinked regular inode under the storage execution lock. diff --git a/kernel/device/service.c b/kernel/device/service.c index 2e65d31c..5f20ce95 100644 --- a/kernel/device/service.c +++ b/kernel/device/service.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include +#include #include #include #include @@ -41,7 +42,11 @@ static int service_binding_stop(void *value) binding->linked=false;binding->active=false;detached=true; } kernel_spin_unlock_irqrestore(&service_binding_lock,flags); - if(detached)service_binding_put(binding);return rc; + if(detached) { + service_binding_put(binding); + devtmpfs_notify(); + } + return rc; } /** @brief Consume a fully stopped module cleanup-ledger binding reference. * @param value Owned ledger reference, consumed once. @@ -75,7 +80,9 @@ int kernel_service_register(struct kernel_service_slot *slot,const struct kernel } else rc=-EBUSY; kernel_spin_unlock_irqrestore(&service_binding_lock,flags); } - service_binding_put(binding);return rc; + service_binding_put(binding); + if(!rc)devtmpfs_notify(); + return rc; } /** @brief Detach an idle exact table without rebinding a former provider's token. * @param slot Permanent core slot. @param descriptor Exact immutable identity. diff --git a/kernel/device/sound_service.c b/kernel/device/sound_service.c index 5785f95b..3e2cddc3 100644 --- a/kernel/device/sound_service.c +++ b/kernel/device/sound_service.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include +#include #include #include #include @@ -63,7 +64,9 @@ int sound_service_register_card(const struct audio_card_identity * identity,cons if(!kernel_service_acquire(&sound_service_slot,&call))return -ENODEV; const struct sound_service_operations *provider_ops=call.operations; int result=provider_ops->register_card ? provider_ops->register_card(identity,operations,context,owner,out_id) : -ENODEV; - kernel_service_release(&call);return result; + kernel_service_release(&call); + if(!result)devtmpfs_notify(); + return result; } /** @brief Disconnect one card through the original sound provider. * @param card Exact registered token. @@ -78,7 +81,9 @@ int sound_service_unregister_card(uint32_t card,uint32_t force) if(!kernel_service_acquire(&sound_service_slot,&call))return -ENODEV; const struct sound_service_operations *provider_ops=call.operations; int result=provider_ops->unregister_card ? provider_ops->unregister_card(card,force) : -ENODEV; - kernel_service_release(&call);return result; + kernel_service_release(&call); + if(!result)devtmpfs_notify(); + return result; } /** @brief Drain sound cards before their hardware owner retires. * @param owner Driver-manager slot to drain. @@ -93,7 +98,9 @@ int sound_service_unregister_owner(uint32_t owner,uint32_t force) if(!kernel_service_acquire(&sound_service_slot,&call))return 0; const struct sound_service_operations *provider_ops=call.operations; int result=provider_ops->unregister_owner ? provider_ops->unregister_owner(owner,force) : 0; - kernel_service_release(&call);return result; + kernel_service_release(&call); + if(!result)devtmpfs_notify(); + return result; } /** @brief Change a card service while retaining optional sound-core code. * @param card Live card token. @@ -123,7 +130,9 @@ int sound_service_request_disconnect(uint32_t card) if(!kernel_service_acquire(&sound_service_slot,&call))return -ENODEV; const struct sound_service_operations *provider_ops=call.operations; int result=provider_ops->request_disconnect ? provider_ops->request_disconnect(card) : -ENODEV; - kernel_service_release(&call);return result; + kernel_service_release(&call); + if(!result)devtmpfs_notify(); + return result; } /** @brief Report completed audio frames without exposing optional code addresses. * @param card Card generation token. diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 0d5b6cf5..4299ebdb 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -108,6 +108,7 @@ static int mount_remount(struct vfs_namespace *ns,struct task *task,uint64_t tar static int mount_backend(struct vfs_namespace *ns,struct task *task,const char *source,uint64_t source_user, const char *type,const char *options,uint64_t flags,struct vfs_mount **out) { + if(!__builtin_strcmp(type,"devtmpfs"))return devtmpfs_create_vfs_mount(source,flags,options,out); if(!__builtin_strcmp(type,"tmpfs"))return storage_new_tmpfs_mount(source,flags,options,task->fsuid,task->fsgid,out); /* The ext3 engine always uses ordered metadata transactions. Consume only * that supported mode before the common FAT option validation/application. */ diff --git a/kernel/workqueue/services.c b/kernel/workqueue/services.c index 50d9bd79..66333220 100644 --- a/kernel/workqueue/services.c +++ b/kernel/workqueue/services.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -32,8 +33,10 @@ static void usb_work(struct kernel_work *work,void *context) */ static void vfs_work(struct kernel_work *work,void *context) { - (void)context;(void)vfs_reclaim_mounts(2); - if(vfs_reclaim_pending())(void)kernel_queue_delayed_work(work,1); + (void)context; + (void)devtmpfs_refresh(); + (void)vfs_reclaim_mounts(2); + if(vfs_reclaim_pending() || devtmpfs_pending())(void)kernel_queue_delayed_work(work,1); } /** @brief Service graphics fences/retirement at the existing tick cadence. * @param work Permanent dispatch work. @param context Unused NULL. diff --git a/net/socket/netlink.c b/net/socket/netlink.c index cdb98e7c..9feae659 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -1,4 +1,5 @@ /* SPDX-License-Identifier: Apache-2.0 */ +#include /* Netlink state is owned by the ordinary kernel execution context. */ #include #include @@ -447,6 +448,7 @@ static void nl_multicast(int protocol, uint32_t group, const void *data, uint32_ void netlink_uevent_change(const char *devpath, const char *subsystem, const char *properties, uint32_t length) { + devtmpfs_notify(); char payload[512]; struct text_stream stream = {.buffer = payload, .capacity = sizeof(payload)}; static const char action[] = "\0ACTION=change\0DEVPATH="; diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index e2714a17..388e9a60 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -21,9 +21,9 @@ def test_real_tmpfs_without_text_routing(self): subprocess.run([ "cc", "-std=gnu11", "-O1", "-g", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Wl,--wrap=storage_ext4_read_inode", "-Wl,--wrap=storage_read_device", "-Wl,--wrap=storage_inode_stat", "-Wl,--wrap=storage_backend_commit_rename_metadata", "-Wl,--wrap=storage_cluster_write", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", - "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_backend_test.c", "kernel/dma/buffer.c", "drivers/storage/ahci/dma.c", "block/partition/mbr.c", + "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_backend_test.c", "kernel/dma/buffer.c", "drivers/storage/ahci/dma.c", "drivers/storage/ahci/interrupt.c", "drivers/storage/nvme/queue.c", "block/partition/mbr.c", "fs/vfs/filesystems.c", "fs/vfs/filesystem_instance.c", "fs/ext_common/journal.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/kernel_file.c", "fs/vfs/kernel_path.c", "fs/vfs/exec_file.c", "fs/vfs/attributes.c", "fs/vfs/initial.c", "fs/vfs/storage_initial.c", "fs/vfs/storage_attributes.c", "fs/vfs/storage_access.c", "fs/vfs/storage_backend.c", "fs/vfs/mutation.c", "fs/vfs/storage_mutation.c", "fs/vfs/storage_create.c", "fs/vfs/storage_security.c", "fs/vfs/write_access.c", - "fs/vfs/storage_mount.c", "fs/vfs/fat_options.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/security/access.c", "lib/text_utf16.c", "fs/devfs/mount.c", "fs/devfs/device.c", "fs/devfs/identity.c", "fs/vfs/pseudo.c", "kernel/exec/runtime.c", "kernel/exec/pending.c", "kernel/syscall/process/exec.c", "kernel/syscall/system/user_string.c", + "fs/vfs/storage_mount.c", "fs/vfs/fat_options.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/security/access.c", "lib/text_utf16.c", "fs/devfs/mount.c", "fs/devfs/devtmpfs.c", "fs/devfs/devtmpfs_nodes.c", "fs/devfs/device.c", "fs/devfs/identity.c", "fs/vfs/pseudo.c", "kernel/exec/runtime.c", "kernel/exec/pending.c", "kernel/syscall/process/exec.c", "kernel/syscall/system/user_string.c", "kernel/syscall/ipc/unix_path.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/create.c", "kernel/syscall/fs/mount.c", "kernel/syscall/fs/mutation.c", "kernel/syscall/fs/directory.c", "kernel/syscall/fs/size.c", "kernel/syscall/fs/sync.c", "kernel/syscall/fs/path.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fd/descriptor.c", "kernel/device/character.c", "kernel/syscall/io/vector.c", "kernel/syscall/fd/pty_descriptor.c", "kernel/sched/tables.c", "kernel/device/mapping.c", "kernel/sched/fs.c", "kernel/sync/wait.c", "-o", str(binary) ], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=20) diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index ef526742..4ba657a0 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -215,6 +215,8 @@ void sched_block_current(void){abort();} void sched_sleep_current_until(uint64_t wake_tick){(void)wake_tick;abort();} bool user_range_writable(uint64_t address,uint64_t length) {return user_range_ok(address,length);} +int user_range_readable(uint64_t address,uint64_t length) +{return user_range_ok(address,length) ? 0 : -EFAULT;} static unsigned readlink_waits; static struct storage_node sync_expected; static unsigned sync_errors; @@ -2287,6 +2289,121 @@ static int64_t scoped_mount_call(struct vfs_namespace *ns,struct task *task,uint if(rc!=-EAGAIN)task_lookup_scope_cancel(task); return rc; } +/** @brief Exercise publication, allocation retry and userspace inode ownership. + * @param ns Live fixture namespace. @param root Its retained root path. + * DRM availability models the provider's real inventory transitions. + */ +static void devtmpfs_device_lifecycle(struct vfs_namespace *ns,const struct vfs_path *root) +{ + bool saved_registered=test_drm_registered,saved_render=test_drm_render_ready; + struct vfs_path directory={0},node={0}; + test_drm_registered=true; + test_drm_render_ready=true; + devtmpfs_notify(); + assert(devtmpfs_pending() && !devtmpfs_refresh() && !devtmpfs_pending()); + assert(!vfs_path_lookup(ns,root,root,"/devtmp-one/dri",0,&directory)); + assert(!vfs_path_lookup(ns,root,root,"/devtmp-one/dri/renderD128",0,&node)); + struct linux_stat_abi status; + assert(!vfs_path_stat(&node,&status)); + assert(status.st_mode==(LINUX_S_IFCHR|0600) && status.st_rdev==0xe280); + struct reliefos_permissions mode={0660,1000,44}; + assert(!vfs_path_permissions(&node,&mode,true)); + uint64_t inode=status.st_ino; + vfs_path_put(&node); + devtmpfs_notify(); + assert(!devtmpfs_refresh()); + assert(!vfs_path_lookup(ns,root,root,"/devtmp-one/dri/renderD128",0,&node)); + assert(!vfs_path_stat(&node,&status) && status.st_ino==inode); + assert(!vfs_path_permissions(&node,&mode,false) && mode.mode==0660 && mode.uid==1000 && mode.gid==44); + vfs_path_put(&node); + + test_drm_render_ready=false; + devtmpfs_notify(); + test_fail_heap_after=0; + assert(devtmpfs_refresh()==-ENOMEM && devtmpfs_pending()); + test_fail_heap_after=-1; + assert(!vfs_path_lookup(ns,root,root,"/devtmp-one/dri/renderD128",0,&node)); + vfs_path_put(&node); + assert(!devtmpfs_refresh() && !devtmpfs_pending()); + assert(vfs_path_lookup(ns,root,root,"/devtmp-one/dri/renderD128",0,&node)==-ENOENT); + + assert(!vfs_path_lookup(ns,root,root,"/devtmp-one/dri/card0",0,&node)); + assert(!vfs_path_remove(ns,&node,false)); + vfs_path_put(&node); + devtmpfs_notify(); + assert(!devtmpfs_refresh()); + assert(vfs_path_lookup(ns,root,root,"/devtmp-one/dri/card0",0,&node)==-ENOENT); + mode=(struct reliefos_permissions){0640,1000,1000}; + assert(!vfs_path_new_file(&directory,"card0",&mode,&node)); + assert(!vfs_path_stat(&node,&status)); + inode=status.st_ino; + vfs_path_put(&node); + test_drm_registered=false; + devtmpfs_notify(); + assert(!devtmpfs_refresh()); + assert(!vfs_path_lookup(ns,root,root,"/devtmp-one/dri/card0",0,&node)); + assert(!vfs_path_stat(&node,&status) && status.st_ino==inode && (status.st_mode&LINUX_S_IFMT)==LINUX_S_IFREG); + assert(!vfs_path_remove(ns,&node,false)); + vfs_path_put(&node); + assert(!vfs_path_remove(ns,&directory,true)); + vfs_path_put(&directory); + test_drm_registered=saved_registered; + test_drm_render_ready=saved_render; + devtmpfs_notify(); + assert(!devtmpfs_refresh()); + puts("PASS devtmpfs lifecycle: hotplug, stable metadata, snapshot OOM retry, user deletion and replacement"); +} +/* udev needs real writable inodes, shared across independent devtmpfs mounts. */ +static void devtmpfs_mount_syscalls(struct vfs_namespace *ns,const struct vfs_path *root,struct tmpfs_super *fs) +{ + assert(!tmpfs_create(fs,"/devtmp-one",LINUX_S_IFDIR|0755,NULL,NULL)); + assert(!tmpfs_create(fs,"/devtmp-two",LINUX_S_IFDIR|0755,NULL,NULL)); + struct task actor={.pid=902,.cap_effective=1ULL<filesystem,"devtmpfs")); + assert(!vfs_path_lookup(ns,root,root,"/devtmp-one/null",0,&node)); + struct linux_stat_abi status; + assert(!vfs_path_stat(&node,&status)); + assert((status.st_mode&LINUX_S_IFMT)==LINUX_S_IFCHR && status.st_rdev==0x103); + struct reliefos_permissions mode={0660,123,456}; + assert(!vfs_path_permissions(&node,&mode,true)); + assert(!vfs_path_lookup(ns,root,root,"/devtmp-two/null",0,&alias)); + mode=(struct reliefos_permissions){0}; + assert(!vfs_path_permissions(&alias,&mode,false)); + assert(mode.mode==0660 && mode.uid==123 && mode.gid==456); + vfs_path_put(&node);vfs_path_put(&alias); + assert(!vfs_path_lookup(ns,root,root,"/devtmp-one/stdin",0,&node)); + char link[64]={0};size_t length=0; + assert(!vfs_path_readlink(&node,link,sizeof(link),&length)); + assert(length==15 && !memcmp(link,"/proc/self/fd/0",15)); + vfs_path_put(&node); + mode=(struct reliefos_permissions){0600,0,0}; + assert(!vfs_path_new_file(&one,"udev-data",&mode,&node)); + vfs_path_put(&node); + devtmpfs_device_lifecycle(ns,root); + assert(!vfs_mount_unmount(ns,&one));vfs_path_put(&one); + assert(!vfs_path_lookup(ns,root,root,"/devtmp-two/udev-data",0,&node)); + vfs_path_put(&node); + assert(!vfs_mount_unmount(ns,&two));vfs_path_put(&two); + vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + lookup_user_base=lookup_user_bytes=0; + puts("PASS devtmpfs mount syscall: shared writable device inodes, metadata, fd symlinks and independent mount policy"); +} + static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_path *root,struct tmpfs_super *fs) { assert(!tmpfs_create(fs,"/syscall-source",LINUX_S_IFDIR|0755,NULL,NULL)); @@ -2307,7 +2424,13 @@ static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pat assert((vfs_path_mount_flags(&mounted)&(MS_RELATIME|MS_NOSUID|MS_NODEV))==(MS_RELATIME|MS_NOSUID|MS_NODEV)); strcpy(user.options,"data=ordered"); assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,UINT64_MAX,target,UINT64_MAX, - MS_REMOUNT|MS_NOSUID|MS_NODEV,options)==-EOPNOTSUPP); + MS_REMOUNT|MS_NOSUID|MS_NODEV,options)==-EINVAL); + assert(!(vfs_path_mount_flags(&mounted)&MS_RDONLY)); + strcpy(user.options,"size=16384,nr_inodes=32,mode=0755"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,UINT64_MAX,target,UINT64_MAX, + MS_REMOUNT|MS_NOSUID|MS_NODEV,options)); + struct reliefos_permissions retained_mode; + assert(!vfs_path_permissions(&mounted,&retained_mode,false) && retained_mode.mode==0700); user.options[0]=0; assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,UINT64_MAX,target,UINT64_MAX, MS_REMOUNT|MS_NOSUID|MS_NODEV,options)); @@ -2525,6 +2648,19 @@ int main(int argc,char **argv) if(argc==3)ext_family(argv[1],argv[2]); if(argc==2)iso_filesystem(argv[1]); if(argc==4)cluster_filesystem(argv[1],argv[2],!strcmp(argv[3],"exfat")); + /* devtmpfs retains a private backing reference for the kernel lifetime. + * Exercise it after fixtures which deliberately recycle all dynamic slots. */ + assert(!tmpfs_new(0,0,"size=0,nr_inodes=0",0,0,&fs)); + g_volumes[0]=(struct storage_volume){.volume_id=0,.kind=STORAGE_VOLUME_ANONYMOUS, + .ready=true,.filesystem=STORAGE_FILESYSTEM_TMPFS,.fs_ops=&storage_tmpfs_ops,.tmpfs=fs}; + ns=(struct vfs_namespace){0}; + assert(!storage_create_vfs_mount(&g_volumes[0],NULL,&mount)); + assert(!vfs_namespace_init(&ns,mount));vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns,&root)); + devtmpfs_mount_syscalls(&ns,&root,fs); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns) && !storage_inode_volume_busy(0)); + tmpfs_destroy(fs);g_volumes[0]=(struct storage_volume){0}; puts("PASS real tmpfs mount backend: inode-relative lookup, covered cwd, symlink traversal, removed objects retained through final path, no text-prefix routing"); return 0; } diff --git a/tools/tests/storage_mkdir_mount_test.c b/tools/tests/storage_mkdir_mount_test.c index d25f1e72..3bcb0805 100644 --- a/tools/tests/storage_mkdir_mount_test.c +++ b/tools/tests/storage_mkdir_mount_test.c @@ -179,8 +179,12 @@ int pty_inode_permissions(const struct storage_node *node,struct reliefos_permis uint32_t smp_cpu_count(void) { return 1; } int pty_lookup_path(const char *path, struct storage_node *node) { (void)path; (void)node; abort(); } +/** @brief Model virtual consoles before tty initialization. + * @param path Requested console path. @param node Optional node output. + * @return ENOENT because this storage fixture has no live VT sessions. + */ int pty_lookup_vt_path(const char *path, struct storage_node *node) -{ (void)path; (void)node; abort(); } +{ (void)path; (void)node; return -2; } /* RAM-backed ext2 must never touch the physical controller or other codecs. */ #ifndef RELIEFNT_FIXTURE_OWN_IRQ_LOCKS void kernel_spin_lock_irqsave(struct kernel_spinlock *lock,uint64_t *flags) From 4e487917e3acba9f7bd2f9245578b95a7214081b Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sat, 28 Nov 2026 18:48:12 +0800 Subject: [PATCH 02/97] feat(tty): add instance-scoped devpts and Unix98 PTY lifecycle --- .github/workflows/build.yml | 4 + .../userspace-api/device-filesystems.rst | 69 ++- drivers/tty/pty/core.c | 54 +- drivers/tty/pty/internal.h | 4 + fs/Kbuild | 2 +- fs/devpts/Kbuild | 3 + fs/devpts/devpts.c | 502 ++++++++++++++++++ fs/proc/procfs.c | 13 +- include/reliefnt/devpts.h | 44 ++ include/reliefnt/pty.h | 17 + include/reliefnt/storage.h | 2 + kernel/syscall/device/device_open.c | 58 +- kernel/syscall/device/legacy_ioctl.c | 3 +- kernel/syscall/fd/pty_descriptor.c | 4 +- kernel/syscall/fs/mount.c | 6 +- tools/test_mount_backend.py | 2 +- tools/tests/Makefile | 1 + tools/tests/linux_pty_test.c | 30 ++ tools/tests/mount_backend_test.c | 277 +++++++++- tools/tests/storage_mkdir_mount_test.c | 2 + 20 files changed, 1063 insertions(+), 34 deletions(-) create mode 100644 fs/devpts/Kbuild create mode 100644 fs/devpts/devpts.c create mode 100644 include/reliefnt/devpts.h diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 678ac219..1fc24ffd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,6 +50,10 @@ jobs: libncurses-dev \ gzip \ squashfs-tools \ + e2fsprogs \ + dosfstools \ + exfatprogs \ + xorriso \ curl \ python3 diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index b6208afa..3fc50c9c 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -1,6 +1,9 @@ -================== -设备节点与 devtmpfs -================== +============================ +设备节点、devtmpfs 与 devpts +============================ + +devtmpfs +======== ``mount("devtmpfs", target, "devtmpfs", flags, data)`` 挂载内核维护的设备节点。 所有挂载共享同一内存文件系统及节点元数据,每个挂载分别维护 ``nodev``、 @@ -8,8 +11,8 @@ 设备节点使用现有 VFS 权限检查。设备打开按 inode 的类型和 ``st_rdev`` 分派到驱动,``nodev`` 挂载拒绝打开设备。 -生命周期 -======== +设备生命周期 +------------ 设备注册、注销及分区变化通知 VFS worker 合并更新。首次挂载同步生成完整 设备清单。后续更新保留已有设备的 ``chmod``、``chown``,并尊重用户删除、 @@ -22,8 +25,8 @@ ``stderr`` 使用指向 ``/proc/self/fd`` 及对应描述符的符号链接。 ``pts`` 和 ``shm`` 提供独立文件系统的挂载目录。 -挂载选项 -======== +devtmpfs 挂载选项 +----------------- 挂载数据使用 tmpfs 的 ``mode``、``uid``、``gid``、``size``、``nr_blocks`` 和 ``nr_inodes`` 语法。私有 backing 初始为 ``mode=0755,size=0,nr_inodes=0``。 @@ -31,9 +34,55 @@ ``gid`` 只在首次创建 tmpfs 时设置根 inode。已有无限容量的实例拒绝追溯增加 容量上限,已有内容也必须容纳在新上限内,与 Linux shmem 的重新配置约束一致。 +devpts +====== + +``mount("devpts", target, "devpts", flags, data)`` 每次创建独立实例,通常挂在 +``/dev/pts``。每个实例有自己的 ``st_dev``、``ptmx`` 和从 0 开始的从端编号; +绑定挂载保留原实例。``statfs`` 报告 ``0x1cd1``,``/proc/filesystems`` 将其列为 +``nodev`` 文件系统。打开 ``ptmx`` 后,``TIOCGPTN`` 返回本实例的编号; +``TIOCSPTLCK`` 解锁后才能打开对应从端。 + +从端报告字符设备号 ``136:<编号>``,但打开时以实际实例和 inode 身份为准,复制 +设备号创建的节点不会连接到该终端。``/proc//stat`` 中的控制终端设备号也 +使用实例内编号;固定虚拟终端仍使用主设备号 4。 + +devpts 挂载选项 +--------------- + +* ``uid=``、``gid=``:新从端的十进制所有者;未指定时使用创建 PTY 的进程的 + ``fsuid``、``fsgid``。根目录和 ``ptmx`` 归挂载者,根目录初始权限为 ``0755``。 +* ``mode=``、``ptmxmode=``:八进制权限,最多保留 ``07777``。默认从端为 + ``0600``、``ptmx`` 为 ``0000``。若直接通过符号链接或绑定挂载打开 ``ptmx``, + 可用 ``ptmxmode=0666`` 或相应的 ``chmod`` 让非特权用户访问。 +* ``max=``:实例内保留的 PTY 数量上限,范围为 0 到 1048576。默认不额外限制 + 内部 PTY 资源。达到上限时,新建返回 ``ENOSPC``。 +* ``newinstance``:兼容选项,可以省略。忽略逗号之间的空字段。 + +重新挂载从默认值解析选项。成功后立即更新 ``ptmx`` 权限和挂载策略;新选项 +只改变以后创建的从端,不重置已有从端的权限或所有者。降低 ``max`` 不会强制 +关闭已有会话。未通过验证的选项不会改变现有配置或挂载策略。标记 ``nodev`` +的挂载点不能用来直接打开设备。 + +编号与卸载 +---------- + +最后一个主端关闭时,从端名称被移除,仍打开的从端收到挂断通知。仍有端点引用 +的会话继续占用编号和 ``max`` 配额;只剩 ``O_PATH`` 等元数据引用时则可以重用 +公开编号。旧的从端 inode 与新会话不同:仍可读取旧 inode 的元数据(链接数为 +0),尝试再次打开设备返回 ``EIO``。正常卸载时仍被打开的路径或端点引用会令 +挂载忙(``EBUSY``);释放引用后可以卸载。 + +打开传统字符设备 ``5:2`` 时,内核从该设备实际所在的目录查找同级 +``pts/ptmx``。找到 devpts 后,新会话及主端描述符属于该实例,传统设备本身的 +权限决定是否可打开。找不到有效的 devpts 多路复用器时沿用启动阶段的旧 PTY +分配;其他查找错误则返回调用方。 + 验证范围 ======== -``tools/test_mount_backend.py`` 覆盖共享挂载、元数据、设备号、符号链接、 -设备增删、用户替换、挂载策略和内存不足重试。目标系统启动与 udev 集成由 -ReliefOS 的系统迁移验证覆盖。 +``tools/test_mount_backend.py`` 覆盖 devtmpfs 共享挂载、元数据、设备号、符号 +链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 +选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` +覆盖 PTY ABI、会话与主端挂断行为。目标系统启动与 udev 集成由 ReliefOS 的 +系统迁移验证覆盖。 diff --git a/drivers/tty/pty/core.c b/drivers/tty/pty/core.c index f56918c3..e622b49e 100644 --- a/drivers/tty/pty/core.c +++ b/drivers/tty/pty/core.c @@ -1,4 +1,5 @@ #include "internal.h" +#include struct pty_session_page { @@ -102,6 +103,10 @@ int pty_get_node(uint32_t pty_id, struct storage_node *node) return 0; } +/** @brief Resolve a legacy PTY pathname under execution ownership. + * @param path Global /dev/pts pathname. + * @param node Optional output metadata. + * @return Zero or negative ENOENT. Devpts bindings are instance-scoped. */ int pty_lookup_path(const char *path, struct storage_node *node) { const char *prefix = "/dev/pts/"; @@ -115,10 +120,48 @@ int pty_lookup_path(const char *path, struct storage_node *node) if (id > pty_session_slot_capacity()) return -2; } while (*path >= '0' && *path <= '9'); struct pty_session *session = find_session(id); - if (*path || !session || session->hungup || session->console) return -2; + if (*path || !session || session->hungup || session->console || session->devpts) return -2; return pty_get_node(id, node); } +/** @brief Read the public PTY number under execution ownership. + * @param pty_id Stable internal ID. + * @return Bound index, or the legacy internal ID if unbound or invalid. */ +uint32_t pty_number(uint32_t pty_id) +{ + struct pty_session *session = find_session(pty_id); + return session && session->devpts ? session->public_number : pty_id; +} + +/** @brief Inspect devpts membership under execution ownership. + * @param pty_id Stable internal ID. + * @return Nonzero when the session belongs to a devpts instance. */ +int pty_is_devpts(uint32_t pty_id) +{ + struct pty_session *session = find_session(pty_id); + return session && session->devpts; +} + +/** @brief Publish one instance-local binding for a retained live session. + * @param pty_id Stable internal ID. + * @param number Public index. + * @param binding Borrowed inode retained until callback delivery. + * @param hangup One-shot unlink callback invoked under execution ownership. + * @return Zero or negative EINVAL/EBUSY. No ownership transfers on failure. */ +int pty_bind_devpts(uint32_t pty_id, uint32_t number, void *binding, + void (*hangup)(void *binding)) +{ + struct pty_session *session = find_session(pty_id); + if (!session || session->hungup || session->console || !binding || !hangup) + return -EINVAL; + if (session->devpts) return -EBUSY; + session->devpts = true; + session->public_number = number; + session->devpts_binding = binding; + session->devpts_hangup = hangup; + return 0; +} + /** @brief Resolve one of the six fixed Linux virtual consoles. * @param path Device pathname, nullable. * @param node Optional output storage node. @@ -362,6 +405,10 @@ void pty_transfer_put(uint32_t pty_id, uint32_t endpoint) * The session is not freed while slave descriptors remain open. The slave * keeps draining buffered input, then reports EOF/POLLHUP and rejects writes * with EIO. SIGHUP and SIGCONT are delivered to the controlling session leader. + * Devpts bindings are unlinked once before the final session reap. + * @param owner_pid Legacy owner of the session. + * @param pty_id Stable internal session ID. + * @return Zero or negative EINVAL. Requires execution ownership. */ int pty_destroy(uint32_t owner_pid, uint32_t pty_id) { @@ -389,6 +436,11 @@ int pty_destroy(uint32_t owner_pid, uint32_t pty_id) sched_signal_user_process(sid, 18); } kernel_poll_readiness_notify(); + void *binding = session->devpts_binding; + void (*hangup)(void *) = session->devpts_hangup; + session->devpts_binding = NULL; + session->devpts_hangup = NULL; + if (hangup) hangup(binding); pty_reap_hungup(pty_id); return 0; } diff --git a/drivers/tty/pty/internal.h b/drivers/tty/pty/internal.h index 806d8350..957ebcd3 100644 --- a/drivers/tty/pty/internal.h +++ b/drivers/tty/pty/internal.h @@ -39,6 +39,10 @@ struct pty_session { uint32_t foreground_pgid; uint32_t transfer_refs; uint32_t transfer_masters; + bool devpts; + uint32_t public_number; + void *devpts_binding; + void (*devpts_hangup)(void *binding); uint8_t input[PTY_INPUT_CAP]; /* Per-slot canonical line ends; EOF is a delimiter, never a returned byte. */ uint8_t input_end[PTY_INPUT_CAP]; diff --git a/fs/Kbuild b/fs/Kbuild index 0360cd15..56687b44 100644 --- a/fs/Kbuild +++ b/fs/Kbuild @@ -1,6 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 # Objects are owned by this directory; child modules own their own lists. -obj-y := initramfs/ devfs/ proc/ security/ sysfs/ tmpfs/ vfs/ notify/ +obj-y := initramfs/ devfs/ devpts/ proc/ security/ sysfs/ tmpfs/ vfs/ notify/ obj-$(CONFIG_EXT_FS_COMMON) += ext_common/ obj-$(CONFIG_EXT2_FS) += ext2/ obj-$(CONFIG_EXT3_FS) += ext3/ diff --git a/fs/devpts/Kbuild b/fs/devpts/Kbuild new file mode 100644 index 00000000..1506b759 --- /dev/null +++ b/fs/devpts/Kbuild @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: Apache-2.0 +obj-y := devpts.o +include $(srctree)/scripts/Makefile.module diff --git a/fs/devpts/devpts.c b/fs/devpts/devpts.c new file mode 100644 index 00000000..74a1c4a1 --- /dev/null +++ b/fs/devpts/devpts.c @@ -0,0 +1,502 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "../vfs/mount_internal.h" + +#define DEVPTS_LIMIT (1u << 20) +#define DEVPTS_ROOT_INO 1u +#define DEVPTS_PTMX_INO 2u + +struct devpts_options { + uint32_t uid, gid, mode, ptmxmode, maximum; + bool set_uid, set_gid; +}; + +struct devpts_instance; +struct devpts_inode { + struct devpts_instance *instance; + struct devpts_inode *next; + uint64_t ino, references; + uint32_t number, pty_id, generation; + bool linked; + struct reliefos_permissions permissions; +}; + +struct devpts_instance { + struct devpts_inode root, ptmx, *slaves; + struct devpts_options options; + uint64_t references, next_inode, flags, device; + uint32_t identity; +}; + +static const struct vfs_backend_ops devpts_ops; +static uint32_t devpts_next_instance; + +/** @brief Encode a Linux dev_t with a full 20-bit minor. + * @param major Linux device major. @param minor Linux device minor. + * @return Encoded native Linux device number. */ +static uint64_t devpts_device(uint32_t major, uint32_t minor) +{ + return ((uint64_t)major << 8) | (minor & 255u) | + ((uint64_t)(minor & ~255u) << 12); +} + +/** @brief Parse a bounded unsigned option without temporary strings. + * @param begin First digit. @param end Exclusive token end. + * @param base Decimal or octal radix. @param limit Largest accepted value. + * @param out Parsed output on success. + * @return Zero or negative EINVAL, without changing out on failure. */ +static int devpts_unsigned(const char *begin, const char *end, uint32_t base, + uint32_t limit, uint32_t *out) +{ + if (begin == end) return -EINVAL; + uint32_t value = 0; + for (const char *p = begin; p != end; ++p) { + uint32_t digit = (uint32_t)(*p - '0'); + if (digit >= base || value > (limit - digit) / base) return -EINVAL; + value = value * base + digit; + } + if (value > limit) return -EINVAL; + *out = value; + return 0; +} + +/** @brief Reconfigure a copied option set atomically. + * @param text Nullable comma-separated kernel mount data. + * @param options Caller-owned candidate, committed only by the caller. + * @return Zero or negative EINVAL. All mounts are independent instances. */ +static int devpts_parse(const char *text, struct devpts_options *options) +{ + if (!text || !*text) return 0; + while (*text) { + const char *end = text; + while (*end && *end != ',') ++end; + if (text == end) { + text = end + 1; + continue; + } + const char *equals = text; + while (equals != end && *equals != '=') ++equals; + size_t length = (size_t)(equals - text); + uint32_t value; + if (length == 11 && !__builtin_memcmp(text, "newinstance", 11) && equals == end) { + /* Independent instances are unconditional, including old callers. */ + } else { + if (equals == end) return -EINVAL; + bool uid = length == 3 && !__builtin_memcmp(text, "uid", 3); + bool gid = length == 3 && !__builtin_memcmp(text, "gid", 3); + bool mode = length == 4 && !__builtin_memcmp(text, "mode", 4); + bool ptmxmode = length == 8 && !__builtin_memcmp(text, "ptmxmode", 8); + bool maximum = length == 3 && !__builtin_memcmp(text, "max", 3); + if (!uid && !gid && !mode && !ptmxmode && !maximum) return -EINVAL; + uint32_t limit = mode || ptmxmode ? 07777u : maximum ? DEVPTS_LIMIT : UINT32_MAX - 1u; + int rc = devpts_unsigned(equals + 1, end, mode || ptmxmode ? 8 : 10, limit, &value); + if (rc) return rc; + if (uid) { options->uid = value; options->set_uid = true; } + if (gid) { options->gid = value; options->set_gid = true; } + if (mode) options->mode = value; + if (ptmxmode) options->ptmxmode = value; + if (maximum) options->maximum = value; + } + text = *end ? end + 1 : end; + } + return 0; +} + +/** @brief Export an inode's generation-checked identity without taking a pin. + * @param inode Borrowed live inode. @param out Borrowed metadata output. */ +static void devpts_node(const struct devpts_inode *inode, struct storage_node *out) +{ + bool root = inode->ino == DEVPTS_ROOT_INO; + *out = (struct storage_node){ + .type = root ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_DEVICE, + .flags = STORAGE_NODE_FLAG_DEVPTS | (root ? 0 : STORAGE_NODE_FLAG_RDEV | STORAGE_NODE_FLAG_DEV_NODE), + .first_cluster = inode->pty_id, + .volume_id = inode->generation, + .mount_generation = inode->instance->identity, + .entry_id = inode->ino, + }; + if (inode->pty_id) out->flags |= STORAGE_NODE_FLAG_PTY; +} + +/** @brief Resolve only identities owned by this instance, including unlinked pins. + * @param instance Borrowed backend. @param node Borrowed metadata. + * @return Borrowed inode or NULL for stale/foreign metadata. */ +static struct devpts_inode *devpts_find(struct devpts_instance *instance, + const struct storage_node *node) +{ + if (!node || !(node->flags & STORAGE_NODE_FLAG_DEVPTS) || + node->mount_generation != instance->identity) return NULL; + if (node->entry_id == DEVPTS_ROOT_INO) return &instance->root; + if (node->entry_id == DEVPTS_PTMX_INO) return &instance->ptmx; + for (struct devpts_inode *inode = instance->slaves; inode; inode = inode->next) { + if (inode->ino == node->entry_id && inode->pty_id == node->first_cluster && + inode->generation == node->volume_id) return inode; + } + return NULL; +} + +/** @brief Drop a mount or slave's instance reference under execution ownership. + * @param instance Owned reference, freed after its last inode and mount retire. */ +static void devpts_instance_put(struct devpts_instance *instance) +{ + if (!--instance->references) kernel_free(instance); +} + +/** @brief Consume a slave inode reference and its final PTY/instance pins. + * @param inode Owned slave pin. Internal session identity survives until here. */ +static void devpts_inode_put(struct devpts_inode *inode) +{ + if (--inode->references) return; + struct devpts_instance *instance = inode->instance; + struct devpts_inode **link = &instance->slaves; + while (*link != inode) link = &(*link)->next; + *link = inode->next; + pty_transfer_put(inode->pty_id, TASK_PTY_ENDPOINT_SLAVE); + kernel_free(inode); + devpts_instance_put(instance); +} + +/** @brief Remove the slave name when its last master hangs up. + * @param binding Owned publication pin, consumed exactly once by PTY core. */ +static void devpts_hangup(void *binding) +{ + struct devpts_inode *inode = binding; + inode->linked = false; + devpts_inode_put(inode); +} + +/** @brief Lookup one currently published child in an execution-owned instance. + * @param context Borrowed instance. @param parent Borrowed directory identity. + * @param name Child basename. @param out Borrowed metadata output. + * @return Zero or negative ENOTDIR/ENOENT. No lookup caching is enabled. */ +static int devpts_lookup(void *context, const struct storage_node *parent, + const char *name, struct storage_node *out) +{ + struct devpts_instance *instance = context; + if (devpts_find(instance, parent) != &instance->root) return -ENOTDIR; + if (!__builtin_strcmp(name, "ptmx")) { + devpts_node(&instance->ptmx, out); + return 0; + } + uint32_t number; + size_t length = __builtin_strlen(name); + if ((length > 1 && name[0] == '0') || + devpts_unsigned(name, name + length, 10, DEVPTS_LIMIT - 1, &number)) return -ENOENT; + for (struct devpts_inode *inode = instance->slaves; inode; inode = inode->next) { + if (inode->number == number && inode->linked) { + devpts_node(inode, out); + return 0; + } + } + return -ENOENT; +} + +/** @brief Acquire an opaque native inode pin under execution ownership. + * @param context Borrowed backend. @param node Borrowed metadata. + * @param pin Owned native pin output on success. + * @return Zero or negative ENOENT. The enclosing mount retains root/ptmx. */ +static int devpts_retain(void *context, const struct storage_node *node, void **pin) +{ + struct devpts_inode *inode = devpts_find(context, node); + if (!inode) return -ENOENT; + if (inode->pty_id) ++inode->references; + *pin = inode; + return 0; +} + +/** @brief Consume a native inode pin after its final dentry retires. + * @param context Borrowed backend. @param node Borrowed metadata. + * @param pin Owned pin returned by retain. Root/ptmx live in the mount. */ +static void devpts_release(void *context, const struct storage_node *node, void *pin) +{ + (void)context; + (void)node; + struct devpts_inode *inode = pin; + if (inode->pty_id) devpts_inode_put(inode); +} + +/** @brief Compare immutable per-instance inode identities. + * @param context Borrowed backend. @param left First metadata. @param right Second metadata. + * @return True for the same live inode, including retained unlinked slaves. */ +static bool devpts_same(void *context, const struct storage_node *left, + const struct storage_node *right) +{ + struct devpts_inode *inode = devpts_find(context, left); + return inode && inode == devpts_find(context, right); +} + +/** @brief Retire the mount's base reference, allowing legacy-open PTYs to drain. + * @param context Owned backend mount reference after all VFS pins retire. */ +static void devpts_destroy(void *context) +{ + devpts_instance_put(context); +} + +/** @brief Read/update inode permissions after the caller's DAC authorization. + * @param context Borrowed backend. @param path Borrowed retained inode. + * @param value Read result or new metadata. @param write Select update. + * @return Zero or negative ENOENT. Requires execution ownership. */ +static int devpts_permissions(void *context, const struct vfs_path *path, + struct reliefos_permissions *value, bool write) +{ + struct devpts_inode *inode = devpts_find(context, vfs_path_node(path)); + if (!inode) return -ENOENT; + if (write) inode->permissions = *value; + else *value = inode->permissions; + return 0; +} + +/** @brief Return stable metadata and instance-local Linux device identity. + * @param context Borrowed backend. @param path Retained actual inode. + * @param out Writable stat output. @return Zero or negative ENOENT. */ +static int devpts_getattr(void *context, const struct vfs_path *path, struct linux_stat_abi *out) +{ + struct devpts_instance *instance = context; + struct devpts_inode *inode = devpts_find(instance, vfs_path_node(path)); + if (!inode) return -ENOENT; + bool root = inode == &instance->root; + *out = (struct linux_stat_abi){ + .st_dev = instance->device, .st_ino = inode->ino, + .st_nlink = root ? 2 : inode->linked ? 1 : 0, + .st_mode = (root ? LINUX_S_IFDIR : LINUX_S_IFCHR) | inode->permissions.mode, + .st_uid = inode->permissions.uid, .st_gid = inode->permissions.gid, + .st_rdev = root ? 0 : inode->pty_id ? devpts_device(136, inode->number) : devpts_device(5, 2), + .st_blksize = 1024, + }; + return 0; +} + +/** @brief Check whether a slave still reserves an index and PTY quota. + * @param inode Borrowed slave with its own session transfer pin. + * @return True while published or held by an endpoint/controlling attachment. + * Retained path metadata alone keeps internal identity alive and permits public + * index reuse after hangup. Execution ownership stabilizes the reference scan. */ +static bool devpts_reserved(const struct devpts_inode *inode) +{ + return inode->linked || sched_pty_reference_count(inode->pty_id) > 1; +} + +/** @brief Count sessions reserving this instance's max quota. + * @param instance Borrowed backend under execution ownership. + * @return Published sessions plus hung-up sessions with live endpoints. */ +static uint32_t devpts_allocated(const struct devpts_instance *instance) +{ + uint32_t count = 0; + for (const struct devpts_inode *inode = instance->slaves; inode; inode = inode->next) + if (devpts_reserved(inode)) ++count; + return count; +} + +/** @brief Report the devpts magic and currently reserved PTY quota. + * @param context Borrowed backend. @param node Borrowed identity. + * @param out Writable statfs result. @return Zero or negative ENOENT. */ +static int devpts_statfs(void *context, const struct storage_node *node, struct linux_statfs_abi *out) +{ + struct devpts_instance *instance = context; + if (!devpts_find(instance, node)) return -ENOENT; + *out = (struct linux_statfs_abi){.f_type = 0x1cd1, .f_bsize = 1024, + .f_files = instance->options.maximum, .f_namelen = 255}; + uint32_t allocated = devpts_allocated(instance); + out->f_ffree = allocated < instance->options.maximum ? + instance->options.maximum - allocated : 0; + out->f_fsid[0] = (int32_t)instance->identity; + return 0; +} + +/** @brief Enumerate ptmx and published slaves using stable monotonic inode cookies. + * @param context Borrowed backend. @param node Borrowed directory identity. + * @param cursor Owned iteration cookie. @param entry Writable dirent result. + * @param flags Current attachment flags, unused. + * @return One for an entry, zero at end, or negative ENOTDIR. */ +static int devpts_readdir(void *context, const struct storage_node *node, uint64_t *cursor, + struct reliefos_dir_entry *entry, uint64_t flags) +{ + (void)flags; + struct devpts_instance *instance = context; + if (devpts_find(instance, node) != &instance->root) return -ENOTDIR; + struct devpts_inode *next = NULL; + if (*cursor < DEVPTS_PTMX_INO) next = &instance->ptmx; + else for (struct devpts_inode *inode = instance->slaves; inode; inode = inode->next) { + if (inode->linked && inode->ino > *cursor && (!next || inode->ino < next->ino)) next = inode; + } + if (!next) return 0; + *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_DEVICE}; + if (next == &instance->ptmx) __builtin_memcpy(entry->name, "ptmx", 5); + else { + char digits[10]; + uint32_t value = next->number, count = 0; + do { digits[count++] = (char)('0' + value % 10); value /= 10; } while (value); + for (uint32_t i = 0; i < count; ++i) entry->name[i] = digits[count - i - 1]; + } + *cursor = next->ino; + return 1; +} + +/** @brief Return shared superblock policy without allocation or I/O. + * @param context Borrowed instance. @return Shared policy flags. */ +static uint64_t devpts_flags(void *context) +{ + return ((struct devpts_instance *)context)->flags; +} + +/** @brief Atomically change options and shared mount policy. + * @param context Borrowed instance. @param flags New shared policy flags. + * @param options Optional copied mount data. @return Zero or negative EINVAL. + * Unspecified options return to defaults and existing slaves retain metadata. + * Execution ownership is required. */ +static int devpts_remount(void *context, uint64_t flags, const char *options) +{ + struct devpts_instance *instance = context; + struct devpts_options candidate = {.mode = 0600, .maximum = DEVPTS_LIMIT}; + int rc = devpts_parse(options, &candidate); + if (rc) return rc; + instance->options = candidate; + instance->ptmx.permissions.mode = candidate.ptmxmode; + instance->flags = flags & VFS_SUPER_POLICY_MASK; + return 0; +} + +static const struct vfs_backend_ops devpts_ops = { + .lookup = devpts_lookup, .retain = devpts_retain, .release = devpts_release, + .same_node = devpts_same, .destroy = devpts_destroy, + .permissions = devpts_permissions, .getattr = devpts_getattr, + .statfs = devpts_statfs, .readdir = devpts_readdir, + .mount_flags = devpts_flags, .remount_options = devpts_remount, +}; + +/** @brief Construct an owned independent devpts backend and attachment. + * @param source Optional diagnostic label. @param flags Final mount policy. + * @param options Optional supported mount data. @param uid Root/ptmx UID. + * @param gid Root/ptmx GID. @param out Owned detached mount output. + * @return Zero or negative errno with complete rollback. Execution-owned. */ +int devpts_create_vfs_mount(const char *source, uint64_t flags, const char *options, + uint32_t uid, uint32_t gid, struct vfs_mount **out) +{ + if (!out) return -EINVAL; + *out = NULL; + if (flags & ~(VFS_MOUNT_POLICY_MASK | VFS_SUPER_POLICY_MASK | MS_STRICTATIME)) return -EOPNOTSUPP; + struct devpts_options parsed = {.mode = 0600, .maximum = DEVPTS_LIMIT}; + int rc = devpts_parse(options, &parsed); + if (rc) return rc; + if (devpts_next_instance >= DEVPTS_LIMIT - 0x10000u - 1u) return -ENOSPC; + struct devpts_instance *instance = kernel_malloc(sizeof(*instance)); + if (!instance) return -ENOMEM; + *instance = (struct devpts_instance){.options = parsed, .references = 1, + .next_inode = 3, .flags = flags & VFS_SUPER_POLICY_MASK, + .identity = ++devpts_next_instance}; + instance->device = devpts_device(0, instance->identity + 0x10000u); + instance->root = (struct devpts_inode){.instance = instance, .ino = DEVPTS_ROOT_INO, + .linked = true, .permissions = {0755, uid, gid}}; + instance->ptmx = (struct devpts_inode){.instance = instance, .ino = DEVPTS_PTMX_INO, + .linked = true, .permissions = {parsed.ptmxmode, uid, gid}}; + struct storage_node root; + devpts_node(&instance->root, &root); + rc = vfs_mount_new(&devpts_ops, instance, NULL, &root, out); + if (rc) { devpts_instance_put(instance); return rc; } + rc = vfs_mount_set_flags(*out, flags & ~VFS_SUPER_POLICY_MASK); + if (!rc) rc = vfs_mount_describe(*out, source && *source ? source : "devpts", "devpts", instance->device); + if (rc) { vfs_mount_put(*out); *out = NULL; } + return rc; +} + +/** @brief Resolve a devpts ptmx directly or through a legacy device's sibling pts. + * @param device Borrowed actual device. @param root Borrowed caller root. + * @param out Owned ptmx path, empty on failure. + * @return Zero or negative errno. Requires execution ownership. */ +int devpts_resolve_ptmx(const struct vfs_path *device, const struct vfs_path *root, + struct vfs_path *out) +{ + if (!out) return -EINVAL; + *out = (struct vfs_path){0}; + if (!vfs_path_node(device)) return -ENODEV; + if (device->mount->ops == &devpts_ops) { + struct devpts_instance *instance = vfs_path_context(device); + if (devpts_find(instance, vfs_path_node(device)) != &instance->ptmx) return -ENODEV; + vfs_path_get(device, out); + return 0; + } + struct vfs_namespace *ns = vfs_path_namespace(device); + if (!ns || !vfs_path_node(root)) return -ENODEV; + struct vfs_path parent = {0}; + vfs_path_get(device, &parent); + vfs_path_parent(root, &parent); + int rc = vfs_path_lookup(ns, root, &parent, "pts/ptmx", VFS_LOOKUP_FOLLOW, out); + vfs_path_put(&parent); + if (rc) return rc; + if (out->mount->ops == &devpts_ops) { + struct devpts_instance *instance = vfs_path_context(out); + if (devpts_find(instance, vfs_path_node(out)) == &instance->ptmx) return 0; + } + vfs_path_put(out); + return -ENODEV; +} + +/** @brief Allocate the first free instance-local index and bind a new session. + * @param ptmx Borrowed authorized multiplexor. @param owner_pid Session owner. + * @param uid Default slave UID. @param gid Default slave GID. + * @param out Internal ID, zero on failure. + * @return Zero or negative errno, rolling back all pins on failure. + * Execution ownership serializes numbering, publication and callback delivery. */ +int devpts_new_pty(const struct vfs_path *ptmx, uint32_t owner_pid, + uint32_t uid, uint32_t gid, uint32_t *out) +{ + if (!out) return -EINVAL; + *out = 0; + if (!vfs_path_node(ptmx) || ptmx->mount->ops != &devpts_ops) return -ENODEV; + struct devpts_instance *instance = vfs_path_context(ptmx); + if (devpts_find(instance, vfs_path_node(ptmx)) != &instance->ptmx) return -ENODEV; + if (devpts_allocated(instance) >= instance->options.maximum || instance->next_inode == UINT64_MAX) return -ENOSPC; + uint32_t number = 0; + /* Endpoint references reserve indices after unlink, metadata-only pins do not. */ + for (;;) { + bool used = false; + for (struct devpts_inode *old = instance->slaves; old; old = old->next) { + if (old->number == number && devpts_reserved(old)) { used = true; break; } + } + if (!used) break; + if (++number == DEVPTS_LIMIT) return -ENOSPC; + } + struct devpts_inode *inode = kernel_malloc(sizeof(*inode)); + if (!inode) return -ENOMEM; + int32_t id = pty_create(owner_pid); + if (id < 0) { kernel_free(inode); return id; } + struct storage_node node; + int rc = pty_get_node((uint32_t)id, &node); + if (!rc) rc = pty_transfer_get((uint32_t)id, TASK_PTY_ENDPOINT_SLAVE); + if (rc) { (void)pty_destroy(owner_pid, (uint32_t)id); kernel_free(inode); return rc; } + *inode = (struct devpts_inode){.instance = instance, .ino = instance->next_inode++, + .references = 1, .number = number, .pty_id = (uint32_t)id, + .generation = node.volume_id, .linked = true, + .permissions = {instance->options.mode, + instance->options.set_uid ? instance->options.uid : uid, + instance->options.set_gid ? instance->options.gid : gid}, + .next = instance->slaves}; + instance->slaves = inode; + ++instance->references; + rc = pty_bind_devpts((uint32_t)id, number, inode, devpts_hangup); + if (rc) { devpts_inode_put(inode); (void)pty_destroy(owner_pid, (uint32_t)id); return rc; } + *out = (uint32_t)id; + return 0; +} + +/** @brief Resolve a live slave using its retained instance/inode/generation. + * @param path Borrowed actual slave. @param out Internal session ID output. + * @return Zero or negative ENODEV/EIO. Requires execution ownership. */ +int devpts_slave_pty(const struct vfs_path *path, uint32_t *out) +{ + if (!out) return -EINVAL; + *out = 0; + if (!vfs_path_node(path) || path->mount->ops != &devpts_ops) return -ENODEV; + struct devpts_inode *inode = devpts_find(vfs_path_context(path), vfs_path_node(path)); + if (!inode || !inode->pty_id) return -ENODEV; + if (!inode->linked || !pty_is_active(inode->pty_id)) return -EIO; + *out = inode->pty_id; + return 0; +} diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 68093d4f..9955155f 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -234,7 +234,7 @@ static int proc_oom_key(const char *name, struct task **task) * @param buffer Writable kernel buffer, always NUL-terminated on return. * @param capacity Nonzero byte capacity of buffer. * @return Zero with the file content in buffer, or negative ENOENT for paths - * this generator does not own. + * this generator does not own. The filesystem list includes devpts. */ static int proc_fill_content(const char *path, char *buffer, uint32_t capacity) { @@ -280,7 +280,7 @@ static int proc_fill_content(const char *path, char *buffer, uint32_t capacity) #ifdef CONFIG_SQUASHFS proc_append_text(buffer, &pos, capacity, "\tsquashfs\n"); #endif - proc_append_text(buffer, &pos, capacity, "nodev\tproc\nnodev\tdevfs\nnodev\tdevtmpfs\nnodev\tsysfs\nnodev\ttmpfs\n"); + proc_append_text(buffer, &pos, capacity, "nodev\tproc\nnodev\tdevfs\nnodev\tdevtmpfs\nnodev\tdevpts\nnodev\tsysfs\nnodev\ttmpfs\n"); return 0; } if (proc_text_eq(path, "/proc/asound/cards")) { @@ -746,6 +746,7 @@ int proc_mount_magic_target(const char *name,struct vfs_path *out) * Legacy private uid/role fields belong in status rather than Linux stat positions. * @param task Borrowed live target. @param s Required output stream. * @param process Sum CPU times across the group; false selects a thread. + * Controlling devpts terminals encode their instance-local public number. * Execution ownership protects task/VMA metadata; CPU counters use their lock. */ static void proc_task_stat(struct task *task, struct text_stream *s, bool process) @@ -760,8 +761,12 @@ static void proc_task_stat(struct task *task, struct text_stream *s, bool proces } } uint32_t foreground = 0; - if (task->controlling_pty_id && pty_get_foreground_pgid(task->controlling_pty_id, &foreground) == 0) - values[7] = (136u << 8) | (task->controlling_pty_id - 1); + if (task->controlling_pty_id && pty_get_foreground_pgid(task->controlling_pty_id, &foreground) == 0) { + uint32_t vt = pty_vt_number(task->controlling_pty_id); + uint32_t number = pty_number(task->controlling_pty_id); + values[7] = vt ? (4u << 8) | vt : (136u << 8) | + (number & 255u) | ((uint64_t)(number & ~255u) << 12); + } values[4] = task->parent_pid; values[5] = task->process_group; values[6] = task->process_session; diff --git a/include/reliefnt/devpts.h b/include/reliefnt/devpts.h new file mode 100644 index 00000000..c9580bba --- /dev/null +++ b/include/reliefnt/devpts.h @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_DEVPTS_H +#define RELIEFNT_DEVPTS_H +#include + +/** @brief Create an independent devpts instance under execution ownership. + * @param source Optional diagnostic mount label. + * @param flags Supported mount policy flags. + * @param options Optional uid/gid/mode/ptmxmode/max/newinstance mount data. + * @param uid Root/ptmx owner filesystem UID. + * @param gid Root/ptmx owner filesystem GID. + * @param out Owned detached mount, empty on failure. + * @return Zero or negative option/allocation errno, with balanced rollback. */ +int devpts_create_vfs_mount(const char *source, uint64_t flags, + const char *options, uint32_t uid, uint32_t gid, + struct vfs_mount **out); + +/** @brief Resolve the actual devpts multiplexor for a retained device inode. + * @param device Borrowed devpts ptmx or legacy 5:2 device path. + * @param root Borrowed caller root constraining sibling traversal. + * @param out Independently retained devpts ptmx path, empty on failure. + * @return Zero or negative ENODEV/lookup errno. A legacy inode selects the + * sibling pts/ptmx through real mount attachments under execution ownership. */ +int devpts_resolve_ptmx(const struct vfs_path *device, + const struct vfs_path *root, struct vfs_path *out); + +/** @brief Allocate and publish a PTY in the exact retained ptmx instance. + * @param ptmx Borrowed authorized devpts multiplexor path. + * @param owner_pid Creating task's internal ID. + * @param uid Default slave owner filesystem UID when uid= is absent. + * @param gid Default slave owner filesystem GID when gid= is absent. + * @param out Internal session ID, zero on failure. + * @return Zero or negative errno. Caller must install a master reference or + * destroy the new session on FD failure. Requires execution ownership. */ +int devpts_new_pty(const struct vfs_path *ptmx, uint32_t owner_pid, + uint32_t uid, uint32_t gid, uint32_t *out); + +/** @brief Resolve a held slave inode to its original live session. + * @param path Borrowed actual devpts slave path. + * @param out Internal session ID, zero on failure. + * @return Zero or negative EIO/ENODEV. Checks instance, inode and generation + * under execution ownership, with no global device-number lookup. */ +int devpts_slave_pty(const struct vfs_path *path, uint32_t *out); +#endif diff --git a/include/reliefnt/pty.h b/include/reliefnt/pty.h index c2d5633e..831f28a4 100644 --- a/include/reliefnt/pty.h +++ b/include/reliefnt/pty.h @@ -18,6 +18,23 @@ int pty_lookup_path(const char *path, struct storage_node *node); * @return Zero if resolved or negative ENOENT. */ int pty_lookup_vt_path(const char *path, struct storage_node *node); int pty_get_node(uint32_t pty_id, struct storage_node *node); +/** @brief Read the userspace PTY number under execution ownership. + * @param pty_id Stable internal session ID. + * @return Instance-local index for devpts, internal ID for legacy PTYs. */ +uint32_t pty_number(uint32_t pty_id); +/** @brief Test whether a session belongs to a devpts instance. + * @param pty_id Stable internal session ID. + * @return Nonzero for a bound devpts session, including after hangup. */ +int pty_is_devpts(uint32_t pty_id); +/** @brief Bind a live PTY to one devpts inode under execution ownership. + * @param pty_id Stable internal session ID, retained by the caller. + * @param number Zero-based public index within the instance. + * @param binding Borrowed inode kept alive until hangup callback delivery. + * @param hangup One-shot callback which consumes the binding's publication pin. + * @return Zero, negative EINVAL for invalid input, or EBUSY if already bound. */ +int pty_bind_devpts(uint32_t pty_id, uint32_t number, void *binding, + void (*hangup)(void *binding)); + int pty_inode_permissions(const struct storage_node *node, struct reliefos_permissions *value, bool write); diff --git a/include/reliefnt/storage.h b/include/reliefnt/storage.h index 595e4e32..510ef27e 100644 --- a/include/reliefnt/storage.h +++ b/include/reliefnt/storage.h @@ -293,6 +293,8 @@ struct storage_read_cursor { /* Native inode carrying st_rdev; first_cluster remains its inode identity. */ #define STORAGE_NODE_FLAG_RDEV 0x00100000u #define STORAGE_NODE_FLAG_SQUASHFS 0x00200000u +/* Instance-bound devpts inode, resolved before global rdev dispatch. */ +#define STORAGE_NODE_FLAG_DEVPTS 0x00400000u #define STORAGE_SYSFS_DEVICE 202u #define STORAGE_NODE_FLAG_DEV_LINK 0x00000200u /* Anonymous filesystem device numbers, also exported in proc mountinfo. */ diff --git a/kernel/syscall/device/device_open.c b/kernel/syscall/device/device_open.c index 174782d0..4e8fb7f1 100644 --- a/kernel/syscall/device/device_open.c +++ b/kernel/syscall/device/device_open.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" #include +#include /** @brief Bind a newly created PTY description to its held device path. * @param task Current fd-table owner under execution ownership. @@ -18,13 +19,46 @@ static int device_pty_path(struct task *task,int fd,const struct vfs_path *path) return fd; } +/** @brief Allocate a master from the actual multiplexor's devpts instance. + * @param task Borrowed descriptor-table owner under execution ownership. + * @param path Borrowed authorized ptmx inode, including legacy 5:2 devices. + * @param flags Sanitized open flags. + * @return Descriptor or negative errno with session and path rollback. + * A legacy inode selects its sibling pts mount. An absent devpts sibling keeps + * the existing bootstrap PTY behavior until the runtime mounts devpts. + */ +static int device_ptmx_open(struct task *task, const struct vfs_path *path, uint32_t flags) +{ + struct vfs_path ptmx = {0}; + int rc = devpts_resolve_ptmx(path, &sched_task_paths(task)->root, &ptmx); + uint32_t id = 0; + if (!rc) { + rc = devpts_new_pty(&ptmx, task->pid, task->fsuid, task->fsgid, &id); + } else if (!(vfs_path_node(path)->flags & STORAGE_NODE_FLAG_DEVPTS) && + (rc == -RELIEFOS_ENOENT || rc == -RELIEFOS_ENODEV)) { + int32_t legacy = pty_create(task->pid); + rc = legacy < 0 ? legacy : 0; + if (!rc) id = (uint32_t)legacy; + } + if (rc) { + vfs_path_put(&ptmx); + return rc; + } + int fd = task_pty_endpoint_fd(task, id, TASK_PTY_ENDPOINT_MASTER, flags); + if (fd < 0) (void)pty_destroy(task->pid, id); + else device_pty_path(task, fd, ptmx.mount ? &ptmx : path); + vfs_path_put(&ptmx); + return fd; +} + /** @brief Open an already authorized character/block device by inode identity. * @param task Current task, borrowed under execution ownership. * @param path Borrowed held device path, retained before driver callbacks. * @param flags Sanitized status/descriptor flags; O_PATH is handled by caller. * @param diagnostic Optional display name, never used for device selection. * @return Descriptor or negative errno. PTY/DRM/audio ownership and failure - * rollback use the existing device lifecycles; no namespace-prefix routing. + * rollback use the existing device lifecycles. Devpts slaves resolve through + * their held instance/inode identity before global device-number dispatch. * No mount/module registry spinlock spans any driver callback or wait. */ int task_open_device_path(struct task *task,const struct vfs_path *path,uint32_t flags, @@ -34,7 +68,10 @@ int task_open_device_path(struct task *task,const struct vfs_path *path,uint32_t if(!node)return -RELIEFOS_EINVAL; if(vfs_path_mount_flags(path)&MS_NODEV)return -RELIEFOS_EACCES; struct storage_node device;bool native=(node->flags&STORAGE_NODE_FLAG_RDEV)!=0; - if(native) { + bool devpts = (node->flags & STORAGE_NODE_FLAG_DEVPTS) != 0; + if (devpts && !(node->flags & STORAGE_NODE_FLAG_PTY)) + return device_ptmx_open(task, path, flags); + if(native && !devpts) { struct linux_stat_abi status;int rc=vfs_path_stat(path,&status); if(!rc)rc=devfs_lookup_rdev(status.st_mode&LINUX_S_IFMT,status.st_rdev,&device); if(rc)return rc; @@ -52,21 +89,22 @@ int task_open_device_path(struct task *task,const struct vfs_path *path,uint32_t return -RELIEFOS_EBADF; } if(node->flags&STORAGE_NODE_FLAG_PTY) { - int fd=task_pty_endpoint_fd(task,node->first_cluster,TASK_PTY_ENDPOINT_SLAVE,flags); + uint32_t id = node->first_cluster; + if (devpts) { + int rc = devpts_slave_pty(path, &id); + if (rc) return rc; + } + int fd=task_pty_endpoint_fd(task,id,TASK_PTY_ENDPOINT_SLAVE,flags); if(fd>=0 && !(flags&LINUX_O_NOCTTY)) - pty_open_controlling(node->first_cluster,task->pid,(flags&LINUX_O_ACCMODE)!=LINUX_O_WRONLY); + pty_open_controlling(id,task->pid,(flags&LINUX_O_ACCMODE)!=LINUX_O_WRONLY); return device_pty_path(task,fd,path); } if(node->first_cluster==STORAGE_DEV_KIND_TTY && (native || (at_root && !__builtin_strcmp(name,"tty")))) { if(!task->controlling_pty_id)return -LINUX_ENXIO; return device_pty_path(task,task_pty_endpoint_fd(task,task->controlling_pty_id,TASK_PTY_ENDPOINT_SLAVE,flags),path); } - if(node->first_cluster==STORAGE_DEV_KIND_PTMX) { - int32_t id=pty_create(task->pid);if(id<0)return id; - int fd=task_pty_endpoint_fd(task,(uint32_t)id,TASK_PTY_ENDPOINT_MASTER,flags); - if(fd<0)(void)pty_destroy(task->pid,(uint32_t)id); - return device_pty_path(task,fd,path); - } + if(node->first_cluster==STORAGE_DEV_KIND_PTMX) + return device_ptmx_open(task, path, flags); if(node->first_cluster==STORAGE_DEV_KIND_DRM_CARD0 && (flags&LINUX_O_EXCL))return -LINUX_EBUSY; uint32_t kind=TASK_FILE_FLAG_DEV_NODE; if(node->first_cluster==STORAGE_DEV_KIND_NULL)kind|=TASK_FILE_FLAG_DEV_NULL; diff --git a/kernel/syscall/device/legacy_ioctl.c b/kernel/syscall/device/legacy_ioctl.c index 0871d8bc..62eeb6b1 100644 --- a/kernel/syscall/device/legacy_ioctl.c +++ b/kernel/syscall/device/legacy_ioctl.c @@ -318,6 +318,7 @@ static int64_t fb_user_blit(struct task *task,const struct framebuffer *fb,uint6 * @param a5 Sixth native ABI argument. * @return Original result, negative errno, or internal blocking/retry status. * @note The caller retains the kernel execution transaction and descriptor pins. + * TIOCGPTN returns the master session's instance-local devpts index. */ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) { @@ -747,7 +748,7 @@ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t if (!endpoint || endpoint->endpoint != TASK_PTY_ENDPOINT_MASTER) return -RELIEFOS_EINVAL; IOCTL_PREPARE(a2, sizeof(uint32_t), true, -RELIEFOS_EINVAL); if (!user_range_writable(a2, sizeof(uint32_t))) return -RELIEFOS_EINVAL; - *(uint32_t *)(uintptr_t)a2 = pty_id; + *(uint32_t *)(uintptr_t)a2 = pty_number(pty_id); return 0; } if (a1 == TIOCSPTLCK) { diff --git a/kernel/syscall/fd/pty_descriptor.c b/kernel/syscall/fd/pty_descriptor.c index 48eb04dc..fc48dd19 100644 --- a/kernel/syscall/fd/pty_descriptor.c +++ b/kernel/syscall/fd/pty_descriptor.c @@ -127,7 +127,7 @@ int task_pty_endpoint_fd(struct task *task, uint32_t pty_id, } /** - * @brief Parse a live numeric devpts path or resolve the active-VT alias. + * @brief Parse a live legacy PTY path or resolve the active-VT alias. * @param path NUL-terminated endpoint path; NULL is rejected. * @param pty_id Writable result for the recognized active PTY identifier. * @return One for a recognized live endpoint path, zero for malformed, inactive, @@ -152,7 +152,7 @@ int task_pty_endpoint_path(const char *path, uint32_t *pty_id) value = value * 10u + digit; ++path; ++digits; } - if (!digits || *path || !value || !pty_is_active(value)) return 0; + if (!digits || *path || !value || !pty_is_active(value) || pty_is_devpts(value)) return 0; *pty_id = value; return 1; } diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 4299ebdb..0e669f66 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -1,4 +1,5 @@ /* SPDX-License-Identifier: Apache-2.0 */ +#include #include "../internal.h" #include #include @@ -94,11 +95,11 @@ static int mount_remount(struct vfs_namespace *ns,struct task *task,uint64_t tar /** @brief Construct one supported backend without publishing a pathname alias. * @param ns Borrowed execution-owned namespace for block-source resolution. - * @param task Authorized caller whose fsuid/fsgid own a new tmpfs root. + * @param task Authorized caller whose fsuid/fsgid own a new tmpfs/devpts root. * @param source Copied kernel source label; its user pointer is passed separately. * @param source_user Original user source pathname for a disk filesystem. * @param type Copied filesystem type, empty for existing native detection. - * @param options Copied tmpfs, FAT ownership, or ext3 ordered-mode options. + * @param options Copied tmpfs/devpts, FAT ownership, or ext3 ordered-mode options. * @param flags Final mount policy without operation bits. * @param out Receives one owned detached mount, empty on failure. * @return Zero or unsupported/device/lookup/provider errno. Source resolution @@ -108,6 +109,7 @@ static int mount_remount(struct vfs_namespace *ns,struct task *task,uint64_t tar static int mount_backend(struct vfs_namespace *ns,struct task *task,const char *source,uint64_t source_user, const char *type,const char *options,uint64_t flags,struct vfs_mount **out) { + if(!__builtin_strcmp(type,"devpts"))return devpts_create_vfs_mount(source,flags,options,task->fsuid,task->fsgid,out); if(!__builtin_strcmp(type,"devtmpfs"))return devtmpfs_create_vfs_mount(source,flags,options,out); if(!__builtin_strcmp(type,"tmpfs"))return storage_new_tmpfs_mount(source,flags,options,task->fsuid,task->fsgid,out); /* The ext3 engine always uses ordered metadata transactions. Consume only diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index 388e9a60..7fe3228f 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -23,7 +23,7 @@ def test_real_tmpfs_without_text_routing(self): "-Wl,--gc-sections", "-Wl,--wrap=storage_ext4_read_inode", "-Wl,--wrap=storage_read_device", "-Wl,--wrap=storage_inode_stat", "-Wl,--wrap=storage_backend_commit_rename_metadata", "-Wl,--wrap=storage_cluster_write", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_backend_test.c", "kernel/dma/buffer.c", "drivers/storage/ahci/dma.c", "drivers/storage/ahci/interrupt.c", "drivers/storage/nvme/queue.c", "block/partition/mbr.c", "fs/vfs/filesystems.c", "fs/vfs/filesystem_instance.c", "fs/ext_common/journal.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/kernel_file.c", "fs/vfs/kernel_path.c", "fs/vfs/exec_file.c", "fs/vfs/attributes.c", "fs/vfs/initial.c", "fs/vfs/storage_initial.c", "fs/vfs/storage_attributes.c", "fs/vfs/storage_access.c", "fs/vfs/storage_backend.c", "fs/vfs/mutation.c", "fs/vfs/storage_mutation.c", "fs/vfs/storage_create.c", "fs/vfs/storage_security.c", "fs/vfs/write_access.c", - "fs/vfs/storage_mount.c", "fs/vfs/fat_options.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/security/access.c", "lib/text_utf16.c", "fs/devfs/mount.c", "fs/devfs/devtmpfs.c", "fs/devfs/devtmpfs_nodes.c", "fs/devfs/device.c", "fs/devfs/identity.c", "fs/vfs/pseudo.c", "kernel/exec/runtime.c", "kernel/exec/pending.c", "kernel/syscall/process/exec.c", "kernel/syscall/system/user_string.c", + "fs/devpts/devpts.c", "drivers/tty/pty/core.c", "drivers/tty/pty/ring.c", "drivers/tty/pty/line_discipline.c", "drivers/tty/pty/session.c", "drivers/tty/pty/vt.c", "kernel/syscall/device/device_open.c", "kernel/syscall/device/device_io.c", "kernel/syscall/fs/stat.c", "fs/vfs/storage_mount.c", "fs/vfs/fat_options.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/security/access.c", "lib/text_utf16.c", "fs/devfs/mount.c", "fs/devfs/devtmpfs.c", "fs/devfs/devtmpfs_nodes.c", "fs/devfs/device.c", "fs/devfs/identity.c", "fs/vfs/pseudo.c", "kernel/exec/runtime.c", "kernel/exec/pending.c", "kernel/syscall/process/exec.c", "kernel/syscall/system/user_string.c", "kernel/syscall/ipc/unix_path.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/create.c", "kernel/syscall/fs/mount.c", "kernel/syscall/fs/mutation.c", "kernel/syscall/fs/directory.c", "kernel/syscall/fs/size.c", "kernel/syscall/fs/sync.c", "kernel/syscall/fs/path.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fd/descriptor.c", "kernel/device/character.c", "kernel/syscall/io/vector.c", "kernel/syscall/fd/pty_descriptor.c", "kernel/sched/tables.c", "kernel/device/mapping.c", "kernel/sched/fs.c", "kernel/sync/wait.c", "-o", str(binary) ], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=20) diff --git a/tools/tests/Makefile b/tools/tests/Makefile index 224ab348..8be48f39 100644 --- a/tools/tests/Makefile +++ b/tools/tests/Makefile @@ -15,6 +15,7 @@ test-host-smoke: --suite acpi_pm_timer --suite apic_timer --suite cpu_accounting \ --suite fat_async_read --suite fat_read_split \ --suite squashfs --suite squashfs_boot \ + --suite linux_pty --suite mount_backend \ --suite vdso_mapping --suite vdso_time test-smp-time: diff --git a/tools/tests/linux_pty_test.c b/tools/tests/linux_pty_test.c index 8be64a9d..6df90ca2 100644 --- a/tools/tests/linux_pty_test.c +++ b/tools/tests/linux_pty_test.c @@ -77,6 +77,35 @@ void console_log(enum console_log_level level, const char *format, ...) } void console_write_len(const char *text, size_t count) { (void)text; (void)count; } +static unsigned devpts_hangups; +/** @brief Observe the binding removal after hangup is visible. + * @param binding Borrowed counter retained until callback delivery. + */ +static void test_devpts_hangup(void *binding) +{ + assert(binding == &devpts_hangups); + ++devpts_hangups; +} + +/** @brief Exercise public numbering, legacy isolation and one-shot hangup. */ +static void test_devpts_binding(void) +{ + pty_init(); + descriptor_refs = 0; + int id = pty_create(owner.pid); + assert(id > 0 && pty_number(id) == (uint32_t)id); + assert(!pty_transfer_get(id, TASK_PTY_ENDPOINT_MASTER)); + assert(!pty_bind_devpts(id, 0, &devpts_hangups, test_devpts_hangup)); + assert(pty_is_devpts(id) && pty_number(id) == 0); + assert(pty_bind_devpts(id, 1, &devpts_hangups, test_devpts_hangup) == -LINUX_EBUSY); + char name[32]; + snprintf(name, sizeof(name), "/dev/pts/%u", id); + assert(pty_lookup_path(name, NULL) == -LINUX_ENOENT); + pty_transfer_put(id, TASK_PTY_ENDPOINT_MASTER); + assert(devpts_hangups == 1 && !pty_is_active(id)); + descriptor_refs = 1; +} + static void test_queue_boundaries(void) { char input[PTY_OUTPUT_CAP + 32], output[sizeof(input)]; @@ -556,6 +585,7 @@ int main(void) assert(pty_write_output(1, "h\ni", 3) == 3); assert(vt_written_len == 4 && !memcmp(vt_written, "h\r\ni", 4)); } + test_devpts_binding(); test_queue_boundaries(); test_cooked_echo(); puts("PASS native PTY modes, OPOST output post-processing, controlling-session isolation and queued-rights lifetime"); diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 4ba657a0..63777a7b 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -6,6 +6,7 @@ #define RELIEFNT_FIXTURE_ISO_READER #define RELIEFNT_FIXTURE_SECTOR_STATS #define RELIEFNT_FIXTURE_REAL_DAC +#define RELIEFNT_FIXTURE_REAL_PTY #define RELIEFNT_FIXTURE_PTY_METADATA #define RELIEFNT_FIXTURE_UNMAPPED_TRUNCATE #define RELIEFNT_FIXTURE_SEPARATE_JOURNAL @@ -25,6 +26,9 @@ int kernel_signal_queue_task(struct task *task,int signal_number) #include #include #include +#include +#include +#include #include #include #include @@ -178,8 +182,76 @@ void sched_truncate_file_mappings(const struct storage_node *node,uint64_t size) assert(node && (node->flags&STORAGE_NODE_FLAG_TMPFS) && size<=INT64_MAX); ++unmapped_truncate_notifications; } -int pty_inode_permissions(const struct storage_node *node,struct reliefos_permissions *value,bool write) -{(void)node;(void)value;(void)write;return -EOPNOTSUPP;} +/* PTYs use the production core and descriptors. This fixture has one actor, + * no asynchronous console hardware and no other scheduler terminal owners. */ +static struct task *devpts_actor; +bool console_vga_text_mode; +/** @brief Reject an unexpected blocked scheduler actor in the synchronous fixture. + * @param task Unexpected waiter. */ +void sched_wake_interruptible(struct task *task) { (void)task; abort(); } +const struct framebuffer *framebuffer_get(void) { return NULL; } +void kernel_spin_init(struct kernel_spinlock *lock) { lock->state = 0; } +void console_vt_write(uint32_t number, const char *text, size_t count) +{ (void)number; (void)text; (void)count; } +struct task *sched_find(uint32_t pid) +{ return devpts_actor && devpts_actor->pid == pid ? devpts_actor : NULL; } +uint32_t sched_pty_reference_count(uint32_t id) { return pty_transfer_count(id, 0); } +uint32_t sched_pty_master_reference_count(uint32_t id) { return pty_transfer_count(id, 1); } +int sched_hangup_user_tasks_for_pty(uint32_t id, uint32_t owner) +{ (void)id; (void)owner; return 0; } +int sched_signal_kernel_group(uint32_t group, int signal) +{ (void)group; (void)signal; return 0; } +int sched_signal_user_process(uint32_t pid, int signal) +{ (void)pid; (void)signal; return 0; } +int sched_process_group_orphaned(uint32_t group) { (void)group; return 0; } +void sched_set_controlling_pty(uint32_t pid, uint32_t id) +{ assert(devpts_actor && devpts_actor->pid == pid); devpts_actor->controlling_pty_id = id; } +void task_epoll_remove_pty_description(struct task_pty_description *description) +{ (void)description; } +/** @brief Clear the fixture actor's controlling-terminal identity on hangup. + * @param id Internal session being detached. */ +void sched_clear_controlling_pty(uint32_t id) +{ if (devpts_actor && devpts_actor->controlling_pty_id == id) devpts_actor->controlling_pty_id = 0; } +struct reliefos_flock_entry reliefos_flocks[RELIEFOS_FLOCK_MAX]; +/** @brief Model the empty advisory-lock and epoll registries in this fixture. + * @param owner Borrowed open description with no registered watches or locks. */ +void syscall_flock_release_owner(struct task_file *owner) { (void)owner; } +/** @brief Observe close against an empty record-lock registry. + * @param task Borrowed actor. @param descriptor Borrowed descriptor. */ +void syscall_record_locks_close(struct task *task, struct task_file *descriptor) +{ (void)task; (void)descriptor; } +/** @brief Retire an unwatched description in this fixture. + * @param description Borrowed open description. */ +void task_epoll_remove_file_description(struct task_file *description) { (void)description; } +/** @brief Reject use of an unmodelled epoll object. + * @param epoll Unexpected owned object. */ +void task_epoll_destroy(struct task_epoll *epoll) { (void)epoll; abort(); } +/** @brief Reject use of an unmodelled pidfd identity. + * @param identity Unexpected owned identity. */ +void sched_task_pidfd_put(struct task_identity *identity) { (void)identity; abort(); } +/** @brief Reject release of an unmodelled input grab. + * @param kind Unexpected device kind. @param token Unexpected grab identity. */ +void input_evdev_release(uint32_t kind, uint64_t token) { (void)kind; (void)token; abort(); } +/** @brief Check that generic close has no pipe resource to release. + * @param file Borrowed fixture description. */ +void task_pipe_release(struct task_file *file) { assert(!(file->flags & TASK_FILE_FLAG_PIPE)); } +/** @brief Check that generic close has no Unix socket resource to release. + * @param file Borrowed fixture description. */ +void task_socket_release(struct task_file *file) { assert(!(file->flags & TASK_FILE_FLAG_SOCKET_UNIX)); } +/** @brief Check that generic close has no Internet socket resource to release. + * @param file Borrowed fixture description. */ +void task_inet_release(struct task_file *file) { assert(!(file->flags & TASK_FILE_FLAG_SOCKET_INET)); } +/** @brief Check that generic close has no shared-memory device to release. + * @param file Borrowed fixture description. */ +void task_shm_release(struct task_file *file) { assert(!task_device_is(file, STORAGE_DEV_KIND_SHM)); } +/** @brief Model the empty queued-socket collector. */ +void task_socket_collect(void) {} +/* The device entry point must route these tests to a real PTY endpoint. */ +int task_shm_attach(struct task_file *file, uint32_t size) +{ (void)file; (void)size; abort(); } +uint64_t input_evdev_cursor_now(void) { abort(); } +uint32_t task_evdev_vt_hint(const struct task *task) { (void)task; abort(); } + static uint64_t filesystem_sector_reads; static uintptr_t lookup_user_base; static size_t lookup_user_bytes; @@ -2404,6 +2476,206 @@ static void devtmpfs_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pa puts("PASS devtmpfs mount syscall: shared writable device inodes, metadata, fd symlinks and independent mount policy"); } +/** @brief Exercise mounted PTYs through the actual device-open/FD lifecycle. + * @param ns Real fixture namespace. @param root Its retained root path. + * @param fs Tmpfs hosting the mountpoints. No asynchronous hardware is used. */ +static void devpts_mount_syscalls(struct vfs_namespace *ns, const struct vfs_path *root, + struct tmpfs_super *fs) +{ + const char *invalid[] = {"uid=", "uid=-1", "gid=4294967295", "mode=08", + "ptmxmode=10000", "max=1048577", "max=-1", "newinstance=1", "unknown=1"}; + struct vfs_mount *detached = NULL; + for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { + assert(devpts_create_vfs_mount(NULL, 0, invalid[i], 0, 0, &detached) == -EINVAL); + assert(!detached); + } + bool created = false; + for (int budget = 0; budget < 20; ++budget) { + test_fail_heap_after = budget; + int rc = devpts_create_vfs_mount(NULL, 0, NULL, 0, 0, &detached); + test_fail_heap_after = -1; + if (!rc) { + vfs_mount_put(detached); + created = true; + break; + } + assert(rc == -ENOMEM && !detached); + } + assert(created); + assert(!tmpfs_create(fs, "/pts-one", LINUX_S_IFDIR | 0755, NULL, NULL)); + assert(!tmpfs_create(fs, "/pts-two", LINUX_S_IFDIR | 0755, NULL, NULL)); + assert(!tmpfs_create(fs, "/ptys", LINUX_S_IFDIR | 0755, NULL, NULL)); + assert(!tmpfs_create(fs, "/ptys/pts", LINUX_S_IFDIR | 0755, NULL, NULL)); + struct storage_node directory; + struct reliefos_permissions device_mode = {0666, 1000, 1000}; + assert(!tmpfs_lookup(fs, "/ptys", &directory)); + assert(!tmpfs_mknod_child(fs, directory.first_cluster, "ptmx", LINUX_S_IFCHR | 0666, + 0x502, &device_mode, NULL)); + assert(!tmpfs_mknod_child(fs, directory.first_cluster, "copied-slave", LINUX_S_IFCHR | 0666, + 136u << 8, &device_mode, NULL)); + assert(!tmpfs_create(fs, "/ptys/link", LINUX_S_IFLNK | 0777, "pts/ptmx", NULL)); + struct task actor = {.pid = 903, .fsuid = 1000, .fsgid = 1000, + .cap_effective = 1ULL << CAP_SYS_ADMIN}; + devpts_actor = &actor; + sched_task_limits(&actor)->nofile.rlim_cur = 64; + vfs_path_get(root, &actor.fs_paths.root); + vfs_path_get(root, &actor.fs_paths.cwd); + struct { char source[16], target[32], type[16], options[96]; } user = { + "devpts", "/pts-one", "devpts", "newinstance,uid=123,gid=456,mode=0620,ptmxmode=0666,max=2"}; + lookup_user_base = (uintptr_t)&user; + lookup_user_bytes = sizeof(user); + assert(!scoped_mount_call(ns, &actor, LINUX_SYS_MOUNT, (uintptr_t)user.source, + (uintptr_t)user.target, (uintptr_t)user.type, MS_NOSUID, (uintptr_t)user.options)); + struct vfs_path one = {0}, two = {0}, first = {0}, second = {0}, slave = {0}; + assert(!vfs_path_lookup(ns, root, root, "/pts-one/ptmx", 0, &one)); + strcpy(user.target, "/pts-two"); + assert(!scoped_mount_call(ns, &actor, LINUX_SYS_MOUNT, (uintptr_t)user.source, + (uintptr_t)user.target, (uintptr_t)user.type, 0, 0)); + assert(!vfs_path_lookup(ns, root, root, "/pts-two/ptmx", 0, &two)); + struct linux_stat_abi status, other; + assert(!vfs_path_stat(&one, &status) && (status.st_mode & 0777) == 0666); + assert(!vfs_path_stat(&two, &other) && (other.st_mode & 0777) == 0); + assert(status.st_rdev == 0x502 && other.st_rdev == 0x502 && status.st_dev != other.st_dev); + int master = task_open_device_path(&actor, &one, LINUX_O_RDWR | LINUX_O_NOCTTY, NULL); + assert(master >= 0); + uint32_t id = task_pty_fd_for_fd(&actor, master)->pty_id; + assert(pty_is_devpts(id) && pty_number(id) == 0); + assert(vfs_path_equal(&task_pty_fd_for_fd(&actor, master)->description->path_ref, &one)); + int another = task_open_device_path(&actor, &two, LINUX_O_RDWR | LINUX_O_NOCTTY, NULL); + assert(another >= 0); + uint32_t other_id = task_pty_fd_for_fd(&actor, another)->pty_id; + assert(id != other_id && pty_number(other_id) == 0); + assert(!vfs_path_lookup(ns, root, root, "/pts-one/0", 0, &first)); + assert(!vfs_path_lookup(ns, root, root, "/pts-two/0", 0, &second)); + assert(!vfs_path_stat(&first, &status) && status.st_uid == 123 && status.st_gid == 456); + assert((status.st_mode & 0777) == 0620); + assert(!vfs_path_stat(&second, &other) && other.st_uid == 1000 && other.st_gid == 1000); + assert(status.st_rdev == other.st_rdev && status.st_dev != other.st_dev); + assert(task_open_device_path(&actor, &first, LINUX_O_RDWR | LINUX_O_NOCTTY, NULL) == -EIO); + assert(!pty_set_lock(id, 0) && !pty_set_lock(other_id, 0)); + int fd = task_open_device_path(&actor, &first, LINUX_O_RDWR | LINUX_O_NOCTTY, NULL); + assert(fd >= 0 && task_pty_fd_for_fd(&actor, fd)->pty_id == id); + int other_fd = task_open_device_path(&actor, &second, LINUX_O_RDWR | LINUX_O_NOCTTY, NULL); + assert(other_fd >= 0 && task_pty_fd_for_fd(&actor, other_fd)->pty_id == other_id); + assert(pty_write_input(actor.pid, id, "one\n", 4) == 4); + char input[8] = {0}; + assert(pty_read_input(other_id, input, sizeof(input)) == -EAGAIN); + assert(pty_read_input(id, input, sizeof(input)) == 4 && !memcmp(input, "one\n", 4)); + assert(!vfs_path_lookup(ns, root, root, "/pts-one", 0, &slave)); + struct vfs_path target = {0}, bound = {0}; + assert(!vfs_path_lookup(ns, root, root, "/ptys/pts", 0, &target)); + assert(!vfs_mount_bind(ns, &slave, &target)); + vfs_path_put(&target); + assert(!vfs_path_lookup(ns, root, root, "/ptys/pts/0", 0, &bound)); + uint32_t bound_id = 0; + assert(!devpts_slave_pty(&bound, &bound_id) && bound_id == id); + vfs_path_put(&bound); + const char *multiplexors[] = {"/ptys/ptmx", "/ptys/link"}; + for (size_t i = 0; i < sizeof(multiplexors) / sizeof(multiplexors[0]); ++i) { + assert(!vfs_path_lookup(ns, root, root, multiplexors[i], VFS_LOOKUP_FOLLOW, &bound)); + int alias = task_open_device_path(&actor, &bound, LINUX_O_RDWR, NULL); + assert(alias >= 0); + struct task_pty_fd *endpoint = task_pty_fd_for_fd(&actor, alias); + assert(pty_number(endpoint->pty_id) == 1 && pty_is_devpts(endpoint->pty_id)); + assert(vfs_path_context(&endpoint->description->path_ref) == vfs_path_context(&one)); + task_pty_release_entry(endpoint); + vfs_path_put(&bound); + } + assert(!vfs_path_lookup(ns, root, root, "/ptys/copied-slave", 0, &bound)); + assert(task_open_device_path(&actor, &bound, LINUX_O_RDWR, NULL) == -ENXIO); + vfs_path_put(&bound); + assert(!vfs_path_lookup(ns, root, root, "/ptys/pts", 0, &target)); + assert(!vfs_mount_unmount(ns, &target)); + vfs_path_put(&target); + vfs_path_put(&slave); + /* Failed option parsing preserves policy and metadata. Remount defaults + * apply to new slaves, while existing slave owners and modes survive. */ + assert(!vfs_path_lookup(ns, root, root, "/pts-one", 0, &target)); + assert(vfs_path_remount_options(&target, MS_NODEV, "ptmxmode=0600,unknown=1") == -EINVAL); + assert(!(vfs_path_mount_flags(&one) & MS_NODEV)); + assert(!vfs_path_stat(&one, &status) && (status.st_mode & 07777) == 0666); + assert(!vfs_path_remount_options(&target, MS_NODEV, ",mode=06720,ptmxmode=01666,max=2,")); + assert(!vfs_path_stat(&one, &status) && (status.st_mode & 07777) == 01666); + assert(task_open_device_path(&actor, &one, LINUX_O_RDWR, NULL) == -EACCES); + assert(task_open_device_path(&actor, &first, LINUX_O_RDWR, NULL) == -EACCES); + assert(!vfs_path_remount_options(&target, MS_NOSUID, NULL)); + assert(!vfs_path_stat(&one, &status) && (status.st_mode & 07777) == 0); + int defaults = task_open_device_path(&actor, &one, LINUX_O_RDWR, NULL); + assert(defaults >= 0); + assert(!vfs_path_lookup(ns, root, root, "/pts-one/1", 0, &slave)); + assert(!vfs_path_stat(&slave, &status) && (status.st_mode & 07777) == 0600); + assert(status.st_uid == actor.fsuid && status.st_gid == actor.fsgid); + task_pty_release_entry(task_pty_fd_for_fd(&actor, defaults)); + vfs_path_put(&slave); + assert(!vfs_path_stat(&first, &status) && (status.st_mode & 07777) == 0620); + assert(status.st_uid == 123 && status.st_gid == 456); + assert(!vfs_path_remount_options(&target, MS_NOSUID, + "uid=123,gid=456,mode=0620,ptmxmode=0666,max=2")); + vfs_path_put(&target); + bool opened = false; + for (int budget = 0; budget < 20; ++budget) { + test_fail_heap_after = budget; + int rc = task_open_device_path(&actor, &one, LINUX_O_RDWR, NULL); + test_fail_heap_after = -1; + if (rc >= 0) { + assert(pty_number(task_pty_fd_for_fd(&actor, rc)->pty_id) == 1); + task_pty_release_entry(task_pty_fd_for_fd(&actor, rc)); + opened = true; + break; + } + assert(rc == -ENOMEM); + assert(vfs_path_lookup(ns, root, root, "/pts-one/1", 0, &slave) == -ENOENT); + } + assert(opened); + /* A failed FD reservation must retire the new name and instance quota. */ + sched_task_limits(&actor)->nofile.rlim_cur = 0; + assert(task_open_device_path(&actor, &one, LINUX_O_RDWR, NULL) == -EMFILE); + sched_task_limits(&actor)->nofile.rlim_cur = 64; + assert(vfs_path_lookup(ns, root, root, "/pts-one/1", 0, &slave) == -ENOENT); + int extra = task_open_device_path(&actor, &one, LINUX_O_RDWR, NULL); + assert(extra >= 0 && pty_number(task_pty_fd_for_fd(&actor, extra)->pty_id) == 1); + assert(task_open_device_path(&actor, &one, LINUX_O_RDWR, NULL) == -ENOSPC); + task_pty_release_entry(task_pty_fd_for_fd(&actor, extra)); + task_pty_release_entry(task_pty_fd_for_fd(&actor, master)); + assert(vfs_path_lookup(ns, root, root, "/pts-one/0", 0, &slave) == -ENOENT); + assert(task_open_device_path(&actor, &first, LINUX_O_RDWR, NULL) == -EIO); + assert(!vfs_path_stat(&first, &status) && status.st_nlink == 0); + assert(pty_read_input(id, input, sizeof(input)) == 0); + extra = task_open_device_path(&actor, &one, LINUX_O_RDWR, NULL); + assert(extra >= 0 && pty_number(task_pty_fd_for_fd(&actor, extra)->pty_id) == 1); + task_pty_release_entry(task_pty_fd_for_fd(&actor, extra)); + task_pty_release_entry(task_pty_fd_for_fd(&actor, fd)); + uint64_t old_ino = status.st_ino; + /* A retained inode alone must allow index/quota reuse after endpoints close. */ + extra = task_open_device_path(&actor, &one, LINUX_O_RDWR, NULL); + assert(extra >= 0 && pty_number(task_pty_fd_for_fd(&actor, extra)->pty_id) == 0); + assert(!vfs_path_lookup(ns, root, root, "/pts-one/0", 0, &slave)); + assert(!vfs_path_stat(&slave, &status) && status.st_ino != old_ino); + assert(task_open_device_path(&actor, &first, LINUX_O_RDWR, NULL) == -EIO); + task_pty_release_entry(task_pty_fd_for_fd(&actor, extra)); + vfs_path_put(&slave); + vfs_path_put(&first); + /* Ordinary unmount stays busy while endpoints or inode paths are retained. */ + assert(!vfs_path_lookup(ns, root, root, "/pts-two", 0, &target)); + assert(vfs_mount_unmount(ns, &target) == -EBUSY); + task_pty_release_entry(task_pty_fd_for_fd(&actor, another)); + task_pty_release_entry(task_pty_fd_for_fd(&actor, other_fd)); + vfs_path_put(&second); + vfs_path_put(&two); + assert(!vfs_mount_unmount(ns, &target)); + vfs_path_put(&target); + vfs_path_put(&one); + assert(!vfs_path_lookup(ns, root, root, "/pts-one", 0, &target)); + assert(!vfs_mount_unmount(ns, &target)); + vfs_path_put(&target); + vfs_path_put(&actor.fs_paths.root); + vfs_path_put(&actor.fs_paths.cwd); + sched_task_pty_release(&actor); + lookup_user_base = lookup_user_bytes = 0; + devpts_actor = NULL; + puts("PASS devpts: independent zero-based indices, metadata, exact device opens, bind identity, max, FD rollback, hangup and reuse"); +} + static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_path *root,struct tmpfs_super *fs) { assert(!tmpfs_create(fs,"/syscall-source",LINUX_S_IFDIR|0755,NULL,NULL)); @@ -2658,6 +2930,7 @@ int main(int argc,char **argv) assert(!vfs_namespace_init(&ns,mount));vfs_mount_put(mount); assert(!vfs_namespace_root(&ns,&root)); devtmpfs_mount_syscalls(&ns,&root,fs); + devpts_mount_syscalls(&ns,&root,fs); vfs_path_put(&root); assert(!vfs_namespace_destroy(&ns) && !storage_inode_volume_busy(0)); tmpfs_destroy(fs);g_volumes[0]=(struct storage_volume){0}; diff --git a/tools/tests/storage_mkdir_mount_test.c b/tools/tests/storage_mkdir_mount_test.c index 3bcb0805..9f1c8e0c 100644 --- a/tools/tests/storage_mkdir_mount_test.c +++ b/tools/tests/storage_mkdir_mount_test.c @@ -177,6 +177,7 @@ int pty_inode_permissions(const struct storage_node *node,struct reliefos_permis { (void)node; (void)value; (void)write; abort(); } #endif uint32_t smp_cpu_count(void) { return 1; } +#ifndef RELIEFNT_FIXTURE_REAL_PTY int pty_lookup_path(const char *path, struct storage_node *node) { (void)path; (void)node; abort(); } /** @brief Model virtual consoles before tty initialization. @@ -185,6 +186,7 @@ int pty_lookup_path(const char *path, struct storage_node *node) */ int pty_lookup_vt_path(const char *path, struct storage_node *node) { (void)path; (void)node; return -2; } +#endif /* RAM-backed ext2 must never touch the physical controller or other codecs. */ #ifndef RELIEFNT_FIXTURE_OWN_IRQ_LOCKS void kernel_spin_lock_irqsave(struct kernel_spinlock *lock,uint64_t *flags) From b24a9f28a317dcfdd3debdb66467050e33841640 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sat, 28 Nov 2026 19:30:21 +0800 Subject: [PATCH 03/97] docs(i18n): translate devtmpfs and devpts manual --- .../userspace-api/device-filesystems.po | 204 ++++++++++++++++++ .../userspace-api/device-filesystems.po | 177 +++++++++++++++ 2 files changed, 381 insertions(+) create mode 100644 Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po create mode 100644 Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po new file mode 100644 index 00000000..f57e9a09 --- /dev/null +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -0,0 +1,204 @@ +# +msgid "" +msgstr "" +"Project-Id-Version: ReliefNT VERSION\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-11-28 00:00+0000\n" +"PO-Revision-Date: 2026-11-28 00:00+0000\n" +"Last-Translator: ReliefNT translators\n" +"Language: en\n" +"Language-Team: en\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "设备节点、devtmpfs 与 devpts" +msgstr "Device nodes, devtmpfs and devpts" + +msgid "devtmpfs" +msgstr "devtmpfs" + +msgid "" +"``mount(\"devtmpfs\", target, \"devtmpfs\", flags, data)`` 挂载内核维护的设备节点。 " +"所有挂载共享同一内存文件系统及节点元数据,每个挂载分别维护 ``nodev``、 ``nosuid``、``noexec`` " +"等挂载点策略。普通文件、目录、符号链接及用户创建的 设备节点使用现有 VFS 权限检查。设备打开按 inode 的类型和 ``st_rdev`` " +"分派到驱动,``nodev`` 挂载拒绝打开设备。" +msgstr "" +"``mount(\"devtmpfs\", target, \"devtmpfs\", flags, data)`` mounts the " +"kernel-maintained device nodes. All mounts share the same in-memory " +"filesystem and node metadata. Each mount retains its own mountpoint " +"policies, including ``nodev``, ``nosuid``, and ``noexec``. Regular files," +" directories, symlinks, and user-created device nodes use the existing " +"VFS permission checks. Device opens are dispatched to drivers by inode " +"type and ``st_rdev``; a ``nodev`` mount rejects device opens." + +msgid "设备生命周期" +msgstr "Device lifecycle" + +msgid "" +"设备注册、注销及分区变化通知 VFS worker 合并更新。首次挂载同步生成完整 设备清单。后续更新保留已有设备的 " +"``chmod``、``chown``,并尊重用户删除、 替换和占用的名称。设备移除只删除仍由内核持有的原 inode,非空目录保留。 " +"内存不足时保留已发布节点与待重试状态。最后一个公开挂载卸载后,私有 backing 继续保留,后续挂载可看到原有内容及权限。" +msgstr "" +"Device registration, removal, and partition changes notify the VFS " +"worker, which coalesces updates. The first mount synchronously populates " +"the complete device inventory. Later updates retain ``chmod`` and " +"``chown`` changes and respect names removed, replaced, or occupied by " +"users. Device removal deletes only the original inode still owned by the " +"kernel; nonempty directories remain. If memory runs out, published nodes " +"remain and the update stays pending for retry. The private backing " +"filesystem survives the last public unmount, so later mounts see the same" +" contents and permissions." + +msgid "" +"设备默认归 root,权限为 ``0600``。``null``、``zero``、``full``、``random``、 " +"``urandom``、``tty`` 和 ``ptmx`` 为 ``0666``。``fd``、``stdin``、``stdout``、 " +"``stderr`` 使用指向 ``/proc/self/fd`` 及对应描述符的符号链接。 ``pts`` 和 ``shm`` " +"提供独立文件系统的挂载目录。" +msgstr "" +"Devices default to root ownership and mode ``0600``. ``null``, ``zero``, " +"``full``, ``random``, ``urandom``, ``tty``, and ``ptmx`` use mode " +"``0666``. ``fd``, ``stdin``, ``stdout``, and ``stderr`` are symlinks to " +"``/proc/self/fd`` and the corresponding descriptors. ``pts`` and ``shm`` " +"provide mountpoints for separate filesystems." + +msgid "devtmpfs 挂载选项" +msgstr "devtmpfs mount options" + +msgid "" +"挂载数据使用 tmpfs 的 ``mode``、``uid``、``gid``、``size``、``nr_blocks`` 和 " +"``nr_inodes`` 语法。私有 backing 初始为 ``mode=0755,size=0,nr_inodes=0``。 " +"重新配置先验证整个选项集,再原子提交容量和超级块策略。``mode``、``uid``、 ``gid`` 只在首次创建 tmpfs 时设置根 " +"inode。已有无限容量的实例拒绝追溯增加 容量上限,已有内容也必须容纳在新上限内,与 Linux shmem 的重新配置约束一致。" +msgstr "" +"Mount data uses the tmpfs syntax for ``mode``, ``uid``, ``gid``, " +"``size``, ``nr_blocks``, and ``nr_inodes``. The private backing " +"filesystem starts with ``mode=0755,size=0,nr_inodes=0``. Reconfiguration " +"validates the whole option set before atomically committing capacity and " +"superblock policy. ``mode``, ``uid``, and ``gid`` set the root inode only" +" at initial tmpfs creation. An existing unlimited instance cannot " +"retroactively acquire a limit, and existing contents must fit under any " +"new limit, matching Linux shmem reconfiguration constraints." + +msgid "devpts" +msgstr "devpts" + +msgid "" +"``mount(\"devpts\", target, \"devpts\", flags, data)`` 每次创建独立实例,通常挂在 " +"``/dev/pts``。每个实例有自己的 ``st_dev``、``ptmx`` 和从 0 开始的从端编号; " +"绑定挂载保留原实例。``statfs`` 报告 ``0x1cd1``,``/proc/filesystems`` 将其列为 ``nodev`` " +"文件系统。打开 ``ptmx`` 后,``TIOCGPTN`` 返回本实例的编号; ``TIOCSPTLCK`` 解锁后才能打开对应从端。" +msgstr "" +"Each ``mount(\"devpts\", target, \"devpts\", flags, data)`` creates a " +"separate instance, normally at ``/dev/pts``. Each instance has its own " +"``st_dev``, ``ptmx``, and slave numbering starting at 0. Bind mounts " +"retain the original instance. ``statfs`` reports ``0x1cd1``, and " +"``/proc/filesystems`` lists devpts as a ``nodev`` filesystem. After " +"opening ``ptmx``, ``TIOCGPTN`` returns the number in that instance. Use " +"``TIOCSPTLCK`` to unlock the slave before opening it." + +msgid "" +"从端报告字符设备号 ``136:<编号>``,但打开时以实际实例和 inode 身份为准,复制 " +"设备号创建的节点不会连接到该终端。``/proc//stat`` 中的控制终端设备号也 使用实例内编号;固定虚拟终端仍使用主设备号 4。" +msgstr "" +"The slave reports character device number ``136:``, but opening " +"it uses the actual instance and inode identity. A node created with a " +"copy of the number will not connect to that terminal. The controlling " +"terminal device number in ``/proc//stat`` also uses the instance-" +"local number. Fixed virtual terminals still use major number 4." + +msgid "devpts 挂载选项" +msgstr "devpts mount options" + +msgid "" +"``uid=``、``gid=``:新从端的十进制所有者;未指定时使用创建 PTY 的进程的 ``fsuid``、``fsgid``。根目录和 " +"``ptmx`` 归挂载者,根目录初始权限为 ``0755``。" +msgstr "" +"``uid=`` and ``gid=`` set the decimal owner IDs for new slaves. When " +"omitted, they default to the PTY creator's ``fsuid`` and ``fsgid``. The " +"mounter owns the root directory and ``ptmx``. The root directory starts " +"with mode ``0755``." + +msgid "" +"``mode=``、``ptmxmode=``:八进制权限,最多保留 ``07777``。默认从端为 ``0600``、``ptmx`` 为 " +"``0000``。若直接通过符号链接或绑定挂载打开 ``ptmx``, 可用 ``ptmxmode=0666`` 或相应的 ``chmod`` " +"让非特权用户访问。" +msgstr "" +"``mode=`` and ``ptmxmode=`` take octal permissions and retain bits " +"through ``07777``. The slave defaults to ``0600`` and ``ptmx`` to " +"``0000``. For direct access to ``ptmx`` through a symlink or bind mount, " +"use ``ptmxmode=0666`` or the equivalent ``chmod`` to grant access to " +"unprivileged users." + +msgid "" +"``max=``:实例内保留的 PTY 数量上限,范围为 0 到 1048576。默认不额外限制 内部 PTY 资源。达到上限时,新建返回 " +"``ENOSPC``。" +msgstr "" +"``max=`` caps reserved PTYs per instance, from 0 to 1048576. By default " +"no additional limit is applied to internal PTY resources. Creating a PTY " +"at the limit fails with ``ENOSPC``." + +msgid "``newinstance``:兼容选项,可以省略。忽略逗号之间的空字段。" +msgstr "" +"``newinstance`` is accepted for compatibility and may be omitted. Empty " +"fields between commas are ignored." + +msgid "" +"重新挂载从默认值解析选项。成功后立即更新 ``ptmx`` 权限和挂载策略;新选项 只改变以后创建的从端,不重置已有从端的权限或所有者。降低 " +"``max`` 不会强制 关闭已有会话。未通过验证的选项不会改变现有配置或挂载策略。标记 ``nodev`` 的挂载点不能用来直接打开设备。" +msgstr "" +"Remount parses options from their defaults. On success it updates " +"``ptmx`` permissions and mount policy immediately. New options affect " +"only future slaves and do not reset existing slave permissions or " +"ownership. Lowering ``max`` does not forcibly close sessions. Options " +"that fail validation leave the configuration and mount policy unchanged. " +"A mountpoint marked ``nodev`` cannot be used to open devices directly." + +msgid "编号与卸载" +msgstr "Numbering and unmounting" + +msgid "" +"最后一个主端关闭时,从端名称被移除,仍打开的从端收到挂断通知。仍有端点引用 的会话继续占用编号和 ``max`` 配额;只剩 ``O_PATH``" +" 等元数据引用时则可以重用 公开编号。旧的从端 inode 与新会话不同:仍可读取旧 inode 的元数据(链接数为 0),尝试再次打开设备返回 " +"``EIO``。正常卸载时仍被打开的路径或端点引用会令 挂载忙(``EBUSY``);释放引用后可以卸载。" +msgstr "" +"Closing the last master unlinks the slave name and notifies still-open " +"slave endpoints of a hangup. Sessions with endpoint references still " +"reserve their number and count against ``max``. If only metadata " +"references such as ``O_PATH`` remain, the public number can be reused. " +"The old slave inode is distinct from the new session: its metadata " +"remains readable (with a link count of 0), but opening it as a device " +"again fails with ``EIO``. Open paths or endpoints make a normal unmount " +"fail with ``EBUSY`` until the references are released." + +msgid "" +"打开传统字符设备 ``5:2`` 时,内核从该设备实际所在的目录查找同级 ``pts/ptmx``。找到 devpts " +"后,新会话及主端描述符属于该实例,传统设备本身的 权限决定是否可打开。找不到有效的 devpts 多路复用器时沿用启动阶段的旧 PTY " +"分配;其他查找错误则返回调用方。" +msgstr "" +"When opening legacy character device ``5:2``, the kernel looks for " +"sibling ``pts/ptmx`` under the actual directory that contains the device." +" If it finds devpts, the new session and master descriptor belong to that" +" instance, while access depends on the permissions of the legacy device " +"node. If no valid devpts multiplexer is found, the kernel uses its early-" +"boot PTY allocation path. Other lookup errors are returned to the caller." + +msgid "验证范围" +msgstr "Validation scope" + +msgid "" +"``tools/test_mount_backend.py`` 覆盖 devtmpfs 共享挂载、元数据、设备号、符号 " +"链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 " +"选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` 覆盖 PTY " +"ABI、会话与主端挂断行为。目标系统启动与 udev 集成由 ReliefOS 的 系统迁移验证覆盖。" +msgstr "" +"``tools/test_mount_backend.py`` checks shared devtmpfs mounts, metadata, " +"device numbers, symlinks, device addition and removal, user replacements," +" mount policies, and retry after allocation failure. It also checks " +"devpts instance isolation, mount options, bind mounts, endpoint " +"lifecycles, number reuse, and failure rollback. " +"``tools/test_linux_pty.py`` checks the PTY ABI, sessions, and master " +"hangup behavior. Guest boot and udev integration are covered by the " +"ReliefOS system migration validation." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po new file mode 100644 index 00000000..3e46b692 --- /dev/null +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -0,0 +1,177 @@ +# +msgid "" +msgstr "" +"Project-Id-Version: ReliefNT VERSION\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-11-28 00:00+0000\n" +"PO-Revision-Date: 2026-11-28 00:00+0000\n" +"Last-Translator: ReliefNT translators\n" +"Language: ja\n" +"Language-Team: ja\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "设备节点、devtmpfs 与 devpts" +msgstr "デバイスノード、devtmpfs と devpts" + +msgid "devtmpfs" +msgstr "devtmpfs" + +msgid "" +"``mount(\"devtmpfs\", target, \"devtmpfs\", flags, data)`` 挂载内核维护的设备节点。 " +"所有挂载共享同一内存文件系统及节点元数据,每个挂载分别维护 ``nodev``、 ``nosuid``、``noexec`` " +"等挂载点策略。普通文件、目录、符号链接及用户创建的 设备节点使用现有 VFS 权限检查。设备打开按 inode 的类型和 ``st_rdev`` " +"分派到驱动,``nodev`` 挂载拒绝打开设备。" +msgstr "" +"``mount(\"devtmpfs\", target, \"devtmpfs\", flags, data)`` " +"はカーネルが管理するデバイスノードをマウントします。すべてのマウントは同じメモリ上のファイルシステムとノードのメタデータを共有します。各マウントは" +" ``nodev``、``nosuid``、``noexec`` " +"などのマウントポイントのポリシーを個別に保持します。通常のファイル、ディレクトリ、シンボリックリンク、ユーザーが作成したデバイスノードには既存の " +"VFS 権限検査が適用されます。デバイスのオープンは inode の種類と ``st_rdev`` " +"に基づいてドライバーへ振り分けられ、``nodev`` のマウントでは拒否されます。" + +msgid "设备生命周期" +msgstr "デバイスのライフサイクル" + +msgid "" +"设备注册、注销及分区变化通知 VFS worker 合并更新。首次挂载同步生成完整 设备清单。后续更新保留已有设备的 " +"``chmod``、``chown``,并尊重用户删除、 替换和占用的名称。设备移除只删除仍由内核持有的原 inode,非空目录保留。 " +"内存不足时保留已发布节点与待重试状态。最后一个公开挂载卸载后,私有 backing 继续保留,后续挂载可看到原有内容及权限。" +msgstr "" +"デバイスの登録、登録解除、パーティションの変更は VFS " +"ワーカーへ通知され、まとめて反映されます。最初のマウントでは完全なデバイス一覧を同期的に生成します。その後の更新は既存ノードの ``chmod``" +" や ``chown`` を保持し、ユーザーによる名前の削除、置換、使用を尊重します。デバイスの削除ではカーネルが保持する元の inode " +"のみを削除し、空でないディレクトリは残します。メモリ不足時は公開済みノードを残し、更新を再試行待ちにします。最後の公開マウントを解除した後も内部のファイルシステムは存続し、再マウント時には元の内容と権限が見えます。" + +msgid "" +"设备默认归 root,权限为 ``0600``。``null``、``zero``、``full``、``random``、 " +"``urandom``、``tty`` 和 ``ptmx`` 为 ``0666``。``fd``、``stdin``、``stdout``、 " +"``stderr`` 使用指向 ``/proc/self/fd`` 及对应描述符的符号链接。 ``pts`` 和 ``shm`` " +"提供独立文件系统的挂载目录。" +msgstr "" +"デバイスの既定の所有者は root、権限は ``0600`` " +"です。``null``、``zero``、``full``、``random``、``urandom``、``tty``、``ptmx`` は " +"``0666`` です。``fd``、``stdin``、``stdout``、``stderr`` は ``/proc/self/fd`` " +"と対応するディスクリプタへのシンボリックリンクです。``pts`` と ``shm`` は個別のファイルシステムのマウントポイントです。" + +msgid "devtmpfs 挂载选项" +msgstr "devtmpfs のマウントオプション" + +msgid "" +"挂载数据使用 tmpfs 的 ``mode``、``uid``、``gid``、``size``、``nr_blocks`` 和 " +"``nr_inodes`` 语法。私有 backing 初始为 ``mode=0755,size=0,nr_inodes=0``。 " +"重新配置先验证整个选项集,再原子提交容量和超级块策略。``mode``、``uid``、 ``gid`` 只在首次创建 tmpfs 时设置根 " +"inode。已有无限容量的实例拒绝追溯增加 容量上限,已有内容也必须容纳在新上限内,与 Linux shmem 的重新配置约束一致。" +msgstr "" +"マウントデータは tmpfs の " +"``mode``、``uid``、``gid``、``size``、``nr_blocks``、``nr_inodes`` " +"の構文を使います。内部のファイルシステムの初期設定は ``mode=0755,size=0,nr_inodes=0`` " +"です。再設定ではすべてのオプションを検証した後、容量とスーパーブロックのポリシーを一括で反映します。``mode``、``uid``、``gid``" +" がルート inode を設定するのは tmpfs " +"の初回作成時のみです。既存の無制限インスタンスに後から上限を設けることはできず、既存の内容は新しい上限内に収まる必要があります。これは Linux" +" shmem の再設定時の制約と同じです。" + +msgid "devpts" +msgstr "devpts" + +msgid "" +"``mount(\"devpts\", target, \"devpts\", flags, data)`` 每次创建独立实例,通常挂在 " +"``/dev/pts``。每个实例有自己的 ``st_dev``、``ptmx`` 和从 0 开始的从端编号; " +"绑定挂载保留原实例。``statfs`` 报告 ``0x1cd1``,``/proc/filesystems`` 将其列为 ``nodev`` " +"文件系统。打开 ``ptmx`` 后,``TIOCGPTN`` 返回本实例的编号; ``TIOCSPTLCK`` 解锁后才能打开对应从端。" +msgstr "" +"``mount(\"devpts\", target, \"devpts\", flags, data)`` " +"はマウントごとに独立したインスタンスを作ります。通常は ``/dev/pts`` にマウントします。各インスタンスには独自の " +"``st_dev``、``ptmx``、0 から始まるスレーブ番号があります。バインドマウントは元のインスタンスを維持します。``statfs``" +" は ``0x1cd1`` を返し、``/proc/filesystems`` は devpts を ``nodev`` " +"ファイルシステムとして列挙します。``ptmx`` を開いた後、``TIOCGPTN`` " +"はそのインスタンス内の番号を返します。対応するスレーブを開く前に ``TIOCSPTLCK`` でロックを解除します。" + +msgid "" +"从端报告字符设备号 ``136:<编号>``,但打开时以实际实例和 inode 身份为准,复制 " +"设备号创建的节点不会连接到该终端。``/proc//stat`` 中的控制终端设备号也 使用实例内编号;固定虚拟终端仍使用主设备号 4。" +msgstr "" +"スレーブのキャラクターデバイス番号は ``136:<番号>`` ですが、オープン時には実際のインスタンスと inode " +"の識別情報を使用します。同じデバイス番号で作成したノードはその端末には接続されません。``/proc//stat`` " +"の制御端末のデバイス番号もインスタンス内の番号を使用します。固定仮想端末のメジャー番号は引き続き 4 です。" + +msgid "devpts 挂载选项" +msgstr "devpts のマウントオプション" + +msgid "" +"``uid=``、``gid=``:新从端的十进制所有者;未指定时使用创建 PTY 的进程的 ``fsuid``、``fsgid``。根目录和 " +"``ptmx`` 归挂载者,根目录初始权限为 ``0755``。" +msgstr "" +"``uid=`` と ``gid=`` は新規スレーブの所有者 ID を 10 進数で指定します。省略時は PTY 作成プロセスの " +"``fsuid`` と ``fsgid`` が使われます。ルートディレクトリと ``ptmx`` " +"の所有者はマウントを行ったユーザーで、ルートディレクトリの初期権限は ``0755`` です。" + +msgid "" +"``mode=``、``ptmxmode=``:八进制权限,最多保留 ``07777``。默认从端为 ``0600``、``ptmx`` 为 " +"``0000``。若直接通过符号链接或绑定挂载打开 ``ptmx``, 可用 ``ptmxmode=0666`` 或相应的 ``chmod`` " +"让非特权用户访问。" +msgstr "" +"``mode=`` と ``ptmxmode=`` は 8 進数の権限を受け取り、``07777`` までのビットを保持します。既定値はスレーブが" +" ``0600``、``ptmx`` が ``0000`` です。シンボリックリンクやバインドマウント経由で ``ptmx`` " +"を直接開く場合は、``ptmxmode=0666`` または同等の ``chmod`` で非特権ユーザーにアクセスを許可できます。" + +msgid "" +"``max=``:实例内保留的 PTY 数量上限,范围为 0 到 1048576。默认不额外限制 内部 PTY 资源。达到上限时,新建返回 " +"``ENOSPC``。" +msgstr "" +"``max=`` はインスタンス内に確保できる PTY 数の上限で、0 から 1048576 まで指定できます。既定では内部 PTY " +"リソースに追加の上限を設けません。上限に達すると新規作成は ``ENOSPC`` を返します。" + +msgid "``newinstance``:兼容选项,可以省略。忽略逗号之间的空字段。" +msgstr "``newinstance`` は互換性のためのオプションで、省略できます。コンマ間の空の項目は無視されます。" + +msgid "" +"重新挂载从默认值解析选项。成功后立即更新 ``ptmx`` 权限和挂载策略;新选项 只改变以后创建的从端,不重置已有从端的权限或所有者。降低 " +"``max`` 不会强制 关闭已有会话。未通过验证的选项不会改变现有配置或挂载策略。标记 ``nodev`` 的挂载点不能用来直接打开设备。" +msgstr "" +"再マウントは既定値からオプションを解釈します。成功すると ``ptmx`` " +"の権限とマウントポリシーを直ちに更新します。新しいオプションは以降に作成するスレーブだけに適用され、既存スレーブの権限や所有者はリセットしません。``max``" +" を減らしても既存セッションは強制終了しません。検証に失敗したオプションは設定やポリシーを変更しません。``nodev`` " +"のマウントポイントからデバイスを直接開くことはできません。" + +msgid "编号与卸载" +msgstr "番号とアンマウント" + +msgid "" +"最后一个主端关闭时,从端名称被移除,仍打开的从端收到挂断通知。仍有端点引用 的会话继续占用编号和 ``max`` 配额;只剩 ``O_PATH``" +" 等元数据引用时则可以重用 公开编号。旧的从端 inode 与新会话不同:仍可读取旧 inode 的元数据(链接数为 0),尝试再次打开设备返回 " +"``EIO``。正常卸载时仍被打开的路径或端点引用会令 挂载忙(``EBUSY``);释放引用后可以卸载。" +msgstr "" +"最後のマスターを閉じるとスレーブ名が削除され、開いているスレーブにはハングアップが通知されます。端点の参照が残るセッションは番号と ``max``" +" の枠を引き続き確保します。``O_PATH`` などのメタデータ参照しか残っていない場合、公開番号は再利用できます。古いスレーブ inode " +"は新しいセッションとは別のもので、メタデータはリンク数 0 のまま参照できますが、デバイスとして再び開くと ``EIO`` " +"が返ります。パスや端点への参照が残る間は通常のアンマウントが ``EBUSY`` となり、参照を解放すると解除できます。" + +msgid "" +"打开传统字符设备 ``5:2`` 时,内核从该设备实际所在的目录查找同级 ``pts/ptmx``。找到 devpts " +"后,新会话及主端描述符属于该实例,传统设备本身的 权限决定是否可打开。找不到有效的 devpts 多路复用器时沿用启动阶段的旧 PTY " +"分配;其他查找错误则返回调用方。" +msgstr "" +"従来のキャラクターデバイス ``5:2`` を開くとき、カーネルはデバイスが実際に存在するディレクトリから同階層の ``pts/ptmx`` " +"を探します。devpts " +"が見つかれば新しいセッションとマスターのディスクリプタはそのインスタンスに属し、アクセス可否は従来のデバイスノードの権限で決まります。有効な " +"devpts マルチプレクサが見つからない場合は起動初期の PTY 割り当てを使用し、それ以外の検索エラーは呼び出し元に返します。" + +msgid "验证范围" +msgstr "検証範囲" + +msgid "" +"``tools/test_mount_backend.py`` 覆盖 devtmpfs 共享挂载、元数据、设备号、符号 " +"链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 " +"选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` 覆盖 PTY " +"ABI、会话与主端挂断行为。目标系统启动与 udev 集成由 ReliefOS 的 系统迁移验证覆盖。" +msgstr "" +"``tools/test_mount_backend.py`` は devtmpfs " +"の共有マウント、メタデータ、デバイス番号、シンボリックリンク、デバイスの追加と削除、ユーザーによる置換、マウントポリシー、メモリ不足後の再試行を検証します。devpts" +" " +"のインスタンス分離、オプション、バインドマウント、端点のライフサイクル、番号の再利用、失敗時のロールバックも検証します。``tools/test_linux_pty.py``" +" は PTY ABI、セッション、マスター側のハングアップを検証します。ゲストの起動と udev の統合は ReliefOS " +"のシステム移行検証の対象です。" From 4e5f2c1375a12bfb7a2e6e7ddccda2e593a4bacf Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sat, 28 Nov 2026 22:27:43 +0800 Subject: [PATCH 04/97] feat(cgroup): add unified hierarchy and pids controller --- .../userspace-api/device-filesystems.po | 115 +++- .../userspace-api/device-filesystems.po | 99 +++- .../userspace-api/device-filesystems.rst | 52 +- fs/Kbuild | 2 +- fs/cgroup/Kbuild | 3 + fs/cgroup/filesystem.c | 509 ++++++++++++++++++ fs/cgroup/hierarchy.c | 300 +++++++++++ fs/cgroup/internal.h | 58 ++ fs/proc/procfs.c | 26 +- fs/sysfs/sysfs.c | 3 + fs/vfs/file.c | 4 +- include/reliefnt/cgroup.h | 43 ++ include/reliefnt/sched.h | 8 +- include/reliefnt/storage.h | 2 + include/reliefnt/task/types.h | 5 + kernel/exec/userland.c | 27 +- kernel/sched/clone.c | 25 +- kernel/sched/exec.c | 6 +- kernel/sched/fair.c | 2 + kernel/sched/internal.h | 4 +- kernel/sched/task.c | 64 ++- kernel/sched/wait.c | 8 +- kernel/syscall/fs/mount.c | 4 +- kernel/syscall/fs/size.c | 4 +- kernel/syscall/io/file_io.c | 4 +- kernel/syscall/io/transfer.c | 3 +- kernel/workqueue/services.c | 4 +- tools/test_cgroup_scheduler.py | 24 + tools/test_mount_backend.py | 4 +- tools/tests/Makefile | 2 +- tools/tests/cgroup_scheduler_test.c | 213 ++++++++ tools/tests/host-suites.list | 1 + tools/tests/mount_backend_test.c | 156 +++++- 33 files changed, 1707 insertions(+), 77 deletions(-) create mode 100644 fs/cgroup/Kbuild create mode 100644 fs/cgroup/filesystem.c create mode 100644 fs/cgroup/hierarchy.c create mode 100644 fs/cgroup/internal.h create mode 100644 include/reliefnt/cgroup.h create mode 100644 tools/test_cgroup_scheduler.py create mode 100644 tools/tests/cgroup_scheduler_test.c diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index f57e9a09..3047796e 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -3,7 +3,7 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2026-11-28 00:00+0000\n" +"POT-Creation-Date: 2026-11-28 22:24+0800\n" "PO-Revision-Date: 2026-11-28 00:00+0000\n" "Last-Translator: ReliefNT translators\n" "Language: en\n" @@ -14,8 +14,8 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.18.0\n" -msgid "设备节点、devtmpfs 与 devpts" -msgstr "Device nodes, devtmpfs and devpts" +msgid "设备与控制组文件系统" +msgstr "Device and control group filesystems" msgid "devtmpfs" msgstr "devtmpfs" @@ -185,6 +185,96 @@ msgstr "" "node. If no valid devpts multiplexer is found, the kernel uses its early-" "boot PTY allocation path. Other lookup errors are returned to the caller." +msgid "cgroup v2" +msgstr "Unified cgroup hierarchy (v2)" + +msgid "" +"``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` " +"挂载统一控制组层级。 ``/proc/filesystems`` 将其列为 ``nodev``,``statfs`` 返回 " +"``0x63677270``。 所有挂载共享同一层级和 inode 身份,包括最后一次卸载后的重新挂载;只读等挂载点 策略独立。管理员可以用 " +"``mkdir`` 创建控制组,用 ``rmdir`` 删除没有活任务和 子组的非根组。" +msgstr "" +"``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` mounts " +"the unified control group hierarchy. ``/proc/filesystems`` lists it as " +"``nodev`` and ``statfs`` reports ``0x63677270``. Mounts share a hierarchy" +" and inode identities, even after the last attachment is unmounted and " +"mounted again. Each attachment has its own policy, including read-only. " +"An administrator can create a group with ``mkdir`` and remove a non-root " +"group with no live tasks or children using ``rmdir``." + +msgid "成员与事件" +msgstr "Membership and events" + +msgid "" +"向 ``cgroup.procs`` 写入 PID 或 TID 会迁移该进程的所有活线程,不迁移子进程; 写入 0 " +"选择调用者。读取该文件列出本组的进程 ID;只读的 ``cgroup.threads`` 列出本组的线程 " +"ID。``/proc//cgroup`` 以 ``0::/路径`` 报告成员身份, 不依赖控制组层级挂载在何处。只有拥有 " +"``CAP_SYS_ADMIN`` 的用户任务能修改层级和控制值。" +msgstr "" +"Writing a PID or TID to ``cgroup.procs`` moves every live thread in that " +"process, but not its child processes. Writing 0 selects the caller. " +"Reading that file lists process IDs in the group; the read-only " +"``cgroup.threads`` lists thread IDs. ``/proc//cgroup`` reports " +"membership as ``0::/path`` regardless of where the hierarchy is mounted. " +"Only user tasks with ``CAP_SYS_ADMIN`` can modify the hierarchy and its " +"controls." + +msgid "" +"非根组的 ``cgroup.events`` 中,``populated`` 表示本组或后代是否仍有活线程, 不包含僵尸。其变化与 " +"``pids.events``、``pids.events.local`` 的变化由 VFS worker 合并后发出 inotify " +"``IN_MODIFY``。被删除的组或已停用的控制器文件不再接受读写; 保留的 inode " +"不会指向后来创建的同名组或文件。仍保留成员引用的僵尸显示 `` (deleted)`` 后缀。" +msgstr "" +"The ``populated`` field in a non-root group’s ``cgroup.events`` reports " +"live threads in the group or its descendants, excluding zombies. The VFS " +"worker coalesces changes to this field and the ``pids.events`` and " +"``pids.events.local`` counters before emitting inotify ``IN_MODIFY``. " +"Retired group and controller files no longer accept reads or writes. A " +"retained inode never resolves to a new group or file with the same name. " +"Zombies retaining membership in a removed group show a `` (deleted)`` " +"suffix." + +msgid "PID 配额" +msgstr "PID limits" + +msgid "" +"``pids`` 是唯一支持的控制器。向 ``cgroup.subtree_control`` 写 ``+pids``, 可为直接子组启用 " +"``pids.max``、``pids.current``、``pids.peak`` 和事件计数。 " +"非根组必须先从父组继承控制器,才能向下启用。已经向下启用的控制器须从下往上停用。 ``pids.max`` 默认为 " +"``max``。降低上限或迁移线程可以使计数超过上限;以后创建的 线程若超过本组或祖先的上限,则返回 ``EAGAIN``。" +msgstr "" +"``pids`` is the only supported controller. Writing ``+pids`` to " +"``cgroup.subtree_control`` enables ``pids.max``, ``pids.current``, " +"``pids.peak`` and the event counters for direct children. A non-root " +"group can enable it only after receiving it from its parent. Disable an " +"enabled controller from the bottom up. ``pids.max`` defaults to ``max``. " +"Lowering a limit or migrating threads can put a group over its limit; " +"subsequent thread creation returns ``EAGAIN`` if it would exceed the " +"group’s limit or an ancestor’s limit." + +msgid "" +"配额按照线程计数,且只在创建成功时计入。普通线程退出后释放其配额;可等待的 僵尸仍计入 ``pids.current``,直至实际回收。带 " +"``WNOWAIT`` 的等待不回收配额。 ``pids.events.local`` 记录本组触发的拒绝,``pids.events`` " +"还累计后代的拒绝。" +msgstr "" +"Each thread is charged only after successful creation. Non-waitable " +"threads release the charge on exit; waitable zombies remain in " +"``pids.current`` until reaped. A wait with ``WNOWAIT`` does not release " +"the charge. ``pids.events.local`` records denials triggered by the " +"group’s own limit, and ``pids.events`` also includes denials triggered in" +" descendants." + +msgid "" +"不支持 cgroup v1、threaded 模式、cgroup namespace、非特权委托或其他控制器。 " +"``nsdelegate``、``memory_recursiveprot`` 只接受为兼容性挂载参数,不启用相应功能。 通知仅支持 " +"inotify,不支持通过 ``POLLPRI`` 订阅状态变化。" +msgstr "" +"cgroup v1, threaded mode, cgroup namespaces, unprivileged delegation and " +"other controllers are not supported. ``nsdelegate`` and " +"``memory_recursiveprot`` are accepted only as compatibility mount " +"options; they do not enable those features. Notifications use inotify; " +"state changes are not available through ``POLLPRI``." + msgid "验证范围" msgstr "Validation scope" @@ -192,13 +282,16 @@ msgid "" "``tools/test_mount_backend.py`` 覆盖 devtmpfs 共享挂载、元数据、设备号、符号 " "链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 " "选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` 覆盖 PTY " -"ABI、会话与主端挂断行为。目标系统启动与 udev 集成由 ReliefOS 的 系统迁移验证覆盖。" +"ABI、会话与主端挂断行为。控制组挂载、文件语义及 inotify 也由 ``tools/test_mount_backend.py`` " +"覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 调度器的配额拒绝、创建回滚、退出及回收。来宾启动、udev " +"和 systemd 集成需要 另行验证。" msgstr "" "``tools/test_mount_backend.py`` checks shared devtmpfs mounts, metadata, " -"device numbers, symlinks, device addition and removal, user replacements," -" mount policies, and retry after allocation failure. It also checks " -"devpts instance isolation, mount options, bind mounts, endpoint " -"lifecycles, number reuse, and failure rollback. " -"``tools/test_linux_pty.py`` checks the PTY ABI, sessions, and master " -"hangup behavior. Guest boot and udev integration are covered by the " -"ReliefOS system migration validation." +"device numbers, symlinks, device lifecycle, user replacements, mount " +"policy and retry after allocation failure. It also checks devpts " +"isolation, options, bind mounts, endpoint lifetime, number reuse and " +"rollback. ``tools/test_linux_pty.py`` checks the PTY ABI, sessions and " +"master hangup. The mount backend suite covers cgroup mounts, control " +"files and inotify. ``tools/test_cgroup_scheduler.py`` exercises quota " +"denials, creation rollback, exit and reap through the real scheduler. " +"Guest boot, udev and systemd integration require separate validation." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index 3e46b692..d7b9c8af 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -3,7 +3,7 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2026-11-28 00:00+0000\n" +"POT-Creation-Date: 2026-11-28 22:24+0800\n" "PO-Revision-Date: 2026-11-28 00:00+0000\n" "Last-Translator: ReliefNT translators\n" "Language: ja\n" @@ -14,8 +14,8 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.18.0\n" -msgid "设备节点、devtmpfs 与 devpts" -msgstr "デバイスノード、devtmpfs と devpts" +msgid "设备与控制组文件系统" +msgstr "デバイスとコントロールグループのファイルシステム" msgid "devtmpfs" msgstr "devtmpfs" @@ -160,6 +160,84 @@ msgstr "" "が見つかれば新しいセッションとマスターのディスクリプタはそのインスタンスに属し、アクセス可否は従来のデバイスノードの権限で決まります。有効な " "devpts マルチプレクサが見つからない場合は起動初期の PTY 割り当てを使用し、それ以外の検索エラーは呼び出し元に返します。" +msgid "cgroup v2" +msgstr "統合 cgroup 階層(v2)" + +msgid "" +"``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` " +"挂载统一控制组层级。 ``/proc/filesystems`` 将其列为 ``nodev``,``statfs`` 返回 " +"``0x63677270``。 所有挂载共享同一层级和 inode 身份,包括最后一次卸载后的重新挂载;只读等挂载点 策略独立。管理员可以用 " +"``mkdir`` 创建控制组,用 ``rmdir`` 删除没有活任务和 子组的非根组。" +msgstr "" +"``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` " +"は統合コントロールグループ階層をマウントします。``/proc/filesystems`` には ``nodev`` " +"と表示され、``statfs`` は ``0x63677270`` を返します。すべてのマウントは階層と inode " +"の識別情報を共有し、最後のマウントを解除しても再マウント時に同じ階層が見えます。読み取り専用などのポリシーはマウントごとに独立しています。管理者は" +" ``mkdir`` でグループを作成し、稼働中のタスクや子グループのない非ルートグループを ``rmdir`` で削除できます。" + +msgid "成员与事件" +msgstr "所属とイベント" + +msgid "" +"向 ``cgroup.procs`` 写入 PID 或 TID 会迁移该进程的所有活线程,不迁移子进程; 写入 0 " +"选择调用者。读取该文件列出本组的进程 ID;只读的 ``cgroup.threads`` 列出本组的线程 " +"ID。``/proc//cgroup`` 以 ``0::/路径`` 报告成员身份, 不依赖控制组层级挂载在何处。只有拥有 " +"``CAP_SYS_ADMIN`` 的用户任务能修改层级和控制值。" +msgstr "" +"``cgroup.procs`` に PID または TID " +"を書き込むと、そのプロセスの稼働中の全スレッドが移動します。子プロセスは移動しません。0 " +"を書き込むと呼び出し元を選択します。このファイルを読むとグループ内の PID が、読み取り専用の ``cgroup.threads`` を読むと " +"TID が列挙されます。``/proc//cgroup`` はマウント位置にかかわらず ``0::/パス`` " +"形式で所属を示します。階層と制御値を変更できるユーザータスクには ``CAP_SYS_ADMIN`` が必要です。" + +msgid "" +"非根组的 ``cgroup.events`` 中,``populated`` 表示本组或后代是否仍有活线程, 不包含僵尸。其变化与 " +"``pids.events``、``pids.events.local`` 的变化由 VFS worker 合并后发出 inotify " +"``IN_MODIFY``。被删除的组或已停用的控制器文件不再接受读写; 保留的 inode " +"不会指向后来创建的同名组或文件。仍保留成员引用的僵尸显示 `` (deleted)`` 后缀。" +msgstr "" +"非ルートグループの ``cgroup.events`` の ``populated`` " +"は、そのグループや子孫に稼働中のスレッドがあるかを示します。ゾンビは含みません。この値と " +"``pids.events``、``pids.events.local`` の変更は VFS ワーカーでまとめられ、inotify の " +"``IN_MODIFY`` として通知されます。削除されたグループや無効化されたコントローラーのファイルは読み書きできません。保持された " +"inode が同名のグループやファイルを参照することはありません。削除済みのグループへの参照を保持するゾンビには `` (deleted)`` " +"が付きます。" + +msgid "PID 配额" +msgstr "PID の上限" + +msgid "" +"``pids`` 是唯一支持的控制器。向 ``cgroup.subtree_control`` 写 ``+pids``, 可为直接子组启用 " +"``pids.max``、``pids.current``、``pids.peak`` 和事件计数。 " +"非根组必须先从父组继承控制器,才能向下启用。已经向下启用的控制器须从下往上停用。 ``pids.max`` 默认为 " +"``max``。降低上限或迁移线程可以使计数超过上限;以后创建的 线程若超过本组或祖先的上限,则返回 ``EAGAIN``。" +msgstr "" +"対応するコントローラーは ``pids`` のみです。``cgroup.subtree_control`` に ``+pids`` " +"を書き込むと、直接の子グループで ``pids.max``、``pids.current``、``pids.peak`` " +"とイベントカウンターが有効になります。非ルートグループでは、親からコントローラーを継承してから子に対して有効にできます。無効化は下位のグループから行います。``pids.max``" +" の既定値は ``max`` " +"です。上限の引き下げやスレッドの移動で上限を超える場合があります。それ以降、所属グループまたは祖先の上限を超えるスレッドの作成は " +"``EAGAIN`` を返します。" + +msgid "" +"配额按照线程计数,且只在创建成功时计入。普通线程退出后释放其配额;可等待的 僵尸仍计入 ``pids.current``,直至实际回收。带 " +"``WNOWAIT`` 的等待不回收配额。 ``pids.events.local`` 记录本组触发的拒绝,``pids.events`` " +"还累计后代的拒绝。" +msgstr "" +"スレッドの作成に成功したときだけ使用数に加算されます。待機対象でないスレッドは終了時に使用数から除かれます。待機対象のゾンビは回収されるまで " +"``pids.current`` に含まれ、``WNOWAIT`` では使用数が減りません。``pids.events.local`` " +"はそのグループの上限による拒否を記録し、``pids.events`` は子孫の上限による拒否も集計します。" + +msgid "" +"不支持 cgroup v1、threaded 模式、cgroup namespace、非特权委托或其他控制器。 " +"``nsdelegate``、``memory_recursiveprot`` 只接受为兼容性挂载参数,不启用相应功能。 通知仅支持 " +"inotify,不支持通过 ``POLLPRI`` 订阅状态变化。" +msgstr "" +"cgroup v1、スレッドモード、cgroup " +"名前空間、非特権ユーザーへの委譲、および他のコントローラーには対応していません。``nsdelegate`` と " +"``memory_recursiveprot`` は互換性のためにマウントオプションとして受理されますが、機能は有効になりません。状態変更は " +"inotify で通知されます。``POLLPRI`` による通知には対応していません。" + msgid "验证范围" msgstr "検証範囲" @@ -167,11 +245,14 @@ msgid "" "``tools/test_mount_backend.py`` 覆盖 devtmpfs 共享挂载、元数据、设备号、符号 " "链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 " "选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` 覆盖 PTY " -"ABI、会话与主端挂断行为。目标系统启动与 udev 集成由 ReliefOS 的 系统迁移验证覆盖。" +"ABI、会话与主端挂断行为。控制组挂载、文件语义及 inotify 也由 ``tools/test_mount_backend.py`` " +"覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 调度器的配额拒绝、创建回滚、退出及回收。来宾启动、udev " +"和 systemd 集成需要 另行验证。" msgstr "" "``tools/test_mount_backend.py`` は devtmpfs " -"の共有マウント、メタデータ、デバイス番号、シンボリックリンク、デバイスの追加と削除、ユーザーによる置換、マウントポリシー、メモリ不足後の再試行を検証します。devpts" -" " -"のインスタンス分離、オプション、バインドマウント、端点のライフサイクル、番号の再利用、失敗時のロールバックも検証します。``tools/test_linux_pty.py``" -" は PTY ABI、セッション、マスター側のハングアップを検証します。ゲストの起動と udev の統合は ReliefOS " -"のシステム移行検証の対象です。" +"の共有マウント、メタデータ、デバイス番号、シンボリックリンク、デバイスの追加と削除、ユーザーによる置き換え、マウントポリシー、割り当て失敗後の再試行を確認します。また、devpts" +" の分離、オプション、バインド、端点の寿命、番号の再利用とロールバックも確認します。``tools/test_linux_pty.py`` は " +"PTY ABI、セッションとマスターの切断を確認します。マウントのテストは cgroup の制御ファイルと inotify " +"も対象とします。``tools/test_cgroup_scheduler.py`` " +"は実際のスケジューラーで上限による拒否、作成失敗時のロールバック、終了と回収を確認します。ゲストの起動、udev、systemd " +"の統合は別途検証が必要です。" diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 3fc50c9c..8e6a8bbf 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -1,6 +1,6 @@ -============================ -设备节点、devtmpfs 与 devpts -============================ +==================== +设备与控制组文件系统 +==================== devtmpfs ======== @@ -78,11 +78,53 @@ devpts 挂载选项 权限决定是否可打开。找不到有效的 devpts 多路复用器时沿用启动阶段的旧 PTY 分配;其他查找错误则返回调用方。 +cgroup v2 +========= + +``mount("none", "/sys/fs/cgroup", "cgroup2", flags, data)`` 挂载统一控制组层级。 +``/proc/filesystems`` 将其列为 ``nodev``,``statfs`` 返回 ``0x63677270``。 +所有挂载共享同一层级和 inode 身份,包括最后一次卸载后的重新挂载;只读等挂载点 +策略独立。管理员可以用 ``mkdir`` 创建控制组,用 ``rmdir`` 删除没有活任务和 +子组的非根组。 + +成员与事件 +---------- + +向 ``cgroup.procs`` 写入 PID 或 TID 会迁移该进程的所有活线程,不迁移子进程; +写入 0 选择调用者。读取该文件列出本组的进程 ID;只读的 ``cgroup.threads`` +列出本组的线程 ID。``/proc//cgroup`` 以 ``0::/路径`` 报告成员身份, +不依赖控制组层级挂载在何处。只有拥有 ``CAP_SYS_ADMIN`` 的用户任务能修改层级和控制值。 + +非根组的 ``cgroup.events`` 中,``populated`` 表示本组或后代是否仍有活线程, +不包含僵尸。其变化与 ``pids.events``、``pids.events.local`` 的变化由 VFS worker +合并后发出 inotify ``IN_MODIFY``。被删除的组或已停用的控制器文件不再接受读写; +保留的 inode 不会指向后来创建的同名组或文件。仍保留成员引用的僵尸显示 +`` (deleted)`` 后缀。 + +PID 配额 +-------- + +``pids`` 是唯一支持的控制器。向 ``cgroup.subtree_control`` 写 ``+pids``, +可为直接子组启用 ``pids.max``、``pids.current``、``pids.peak`` 和事件计数。 +非根组必须先从父组继承控制器,才能向下启用。已经向下启用的控制器须从下往上停用。 +``pids.max`` 默认为 ``max``。降低上限或迁移线程可以使计数超过上限;以后创建的 +线程若超过本组或祖先的上限,则返回 ``EAGAIN``。 + +配额按照线程计数,且只在创建成功时计入。普通线程退出后释放其配额;可等待的 +僵尸仍计入 ``pids.current``,直至实际回收。带 ``WNOWAIT`` 的等待不回收配额。 +``pids.events.local`` 记录本组触发的拒绝,``pids.events`` 还累计后代的拒绝。 + +不支持 cgroup v1、threaded 模式、cgroup namespace、非特权委托或其他控制器。 +``nsdelegate``、``memory_recursiveprot`` 只接受为兼容性挂载参数,不启用相应功能。 +通知仅支持 inotify,不支持通过 ``POLLPRI`` 订阅状态变化。 + 验证范围 ======== ``tools/test_mount_backend.py`` 覆盖 devtmpfs 共享挂载、元数据、设备号、符号 链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` -覆盖 PTY ABI、会话与主端挂断行为。目标系统启动与 udev 集成由 ReliefOS 的 -系统迁移验证覆盖。 +覆盖 PTY ABI、会话与主端挂断行为。控制组挂载、文件语义及 inotify 也由 +``tools/test_mount_backend.py`` 覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 +调度器的配额拒绝、创建回滚、退出及回收。来宾启动、udev 和 systemd 集成需要 +另行验证。 diff --git a/fs/Kbuild b/fs/Kbuild index 56687b44..17014fc1 100644 --- a/fs/Kbuild +++ b/fs/Kbuild @@ -1,6 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 # Objects are owned by this directory; child modules own their own lists. -obj-y := initramfs/ devfs/ devpts/ proc/ security/ sysfs/ tmpfs/ vfs/ notify/ +obj-y := initramfs/ cgroup/ devfs/ devpts/ proc/ security/ sysfs/ tmpfs/ vfs/ notify/ obj-$(CONFIG_EXT_FS_COMMON) += ext_common/ obj-$(CONFIG_EXT2_FS) += ext2/ obj-$(CONFIG_EXT3_FS) += ext3/ diff --git a/fs/cgroup/Kbuild b/fs/cgroup/Kbuild new file mode 100644 index 00000000..75fab244 --- /dev/null +++ b/fs/cgroup/Kbuild @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: Apache-2.0 +obj-y := hierarchy.o filesystem.o +include $(srctree)/scripts/Makefile.module diff --git a/fs/cgroup/filesystem.c b/fs/cgroup/filesystem.c new file mode 100644 index 00000000..488c3cf3 --- /dev/null +++ b/fs/cgroup/filesystem.c @@ -0,0 +1,509 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "internal.h" +#include +#include +#include +#include +#include +#include +#include + +#define CGROUP_FILE_SHIFT 4u +#define CGROUP_COMMAND_MAX 4095u +_Static_assert(CG_FILE_COUNT <= (1u << CGROUP_FILE_SHIFT), "cgroup inode file bits"); + +static const struct vfs_backend_ops cgroup_ops; +static const struct cgroup_control { + const char *name; + bool writable; +} controls[CG_FILE_COUNT] = { + [CG_PROCS] = {"cgroup.procs", true}, [CG_THREADS] = {"cgroup.threads", false}, + [CG_CONTROLLERS] = {"cgroup.controllers", false}, [CG_SUBTREE] = {"cgroup.subtree_control", true}, + [CG_TYPE] = {"cgroup.type", false}, [CG_EVENTS] = {"cgroup.events", false}, + [CG_STAT] = {"cgroup.stat", false}, [CG_PIDS_MAX] = {"pids.max", true}, + [CG_PIDS_CURRENT] = {"pids.current", false}, [CG_PIDS_PEAK] = {"pids.peak", false}, + [CG_PIDS_EVENTS] = {"pids.events", false}, [CG_PIDS_LOCAL] = {"pids.events.local", false}, +}; + +/** @brief Encode group, file and controller incarnation into a stable inode key. */ +struct storage_node cgroup_node(const struct cgroup *g, enum cgroup_file file, uint32_t epoch) +{ + return (struct storage_node){.type = file == CG_DIR ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_FILE, + .flags = STORAGE_NODE_FLAG_CGROUP, .first_cluster = g->id, + .entry_id = ((uint64_t)g->id << 32) | (file >= CG_PIDS_MAX ? epoch << CGROUP_FILE_SHIFT : 0) | file}; +} + +/** @brief Publish an event on the shared hierarchy, or retire an unlinked inode's watch. */ +void cgroup_notify(const struct storage_node *node, bool removed) +{ + struct fsnotify_key key = {.ops = &cgroup_ops, .context = &cgroup_root, .node = *node}; + if (removed) fsnotify_delete(&key); + else fsnotify_emit(&key, IN_MODIFY, 0, NULL, false); +} + +/** @brief Map a canonical inode number to its file selector. */ +static enum cgroup_file node_file(const struct storage_node *node) +{ return node->entry_id & ((1u << CGROUP_FILE_SHIFT) - 1u); } + +/** @brief Test visibility under execution ownership (remote exits do not change it). */ +static bool file_visible(const struct cgroup *g, enum cgroup_file file) +{ + if (!g->linked || file >= CG_FILE_COUNT) return false; + if (file >= CG_PIDS_MAX) return cgroup_pids_enabled(g); + return g->parent || (file != CG_TYPE && file != CG_EVENTS); +} + +/** @brief Match a visible inode, never a recreated directory or controller generation. */ +static bool node_live(const struct cgroup *g, const struct storage_node *node) +{ + enum cgroup_file file = node_file(node); + return g && file_visible(g, file) && + node->entry_id == cgroup_node(g, file, g->parent ? g->parent->pids_epoch : 0).entry_id; +} + +/** @brief Look up one live directory or control file with no text-path replay. */ +static int cgroup_lookup(void *context, const struct storage_node *parent, const char *name, + struct storage_node *out) +{ + (void)context; + struct cgroup *g = cgroup_find(parent->first_cluster); + if (!node_live(g, parent)) return -ENOENT; + if (node_file(parent) != CG_DIR) return -ENOTDIR; + for (enum cgroup_file file = CG_PROCS; file < CG_FILE_COUNT; ++file) { + if (!file_visible(g, file) || __builtin_strcmp(controls[file].name, name)) continue; + *out = cgroup_node(g, file, g->parent ? g->parent->pids_epoch : 0); + return 0; + } + for (struct cgroup *child = g->children; child; child = child->sibling) { + if (__builtin_strcmp(child->name, name)) continue; + *out = cgroup_node(child, CG_DIR, 0); + return 0; + } + return -ENOENT; +} + +/** @brief Pin the actual group for one dentry or control file. */ +static int cgroup_retain(void *context, const struct storage_node *node, void **pin) +{ + (void)context; + *pin = NULL; + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENOENT; + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + cgroup_get_locked(g); + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + *pin = g; + return 0; +} + +/** @brief Release the inode pin independently of its current name and visibility. */ +static void cgroup_release(void *context, const struct storage_node *node, void *pin) +{ + (void)context; (void)node; + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + cgroup_put_locked(pin); + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + cgroup2_kick(); +} + +/** @brief Compare immutable keys; watches also use this after namespace removal. */ +static bool cgroup_same(void *context, const struct storage_node *a, const struct storage_node *b) +{ (void)context; return a->entry_id == b->entry_id; } + +/** @brief Restrict hierarchy changes to a system administrator (no delegation). */ +static bool cgroup_admin(void) +{ + const struct task *task = sched_current_task(); + return !task || task->kind == TASK_KIND_KERNEL || (task->cap_effective & (1ULL << CAP_SYS_ADMIN)); +} + +/** @brief Return directory or control metadata for a retained inode key. */ +static struct reliefos_permissions cgroup_mode(const struct cgroup *g, enum cgroup_file file) +{ + if (file == CG_DIR) return g->mode; + return (struct reliefos_permissions){controls[file].writable ? 0644u : 0444u, g->mode.uid, g->mode.gid}; +} + +/** @brief Expose DAC metadata and allow only privileged directory attribute changes. */ +static int cgroup_permissions(void *context, const struct vfs_path *path, + struct reliefos_permissions *value, bool write) +{ + (void)context; + const struct storage_node *node = vfs_path_node(path); + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENODEV; + enum cgroup_file file = node_file(node); + if (!write) { *value = cgroup_mode(g, file); return 0; } + if (vfs_path_mount_flags(path) & MS_RDONLY) return -EROFS; + if (file != CG_DIR || !cgroup_admin()) return -EPERM; + g->mode = (struct reliefos_permissions){value->mode & 0777u, value->uid, value->gid}; + return 0; +} + +/** @brief Report shared device identity and zero links for retired inode incarnations. */ +static int cgroup_stat(void *context, const struct vfs_path *path, struct linux_stat_abi *out) +{ + (void)context; + const struct storage_node *node = vfs_path_node(path); + const struct cgroup *g = cgroup_find(node->first_cluster); + enum cgroup_file file = node_file(node); + if (!g || file >= CG_FILE_COUNT) return -ENOENT; + struct reliefos_permissions mode = cgroup_mode(g, file); + uint64_t links = 0; + if (node_live(g, node)) { + links = file == CG_DIR ? 2 : 1; + if (file == CG_DIR) for (const struct cgroup *child = g->children; child; child = child->sibling) ++links; + } + *out = (struct linux_stat_abi){.st_dev = CGROUP_DEVICE, .st_ino = node->entry_id, .st_nlink = links, + .st_mode = (file == CG_DIR ? LINUX_S_IFDIR : LINUX_S_IFREG) | mode.mode, + .st_uid = mode.uid, .st_gid = mode.gid, .st_blksize = 4096}; + return 0; +} + +/** @brief Return Linux cgroup2 magic and the shared device's filesystem ID. */ +static int cgroup_statfs(void *context, const struct storage_node *node, struct linux_statfs_abi *out) +{ + (void)context; (void)node; + *out = (struct linux_statfs_abi){.f_type = CGROUP_MAGIC, .f_bsize = 4096, .f_frsize = 4096, + .f_namelen = VFS_NAME_MAX, .f_fsid = {CGROUP_DEVICE, 0}}; + return 0; +} + +/** @brief Publish only directories, reserving the control names even when disabled. */ +static int cgroup_create(void *context, const struct storage_node *parent, const char *name, uint32_t type, + const struct reliefos_permissions *mode, const char *target, + struct storage_node *out, void **pin) +{ + (void)context; (void)target; + if (type != LINUX_S_IFDIR || !cgroup_admin()) return -EPERM; + for (enum cgroup_file file = CG_PROCS; file < CG_FILE_COUNT; ++file) + if (!__builtin_strcmp(controls[file].name, name)) return -EEXIST; + struct cgroup *g = NULL; + int rc = cgroup_mkdir(cgroup_find(parent->first_cluster), name, mode, &g); + if (rc) return rc; + *out = cgroup_node(g, CG_DIR, 0); + return pin ? cgroup_retain(context, out, pin) : 0; +} + +/** @brief Retire the weak watches of every file in a removed controller incarnation. */ +static void cgroup_remove_files(const struct cgroup *g, enum cgroup_file first, uint32_t epoch) +{ + if (!fsnotify_has_watches()) return; + for (enum cgroup_file file = first; file < CG_FILE_COUNT; ++file) { + struct storage_node key = cgroup_node(g, file, epoch); + cgroup_notify(&key, true); + } +} + +/** @brief Remove an empty group and retire its control and directory watch keys. */ +static int cgroup_remove(void *context, const struct vfs_path *path, bool directory) +{ + (void)context; + if (!directory || !cgroup_admin()) return -EPERM; + struct cgroup *g = cgroup_find(vfs_path_node(path)->first_cluster); + if (!g) return -ENOENT; + int rc = cgroup_rmdir(g); + if (!rc) cgroup_remove_files(g, CG_DIR, g->parent->pids_epoch); + return rc; +} + +/** @brief Enumerate dot entries, visible files and subgroups with monotonic directory cookies. */ +static int cgroup_dir_next(const struct storage_node *node, uint64_t *cursor, + char *name, size_t capacity, uint32_t *type) +{ + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENOENT; + uint64_t next = *cursor; + const char *text = NULL; + *type = RELIEFOS_FS_TYPE_DIR; + if (next < 2) text = next++ ? ".." : "."; + else { + while (next < CG_FILE_COUNT + 1u) { + enum cgroup_file file = (enum cgroup_file)(next++ - 1); + if (!file_visible(g, file)) continue; + text = controls[file].name; + *type = RELIEFOS_FS_TYPE_FILE; + break; + } + if (!text) { + const struct cgroup *first = NULL; + for (const struct cgroup *child = g->children; child; child = child->sibling) + if ((uint64_t)child->id + CG_FILE_COUNT >= next && (!first || child->id < first->id)) first = child; + if (!first) return 0; + text = first->name; + next = (uint64_t)first->id + CG_FILE_COUNT + 1u; + } + } + size_t length = __builtin_strlen(text) + 1u; + if (length > capacity) return -ENAMETOOLONG; + __builtin_memcpy(name, text, length); + *cursor = next; + return 1; +} + +/** @brief Export the legacy directory record without truncating its identity. */ +static int cgroup_readdir(void *context, const struct storage_node *node, uint64_t *cursor, + struct reliefos_dir_entry *entry, uint64_t flags) +{ + (void)context; (void)flags; + return cgroup_dir_next(node, cursor, entry->name, sizeof(entry->name), &entry->type); +} + +/** @brief Export a Linux getdents name up to NAME_MAX. */ +static int cgroup_readdir_name(void *context, const struct storage_node *node, uint64_t *cursor, + char *name, size_t capacity, uint64_t flags) +{ + (void)context; (void)flags; + uint32_t type; + return cgroup_dir_next(node, cursor, name, capacity, &type); +} + +/** @brief Partition integer IDs in place by descending bit without allocating a second list. */ +static void sort_ids(uint32_t *ids, size_t count, uint32_t bit) +{ + if (count < 2 || !bit) return; + size_t first = 0, last = count; + while (first < last) { + if (!(ids[first] & bit)) ++first; + else { + uint32_t temp = ids[first]; + ids[first] = ids[--last]; + ids[last] = temp; + } + } + sort_ids(ids, first, bit >> 1); + sort_ids(ids + first, count - first, bit >> 1); +} + +/** @brief Match one live thread, treating an uncharged membership as the root. */ +static bool cgroup_matches(const struct cgroup *g, const struct task *task) +{ + return cgroup_live_task(task) && (task->cgroup ? task->cgroup : &cgroup_root) == g; +} + +/** @brief Snapshot matching live IDs under the task lock; format and deduplicate outside it. */ +static int cgroup_read_members(const struct cgroup *g, bool threads, struct text_stream *text) +{ + if (!text->capacity) return 0; + uint64_t flags; + size_t capacity = 0; + const struct task *task; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + for (uint32_t i = 0; (task = sched_task_at(i)); ++i) + if (cgroup_matches(g, task)) ++capacity; + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + if (!capacity) return 0; + if (capacity > SIZE_MAX / sizeof(uint32_t)) return -ENOMEM; + uint32_t *ids = kernel_malloc(capacity * sizeof(*ids)); + if (!ids) return -ENOMEM; + size_t count = 0; + /* The execution writer serializes admissions and moves; a remote exit can + * only reduce the number of live members between the count and snapshot. */ + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + for (uint32_t i = 0; count < capacity; ++i) { + const struct task *task = sched_task_at(i); + if (!task) break; + if (cgroup_matches(g, task)) + ids[count++] = threads ? task->pid : sched_task_tgid(task); + } + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + if (!threads) sort_ids(ids, count, 1u << 31); + for (size_t i = 0; i < count && text->written < text->capacity; ++i) { + if (threads || !i || ids[i] != ids[i-1]) { + text_unsigned(text, ids[i]); + text_string(text, "\n"); + } + } + kernel_free(ids); + return 0; +} + +/** @brief Render the stable Linux control names and a locked counter snapshot. */ +static int cgroup_read(void *context, const struct storage_node *node, uint64_t offset, + void *buffer, uint32_t capacity, uint32_t *read, uint64_t mount_flags) +{ + (void)context; (void)mount_flags; + *read = 0; + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENODEV; + struct text_stream text = {.offset = offset, .buffer = buffer, .capacity = capacity}; + enum cgroup_file file = node_file(node); + if (file == CG_PROCS || file == CG_THREADS) { + int rc = cgroup_read_members(g, file == CG_THREADS, &text); + *read = text.written; + return rc; + } + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + switch (file) { + case CG_TYPE: text_string(&text, "domain\n"); break; + case CG_CONTROLLERS: + if (!g->parent || cgroup_pids_enabled(g)) text_string(&text, "pids\n"); + break; + case CG_SUBTREE: + if (g->subtree_pids) text_string(&text, "pids\n"); + break; + case CG_EVENTS: text_string(&text, g->live ? "populated 1\nfrozen 0\n" : "populated 0\nfrozen 0\n"); break; + case CG_STAT: + text_string(&text, "nr_descendants "); text_unsigned(&text, g->descendants); + text_string(&text, "\nnr_dying_descendants "); text_unsigned(&text, g->dying); + text_string(&text, "\n"); break; + case CG_PIDS_MAX: + if (g->limit == CGROUP_PIDS_UNLIMITED) text_string(&text, "max"); + else text_unsigned(&text, g->limit); + text_string(&text, "\n"); break; + case CG_PIDS_CURRENT: case CG_PIDS_PEAK: case CG_PIDS_EVENTS: case CG_PIDS_LOCAL: + if (file >= CG_PIDS_EVENTS) text_string(&text, "max "); + text_unsigned(&text, file == CG_PIDS_CURRENT ? g->charged : file == CG_PIDS_PEAK ? g->peak : + file == CG_PIDS_EVENTS ? g->events : g->local_events); + text_string(&text, "\n"); break; + default: kernel_spin_unlock_irqrestore(&scheduler_lock, flags); return -EINVAL; + } + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + *read = text.written; + return 0; +} + +/** @brief Recognize ASCII whitespace in a userspace control write. */ +static bool command_space(char c) +{ return c == ' ' || (c >= '\t' && c <= '\r'); } + +/** @brief Parse a complete unsigned base-0 integer with a bounded target range. */ +static int command_number(const char *text, size_t length, uint32_t maximum, uint32_t *out) +{ + if (length && *text == '+') { ++text; --length; } + if (!length) return -EINVAL; + unsigned base = 10; + if (length > 1 && text[0] == '0') { + if (text[1] == 'x' || text[1] == 'X') { text += 2; length -= 2; base = 16; } + else base = 8; + } + if (!length) return -EINVAL; + uint32_t value = 0; + for (size_t i = 0; i < length; ++i) { + unsigned char c = text[i]; + unsigned digit = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : + c >= 'A' && c <= 'F' ? c - 'A' + 10 : base; + if (digit >= base || value > (maximum - digit) / base) return -EINVAL; + value = value * base + digit; + } + *out = value; + return 0; +} + +/** @brief Validate every controller token before changing any child file or limit. */ +static int command_subtree(const char *text, size_t length, int *enable) +{ + *enable = -1; + for (size_t i = 0; i < length;) { + if (command_space(text[i])) { ++i; continue; } + if (length - i < 5 || (text[i] != '+' && text[i] != '-') || + __builtin_memcmp(text+i+1, "pids", 4) || + (length - i > 5 && !command_space(text[i+5]))) return -EINVAL; + *enable = text[i] == '+'; + i += 5; + } + return 0; +} + +/** @brief Apply one fully validated cgroup control write in a scheduler transaction. */ +static int cgroup_write(void *context, struct storage_node *node, uint64_t offset, + const void *bytes, uint32_t length, uint32_t *written) +{ + (void)context; (void)offset; + *written = 0; + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENODEV; + enum cgroup_file file = node_file(node); + if (file == CG_DIR || !controls[file].writable || !cgroup_admin()) return -EPERM; + if (!length) return 0; + if (length > CGROUP_COMMAND_MAX) return -E2BIG; + const char *text = bytes; + size_t count = length; + while (count && command_space(*text)) { ++text; --count; } + while (count && command_space(text[count-1])) --count; + int enable = -1, rc = 0; + uint32_t value = 0; + uint64_t limit = CGROUP_PIDS_UNLIMITED; + if (file == CG_SUBTREE) rc = command_subtree(text, count, &enable); + else if (file == CG_PROCS) rc = command_number(text, count, INT32_MAX, &value); + else if (count != 3 || __builtin_memcmp(text, "max", 3)) { + rc = command_number(text, count, CGROUP_PIDS_MAX, &value); + limit = value; + } + if (rc) return rc; + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + uint32_t retired_epoch = !enable && g->subtree_pids ? g->pids_epoch : 0; + if (file == CG_SUBTREE && enable >= 0) rc = cgroup_set_subtree_locked(g, enable); + else if (file == CG_PROCS) rc = cgroup_move_locked(g, value); + else if (file == CG_PIDS_MAX) g->limit = limit; + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + if (rc) return rc; + if (retired_epoch) + for (const struct cgroup *child = g->children; child; child = child->sibling) + cgroup_remove_files(child, CG_PIDS_MAX, retired_epoch); + cgroup2_kick(); + *written = length; + return 0; +} + +/** @brief Accept harmless O_TRUNC on writable live controls, without changing policy. */ +static int cgroup_truncate(void *context, struct storage_node *node, uint64_t length) +{ + (void)context; + if (!node_live(cgroup_find(node->first_cluster), node)) return -ENODEV; + if (!controls[node_file(node)].writable || !cgroup_admin()) return -EPERM; + return length ? -EINVAL : 0; +} + +/** @brief Validate attachment options without claiming the unimplemented controllers or delegation. */ +static int cgroup_remount(void *context, uint64_t flags, const char *options) +{ + (void)context; + if (flags & ~MS_RDONLY) return -EOPNOTSUPP; + for (const char *start = options; start && *start;) { + const char *end = start; + while (*end && *end != ',') ++end; + size_t n = (size_t)(end - start); + if (n && !(n == sizeof("nsdelegate") - 1 && !__builtin_memcmp(start, "nsdelegate", n)) && + !(n == sizeof("memory_recursiveprot") - 1 && + !__builtin_memcmp(start, "memory_recursiveprot", n))) return -EINVAL; + start = *end ? end + 1 : end; + } + return 0; +} + +/** @brief Generated controls apply synchronously; no backing data require a flush. */ +static int cgroup_sync(void *context, const struct storage_node *node, bool filesystem, bool data_only) +{ + (void)context; (void)filesystem; (void)data_only; + return node_live(cgroup_find(node->first_cluster), node) ? 0 : -ENODEV; +} + +static const struct vfs_backend_ops cgroup_ops = { + .lookup = cgroup_lookup, .retain = cgroup_retain, .release = cgroup_release, .same_node = cgroup_same, + .remount_options = cgroup_remount, .read = cgroup_read, .readdir = cgroup_readdir, + .readdir_name = cgroup_readdir_name, .permissions = cgroup_permissions, .create_node = cgroup_create, + .getattr = cgroup_stat, .statfs = cgroup_statfs, .write = cgroup_write, .truncate = cgroup_truncate, + .sync = cgroup_sync, .remove_node = cgroup_remove, +}; + +/** @brief Construct a new attachment of the permanent unified cgroup hierarchy. */ +int cgroup2_create_vfs_mount(const char *source, uint64_t flags, const char *options, struct vfs_mount **out) +{ + if (!out) return -EINVAL; + *out = NULL; + if (flags & ~(VFS_MOUNT_POLICY_MASK | MS_STRICTATIME)) return -EOPNOTSUPP; + int rc = cgroup_remount(&cgroup_root, flags & MS_RDONLY, options); + if (rc) return rc; + struct storage_node root = cgroup_node(&cgroup_root, CG_DIR, 0); + rc = vfs_mount_new(&cgroup_ops, &cgroup_root, NULL, &root, out); + if (rc) return rc; + rc = vfs_mount_set_flags(*out, flags); + if (!rc) rc = vfs_mount_describe(*out, source && *source ? source : "cgroup2", "cgroup2", CGROUP_DEVICE); + if (rc) { vfs_mount_put(*out); *out = NULL; } + return rc; +} diff --git a/fs/cgroup/hierarchy.c b/fs/cgroup/hierarchy.c new file mode 100644 index 00000000..ae51c5b4 --- /dev/null +++ b/fs/cgroup/hierarchy.c @@ -0,0 +1,300 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "internal.h" +#include +#include +#include +#include +#include +#include + +#define CGROUP_INDEX_BUCKETS 256u +#define CGROUP_FILE_BIT(file) (1u << (file)) +#define CGROUP_PIDS_EVENT_BITS (CGROUP_FILE_BIT(CG_PIDS_EVENTS) | CGROUP_FILE_BIT(CG_PIDS_LOCAL)) + +struct cgroup cgroup_root = {.id=1,.refs=1,.linked=true,.mode={0755,0,0}}; +static struct cgroup *index[CGROUP_INDEX_BUCKETS]; +static uint32_t last_id = 1; +static struct cgroup *work_head, **work_tail = &work_head; +static bool work_pending; + +/** @brief Find one group, including unlinked but retained identities. */ +struct cgroup *cgroup_find(uint32_t id) +{ + if (id == cgroup_root.id) return &cgroup_root; + for (struct cgroup *g = index[id % CGROUP_INDEX_BUCKETS]; g; g = g->index_next) + if (g->id == id) return g; + return NULL; +} + +/** @brief Coalesce a group's work without allocation or a scheduler wakeup. */ +static void queue_locked(struct cgroup *g, uint16_t bits) +{ + g->pending |= bits; + if (g->queued) return; + g->queued = true; + *work_tail = g; + work_tail = &g->work_next; + __atomic_store_n(&work_pending, true, __ATOMIC_RELEASE); +} + +/** @brief Schedule delivery only after dropping the scheduler lock. */ +void cgroup2_kick(void) +{ + if (__atomic_load_n(&work_pending, __ATOMIC_ACQUIRE)) + kernel_deferred_schedule(DEFERRED_VFS); +} + +/** @brief Retain inode, child or task ownership of a group. */ +void cgroup_get_locked(struct cgroup *g) { ++g->refs; } + +/** @brief Defer reclamation even if the final pin is dropped from task exit. */ +void cgroup_put_locked(struct cgroup *g) +{ + if (!--g->refs) queue_locked(g, 0); +} + +/** @brief Construct a fully initialized empty child before publishing it. */ +int cgroup_mkdir(struct cgroup *parent, const char *name, const struct reliefos_permissions *mode, + struct cgroup **out) +{ + if (!parent->linked) return -ENOENT; + if (!__builtin_strncmp(name, "cgroup.", 7)) return -EINVAL; + for (struct cgroup *child = parent->children; child; child = child->sibling) + if (!__builtin_strcmp(child->name, name)) return -EEXIST; + size_t n = __builtin_strlen(name); + if (parent->path_length + 1 + n >= VFS_PATH_MAX) return -ENAMETOOLONG; + if (last_id == UINT32_MAX) return -ENOSPC; + struct cgroup *g = kernel_malloc(sizeof(*g) + n + 1); + if (!g) return -ENOMEM; + *g = (struct cgroup){.parent=parent,.refs=1,.linked=true,.limit=CGROUP_PIDS_UNLIMITED, + .mode={mode->mode & 0777u,mode->uid,mode->gid},.id=++last_id, + .path_length=(uint16_t)(parent->path_length+1+n),.depth=(uint16_t)(parent->depth+1)}; + __builtin_memcpy(g->name, name, n+1); + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + cgroup_get_locked(parent); + g->sibling = parent->children; + parent->children = g; + for (struct cgroup *p = parent; p; p = p->parent) ++p->descendants; + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + struct cgroup **bucket = &index[g->id % CGROUP_INDEX_BUCKETS]; + g->index_next = *bucket; + *bucket = g; + *out = g; + return 0; +} + +/** @brief Unpublish a child only when no live task or linked child remains. */ +int cgroup_rmdir(struct cgroup *g) +{ + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + int rc = !g->linked ? -ENOENT : !g->parent || g->children || g->live ? -EBUSY : 0; + if (!rc) { + struct cgroup **link = &g->parent->children; + while (*link != g) link = &(*link)->sibling; + *link = g->sibling; + g->linked = false; + g->pending = 0; + for (struct cgroup *p = g->parent; p; p = p->parent) { --p->descendants; ++p->dying; } + cgroup_put_locked(g); + } + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + if (!rc) cgroup2_kick(); + return rc; +} + +/** @brief Return whether pids files and enforcement are enabled at this group. */ +bool cgroup_pids_enabled(const struct cgroup *g) +{ return g->parent && g->parent->subtree_pids; } + +/** @brief Change the state of all direct pids children in one locked transaction. */ +int cgroup_set_subtree_locked(struct cgroup *g, bool enabled) +{ + if (g->subtree_pids == enabled) return 0; + if (enabled && g->parent && !cgroup_pids_enabled(g)) return -ENOENT; + if (enabled && g->pids_epoch == CGROUP_PIDS_EPOCH_MAX) return -ENOSPC; + if (!enabled) + for (struct cgroup *child = g->children; child; child = child->sibling) + if (child->subtree_pids) return -EBUSY; + for (struct cgroup *child = g->children; child; child = child->sibling) { + child->pending &= ~CGROUP_PIDS_EVENT_BITS; + child->limit = CGROUP_PIDS_UNLIMITED; + child->events = child->local_events = 0; + child->peak = child->charged; + } + if (enabled) ++g->pids_epoch; + g->subtree_pids = enabled; + return 0; +} + +/** @brief Apply signed task/population deltas below (but not including) stop. + * Root needs no population counter or PID charge. Caller holds scheduler_lock. */ +static void adjust_locked(struct cgroup *g, const struct cgroup *stop, int64_t charged, int64_t live) +{ + for (; g && g->parent && g != stop; g = g->parent) { + bool populated = g->live != 0; + g->live += live; + g->charged += charged; + if (g->charged > g->peak) g->peak = g->charged; + if (populated != (g->live != 0) && g->linked) queue_locked(g, CGROUP_FILE_BIT(CG_EVENTS)); + } +} + +/** @brief Check whether one more thread fits the closest applicable limits. */ +bool cgroup2_fork_allowed(const struct task *parent) +{ + for (struct cgroup *g = parent ? parent->cgroup : NULL; g && g->parent; g = g->parent) { + if (!g->linked || !cgroup_pids_enabled(g) || g->charged < g->limit) continue; + ++g->local_events; + queue_locked(g, CGROUP_FILE_BIT(CG_PIDS_LOCAL)); + for (struct cgroup *p = g; p->parent; p = p->parent) { + ++p->events; + queue_locked(p, CGROUP_FILE_BIT(CG_PIDS_EVENTS)); + } + return false; + } + return true; +} + +/** @brief Charge a new thread only once all fallible construction has succeeded. */ +void cgroup2_fork_commit(struct task *child, const struct task *parent) +{ + struct cgroup *g = parent ? parent->cgroup : NULL; + if (!g) return; + child->cgroup = g; + cgroup_get_locked(g); + adjust_locked(g, NULL, 1, 1); +} + +/** @brief Separate live population from the PID charge of a waitable zombie. */ +void cgroup2_task_exit(struct task *task) +{ + if (!task->cgroup) return; + adjust_locked(task->cgroup, NULL, 0, -1); + if (!(task->flags & TASK_FLAG_WAITABLE_CHILD) || !task->parent_pid) cgroup2_task_reap(task); +} + +/** @brief Release an exiting thread's or reaped zombie's charge without VFS I/O. */ +void cgroup2_task_reap(struct task *task) +{ + struct cgroup *g = task->cgroup; + if (!g) return; + task->cgroup = NULL; + adjust_locked(g, NULL, -1, 0); + cgroup_put_locked(g); +} + +/** @brief Match a live user thread (including blocked or stopped tasks). */ +bool cgroup_live_task(const struct task *task) +{ return task->pid && task->kind == TASK_KIND_USER && task->state != TASK_EXITED && + !(task->flags & TASK_FLAG_LAUNCH_PREPARING); } + +/** @brief Find the common ancestor so a migration never changes its population. */ +static struct cgroup *common_ancestor(struct cgroup *a, struct cgroup *b) +{ + while (a->depth > b->depth) a = a->parent; + while (b->depth > a->depth) b = b->parent; + while (a != b) { a = a->parent; b = b->parent; } + return a; +} + +/** @brief Migrate the live process, not the selected individual thread. + * An exited leader with surviving threads still identifies that process. + * Migration may exceed a limit; subsequent fork admission enforces it. */ +int cgroup_move_locked(struct cgroup *destination, uint32_t pid) +{ + if (!destination->linked) return -ENODEV; + struct task *target = pid ? sched_find(pid) : sched_current_task(); + if (!target || !target->pid || target->kind != TASK_KIND_USER) return -ESRCH; + uint32_t tgid = sched_task_tgid(target); + if (!cgroup_live_task(target) && target->pid != tgid) return -ESRCH; + struct cgroup *old = NULL; + int64_t moved = 0; + struct task *task; + for (uint32_t i = 0; (task = sched_task_at(i)); ++i) { + if (!cgroup_live_task(task) || sched_task_tgid(task) != tgid) continue; + struct cgroup *from = task->cgroup ? task->cgroup : &cgroup_root; + if (destination == from) return 0; + old = from; + if (task->cgroup) cgroup_put_locked(task->cgroup); + task->cgroup = destination->parent ? destination : NULL; + if (task->cgroup) cgroup_get_locked(task->cgroup); + ++moved; + } + if (!moved) return -ESRCH; + struct cgroup *ancestor = common_ancestor(old, destination); + adjust_locked(old, ancestor, -moved, -moved); + adjust_locked(destination, ancestor, moved, moved); + return 0; +} + +/** @brief Produce a Linux unified membership record without resolving mounts. */ +void cgroup2_proc_emit(const struct task *task, struct text_stream *stream) +{ + char path[VFS_PATH_MAX]; + unsigned start = sizeof(path); + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + const struct cgroup *g = task->cgroup; + bool deleted = g && !g->linked; + while (g && g->parent) { + unsigned n = g->path_length - g->parent->path_length - 1u; + start -= n; + __builtin_memcpy(path+start, g->name, n); + path[--start] = '/'; + g = g->parent; + } + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + text_string(stream, "0::"); + if (start == sizeof(path)) text_string(stream, "/"); + else text_bytes(stream, path+start, sizeof(path)-start); + if (deleted) text_string(stream, " (deleted)"); + text_string(stream, "\n"); +} + +/** @brief Remove a zero-ref group from the index and release its retained ancestry. + * Must run under execution ownership with scheduler_lock held. Caller frees + * the now unreachable record outside the lock. */ +static void retire_locked(struct cgroup *g) +{ + struct cgroup **link = &index[g->id % CGROUP_INDEX_BUCKETS]; + while (*link != g) link = &(*link)->index_next; + *link = g->index_next; + for (struct cgroup *p = g->parent; p; p = p->parent) --p->dying; + cgroup_put_locked(g->parent); +} + +/** @brief Flush pending events by immutable key after leaving the task lock. */ +void cgroup2_service(unsigned budget) +{ + while (budget--) { + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + struct cgroup *g = work_head; + if (!g) { kernel_spin_unlock_irqrestore(&scheduler_lock, flags); break; } + work_head = g->work_next; + if (!work_head) { + work_tail = &work_head; + __atomic_store_n(&work_pending, false, __ATOMIC_RELEASE); + } + g->work_next = NULL; + g->queued = false; + uint16_t pending = g->linked ? g->pending : 0; + g->pending = 0; + uint32_t epoch = g->parent ? g->parent->pids_epoch : 0; + bool free_group = g->refs == 0; + if (free_group) retire_locked(g); + uint32_t id = g->id; + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + if (free_group) { kernel_free(g); continue; } + /* Delivery can wake waiters; keep no borrowed group across callbacks. */ + const struct cgroup key = {.id=id}; + for (enum cgroup_file file = CG_EVENTS; pending && file < CG_FILE_COUNT; ++file) { + if (!(pending & CGROUP_FILE_BIT(file))) continue; + struct storage_node node = cgroup_node(&key, file, epoch); + cgroup_notify(&node, false); + } + } + cgroup2_kick(); +} diff --git a/fs/cgroup/internal.h b/fs/cgroup/internal.h new file mode 100644 index 00000000..8d9e6fb7 --- /dev/null +++ b/fs/cgroup/internal.h @@ -0,0 +1,58 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_CGROUP_INTERNAL_H +#define RELIEFNT_CGROUP_INTERNAL_H +#include +#include +#include + +#define CGROUP_PIDS_MAX 4194304u +#define CGROUP_PIDS_UNLIMITED UINT64_MAX +#define CGROUP_PIDS_EPOCH_MAX (UINT32_MAX >> 4) +#define CGROUP_DEVICE 203u +#define CGROUP_MAGIC 0x63677270u + +enum cgroup_file { + CG_DIR, CG_PROCS, CG_THREADS, CG_CONTROLLERS, CG_SUBTREE, CG_TYPE, CG_EVENTS, CG_STAT, + CG_PIDS_MAX, CG_PIDS_CURRENT, CG_PIDS_PEAK, CG_PIDS_EVENTS, CG_PIDS_LOCAL, CG_FILE_COUNT, +}; + +/* Topology/index and VFS operations require the execution writer. All task + * membership, counters, controller state, refs and pending bits are also + * serialized by scheduler_lock, including updates from remote task exit. */ +struct cgroup { + struct cgroup *parent, *children, *sibling, *index_next, *work_next; + uint64_t refs, live, charged, limit, peak, events, local_events; + uint32_t id, pids_epoch, descendants, dying; + uint16_t path_length, depth, pending; + bool linked, subtree_pids, queued; + struct reliefos_permissions mode; + char name[]; +}; + +extern struct kernel_spinlock scheduler_lock; +extern struct cgroup cgroup_root; + +/** @brief Borrow an ID-indexed object under VFS execution ownership. */ +struct cgroup *cgroup_find(uint32_t id); +/** @brief Allocate and publish an empty child and its globally unique identity. */ +int cgroup_mkdir(struct cgroup *parent, const char *name, const struct reliefos_permissions *mode, + struct cgroup **out); +/** @brief Unlink an empty group without invalidating retained task or inode pins. */ +int cgroup_rmdir(struct cgroup *group); +/** @brief Acquire one more reference to a live group; caller holds scheduler_lock. */ +void cgroup_get_locked(struct cgroup *group); +/** @brief Drop one reference, queuing final release; caller holds scheduler_lock. */ +void cgroup_put_locked(struct cgroup *group); +/** @brief Test controller availability while holding scheduler_lock. */ +bool cgroup_pids_enabled(const struct cgroup *group); +/** @brief Switch child controller visibility atomically with fork admission. */ +int cgroup_set_subtree_locked(struct cgroup *group, bool enabled); +/** @brief Move the live thread group identified by PID or TID under scheduler_lock. */ +int cgroup_move_locked(struct cgroup *destination, uint32_t pid); +/** @brief Identify a live, published user thread in the locked task table. */ +bool cgroup_live_task(const struct task *task); +/** @brief Export an inode's globally unique key for a borrowed group and epoch. */ +struct storage_node cgroup_node(const struct cgroup *group, enum cgroup_file file, uint32_t epoch); +/** @brief Deliver an event-key snapshot outside scheduler_lock under execution ownership. */ +void cgroup_notify(const struct storage_node *node, bool removed); +#endif diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 9955155f..96e8f133 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -234,7 +235,7 @@ static int proc_oom_key(const char *name, struct task **task) * @param buffer Writable kernel buffer, always NUL-terminated on return. * @param capacity Nonzero byte capacity of buffer. * @return Zero with the file content in buffer, or negative ENOENT for paths - * this generator does not own. The filesystem list includes devpts. + * this generator does not own. The filesystem list includes devpts and cgroup2. */ static int proc_fill_content(const char *path, char *buffer, uint32_t capacity) { @@ -280,7 +281,7 @@ static int proc_fill_content(const char *path, char *buffer, uint32_t capacity) #ifdef CONFIG_SQUASHFS proc_append_text(buffer, &pos, capacity, "\tsquashfs\n"); #endif - proc_append_text(buffer, &pos, capacity, "nodev\tproc\nnodev\tdevfs\nnodev\tdevtmpfs\nnodev\tdevpts\nnodev\tsysfs\nnodev\ttmpfs\n"); + proc_append_text(buffer, &pos, capacity, "nodev\tproc\nnodev\tdevfs\nnodev\tdevtmpfs\nnodev\tdevpts\nnodev\tcgroup2\nnodev\tsysfs\nnodev\ttmpfs\n"); return 0; } if (proc_text_eq(path, "/proc/asound/cards")) { @@ -824,7 +825,8 @@ static void proc_task_stat(struct task *task, struct text_stream *s, bool proces /** @brief Look up proc node types without following the last symbolic link. * @param path Borrowed absolute intrinsic pathname, NULL is rejected. * @param out Optional caller-owned writable node metadata. - * @return Zero or negative ENOENT. Execution-owned; no reference transfers. */ + * @return Zero or negative ENOENT. Execution-owned; no reference transfers. + * Includes the unified cgroup membership file in process and thread views. */ int proc_lookup(const char *path, struct storage_node *out) { int extra = proc_extra_kind(path); @@ -969,7 +971,8 @@ int proc_lookup(const char *path, struct storage_node *out) } if ((kind == 2 || kind == 3) && file && (proc_text_eq(file, "stat") || proc_text_eq(file, "comm") || proc_text_eq(file, "cmdline") || proc_text_eq(file, "environ") || proc_text_eq(file, "status") || - proc_text_eq(file, "oom_score") || proc_text_eq(file, "oom_score_adj"))) { + proc_text_eq(file, "oom_score") || proc_text_eq(file, "oom_score_adj") || + proc_text_eq(file, "cgroup"))) { if (kind == 2 && !sched_find(pid)) return -2; if (out) { *out = (struct storage_node){ @@ -993,7 +996,8 @@ int proc_lookup(const char *path, struct storage_node *out) * @param length Maximum bytes to copy. * @param out_read Optional caller-owned writable actual byte count. * @return Zero or negative errno, preserving backend failures. Execution-owned; - * retains no caller memory and live generated views can change between reads. */ + * retains no caller memory and live generated views can change between reads. + * A cgroup membership record reflects a single locked ancestry snapshot. */ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, uint32_t *out_read) { @@ -1043,6 +1047,15 @@ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, } const char *file=0; uint32_t pid=0; int kind=proc_path_kind(path,&file,&pid); if(kind==3) pid=sched_current_pid(); + if ((kind == 2 || kind == 3) && file && proc_text_eq(file,"cgroup")) { + const struct task *task=sched_find(pid); + if (!pid || !task || task->kind != TASK_KIND_USER) return -ENOENT; + struct text_stream stream={.offset=offset,.buffer=buffer,.capacity=length}; + if (cgroup2_proc_emit) cgroup2_proc_emit(task,&stream); + else text_string(&stream,"0::/\n"); + if(out_read)*out_read=stream.written; + return 0; + } if ((kind == 2 || kind == 3) && file && (proc_text_eq(file,"oom_score") || proc_text_eq(file,"oom_score_adj"))) { struct task *task=sched_find(pid); @@ -1167,6 +1180,7 @@ int proc_readlink(const char *path, char *buffer, uint32_t capacity) * @param entry Required writable record, assigned on success. * @return One entry, zero EOF, or negative errno. Caller serializes execution * and retains the provider; no scheduler lock spans a generated-file callback. + * The process entries include unified cgroup membership. */ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry *entry) { @@ -1286,7 +1300,7 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * "exe", "cwd", "root", "comm", "environ", "fd", "task", "fdinfo", "limits", "statm", "maps", "smaps", "smaps_rollup", "auxv", "io", - "oom_score", "oom_score_adj"}; + "oom_score", "oom_score_adj", "cgroup"}; if (*offset == 11 && (proc_thread_path(path) || sched_task_tgid(sched_find(pid)) != pid || !__builtin_strncmp(path, "/proc/thread-self", 17))) ++*offset; diff --git a/fs/sysfs/sysfs.c b/fs/sysfs/sysfs.c index 32bddcdd..803fcfe0 100644 --- a/fs/sysfs/sysfs.c +++ b/fs/sysfs/sysfs.c @@ -447,9 +447,12 @@ static int sys_modules_walk(sys_visit visit,void *context) } return 0; } +/** @brief Walk sysfs nodes, including the empty cgroup2 mountpoint. */ static int sys_walk(sys_visit visit, void *ctx) { static const char *dirs[] = {"/sys", + "/sys/fs", + "/sys/fs/cgroup", "/sys/dev", "/sys/dev/char", "/sys/dev/block", diff --git a/fs/vfs/file.c b/fs/vfs/file.c index 0944b882..51f7c8cb 100644 --- a/fs/vfs/file.c +++ b/fs/vfs/file.c @@ -204,6 +204,8 @@ int vfs_path_new_file(const struct vfs_path *parent,const char *name, const struct reliefos_permissions *value,struct vfs_path *out) {return !out ? -EINVAL : vfs_path_create_node(parent,name,LINUX_S_IFREG,value,NULL,out);} +/** @brief Create a child only through a writable attachment and supported provider. + * No cached or returned inode is published before successful backend creation. */ int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t type, const struct reliefos_permissions *value,const char *target,struct vfs_path *out) { @@ -221,7 +223,7 @@ int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t type!=LINUX_S_IFIFO && type!=LINUX_S_IFSOCK)return -EOPNOTSUPP; if(type==LINUX_S_IFLNK && (!target || !target[0]))return -ENOENT; if(type!=LINUX_S_IFLNK && target)return -EINVAL; - if(!parent->mount->ops->create_node)return -EROFS; + if((vfs_path_mount_flags(parent)&MS_RDONLY) || !parent->mount->ops->create_node)return -EROFS; struct vfs_dentry *reserved=NULL; if(out) { reserved=kernel_malloc(sizeof(*reserved));if(!reserved)return -ENOMEM; diff --git a/include/reliefnt/cgroup.h b/include/reliefnt/cgroup.h new file mode 100644 index 00000000..1903323b --- /dev/null +++ b/include/reliefnt/cgroup.h @@ -0,0 +1,43 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_CGROUP_H +#define RELIEFNT_CGROUP_H +#include + +struct task; +struct text_stream; +struct vfs_mount; + +/** @brief Open a detached view of the single cgroup v2 hierarchy. + * @param source Optional copied mount label. @param flags Attachment policy. + * @param options Optional compatibility options. @param out Owned mount on success. + * @return Zero or negative errno with empty output. Execution writer required. */ +int cgroup2_create_vfs_mount(const char *source, uint64_t flags, const char *options, + struct vfs_mount **out); + +/** @brief Deliver a bounded batch of deferred notifications and retire dead groups. + * @param budget Maximum queued groups to process. Execution writer required. */ +void cgroup2_service(unsigned budget); + +/* The standalone scheduler/proc fixtures can omit the facility. Production + * always links it through the mount and deferred-work entry points. */ +/** @brief Check a prospective child against the parent's ancestor limits. + * @param parent Borrowed user parent or NULL for root. Caller holds scheduler_lock. + * @return True if allowed; false records a rejection without charging the child. */ +bool cgroup2_fork_allowed(const struct task *parent) __attribute__((weak)); +/** @brief Charge one successfully published user task to the inherited group. + * @param child Fresh task with no charge. @param parent Borrowed parent or NULL. + * Requires scheduler_lock and a successful admission in the same transaction. */ +void cgroup2_fork_commit(struct task *child, const struct task *parent) __attribute__((weak)); +/** @brief Remove a first-time exit from the population, retaining waitable charges. + * @param task Borrowed task immediately before exit under scheduler_lock. */ +void cgroup2_task_exit(struct task *task) __attribute__((weak)); +/** @brief Release a dead task's charge and group pin once, under scheduler_lock. + * @param task Borrowed exited task that is no longer waitable. */ +void cgroup2_task_reap(struct task *task) __attribute__((weak)); +/** @brief Request a worker turn if changes are pending; never under scheduler_lock. */ +void cgroup2_kick(void) __attribute__((weak)); +/** @brief Write a task's unified membership line, including deleted ancestry. + * @param task Borrowed published task under execution ownership. + * @param stream Caller-owned positional text stream. Takes scheduler_lock internally. */ +void cgroup2_proc_emit(const struct task *task, struct text_stream *stream) __attribute__((weak)); +#endif diff --git a/include/reliefnt/sched.h b/include/reliefnt/sched.h index fde3c96c..703d95ca 100644 --- a/include/reliefnt/sched.h +++ b/include/reliefnt/sched.h @@ -20,10 +20,14 @@ void sched_init(void); */ struct task *sched_create_kernel_task(const char *name,uint64_t entry,uint64_t low,uint64_t top,uint32_t cpu); /** - * @brief Create a user task named name with the given entry, stack, parent, and flags; returns pid. + * @brief Prepare a blocked user task with inherited identity but no cgroup charge. + * @return Prepared PID or negative errno. Caller finishes with sched_publish_user_task(). */ -uint32_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack_top, +int64_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack_top, uint32_t parent_pid, uint32_t flags); +/** @brief Publish a prepared task under the scheduler lock with current cgroup admission. + * @return Zero or negative errno. Failed admission leaves the launch uncharged. */ +int sched_publish_user_task(uint32_t pid); /** * @brief Wake (or release) task's CLONE_VFORK child as exec/exit completes. * diff --git a/include/reliefnt/storage.h b/include/reliefnt/storage.h index 510ef27e..6268626a 100644 --- a/include/reliefnt/storage.h +++ b/include/reliefnt/storage.h @@ -295,6 +295,8 @@ struct storage_read_cursor { #define STORAGE_NODE_FLAG_SQUASHFS 0x00200000u /* Instance-bound devpts inode, resolved before global rdev dispatch. */ #define STORAGE_NODE_FLAG_DEVPTS 0x00400000u +/* Generated cgroup2 controls, not regular-file data for RLIMIT_FSIZE. */ +#define STORAGE_NODE_FLAG_CGROUP 0x00800000u #define STORAGE_SYSFS_DEVICE 202u #define STORAGE_NODE_FLAG_DEV_LINK 0x00000200u /* Anonymous filesystem device numbers, also exported in proc mountinfo. */ diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index cbb850cb..2526bbf6 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -27,6 +27,7 @@ struct drm_file; struct drm_prime_file; struct task_epoll_watch; struct task_identity; +struct cgroup; struct vfs_exec_source; struct task_transfer_state; struct seccomp_filter; @@ -250,6 +251,8 @@ enum task_kind { #define TASK_FLAG_FORK_NOEXEC 0x00000100u #define TASK_FLAG_ORPHAN_NOTIFY 0x00000200u #define TASK_FLAG_PDEATH_NOTIFY 0x00000400u +/* Internal launch has a PID but is not published as a runnable cgroup member. */ +#define TASK_FLAG_LAUNCH_PREPARING 0x00000800u /* A stopped or continued child retains its task slot until its parent has * observed the state transition through waitpid. */ @@ -524,6 +527,8 @@ struct task_lookup_scope { struct task { /* Lazily allocated PID identity, retained independently by proc inodes. */ struct task_identity *identity_token; + /* Owned non-root membership or zombie charge, protected by scheduler_lock. */ + struct cgroup *cgroup; uint64_t proc_read_chars, proc_write_chars, proc_read_calls, proc_write_calls; uint64_t proc_read_bytes, proc_write_bytes; /* Group-leader CPU time retained when retired thread slots are reused. diff --git a/kernel/exec/userland.c b/kernel/exec/userland.c index fb555f34..3b5b7a16 100644 --- a/kernel/exec/userland.c +++ b/kernel/exec/userland.c @@ -731,7 +731,8 @@ static int userland_bind_pending_image(struct task *task,const char *path) * @param make_ready Nonzero to publish after all references/parameters attach. * @return PID or negative errno. Requires the published shared namespace; * initializes fresh root/cwd before publication without resetting inherited - * objects. Execution-owned task context; no scheduler lock spans backend I/O. + * objects. Runnable publication checks the current cgroup PID quota. + * Execution-owned task context; no scheduler lock spans backend I/O. */ static int64_t spawn_pending_image_ex(const char *path, const char *task_name, const struct exec_launch *launch, @@ -741,10 +742,9 @@ static int64_t spawn_pending_image_ex(const char *path, const char *task_name, { struct vfs_namespace *namespace=vfs_system_namespace(); if(!namespace)return -19; - uint32_t pid = sched_create_user_task(task_name, 0, USER_STACK_TOP, parent, flags); - if (!pid) { - return -12; - } + int64_t prepared = sched_create_user_task(task_name, 0, USER_STACK_TOP, parent, flags); + if (prepared < 0) return prepared; + uint32_t pid = (uint32_t)prepared; int fs_ret=sched_task_fs_start(sched_find(pid),namespace); if(fs_ret<0){sched_exit(pid,127);return fs_ret;} sched_set_task_path(pid, path); @@ -775,7 +775,8 @@ static int64_t spawn_pending_image_ex(const char *path, const char *task_name, * scheduler has been published. Bootstrap callers may defer this one * final transition while they attach the controlling PTY. */ if (make_ready) { - sched_mark_ready(pid); + int rc = sched_publish_user_task(pid); + if (rc) { sched_exit(pid, 127); return rc; } } return pid; } @@ -1068,7 +1069,7 @@ const char *userland_boot_cmdline(void) /** * @brief Prepare runtime objects in the assembled namespace and start PID1. * @param boot Borrowed boot handoff; namespace already owns root/providers. - * @return None. Stops at idle on missing root/namespace or failed preparation; + * @return None. Stops at idle on missing root/namespace or failed launch; * otherwise starts the configured user image with inherited actual root/cwd. * Exclusive boot execution precedes user tasks and secondary CPU startup. */ @@ -1118,7 +1119,11 @@ void userland_init(const struct boot_info *boot) } init_pid = (uint32_t)pid; console_info("[reliefnt] PID 1 path=%s console=tty1\n", init_path); - sched_mark_ready(init_pid); + int publish = sched_publish_user_task(init_pid); + if (publish < 0) { + console_fatal("[boot] cannot publish PID 1 ret=%d\n", publish); + kernel_idle_loop(); + } } /** @@ -1401,7 +1406,8 @@ int64_t userland_spawn_path_argv_with_fds(const char *path, } /** - * @brief Spawn path as a child of parent_pid and tag it with the given user identity/session; returns the PID or a negative errno. + * @brief Spawn path as a child of parent_pid with the given user identity/session. + * @return PID or negative errno, including EAGAIN on cgroup quota denial. */ int64_t userland_spawn_path_argv_for_user(const char *path, const char *const argv[], @@ -1431,7 +1437,8 @@ int64_t userland_spawn_path_argv_for_user(const char *path, sched_set_task_identity((uint32_t)pid, user, session_id); ret=userland_bind_pending_image(sched_find((uint32_t)pid),path); if(ret<0){sched_exit((uint32_t)pid,127);return ret;} - sched_mark_ready((uint32_t)pid); + ret = sched_publish_user_task((uint32_t)pid); + if (ret < 0) { sched_exit((uint32_t)pid, 127); return ret; } console_debug("[reliefnt] spawn trusted path=%s pid=%u parent=%u user=%u\n", path, (unsigned)pid, parent_pid, user->uid); } diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index fb02ba7b..f1c220ac 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -1,4 +1,5 @@ #include "internal.h" +#include #include /** @brief Invalidate OOM snapshots when a vfork relation ends. @@ -168,6 +169,9 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) * @return Child process ID, or a negative errno if creation fails. Copies held * root/cwd objects for fork, shares them for CLONE_FS, and releases only child * ownership on rollback. Called under execution ownership; takes scheduler_lock. + * Checks cgroup admission before construction and charges only at publication. + * Rollback hides the reserved PID before unlocking for provider cleanup; the + * blocked slot is not reusable until cleanup completes. * The child never borrows the parent's retained PID-identity object or pending * syscall lookup names/root/dirfd references or imported vector/transfer state, * including on early allocation failure. @@ -200,9 +204,10 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag sched_task_identity_put(identity); return -22; } - if (task_nproc_denied_locked(parent)) { + if (task_nproc_denied_locked(parent) || (cgroup2_fork_allowed && !cgroup2_fork_allowed(parent))) { kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_identity_put(identity); + if (cgroup2_kick) cgroup2_kick(); return -LINUX_EAGAIN; } parent->nproc_exceeded = false; @@ -230,6 +235,8 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag } task_zero(child); *child = *parent; + /* Borrowed by the shallow copy; only successful publication takes a charge. */ + child->cgroup = NULL; #ifdef CONFIG_SECCOMP_FILTER /* The shallow copy hasn't taken a reference, nor does a new thread * inherit a pending synchronous signal. */ @@ -554,10 +561,12 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag child->proc_read_bytes = child->proc_write_bytes = 0; child->cpu_user_ticks = child->cpu_system_ticks = 0; child->retired_user_ticks = child->retired_system_ticks = 0; + if (cgroup2_fork_commit) cgroup2_fork_commit(child, parent); ++proc_created; child->state = TASK_READY; sched_request_reschedule_all_online(); kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); + if (cgroup2_kick) cgroup2_kick(); /* Execution ownership keeps the published child stable while this * non-scheduler-locked healthy-path MM identity preparation runs. */ uint64_t generation; @@ -565,14 +574,19 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag return (int64_t)child_pid; fail: - sched_task_fs_release(child); + /* Retain the blocked slot, but hide its unbound PID before allowing + * provider puts to take scheduler_lock (e.g. Unix socket GC closing a + * cgroup file from an SCM_RIGHTS queue). */ + child->pid = 0; if (child->shared_mm) --child->shared_mm->references; - else { + if (child->shared_files) --child->shared_files->references; + kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); + sched_task_fs_release(child); + if (!child->shared_mm) { address_space_destroy(sched_task_as(child)); sched_task_vma_release(child); } - if (child->shared_files) --child->shared_files->references; - else { + if (!child->shared_files) { if (files_retained) syscall_release_task_files(child); else { sched_task_file_release(child); @@ -582,6 +596,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag kernel_free(child->exec_argv); kernel_free(child->exec_envp); kernel_free(child->exec_data); + kernel_spin_lock_irqsave(&scheduler_lock, &lock_flags); task_zero(child); child->state = TASK_EXITED; child->running_cpu = SCHED_CPU_NONE; diff --git a/kernel/sched/exec.c b/kernel/sched/exec.c index 08037dd6..7a889857 100644 --- a/kernel/sched/exec.c +++ b/kernel/sched/exec.c @@ -1,5 +1,6 @@ #include #include "internal.h" +#include /** @brief Invalidate OOM holder snapshots after an exec root commit. * Production supplies the allocation-free notifier; detached scheduler @@ -127,7 +128,8 @@ int sched_set_task_exec_params(uint32_t pid, uint32_t argc, char *const argv[], * @param task Current task under exclusive execution ownership; required. * @return Zero when ready, negative file-table error, or EAGAIN while a remote * sibling is retiring. Retains the filesystem state shared via CLONE_FS. - * Called without scheduler_lock; takes it for signals. + * During de-threading, the retired leader's PID charge does not follow its + * PID to the surviving task. Called without scheduler_lock; takes it for signals. */ int sched_prepare_exec_current(struct task *task) { @@ -187,6 +189,7 @@ int sched_prepare_exec_current(struct task *task) task->parent_exit_notified = 0; task->flags |= leader->flags & TASK_FLAG_WAITABLE_CHILD; leader->flags &= ~TASK_FLAG_WAITABLE_CHILD; + if (cgroup2_task_reap) cgroup2_task_reap(leader); leader->process_pending_signals = 0; leader->alarm_deadline = 0; leader->alarm_interval_ns = leader->alarm_last_expiry = 0; @@ -201,6 +204,7 @@ int sched_prepare_exec_current(struct task *task) current_pid[scheduler_cpu_index()] = group; current_task[scheduler_cpu_index()] = task; kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + if (cgroup2_kick) cgroup2_kick(); } if (task->shared_sighand) { struct task_sighand_state *old = task->shared_sighand; diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 8b3b1002..b664e599 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -55,9 +55,11 @@ static struct task *fair_task(struct eevdf_entity *entity) return (struct task *)((char *)entity - __builtin_offsetof(struct task, fair)); } +/** @brief Admit runnable user tasks only after their launch has been published. */ static bool fair_runnable(const struct task *task) { return task->kind == TASK_KIND_USER && + !(task->flags & TASK_FLAG_LAUNCH_PREPARING) && (task->state == TASK_READY || task->state == TASK_RUNNING) && (!task->vfork_child || kernel_signal_fatal_pending(task)) && (task->entry || (task->image && task->image_len) || (task->flags & TASK_FLAG_PENDING_LOAD)) && diff --git a/kernel/sched/internal.h b/kernel/sched/internal.h index 87c67814..4009b557 100644 --- a/kernel/sched/internal.h +++ b/kernel/sched/internal.h @@ -651,9 +651,9 @@ struct task *alloc_task_slot(void); struct task *sched_create_kernel_task(const char *name,uint64_t entry,uint64_t low,uint64_t top,uint32_t cpu); /** - * @brief Allocate a user task, build its address space and stack, and inherit cwd/identity from parent. + * @brief Prepare an unpublished user task and its address space; return PID or negative errno. */ -uint32_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack_top, +int64_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack_top, uint32_t parent_pid, uint32_t flags); /** diff --git a/kernel/sched/task.c b/kernel/sched/task.c index e922cbc1..8b5d181a 100644 --- a/kernel/sched/task.c +++ b/kernel/sched/task.c @@ -1,4 +1,5 @@ #include "internal.h" +#include #ifdef CONFIG_SWAP /** @brief Cancel a task's optional pressure-refill state and its owned queue link. * @param task Execution-owned task, nullable; borrowed without ownership transfer. @@ -419,27 +420,29 @@ struct task *sched_create_kernel_task(const char *name,uint64_t entry,uint64_t l * @brief Allocate a user task, build its address space and stack, and inherit cwd/identity from parent. * @param name Borrowed NUL-terminated task name. @param entry User entry address. * @param stack_top Initial exclusive stack top. @param parent_pid Inheriting parent. - * @param flags Initial task flags. @return Published PID, or zero on failure. - * Prepares PID identity before scheduler locking and retains root state for the task. + * @param flags Initial task flags. @return Prepared PID or negative errno. + * Prepares the address space and PID identity but neither charges cgroups nor + * makes the task runnable. Execution ownership required through final publication. */ -uint32_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack_top, +int64_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack_top, uint32_t parent_pid, uint32_t flags) { struct task_identity *identity = sched_task_identity_prepare(); - if (!identity) return 0; + if (!identity) return -LINUX_ENOMEM; uint64_t lock_flags; kernel_spin_lock_irqsave(&scheduler_lock, &lock_flags); - if (task_nproc_denied_locked(sched_find(parent_pid))) { + struct task *real_parent = parent_pid ? sched_find(parent_pid) : NULL; + if (task_nproc_denied_locked(real_parent)) { kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_identity_put(identity); - return 0; + return -LINUX_EAGAIN; } struct task *task = alloc_task_slot(); uint32_t pid; if (!task) { kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_identity_put(identity); - return 0; + return -LINUX_ENOMEM; } pid = task_allocate_pid(); if (!pid) { @@ -447,12 +450,11 @@ uint32_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack task->state = TASK_EXITED; kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_identity_put(identity); - return 0; + return -LINUX_ENOMEM; } task_zero(task); task->pid = pid; task->start_uptime_ms = time_uptime_ms(); - struct task *real_parent = parent_pid ? sched_find(parent_pid) : NULL; task->parent_pid = real_parent ? sched_task_tgid(real_parent) : parent_pid; task->pdeath_parent_pid = parent_pid; task->parent_exit_signal = 17; @@ -485,7 +487,7 @@ uint32_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack task->flags = TASK_FLAG_RESOURCES_RELEASED; kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_identity_put(identity); - return 0; + return -LINUX_ENOMEM; } task->frame.rip = entry; task->frame.cs = RELIEFNT_USER_CS; @@ -498,7 +500,7 @@ uint32_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack task->state = TASK_BLOCKED; task->running_cpu = SCHED_CPU_NONE; task->kind = TASK_KIND_USER; - task->flags = flags; + task->flags = flags | TASK_FLAG_LAUNCH_PREPARING; sched_task_identity_bind(task, identity); task_clear_identity(task); task_copy_cwd(task, "/"); @@ -532,7 +534,6 @@ uint32_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack (unsigned long long)task->entry, (unsigned long long)task->stack_top, task->flags); - ++proc_created; kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); /* The task is still unpublished to its caller; prepare the root identity * after dropping scheduler_lock. Reclaim can use its reserve fallback if @@ -542,12 +543,43 @@ uint32_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack return task->pid; } +/** @brief Admit a fully prepared launch and make it runnable in one transaction. + * @param pid Prepared task's PID. @return Zero, -ESRCH or -EAGAIN on quota denial. + * Caller owns execution and must retire the still uncharged task on failure. + * Inherit cgroup membership only from a published, live user parent. + */ +int sched_publish_user_task(uint32_t pid) +{ + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + struct task *task = pid ? sched_find(pid) : NULL; + int rc = -LINUX_ESRCH; + if (task && task->state != TASK_EXITED && (task->flags & TASK_FLAG_LAUNCH_PREPARING)) { + const struct task *parent = task->pdeath_parent_pid ? sched_find(task->pdeath_parent_pid) : NULL; + if (parent && (parent->kind != TASK_KIND_USER || parent->state == TASK_EXITED || + (parent->flags & TASK_FLAG_LAUNCH_PREPARING))) parent = NULL; + if (cgroup2_fork_allowed && !cgroup2_fork_allowed(parent)) rc = -LINUX_EAGAIN; + else { + if (cgroup2_fork_commit) cgroup2_fork_commit(task, parent); + task->flags &= ~TASK_FLAG_LAUNCH_PREPARING; + task->state = TASK_READY; + ++proc_created; + sched_request_reschedule_all_online(); + rc = 0; + } + } + kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + if (cgroup2_kick) cgroup2_kick(); + return rc; +} + /** * @brief Publish terminal task state and log its first exit after releasing the scheduler lock. * @param pid Task identifier; PID 1 panics and an absent PID has no exit event. * @param code Exit status; repeated calls retain the existing status-update and cleanup semantics. * The caller must not hold scheduler_lock. Capture a bounded diagnostic under - * that lock; defer resource release until the CPU reservation is quiescent. + * that lock, update cgroup population once, and defer resource release until + * the CPU reservation is quiescent. */ void sched_exit(uint32_t pid, uint64_t code) { @@ -570,6 +602,7 @@ void sched_exit(uint32_t pid, uint64_t code) exiting = tasks[i]; exit_event = tasks[i]->state != TASK_EXITED; if (exit_event) { + if (cgroup2_task_exit) cgroup2_task_exit(exiting); exit_pid = tasks[i]->pid; exit_code = code; task_copy_identity_text(exit_name, sizeof(exit_name), tasks[i]->name); @@ -599,7 +632,8 @@ void sched_exit(uint32_t pid, uint64_t code) tasks[i]->parent_pid = 1; /* Thread siblings follow the parent relationship, but only * process leaders become waitable children of PID 1. */ - if (tasks[i]->pid == sched_task_tgid(tasks[i])) { + if (tasks[i]->pid == sched_task_tgid(tasks[i]) && + !(tasks[i]->flags & TASK_FLAG_LAUNCH_PREPARING)) { tasks[i]->parent_exit_signal = 17; tasks[i]->parent_exit_notified = 0; tasks[i]->flags |= TASK_FLAG_WAITABLE_CHILD; @@ -610,6 +644,7 @@ void sched_exit(uint32_t pid, uint64_t code) } else { tasks[i]->parent_pid = 0; tasks[i]->flags &= ~TASK_FLAG_WAITABLE_CHILD; + if (tasks[i]->state == TASK_EXITED && cgroup2_task_reap) cgroup2_task_reap(tasks[i]); } } } @@ -646,6 +681,7 @@ void sched_exit(uint32_t pid, uint64_t code) * after retirement and the mm_release futex work below. */ } kernel_spin_unlock_irqrestore(&scheduler_lock, flags); + if (cgroup2_kick) cgroup2_kick(); if (exit_event) { console_debug("[reliefnt] scheduler task exited pid=%u name=%s code=%llu\n", exit_pid, diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index 3af4c154..dc39999d 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -1,5 +1,6 @@ #include #include "internal.h" +#include #include #include @@ -167,7 +168,8 @@ static void sched_wait_usage(struct linux_rusage *out, const struct task *task) * -2 for an absent waiter, or -RELIEFOS_EAGAIN while a matching child is pending. * The caller must not hold scheduler_lock; resource teardown and diagnostics * execute outside it. WNOWAIT observes without consuming or logging a reap. - * Consuming a zombie invalidates its retained PID identity before PID unpublish. + * Consuming a zombie releases its cgroup charge and invalidates its retained + * PID identity before PID unpublish. */ static int64_t sched_wait_child(uint32_t waiter_pid, int32_t wanted_pid, const struct task_identity *identity, @@ -202,7 +204,7 @@ static int64_t sched_wait_child(uint32_t waiter_pid, int32_t wanted_pid, for (uint32_t i = 0; i < task_count; ++i) { struct task *task = tasks[i]; if (exact && task != exact) continue; - if (task->pid == 0 || task->kind != TASK_KIND_USER) { + if (task->pid == 0 || task->kind != TASK_KIND_USER || (task->flags & TASK_FLAG_LAUNCH_PREPARING)) { continue; } if (task->pid != sched_task_tgid(task)) continue; @@ -286,6 +288,7 @@ static int64_t sched_wait_child(uint32_t waiter_pid, int32_t wanted_pid, kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); return reap_pid; } + if (cgroup2_task_reap) cgroup2_task_reap(reap_task); reap_task->parent_pid = 0; notify_pidfd = sched_task_pidfd_watched(reap_task); sched_task_identity_detach(reap_task); @@ -311,6 +314,7 @@ static int64_t sched_wait_child(uint32_t waiter_pid, int32_t wanted_pid, kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); if (notify_pidfd) kernel_poll_readiness_notify(); if (reap_event) { + if (cgroup2_kick) cgroup2_kick(); console_debug("[reliefnt] scheduler wait reaped pid=%u by pid=%u\n", reap_pid, waiter_pid); } diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 0e669f66..48666f0a 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -1,4 +1,5 @@ /* SPDX-License-Identifier: Apache-2.0 */ +#include #include #include "../internal.h" #include @@ -99,7 +100,7 @@ static int mount_remount(struct vfs_namespace *ns,struct task *task,uint64_t tar * @param source Copied kernel source label; its user pointer is passed separately. * @param source_user Original user source pathname for a disk filesystem. * @param type Copied filesystem type, empty for existing native detection. - * @param options Copied tmpfs/devpts, FAT ownership, or ext3 ordered-mode options. + * @param options Copied options for tmpfs, devpts, cgroup2, FAT or ext3. * @param flags Final mount policy without operation bits. * @param out Receives one owned detached mount, empty on failure. * @return Zero or unsupported/device/lookup/provider errno. Source resolution @@ -109,6 +110,7 @@ static int mount_remount(struct vfs_namespace *ns,struct task *task,uint64_t tar static int mount_backend(struct vfs_namespace *ns,struct task *task,const char *source,uint64_t source_user, const char *type,const char *options,uint64_t flags,struct vfs_mount **out) { + if(!__builtin_strcmp(type,"cgroup2"))return cgroup2_create_vfs_mount(source,flags,options,out); if(!__builtin_strcmp(type,"devpts"))return devpts_create_vfs_mount(source,flags,options,task->fsuid,task->fsgid,out); if(!__builtin_strcmp(type,"devtmpfs"))return devtmpfs_create_vfs_mount(source,flags,options,out); if(!__builtin_strcmp(type,"tmpfs"))return storage_new_tmpfs_mount(source,flags,options,task->fsuid,task->fsgid,out); diff --git a/kernel/syscall/fs/size.c b/kernel/syscall/fs/size.c index aef920b1..c7e052f0 100644 --- a/kernel/syscall/fs/size.c +++ b/kernel/syscall/fs/size.c @@ -7,7 +7,8 @@ * @param path Borrowed held inode retaining its provider through I/O. * @param length Validated nonnegative logical size. * @return Zero or negative errno. Acquires a temporary inode/write lease - * before truncation and releases it on every outcome, including retry. + * before truncation for stored files, releasing it on every outcome. Generated + * cgroup controls validate truncation directly without a storage inode lease. * No text lookup or graph/module spinlock spans the provider callback. */ static int truncate_inode_path(struct task *task,const struct vfs_path *path,uint64_t length) @@ -16,6 +17,7 @@ static int truncate_inode_path(struct task *task,const struct vfs_path *path,uin if(!node)return -RELIEFOS_EINVAL; if(node->type==RELIEFOS_FS_TYPE_DIR)return -RELIEFOS_EISDIR; if(node->type!=RELIEFOS_FS_TYPE_FILE)return -RELIEFOS_EINVAL; + if(node->flags&STORAGE_NODE_FLAG_CGROUP)return vfs_path_truncate(path,length); int limited=task_file_limit_size(task,length);if(limited)return limited; struct storage_inode_ref *inode=NULL; int rc=storage_inode_get(node,&inode);if(rc)return rc; diff --git a/kernel/syscall/io/file_io.c b/kernel/syscall/io/file_io.c index afd02148..bb9909ca 100644 --- a/kernel/syscall/io/file_io.c +++ b/kernel/syscall/io/file_io.c @@ -205,6 +205,7 @@ static void regular_stage_copy_read(struct regular_io_stage *s, uint32_t count) * genuine block nodes use the block service. No graph/module lock spans * callbacks. O_APPEND stats the actual inode; sync flags flush the retained * provider, except for the immediately committed proc diagnostic control. + * Generated controls, including cgroup commands, do not grow a stored file. */ int64_t syscall_regular_io(struct task *task, struct task_file *file, uint64_t buffer, uint64_t count, uint64_t position, bool writing, bool positional) @@ -245,7 +246,8 @@ int64_t syscall_regular_io(struct task *task, struct task_file *file, uint64_t b } if (position > INT64_MAX || count > (uint64_t)INT64_MAX - position) return -LINUX_EINVAL; - if (!block && writing && !(file->node.flags & (STORAGE_NODE_FLAG_PROC | STORAGE_NODE_FLAG_SYSFS))) { + if (!block && writing && !(file->node.flags & (STORAGE_NODE_FLAG_PROC | STORAGE_NODE_FLAG_SYSFS | + STORAGE_NODE_FLAG_CGROUP))) { int ret = task_file_limit_write(task, position, &count, !task->vector_io || !task->vector_io->completed); if (ret) return ret; diff --git a/kernel/syscall/io/transfer.c b/kernel/syscall/io/transfer.c index cf9bb8a0..ce472053 100644 --- a/kernel/syscall/io/transfer.c +++ b/kernel/syscall/io/transfer.c @@ -149,6 +149,7 @@ static int transfer_begin(struct task *task,bool range,const uint64_t args[6]) * @return Zero or negative busy/metadata/range errno. EAGAIN retains original * offsets and provider pins. No partial new reservation is acquired when the * peer OFD is owned by another task. Provider metadata I/O is synchronous. + * Do not apply stored-file growth limits to generated control destinations. */ static int transfer_prepare(struct task *task) { @@ -176,7 +177,7 @@ static int transfer_prepare(struct task *task) state->output_positioninput_position+state->count && state->input_positionoutput_position+state->count)return -EINVAL; if(state->output->node.type==RELIEFOS_FS_TYPE_FILE && - !(state->output->node.flags&(STORAGE_NODE_FLAG_PROC|STORAGE_NODE_FLAG_SYSFS))) { + !(state->output->node.flags&(STORAGE_NODE_FLAG_PROC|STORAGE_NODE_FLAG_SYSFS|STORAGE_NODE_FLAG_CGROUP))) { rc=task_file_limit_write(task,state->output_position,&state->count,true); if(rc)return rc; } diff --git a/kernel/workqueue/services.c b/kernel/workqueue/services.c index 66333220..1b31382f 100644 --- a/kernel/workqueue/services.c +++ b/kernel/workqueue/services.c @@ -1,4 +1,5 @@ /* SPDX-License-Identifier: Apache-2.0 */ +#include #include #include #include @@ -28,13 +29,14 @@ static void usb_work(struct kernel_work *work,void *context) (void)context;usb_process_work(); if(usb_service_pending())(void)kernel_queue_delayed_work(work,1); } -/** @brief Retry bounded detached-mount cleanup while preserving failed owners. +/** @brief Service device and cgroup updates and retry bounded mount cleanup. * @param work Permanent VFS work. @param context Unused NULL. */ static void vfs_work(struct kernel_work *work,void *context) { (void)context; (void)devtmpfs_refresh(); + cgroup2_service(16); (void)vfs_reclaim_mounts(2); if(vfs_reclaim_pending() || devtmpfs_pending())(void)kernel_queue_delayed_work(work,1); } diff --git a/tools/test_cgroup_scheduler.py b/tools/test_cgroup_scheduler.py new file mode 100644 index 00000000..98644fec --- /dev/null +++ b/tools/test_cgroup_scheduler.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""Exercise cgroup admission and retirement through the real scheduler.""" +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[1] + + +def main() -> None: + with tempfile.TemporaryDirectory(prefix="reliefnt-cgroup-sched-") as directory: + binary = Path(directory) / "cgroup-scheduler" + subprocess.run([ + "clang", "-std=c11", "-O1", "-g", "-ffunction-sections", "-fdata-sections", + "-Wl,--gc-sections", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", + "-Iinclude", "-Iinclude/uapi", "tools/tests/cgroup_scheduler_test.c", + "fs/cgroup/hierarchy.c", "fs/cgroup/filesystem.c", "fs/vfs/lookup_cache.c", + "fs/vfs/file.c", "-o", str(binary), + ], cwd=ROOT, check=True) + subprocess.run([str(binary)], cwd=ROOT, check=True, timeout=20) + + +if __name__ == "__main__": + main() diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index 7fe3228f..a68bb612 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Walk actual retained tmpfs inode objects through the native mount graph.""" +"""Exercise actual filesystem backends through the native mount graph.""" from pathlib import Path import subprocess import tempfile @@ -22,6 +22,8 @@ def test_real_tmpfs_without_text_routing(self): "cc", "-std=gnu11", "-O1", "-g", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Wl,--wrap=storage_ext4_read_inode", "-Wl,--wrap=storage_read_device", "-Wl,--wrap=storage_inode_stat", "-Wl,--wrap=storage_backend_commit_rename_metadata", "-Wl,--wrap=storage_cluster_write", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_backend_test.c", "kernel/dma/buffer.c", "drivers/storage/ahci/dma.c", "drivers/storage/ahci/interrupt.c", "drivers/storage/nvme/queue.c", "block/partition/mbr.c", + "fs/cgroup/filesystem.c", "fs/cgroup/hierarchy.c", "fs/vfs/notify.c", + "fs/notify/core.c", "fs/notify/limits.c", "fs/notify/queue.c", "fs/notify/watch.c", "fs/vfs/filesystems.c", "fs/vfs/filesystem_instance.c", "fs/ext_common/journal.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/kernel_file.c", "fs/vfs/kernel_path.c", "fs/vfs/exec_file.c", "fs/vfs/attributes.c", "fs/vfs/initial.c", "fs/vfs/storage_initial.c", "fs/vfs/storage_attributes.c", "fs/vfs/storage_access.c", "fs/vfs/storage_backend.c", "fs/vfs/mutation.c", "fs/vfs/storage_mutation.c", "fs/vfs/storage_create.c", "fs/vfs/storage_security.c", "fs/vfs/write_access.c", "fs/devpts/devpts.c", "drivers/tty/pty/core.c", "drivers/tty/pty/ring.c", "drivers/tty/pty/line_discipline.c", "drivers/tty/pty/session.c", "drivers/tty/pty/vt.c", "kernel/syscall/device/device_open.c", "kernel/syscall/device/device_io.c", "kernel/syscall/fs/stat.c", "fs/vfs/storage_mount.c", "fs/vfs/fat_options.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/security/access.c", "lib/text_utf16.c", "fs/devfs/mount.c", "fs/devfs/devtmpfs.c", "fs/devfs/devtmpfs_nodes.c", "fs/devfs/device.c", "fs/devfs/identity.c", "fs/vfs/pseudo.c", "kernel/exec/runtime.c", "kernel/exec/pending.c", "kernel/syscall/process/exec.c", "kernel/syscall/system/user_string.c", "kernel/syscall/ipc/unix_path.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/create.c", "kernel/syscall/fs/mount.c", "kernel/syscall/fs/mutation.c", "kernel/syscall/fs/directory.c", "kernel/syscall/fs/size.c", "kernel/syscall/fs/sync.c", "kernel/syscall/fs/path.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fd/descriptor.c", "kernel/device/character.c", "kernel/syscall/io/vector.c", "kernel/syscall/fd/pty_descriptor.c", "kernel/sched/tables.c", "kernel/device/mapping.c", "kernel/sched/fs.c", "kernel/sync/wait.c", "-o", str(binary) diff --git a/tools/tests/Makefile b/tools/tests/Makefile index 8be48f39..88a15a59 100644 --- a/tools/tests/Makefile +++ b/tools/tests/Makefile @@ -15,7 +15,7 @@ test-host-smoke: --suite acpi_pm_timer --suite apic_timer --suite cpu_accounting \ --suite fat_async_read --suite fat_read_split \ --suite squashfs --suite squashfs_boot \ - --suite linux_pty --suite mount_backend \ + --suite linux_pty --suite mount_backend --suite cgroup_scheduler \ --suite vdso_mapping --suite vdso_time test-smp-time: diff --git a/tools/tests/cgroup_scheduler_test.c b/tools/tests/cgroup_scheduler_test.c new file mode 100644 index 00000000..08d5660d --- /dev/null +++ b/tools/tests/cgroup_scheduler_test.c @@ -0,0 +1,213 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +/* Real scheduler, hierarchy and cgroup backend. Model only MM/CPU, empty + * descriptors, and the deferred notification boundary in this host fixture. */ +#define main exit_logging_fixture_main +#include "task_exit_logging_test.c" +#undef main +#include +#include +#include + +static bool fail_clone_setup; + +/** @brief Supply physical memory for the scheduler's default process limits. */ +uint64_t mm_total_memory_kib(void) { return 65536; } +/** @brief Give each modeled address space a nonzero root; no pages are accessed. */ +bool address_space_create(struct address_space *as) +{ as->cr3 = 0x2000; return true; } +/** @brief Accept only a stack on a created address space. */ +bool address_space_map_user_stack(struct address_space *as, uint64_t top) +{ assert(as->cr3 && top); return true; } +/** @brief Model successful MM duplication; fork still runs its real scheduler path. */ +bool address_space_clone_cow(struct address_space *from, struct address_space *to) +{ assert(from->cr3 && !to->cr3); return address_space_create(to); } +/** @brief Supply a generation without allocating a host page table. */ +int mm_context_ensure_generation(struct address_space *as, uint64_t *generation) +{ assert(as->cr3 && !scheduler_lock_depth); *generation = 1; return 0; } +/** @brief The fixture never writes through a Linux clone TID pointer. */ +bool user_range_writable(uint64_t address, uint64_t length) +{ (void)address; (void)length; abort(); } +/** @brief Reject unexpected user-memory writes. */ +int user_copy_to_task(struct task *task, uint64_t address, const void *source, uint64_t length) +{ (void)task; (void)address; (void)source; (void)length; abort(); } +/** @brief Reject unexpected page-permission queries. */ +bool address_space_user_page_writable(const struct address_space *as, uint64_t address) +{ (void)as; (void)address; abort(); } +/** @brief Reject unexpected COW faults. */ +bool address_space_handle_cow_fault(struct address_space *as, uint64_t address) +{ (void)as; (void)address; abort(); } +/** @brief No host FPU state is needed for scheduler accounting. */ +void arch_fpu_task_init(void *state) { assert(state); } +/** @brief No host FPU state is needed when cloning an abstract task. */ +void arch_fpu_save(void *state) { assert(state); } +/** @brief Only empty descriptor tables are modeled. */ +int syscall_clone_task_files(const struct task *parent, struct task *child) +{ assert(!parent->file_extra_count && !child->file_extra_count && !parent->pty_fd_count); return 0; } +/** @brief Inject a failure after fork has reserved its slot and cloned descriptors. */ +int task_sysv_sem_clone(struct task *parent, struct task *child, uint64_t flags) +{ assert(!parent->sysv_undo && !child->sysv_undo && flags == 17); return fail_clone_setup ? -ENOMEM : 0; } +/** @brief No executable inode is installed in the modeled MM. */ +void storage_inode_retain(struct storage_inode_ref *inode) { assert(!inode); } +/** @brief Reject an executable write denial on an empty image. */ +int storage_inode_deny_write(struct storage_inode_ref *inode) { assert(!inode); abort(); } +/** @brief The fixture starts from root credentials with no supplementary groups. */ +void task_groups_retain(struct task_groups *groups) { assert(!groups); } +/** @brief No mapped file descriptors are owned by the modeled MM. */ +struct task_file *task_file_get(struct task_file *file) { assert(!file); return NULL; } +/** @brief Reject a device-backed VMA in the empty modeled address space. */ +int device_mapping_get(struct device_mapping *mapping) { (void)mapping; abort(); } +/** @brief Reject a device-backed range in the empty modeled address space. */ +int device_mapping_retain_range(struct device_mapping *mapping, uint64_t offset, uint64_t length) +{ (void)mapping; (void)offset; (void)length; abort(); } +/** @brief The modeled address space has no SysV shared-memory attachments. */ +int sysv_shm_vma_clone(struct task *task, struct task_vma *dst, const struct task_vma *src) +{ assert(task && dst && src && !src->sysv_shm_attachment); return 0; } +/** @brief Scheduling work may wake tasks and must not hold the scheduler lock. */ +void kernel_deferred_request(enum kernel_deferred_service service) +{ assert(service == DEFERRED_VFS && !scheduler_lock_depth); } +/** @brief No inotify watchers; delivery itself must still run outside the lock. */ +void fsnotify_emit(const struct fsnotify_key *key, uint32_t mask, uint32_t cookie, + const char *name, bool unlinked) +{ assert(key && mask == IN_MODIFY && !cookie && !name && !unlinked && !scheduler_lock_depth); } +/** @brief The fixtures for inotify itself live in the mount backend suite. */ +bool fsnotify_has_watches(void) { return false; } +/** @brief Reject an unexpected watch deletion. */ +void fsnotify_delete(const struct fsnotify_key *key) { (void)key; abort(); } + +/** @brief Create and pin a child through the mounted cgroup backend. */ +static struct vfs_path make_group(const struct vfs_path *parent, const char *name) +{ + struct storage_node node = {0}; + const struct reliefos_permissions mode = {.mode = 0755}; + struct vfs_path path; + assert(!parent->mount->ops->create_node(parent->mount->context, vfs_path_node(parent), + name, LINUX_S_IFDIR, &mode, NULL, &node, NULL)); + assert(!vfs_path_lookup_child(parent, name, &path)); + return path; +} + +/** @brief Read or write a cgroup control and check the exact returned bytes. */ +static void control(const struct vfs_path *group, const char *name, const char *text, bool write) +{ + struct vfs_path path; + char bytes[64]; + uint32_t count = 0; + assert(!vfs_path_lookup_child(group, name, &path)); + struct storage_node node = *vfs_path_node(&path); + if (write) + assert(!path.mount->ops->write(path.mount->context, &node, 0, text, strlen(text), &count)); + else + assert(!path.mount->ops->read(path.mount->context, &node, 0, bytes, sizeof(bytes), &count, 0)); + assert(count == strlen(text) && (write || !memcmp(bytes, text, count))); + vfs_path_put(&path); +} + +/** @brief Check the real membership emitter, including its deleted-path suffix. */ +static void membership(const struct task *task, const char *expected) +{ + char bytes[80]; + struct text_stream text = {.buffer = bytes, .capacity = sizeof(bytes)}; + cgroup2_proc_emit(task, &text); + assert(text.written == strlen(expected) && !memcmp(bytes, expected, text.written)); +} + +/** @brief Check fork, internal publication, exit and reap against a real hierarchy. */ +int main(void) +{ + next_pid = 200; + uint32_t published = proc_created; + int64_t actor_pid = sched_create_user_task("actor", RELIEFNT_USER_BASE, USER_STACK_TOP, 0, 0); + assert(actor_pid > 1 && !sched_publish_user_task((uint32_t)actor_pid)); + struct task *actor = sched_find((uint32_t)actor_pid); + assert(actor && actor->state == TASK_READY && proc_created == published + 1); + current_task[0] = actor; + current_pid[0] = actor->pid; + + struct vfs_mount *mount = NULL; + struct vfs_namespace ns = {0}; + struct vfs_path root; + assert(!cgroup2_create_vfs_mount(NULL, 0, NULL, &mount)); + assert(!vfs_namespace_init(&ns, mount) && !vfs_namespace_root(&ns, &root)); + vfs_mount_put(mount); + struct vfs_path parent = make_group(&root, "jobs"); + struct vfs_path caller = make_group(&parent, "caller"); + struct vfs_path worker = make_group(&parent, "worker"); + control(&root, "cgroup.subtree_control", "+pids", true); + control(&parent, "cgroup.subtree_control", "+pids", true); + control(&parent, "pids.max", "2", true); + control(&caller, "cgroup.procs", "0", true); + membership(actor, "0::/jobs/caller\n"); + + fail_clone_setup = true; + assert(sched_clone_current(&actor->frame, 17, 0, 0, 0, 0) == -ENOMEM); + fail_clone_setup = false; + control(&parent, "pids.current", "1\n", false); + control(&parent, "pids.peak", "1\n", false); + assert(proc_created == published + 1); + + int64_t child_pid = sched_clone_current(&actor->frame, 17, 0, 0, 0, 0); + struct task *child = child_pid > 0 ? sched_find((uint32_t)child_pid) : NULL; + assert(child && child->state == TASK_READY && proc_created == published + 2); + membership(child, "0::/jobs/caller\n"); + char pid[16]; + snprintf(pid, sizeof(pid), "%u", child->pid); + control(&worker, "cgroup.procs", pid, true); + assert(sched_clone_current(&actor->frame, 17, 0, 0, 0, 0) == -EAGAIN); + control(&parent, "pids.current", "2\n", false); + control(&parent, "pids.peak", "2\n", false); + control(&parent, "pids.events.local", "max 1\n", false); + control(&caller, "pids.events", "max 0\n", false); + + int64_t draft = sched_create_user_task("draft", RELIEFNT_USER_BASE, USER_STACK_TOP, actor->pid, 0); + assert(draft > 0 && !sched_wait_reap(actor->pid, (int32_t)draft, LINUX_WEXITED, NULL, NULL)); + assert(sched_publish_user_task((uint32_t)draft) == -EAGAIN); + sched_exit((uint32_t)draft, 127); + control(&parent, "pids.current", "2\n", false); + control(&parent, "pids.events", "max 2\n", false); + + sched_exit((uint32_t)child_pid, 23); + control(&worker, "cgroup.events", "populated 0\nfrozen 0\n", false); + control(&worker, "pids.current", "1\n", false); + int status = 0; + assert(sched_wait_reap(actor->pid, (int32_t)child_pid, LINUX_WEXITED | LINUX_WNOWAIT, + &status, NULL) == child_pid && status == 23 << 8); + assert(sched_clone_current(&actor->frame, 17, 0, 0, 0, 0) == -EAGAIN); + assert(!worker.mount->ops->remove_node(worker.mount->context, &worker, true)); + membership(child, "0::/jobs/worker (deleted)\n"); + + /* A retained zombie is not a valid source of membership at publication. */ + draft = sched_create_user_task("root-fallback", RELIEFNT_USER_BASE, USER_STACK_TOP, + (uint32_t)child_pid, 0); + assert(draft > 0 && !sched_publish_user_task((uint32_t)draft)); + membership(sched_find((uint32_t)draft), "0::/\n"); + sched_exit((uint32_t)draft, 0); + assert(sched_wait_reap(actor->pid, (int32_t)child_pid, LINUX_WEXITED, + &status, NULL) == child_pid && !sched_find((uint32_t)child_pid)); + control(&parent, "pids.current", "1\n", false); + + draft = sched_create_user_task("published", RELIEFNT_USER_BASE, USER_STACK_TOP, actor->pid, 0); + assert(draft > 0 && !sched_publish_user_task((uint32_t)draft)); + membership(sched_find((uint32_t)draft), "0::/jobs/caller\n"); + control(&caller, "pids.current", "2\n", false); + sched_exit((uint32_t)draft, 0); + control(&caller, "pids.current", "1\n", false); + control(&root, "cgroup.procs", "0", true); + assert(!caller.mount->ops->remove_node(caller.mount->context, &caller, true)); + assert(!parent.mount->ops->remove_node(parent.mount->context, &parent, true)); + vfs_path_put(&worker); + vfs_path_put(&caller); + vfs_path_put(&parent); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns)); + cgroup2_service(16); + sched_exit(actor->pid, 0); + for (uint32_t i = 0; i < task_count; ++i) { + sched_task_identity_detach(tasks[i]); + free(tasks[i]); + } + free(tasks); + tasks = NULL; + current_task[0] = NULL; + puts("PASS cgroup2 real scheduler: ancestor admission, clone rollback, launch, exit, WNOWAIT and reap"); + return 0; +} diff --git a/tools/tests/host-suites.list b/tools/tests/host-suites.list index 08899ff0..7cfebdd3 100644 --- a/tools/tests/host-suites.list +++ b/tools/tests/host-suites.list @@ -159,6 +159,7 @@ usb_storage tools/test_usb_storage.py mbr_partitions tools/test_mbr_partitions.py mount_tree tools/test_mount_tree.py mount_backend tools/test_mount_backend.py +cgroup_scheduler tools/test_cgroup_scheduler.py filesystem_registry tools/test_filesystem_registry.py filesystem_boundaries tools/test_filesystem_boundaries.py filesystem_format tools/test_filesystem_format.py diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 63777a7b..9c72dd03 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -12,7 +12,9 @@ #define RELIEFNT_FIXTURE_SEPARATE_JOURNAL #define RELIEFNT_FIXTURE_DEVICE_FLUSH #define main storage_mkdir_reference_main +#define sched_current_task storage_fixture_current_task #include "storage_mkdir_mount_test.c" +#undef sched_current_task #undef main static unsigned file_size_signals; /** @brief Observe FSIZE delivery while keeping the VFS fixture alive. @@ -27,10 +29,15 @@ int kernel_signal_queue_task(struct task *task,int signal_number) #include #include #include +#include +#include +#include +#include #include #include #include #include +#include #include #include "../../kernel/syscall/internal.h" #include "../../kernel/syscall/ipc/unix_path.h" @@ -185,6 +192,8 @@ void sched_truncate_file_mappings(const struct storage_node *node,uint64_t size) /* PTYs use the production core and descriptors. This fixture has one actor, * no asynchronous console hardware and no other scheduler terminal owners. */ static struct task *devpts_actor; +static struct task *cgroup_tasks[2]; +struct kernel_spinlock scheduler_lock; bool console_vga_text_mode; /** @brief Reject an unexpected blocked scheduler actor in the synchronous fixture. * @param task Unexpected waiter. */ @@ -193,8 +202,20 @@ const struct framebuffer *framebuffer_get(void) { return NULL; } void kernel_spin_init(struct kernel_spinlock *lock) { lock->state = 0; } void console_vt_write(uint32_t number, const char *text, size_t count) { (void)number; (void)text; (void)count; } +/** @brief Return the cgroup scenario's current actor; other cases run as kernel. */ +struct task *sched_current_task(void) { return cgroup_tasks[0]; } +/** @brief Enumerate the two user threads enrolled in the cgroup scenario. */ +struct task *sched_task_at(uint32_t index) { return index < 2 ? cgroup_tasks[index] : NULL; } +/** @brief Resolve a modeled PID without changing scheduler ownership. */ struct task *sched_find(uint32_t pid) -{ return devpts_actor && devpts_actor->pid == pid ? devpts_actor : NULL; } +{ + for (uint32_t i = 0; i < 2; ++i) + if (cgroup_tasks[i] && cgroup_tasks[i]->pid == pid) return cgroup_tasks[i]; + return devpts_actor && devpts_actor->pid == pid ? devpts_actor : NULL; +} +/** @brief Model the deferred-service handoff; never wake while holding the task lock. */ +void kernel_deferred_request(enum kernel_deferred_service service) +{ assert(service == DEFERRED_VFS && !scheduler_lock.state); } uint32_t sched_pty_reference_count(uint32_t id) { return pty_transfer_count(id, 0); } uint32_t sched_pty_master_reference_count(uint32_t id) { return pty_transfer_count(id, 1); } int sched_hangup_user_tasks_for_pty(uint32_t id, uint32_t owner) @@ -2361,6 +2382,138 @@ static int64_t scoped_mount_call(struct vfs_namespace *ns,struct task *task,uint if(rc!=-EAGAIN)task_lookup_scope_cancel(task); return rc; } + +/** @brief Read a generated cgroup control by its retained inode and check exact bytes. */ +static void cgroup_check_text(const struct vfs_path *directory,const char *name,const char *expected) +{ + struct vfs_path file={0};char data[80];uint32_t count=0; + assert(!vfs_path_lookup_child(directory,name,&file)); + assert(!vfs_path_read(&file,0,data,sizeof(data),&count)); + assert(count==strlen(expected) && !memcmp(data,expected,count)); + vfs_path_put(&file); +} + +/** @brief Write one command through a real VFS control and check completion semantics. */ +static void cgroup_write_text(const struct vfs_path *directory,const char *name,const char *text,int status) +{ + struct vfs_path file={0};uint32_t count=UINT32_MAX; + assert(!vfs_path_lookup_child(directory,name,&file)); + assert(vfs_path_write(&file,0,text,strlen(text),&count)==status); + assert(count==(status ? 0 : strlen(text))); + vfs_path_put(&file); +} + +/** @brief Verify one nameless inode notification from the real inotify core. */ +static void cgroup_expect_event(struct fsnotify_instance *instance,int wd,uint32_t mask) +{ + const struct inotify_event *event=NULL; + assert(fsnotify_peek(instance,&event)==sizeof(*event)); + assert(event->wd==wd && event->mask==mask && !event->cookie && !event->len); + fsnotify_pop(instance); +} + +/** @brief Exercise cgroup attachments, generated controls, migration and inode lifetime. */ +static void cgroup_mount_syscalls(struct vfs_namespace *ns,const struct vfs_path *root) +{ + assert(!vfs_kernel_mkdir(ns,"/cgroup",0755)); + assert(!vfs_kernel_mkdir(ns,"/cgroup-ro",0755)); + struct task actor={.pid=903,.kind=TASK_KIND_USER,.state=TASK_RUNNING,.cap_effective=1ULL<0); + assert(!vfs_notify_key(&old,&key)); + int removed=fsnotify_add_watch(watch,&key,IN_DELETE_SELF);assert(removed>0); + + cgroup_write_text(&group,"pids.max","0",0); + actor.cap_effective=0; + cgroup_write_text(&group,"cgroup.procs","904",-EPERM); + actor.cap_effective=1ULL< Date: Sat, 28 Nov 2026 22:51:39 +0800 Subject: [PATCH 05/97] feat(vfs): support recursive directory bind mounts --- .../en/LC_MESSAGES/userspace-api/abi.po | 41 ++++-- .../ja/LC_MESSAGES/userspace-api/abi.po | 32 +++-- Documentation/userspace-api/abi.rst | 7 +- fs/vfs/mount_tree.c | 125 +++++++++++++++--- include/reliefnt/mount.h | 9 ++ kernel/syscall/fs/mount.c | 12 +- tools/tests/mount_backend_test.c | 71 +++++++++- 7 files changed, 256 insertions(+), 41 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index fdc42434..de6b43d6 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -52,17 +52,36 @@ msgid "目录 bind mount" msgstr "Directory Bind Mounts" msgid "" -"``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录绑定。 新挂载保留源目录的实际 inode、父链和文件系统生命周期,继承源挂载的 " -"只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot " -"边界按新挂载计算。 源文件系统在绑定仍存在时不能卸载,解绑不销毁源文件系统。 递归绑定、文件绑定和 bind remount 尚不支持,返回明确错误。" -msgstr "" -"``mount(source, target, NULL, MS_BIND, NULL)`` supports nonrecursive directory binds. The new " -"mount retains the source directory's actual inode, parent chain, and filesystem lifecycle, and " -"inherits source mount policies such as read-only, nosuid, and nodev. The root field of " -"``/proc/self/mountinfo`` reports the source directory's path within its filesystem; namespace " -"paths, ``..``, and chroot boundaries are computed relative to the new mount. The source filesystem" -" cannot be unmounted while the bind remains, and unbinding does not destroy it. Recursive binds, " -"file binds, and bind remounts are not yet supported and return explicit errors." +"``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录绑定。 新挂载保留源目录的实际 " +"inode、父链和文件系统生命周期,继承源挂载的 只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 " +"root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 " +"源文件系统在绑定仍存在时不能卸载,解绑不销毁源文件系统。" +msgstr "" +"``mount(source, target, NULL, MS_BIND, NULL)`` supports nonrecursive " +"directory binds. The new mount retains the source directory's actual " +"inode, parent chain, and filesystem lifecycle, and inherits source mount " +"policies such as read-only, nosuid, and nodev. The root field of " +"``/proc/self/mountinfo`` reports the source directory's path within its " +"filesystem; namespace paths, ``..``, and chroot boundaries are computed " +"relative to the new mount. The source filesystem cannot be unmounted " +"while the bind remains, and unbinding does not destroy it." + +msgid "" +"``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 " +"inode 和文件系统。源目录之外的挂载不复制, 后续拓扑变更也不会传播。准备失败时目的树和现有挂载保持原样。" +msgstr "" +"``MS_BIND | MS_REC`` also copies the topology of mounts below the source " +"directory. Submounts in the destination tree have new mount IDs and " +"independent policies, but each shares its original inodes and filesystem." +" Mounts outside the source directory are not copied, and later topology " +"changes do not propagate. Preparation failure leaves the destination tree" +" and existing mounts unchanged." + +msgid "文件绑定和 bind remount 尚不支持,返回明确错误。" +msgstr "" +"File binds and bind remounts are not yet supported and return explicit " +"errors." + msgid "按任务选择 uname 系统名" msgstr "Selecting the uname system name per task" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index d2d2f7eb..87ad1688 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -47,15 +47,29 @@ msgid "目录 bind mount" msgstr "ディレクトリーの bind mount" msgid "" -"``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录绑定。 新挂载保留源目录的实际 inode、父链和文件系统生命周期,继承源挂载的 " -"只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot " -"边界按新挂载计算。 源文件系统在绑定仍存在时不能卸载,解绑不销毁源文件系统。 递归绑定、文件绑定和 bind remount 尚不支持,返回明确错误。" -msgstr "" -"``mount(source, target, NULL, MS_BIND, NULL)`` は非再帰のディレクトリーバインドに対応します。新しいマウントは元ディレクトリーの実際の " -"inode、親チェーン、ファイルシステムのライフサイクルを保持し、元マウントの読み取り専用、nosuid、nodev などの方針を継承します。``/proc/self/mountinfo`` の " -"root フィールドは元ディレクトリーのファイルシステム内のパスを報告し、名前空間のパス、``..``、chroot " -"境界は新マウントを基準に計算します。バインドが残る間は元ファイルシステムをアンマウントできず、バインド解除で元ファイルシステムを破棄することもありません。再帰バインド、ファイルバインド、bind " -"remount は未対応で、明示的なエラーを返します。" +"``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录绑定。 新挂载保留源目录的实际 " +"inode、父链和文件系统生命周期,继承源挂载的 只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 " +"root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 " +"源文件系统在绑定仍存在时不能卸载,解绑不销毁源文件系统。" +msgstr "" +"``mount(source, target, NULL, MS_BIND, NULL)`` " +"は非再帰のディレクトリーバインドに対応します。新しいマウントは元ディレクトリーの実際の " +"inode、親チェーン、ファイルシステムのライフサイクルを保持し、元マウントの読み取り専用、nosuid、nodev " +"などの方針を継承します。``/proc/self/mountinfo`` の root " +"フィールドは元ディレクトリーのファイルシステム内のパスを報告し、名前空間のパス、``..``、chroot " +"境界は新マウントを基準に計算します。バインドが残る間は元ファイルシステムをアンマウントできず、バインド解除で元ファイルシステムを破棄することもありません。" + +msgid "" +"``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 " +"inode 和文件系统。源目录之外的挂载不复制, 后续拓扑变更也不会传播。准备失败时目的树和现有挂载保持原样。" +msgstr "" +"``MS_BIND | MS_REC`` は元ディレクトリー配下のマウント構造も複製します。複製先の子マウントには新しいマウント ID " +"と独立したポリシーが割り当てられますが、それぞれ元の inode " +"とファイルシステムを共有します。元ディレクトリー外のマウントは複製されず、後から行った構造の変更も伝播しません。準備に失敗しても複製先のツリーと既存のマウントは変化しません。" + +msgid "文件绑定和 bind remount 尚不支持,返回明确错误。" +msgstr "ファイルのバインドと bind remount にはまだ対応せず、明示的なエラーを返します。" + msgid "按任务选择 uname 系统名" msgstr "タスクごとの uname システム名の選択" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index b853925f..069ee549 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -45,7 +45,12 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 源文件系统在绑定仍存在时不能卸载,解绑不销毁源文件系统。 -递归绑定、文件绑定和 bind remount 尚不支持,返回明确错误。 + +``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 +挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载不复制, +后续拓扑变更也不会传播。准备失败时目的树和现有挂载保持原样。 + +文件绑定和 bind remount 尚不支持,返回明确错误。 glibc 线程与 CPU 状态兼容 ========================= diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index c2823c26..ce538494 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -233,20 +233,15 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const stru mount->next=ns->mounts;ns->mounts=mount;return 0; } -/** @brief Publish an independent directory view sharing the retained source graph. - * @param ns Borrowed execution-owned namespace. - * @param source Borrowed directory path retained before publication. - * @param target Borrowed destination directory path in the same namespace. - * @return Zero or negative errno; every allocation/admission/attach failure - * releases only newly acquired references. No provider context is duplicated, - * and no graph lock spans allocation or backend callbacks. +/** @brief Prepare an unattached directory view of an existing filesystem. + * @param source Valid retained source directory; its mount and inode are shared. + * @param out Receives the privately owned clone on success, NULL on failure. + * @return Zero or negative provider/admission/allocation errno. No new backend + * is created, and the clone has no namespace membership or inotify registration. */ -int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path *target) +static int vfs_bind_clone(const struct vfs_path *source,struct vfs_mount **out) { - if(!ns || !vfs_path_valid(source) || !vfs_path_valid(target))return -EINVAL; - if(source->mount->ns!=ns || target->mount->ns!=ns)return -EXDEV; - if(source->dentry->node.type!=RELIEFOS_FS_TYPE_DIR || target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; - if(source->dentry->disconnected)return -ENOENT; + *out=NULL; struct vfs_mount *original=source->mount; if(!try_module_get(original->owner))return -ENODEV; struct vfs_mount *mount=kernel_malloc(sizeof(*mount)); @@ -254,11 +249,111 @@ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source,const *mount=(struct vfs_mount){.ops=original->ops,.context=original->context, .owner=original->owner,.references=1,.root=source->dentry,.policy=original->policy}; vfs_path_get(source,&mount->bind_source); - if(vfs_notify_mount_created)vfs_notify_mount_created(mount); int rc=vfs_mount_describe(mount,original->source ? original->source : "none", original->filesystem ? original->filesystem : "none",original->device); - if(!rc)rc=vfs_mount_attach(ns,mount,target); - vfs_mount_put(mount);return rc; + if(rc)vfs_mount_put(mount); + else *out=mount; + return rc; +} + +/** @brief Find the next direct submount within the selected directory view. + * @param view The original mount and the directory bounding its subtree. + * @param candidate Start of a suffix of the unchanged namespace mount list. + * @return Borrowed matching attachment or NULL. A mount on the same backing + * dentry through another attachment is not part of this view. + */ +static struct vfs_mount *vfs_bind_child_mount(const struct vfs_path *view,struct vfs_mount *candidate) +{ + for(;candidate;candidate=candidate->next) { + if(candidate->point.mount!=view->mount)continue; + for(const struct vfs_dentry *d=candidate->point.dentry;d && !d->disconnected;d=d->parent) + if(d==view->dentry)return candidate; + } + return NULL; +} + +/** @brief Clone and publish a directory attachment and optionally its submounts. + * @param ns Borrowed namespace under execution ownership. + * @param source Borrowed retained source directory in ns. + * @param target Borrowed retained destination directory in ns. + * @param recursive True to copy the source's exact descendant attachments. + * @return Zero or negative errno. Staging traverses the original graph without + * recursion or pathname replay; on failure the graph and next ID are unchanged. + */ +static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, + const struct vfs_path *target,bool recursive) +{ + if(!ns || !ns->root || !vfs_path_valid(source) || !vfs_path_valid(target))return -EINVAL; + if(source->mount->ns!=ns || target->mount->ns!=ns)return -EXDEV; + if(source->dentry->node.type!=RELIEFOS_FS_TYPE_DIR || target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; + if(source->dentry->disconnected || target->dentry->disconnected)return -ENOENT; + if(vfs_covering(ns,target))return -EBUSY; + + struct vfs_path view=*source,point=*target; + struct vfs_mount *pending=NULL; + uint64_t next_id=ns->next_id; + int rc=0; + for(;;) { + if(!next_id){rc=-EOVERFLOW;break;} + struct vfs_mount *copy; + rc=vfs_bind_clone(&view,©); + if(rc)break; + copy->id=next_id++; + vfs_path_get(&point,©->point); + copy->next=pending;pending=copy; + if(!recursive)break; + + /* Walk the two trees in step. Their mountpoint dentries are shared; + * only the parent attachment changes. Never visit a staged clone. */ + struct vfs_mount *child=vfs_bind_child_mount(&view,ns->mounts); + while(!child && view.mount!=source->mount) { + struct vfs_mount *previous=view.mount; + copy=copy->point.mount; + view=(struct vfs_path){previous->point.mount,copy->root}; + child=vfs_bind_child_mount(&view,previous->next); + } + if(!child)break; + view=(struct vfs_path){child,child->root}; + point=(struct vfs_path){copy,child->point.dentry}; + } + if(rc) { + /* Reverse creation order always releases descendants before parents. */ + while(pending) { + struct vfs_mount *copy=pending;pending=copy->next; + vfs_path_put(©->point);vfs_mount_put(copy); + } + return rc; + } + + /* Transfer the staging references to the namespace in one commit. */ + struct vfs_mount **tail=&pending; + for(;*tail;tail=&(*tail)->next) { + (*tail)->ns=ns; + if(vfs_notify_mount_created)vfs_notify_mount_created(*tail); + } + *tail=ns->mounts;ns->mounts=pending;ns->next_id=next_id; + return 0; +} + +/** @brief Publish one directory view without copying submounts. + * @param ns Execution-owned namespace. @param source Retained source directory. + * @param target Retained destination directory. + * @return Zero or negative errno without partial publication. + */ +int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path *target) +{ + return vfs_bind_tree(ns,source,target,false); +} + +/** @brief Publish a directory view with independent copies of its submounts. + * @param ns Execution-owned namespace. @param source Retained subtree root. + * @param target Retained destination directory. + * @return Zero or negative errno without partial publication. + */ +int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *source, + const struct vfs_path *target) +{ + return vfs_bind_tree(ns,source,target,true); } int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path *target) diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index b75435aa..6098894f 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -530,6 +530,15 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount, */ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); +/** @brief Bind a directory and all attachments beneath it in one transaction. + * @param ns Execution-owned namespace containing both retained paths. + * @param source Directory that bounds the original mount subtree. + * @param target Uncovered destination directory in the same namespace. + * @return Zero or negative errno without publishing a partial tree. Each clone + * has an independent ID and mount policy but pins the original backing objects. + */ +int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *source, + const struct vfs_path *target); /** @brief Atomically move an attached subtree, preserving held paths and IDs. * @param ns Namespace under execution ownership. * @param source Held root of an attached mount, never the namespace base root. diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 48666f0a..f69e49d9 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -25,20 +25,23 @@ static int mount_move(struct vfs_namespace *ns,struct task *task,uint64_t source vfs_path_put(&from.path);vfs_path_put(&to.path);return rc; } -/** @brief Resolve and retain both endpoints of a nonrecursive directory bind. +/** @brief Resolve and retain both endpoints of a directory bind. * @param ns Authorized caller's execution-owned namespace. * @param task Caller with retry-stable user lookup operands. * @param source Required user source path. @param target Required user target. + * @param recursive True to clone submounts beneath the resolved source. * @return Zero or negative lookup/type/busy/allocation errno. Local paths * always retire; successful attachment retains the actual source objects. */ -static int mount_bind(struct vfs_namespace *ns,struct task *task,uint64_t source,uint64_t target) +static int mount_bind(struct vfs_namespace *ns,struct task *task,uint64_t source,uint64_t target, + bool recursive) { struct vfs_lookup_result from={0},to={0}; int rc=resolve_user_object_at_flags(ns,task,LINUX_AT_FDCWD,source,false,false,VFS_LOOKUP_FOLLOW,&from); if(!rc)storage_release_task_io(task->pid); if(!rc)rc=resolve_user_object_at_flags(ns,task,LINUX_AT_FDCWD,target,false,false,VFS_LOOKUP_FOLLOW,&to); - if(!rc)rc=vfs_mount_bind(ns,&from.path,&to.path); + if(!rc)rc=recursive ? vfs_mount_bind_recursive(ns,&from.path,&to.path) : + vfs_mount_bind(ns,&from.path,&to.path); vfs_path_put(&from.path);vfs_path_put(&to.path);return rc; } @@ -186,7 +189,8 @@ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_ a3&=~MS_SILENT; if(a3&MS_REMOUNT)return mount_remount(ns,task,a1,a3&~MS_REMOUNT,a4); if(a3&MS_MOVE)return a3!=MS_MOVE ? -RELIEFOS_EOPNOTSUPP : mount_move(ns,task,a0,a1); - if(a3&MS_BIND)return a3!=MS_BIND ? -RELIEFOS_EOPNOTSUPP : mount_bind(ns,task,a0,a1); + if(a3&MS_BIND)return a3&~(MS_BIND|MS_REC) ? -RELIEFOS_EOPNOTSUPP : + mount_bind(ns,task,a0,a1,(a3&MS_REC)!=0); const uint64_t supported=MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_SYNCHRONOUS|MS_DIRSYNC| MS_NOATIME|MS_NODIRATIME|MS_RELATIME|MS_STRICTATIME|MS_LAZYTIME; if(a3&~supported)return -RELIEFOS_EOPNOTSUPP; diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 9c72dd03..520cbe37 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2866,7 +2866,6 @@ static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pat assert(vfs_path_mount_flags(&mounted)&MS_RDONLY); assert(vfs_path_mount_flags(&mounted)&MS_RELATIME);vfs_path_put(&mounted); strcpy(user.source,"/syscall-source");strcpy(user.target,"/syscall-destination"); - assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,source,target,UINT64_MAX,MS_BIND|MS_REC,UINT64_MAX)==-EOPNOTSUPP); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,source,target,UINT64_MAX,MS_BIND|MS_SILENT,UINT64_MAX)); assert(!vfs_path_lookup(ns,root,root,user.target,0,&mounted)); assert(vfs_path_context(&mounted)==volume); @@ -2900,6 +2899,75 @@ static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pat puts("PASS actual mount/remount/MS_MOVE/umount syscalls: scoped objects, capability, busy refs, atime preservation, ignored remount source/type and nofollow"); } +/** @brief Clone only the selected directory's mount topology, or publish none of it. + * @param ns Borrowed test-owned namespace. @param root Held root in that namespace. + * @param fs Base tmpfs in which to prepare the source, target and sibling points. + */ +static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_path *root, + struct tmpfs_super *fs) +{ + const char *directories[]={"/rbind-source","/rbind-source/view","/rbind-source/view/child", + "/rbind-source/view/peer","/rbind-source/outside","/rbind-target"}; + for(unsigned i=0;inext_id; + bool attached=false; + for(int budget=0;budget<64;++budget) { + test_fail_heap_after=budget; + int64_t rc=scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,source,target,UINT64_MAX, + MS_BIND|MS_REC,UINT64_MAX); + test_fail_heap_after=-1; + if(!rc){attached=true;break;} + assert(rc==-ENOMEM); + struct vfs_path unchanged={0}; + assert(ns->next_id==next_id && !actor.lookup_scope.armed); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&unchanged)); + assert(vfs_path_equal(&unchanged,&point));vfs_path_put(&unchanged); + } + assert(attached && ns->next_id==next_id+4); + struct vfs_path bound={0},copy[3]={0}; + const char *copy_names[]={"/rbind-target/child","/rbind-target/child/deep","/rbind-target/peer"}; + assert(!vfs_path_lookup(ns,root,root,user.target,0,&bound)); + for(unsigned i=0;i<3;++i) { + assert(!vfs_path_lookup(ns,root,root,copy_names[i],0,©[i])); + assert(vfs_path_same_inode(©[i],&original[i])); + assert(vfs_path_mount_id(©[i])!=vfs_path_mount_id(&original[i])); + assert(vfs_path_mount_flags(©[i])==vfs_path_mount_flags(&original[i])); + } + assert(vfs_path_lookup(ns,root,root,"/rbind-target/outside",0,&(struct vfs_path){0})==-ENOENT); + assert(vfs_mount_unmount(ns,&bound)==-EBUSY); + assert(!vfs_mount_unmount(ns,©[1]));vfs_path_put(©[1]); + assert(!vfs_mount_unmount(ns,©[0]));vfs_path_put(©[0]); + assert(!vfs_mount_unmount(ns,©[2]));vfs_path_put(©[2]); + assert(!vfs_mount_unmount(ns,&bound));vfs_path_put(&bound); + for(unsigned i=4;i>0;--i) { + assert(!vfs_mount_unmount(ns,&original[i-1]));vfs_path_put(&original[i-1]); + } + vfs_path_put(&point);vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + lookup_user_base=lookup_user_bytes=0; + puts("PASS recursive bind: subdirectory boundary, sibling/nested topology, distinct policies and OOM rollback"); +} + /** @brief Check real deferred-script rewriting, final DAC and OOM ownership. * @param fs Borrowed initial memory filesystem with no published namespace. * @return None. Uses actual namei/inodes/script parser, retires every task @@ -3005,6 +3073,7 @@ int main(int argc,char **argv) runtime_failed_teardown(); runtime_attachment_policies(&ns,&root); runtime_mount_syscalls(&ns,&root,fs); + runtime_recursive_bind(&ns,&root,fs); device_mount_objects(&ns,&root,fs); assert(!vfs_path_lookup(&ns,&root,&root,"mnt",VFS_LOOKUP_FOLLOW,&old_dir)); assert(!vfs_path_lookup(&ns,&root,&old_dir,"old",VFS_LOOKUP_FOLLOW,&old_file)); From 240945d029160c3bf29209b7de3f4fde6ac81184 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sat, 28 Nov 2026 23:16:53 +0800 Subject: [PATCH 06/97] feat(vfs): support per-mount bind remount policy --- .../en/LC_MESSAGES/userspace-api/abi.po | 12 ++- .../ja/LC_MESSAGES/userspace-api/abi.po | 10 +- Documentation/userspace-api/abi.rst | 11 +- fs/vfs/file.c | 23 ++++ fs/vfs/mount_internal.h | 1 + fs/vfs/mount_tree.c | 24 +++++ include/reliefnt/mount.h | 20 ++++ include/reliefnt/syscall_internal.h | 6 +- include/reliefnt/task/types.h | 1 + kernel/syscall/fd/descriptor.c | 10 +- kernel/syscall/fd/open.c | 43 ++++---- kernel/syscall/fs/mount.c | 28 ++++- tools/test_mount_backend.py | 2 +- tools/tests/mount_backend_test.c | 101 ++++++++++++++++++ 14 files changed, 254 insertions(+), 38 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index de6b43d6..bc77b925 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -77,10 +77,14 @@ msgstr "" "changes do not propagate. Preparation failure leaves the destination tree" " and existing mounts unchanged." -msgid "文件绑定和 bind remount 尚不支持,返回明确错误。" -msgstr "" -"File binds and bind remounts are not yet supported and return explicit " -"errors." +msgid "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" +msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` only changes the policy at the target mountpoint. It does not read the source, type, or filesystem options. The source mount, submounts, and shared filesystem are unchanged. Omitted atime options preserve the existing policy. If the shared filesystem is read-only, clearing the mountpoint's read-only flag does not make it writable." + +msgid "只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。" +msgstr "A readonly transition returns EBUSY without changing policy while any regular file is open for writing on the target mount. References to the same open file description from dup, fork, and file mappings extend that restriction. Writers on other mounts and O_PATH-only handles do not block the transition." + +msgid "文件绑定尚不支持,返回明确错误。" +msgstr "File binds are not yet supported and return an explicit error." msgid "按任务选择 uname 系统名" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 87ad1688..f3999d43 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -67,8 +67,14 @@ msgstr "" "と独立したポリシーが割り当てられますが、それぞれ元の inode " "とファイルシステムを共有します。元ディレクトリー外のマウントは複製されず、後から行った構造の変更も伝播しません。準備に失敗しても複製先のツリーと既存のマウントは変化しません。" -msgid "文件绑定和 bind remount 尚不支持,返回明确错误。" -msgstr "ファイルのバインドと bind remount にはまだ対応せず、明示的なエラーを返します。" +msgid "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" +msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` は対象マウントポイントのポリシーだけを変更します。ソース、タイプ、ファイルシステムのオプションは読み取りません。元のマウント、子マウント、共有ファイルシステムは変化しません。atime オプションを省略すると既存のポリシーが維持されます。共有ファイルシステムが読み取り専用である場合、マウントポイントの読み取り専用フラグを解除しても書き込み可能にはなりません。" + +msgid "只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。" +msgstr "対象マウント上の通常ファイルが書き込み用に開かれている間、読み取り専用への切り替えはポリシーを変更せず EBUSY を返します。dup、fork、ファイルマッピングが同じオープンファイル記述を保持する間もこの制限は続きます。他のマウントの書き込み元や O_PATH だけのハンドルは切り替えを妨げません。" + +msgid "文件绑定尚不支持,返回明确错误。" +msgstr "ファイルのバインドにはまだ対応せず、明示的なエラーを返します。" msgid "按任务选择 uname 系统名" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 069ee549..faa83917 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -50,7 +50,16 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载不复制, 后续拓扑变更也不会传播。准备失败时目的树和现有挂载保持原样。 -文件绑定和 bind remount 尚不支持,返回明确错误。 +``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` +只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 +文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 +挂载点的只读标志不会使其可写。 + +只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 +dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 +或仅持有 O_PATH 不会阻止此转换。 + +文件绑定尚不支持,返回明确错误。 glibc 线程与 CPU 状态兼容 ========================= diff --git a/fs/vfs/file.c b/fs/vfs/file.c index 51f7c8cb..60939383 100644 --- a/fs/vfs/file.c +++ b/fs/vfs/file.c @@ -139,6 +139,29 @@ int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags) mount->policy=vfs_policy_bits(flags);return 0; } +/** @brief Change only the exact attached root's policy for MS_BIND|MS_REMOUNT. + * @param path Borrowed retained mount root, not an interior dentry. + * @param flags Remount flags without MS_BIND and MS_REMOUNT. Supported shared + * policy bits and MS_REC are ignored; no submount or superblock is changed. + * @return Zero, EINVAL for a non-mount root, EOPNOTSUPP for unsupported flags, + * or EBUSY for a readonly transition with local writers. Validation and + * policy publication are serialized by execution ownership, with no backend + * reconfiguration. Omitted atime flags preserve the attachment's selection. + */ +int vfs_path_bind_remount(const struct vfs_path *path,uint64_t flags) +{ + if(!vfs_path_valid(path) || !path->mount->ns || path->dentry!=path->mount->root)return -EINVAL; + if(flags&~(VFS_MOUNT_POLICY_MASK|VFS_SUPER_POLICY_MASK|MS_STRICTATIME|MS_REC))return -EOPNOTSUPP; + struct vfs_mount *mount=path->mount; + const uint64_t atime=MS_NOATIME|MS_NODIRATIME|MS_RELATIME; + if(!(flags&(atime|MS_STRICTATIME)))flags|=mount->policy&atime; + else if(flags&MS_NOATIME)flags&=~MS_RELATIME; + else flags|=MS_RELATIME; + uint64_t policy=vfs_policy_bits(flags); + if(mount->writers && (policy&MS_RDONLY) && !(vfs_path_mount_flags(path)&MS_RDONLY))return -EBUSY; + mount->policy=policy;return 0; +} + /** @brief Reconfigure the selected attachment after shared backend preparation. * @param path Borrowed actual attached filesystem root, required. * @param flags Requested supported MS flags; omitted atime preserves old bits. diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index f12ea812..b7a2f50e 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -31,6 +31,7 @@ struct vfs_mount { void *context; struct module *owner; uint64_t references,id,policy; + uint64_t writers; /* Open writable file descriptions on this attachment. */ char *source,*filesystem; uint64_t device; }; diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index ce538494..6f666a0d 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -85,6 +85,30 @@ void vfs_path_get(const struct vfs_path *source,struct vfs_path *out) *out=*source;++out->mount->references;++out->dentry->references; } +/** @brief Admit a writer on the exact attachment held by a regular-file OFD. + * @param path Borrowed retained path, held until the matching release. + * @return Zero, EINVAL for an invalid path, EROFS for either readonly layer, + * or EOVERFLOW. Execution ownership serializes admission with remount; this + * acquires no path, inode, backend write lease or allocation of its own. + */ +int vfs_path_write_get(const struct vfs_path *path) +{ + if(!vfs_path_valid(path))return -EINVAL; + struct vfs_mount *mount=path->mount; + if((mount->policy|vfs_super_flags(mount))&MS_RDONLY)return -EROFS; + if(mount->writers==UINT64_MAX)return -EOVERFLOW; + ++mount->writers;return 0; +} + +/** @brief Retire one attachment writer before giving up its holding path. + * @param path Live retained path whose attachment owns the writer charge. + * Execution ownership is required; no inode or path reference is consumed. + */ +void vfs_path_write_put(const struct vfs_path *path) +{ + --path->mount->writers; +} + /* The root has one permanent mount-owned reference. A child retains its * parent dentry once, independently of the number of paths to the child. */ void vfs_dentry_put(struct vfs_mount *mount,struct vfs_dentry *dentry) diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 6098894f..ca947416 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -248,6 +248,15 @@ int vfs_path_remount(const struct vfs_path *path,uint64_t flags); * Caller holds execution ownership and has checked CAP_SYS_ADMIN. */ int vfs_path_remount_options(const struct vfs_path *path,uint64_t flags,const char *options); +/** @brief Apply bind-remount flags only to the exact selected attachment. + * @param path Borrowed retained mount root under execution ownership. + * @param flags Requested flags without MS_BIND and MS_REMOUNT. + * Supported shared policy bits and MS_REC are ignored, as are submounts. + * @return Zero or negative errno, leaving policy unchanged on failure. A new + * readonly transition with writers on this attachment returns EBUSY; shared + * backend flags stay effective and no provider reconfiguration is invoked. + */ +int vfs_path_bind_remount(const struct vfs_path *path,uint64_t flags); struct vfs_boot_mount { const char *target; /* Transfer one detached owned mount only on success; callbacks/context @@ -313,6 +322,17 @@ int vfs_path_dirent_stat(const struct vfs_path *directory,const char *name,struc * @return Zero or negative errno; no namespace lookup or lock across I/O. */ int vfs_path_statfs(const struct vfs_path *path,struct linux_statfs_abi *out); +/** @brief Acquire one writer charge on a held regular file's attachment. + * @param path Borrowed path retained by the caller until vfs_path_write_put. + * @return Zero or negative errno. Execution ownership serializes access with + * per-mount policy changes; no additional path or inode reference is taken. + */ +int vfs_path_write_get(const struct vfs_path *path); +/** @brief Release the writer charge before dropping its path reference. + * @param path Retained path on which vfs_path_write_get succeeded. + * Caller holds execution ownership and consumes exactly one charge. + */ +void vfs_path_write_put(const struct vfs_path *path); /** @brief Write through a retained inode after caller DAC/writer admission. * @param path Borrowed file path retaining its provider. * @param offset Nonnegative byte offset. diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index 662c135b..b1e0fc0f 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -281,9 +281,11 @@ int task_file_reference(struct task_file *destination, struct task_file *source) struct task_file *task_file_get(struct task_file *source); /** @brief Bind an authorized held path to the canonical open-file description. - * @param file Live descriptor or canonical OFD under execution ownership. + * @param file Live descriptor or canonical OFD under execution ownership, + * without an active attachment writer charge. * @param path Borrowed path; NULL clears the previous binding. - * Takes the new reference before dropping the old one, without allocation. + * Ignores descriptions with an active writer charge. Otherwise takes the + * new reference before dropping the old one, without allocation. * Dup/fork/in-flight/VMA references share this one OFD-owned mount lifetime; * final close releases it after file/device callbacks. No graph lock is held. */ diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index 2526bbf6..54e203bb 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -134,6 +134,7 @@ struct task_file { struct vfs_open_file *provider_file; /* Optional state shared by this canonical OFD. */ struct character_file *character_file; /* Exact character provider owned once per canonical OFD. */ bool inode_write_access; /* One writable lease per canonical OFD. */ + bool mount_write_access; /* Writer charge against path_ref's attachment. */ bool notify_open; /* OPEN was published for this OFD; emit CLOSE only once. */ uint64_t offset; uint64_t aux; diff --git a/kernel/syscall/fd/descriptor.c b/kernel/syscall/fd/descriptor.c index a28ec941..3e418a9f 100644 --- a/kernel/syscall/fd/descriptor.c +++ b/kernel/syscall/fd/descriptor.c @@ -49,7 +49,8 @@ static void clear_task_files(struct task *task); * @note A final canonical release detaches weak epoll watches before releasing * OFD-owned resources. SCM queue and in-flight I/O references use this same path. * Captured provider state closes before its inode/path/code can retire. Caller - * holds execution ownership without graph/scheduler/module locks across cleanup. + * holds execution ownership without graph/scheduler/module locks across cleanup; + * the attachment writer charge ends before its OFD-owned path is released. */ int clear_task_file_result(struct task_file *file) { @@ -112,6 +113,8 @@ int clear_task_file_result(struct task_file *file) file->aux2 != 0) { input_evdev_release(file->node.first_cluster, file->aux2); } + if(file->mount_write_access)vfs_path_write_put(&file->path_ref); + file->mount_write_access=false; vfs_path_put(&file->path_ref); file->used = 0; file->kind = 0; @@ -221,14 +224,15 @@ struct task_file *task_file_get(struct task_file *source) } /** @brief Give a canonical OFD an independent reference to its actual path. - * @param file Live descriptor or canonical OFD, borrowed under execution ownership. + * @param file Live descriptor or canonical OFD without an attachment writer + * charge, borrowed under execution ownership. * @param path Borrowed held path or NULL to detach a former binding. * Retains before releasing, so rebinding to the same pair is safe. No allocation; * final backend release may perform I/O and runs without a mount graph lock. */ void task_file_bind_path(struct task_file *file,const struct vfs_path *path) { - file=task_file_description(file);if(!file || !file->used)return; + file=task_file_description(file);if(!file || !file->used || file->mount_write_access)return; struct vfs_path next={0};vfs_path_get(path,&next); struct vfs_path old=file->path_ref;file->path_ref=next;vfs_path_put(&old); } diff --git a/kernel/syscall/fd/open.c b/kernel/syscall/fd/open.c index c1406b02..2bcaf3e9 100644 --- a/kernel/syscall/fd/open.c +++ b/kernel/syscall/fd/open.c @@ -39,35 +39,35 @@ static int open_truncate_inode(struct task_file *file) * @param flags Sanitized native flags, including private O_PATH translation. * @param diagnostic Optional display name; never used for inode I/O. * @return Descriptor or negative errno with complete rollback. Writer admission - * precedes truncation, including the temporary lease for O_RDONLY|O_TRUNC. - * Optional provider capture belongs to this canonical OFD and rolls back on - * every failure. O_PATH never captures, truncates or acquires a writer lease. + * precedes truncation. A writable regular description owns its attachment's + * writer charge, even without provider-private state. Optional provider state + * and the charge roll back together. O_PATH acquires neither and never truncates. * No graph/module lock spans provider callbacks or I/O. */ static int open_inode_path(struct task *task,const struct vfs_path *path,uint32_t flags, const char *diagnostic) { const struct storage_node *node=vfs_path_node(path); - int fd; - if(node->flags&STORAGE_NODE_FLAG_MEMFD) { - struct task_file *file=NULL;fd=task_allocate_fd(task,0,&file);if(fd<0)return fd; + struct task_file *file=NULL; + bool shmem=(node->flags&STORAGE_NODE_FLAG_MEMFD)!=0; + int fd,rc=0; + if(shmem) { + fd=task_allocate_fd(task,0,&file);if(fd<0)return fd; file->flags=flags;file->fd_flags=flags&LINUX_O_CLOEXEC ? RELIEFOS_FD_CLOEXEC : 0; - int rc=task_shm_reopen(file,path); - if(!rc && !(flags&TASK_FILE_FLAG_PATH) && (flags&LINUX_O_TRUNC))rc=open_truncate_inode(file); - if(rc){task_discard_file_fd(task,fd);return rc;} - return fd; - } - fd=alloc_task_fd(task,node,flags,diagnostic); - if(fd<0){return fd;} - struct task_file *file=task_file_for_fd(task,fd);task_file_bind_path(file,path); - if(!(flags&TASK_FILE_FLAG_PATH)) { - int rc=vfs_file_open(path,flags,&file->provider_file); - if(rc){task_discard_file_fd(task,fd);return rc;} + rc=task_shm_reopen(file,path); + } else { + fd=alloc_task_fd(task,node,flags,diagnostic);if(fd<0)return fd; + file=task_file_for_fd(task,fd);task_file_bind_path(file,path); } - if(!(flags&TASK_FILE_FLAG_PATH) && node->type==RELIEFOS_FS_TYPE_FILE && (flags&LINUX_O_TRUNC)) { - int rc=open_truncate_inode(file); - if(rc){task_discard_file_fd(task,fd);return rc;} + if(!rc && !(flags&TASK_FILE_FLAG_PATH)) { + if(node->type==RELIEFOS_FS_TYPE_FILE && file_can_write(file)) { + rc=vfs_path_write_get(&file->path_ref); + if(!rc)file->mount_write_access=true; + } + if(!rc && !shmem)rc=vfs_file_open(path,flags,&file->provider_file); + if(!rc && node->type==RELIEFOS_FS_TYPE_FILE && (flags&LINUX_O_TRUNC))rc=open_truncate_inode(file); } + if(rc){task_discard_file_fd(task,fd);return rc;} return fd; } @@ -81,7 +81,8 @@ static int open_inode_path(struct task *task,const struct vfs_path *path,uint32_ * @return Descriptor, negative errno or FIFO blocking sentinel. Existing * O_CREAT files keep their metadata; dangling links create at their actual * target, O_EXCL never follows the final link, and O_PATH avoids inode/device - * open side effects. Every published OFD retains its mount before final puts. + * open side effects. A writable regular OFD holds a writer charge on its + * selected attachment until the last reference retires. */ int64_t syscall_open_object(struct vfs_namespace *ns,struct task *task,int32_t dirfd, uint64_t pathname,uint32_t flags,uint32_t mode) diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index f69e49d9..6936cbfb 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -72,6 +72,22 @@ static int mount_unmount(struct vfs_namespace *ns,struct task *task,uint64_t tar vfs_path_put(&found.path);return rc; } +/** @brief Resolve only the target and apply bind-remount attachment policy. + * @param ns Borrowed execution-owned namespace. + * @param task Authorized caller with retry-stable lookup operands. + * @param target Required user mountpoint pathname. + * @param flags Final requested flags excluding MS_BIND and MS_REMOUNT. + * @return Zero or negative lookup/policy/busy errno. No source, filesystem + * type or data argument is read and the shared backend is not reconfigured. + */ +static int mount_bind_remount(struct vfs_namespace *ns,struct task *task,uint64_t target,uint64_t flags) +{ + struct vfs_lookup_result found={0}; + int rc=resolve_user_object_at_flags(ns,task,LINUX_AT_FDCWD,target,false,false,VFS_LOOKUP_FOLLOW,&found); + if(!rc)rc=vfs_path_bind_remount(&found.path,flags); + vfs_path_put(&found.path);return rc; +} + /** @brief Validate and apply policy to the actual selected filesystem root. * @param ns Borrowed execution-owned namespace. * @param task Authorized calling task with retry-stable lookup scope. @@ -168,12 +184,13 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * * @param ns Borrowed live namespace under execution ownership. * @param task Calling task, required; CAP_SYS_ADMIN checked before user input. * @param number Linux MOUNT or UMOUNT2 operation number. - * @param a0 User source/label, or unmount target pointer. + * @param a0 User source/label, or unmount target pointer; ignored for remount. * @param a1 Mount target pointer, or unmount low-32-bit flags. - * @param a2 User filesystem type; ignored for remount/move/unmount. + * @param a2 User filesystem type; ignored for bind/remount/move/unmount. * @param a3 Native mount flags; ignored for unmount. Legacy magic and the * MS_SILENT diagnostic hint never become attachment policy or move selectors. - * @param a4 Optional user mount data; ignored for unmount. + * @param a4 Optional user mount data; ignored for bind, bind remount, move + * and unmount. * @return Zero or negative Linux errno/internal EAGAIN. Text and lookup state * remain scope-owned across waits; temporary unscoped allocations are always * freed. The resulting graph owns backend lifetime, without target prefixes. @@ -187,7 +204,10 @@ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_ if(number!=LINUX_SYS_MOUNT)return -RELIEFOS_ENOSYS; if((a3&MS_MGC_MSK)==MS_MGC_VAL)a3&=~MS_MGC_MSK; a3&=~MS_SILENT; - if(a3&MS_REMOUNT)return mount_remount(ns,task,a1,a3&~MS_REMOUNT,a4); + if(a3&MS_REMOUNT) { + if(a3&MS_BIND)return mount_bind_remount(ns,task,a1,a3&~(MS_REMOUNT|MS_BIND)); + return mount_remount(ns,task,a1,a3&~MS_REMOUNT,a4); + } if(a3&MS_MOVE)return a3!=MS_MOVE ? -RELIEFOS_EOPNOTSUPP : mount_move(ns,task,a0,a1); if(a3&MS_BIND)return a3&~(MS_BIND|MS_REC) ? -RELIEFOS_EOPNOTSUPP : mount_bind(ns,task,a0,a1,(a3&MS_REC)!=0); diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index a68bb612..e466539e 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -26,7 +26,7 @@ def test_real_tmpfs_without_text_routing(self): "fs/notify/core.c", "fs/notify/limits.c", "fs/notify/queue.c", "fs/notify/watch.c", "fs/vfs/filesystems.c", "fs/vfs/filesystem_instance.c", "fs/ext_common/journal.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/kernel_file.c", "fs/vfs/kernel_path.c", "fs/vfs/exec_file.c", "fs/vfs/attributes.c", "fs/vfs/initial.c", "fs/vfs/storage_initial.c", "fs/vfs/storage_attributes.c", "fs/vfs/storage_access.c", "fs/vfs/storage_backend.c", "fs/vfs/mutation.c", "fs/vfs/storage_mutation.c", "fs/vfs/storage_create.c", "fs/vfs/storage_security.c", "fs/vfs/write_access.c", "fs/devpts/devpts.c", "drivers/tty/pty/core.c", "drivers/tty/pty/ring.c", "drivers/tty/pty/line_discipline.c", "drivers/tty/pty/session.c", "drivers/tty/pty/vt.c", "kernel/syscall/device/device_open.c", "kernel/syscall/device/device_io.c", "kernel/syscall/fs/stat.c", "fs/vfs/storage_mount.c", "fs/vfs/fat_options.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/security/access.c", "lib/text_utf16.c", "fs/devfs/mount.c", "fs/devfs/devtmpfs.c", "fs/devfs/devtmpfs_nodes.c", "fs/devfs/device.c", "fs/devfs/identity.c", "fs/vfs/pseudo.c", "kernel/exec/runtime.c", "kernel/exec/pending.c", "kernel/syscall/process/exec.c", "kernel/syscall/system/user_string.c", - "kernel/syscall/ipc/unix_path.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/create.c", "kernel/syscall/fs/mount.c", "kernel/syscall/fs/mutation.c", "kernel/syscall/fs/directory.c", "kernel/syscall/fs/size.c", "kernel/syscall/fs/sync.c", "kernel/syscall/fs/path.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fd/descriptor.c", "kernel/device/character.c", "kernel/syscall/io/vector.c", "kernel/syscall/fd/pty_descriptor.c", "kernel/sched/tables.c", "kernel/device/mapping.c", "kernel/sched/fs.c", "kernel/sync/wait.c", "-o", str(binary) + "kernel/syscall/ipc/unix_path.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/create.c", "kernel/syscall/fs/mount.c", "kernel/syscall/fs/mutation.c", "kernel/syscall/fs/directory.c", "kernel/syscall/fs/size.c", "kernel/syscall/fs/sync.c", "kernel/syscall/fs/path.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fd/descriptor.c", "kernel/syscall/fd/open.c", "kernel/device/character.c", "kernel/syscall/io/vector.c", "kernel/syscall/fd/pty_descriptor.c", "kernel/sched/tables.c", "kernel/device/mapping.c", "kernel/sched/fs.c", "kernel/sync/wait.c", "-o", str(binary) ], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=20) for filesystem in ("ext2", "ext4"): diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 520cbe37..ea23cf1e 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -270,6 +270,19 @@ void task_socket_collect(void) {} /* The device entry point must route these tests to a real PTY endpoint. */ int task_shm_attach(struct task_file *file, uint32_t size) { (void)file; (void)size; abort(); } +/** @brief Reject anonymous shmem in the regular-file mount fixture. + * @param file Unexpected destination OFD. @param path Unexpected memfd path. + * @return Does not return; the fixture does not create a memfd. + */ +int task_shm_reopen(struct task_file *file,const struct vfs_path *path) +{ (void)file; (void)path; abort(); } +/** @brief Reject FIFO rendezvous in the regular-file mount fixture. + * @param task Unexpected caller. @param node Unexpected FIFO, nullable on retry. + * @param flags Unexpected open flags. @param path Unexpected diagnostic name. + * @return Does not return; the fixture does not open FIFOs. + */ +int task_fifo_open(struct task *task,const struct storage_node *node,uint32_t flags,const char *path) +{ (void)task; (void)node; (void)flags; (void)path; abort(); } uint64_t input_evdev_cursor_now(void) { abort(); } uint32_t task_evdev_vt_hint(const struct task *task) { (void)task; abort(); } @@ -2968,6 +2981,93 @@ static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_pat puts("PASS recursive bind: subdirectory boundary, sibling/nested topology, distinct policies and OOM rollback"); } +/** @brief Exercise per-attachment bind remount and canonical OFD writer lifetime. + * @param ns Borrowed test namespace with both source and destination visible. + * @param root Held namespace root. @param fs Base tmpfs for fixture mountpoints. + */ +static void runtime_bind_remount(struct vfs_namespace *ns,const struct vfs_path *root, + struct tmpfs_super *fs) +{ + struct { + char source[32],target[32],source_file[40],target_file[40]; + } user={"/bind-remount-source","/bind-remount-target", + "/bind-remount-source/data","/bind-remount-target/data"}; + assert(!tmpfs_create(fs,user.source,LINUX_S_IFDIR|0755,NULL,NULL)); + assert(!tmpfs_create(fs,user.target,LINUX_S_IFDIR|0755,NULL,NULL)); + struct task actor={.pid=905,.fsuid=1000,.fsgid=1000,.cap_effective=1ULL<nofile.rlim_cur=32; + vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + uint64_t source=(uintptr_t)user.source,target=(uintptr_t)user.target; + const uint64_t remount=MS_BIND|MS_REMOUNT; + struct vfs_path point={0},original={0},bound={0},child={0}; + struct vfs_mount *mount=NULL; + assert(!vfs_path_lookup(ns,root,root,user.source,0,&point)); + assert(!storage_new_tmpfs_mount("bind-fixture",MS_NOATIME,"size=32768",1000,1000,&mount)); + assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); + assert(!vfs_path_lookup(ns,root,root,user.source,0,&original)); + struct reliefos_permissions mode={0600,1000,1000}; + assert(!vfs_path_new_file(&original,"data",&mode,&point));vfs_path_put(&point); + mode.mode=0755; + assert(!vfs_path_create_node(&original,"child",LINUX_S_IFDIR,&mode,NULL,&point)); + assert(!storage_new_tmpfs_mount("bind-child",MS_RELATIME,NULL,1000,1000,&mount)); + assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,source,target,UINT64_MAX,MS_BIND|MS_REC,UINT64_MAX)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&bound)); + assert(!vfs_path_lookup(ns,root,&bound,"child",0,&child)); + + int source_fd=syscall_open_object(ns,&actor,LINUX_AT_FDCWD,(uintptr_t)user.source_file,LINUX_O_RDWR,0); + int path_fd=syscall_open_object(ns,&actor,LINUX_AT_FDCWD,(uintptr_t)user.target_file,LINUX_O_PATH,0); + assert(source_fd>=0 && path_fd>=0); + const uint64_t policy=MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC; + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,UINT64_MAX,target,UINT64_MAX, + remount|policy|MS_SYNCHRONOUS|MS_REC,UINT64_MAX)); + assert(vfs_path_mount_flags(&bound)==(policy|MS_NOATIME)); + assert(vfs_path_mount_flags(&original)==MS_NOATIME && vfs_path_mount_flags(&child)==MS_RELATIME); + struct linux_statfs_abi stats; + assert(!vfs_path_statfs(&bound,&stats) && stats.f_blocks==8 && + (stats.f_flags&~LINUX_ST_VALID)==(policy|MS_NOATIME)); + char table[4096];uint32_t count=0; + assert(!vfs_read_mount_table(ns,root,true,0,table,sizeof(table)-1,&count));table[count]=0; + assert(strstr(table," /bind-remount-target ro,nosuid,nodev,noexec,noatime - tmpfs bind-fixture rw\n")); + struct task_file *origin=task_file_for_fd(&actor,source_fd); + assert(!vfs_path_write(&origin->path_ref,0,"x",1,&count) && count==1); + assert(syscall_open_object(ns,&actor,LINUX_AT_FDCWD,(uintptr_t)user.target_file,LINUX_O_WRONLY,0)==-EROFS); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,(uintptr_t)user.target_file,0,remount,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,target,0,remount|MS_NODIRATIME,0)); + assert(vfs_path_mount_flags(&bound)==(MS_NODIRATIME|MS_RELATIME)); + + int fd=syscall_open_object(ns,&actor,LINUX_AT_FDCWD,(uintptr_t)user.target_file,LINUX_O_RDWR,0); + assert(fd>=0 && !task_file_for_fd(&actor,fd)->provider_file); + int duplicate=task_duplicate_file_fd(&actor,fd,0,0); + assert(duplicate>=0 && duplicate!=fd); + /* A mapping retains the canonical OFD with the same get/put pair. */ + struct task_file *mapping_pin=task_file_get(task_file_for_fd(&actor,duplicate));assert(mapping_pin); + task_discard_file_fd(&actor,fd); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,target,0,remount|policy,0)==-EBUSY); + task_discard_file_fd(&actor,duplicate); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,target,0,remount|policy,0)==-EBUSY); + assert(vfs_path_mount_flags(&bound)==(MS_NODIRATIME|MS_RELATIME)); + task_file_put(mapping_pin); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,target,0,remount|policy|MS_STRICTATIME,0)); + assert(vfs_path_mount_flags(&bound)==policy); + task_discard_file_fd(&actor,source_fd);task_discard_file_fd(&actor,path_fd); + + assert(!vfs_path_remount(&original,MS_RDONLY)); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,target,0,remount,0)); + assert(vfs_path_mount_flags(&bound)==MS_RDONLY && vfs_path_mount_flags(&child)==MS_RELATIME); + assert(!vfs_path_remount(&original,0)); + assert(!(vfs_path_mount_flags(&bound)&MS_RDONLY)); + assert(!vfs_mount_unmount(ns,&child));vfs_path_put(&child); + assert(!vfs_mount_unmount(ns,&bound));vfs_path_put(&bound); + assert(!vfs_path_lookup(ns,root,&original,"child",0,&child)); + assert(!vfs_mount_unmount(ns,&child));vfs_path_put(&child); + assert(!vfs_mount_unmount(ns,&original));vfs_path_put(&original); + vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + lookup_user_base=lookup_user_bytes=0; + puts("PASS bind remount: local policy, shared readonly, and stateless writer until final OFD put"); +} + /** @brief Check real deferred-script rewriting, final DAC and OOM ownership. * @param fs Borrowed initial memory filesystem with no published namespace. * @return None. Uses actual namei/inodes/script parser, retires every task @@ -3074,6 +3174,7 @@ int main(int argc,char **argv) runtime_attachment_policies(&ns,&root); runtime_mount_syscalls(&ns,&root,fs); runtime_recursive_bind(&ns,&root,fs); + runtime_bind_remount(&ns,&root,fs); device_mount_objects(&ns,&root,fs); assert(!vfs_path_lookup(&ns,&root,&root,"mnt",VFS_LOOKUP_FOLLOW,&old_dir)); assert(!vfs_path_lookup(&ns,&root,&old_dir,"old",VFS_LOOKUP_FOLLOW,&old_file)); From 09db4088e91170c32cefebb43f72008d683e2331 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sat, 28 Nov 2026 23:38:09 +0800 Subject: [PATCH 07/97] feat(vfs): support lazy unmount of mount subtrees --- .../en/LC_MESSAGES/userspace-api/abi.po | 15 +++- .../ja/LC_MESSAGES/userspace-api/abi.po | 13 ++- Documentation/userspace-api/abi.rst | 14 ++- fs/vfs/dentry.c | 8 +- fs/vfs/file.c | 5 +- fs/vfs/mount_internal.h | 13 ++- fs/vfs/mount_tree.c | 66 ++++++++++++-- fs/vfs/mutation.c | 16 +++- fs/vfs/path.c | 53 ++++++++--- include/reliefnt/mount.h | 27 ++++-- kernel/syscall/fs/mount.c | 19 ++-- tools/tests/mount_backend_test.c | 89 ++++++++++++++++++- 12 files changed, 289 insertions(+), 49 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index bc77b925..ceec5ffa 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -55,7 +55,7 @@ msgid "" "``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录绑定。 新挂载保留源目录的实际 " "inode、父链和文件系统生命周期,继承源挂载的 只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 " "root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 " -"源文件系统在绑定仍存在时不能卸载,解绑不销毁源文件系统。" +"源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" msgstr "" "``mount(source, target, NULL, MS_BIND, NULL)`` supports nonrecursive " "directory binds. The new mount retains the source directory's actual " @@ -63,8 +63,8 @@ msgstr "" "policies such as read-only, nosuid, and nodev. The root field of " "``/proc/self/mountinfo`` reports the source directory's path within its " "filesystem; namespace paths, ``..``, and chroot boundaries are computed " -"relative to the new mount. The source filesystem cannot be unmounted " -"while the bind remains, and unbinding does not destroy it." +"relative to the new mount. The source filesystem cannot be ordinarily " +"unmounted while the bind remains, and unbinding does not destroy it." msgid "" "``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 " @@ -102,6 +102,15 @@ msgstr "``RELIEFOS_PR_GET_UNAME_LINUX`` (``0x52550002``): all arguments must be msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" msgstr "Invalid values and nonzero reserved arguments return EINVAL without changing state. New tasks use ReliefNT by default. fork, vfork, and clone copy the calling task's selection, and exec preserves it. Other existing tasks are unaffected; threads may also set their selection independently. The switch changes only the ``sysname`` returned by ``uname(2)`` to Linux; other fields, global UTS state, and procfs are unchanged. Both the standard libc prctl wrapper and raw syscalls are supported. Linux personality values retain their existing meaning." +msgid "延迟卸载" +msgstr "Lazy Unmount" + +msgid "``umount2(target, MNT_DETACH)`` 立即移除目标挂载及其子挂载的命名空间连接, 不等待持有者或同步刷盘。新的路径查找会看到原挂载点下的内容,挂载表不再列出 已摘除的挂载。永久的命名空间基准根不可摘除。" +msgstr "``umount2(target, MNT_DETACH)`` immediately disconnects the target and its submounts from the namespace without waiting for references or synchronously flushing data. Fresh lookups see the original contents beneath the mountpoint, and the mount table no longer lists the detached mounts. The permanent namespace anchor cannot be detached." + +msgid "已打开的文件及持有的目录仍可使用,子挂载的独立引用亦有效。从保留的目录开始 查找时不再跨越被摘除的挂载边,``..`` 不越过已摘除的挂载根。当工作目录不再 连接到任务根时,原始 ``getcwd`` 返回以 ``(unreachable)`` 开头的路径。 最后的引用释放后由 VFS 工作队列完成文件系统清理。" +msgstr "Open files and retained directories remain usable, including independent references to submounts. Lookups starting from a retained directory no longer cross the detached mount edges, and ``..`` stops at the detached mount root. If the working directory is no longer connected to the task root, raw ``getcwd`` returns a path prefixed with ``(unreachable)``. The VFS work queue completes filesystem cleanup after the last reference is released." + msgid "glibc 线程与 CPU 状态兼容" msgstr "glibc thread and CPU-state compatibility" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index f3999d43..6ab419fe 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -50,14 +50,14 @@ msgid "" "``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录绑定。 新挂载保留源目录的实际 " "inode、父链和文件系统生命周期,继承源挂载的 只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 " "root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 " -"源文件系统在绑定仍存在时不能卸载,解绑不销毁源文件系统。" +"源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" msgstr "" "``mount(source, target, NULL, MS_BIND, NULL)`` " "は非再帰のディレクトリーバインドに対応します。新しいマウントは元ディレクトリーの実際の " "inode、親チェーン、ファイルシステムのライフサイクルを保持し、元マウントの読み取り専用、nosuid、nodev " "などの方針を継承します。``/proc/self/mountinfo`` の root " "フィールドは元ディレクトリーのファイルシステム内のパスを報告し、名前空間のパス、``..``、chroot " -"境界は新マウントを基準に計算します。バインドが残る間は元ファイルシステムをアンマウントできず、バインド解除で元ファイルシステムを破棄することもありません。" +"境界は新マウントを基準に計算します。バインドが残る間は元ファイルシステムの通常のアンマウントはできず、バインド解除で元ファイルシステムを破棄することもありません。" msgid "" "``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 " @@ -92,6 +92,15 @@ msgstr "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):すべての引数 msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" msgstr "不正な値やゼロ以外の予約引数には、状態を変更せず EINVAL を返します。新しいタスクは既定で ReliefNT を使用します。fork、vfork、clone は呼び出しタスクの選択をコピーし、exec は選択を保持します。既存の別タスクは影響を受けず、スレッドも独立に選択できます。このスイッチは ``uname(2)`` の ``sysname`` だけを Linux に変更し、他のフィールド、グローバルな UTS 状態、procfs は変更しません。標準 libc の prctl ラッパーとシステムコールの直接呼び出しに対応し、personality 値の意味は変更しません。" +msgid "延迟卸载" +msgstr "遅延アンマウント" + +msgid "``umount2(target, MNT_DETACH)`` 立即移除目标挂载及其子挂载的命名空间连接, 不等待持有者或同步刷盘。新的路径查找会看到原挂载点下的内容,挂载表不再列出 已摘除的挂载。永久的命名空间基准根不可摘除。" +msgstr "``umount2(target, MNT_DETACH)`` は、参照の解放や同期フラッシュを待たずに、対象とその子マウントを名前空間から直ちに切り離します。新しいパス検索ではマウントポイントの元の内容が見え、切り離されたマウントはマウントテーブルに表示されません。名前空間の恒久的な基準ルートは切り離せません。" + +msgid "已打开的文件及持有的目录仍可使用,子挂载的独立引用亦有效。从保留的目录开始 查找时不再跨越被摘除的挂载边,``..`` 不越过已摘除的挂载根。当工作目录不再 连接到任务根时,原始 ``getcwd`` 返回以 ``(unreachable)`` 开头的路径。 最后的引用释放后由 VFS 工作队列完成文件系统清理。" +msgstr "開いたファイルと保持中のディレクトリは、子マウントへの独立した参照も含めて引き続き使用できます。保持したディレクトリからの検索は切り離されたマウント境界を通過せず、``..`` は切り離されたマウントのルートで止まります。作業ディレクトリがタスクのルートにつながっていない場合、生の ``getcwd`` は ``(unreachable)`` で始まるパスを返します。最後の参照が解放された後、VFS のワークキューがファイルシステムの後処理を行います。" + msgid "glibc 线程与 CPU 状态兼容" msgstr "glibc のスレッドと CPU 状態の互換性" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index faa83917..3e0d46bf 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -44,7 +44,7 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 新挂载保留源目录的实际 inode、父链和文件系统生命周期,继承源挂载的 只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 -源文件系统在绑定仍存在时不能卸载,解绑不销毁源文件系统。 +源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。 ``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载不复制, @@ -61,6 +61,18 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 文件绑定尚不支持,返回明确错误。 +延迟卸载 +======== + +``umount2(target, MNT_DETACH)`` 立即移除目标挂载及其子挂载的命名空间连接, +不等待持有者或同步刷盘。新的路径查找会看到原挂载点下的内容,挂载表不再列出 +已摘除的挂载。永久的命名空间基准根不可摘除。 + +已打开的文件及持有的目录仍可使用,子挂载的独立引用亦有效。从保留的目录开始 +查找时不再跨越被摘除的挂载边,``..`` 不越过已摘除的挂载根。当工作目录不再 +连接到任务根时,原始 ``getcwd`` 返回以 ``(unreachable)`` 开头的路径。 +最后的引用释放后由 VFS 工作队列完成文件系统清理。 + glibc 线程与 CPU 状态兼容 ========================= diff --git a/fs/vfs/dentry.c b/fs/vfs/dentry.c index 3e8ca680..7a5642ea 100644 --- a/fs/vfs/dentry.c +++ b/fs/vfs/dentry.c @@ -26,13 +26,19 @@ void vfs_rename_abort(struct vfs_rename *change) kernel_free(change->name);kernel_free(change); } +/** @brief Prepare rename on one attachment, even if held after lazy detach. + * @param ns Borrowed execution-owned namespace. @param source Retained inode. + * @param parent Held destination directory on the same attachment. + * @param name Borrowed new basename. @param out Receives owned change on success. + * @return Zero or negative errno without mutating the source or destination. + */ int vfs_rename_prepare(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *parent,const char *name, struct vfs_rename **out) { if(!out)return -EINVAL;*out=NULL; if(!ns || !vfs_path_valid(source) || !vfs_path_valid(parent) || !name)return -EINVAL; - if(source->mount->ns!=ns || parent->mount->ns!=ns || source->mount!=parent->mount)return -EXDEV; + if(source->mount!=parent->mount || !vfs_path_walkable(ns,source))return -EXDEV; if(parent->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; if(source->dentry->disconnected || parent->dentry->disconnected)return -ENOENT; if(source->dentry==source->mount->root || vfs_path_covered(ns,source))return -EBUSY; diff --git a/fs/vfs/file.c b/fs/vfs/file.c index 60939383..f80cefcb 100644 --- a/fs/vfs/file.c +++ b/fs/vfs/file.c @@ -126,15 +126,16 @@ uint64_t vfs_path_mount_flags(const struct vfs_path *path) } /** @brief Configure a detached attachment without mutating its shared backend. - * @param mount Owned unpublished mount, required. + * @param mount Owned mount never published in a namespace, required. * @param flags Only per-mount bits and optional strictatime selector. * @return Zero or negative state/unsupported errno, preserving state on error. + * A lazily detached attachment keeps its policy until retirement. * Pure execution-owned publication, no callbacks/allocation/ownership change. */ int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags) { if(!mount || !mount->references)return -EINVAL; - if(mount->ns || mount->point.mount)return -EBUSY; + if(mount->ns || mount->point.mount || mount->lazy_detached)return -EBUSY; if(flags&~(VFS_MOUNT_POLICY_MASK|MS_STRICTATIME))return -EOPNOTSUPP; mount->policy=vfs_policy_bits(flags);return 0; } diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index b7a2f50e..256e7aeb 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -32,9 +32,21 @@ struct vfs_mount { struct module *owner; uint64_t references,id,policy; uint64_t writers; /* Open writable file descriptions on this attachment. */ + bool lazy_detached; /* No namespace edges; retained paths still work. */ char *source,*filesystem; uint64_t device; }; +bool vfs_path_valid(const struct vfs_path *path); +/** @brief Admit a held path for pathname access, not mount topology changes. + * @param ns Borrowed execution-owned lookup namespace. + * @param path Borrowed retained path, nullable. + * @return True for a member or a previously attached mount now detached. + * Unpublished mounts and live mounts in an unrelated namespace are excluded. + */ +static inline bool vfs_path_walkable(const struct vfs_namespace *ns,const struct vfs_path *path) +{ + return ns && vfs_path_valid(path) && (path->mount->ns==ns || path->mount->lazy_detached); +} /** @brief Normalize supported attachment input independently of its backend. * @param flags Native MS inputs; unsupported bits have no representation here. * @return Canonical mount bits. Strictatime clears both noatime and relatime, @@ -128,7 +140,6 @@ struct vfs_rename { }; /* All helpers require the caller's execution transaction. No internal spinlock * or backend callback is hidden behind a mount graph lock. */ -bool vfs_path_valid(const struct vfs_path *path); /** @brief Resolve a child for a retained walker, preserving its private * pre-I/O native-workspace marker. The walker owns final normalization. */ diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index 6f666a0d..e581eedc 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -129,8 +129,9 @@ void vfs_dentry_put(struct vfs_mount *mount,struct vfs_dentry *dentry) /** @brief Release final root ownership before finish or deferred reclamation. * @param mount Owned live reference or NULL, under execution ownership. - * @return None. Final failure transfers the rootless backend and provider pin - * to the private FIFO; no allocation or graph/module lock spans callbacks. + * @return None. Lazy detach and final finish failure transfer the rootless + * mount/provider pin to the FIFO; lazy detach never flushes in this path. + * No allocation or graph/module lock spans callbacks. */ void vfs_mount_put(struct vfs_mount *mount) { @@ -138,7 +139,7 @@ void vfs_mount_put(struct vfs_mount *mount) vfs_lookup_cache_purge(mount); if(!mount->bind_source.mount)vfs_dentry_put(mount,mount->root); mount->root=NULL; - if(!vfs_finish_retirement(mount))vfs_queue_retirement(mount); + if(mount->lazy_detached || !vfs_finish_retirement(mount))vfs_queue_retirement(mount); } void vfs_path_put(struct vfs_path *path) @@ -148,10 +149,16 @@ void vfs_path_put(struct vfs_path *path) vfs_dentry_put(old.mount,old.dentry);vfs_mount_put(old.mount); } +/** @brief Set diagnostic identity on an unpublished mount. + * @param mount Owned mount never published in a namespace. + * @param source Nonempty backing label. @param filesystem Nonempty type name. + * @param device Linux encoded device number. + * @return Zero or negative errno; a lazily detached mount cannot be renamed. + */ int vfs_mount_describe(struct vfs_mount *mount,const char *source,const char *filesystem,uint64_t device) { if(!mount || !source || !source[0] || !filesystem || !filesystem[0])return -EINVAL; - if(mount->ns || mount->point.mount)return -EBUSY; + if(mount->ns || mount->point.mount || mount->lazy_detached)return -EBUSY; size_t source_length=0,type_length=0; while(source[source_length])if(++source_length>=VFS_PATH_MAX)return -ENAMETOOLONG; while(filesystem[type_length]) { @@ -213,9 +220,13 @@ int vfs_path_anonymous(struct vfs_mount *mount,const struct storage_node *node,s struct vfs_path value={mount,dentry};vfs_path_get(&value,out);return 0; } +/** @brief Retain an unpublished mount as the permanent namespace anchor. + * @param ns Borrowed empty namespace. @param root Borrowed unpublished root. + * @return Zero or negative errno. Previously lazily detached roots are rejected. + */ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root) { - if(!ns || ns->root || ns->mounts || !root || root->ns || root->point.mount)return -EINVAL; + if(!ns || ns->root || ns->mounts || !root || root->ns || root->point.mount || root->lazy_detached)return -EINVAL; ++root->references;root->ns=ns;root->id=1;root->next=NULL; ns->root=root;ns->mounts=root;ns->next_id=2;return 0; } @@ -245,12 +256,19 @@ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out) vfs_follow_mounts(ns,out);return 0; } +/** @brief Publish an unused mount at an exact directory in the namespace. + * @param ns Borrowed execution-owned namespace. + * @param mount Caller-retained unpublished mount; membership takes its own ref. + * @param target Borrowed retained directory path in ns. + * @return Zero or negative errno, with no graph change on failure. A mount + * that was lazily detached is not eligible for reattachment. + */ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const struct vfs_path *target) { if(!ns || !ns->root || !mount || !vfs_path_valid(target))return -EINVAL; if(target->mount->ns!=ns)return -EXDEV; if(target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; - if(mount->ns || mount->point.mount || vfs_covering(ns,target))return -EBUSY; + if(mount->ns || mount->point.mount || mount->lazy_detached || vfs_covering(ns,target))return -EBUSY; if(!ns->next_id)return -EOVERFLOW; vfs_path_get(target,&mount->point);++mount->references; mount->ns=ns;mount->id=ns->next_id++; @@ -418,6 +436,34 @@ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path) vfs_mount_detach(ns,mount);return 0; } +/** @brief Disconnect a visible subtree before releasing any association. + * @param ns Borrowed namespace under execution ownership. + * @param path Held selected mount root, excluding the permanent anchor. + * @return Zero or negative errno before mutation. Retained paths keep their + * objects; no allocation, sync, busy preflight or final backend finish here. + */ +int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path) +{ + if(!ns || !vfs_path_valid(path))return -EINVAL; + struct vfs_mount *root=path->mount; + if(root->ns!=ns || path->dentry!=root->root)return -EINVAL; + if(root==ns->root || !root->point.mount)return -EBUSY; + + struct vfs_mount *detached=NULL,**link=&ns->mounts; + while(*link) { + struct vfs_mount *mount=*link,*ancestor=mount; + while(ancestor && ancestor!=root)ancestor=ancestor->point.mount; + if(!ancestor){link=&mount->next;continue;} + *link=mount->next;mount->next=detached;detached=mount; + mount->ns=NULL;mount->lazy_detached=true; + } + while(detached) { + struct vfs_mount *mount=detached;detached=mount->next;mount->next=NULL; + vfs_path_put(&mount->point);vfs_mount_put(mount); + } + return 0; +} + int vfs_namespace_destroy(struct vfs_namespace *ns) { if(!ns)return -EINVAL; @@ -510,6 +556,11 @@ int vfs_bind_child(const struct vfs_path *parent,const char *name, struct vfs_path value={mount,dentry};vfs_path_get(&value,out);return 0; } +/** @brief Walk one parent step across visible edges or stop at a detached root. + * @param root Borrowed task lookup boundary. + * @param path Owned current path, replaced with an equally owned parent. + * Unattached bind roots do not expose the backing dentry's outside parent. + */ void vfs_path_parent(const struct vfs_path *root,struct vfs_path *path) { if(vfs_path_equal(root,path))return; @@ -518,6 +569,7 @@ void vfs_path_parent(const struct vfs_path *root,struct vfs_path *path) next=next.mount->point; if(vfs_path_equal(root,&next))break; } - if(!vfs_path_equal(root,&next) && next.dentry->parent)next.dentry=next.dentry->parent; + if(!vfs_path_equal(root,&next) && next.dentry!=next.mount->root && next.dentry->parent) + next.dentry=next.dentry->parent; struct vfs_path owned={0};vfs_path_get(&next,&owned);vfs_path_put(path);*path=owned; } diff --git a/fs/vfs/mutation.c b/fs/vfs/mutation.c index 035e52ec..f0d11241 100644 --- a/fs/vfs/mutation.c +++ b/fs/vfs/mutation.c @@ -18,10 +18,16 @@ static unsigned vfs_notify_last_link(const struct vfs_path *path) return rc ? 2 : status.st_nlink<=1 ? 1 : 0; } +/** @brief Remove a retained member without crossing a mountpoint. + * @param ns Borrowed execution-owned namespace. @param path Retained member, + * possibly in an attachment retained after lazy detach. + * @param directory True for rmdir, false for unlink. + * @return Zero or negative policy/type/provider errno. + */ int vfs_path_remove(struct vfs_namespace *ns,const struct vfs_path *path,bool directory) { if(!ns || !vfs_path_valid(path))return -EINVAL; - if(path->mount->ns!=ns)return -EXDEV; + if(!vfs_path_walkable(ns,path))return -EXDEV; if(path->dentry->disconnected)return -ENOENT; if(path->dentry==path->mount->root || vfs_path_covered(ns,path))return -EBUSY; if((path->dentry->node.type==RELIEFOS_FS_TYPE_DIR)!=directory) @@ -67,12 +73,18 @@ int vfs_path_rename(struct vfs_namespace *ns,const struct vfs_path *source, vfs_rename_abort(change);return rc ? rc : -EIO; } +/** @brief Link a live inode within one writable attachment. + * @param ns Borrowed execution-owned namespace. @param source Retained inode. + * @param parent Retained directory on the same attachment; lazy detach does + * not revoke a held attachment. @param name Borrowed destination basename. + * @return Zero or negative preflight/provider errno. + */ int vfs_path_link(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *parent,const char *name) { if(!ns || !vfs_path_valid(source) || !vfs_path_valid(parent))return -EINVAL; if(source->dentry->node.type==RELIEFOS_FS_TYPE_DIR)return -EPERM; - if(source->mount!=parent->mount || source->mount->ns!=ns)return -EXDEV; + if(source->mount!=parent->mount || !vfs_path_walkable(ns,source))return -EXDEV; if(vfs_path_mount_flags(source)&MS_RDONLY)return -EROFS; struct vfs_path existing={0};int rc=vfs_path_lookup_child(parent,name,&existing); if(!rc){vfs_path_put(&existing);return -EEXIST;} diff --git a/fs/vfs/path.c b/fs/vfs/path.c index 9f1a8120..1057c881 100644 --- a/fs/vfs/path.c +++ b/fs/vfs/path.c @@ -31,15 +31,21 @@ void vfs_walk_cancel(struct vfs_walk **state) kernel_free(walk); } -/* Own all cursor text and objects before the first backend search/lookup. - * Only per-call policy callbacks are borrowed; no callback context survives - * EAGAIN. A retained current object never follows a newly added overmount. */ +/** @brief Own cursor text and paths before the first backend search/lookup. + * @param ns Borrowed execution-owned namespace. + * @param root Retained absolute lookup boundary, including detached roots. + * @param start Retained cwd or dirfd; relative access survives lazy detach. + * @param name Borrowed pathname. @param flags Validated lookup mode. + * @param state Receives the new owned cursor on success. + * @return Zero or negative errno. No callback context survives a wait and an + * already retained current object does not redirect through a new cover. + */ static int vfs_walk_new(struct vfs_namespace *ns,const struct vfs_path *root, const struct vfs_path *start,const char *name,unsigned flags, struct vfs_walk **state) { if(!ns || !vfs_path_valid(root) || !vfs_path_valid(start) || !name)return -EINVAL; - if(root->mount->ns!=ns || start->mount->ns!=ns)return -EXDEV; + if(!vfs_path_walkable(ns,root) || !vfs_path_walkable(ns,start))return -EXDEV; size_t length=vfs_path_length(name);if(length>=VFS_PATH_MAX)return -ENAMETOOLONG; if(!length)return -ENOENT; struct vfs_walk *walk=kernel_malloc(sizeof(*walk)); @@ -221,15 +227,30 @@ static int vfs_path_format_walk(const struct vfs_path *root,const struct vfs_pat __builtin_memmove(buffer,buffer+at,capacity-at);return 0; } +/** @brief Format a held path when connected to the specified lookup root. + * @param ns Borrowed execution-owned namespace. + * @param root Retained formatting boundary, possibly lazily detached. + * @param path Borrowed retained path. @param buffer Required output storage. + * @param capacity Bytes including NUL. + * @return Zero or negative errno; ENOENT when attachment edges do not connect. + */ int vfs_path_format(const struct vfs_namespace *ns,const struct vfs_path *root, const struct vfs_path *path,char *buffer,size_t capacity) { if(!buffer || !capacity)return -EINVAL;buffer[0]=0; if(!ns || !vfs_path_valid(root) || !vfs_path_valid(path))return -EINVAL; - if(root->mount->ns!=ns || path->mount->ns!=ns)return -EXDEV; + if(!vfs_path_walkable(ns,root) || !vfs_path_walkable(ns,path))return -EXDEV; return vfs_path_format_walk(root,path,buffer,capacity,false); } +/** @brief Format a proc/descriptor link without granting pathname access. + * @param ns Borrowed namespace, unnecessary for detached or anonymous paths. + * @param root Optional caller root for those paths, required for live names. + * @param path Actual retained object. @param buffer Required output storage. + * @param capacity Bytes including NUL and any deleted suffix. + * @return Zero or negative errno. A detached path is printed relative to its + * surviving mount root when not reachable from the caller root. + */ int vfs_path_format_link(const struct vfs_namespace *ns,const struct vfs_path *root, const struct vfs_path *path,char *buffer,size_t capacity) { @@ -238,11 +259,15 @@ int vfs_path_format_link(const struct vfs_namespace *ns,const struct vfs_path *r if(path->dentry!=path->mount->root && !path->dentry->name) return path->mount->ops->display_name ? path->mount->ops->display_name(path->mount->context, &path->dentry->node,buffer,capacity) : -EOPNOTSUPP; - if(!ns || !ns->root || !vfs_path_valid(root))return -EINVAL; - if(root->mount->ns!=ns || path->mount->ns!=ns)return -EXDEV; - int rc=vfs_path_format_walk(root,path,buffer,capacity,true); + bool detached=path->mount->lazy_detached; + if(!detached) { + if(!ns || !ns->root || !vfs_path_valid(root))return -EINVAL; + if(!vfs_path_walkable(ns,root) || path->mount->ns!=ns)return -EXDEV; + } + int rc=vfs_path_valid(root) ? vfs_path_format_walk(root,path,buffer,capacity,true) : -ENOENT; if(rc==-ENOENT) { - struct vfs_path anchor={ns->root,ns->root->root}; + struct vfs_mount *base=detached ? path->mount : ns->root; + struct vfs_path anchor={base,base->root}; rc=vfs_path_format_walk(&anchor,path,buffer,capacity,true); } if(!rc && path->dentry->disconnected) { @@ -263,6 +288,13 @@ int vfs_path_backend_name(const struct vfs_path *path,char *buffer,size_t capaci return vfs_path_format_walk(&root,&native,buffer,capacity,false); } +/** @brief Format the held cwd, including the unreachable detached case. + * @param ns Borrowed execution-owned namespace. @param root Owned task root. + * @param cwd Held current directory. @param buffer Required output storage. + * @param capacity Bytes including NUL and any unreachable prefix. + * @return Zero or negative errno. A detached cwd outside root uses its mount + * root rather than inventing a path back to the former attachment point. + */ int vfs_path_getcwd(const struct vfs_namespace *ns,const struct vfs_path *root, const struct vfs_path *cwd,char *buffer,size_t capacity) { @@ -272,7 +304,8 @@ int vfs_path_getcwd(const struct vfs_namespace *ns,const struct vfs_path *root, static const char marker[]="(unreachable)"; size_t prefix=sizeof(marker)-1; if(capacity<=prefix)return -ENAMETOOLONG; - struct vfs_path anchor={ns->root,ns->root->root}; + struct vfs_mount *base=cwd->mount->lazy_detached ? cwd->mount : ns->root; + struct vfs_path anchor={base,base->root}; rc=vfs_path_format(ns,&anchor,cwd,buffer+prefix,capacity-prefix); if(!rc)__builtin_memcpy(buffer,marker,prefix); else buffer[0]=0; diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index ca947416..ead3632f 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -188,7 +188,7 @@ bool vfs_path_same_inode(const struct vfs_path *left,const struct vfs_path *righ bool vfs_path_same_filesystem(const struct vfs_path *left,const struct vfs_path *right); /** @brief Borrow the shared namespace containing an owned path. * @param path Borrowed retained path, nullable; serialized task context. - * @return Namespace or NULL for an invalid/detached anonymous mount. The + * @return Namespace or NULL for an invalid path or detached mount. The * caller must retain its path and may not persist the bare pointer. No I/O, * graph traversal, locking or ownership transfer occurs. */ @@ -435,7 +435,7 @@ struct vfs_lookup_result { /** @brief Resolve a path or its creation parent with per-directory authorization. * @param ns Shared namespace under execution ownership. * @param root Held task root, used for absolute input/links and .. boundary. - * @param start Held cwd/dirfd for relative input. + * @param start Held cwd/dirfd for relative input, including a lazily detached mount. * @param name Kernel-owned NUL-terminated input, at most VFS_PATH_MAX-1 bytes. * @param policy Borrowed callback/context/flags; NULL follows links as kernel. * @param out Empty output; owns one path on success. PARENT returns the held @@ -489,7 +489,7 @@ int vfs_mount_new(const struct vfs_backend_ops *ops,void *context,struct module const struct storage_node *root,struct vfs_mount **out); /** @brief Drop an owned mount handle; retire its root before final teardown. * @param mount Owned reference or NULL; task context under execution ownership. - * A failed finish retains context/code in the detached core retirement queue. + * Lazy detach or a failed finish retains context/code in the retirement queue. * No allocation or graph/module lock spans finish/destroy callbacks. */ void vfs_mount_put(struct vfs_mount *mount); @@ -516,7 +516,7 @@ bool vfs_reclaim_pending(void); int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags); /** @brief Initialize an empty namespace, retaining its initial root mount. * @param ns Zero-initialized namespace owned by the caller. - * @param root Detached mount, borrowed and retained; caller keeps its handle. + * @param root Unpublished mount, borrowed and retained; caller keeps its handle. * @return Zero or negative errno, no change on failure. Serialized task context. */ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root); @@ -534,7 +534,7 @@ int vfs_namespace_destroy(struct vfs_namespace *ns); int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out); /** @brief Attach a detached mount at a directory object, retaining both sides. * @param ns Shared namespace under execution ownership. - * @param mount Detached mount; caller retains its own handle. + * @param mount Unpublished mount; caller retains its own handle. * @param target Held directory path in ns; an already covered slot is busy. * @return Zero or negative errno without partial publication. Task context. */ @@ -575,6 +575,13 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source, * success retains the caller's path until vfs_path_put, no forced free. */ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path); +/** @brief Lazily disconnect a mounted subtree without ordinary busy checking. + * @param ns Borrowed namespace under execution ownership. + * @param path Retained visible root of a mount, not the namespace anchor. + * @return Zero or negative errno. Held paths remain usable; final cleanup + * is deferred. No new allocations or synchronous backend flush on detach. + */ +int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path); /** @brief Prepare retained directory-name changes before a backend rename. * @param ns Shared namespace, serialized by the execution transaction. * @param source Held source dentry, excluding a mount root or covered point. @@ -744,6 +751,7 @@ int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t /** @brief Unlink/rmdir the exact retained directory member. * @param ns Borrowed shared namespace under execution ownership. * @param path Borrowed victim path retaining its parent, inode and provider. + * A previously detached but retained attachment remains usable. * @param directory Select rmdir rather than unlink type/empty checks. * @return Zero or negative errno. Caller authorizes parent/sticky policy. * Rejects mount roots/covered mountpoints, retains metadata before removal, @@ -811,9 +819,9 @@ int vfs_path_lookup(struct vfs_namespace *ns,const struct vfs_path *root, int vfs_path_format(const struct vfs_namespace *ns,const struct vfs_path *root, const struct vfs_path *path,char *buffer,size_t capacity); /** @brief Render a held object for proc magic-link diagnostics, like d_path. - * @param ns Borrowed shared namespace, nullable for an anonymous inode. - * @param root Held caller root; nullable for an anonymous inode. Paths outside - * it use the namespace base root. + * @param ns Borrowed namespace, nullable for anonymous or lazily detached paths. + * @param root Held caller root; nullable for those paths. Paths outside it + * use the namespace base root or the surviving detached mount root. * @param path Actual held object, including a renamed or unlinked dentry. * @param buffer Writable diagnostic output, empty on failure. * @param capacity Bytes including NUL and any deleted suffix. @@ -832,7 +840,8 @@ int vfs_path_format_link(const struct vfs_namespace *ns,const struct vfs_path *r * @param capacity Bytes including NUL; no truncated path is returned. * @return Zero or negative errno. Disconnected/deleted directories return * ENOENT; a still-linked cwd outside root is prefixed with (unreachable). - * Uses actual mount attachments, never replays a cached pathname or performs I/O. + * Detached cwd names are relative to their surviving mount root. Uses actual + * mount attachments, never replays a cached pathname or performs I/O. */ int vfs_path_getcwd(const struct vfs_namespace *ns,const struct vfs_path *root, const struct vfs_path *cwd,char *buffer,size_t capacity); diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 6936cbfb..76d9d5da 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -45,29 +45,28 @@ static int mount_bind(struct vfs_namespace *ns,struct task *task,uint64_t source vfs_path_put(&from.path);vfs_path_put(&to.path);return rc; } -/** @brief Sync and detach the selected topmost mount with real busy checking. +/** @brief Detach the selected visible mount; only ordinary unmount syncs. * @param ns Borrowed execution-owned namespace. * @param task Authorized caller retaining any retry scope. * @param target User target pathname pointer, required. * @param flags Low-32-bit Linux umount flags; nofollow is supported. - * @return Zero or input/unsupported/lookup/busy/provider errno. Lazy/forced/ - * expired unmount is explicitly unsupported. A sync wait keeps the original - * scope; after sync its redundant reference is retired before graph detach. - * The local path pins code/backing until all callbacks and cleanup finish. + * @return Zero or input/unsupported/lookup/busy/provider errno. MNT_DETACH + * immediately disconnects the subtree; forced/expire operations are unsupported. + * Only ordinary unmount can wait in sync; both discard redundant lookup refs + * before detaching. The local path pins the provider across the operation. */ static int mount_unmount(struct vfs_namespace *ns,struct task *task,uint64_t target,uint32_t flags) { if(flags&~(MNT_FORCE|MNT_DETACH|MNT_EXPIRE|UMOUNT_NOFOLLOW))return -RELIEFOS_EINVAL; - if(flags&(MNT_FORCE|MNT_DETACH|MNT_EXPIRE))return -RELIEFOS_EOPNOTSUPP; + if((flags&MNT_EXPIRE) && (flags&(MNT_FORCE|MNT_DETACH)))return -RELIEFOS_EINVAL; + if(flags&(MNT_FORCE|MNT_EXPIRE))return -RELIEFOS_EOPNOTSUPP; struct vfs_lookup_result found={0}; int rc=resolve_user_object_at_flags(ns,task,LINUX_AT_FDCWD,target,false,false, flags&UMOUNT_NOFOLLOW ? 0 : VFS_LOOKUP_FOLLOW,&found); - if(!rc) { - rc=vfs_path_sync(&found.path,true,false); - } + if(!rc && !(flags&MNT_DETACH))rc=vfs_path_sync(&found.path,true,false); if(!rc) { task_lookup_scope_cancel(task); - rc=vfs_mount_unmount(ns,&found.path); + rc=flags&MNT_DETACH ? vfs_mount_unmount_lazy(ns,&found.path) : vfs_mount_unmount(ns,&found.path); } vfs_path_put(&found.path);return rc; } diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index ea23cf1e..9b55dbd9 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2892,7 +2892,7 @@ static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pat assert(!vfs_path_lookup(ns,root,root,user.target,0,&mounted)); assert(vfs_path_context(&mounted)==volume && (vfs_path_mount_flags(&mounted)&MS_RDONLY));vfs_path_put(&mounted); assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,target,0x100,0,0,0)==-EINVAL); - assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,target,MNT_DETACH,0,0,0)==-EOPNOTSUPP); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,target,MNT_FORCE,0,0,0)==-EOPNOTSUPP); strcpy(user.source,"/syscall-link"); assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,source,UMOUNT_NOFOLLOW,0,0,0)==-EINVAL); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,source,0,0,0,0)); @@ -2981,6 +2981,92 @@ static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_pat puts("PASS recursive bind: subdirectory boundary, sibling/nested topology, distinct policies and OOM rollback"); } +/** @brief Verify lazy detach hides a mount tree without revoking retained paths. + * @param ns Borrowed namespace under fixture execution ownership. + * @param root Retained namespace anchor. @param fs Base tmpfs for the fixture. + */ +static void runtime_lazy_unmount(struct vfs_namespace *ns,const struct vfs_path *root, + struct tmpfs_super *fs) +{ + const struct reliefos_permissions mode={0755,1000,1000}; + const struct reliefos_permissions file_mode={0644,1000,1000}; + assert(!tmpfs_create(fs,"/lazy-root",LINUX_S_IFDIR|0755,NULL,NULL)); + assert(!tmpfs_create(fs,"/lazy-link",LINUX_S_IFLNK|0777,"lazy-root",NULL)); + struct vfs_path cover={0},top={0},point={0},child={0},alias={0},result={0}; + assert(!vfs_path_lookup(ns,root,root,"/lazy-root",0,&cover)); + struct vfs_mount *mount=NULL; + assert(!storage_new_tmpfs_mount("lazy-parent",0,NULL,1000,1000,&mount)); + assert(!vfs_mount_attach(ns,mount,&cover));vfs_mount_put(mount); + assert(!vfs_path_lookup(ns,root,root,"/lazy-root",0,&top)); + struct storage_volume *outer=vfs_path_context(&top); + assert(!vfs_path_create_node(&top,"child",LINUX_S_IFDIR,&mode,NULL,&point)); + assert(!storage_new_tmpfs_mount("lazy-child",0,NULL,1000,1000,&mount)); + assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount); + vfs_path_put(&point); + assert(!vfs_path_lookup(ns,root,&top,"child",0,&child)); + struct storage_volume *inner=vfs_path_context(&child); + struct vfs_path source={0}; + assert(!vfs_path_create_node(&child,"view",LINUX_S_IFDIR,&mode,NULL,&source)); + assert(!vfs_path_create_node(&child,"alias",LINUX_S_IFDIR,&mode,NULL,&point)); + assert(!vfs_path_new_file(&source,"data",&file_mode,&result)); + uint32_t count=0; + assert(!vfs_path_write(&result,0,"old",3,&count) && count==3); + vfs_path_put(&result); + assert(!vfs_mount_bind(ns,&source,&point)); + vfs_path_put(&source);vfs_path_put(&point); + assert(!vfs_path_lookup(ns,root,&child,"alias",0,&alias)); + + struct task actor={.pid=904,.fsuid=1000,.fsgid=1000}; + sched_task_limits(&actor)->nofile.rlim_cur=32; + vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(&alias,&actor.fs_paths.cwd); + struct {char target[24],link[24],base[4],file[8],cwd[64];} user={ + .target="/lazy-root",.link="/lazy-link",.base="/",.file="data"}; + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + const uint64_t target=(uintptr_t)user.target,link=(uintptr_t)user.link; + assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,target,MNT_DETACH,0,0,0)==-EPERM); + actor.cap_effective=1ULL<ready && inner->ready); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,target,MNT_DETACH|MNT_EXPIRE,0,0,0)==-EINVAL); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,(uintptr_t)user.base,MNT_DETACH,0,0,0)==-EBUSY); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,target,MNT_DETACH,0,0,0)==-EINVAL); + assert(!vfs_path_namespace(&top) && !vfs_path_namespace(&child) && !vfs_path_namespace(&alias)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&result) && vfs_path_equal(&result,&cover)); + vfs_path_put(&result); + assert(vfs_path_lookup(ns,root,root,"/lazy-root/child",0,&result)==-ENOENT); + assert(!vfs_path_lookup(ns,root,&top,"child",0,&result)); + assert(vfs_path_same_filesystem(&result,&top));vfs_path_put(&result); + char text[4096]; + assert(!vfs_read_mount_table(ns,root,true,0,text,sizeof(text)-1,&count));text[count]=0; + assert(!strstr(text,"lazy-root") && !strstr(text,"lazy-child")); + assert(!vfs_path_lookup(ns,root,&alias,"..",0,&result) && vfs_path_equal(&result,&alias)); + vfs_path_put(&result); + assert(syscall_directory(ns,&actor,LINUX_SYS_GETCWD,(uintptr_t)user.cwd,sizeof(user.cwd))==(int64_t)sizeof("(unreachable)/")); + assert(!strcmp(user.cwd,"(unreachable)/")); + + int fd=syscall_open_object(ns,&actor,LINUX_AT_FDCWD,(uintptr_t)user.file,LINUX_O_RDONLY,0); + assert(fd>=0); + const struct vfs_path *file=&task_file_for_fd(&actor,fd)->path_ref; + assert(!vfs_path_read(file,0,text,sizeof(text),&count) && count==3 && !memcmp(text,"old",3)); + assert(!vfs_path_format_link(NULL,NULL,file,text,sizeof(text)) && !strcmp(text,"/data")); + assert(!vfs_path_rename(ns,file,&alias,"renamed")); + assert(!vfs_path_link(ns,file,&alias,"hardlink")); + assert(!vfs_path_remove(ns,file,false)); + assert(!vfs_path_read(file,0,text,sizeof(text),&count) && count==3 && !memcmp(text,"old",3)); + vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + vfs_path_put(&cover);vfs_path_put(&top);vfs_path_put(&child);vfs_path_put(&alias); + assert(inner->ready);task_discard_file_fd(&actor,fd); + assert(outer->ready && inner->ready && vfs_reclaim_pending()); + for(unsigned attempt=0;attempt<3 && vfs_reclaim_pending();++attempt) + assert(vfs_reclaim_mounts(8)); + assert(!vfs_reclaim_pending()); + assert(!outer->ready && !inner->ready); + lookup_user_base=lookup_user_bytes=0; + puts("PASS lazy unmount: immediate subtree removal, held paths, mount-root boundary and deferred cleanup"); +} + /** @brief Exercise per-attachment bind remount and canonical OFD writer lifetime. * @param ns Borrowed test namespace with both source and destination visible. * @param root Held namespace root. @param fs Base tmpfs for fixture mountpoints. @@ -3175,6 +3261,7 @@ int main(int argc,char **argv) runtime_mount_syscalls(&ns,&root,fs); runtime_recursive_bind(&ns,&root,fs); runtime_bind_remount(&ns,&root,fs); + runtime_lazy_unmount(&ns,&root,fs); device_mount_objects(&ns,&root,fs); assert(!vfs_path_lookup(&ns,&root,&root,"mnt",VFS_LOOKUP_FOLLOW,&old_dir)); assert(!vfs_path_lookup(&ns,&root,&old_dir,"old",VFS_LOOKUP_FOLLOW,&old_file)); From 4897b0b1dc739d7914bb3ce0b715b72043552269 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sat, 28 Nov 2026 23:50:46 +0800 Subject: [PATCH 08/97] feat(vfs): support private and unbindable mount types --- .../en/LC_MESSAGES/userspace-api/abi.po | 16 +++--- .../ja/LC_MESSAGES/userspace-api/abi.po | 13 +++-- Documentation/userspace-api/abi.rst | 14 ++++- fs/vfs/mount_internal.h | 1 + fs/vfs/mount_table.c | 7 ++- fs/vfs/mount_tree.c | 50 ++++++++++++++--- include/reliefnt/mount.h | 16 +++++- kernel/syscall/fs/mount.c | 25 +++++++-- tools/tests/mount_backend_test.c | 54 ++++++++++++++++++- 9 files changed, 164 insertions(+), 32 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index ceec5ffa..07a6efe8 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -68,14 +68,8 @@ msgstr "" msgid "" "``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 " -"inode 和文件系统。源目录之外的挂载不复制, 后续拓扑变更也不会传播。准备失败时目的树和现有挂载保持原样。" -msgstr "" -"``MS_BIND | MS_REC`` also copies the topology of mounts below the source " -"directory. Submounts in the destination tree have new mount IDs and " -"independent policies, but each shares its original inodes and filesystem." -" Mounts outside the source directory are not copied, and later topology " -"changes do not propagate. Preparation failure leaves the destination tree" -" and existing mounts unchanged." +"inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" +msgstr "``MS_BIND | MS_REC`` also copies the mount topology beneath the source directory. The new attachments have their own mount IDs and policies but share their respective source inodes and filesystems. Mounts outside the source directory and unbindable subtrees are skipped. Preparation failure leaves the destination tree and existing mounts unchanged." msgid "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` only changes the policy at the target mountpoint. It does not read the source, type, or filesystem options. The source mount, submounts, and shared filesystem are unchanged. Omitted atime options preserve the existing policy. If the shared filesystem is read-only, clearing the mountpoint's read-only flag does not make it writable." @@ -102,6 +96,12 @@ msgstr "``RELIEFOS_PR_GET_UNAME_LINUX`` (``0x52550002``): all arguments must be msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" msgstr "Invalid values and nonzero reserved arguments return EINVAL without changing state. New tasks use ReliefNT by default. fork, vfork, and clone copy the calling task's selection, and exec preserves it. Other existing tasks are unaffected; threads may also set their selection independently. The switch changes only the ``sysname`` returned by ``uname(2)`` to Linux; other fields, global UTS state, and procfs are unchanged. Both the standard libc prctl wrapper and raw syscalls are supported. Linux personality values retain their existing meaning." +msgid "私有和不可绑定挂载" +msgstr "Private and unbindable mounts" + +msgid "新挂载默认是 private。``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` 将 目标恢复为 private;``MS_UNBINDABLE`` 使目标不可作为 bind 源,并使递归 bind 跳过该子树。``MS_REC`` 将同一类型应用于目标及其现有子挂载;以后新建的子挂载 不会继承 unbindable。类型变更要求 ``CAP_SYS_ADMIN`` 且目标必须是挂载根, 不改变访问策略、文件系统状态或已有 bind。``/proc/self/mountinfo`` 使用 ``unbindable`` 可选字段报告不可绑定挂载。共享和 slave 传播尚不支持。" +msgstr "New mounts are private by default. ``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` makes the target private again. ``MS_UNBINDABLE`` prohibits using the target as a bind source and prunes its subtree from recursive binds. ``MS_REC`` applies the selected type to the target and its existing submounts; new submounts do not inherit the unbindable type. Changing the type requires ``CAP_SYS_ADMIN`` and a target at a mount root. It does not change access policy, filesystem state, or existing binds. ``/proc/self/mountinfo`` reports the ``unbindable`` optional field. Shared and slave propagation are not yet supported." + msgid "延迟卸载" msgstr "Lazy Unmount" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 6ab419fe..7e747250 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -61,11 +61,8 @@ msgstr "" msgid "" "``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 " -"inode 和文件系统。源目录之外的挂载不复制, 后续拓扑变更也不会传播。准备失败时目的树和现有挂载保持原样。" -msgstr "" -"``MS_BIND | MS_REC`` は元ディレクトリー配下のマウント構造も複製します。複製先の子マウントには新しいマウント ID " -"と独立したポリシーが割り当てられますが、それぞれ元の inode " -"とファイルシステムを共有します。元ディレクトリー外のマウントは複製されず、後から行った構造の変更も伝播しません。準備に失敗しても複製先のツリーと既存のマウントは変化しません。" +"inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" +msgstr "``MS_BIND | MS_REC`` は元ディレクトリー配下のマウント構造も複製します。複製されたマウントはそれぞれ独立したマウント ID とポリシーを持ち、元の inode とファイルシステムを共有します。元ディレクトリー外のマウントと unbindable のサブツリーは複製されません。準備に失敗しても複製先のツリーと既存のマウントは変化しません。" msgid "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` は対象マウントポイントのポリシーだけを変更します。ソース、タイプ、ファイルシステムのオプションは読み取りません。元のマウント、子マウント、共有ファイルシステムは変化しません。atime オプションを省略すると既存のポリシーが維持されます。共有ファイルシステムが読み取り専用である場合、マウントポイントの読み取り専用フラグを解除しても書き込み可能にはなりません。" @@ -92,6 +89,12 @@ msgstr "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):すべての引数 msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" msgstr "不正な値やゼロ以外の予約引数には、状態を変更せず EINVAL を返します。新しいタスクは既定で ReliefNT を使用します。fork、vfork、clone は呼び出しタスクの選択をコピーし、exec は選択を保持します。既存の別タスクは影響を受けず、スレッドも独立に選択できます。このスイッチは ``uname(2)`` の ``sysname`` だけを Linux に変更し、他のフィールド、グローバルな UTS 状態、procfs は変更しません。標準 libc の prctl ラッパーとシステムコールの直接呼び出しに対応し、personality 値の意味は変更しません。" +msgid "私有和不可绑定挂载" +msgstr "プライベートとバインド不可のマウント" + +msgid "新挂载默认是 private。``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` 将 目标恢复为 private;``MS_UNBINDABLE`` 使目标不可作为 bind 源,并使递归 bind 跳过该子树。``MS_REC`` 将同一类型应用于目标及其现有子挂载;以后新建的子挂载 不会继承 unbindable。类型变更要求 ``CAP_SYS_ADMIN`` 且目标必须是挂载根, 不改变访问策略、文件系统状态或已有 bind。``/proc/self/mountinfo`` 使用 ``unbindable`` 可选字段报告不可绑定挂载。共享和 slave 传播尚不支持。" +msgstr "新しいマウントは既定で private です。``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` は対象を private に戻します。``MS_UNBINDABLE`` は対象をバインド元として使えなくし、再帰バインドではそのサブツリーを除外します。``MS_REC`` は対象と既存の子マウントに同じ種別を適用します。後から作られた子マウントは unbindable を継承しません。種別を変更するには ``CAP_SYS_ADMIN`` が必要で、対象はマウントのルートでなければなりません。アクセス方針、ファイルシステムの状態、既存のバインドは変化しません。``/proc/self/mountinfo`` はオプションの ``unbindable`` フィールドでこの種別を示します。shared と slave の伝播にはまだ対応していません。" + msgid "延迟卸载" msgstr "遅延アンマウント" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 3e0d46bf..c07c4e24 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -47,8 +47,8 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。 ``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 -挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载不复制, -后续拓扑变更也不会传播。准备失败时目的树和现有挂载保持原样。 +挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载和 +unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。 ``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 @@ -61,6 +61,16 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 文件绑定尚不支持,返回明确错误。 +私有和不可绑定挂载 +================== + +新挂载默认是 private。``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` 将 +目标恢复为 private;``MS_UNBINDABLE`` 使目标不可作为 bind 源,并使递归 bind +跳过该子树。``MS_REC`` 将同一类型应用于目标及其现有子挂载;以后新建的子挂载 +不会继承 unbindable。类型变更要求 ``CAP_SYS_ADMIN`` 且目标必须是挂载根, +不改变访问策略、文件系统状态或已有 bind。``/proc/self/mountinfo`` 使用 +``unbindable`` 可选字段报告不可绑定挂载。共享和 slave 传播尚不支持。 + 延迟卸载 ======== diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 256e7aeb..05db5a0e 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -32,6 +32,7 @@ struct vfs_mount { struct module *owner; uint64_t references,id,policy; uint64_t writers; /* Open writable file descriptions on this attachment. */ + bool unbindable; /* Pruned by recursive bind; never a valid bind source. */ bool lazy_detached; /* No namespace edges; retained paths still work. */ char *source,*filesystem; uint64_t device; diff --git a/fs/vfs/mount_table.c b/fs/vfs/mount_table.c index 97ff4a41..fae5bed1 100644 --- a/fs/vfs/mount_table.c +++ b/fs/vfs/mount_table.c @@ -66,7 +66,8 @@ static void mount_options(struct mount_text *text,uint64_t flags,bool mountinfo, * @param info True for mountinfo, false for combined mounts options. * @param text Borrowed bounded stream state. @param workspace Two VFS_PATH_MAX buffers. * @return Zero, hidden-root success or negative path-format errno. No - * allocation/I/O/ownership change; flags are read from their actual owners. + * allocation/I/O/ownership change; access flags and optional propagation + * tags are read from their actual owners. */ static int mount_line(const struct vfs_namespace *ns,const struct vfs_path *root, const struct vfs_mount *mount,bool info,struct mount_text *text,char *workspace) @@ -94,7 +95,9 @@ static int mount_line(const struct vfs_namespace *ns,const struct vfs_path *root mount_number(text,(mount->device>>8)&0xfff);mount_emit(text,":"); mount_number(text,(mount->device&255)|((mount->device>>12)&~255ULL));mount_emit(text," "); mount_field(text,backing);mount_emit(text," ");mount_field(text,point);mount_emit(text," "); - mount_options(text,mount->policy,true,false);mount_emit(text," - ");mount_emit(text,filesystem);mount_emit(text," "); + mount_options(text,mount->policy,true,false); + if(mount->unbindable)mount_emit(text," unbindable"); + mount_emit(text," - ");mount_emit(text,filesystem);mount_emit(text," "); mount_field(text,source);mount_emit(text," ");mount_options(text,vfs_super_flags(mount),true,true);mount_emit(text,"\n"); } else { mount_field(text,source);mount_emit(text," ");mount_field(text,point);mount_emit(text," "); diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index e581eedc..69188394 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -275,6 +275,39 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const stru mount->next=ns->mounts;ns->mounts=mount;return 0; } +/** @brief Check mount ancestry by retained topology rather than pathname. + * @param root Borrowed candidate subtree root. + * @param mount Borrowed attachment to test. + * @return True if mount is root or reaches it through parent edges. + */ +static bool vfs_mount_below(const struct vfs_mount *root,const struct vfs_mount *mount) +{ + for(;mount;mount=mount->point.mount)if(mount==root)return true; + return false; +} + +/** @brief Apply private or unbindable propagation type to live attachments. + * @param ns Borrowed namespace under execution ownership. + * @param path Retained exact root of the selected live mount. + * @param flags One propagation selector and optional MS_REC. + * @return Zero or negative errno. The whole change is validated before + * editing any mount. No allocation, backend callback or access-policy change. + */ +int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *path,uint64_t flags) +{ + uint64_t type=flags&~MS_REC; + if(!type || (type&(type-1)) || (type&~VFS_PROPAGATION_MASK))return -EINVAL; + if(!ns || !vfs_path_valid(path) || path->mount->ns!=ns || path->dentry!=path->mount->root) + return -EINVAL; + if(type!=MS_PRIVATE && type!=MS_UNBINDABLE)return -EOPNOTSUPP; + bool unbindable=type==MS_UNBINDABLE; + path->mount->unbindable=unbindable; + if(flags&MS_REC) + for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) + if(vfs_mount_below(path->mount,mount))mount->unbindable=unbindable; + return 0; +} + /** @brief Prepare an unattached directory view of an existing filesystem. * @param source Valid retained source directory; its mount and inode are shared. * @param out Receives the privately owned clone on success, NULL on failure. @@ -301,13 +334,14 @@ static int vfs_bind_clone(const struct vfs_path *source,struct vfs_mount **out) /** @brief Find the next direct submount within the selected directory view. * @param view The original mount and the directory bounding its subtree. * @param candidate Start of a suffix of the unchanged namespace mount list. - * @return Borrowed matching attachment or NULL. A mount on the same backing - * dentry through another attachment is not part of this view. + * @return Borrowed matching bindable attachment or NULL. An unbindable + * attachment prunes its branch; a mount through another attachment is not + * part of the view even when its backing dentry is shared. */ static struct vfs_mount *vfs_bind_child_mount(const struct vfs_path *view,struct vfs_mount *candidate) { for(;candidate;candidate=candidate->next) { - if(candidate->point.mount!=view->mount)continue; + if(candidate->point.mount!=view->mount || candidate->unbindable)continue; for(const struct vfs_dentry *d=candidate->point.dentry;d && !d->disconnected;d=d->parent) if(d==view->dentry)return candidate; } @@ -318,7 +352,7 @@ static struct vfs_mount *vfs_bind_child_mount(const struct vfs_path *view,struct * @param ns Borrowed namespace under execution ownership. * @param source Borrowed retained source directory in ns. * @param target Borrowed retained destination directory in ns. - * @param recursive True to copy the source's exact descendant attachments. + * @param recursive True to copy the source's bindable descendant branches. * @return Zero or negative errno. Staging traverses the original graph without * recursion or pathname replay; on failure the graph and next ID are unchanged. */ @@ -327,6 +361,7 @@ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, { if(!ns || !ns->root || !vfs_path_valid(source) || !vfs_path_valid(target))return -EINVAL; if(source->mount->ns!=ns || target->mount->ns!=ns)return -EXDEV; + if(source->mount->unbindable)return -EINVAL; if(source->dentry->node.type!=RELIEFOS_FS_TYPE_DIR || target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; if(source->dentry->disconnected || target->dentry->disconnected)return -ENOENT; if(vfs_covering(ns,target))return -EBUSY; @@ -387,7 +422,7 @@ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source,const return vfs_bind_tree(ns,source,target,false); } -/** @brief Publish a directory view with independent copies of its submounts. +/** @brief Publish a directory view with independent copies of its bindable subtrees. * @param ns Execution-owned namespace. @param source Retained subtree root. * @param target Retained destination directory. * @return Zero or negative errno without partial publication. @@ -451,9 +486,8 @@ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path) struct vfs_mount *detached=NULL,**link=&ns->mounts; while(*link) { - struct vfs_mount *mount=*link,*ancestor=mount; - while(ancestor && ancestor!=root)ancestor=ancestor->point.mount; - if(!ancestor){link=&mount->next;continue;} + struct vfs_mount *mount=*link; + if(!vfs_mount_below(root,mount)){link=&mount->next;continue;} *link=mount->next;mount->next=detached;detached=mount; mount->ns=NULL;mount->lazy_detached=true; } diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index ead3632f..1a263c54 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -9,6 +9,7 @@ * MS_STRICTATIME is an input selector, represented by cleared atime bits. */ #define VFS_MOUNT_POLICY_MASK (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOATIME|MS_NODIRATIME|MS_RELATIME) #define VFS_SUPER_POLICY_MASK (MS_RDONLY|MS_SYNCHRONOUS|MS_DIRSYNC|MS_LAZYTIME) +#define VFS_PROPAGATION_MASK (MS_SHARED|MS_PRIVATE|MS_SLAVE|MS_UNBINDABLE) struct module; struct vfs_mount; @@ -540,22 +541,33 @@ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out); */ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount, const struct vfs_path *target); +/** @brief Isolate one mount attachment or its complete visible subtree. + * @param ns Borrowed execution-owned namespace. + * @param path Held root of an attached mount in ns, not an interior dentry. + * @param flags Exactly one propagation type, optionally with MS_REC. + * @return Zero or negative errno without partial changes. MS_PRIVATE and + * MS_UNBINDABLE do not change access policy or call into the backend. + * Peer/slave propagation is not yet supported. + */ +int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *path,uint64_t flags); /** @brief Bind one directory inode into a separate nonrecursive attachment. * @param ns Execution-owned namespace containing both retained paths. * @param source Directory whose actual dentry/backend remain pinned. * @param target Destination directory, required in the same namespace. * @return Zero or negative errno without a partial attachment. Inherits * source mount policy; shares inode identities and backend lifetime without - * duplicating provider destruction. Child mounts are not copied. + * duplicating provider destruction. Child mounts are not copied and an + * unbindable source returns EINVAL. */ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); -/** @brief Bind a directory and all attachments beneath it in one transaction. +/** @brief Bind a directory and its bindable subtrees in one transaction. * @param ns Execution-owned namespace containing both retained paths. * @param source Directory that bounds the original mount subtree. * @param target Uncovered destination directory in the same namespace. * @return Zero or negative errno without publishing a partial tree. Each clone * has an independent ID and mount policy but pins the original backing objects. + * Unbindable descendant branches are skipped; an unbindable source is rejected. */ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 76d9d5da..3ef8a078 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -87,6 +87,21 @@ static int mount_bind_remount(struct vfs_namespace *ns,struct task *task,uint64_ vfs_path_put(&found.path);return rc; } +/** @brief Change propagation on the actual selected mount attachment. + * @param ns Borrowed namespace under execution ownership. + * @param task Authorized caller with retry-stable pathname state. + * @param target Required user mountpoint pathname, following final symlinks. + * @param flags Propagation selector and optional recursion. + * @return Zero or negative lookup/type errno. No other arguments are read. + */ +static int mount_propagation(struct vfs_namespace *ns,struct task *task,uint64_t target,uint64_t flags) +{ + struct vfs_lookup_result found={0}; + int rc=resolve_user_object_at_flags(ns,task,LINUX_AT_FDCWD,target,false,false,VFS_LOOKUP_FOLLOW,&found); + if(!rc)rc=vfs_mount_set_propagation(ns,&found.path,flags); + vfs_path_put(&found.path);return rc; +} + /** @brief Validate and apply policy to the actual selected filesystem root. * @param ns Borrowed execution-owned namespace. * @param task Authorized calling task with retry-stable lookup scope. @@ -183,13 +198,14 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * * @param ns Borrowed live namespace under execution ownership. * @param task Calling task, required; CAP_SYS_ADMIN checked before user input. * @param number Linux MOUNT or UMOUNT2 operation number. - * @param a0 User source/label, or unmount target pointer; ignored for remount. + * @param a0 User source/label, or unmount target pointer; ignored for remount + * and propagation changes. * @param a1 Mount target pointer, or unmount low-32-bit flags. - * @param a2 User filesystem type; ignored for bind/remount/move/unmount. + * @param a2 User filesystem type; ignored for bind/remount/move/propagation/unmount. * @param a3 Native mount flags; ignored for unmount. Legacy magic and the * MS_SILENT diagnostic hint never become attachment policy or move selectors. * @param a4 Optional user mount data; ignored for bind, bind remount, move - * and unmount. + * propagation changes and unmount. * @return Zero or negative Linux errno/internal EAGAIN. Text and lookup state * remain scope-owned across waits; temporary unscoped allocations are always * freed. The resulting graph owns backend lifetime, without target prefixes. @@ -207,9 +223,10 @@ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_ if(a3&MS_BIND)return mount_bind_remount(ns,task,a1,a3&~(MS_REMOUNT|MS_BIND)); return mount_remount(ns,task,a1,a3&~MS_REMOUNT,a4); } - if(a3&MS_MOVE)return a3!=MS_MOVE ? -RELIEFOS_EOPNOTSUPP : mount_move(ns,task,a0,a1); if(a3&MS_BIND)return a3&~(MS_BIND|MS_REC) ? -RELIEFOS_EOPNOTSUPP : mount_bind(ns,task,a0,a1,(a3&MS_REC)!=0); + if(a3&VFS_PROPAGATION_MASK)return mount_propagation(ns,task,a1,a3); + if(a3&MS_MOVE)return a3!=MS_MOVE ? -RELIEFOS_EOPNOTSUPP : mount_move(ns,task,a0,a1); const uint64_t supported=MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_SYNCHRONOUS|MS_DIRSYNC| MS_NOATIME|MS_NODIRATIME|MS_RELATIME|MS_STRICTATIME|MS_LAZYTIME; if(a3&~supported)return -RELIEFOS_EOPNOTSUPP; diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 9b55dbd9..2aa36b75 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2912,6 +2912,57 @@ static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pat puts("PASS actual mount/remount/MS_MOVE/umount syscalls: scoped objects, capability, busy refs, atime preservation, ignored remount source/type and nofollow"); } +/** @brief Check root-scoped propagation changes and unbindable bind pruning. + * @param ns Borrowed test namespace. @param root Retained namespace root. + * @param actor Privileged task with the fixture paths. + * @param source Writable user-path slot for the bind source. + * @param target Writable user-path slot for the mount/bind target. + * @param peer Held original bindable sibling for inode comparison. + */ +static void runtime_unbindable(struct vfs_namespace *ns,const struct vfs_path *root, + struct task *actor,char *source,char *target, + const struct vfs_path *peer) +{ + const uint64_t from=(uintptr_t)source,to=(uintptr_t)target; + const uint64_t ignored=UINT64_MAX; + strcpy(target,"/rbind-source/view"); + assert(scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,ignored,to,ignored,MS_PRIVATE,ignored)==-EINVAL); + strcpy(target,"/rbind-source/view/child"); + assert(scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,ignored,to,ignored,MS_UNBINDABLE|MS_PRIVATE,ignored)==-EINVAL); + actor->cap_effective=0; + assert(scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,ignored,to,ignored,MS_UNBINDABLE,ignored)==-EPERM); + actor->cap_effective=1ULL<next_id; + for(unsigned i=0;i<2;++i) + assert(scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,from,to,ignored,MS_BIND|(i ? MS_REC : 0),ignored)==-EINVAL); + assert(ns->next_id==before); + strcpy(source,"/rbind-source/view"); + assert(!scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,from,to,ignored,MS_BIND|MS_REC,ignored)); + assert(ns->next_id==before+2); + struct vfs_path found={0}; + assert(vfs_path_lookup(ns,root,root,"/rbind-target/child/deep",0,&found)==-ENOENT); + assert(!vfs_path_lookup(ns,root,root,"/rbind-target/peer",0,&found)); + assert(vfs_path_same_inode(&found,peer)); + assert(!vfs_mount_unmount(ns,&found));vfs_path_put(&found); + assert(!vfs_path_lookup(ns,root,root,target,0,&found)); + assert(!vfs_mount_unmount(ns,&found));vfs_path_put(&found); + + strcpy(target,"/rbind-source/view/child"); + assert(!scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,ignored,to,ignored,MS_PRIVATE|MS_REC,ignored)); + assert(!vfs_read_mount_table(ns,root,true,0,table,sizeof(table)-1,&count));table[count]=0; + assert(!strstr(table," unbindable - ")); + puts("PASS mount propagation types: root and capability checks, recursive private, unbindable mountinfo and bind pruning"); +} + /** @brief Clone only the selected directory's mount topology, or publish none of it. * @param ns Borrowed test-owned namespace. @param root Held root in that namespace. * @param fs Base tmpfs in which to prepare the source, target and sibling points. @@ -2939,7 +2990,7 @@ static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_pat } struct task actor={.pid=902,.fsuid=1000,.fsgid=1000,.cap_effective=1ULL<0;--i) { assert(!vfs_mount_unmount(ns,&original[i-1]));vfs_path_put(&original[i-1]); } From afe0124655700fae421cf8b1c48ebb443a9342d8 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 00:30:33 +0800 Subject: [PATCH 09/97] feat(vfs): propagate mounts among shared peers --- .../en/LC_MESSAGES/userspace-api/abi.po | 14 +- .../ja/LC_MESSAGES/userspace-api/abi.po | 14 +- Documentation/userspace-api/abi.rst | 26 +- fs/vfs/mount_internal.h | 5 +- fs/vfs/mount_table.c | 4 +- fs/vfs/mount_tree.c | 439 +++++++++++++----- include/reliefnt/mount.h | 38 +- kernel/syscall/fs/mount.c | 7 +- tools/tests/mount_backend_test.c | 186 ++++++++ 9 files changed, 592 insertions(+), 141 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 07a6efe8..3d29fd2e 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -96,11 +96,17 @@ msgstr "``RELIEFOS_PR_GET_UNAME_LINUX`` (``0x52550002``): all arguments must be msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" msgstr "Invalid values and nonzero reserved arguments return EINVAL without changing state. New tasks use ReliefNT by default. fork, vfork, and clone copy the calling task's selection, and exec preserves it. Other existing tasks are unaffected; threads may also set their selection independently. The switch changes only the ``sysname`` returned by ``uname(2)`` to Linux; other fields, global UTS state, and procfs are unchanged. Both the standard libc prctl wrapper and raw syscalls are supported. Linux personality values retain their existing meaning." -msgid "私有和不可绑定挂载" -msgstr "Private and unbindable mounts" +msgid "挂载传播" +msgstr "Mount propagation" -msgid "新挂载默认是 private。``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` 将 目标恢复为 private;``MS_UNBINDABLE`` 使目标不可作为 bind 源,并使递归 bind 跳过该子树。``MS_REC`` 将同一类型应用于目标及其现有子挂载;以后新建的子挂载 不会继承 unbindable。类型变更要求 ``CAP_SYS_ADMIN`` 且目标必须是挂载根, 不改变访问策略、文件系统状态或已有 bind。``/proc/self/mountinfo`` 使用 ``unbindable`` 可选字段报告不可绑定挂载。共享和 slave 传播尚不支持。" -msgstr "New mounts are private by default. ``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` makes the target private again. ``MS_UNBINDABLE`` prohibits using the target as a bind source and prunes its subtree from recursive binds. ``MS_REC`` applies the selected type to the target and its existing submounts; new submounts do not inherit the unbindable type. Changing the type requires ``CAP_SYS_ADMIN`` and a target at a mount root. It does not change access policy, filesystem state, or existing binds. ``/proc/self/mountinfo`` reports the ``unbindable`` optional field. Shared and slave propagation are not yet supported." +msgid "``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 绑定共享挂载时,副本加入源的组。``MS_PRIVATE`` 使目标离开其组; ``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。 ``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:`` 或 ``unbindable``。" +msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` creates a peer group for a target that is not already shared. Binding a shared mount joins the copy to the source group. ``MS_PRIVATE`` removes the target from its group; ``MS_UNBINDABLE`` also prohibits use as a bind source and prunes its subtree from recursive binds. ``MS_REC`` applies the selected type to the target and its existing submounts; it neither merges separate submounts into one group nor changes an existing shared group ID. Changing the type requires ``CAP_SYS_ADMIN`` and a target at a mount root. It does not change mount access policy or filesystem state. ``/proc/self/mountinfo`` reports the optional field ``shared:`` or ``unbindable``." + +msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,其他对等挂载在相同目录对象 处接收副本;目标位于接收方 bind 根之外时不传播。没有继承源组的副本形成新组, 新挂载位于非共享父挂载下时默认是 private。所有副本一起发布;分配失败时不留下 部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出 共享父挂载返回 EINVAL。``MS_SLAVE`` 和跨命名空间传播尚不支持。" +msgstr "Creating a mount or bind (including a recursive bind) under a shared parent delivers copies at the same directory object on its other peers. An event is not delivered outside a receiving bind root. Copies that do not inherit a source group form a new group; a new filesystem mount under a nonshared parent is private by default. All copies are published together; an allocation failure leaves no partial mounts. Insertion at a covered receiver and moving into a shared parent return EOPNOTSUPP; moving out of a shared parent returns EINVAL. ``MS_SLAVE`` and propagation across namespaces are not yet supported." + +msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。存在不随事件卸载的子挂载时保留该接收分支。 延迟卸载为目标子树中的每个挂载传播事件,不因打开路径阻塞,仍保留接收方的无关 子挂载。接收方保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" +msgstr "An unmount propagates from the target’s parent to the matching mountpoints. An ordinary unmount returns EBUSY without removing any mount if a removable receiver still has an open path. A receiver is kept when it has submounts that are not being removed. Lazy unmount propagates each mount in the requested subtree without waiting for open paths and preserves unrelated submounts at receivers. A retained receiver can still use its backing even after the initiating attachment is detached." msgid "延迟卸载" msgstr "Lazy Unmount" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 7e747250..7877ca60 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -89,11 +89,17 @@ msgstr "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):すべての引数 msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" msgstr "不正な値やゼロ以外の予約引数には、状態を変更せず EINVAL を返します。新しいタスクは既定で ReliefNT を使用します。fork、vfork、clone は呼び出しタスクの選択をコピーし、exec は選択を保持します。既存の別タスクは影響を受けず、スレッドも独立に選択できます。このスイッチは ``uname(2)`` の ``sysname`` だけを Linux に変更し、他のフィールド、グローバルな UTS 状態、procfs は変更しません。標準 libc の prctl ラッパーとシステムコールの直接呼び出しに対応し、personality 値の意味は変更しません。" -msgid "私有和不可绑定挂载" -msgstr "プライベートとバインド不可のマウント" +msgid "挂载传播" +msgstr "マウントの伝播" -msgid "新挂载默认是 private。``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` 将 目标恢复为 private;``MS_UNBINDABLE`` 使目标不可作为 bind 源,并使递归 bind 跳过该子树。``MS_REC`` 将同一类型应用于目标及其现有子挂载;以后新建的子挂载 不会继承 unbindable。类型变更要求 ``CAP_SYS_ADMIN`` 且目标必须是挂载根, 不改变访问策略、文件系统状态或已有 bind。``/proc/self/mountinfo`` 使用 ``unbindable`` 可选字段报告不可绑定挂载。共享和 slave 传播尚不支持。" -msgstr "新しいマウントは既定で private です。``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` は対象を private に戻します。``MS_UNBINDABLE`` は対象をバインド元として使えなくし、再帰バインドではそのサブツリーを除外します。``MS_REC`` は対象と既存の子マウントに同じ種別を適用します。後から作られた子マウントは unbindable を継承しません。種別を変更するには ``CAP_SYS_ADMIN`` が必要で、対象はマウントのルートでなければなりません。アクセス方針、ファイルシステムの状態、既存のバインドは変化しません。``/proc/self/mountinfo`` はオプションの ``unbindable`` フィールドでこの種別を示します。shared と slave の伝播にはまだ対応していません。" +msgid "``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 绑定共享挂载时,副本加入源的组。``MS_PRIVATE`` 使目标离开其组; ``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。 ``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:`` 或 ``unbindable``。" +msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` は、まだ共有されていない対象にピアグループを作ります。共有マウントをバインドすると、コピーはバインド元のグループに加わります。``MS_PRIVATE`` は対象をグループから外します。``MS_UNBINDABLE`` はさらにバインド元としての使用を禁止し、再帰バインドからそのサブツリーを除外します。``MS_REC`` は選択した種別を対象と既存の子マウントに適用しますが、別々の子マウントを同じグループにまとめたり、既存の共有グループ ID を変更したりしません。種別の変更には ``CAP_SYS_ADMIN`` が必要で、対象はマウントのルートでなければなりません。アクセス方針やファイルシステムの状態は変わりません。``/proc/self/mountinfo`` はオプションフィールド ``shared:`` または ``unbindable`` を表示します。" + +msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,其他对等挂载在相同目录对象 处接收副本;目标位于接收方 bind 根之外时不传播。没有继承源组的副本形成新组, 新挂载位于非共享父挂载下时默认是 private。所有副本一起发布;分配失败时不留下 部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出 共享父挂载返回 EINVAL。``MS_SLAVE`` 和跨命名空间传播尚不支持。" +msgstr "共有マウントの下に新しいマウントやバインド(再帰バインドを含む)を作ると、他のピアの同じディレクトリオブジェクトにコピーが作られます。受信側のバインドルート外には伝播しません。バインド元のグループを継承しないコピーは新しいグループを作り、非共有の親の下に作る新規ファイルシステムマウントは既定で private です。すべてのコピーを一度に公開し、割り当てに失敗しても一部のマウントは残りません。受信位置がすでにマウントで覆われている場合や共有の親への移動は EOPNOTSUPP、共有の親からの移動は EINVAL を返します。``MS_SLAVE`` と名前空間間の伝播にはまだ対応していません。" + +msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。存在不随事件卸载的子挂载时保留该接收分支。 延迟卸载为目标子树中的每个挂载传播事件,不因打开路径阻塞,仍保留接收方的无关 子挂载。接收方保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" +msgstr "アンマウントは対象の親から対応するマウントポイントへ伝播します。通常のアンマウントでは、取り外し対象となる受信側に開いたパスがあれば、どのマウントも取り外さず EBUSY を返します。イベントで取り外されない子マウントがあれば、その受信側は残ります。遅延アンマウントは開いたパスを待たずに対象サブツリー内の各マウントのイベントを伝播し、受信側の無関係な子マウントを残します。受信側に残ったマウントは、操作元が切り離された後もバックエンドを使えます。" msgid "延迟卸载" msgstr "遅延アンマウント" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index c07c4e24..e75005dc 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -61,15 +61,27 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 文件绑定尚不支持,返回明确错误。 -私有和不可绑定挂载 +挂载传播 ================== -新挂载默认是 private。``mount(NULL, target, NULL, MS_PRIVATE, NULL)`` 将 -目标恢复为 private;``MS_UNBINDABLE`` 使目标不可作为 bind 源,并使递归 bind -跳过该子树。``MS_REC`` 将同一类型应用于目标及其现有子挂载;以后新建的子挂载 -不会继承 unbindable。类型变更要求 ``CAP_SYS_ADMIN`` 且目标必须是挂载根, -不改变访问策略、文件系统状态或已有 bind。``/proc/self/mountinfo`` 使用 -``unbindable`` 可选字段报告不可绑定挂载。共享和 slave 传播尚不支持。 +``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 +绑定共享挂载时,副本加入源的组。``MS_PRIVATE`` 使目标离开其组; +``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。 +``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, +也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, +不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 +``shared:`` 或 ``unbindable``。 + +在共享父挂载下创建挂载或 bind(包括递归 bind)时,其他对等挂载在相同目录对象 +处接收副本;目标位于接收方 bind 根之外时不传播。没有继承源组的副本形成新组, +新挂载位于非共享父挂载下时默认是 private。所有副本一起发布;分配失败时不留下 +部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出 +共享父挂载返回 EINVAL。``MS_SLAVE`` 和跨命名空间传播尚不支持。 + +卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 +时返回 EBUSY,不移除任何挂载。存在不随事件卸载的子挂载时保留该接收分支。 +延迟卸载为目标子树中的每个挂载传播事件,不因打开路径阻塞,仍保留接收方的无关 +子挂载。接收方保留的挂载可以继续使用其后端,即使发起挂载已被摘除。 延迟卸载 ======== diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 05db5a0e..18bd92df 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -30,8 +30,11 @@ struct vfs_mount { const struct vfs_backend_ops *ops; void *context; struct module *owner; - uint64_t references,id,policy; + uint64_t references,id,policy,peer_group; /* Zero group is not shared. */ + uint64_t propagation_pins; /* Replica lifetime references, not open paths. */ uint64_t writers; /* Open writable file descriptions on this attachment. */ + bool propagation_backing; /* This bind_source is a replica lifetime pin. */ + bool unmount_selected; /* Scratch under the namespace execution writer. */ bool unbindable; /* Pruned by recursive bind; never a valid bind source. */ bool lazy_detached; /* No namespace edges; retained paths still work. */ char *source,*filesystem; diff --git a/fs/vfs/mount_table.c b/fs/vfs/mount_table.c index fae5bed1..19b4b19c 100644 --- a/fs/vfs/mount_table.c +++ b/fs/vfs/mount_table.c @@ -96,7 +96,9 @@ static int mount_line(const struct vfs_namespace *ns,const struct vfs_path *root mount_number(text,(mount->device&255)|((mount->device>>12)&~255ULL));mount_emit(text," "); mount_field(text,backing);mount_emit(text," ");mount_field(text,point);mount_emit(text," "); mount_options(text,mount->policy,true,false); - if(mount->unbindable)mount_emit(text," unbindable"); + if(mount->peer_group) { + mount_emit(text," shared:");mount_number(text,mount->peer_group); + } else if(mount->unbindable)mount_emit(text," unbindable"); mount_emit(text," - ");mount_emit(text,filesystem);mount_emit(text," "); mount_field(text,source);mount_emit(text," ");mount_options(text,vfs_super_flags(mount),true,true);mount_emit(text,"\n"); } else { diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index 69188394..db05ceea 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -34,6 +34,7 @@ static bool vfs_finish_retirement(struct vfs_mount *mount) { if(mount->bind_source.mount) { struct vfs_path backing=mount->bind_source; + if(mount->propagation_backing)--backing.mount->propagation_pins; if(vfs_notify_mount_retired)vfs_notify_mount_retired(mount); struct module *owner=mount->owner; kernel_free(mount->source);kernel_free(mount); @@ -228,7 +229,7 @@ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root) { if(!ns || ns->root || ns->mounts || !root || root->ns || root->point.mount || root->lazy_detached)return -EINVAL; ++root->references;root->ns=ns;root->id=1;root->next=NULL; - ns->root=root;ns->mounts=root;ns->next_id=2;return 0; + ns->root=root;ns->mounts=root;ns->next_id=2;ns->next_peer_id=1;return 0; } /* Mountpoint identity is a retained parent mount + dentry, never text. */ @@ -256,25 +257,6 @@ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out) vfs_follow_mounts(ns,out);return 0; } -/** @brief Publish an unused mount at an exact directory in the namespace. - * @param ns Borrowed execution-owned namespace. - * @param mount Caller-retained unpublished mount; membership takes its own ref. - * @param target Borrowed retained directory path in ns. - * @return Zero or negative errno, with no graph change on failure. A mount - * that was lazily detached is not eligible for reattachment. - */ -int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const struct vfs_path *target) -{ - if(!ns || !ns->root || !mount || !vfs_path_valid(target))return -EINVAL; - if(target->mount->ns!=ns)return -EXDEV; - if(target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; - if(mount->ns || mount->point.mount || mount->lazy_detached || vfs_covering(ns,target))return -EBUSY; - if(!ns->next_id)return -EOVERFLOW; - vfs_path_get(target,&mount->point);++mount->references; - mount->ns=ns;mount->id=ns->next_id++; - mount->next=ns->mounts;ns->mounts=mount;return 0; -} - /** @brief Check mount ancestry by retained topology rather than pathname. * @param root Borrowed candidate subtree root. * @param mount Borrowed attachment to test. @@ -286,12 +268,13 @@ static bool vfs_mount_below(const struct vfs_mount *root,const struct vfs_mount return false; } -/** @brief Apply private or unbindable propagation type to live attachments. +/** @brief Apply one supported propagation type to selected live attachments. * @param ns Borrowed namespace under execution ownership. * @param path Retained exact root of the selected live mount. * @param flags One propagation selector and optional MS_REC. * @return Zero or negative errno. The whole change is validated before - * editing any mount. No allocation, backend callback or access-policy change. + * editing any mount or advancing the group ID counter. No allocation, backend + * callback or access-policy change. Slave propagation is not implemented. */ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *path,uint64_t flags) { @@ -299,31 +282,49 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa if(!type || (type&(type-1)) || (type&~VFS_PROPAGATION_MASK))return -EINVAL; if(!ns || !vfs_path_valid(path) || path->mount->ns!=ns || path->dentry!=path->mount->root) return -EINVAL; - if(type!=MS_PRIVATE && type!=MS_UNBINDABLE)return -EOPNOTSUPP; - bool unbindable=type==MS_UNBINDABLE; - path->mount->unbindable=unbindable; - if(flags&MS_REC) - for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) - if(vfs_mount_below(path->mount,mount))mount->unbindable=unbindable; + if(type==MS_SLAVE)return -EOPNOTSUPP; + struct vfs_mount *root=path->mount; + bool recursive=(flags&MS_REC)!=0; + uint64_t next=ns->next_peer_id; + if(type==MS_SHARED) { + for(struct vfs_mount *mount=recursive ? ns->mounts : root;mount; + mount=recursive ? mount->next : NULL) { + if(mount->peer_group || !vfs_mount_below(root,mount))continue; + if(!next)return -EOVERFLOW; + ++next; + } + } + for(struct vfs_mount *mount=recursive ? ns->mounts : root;mount; + mount=recursive ? mount->next : NULL) { + if(!vfs_mount_below(root,mount))continue; + mount->unbindable=type==MS_UNBINDABLE; + if(type!=MS_SHARED)mount->peer_group=0; + else if(!mount->peer_group)mount->peer_group=ns->next_peer_id++; + } return 0; } /** @brief Prepare an unattached directory view of an existing filesystem. - * @param source Valid retained source directory; its mount and inode are shared. + * @param view Valid source directory; supplies the root and attachment policy. + * @param backing Retained path to the same dentry, pinned for this view's lifetime. + * @param propagation True for a fresh mount's replica-only backing reference. * @param out Receives the privately owned clone on success, NULL on failure. * @return Zero or negative provider/admission/allocation errno. No new backend * is created, and the clone has no namespace membership or inotify registration. */ -static int vfs_bind_clone(const struct vfs_path *source,struct vfs_mount **out) +static int vfs_bind_clone(const struct vfs_path *view,const struct vfs_path *backing, + bool propagation,struct vfs_mount **out) { *out=NULL; - struct vfs_mount *original=source->mount; + struct vfs_mount *original=view->mount; if(!try_module_get(original->owner))return -ENODEV; struct vfs_mount *mount=kernel_malloc(sizeof(*mount)); if(!mount){module_put(original->owner);return -ENOMEM;} *mount=(struct vfs_mount){.ops=original->ops,.context=original->context, - .owner=original->owner,.references=1,.root=source->dentry,.policy=original->policy}; - vfs_path_get(source,&mount->bind_source); + .owner=original->owner,.references=1,.root=view->dentry,.policy=original->policy, + .propagation_backing=propagation}; + vfs_path_get(backing,&mount->bind_source); + if(propagation)++backing->mount->propagation_pins; int rc=vfs_mount_describe(mount,original->source ? original->source : "none", original->filesystem ? original->filesystem : "none",original->device); if(rc)vfs_mount_put(mount); @@ -331,6 +332,113 @@ static int vfs_bind_clone(const struct vfs_path *source,struct vfs_mount **out) return rc; } +struct vfs_mount_batch { + struct vfs_mount *pending; + uint64_t next_id,next_peer_id; +}; + +/** @brief Add one privately owned mount reference to an unpublished batch. + * @param batch Staging list ordered from newest to oldest for rollback. + * @param mount Prepared mount; its reference transfers to the batch. + * @param point Borrowed exact destination, retained by the staged mount. + * @param id Reserved mount ID. @param group Reserved or inherited peer ID. + */ +static void vfs_stage_mount(struct vfs_mount_batch *batch,struct vfs_mount *mount, + const struct vfs_path *point,uint64_t id,uint64_t group) +{ + mount->id=id;mount->peer_group=group; + vfs_path_get(point,&mount->point); + mount->next=batch->pending;batch->pending=mount; +} + +/** @brief Roll back all staged mounts or publish them together without allocation. + * @param ns Borrowed execution-owned namespace. + * @param batch Owned unpublished mounts and tentative ID counters. + * @param status Nonzero to discard, zero to commit all changes. + * @return The supplied status. Rollback releases descendants before parents; + * neither graph nor namespace counters change on error. + */ +static int vfs_finish_mount_batch(struct vfs_namespace *ns,struct vfs_mount_batch *batch,int status) +{ + if(status) { + while(batch->pending) { + struct vfs_mount *mount=batch->pending;batch->pending=mount->next; + mount->next=NULL;vfs_path_put(&mount->point);vfs_mount_put(mount); + } + return status; + } + struct vfs_mount **tail=&batch->pending; + for(;*tail;tail=&(*tail)->next) { + struct vfs_mount *mount=*tail;mount->ns=ns; + if(!mount->notify_link && vfs_notify_mount_created)vfs_notify_mount_created(mount); + } + *tail=ns->mounts;ns->mounts=batch->pending; + ns->next_id=batch->next_id;ns->next_peer_id=batch->next_peer_id; + return 0; +} + +/** @brief Test whether one connected dentry lies inside a directory view. + * @param dentry Borrowed candidate. @param root Borrowed directory boundary. + * @return True for the boundary itself or a descendant connected to it. + */ +static bool vfs_dentry_below(const struct vfs_dentry *dentry,const struct vfs_dentry *root) +{ + for(;dentry && !dentry->disconnected;dentry=dentry->parent) + if(dentry==root)return true; + return false; +} + +/** @brief Identify another shared parent containing this exact mountpoint. + * @param target Resolved origin within a shared parent, borrowed. + * @param peer Candidate live attachment in the same namespace. + * @return True for a different group member whose bind root contains target. + */ +static bool vfs_mount_receiver(const struct vfs_path *target,const struct vfs_mount *peer) +{ + return peer!=target->mount && target->mount->peer_group && + peer->peer_group==target->mount->peer_group && vfs_dentry_below(target->dentry,peer->root); +} + +/** @brief Publish a new mount and all shared peer copies in one transaction. + * @param ns Borrowed execution-owned namespace. + * @param mount Caller-retained unpublished mount; membership takes its own ref. + * @param target Borrowed retained directory path in ns. + * @return Zero or negative errno, without consuming IDs or modifying the + * mount on failure. Already covered receiver slots are unsupported. + */ +int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const struct vfs_path *target) +{ + if(!ns || !ns->root || !mount || !vfs_path_valid(target))return -EINVAL; + if(target->mount->ns!=ns)return -EXDEV; + if(target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; + if(target->dentry->disconnected)return -ENOENT; + if(mount->ns || mount->point.mount || mount->lazy_detached || vfs_covering(ns,target))return -EBUSY; + if(!ns->next_id)return -EOVERFLOW; + struct vfs_mount_batch batch={.next_id=ns->next_id+1,.next_peer_id=ns->next_peer_id}; + uint64_t group=0; + int rc=0; + if(target->mount->peer_group) { + if(!batch.next_peer_id)return -EOVERFLOW; + group=batch.next_peer_id++; + struct vfs_path view={mount,mount->root}; + for(struct vfs_mount *peer=ns->mounts;peer;peer=peer->next) { + if(!vfs_mount_receiver(target,peer))continue; + struct vfs_path point={peer,target->dentry}; + if(vfs_covering(ns,&point)){rc=-EOPNOTSUPP;break;} + if(!batch.next_id){rc=-EOVERFLOW;break;} + struct vfs_mount *copy; + rc=vfs_bind_clone(&view,&view,true,©); + if(rc)break; + vfs_stage_mount(&batch,copy,&point,batch.next_id++,group); + } + } + if(!rc) { + ++mount->references; + vfs_stage_mount(&batch,mount,target,ns->next_id,group); + } + return vfs_finish_mount_batch(ns,&batch,rc); +} + /** @brief Find the next direct submount within the selected directory view. * @param view The original mount and the directory bounding its subtree. * @param candidate Start of a suffix of the unchanged namespace mount list. @@ -340,76 +448,94 @@ static int vfs_bind_clone(const struct vfs_path *source,struct vfs_mount **out) */ static struct vfs_mount *vfs_bind_child_mount(const struct vfs_path *view,struct vfs_mount *candidate) { - for(;candidate;candidate=candidate->next) { - if(candidate->point.mount!=view->mount || candidate->unbindable)continue; - for(const struct vfs_dentry *d=candidate->point.dentry;d && !d->disconnected;d=d->parent) - if(d==view->dentry)return candidate; - } + for(;candidate;candidate=candidate->next) + if(candidate->point.mount==view->mount && !candidate->unbindable && + vfs_dentry_below(candidate->point.dentry,view->dentry))return candidate; return NULL; } -/** @brief Clone and publish a directory attachment and optionally its submounts. - * @param ns Borrowed namespace under execution ownership. - * @param source Borrowed retained source directory in ns. - * @param target Borrowed retained destination directory in ns. - * @param recursive True to copy the source's bindable descendant branches. - * @return Zero or negative errno. Staging traverses the original graph without - * recursion or pathname replay; on failure the graph and next ID are unchanged. +/** @brief Stage one bind tree using previously resolved directory identities. + * @param batch Transaction owning all clones, including partial trees on error. + * @param source Source view in the live graph or first staged tree. + * @param target Borrowed retained destination for this tree. + * @param mounts Fixed inventory of source attachments for a recursive walk. + * @param recursive True to copy bindable child mounts. + * @param shared True to give previously private copies a peer group. + * @param receiver True when replaying the first staged tree for another peer. + * @param out Receives the staged tree root, possibly NULL on failure. + * @return Zero or negative errno. No backend graph changes or path replay. */ -static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, - const struct vfs_path *target,bool recursive) +static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_path *source, + const struct vfs_path *target,struct vfs_mount *mounts, + bool recursive,bool shared,bool receiver,struct vfs_mount **out) { - if(!ns || !ns->root || !vfs_path_valid(source) || !vfs_path_valid(target))return -EINVAL; - if(source->mount->ns!=ns || target->mount->ns!=ns)return -EXDEV; - if(source->mount->unbindable)return -EINVAL; - if(source->dentry->node.type!=RELIEFOS_FS_TYPE_DIR || target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; - if(source->dentry->disconnected || target->dentry->disconnected)return -ENOENT; - if(vfs_covering(ns,target))return -EBUSY; - struct vfs_path view=*source,point=*target; - struct vfs_mount *pending=NULL; - uint64_t next_id=ns->next_id; - int rc=0; + *out=NULL; for(;;) { - if(!next_id){rc=-EOVERFLOW;break;} + if(!batch->next_id)return -EOVERFLOW; + uint64_t group=view.mount->peer_group; + if(shared && !group) { + if(!batch->next_peer_id)return -EOVERFLOW; + group=batch->next_peer_id++; + } struct vfs_mount *copy; - rc=vfs_bind_clone(&view,©); - if(rc)break; - copy->id=next_id++; - vfs_path_get(&point,©->point); - copy->next=pending;pending=copy; - if(!recursive)break; + /* All parallel bind views retain the actual source, not another + * destination which may be unmounted independently. */ + const struct vfs_path *backing=receiver ? &view.mount->bind_source : &view; + int rc=vfs_bind_clone(&view,backing,false,©); + if(rc)return rc; + vfs_stage_mount(batch,copy,&point,batch->next_id++,group); + if(!*out)*out=copy; + if(!recursive)return 0; /* Walk the two trees in step. Their mountpoint dentries are shared; - * only the parent attachment changes. Never visit a staged clone. */ - struct vfs_mount *child=vfs_bind_child_mount(&view,ns->mounts); + * only the parent attachment changes. The inventory stays fixed. */ + struct vfs_mount *child=vfs_bind_child_mount(&view,mounts); while(!child && view.mount!=source->mount) { struct vfs_mount *previous=view.mount; copy=copy->point.mount; view=(struct vfs_path){previous->point.mount,copy->root}; child=vfs_bind_child_mount(&view,previous->next); } - if(!child)break; + if(!child)return 0; view=(struct vfs_path){child,child->root}; point=(struct vfs_path){copy,child->point.dentry}; } - if(rc) { - /* Reverse creation order always releases descendants before parents. */ - while(pending) { - struct vfs_mount *copy=pending;pending=copy->next; - vfs_path_put(©->point);vfs_mount_put(copy); - } - return rc; - } +} - /* Transfer the staging references to the namespace in one commit. */ - struct vfs_mount **tail=&pending; - for(;*tail;tail=&(*tail)->next) { - (*tail)->ns=ns; - if(vfs_notify_mount_created)vfs_notify_mount_created(*tail); +/** @brief Publish a directory bind and all shared peer copies atomically. + * @param ns Borrowed execution-owned namespace. + * @param source Borrowed retained source directory in ns. + * @param target Borrowed retained destination directory in ns. + * @param recursive True to copy the source's bindable descendant branches. + * @return Zero or negative errno without consuming IDs or partially publishing. + */ +static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, + const struct vfs_path *target,bool recursive) +{ + if(!ns || !ns->root || !vfs_path_valid(source) || !vfs_path_valid(target))return -EINVAL; + if(source->mount->ns!=ns || target->mount->ns!=ns)return -EXDEV; + if(source->mount->unbindable)return -EINVAL; + if(source->dentry->node.type!=RELIEFOS_FS_TYPE_DIR || target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; + if(source->dentry->disconnected || target->dentry->disconnected)return -ENOENT; + if(vfs_covering(ns,target))return -EBUSY; + + struct vfs_mount_batch batch={.next_id=ns->next_id,.next_peer_id=ns->next_peer_id}; + struct vfs_mount *first; + bool shared=target->mount->peer_group!=0; + int rc=vfs_stage_bind_tree(&batch,source,target,ns->mounts,recursive,shared,false,&first); + if(!rc && shared) { + struct vfs_mount *inventory=batch.pending; + struct vfs_path view={first,first->root}; + for(struct vfs_mount *peer=ns->mounts;!rc && peer;peer=peer->next) { + if(!vfs_mount_receiver(target,peer))continue; + struct vfs_path point={peer,target->dentry}; + if(vfs_covering(ns,&point)){rc=-EOPNOTSUPP;break;} + struct vfs_mount *copy; + rc=vfs_stage_bind_tree(&batch,&view,&point,inventory,recursive,false,true,©); + } } - *tail=ns->mounts;ns->mounts=pending;ns->next_id=next_id; - return 0; + return vfs_finish_mount_batch(ns,&batch,rc); } /** @brief Publish one directory view without copying submounts. @@ -433,6 +559,13 @@ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *sou return vfs_bind_tree(ns,source,target,true); } +/** @brief Move a subtree only when neither parent needs propagation. + * @param ns Borrowed execution-owned namespace. + * @param source Retained mounted root, excluding the namespace anchor. + * @param target Retained destination directory in ns. + * @return Zero or negative errno before mutation. Moving out of a shared + * parent is invalid; moving into one needs not-yet-supported propagation. + */ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path *target) { if(!ns || !vfs_path_valid(source) || !vfs_path_valid(target))return -EINVAL; @@ -441,6 +574,8 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const if(source->dentry!=mount->root)return -EINVAL; if(mount==ns->root || !mount->point.mount)return -EBUSY; if(target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; + if(mount->point.mount->peer_group)return -EINVAL; + if(target->mount->peer_group)return -EOPNOTSUPP; for(struct vfs_mount *ancestor=target->mount;ancestor;ancestor=ancestor->point.mount) for(struct vfs_mount *backing=ancestor;backing;backing=backing->bind_source.mount) if(backing==mount)return -ELOOP; @@ -449,29 +584,134 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path old=mount->point;mount->point=replacement;vfs_path_put(&old);return 0; } +/** @brief Disconnect a single leaf during namespace destruction. + * @param ns Borrowed execution-owned namespace. + * @param mount Live leaf with no remaining dependents in ns. + */ static void vfs_mount_detach(struct vfs_namespace *ns,struct vfs_mount *mount) { struct vfs_mount **link=&ns->mounts; while(*link && *link!=mount)link=&(*link)->next; if(*link)*link=mount->next; struct vfs_path old=mount->point;mount->point=(struct vfs_path){0}; - mount->ns=NULL;mount->next=NULL;vfs_path_put(&old);vfs_mount_put(mount); + mount->ns=NULL;mount->next=NULL;mount->peer_group=0;mount->unbindable=false; + vfs_path_put(&old);vfs_mount_put(mount); } +/** @brief Mark origin mounts and the matching slots of their shared parents. + * @param ns Borrowed namespace under execution ownership. + * @param root Root of the requested unmount. + * @param subtree True to send events for the entire original subtree. + * Only parents' groups determine delivery. A receiver which has any child + * outside the batch is kept, even if other children of that receiver detach. + */ +static void vfs_select_unmounts(struct vfs_namespace *ns,struct vfs_mount *root,bool subtree) +{ + bool propagated=false; + for(struct vfs_mount *event=subtree ? ns->mounts : root;event; + event=subtree ? event->next : NULL) { + if(subtree && !vfs_mount_below(root,event))continue; + event->unmount_selected=true; + struct vfs_mount *parent=event->point.mount; + if(!parent || !parent->peer_group)continue; + for(struct vfs_mount *receiver=ns->mounts;receiver;receiver=receiver->next) { + const struct vfs_path *point=&receiver->point; + if(point->mount && point->mount!=parent && point->mount->peer_group==parent->peer_group && + point->dentry==event->point.dentry) { + receiver->unmount_selected=true;propagated=true; + } + } + } + if(propagated) { + for(struct vfs_mount *child=ns->mounts;child;child=child->next) { + if(child->unmount_selected)continue; + for(struct vfs_mount *parent=child->point.mount;parent && parent->unmount_selected; + parent=parent->point.mount)parent->unmount_selected=false; + } + } +} + +/** @brief Reject busy mounts before changing any member of an unmount batch. + * @param ns Borrowed execution-owned namespace with selected mounts marked. + * @param root Origin mount with the caller's lookup reference. + * @return Zero or negative busy/provider errno. Replica lifetime pins and + * edges disappearing in this batch are not external path references. A + * regular bind outside the batch still pins its source as before. + */ +static int vfs_unmount_preflight(const struct vfs_namespace *ns,const struct vfs_mount *root) +{ + for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { + if(!mount->unmount_selected)continue; + uint64_t expected=1+(mount==root)+mount->propagation_pins; + struct vfs_mount *backing=mount->propagation_backing ? mount->bind_source.mount : mount; + uint64_t replicas=0; + bool first_replica=true; + for(struct vfs_mount *other=ns->mounts;other;other=other->next) { + if(!other->unmount_selected)continue; + if(other->point.mount==mount)++expected; + if(other->bind_source.mount==mount && !other->propagation_backing)++expected; + if(other->bind_source.mount==backing && other->propagation_backing) { + ++replicas; + if(other->idid)first_replica=false; + } + } + if(mount->references!=expected)return -EBUSY; + /* Check native backing users once only when origin and all lifetime + * replicas are going away. The origin may already be detached. */ + bool final_check=mount->propagation_backing ? !backing->ns && first_replica && + backing->references==backing->propagation_pins : !mount->bind_source.mount; + if(final_check && replicas==backing->propagation_pins && backing->ops->can_unmount) { + int rc=backing->ops->can_unmount(backing->context,backing->root->backend_pin); + if(rc)return rc; + } + } + return 0; +} + +/** @brief Unlink the entire selected graph before dropping retained edges. + * @param ns Borrowed execution-owned namespace with selected mounts marked. + * @param lazy True to keep external paths walkable and defer final teardown. + * No allocation, and lazy unmount invokes no synchronous backend finish. + */ +static void vfs_disconnect_unmounts(struct vfs_namespace *ns,bool lazy) +{ + struct vfs_mount *detached=NULL,**link=&ns->mounts; + while(*link) { + struct vfs_mount *mount=*link; + if(!mount->unmount_selected){link=&mount->next;continue;} + *link=mount->next;mount->next=detached;detached=mount; + mount->ns=NULL;mount->lazy_detached=lazy; + mount->peer_group=0;mount->unbindable=false;mount->unmount_selected=false; + } + while(detached) { + struct vfs_mount *mount=detached;detached=mount->next;mount->next=NULL; + vfs_path_put(&mount->point);vfs_mount_put(mount); + } +} + +/** @brief Detach one idle mount and all removable counterparts atomically. + * @param ns Borrowed execution-owned namespace. + * @param path Retained origin root, excluding the permanent anchor. + * @return Zero or negative errno; failures leave all attachments intact. + */ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path) { if(!ns || !vfs_path_valid(path))return -EINVAL; - struct vfs_mount *mount=path->mount; - if(mount->ns!=ns)return -EXDEV; - if(path->dentry!=mount->root)return -EINVAL; - if(mount==ns->root || !mount->point.mount || mount->references!=2)return -EBUSY; - if(!mount->bind_source.mount && mount->ops->can_unmount) { - int rc=mount->ops->can_unmount(mount->context,mount->root->backend_pin);if(rc)return rc; - } - vfs_mount_detach(ns,mount);return 0; + struct vfs_mount *root=path->mount; + if(root->ns!=ns)return -EXDEV; + if(path->dentry!=root->root)return -EINVAL; + if(root==ns->root || !root->point.mount)return -EBUSY; + for(struct vfs_mount *child=ns->mounts;child;child=child->next) + if(child->point.mount==root)return -EBUSY; + + vfs_select_unmounts(ns,root,false); + int rc=vfs_unmount_preflight(ns,root); + if(!rc)vfs_disconnect_unmounts(ns,false); + else for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next)mount->unmount_selected=false; + return rc; } -/** @brief Disconnect a visible subtree before releasing any association. +/** @brief Disconnect a visible subtree and its removable shared counterparts. * @param ns Borrowed namespace under execution ownership. * @param path Held selected mount root, excluding the permanent anchor. * @return Zero or negative errno before mutation. Retained paths keep their @@ -483,19 +723,8 @@ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path) struct vfs_mount *root=path->mount; if(root->ns!=ns || path->dentry!=root->root)return -EINVAL; if(root==ns->root || !root->point.mount)return -EBUSY; - - struct vfs_mount *detached=NULL,**link=&ns->mounts; - while(*link) { - struct vfs_mount *mount=*link; - if(!vfs_mount_below(root,mount)){link=&mount->next;continue;} - *link=mount->next;mount->next=detached;detached=mount; - mount->ns=NULL;mount->lazy_detached=true; - } - while(detached) { - struct vfs_mount *mount=detached;detached=mount->next;mount->next=NULL; - vfs_path_put(&mount->point);vfs_mount_put(mount); - } - return 0; + vfs_select_unmounts(ns,root,true); + vfs_disconnect_unmounts(ns,true);return 0; } int vfs_namespace_destroy(struct vfs_namespace *ns) diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 1a263c54..5f3b75f9 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -194,7 +194,7 @@ bool vfs_path_same_filesystem(const struct vfs_path *left,const struct vfs_path * graph traversal, locking or ownership transfer occurs. */ struct vfs_namespace *vfs_path_namespace(const struct vfs_path *path); -struct vfs_namespace {struct vfs_mount *root,*mounts;uint64_t next_id;}; +struct vfs_namespace {struct vfs_mount *root,*mounts;uint64_t next_id,next_peer_id;}; /** @brief Assign immutable diagnostic identity before publishing a mount. * @param mount Owned detached mount, required; attachment returns EBUSY. * @param source Nonempty kernel source label, copied with PATH_MAX bounds. @@ -533,21 +533,22 @@ int vfs_namespace_destroy(struct vfs_namespace *ns); * @return Zero or negative errno. Serialized task context. */ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out); -/** @brief Attach a detached mount at a directory object, retaining both sides. +/** @brief Attach an unpublished mount and propagate to eligible shared peers. * @param ns Shared namespace under execution ownership. * @param mount Unpublished mount; caller retains its own handle. * @param target Held directory path in ns; an already covered slot is busy. - * @return Zero or negative errno without partial publication. Task context. + * @return Zero or negative errno without partial publication or ID use on + * failure. Covered receiver insertion is not supported. Task context. */ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount, const struct vfs_path *target); -/** @brief Isolate one mount attachment or its complete visible subtree. +/** @brief Change the propagation type of a mount or its visible subtree. * @param ns Borrowed execution-owned namespace. * @param path Held root of an attached mount in ns, not an interior dentry. * @param flags Exactly one propagation type, optionally with MS_REC. - * @return Zero or negative errno without partial changes. MS_PRIVATE and - * MS_UNBINDABLE do not change access policy or call into the backend. - * Peer/slave propagation is not yet supported. + * @return Zero or negative errno without partial changes. MS_SHARED assigns + * peer groups to nonshared mounts; MS_PRIVATE and MS_UNBINDABLE leave a group. + * No backend or access policy changes. MS_SLAVE is not yet supported. */ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *path,uint64_t flags); /** @brief Bind one directory inode into a separate nonrecursive attachment. @@ -556,7 +557,8 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa * @param target Destination directory, required in the same namespace. * @return Zero or negative errno without a partial attachment. Inherits * source mount policy; shares inode identities and backend lifetime without - * duplicating provider destruction. Child mounts are not copied and an + * duplicating provider destruction. Joins the source's shared group and + * propagates under a shared destination. Child mounts are not copied and an * unbindable source returns EINVAL. */ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, @@ -567,6 +569,7 @@ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, * @param target Uncovered destination directory in the same namespace. * @return Zero or negative errno without publishing a partial tree. Each clone * has an independent ID and mount policy but pins the original backing objects. + * Each eligible shared destination peer receives the same bindable tree. * Unbindable descendant branches are skipped; an unbindable source is rejected. */ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *source, @@ -575,23 +578,26 @@ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *sou * @param ns Namespace under execution ownership. * @param source Held root of an attached mount, never the namespace base root. * @param target Held destination directory path in the same namespace. - * @return Zero or negative errno; cycles/cross-namespace/invalid targets leave - * the old attachment unchanged. No callbacks or allocation during commit. + * @return Zero or negative errno; moving out of a shared parent gives EINVAL, + * moving into one is unsupported. Rejected moves leave the attachment intact. + * No callbacks or allocation during commit. */ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); -/** @brief Detach an unused mounted tree root using ordinary Linux busy semantics. +/** @brief Unmount one root and its removable shared propagation counterparts. * @param ns Namespace under execution ownership. * @param path The caller's sole external path to the mounted root. - * @return Zero or negative errno. Children/other held paths keep it busy; - * success retains the caller's path until vfs_path_put, no forced free. + * @return Zero or negative errno. The origin must have no child mounts; a + * receiver with children is skipped. Other held paths on selected mounts + * keep the entire operation busy. Success does not consume the caller's path. */ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path); -/** @brief Lazily disconnect a mounted subtree without ordinary busy checking. +/** @brief Lazily disconnect a subtree and eligible propagated attachments. * @param ns Borrowed namespace under execution ownership. * @param path Retained visible root of a mount, not the namespace anchor. - * @return Zero or negative errno. Held paths remain usable; final cleanup - * is deferred. No new allocations or synchronous backend flush on detach. + * @return Zero or negative errno. Receivers with unrelated children remain + * attached. Held paths remain usable and final cleanup is deferred. No new + * allocations or synchronous backend flush on detach. */ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path); /** @brief Prepare retained directory-name changes before a backend rename. diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 3ef8a078..599b4b0f 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -45,13 +45,14 @@ static int mount_bind(struct vfs_namespace *ns,struct task *task,uint64_t source vfs_path_put(&from.path);vfs_path_put(&to.path);return rc; } -/** @brief Detach the selected visible mount; only ordinary unmount syncs. +/** @brief Detach the selected visible mount and applicable shared counterparts. * @param ns Borrowed execution-owned namespace. * @param task Authorized caller retaining any retry scope. * @param target User target pathname pointer, required. * @param flags Low-32-bit Linux umount flags; nofollow is supported. * @return Zero or input/unsupported/lookup/busy/provider errno. MNT_DETACH - * immediately disconnects the subtree; forced/expire operations are unsupported. + * immediately disconnects the subtree and removable propagated mounts; + * forced/expire operations are unsupported. * Only ordinary unmount can wait in sync; both discard redundant lookup refs * before detaching. The local path pins the provider across the operation. */ @@ -87,7 +88,7 @@ static int mount_bind_remount(struct vfs_namespace *ns,struct task *task,uint64_ vfs_path_put(&found.path);return rc; } -/** @brief Change propagation on the actual selected mount attachment. +/** @brief Apply a propagation type to the selected mount or its subtree. * @param ns Borrowed namespace under execution ownership. * @param task Authorized caller with retry-stable pathname state. * @param target Required user mountpoint pathname, following final symlinks. diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 2aa36b75..2ba85889 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -3033,6 +3033,191 @@ static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_pat puts("PASS recursive bind: subdirectory boundary, sibling/nested topology, distinct policies and OOM rollback"); } +/** @brief Read one mountinfo row's shared peer ID, or zero for a private mount. + * @param ns Borrowed namespace. @param root Retained mount table viewer root. + * @param point Expected absolute mountpoint, with no mountinfo escapes. + * @return The parsed peer group ID; the fixture requires a matching row. + */ +static unsigned long long fixture_shared_id(struct vfs_namespace *ns,const struct vfs_path *root, + const char *point) +{ + char table[6144],field[128];uint32_t count=0; + assert(!vfs_read_mount_table(ns,root,true,0,table,sizeof(table)-1,&count));table[count]=0; + assert(snprintf(field,sizeof(field)," %s ",point)<(int)sizeof(field)); + char *row=strstr(table,field);assert(row); + char *separator=strstr(row," - ");assert(separator); + char *tag=strstr(row," shared:"); + return tag && tagnext_id,covered_peer_id=ns->next_peer_id; + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,type,0,0)==-EOPNOTSUPP); + assert(ns->next_id==covered_id && ns->next_peer_id==covered_peer_id); + assert(!vfs_path_lookup(ns,root,root,"/shared-b/covered",0,&point)); + assert(!vfs_path_lookup(ns,root,root,"/shared-b",0,&b)); + assert(vfs_path_mount_id(&point)==vfs_path_mount_id(&b));vfs_path_put(&point);vfs_path_put(&b); + strcpy(user.target,"/shared-a/covered"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + + assert(!vfs_path_lookup(ns,root,root,"/shared-a/outside",0,&point)); + assert(!storage_new_tmpfs_mount("shared event",0,NULL,1000,1000,&mount)); + const uint64_t next_id=ns->next_id,peer_id=ns->next_peer_id; + test_fail_heap_after=1; + assert(vfs_mount_attach(ns,mount,&point)==-ENOMEM); + test_fail_heap_after=-1; + assert(ns->next_id==next_id && ns->next_peer_id==peer_id); + assert(!vfs_path_lookup(ns,root,root,"/shared-a/outside",0,&found)); + assert(vfs_path_equal(&found,&point));vfs_path_put(&found); + assert(!vfs_path_lookup(ns,root,root,"/shared-b/outside",0,&found)); + assert(vfs_path_same_inode(&found,&point));vfs_path_put(&found); + assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); + assert(ns->next_id==next_id+2); + unsigned long long event=fixture_shared_id(ns,root,"/shared-a/outside"); + assert(event && event!=group && fixture_shared_id(ns,root,"/shared-b/outside")==event); + assert(vfs_path_lookup(ns,root,root,"/shared-narrow/outside",0,&found)==-ENOENT); + assert(!vfs_path_lookup(ns,root,root,"/shared-b/outside",0,&b)); + strcpy(user.target,"/shared-a/outside"); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)==-EBUSY); + vfs_path_put(&b); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + assert(!vfs_path_lookup(ns,root,root,"/shared-b/outside",0,&b)); + assert(!vfs_path_lookup(ns,root,root,"/shared-a/outside",0,&a)); + assert(vfs_path_same_inode(&a,&b));vfs_path_put(&a);vfs_path_put(&b); + assert(!vfs_kernel_mkdir(ns,"/shared-b/outside/after",0755)); + + strcpy(user.source,"shared source");strcpy(user.target,"/shared-source"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,0,0)); + assert(!vfs_kernel_mkdir(ns,"/shared-source/child",0755)); + strcpy(user.target,"/shared-source/child"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,0,0)); + assert(!vfs_kernel_mkdir(ns,"/shared-source/child/nested",0755)); + assert(!vfs_path_lookup(ns,root,root,"/shared-source",0,&a)); + assert(!vfs_path_lookup(ns,root,root,"/shared-a/p/event",0,&point)); + const uint64_t bind_id=ns->next_id,bind_peer_id=ns->next_peer_id; + /* The first tree and one receiver tree fit, but not the final receiver. */ + test_fail_heap_after=8; + assert(vfs_mount_bind_recursive(ns,&a,&point)==-ENOMEM); + test_fail_heap_after=-1; + assert(ns->next_id==bind_id && ns->next_peer_id==bind_peer_id); + assert(!fixture_shared_id(ns,root,"/shared-source")); + assert(vfs_path_lookup(ns,root,root,"/shared-a/p/event/child",0,&found)==-ENOENT); + assert(vfs_path_lookup(ns,root,root,"/shared-b/p/event/child",0,&found)==-ENOENT); + assert(vfs_path_lookup(ns,root,root,"/shared-narrow/event/child",0,&found)==-ENOENT); + vfs_path_put(&point);vfs_path_put(&a); + strcpy(user.source,"/shared-source");strcpy(user.target,"/shared-a/p/event"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,UINT64_MAX,MS_BIND|MS_REC,0)); + unsigned long long child=fixture_shared_id(ns,root,"/shared-a/p/event/child"); + assert(child && child==fixture_shared_id(ns,root,"/shared-b/p/event/child") && + child==fixture_shared_id(ns,root,"/shared-narrow/event/child")); + assert(!fixture_shared_id(ns,root,"/shared-source/child")); + strcpy(user.source,"nested event");strcpy(user.target,"/shared-narrow/event/child/nested"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,0,0)); + assert(!vfs_path_lookup(ns,root,root,"/shared-a/p/event/child/nested",0,&a)); + assert(!vfs_path_lookup(ns,root,root,"/shared-b/p/event/child/nested",0,&b)); + assert(vfs_path_same_inode(&a,&b));vfs_path_put(&a); + strcpy(user.target,"/shared-a/p/event"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,MNT_DETACH,0,0,0)); + assert(vfs_path_lookup(ns,root,root,"/shared-b/p/event/child",0,&found)==-ENOENT); + assert(vfs_path_lookup(ns,root,root,"/shared-narrow/event/child",0,&found)==-ENOENT); + assert(!vfs_path_namespace(&b));vfs_path_put(&b); + while(vfs_reclaim_mounts(32)){} + + strcpy(user.source,"/shared-source"); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_MOVE,0)==-EOPNOTSUPP); + for(unsigned lazy=0;lazy<2;++lazy) { + strcpy(user.source,"peer with local child");strcpy(user.target,"/shared-a/p/event"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,0,0)); + assert(!vfs_kernel_mkdir(ns,"/shared-b/p/event/local",0755)); + strcpy(user.target,"/shared-b/p/event"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_PRIVATE,0)); + strcpy(user.target,"/shared-b/p/event/local"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,0,0)); + strcpy(user.source,"/shared-a/p/event");strcpy(user.target,"/shared-source-copy"); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_MOVE,0)==-EINVAL); + strcpy(user.target,"/shared-a/p/event"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,lazy ? MNT_DETACH : 0,0,0,0)); + assert(vfs_path_lookup(ns,root,root,"/shared-a/p/event/local",0,&found)==-ENOENT); + assert(vfs_path_lookup(ns,root,root,"/shared-narrow/event/local",0,&found)==-ENOENT); + assert(!vfs_path_lookup(ns,root,root,"/shared-b/p/event/local",0,&b));vfs_path_put(&b); + assert(!vfs_kernel_mkdir(ns,"/shared-b/p/event/still-writable",0755)); + while(vfs_reclaim_mounts(32)){} + strcpy(user.target,"/shared-b/p/event/local"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + strcpy(user.target,"/shared-b/p/event"); + if(!lazy) { + /* A last live replica still has to check native backing users. */ + struct storage_inode_ref *pin=NULL; + assert(!vfs_path_lookup(ns,root,root,user.target,0,&b)); + assert(!storage_inode_get(vfs_path_node(&b),&pin) && pin);vfs_path_put(&b); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)==-EBUSY); + assert(!storage_inode_put(pin)); + } + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + while(vfs_reclaim_mounts(32)){} + } + + strcpy(user.source,"/shared-source");strcpy(user.target,"/shared-source"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_SHARED|MS_REC,0)); + unsigned long long source_group=fixture_shared_id(ns,root,"/shared-source"); + unsigned long long source_child=fixture_shared_id(ns,root,"/shared-source/child"); + assert(source_group && source_child && source_group!=source_child); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_SHARED|MS_REC,0)); + assert(fixture_shared_id(ns,root,"/shared-source")==source_group); + assert(fixture_shared_id(ns,root,"/shared-source/child")==source_child); + strcpy(user.target,"/shared-source-copy"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_BIND|MS_REC,0)); + assert(fixture_shared_id(ns,root,"/shared-source-copy")==source_group); + assert(fixture_shared_id(ns,root,"/shared-source-copy/child")==source_child); + strcpy(user.target,"/shared-source/child"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + assert(vfs_path_lookup(ns,root,root,"/shared-source-copy/child/nested",0,&found)==-ENOENT); + + strcpy(user.target,"/shared-b"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_PRIVATE,0)); + assert(!fixture_shared_id(ns,root,"/shared-b") && fixture_shared_id(ns,root,"/shared-a")==group); + const char *cleanup[]={"/shared-source-copy","/shared-source","/shared-narrow","/shared-b","/shared-a"}; + for(unsigned i=0;i Date: Sun, 29 Nov 2026 00:53:58 +0800 Subject: [PATCH 10/97] feat(vfs): propagate mount events downstream to slaves --- .../en/LC_MESSAGES/userspace-api/abi.po | 14 +- .../ja/LC_MESSAGES/userspace-api/abi.po | 14 +- Documentation/userspace-api/abi.rst | 25 +- fs/vfs/mount_internal.h | 1 + fs/vfs/mount_table.c | 3 + fs/vfs/mount_tree.c | 248 ++++++++++++------ include/reliefnt/mount.h | 17 +- kernel/syscall/fs/mount.c | 2 +- tools/tests/mount_backend_test.c | 183 ++++++++++++- 9 files changed, 390 insertions(+), 117 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 3d29fd2e..372578e5 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -99,11 +99,17 @@ msgstr "Invalid values and nonzero reserved arguments return EINVAL without chan msgid "挂载传播" msgstr "Mount propagation" -msgid "``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 绑定共享挂载时,副本加入源的组。``MS_PRIVATE`` 使目标离开其组; ``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。 ``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:`` 或 ``unbindable``。" -msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` creates a peer group for a target that is not already shared. Binding a shared mount joins the copy to the source group. ``MS_PRIVATE`` removes the target from its group; ``MS_UNBINDABLE`` also prohibits use as a bind source and prunes its subtree from recursive binds. ``MS_REC`` applies the selected type to the target and its existing submounts; it neither merges separate submounts into one group nor changes an existing shared group ID. Changing the type requires ``CAP_SYS_ADMIN`` and a target at a mount root. It does not change mount access policy or filesystem state. ``/proc/self/mountinfo`` reports the optional field ``shared:`` or ``unbindable``." +msgid "``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 ``MS_SLAVE`` 使共享挂载离开对等组,并从剩余组成员接收传播;没有剩余成员时 继承原上游组,若无上游则变成 private。对非共享挂载执行 ``MS_SLAVE`` 不改变 其类型。slave 可再设为 shared,保留其上游关系。bind 副本继承源的传播关系。" +msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` creates a peer group for a nonshared target. ``MS_SLAVE`` takes a shared mount out of its peer group so it receives events from the remaining peers. If none remain, it inherits the previous master group or becomes private if it has no master. ``MS_SLAVE`` leaves a nonshared mount's type unchanged. A slave can become shared without losing its master. Bind copies inherit the source's propagation relationships." -msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,其他对等挂载在相同目录对象 处接收副本;目标位于接收方 bind 根之外时不传播。没有继承源组的副本形成新组, 新挂载位于非共享父挂载下时默认是 private。所有副本一起发布;分配失败时不留下 部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出 共享父挂载返回 EINVAL。``MS_SLAVE`` 和跨命名空间传播尚不支持。" -msgstr "Creating a mount or bind (including a recursive bind) under a shared parent delivers copies at the same directory object on its other peers. An event is not delivered outside a receiving bind root. Copies that do not inherit a source group form a new group; a new filesystem mount under a nonshared parent is private by default. All copies are published together; an allocation failure leaves no partial mounts. Insertion at a covered receiver and moving into a shared parent return EOPNOTSUPP; moving out of a shared parent returns EINVAL. ``MS_SLAVE`` and propagation across namespaces are not yet supported." +msgid "``MS_PRIVATE`` 清除目标的对等组和上游关系;``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员时,其下游改接到该组 原来的上游组,若无上游则不再接收传播。" +msgstr "``MS_PRIVATE`` removes the target from its peer and master groups. ``MS_UNBINDABLE`` also rejects the target as a bind source and prunes the subtree during recursive bind. When an upstream group loses its last member, its receivers follow that group's previous master or stop receiving events if there is none." + +msgid "``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。" +msgstr "``MS_REC`` applies the selected type to the mount and its existing descendants without putting distinct submounts into one group or changing existing shared group IDs. A type change requires ``CAP_SYS_ADMIN`` and an exact mount root, and does not change mount access policy or filesystem state. ``/proc/self/mountinfo`` reports the optional tags ``shared:``, ``master:``, or ``unbindable``. It does not yet report ``propagate_from``." + +msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出共享父挂载返回 EINVAL。目前仅支持同一挂载命名空间内的传播。" +msgstr "New mounts and binds (including recursive binds) under a shared parent are copied to peers and downstream slaves at the same directory object. Events do not go upstream. A receiver whose bind root excludes the target is skipped, but its downstream mounts with matching directories can still receive a copy. Copies within one receiving peer group share an ID and follow the nearest upstream copy group. New filesystem mounts under nonshared parents are private by default. All copies are published together; allocation failure leaves none attached. A covered receiving slot or a move into a shared parent returns EOPNOTSUPP. Moving out of a shared parent returns EINVAL. Propagation is supported only within a single mount namespace." msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。存在不随事件卸载的子挂载时保留该接收分支。 延迟卸载为目标子树中的每个挂载传播事件,不因打开路径阻塞,仍保留接收方的无关 子挂载。接收方保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" msgstr "An unmount propagates from the target’s parent to the matching mountpoints. An ordinary unmount returns EBUSY without removing any mount if a removable receiver still has an open path. A receiver is kept when it has submounts that are not being removed. Lazy unmount propagates each mount in the requested subtree without waiting for open paths and preserves unrelated submounts at receivers. A retained receiver can still use its backing even after the initiating attachment is detached." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 7877ca60..4f8b77d8 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -92,11 +92,17 @@ msgstr "不正な値やゼロ以外の予約引数には、状態を変更せず msgid "挂载传播" msgstr "マウントの伝播" -msgid "``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 绑定共享挂载时,副本加入源的组。``MS_PRIVATE`` 使目标离开其组; ``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。 ``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:`` 或 ``unbindable``。" -msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` は、まだ共有されていない対象にピアグループを作ります。共有マウントをバインドすると、コピーはバインド元のグループに加わります。``MS_PRIVATE`` は対象をグループから外します。``MS_UNBINDABLE`` はさらにバインド元としての使用を禁止し、再帰バインドからそのサブツリーを除外します。``MS_REC`` は選択した種別を対象と既存の子マウントに適用しますが、別々の子マウントを同じグループにまとめたり、既存の共有グループ ID を変更したりしません。種別の変更には ``CAP_SYS_ADMIN`` が必要で、対象はマウントのルートでなければなりません。アクセス方針やファイルシステムの状態は変わりません。``/proc/self/mountinfo`` はオプションフィールド ``shared:`` または ``unbindable`` を表示します。" +msgid "``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 ``MS_SLAVE`` 使共享挂载离开对等组,并从剩余组成员接收传播;没有剩余成员时 继承原上游组,若无上游则变成 private。对非共享挂载执行 ``MS_SLAVE`` 不改变 其类型。slave 可再设为 shared,保留其上游关系。bind 副本继承源的传播关系。" +msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` は、共有されていない対象にピアグループを作ります。``MS_SLAVE`` は共有マウントをピアグループから外し、残ったピアからイベントを受け取るようにします。ピアが残らなければ以前の上流グループを引き継ぎ、上流がなければプライベートになります。共有されていないマウントに対する ``MS_SLAVE`` は種別を変えません。スレーブは上流との関係を保ったまま共有にできます。バインドのコピーは元の伝播関係を引き継ぎます。" -msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,其他对等挂载在相同目录对象 处接收副本;目标位于接收方 bind 根之外时不传播。没有继承源组的副本形成新组, 新挂载位于非共享父挂载下时默认是 private。所有副本一起发布;分配失败时不留下 部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出 共享父挂载返回 EINVAL。``MS_SLAVE`` 和跨命名空间传播尚不支持。" -msgstr "共有マウントの下に新しいマウントやバインド(再帰バインドを含む)を作ると、他のピアの同じディレクトリオブジェクトにコピーが作られます。受信側のバインドルート外には伝播しません。バインド元のグループを継承しないコピーは新しいグループを作り、非共有の親の下に作る新規ファイルシステムマウントは既定で private です。すべてのコピーを一度に公開し、割り当てに失敗しても一部のマウントは残りません。受信位置がすでにマウントで覆われている場合や共有の親への移動は EOPNOTSUPP、共有の親からの移動は EINVAL を返します。``MS_SLAVE`` と名前空間間の伝播にはまだ対応していません。" +msgid "``MS_PRIVATE`` 清除目标的对等组和上游关系;``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员时,其下游改接到该组 原来的上游组,若无上游则不再接收传播。" +msgstr "``MS_PRIVATE`` は対象のピアグループと上流グループとの関係を解除します。``MS_UNBINDABLE`` はさらにバインド元としての使用を禁止し、再帰バインドからそのサブツリーを除外します。上流グループの最後のメンバーが離脱すると、その下流は以前の上流グループを引き継ぎ、上流がなければイベントを受け取らなくなります。" + +msgid "``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。" +msgstr "``MS_REC`` は選択した種別を対象と既存の子マウントに適用しますが、別々の子マウントを同じグループにまとめたり、既存の共有グループ ID を変更したりしません。種別の変更には ``CAP_SYS_ADMIN`` が必要で、対象はマウントのルートでなければなりません。アクセス方針やファイルシステムの状態は変わりません。``/proc/self/mountinfo`` はオプションフィールド ``shared:``、``master:``、``unbindable`` を表示します。``propagate_from`` はまだ表示しません。" + +msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出共享父挂载返回 EINVAL。目前仅支持同一挂载命名空间内的传播。" +msgstr "共有の親マウントの下でマウントやバインド(再帰バインドを含む)を作成すると、ピアと下流のスレーブは同じディレクトリオブジェクトの位置にコピーを受け取ります。イベントは上流には伝わりません。対象をバインドルートに含まない受信側はスキップされますが、対応するディレクトリを含む下流には伝播します。同じ受信ピアグループ内のコピーは ID を共有し、最も近い上流のコピーグループに従います。非共有の親の下の新規ファイルシステムマウントは既定でプライベートです。コピーはすべて一括して公開され、割り当てに失敗しても一部だけが残ることはありません。すでに別のマウントがある受信位置や共有の親への移動は EOPNOTSUPP、共有の親からの移動は EINVAL になります。伝播は単一のマウント名前空間内に限られます。" msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。存在不随事件卸载的子挂载时保留该接收分支。 延迟卸载为目标子树中的每个挂载传播事件,不因打开路径阻塞,仍保留接收方的无关 子挂载。接收方保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" msgstr "アンマウントは対象の親から対応するマウントポイントへ伝播します。通常のアンマウントでは、取り外し対象となる受信側に開いたパスがあれば、どのマウントも取り外さず EBUSY を返します。イベントで取り外されない子マウントがあれば、その受信側は残ります。遅延アンマウントは開いたパスを待たずに対象サブツリー内の各マウントのイベントを伝播し、受信側の無関係な子マウントを残します。受信側に残ったマウントは、操作元が切り離された後もバックエンドを使えます。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index e75005dc..d3b778e0 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -65,18 +65,25 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 ================== ``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 -绑定共享挂载时,副本加入源的组。``MS_PRIVATE`` 使目标离开其组; -``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。 +``MS_SLAVE`` 使共享挂载离开对等组,并从剩余组成员接收传播;没有剩余成员时 +继承原上游组,若无上游则变成 private。对非共享挂载执行 ``MS_SLAVE`` 不改变 +其类型。slave 可再设为 shared,保留其上游关系。bind 副本继承源的传播关系。 + +``MS_PRIVATE`` 清除目标的对等组和上游关系;``MS_UNBINDABLE`` 还禁止把目标作为 +bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员时,其下游改接到该组 +原来的上游组,若无上游则不再接收传播。 + ``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 -``shared:`` 或 ``unbindable``。 - -在共享父挂载下创建挂载或 bind(包括递归 bind)时,其他对等挂载在相同目录对象 -处接收副本;目标位于接收方 bind 根之外时不传播。没有继承源组的副本形成新组, -新挂载位于非共享父挂载下时默认是 private。所有副本一起发布;分配失败时不留下 -部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出 -共享父挂载返回 EINVAL。``MS_SLAVE`` 和跨命名空间传播尚不支持。 +``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。 + +在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 +相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, +但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 +上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; +分配失败不留下部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 +EOPNOTSUPP;移出共享父挂载返回 EINVAL。目前仅支持同一挂载命名空间内的传播。 卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。存在不随事件卸载的子挂载时保留该接收分支。 diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 18bd92df..276c2c69 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -25,6 +25,7 @@ struct vfs_mount { struct vfs_namespace *ns; struct vfs_mount *next,*notify_next; struct vfs_mount **notify_link; + struct vfs_mount *master; /* Weak edge to a live member of the upstream peer group. */ struct vfs_path point,bind_source; struct vfs_dentry *root; const struct vfs_backend_ops *ops; diff --git a/fs/vfs/mount_table.c b/fs/vfs/mount_table.c index 19b4b19c..d3d85d76 100644 --- a/fs/vfs/mount_table.c +++ b/fs/vfs/mount_table.c @@ -99,6 +99,9 @@ static int mount_line(const struct vfs_namespace *ns,const struct vfs_path *root if(mount->peer_group) { mount_emit(text," shared:");mount_number(text,mount->peer_group); } else if(mount->unbindable)mount_emit(text," unbindable"); + if(mount->master) { + mount_emit(text," master:");mount_number(text,mount->master->peer_group); + } mount_emit(text," - ");mount_emit(text,filesystem);mount_emit(text," "); mount_field(text,source);mount_emit(text," ");mount_options(text,vfs_super_flags(mount),true,true);mount_emit(text,"\n"); } else { diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index db05ceea..76d254f5 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -268,13 +268,34 @@ static bool vfs_mount_below(const struct vfs_mount *root,const struct vfs_mount return false; } +/** @brief Leave a peer group without orphaning its downstream attachments. + * @param ns Borrowed execution-owned namespace. + * @param mount Live departing member (a nonmember is unchanged). + * @return A live peer, or the old master if no peer remains. If the group + * survives, its receivers stay with the group; otherwise they inherit its + * master. These weak edges never pin a mount or a backend. + */ +static struct vfs_mount *vfs_leave_peer_group(struct vfs_namespace *ns,struct vfs_mount *mount) +{ + struct vfs_mount *upstream=mount->master; + if(!mount->peer_group)return upstream; + for(struct vfs_mount *peer=ns->mounts;peer;peer=peer->next) + if(peer!=mount && peer->peer_group==mount->peer_group){upstream=peer;break;} + for(struct vfs_mount *other=ns->mounts;other;other=other->next) + if(other->master==mount)other->master=upstream; + mount->peer_group=0; + return upstream; +} + /** @brief Apply one supported propagation type to selected live attachments. * @param ns Borrowed namespace under execution ownership. * @param path Retained exact root of the selected live mount. * @param flags One propagation selector and optional MS_REC. * @return Zero or negative errno. The whole change is validated before - * editing any mount or advancing the group ID counter. No allocation, backend - * callback or access-policy change. Slave propagation is not implemented. + * editing any mount or advancing the group ID counter. Making a slave retains + * an upstream group if available; private and unbindable clear the selected + * attachment's propagation membership. + * No allocation, backend callback or access-policy change. */ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *path,uint64_t flags) { @@ -282,7 +303,6 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa if(!type || (type&(type-1)) || (type&~VFS_PROPAGATION_MASK))return -EINVAL; if(!ns || !vfs_path_valid(path) || path->mount->ns!=ns || path->dentry!=path->mount->root) return -EINVAL; - if(type==MS_SLAVE)return -EOPNOTSUPP; struct vfs_mount *root=path->mount; bool recursive=(flags&MS_REC)!=0; uint64_t next=ns->next_peer_id; @@ -297,9 +317,16 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa for(struct vfs_mount *mount=recursive ? ns->mounts : root;mount; mount=recursive ? mount->next : NULL) { if(!vfs_mount_below(root,mount))continue; - mount->unbindable=type==MS_UNBINDABLE; - if(type!=MS_SHARED)mount->peer_group=0; - else if(!mount->peer_group)mount->peer_group=ns->next_peer_id++; + if(type==MS_SHARED) { + if(!mount->peer_group)mount->peer_group=ns->next_peer_id++; + mount->unbindable=false; + } else if(type==MS_SLAVE) { + if(mount->peer_group)mount->master=vfs_leave_peer_group(ns,mount); + } else { + vfs_leave_peer_group(ns,mount); + mount->master=NULL; + mount->unbindable=type==MS_UNBINDABLE; + } } return 0; } @@ -341,12 +368,11 @@ struct vfs_mount_batch { * @param batch Staging list ordered from newest to oldest for rollback. * @param mount Prepared mount; its reference transfers to the batch. * @param point Borrowed exact destination, retained by the staged mount. - * @param id Reserved mount ID. @param group Reserved or inherited peer ID. */ static void vfs_stage_mount(struct vfs_mount_batch *batch,struct vfs_mount *mount, - const struct vfs_path *point,uint64_t id,uint64_t group) + const struct vfs_path *point) { - mount->id=id;mount->peer_group=group; + mount->id=batch->next_id++; vfs_path_get(point,&mount->point); mount->next=batch->pending;batch->pending=mount; } @@ -388,55 +414,39 @@ static bool vfs_dentry_below(const struct vfs_dentry *dentry,const struct vfs_de return false; } -/** @brief Identify another shared parent containing this exact mountpoint. - * @param target Resolved origin within a shared parent, borrowed. - * @param peer Candidate live attachment in the same namespace. - * @return True for a different group member whose bind root contains target. +/** @brief Measure the downward propagation distance from a shared origin. + * @param origin Borrowed attachment sending the event. + * @param receiver Borrowed candidate attachment in the same namespace. + * @param depth Receives zero for peers, positive for downstream groups. + * @return True for a peer or downstream receiver, including origin itself + * if shared. Following upstream edges cannot route an event back upstream. */ -static bool vfs_mount_receiver(const struct vfs_path *target,const struct vfs_mount *peer) +static bool vfs_propagation_depth(const struct vfs_mount *origin,const struct vfs_mount *receiver, + uint64_t *depth) { - return peer!=target->mount && target->mount->peer_group && - peer->peer_group==target->mount->peer_group && vfs_dentry_below(target->dentry,peer->root); + *depth=0; + if(!origin->peer_group)return false; + for(;receiver;receiver=receiver->master,++*depth) + if(receiver->peer_group==origin->peer_group)return true; + return false; } -/** @brief Publish a new mount and all shared peer copies in one transaction. - * @param ns Borrowed execution-owned namespace. - * @param mount Caller-retained unpublished mount; membership takes its own ref. - * @param target Borrowed retained directory path in ns. - * @return Zero or negative errno, without consuming IDs or modifying the - * mount on failure. Already covered receiver slots are unsupported. +/** @brief Find a staged view from a particular receiver's peer group. + * @param batch Borrowed batch for this single propagation event. + * @param receiver Borrowed live shared destination parent. + * @param dentry Exact event mountpoint, identical in all receiving parents. + * @return A staged event root, or NULL if this group has no prepared view. + * Submounts of staged trees cannot match a live destination parent. */ -int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const struct vfs_path *target) +static struct vfs_mount *vfs_staged_peer(const struct vfs_mount_batch *batch, + const struct vfs_mount *receiver,const struct vfs_dentry *dentry) { - if(!ns || !ns->root || !mount || !vfs_path_valid(target))return -EINVAL; - if(target->mount->ns!=ns)return -EXDEV; - if(target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; - if(target->dentry->disconnected)return -ENOENT; - if(mount->ns || mount->point.mount || mount->lazy_detached || vfs_covering(ns,target))return -EBUSY; - if(!ns->next_id)return -EOVERFLOW; - struct vfs_mount_batch batch={.next_id=ns->next_id+1,.next_peer_id=ns->next_peer_id}; - uint64_t group=0; - int rc=0; - if(target->mount->peer_group) { - if(!batch.next_peer_id)return -EOVERFLOW; - group=batch.next_peer_id++; - struct vfs_path view={mount,mount->root}; - for(struct vfs_mount *peer=ns->mounts;peer;peer=peer->next) { - if(!vfs_mount_receiver(target,peer))continue; - struct vfs_path point={peer,target->dentry}; - if(vfs_covering(ns,&point)){rc=-EOPNOTSUPP;break;} - if(!batch.next_id){rc=-EOVERFLOW;break;} - struct vfs_mount *copy; - rc=vfs_bind_clone(&view,&view,true,©); - if(rc)break; - vfs_stage_mount(&batch,copy,&point,batch.next_id++,group); - } - } - if(!rc) { - ++mount->references; - vfs_stage_mount(&batch,mount,target,ns->next_id,group); + for(struct vfs_mount *mount=batch->pending;mount;mount=mount->next) { + const struct vfs_mount *parent=mount->point.mount; + if(mount->point.dentry==dentry && parent->ns==receiver->ns && + parent->peer_group==receiver->peer_group)return mount; } - return vfs_finish_mount_batch(ns,&batch,rc); + return NULL; } /** @brief Find the next direct submount within the selected directory view. @@ -454,26 +464,30 @@ static struct vfs_mount *vfs_bind_child_mount(const struct vfs_path *view,struct return NULL; } +enum vfs_mount_copy { VFS_COPY_BIND,VFS_COPY_PEER,VFS_COPY_SLAVE }; + /** @brief Stage one bind tree using previously resolved directory identities. * @param batch Transaction owning all clones, including partial trees on error. - * @param source Source view in the live graph or first staged tree. + * @param source Source view in the live graph or a previously staged tree. * @param target Borrowed retained destination for this tree. * @param mounts Fixed inventory of source attachments for a recursive walk. * @param recursive True to copy bindable child mounts. - * @param shared True to give previously private copies a peer group. - * @param receiver True when replaying the first staged tree for another peer. + * @param shared True if the destination parent is shared. + * @param kind A direct bind, or a replay sharing or following the source group. + * @param fresh True for replicas of a new mount; their backing pins are internal. * @param out Receives the staged tree root, possibly NULL on failure. * @return Zero or negative errno. No backend graph changes or path replay. */ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_path *source, const struct vfs_path *target,struct vfs_mount *mounts, - bool recursive,bool shared,bool receiver,struct vfs_mount **out) + bool recursive,bool shared,enum vfs_mount_copy kind, + bool fresh,struct vfs_mount **out) { struct vfs_path view=*source,point=*target; *out=NULL; for(;;) { if(!batch->next_id)return -EOVERFLOW; - uint64_t group=view.mount->peer_group; + uint64_t group=kind==VFS_COPY_SLAVE ? 0 : view.mount->peer_group; if(shared && !group) { if(!batch->next_peer_id)return -EOVERFLOW; group=batch->next_peer_id++; @@ -481,10 +495,14 @@ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_pa struct vfs_mount *copy; /* All parallel bind views retain the actual source, not another * destination which may be unmounted independently. */ - const struct vfs_path *backing=receiver ? &view.mount->bind_source : &view; - int rc=vfs_bind_clone(&view,backing,false,©); + bool replay=kind!=VFS_COPY_BIND && (fresh ? view.mount->propagation_backing : + view.mount->bind_source.mount!=NULL); + const struct vfs_path *backing=replay ? &view.mount->bind_source : &view; + int rc=vfs_bind_clone(&view,backing,fresh,©); if(rc)return rc; - vfs_stage_mount(batch,copy,&point,batch->next_id++,group); + copy->peer_group=group; + copy->master=kind==VFS_COPY_SLAVE ? view.mount : view.mount->master; + vfs_stage_mount(batch,copy,&point); if(!*out)*out=copy; if(!recursive)return 0; @@ -503,7 +521,79 @@ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_pa } } -/** @brief Publish a directory bind and all shared peer copies atomically. +/** @brief Stage the peers and downstream receivers of one mount tree. + * @param ns Borrowed execution-owned namespace; live inventory stays fixed. + * @param batch Owns the already staged origin and all prepared replicas. + * @param origin Borrowed event root in the batch. + * @param recursive True to copy the prepared bindable descendants. + * @param fresh True for a new filesystem, false for a regular bind. + * @return Zero or negative errno. Parents are visited before their slaves; + * each receiving peer group shares one new group per copied attachment. + * A group with no matching directory view is skipped as a recipient but + * does not block eligible descendants from receiving the event. + */ +static int vfs_stage_propagation(struct vfs_namespace *ns,struct vfs_mount_batch *batch, + struct vfs_mount *origin,bool recursive,bool fresh) +{ + const struct vfs_path *target=&origin->point; + if(!target->mount->peer_group)return 0; + for(uint64_t level=0;;++level) { + bool deeper=false; + for(struct vfs_mount *peer=ns->mounts;peer;peer=peer->next) { + uint64_t depth; + if(peer==target->mount || !vfs_propagation_depth(target->mount,peer,&depth) || + !vfs_dentry_below(target->dentry,peer->root))continue; + if(depth>level){deeper=true;continue;} + if(depth!=level)continue; + struct vfs_path point={peer,target->dentry}; + if(vfs_covering(ns,&point))return -EOPNOTSUPP; + + struct vfs_mount *prior=peer->peer_group ? vfs_staged_peer(batch,peer,point.dentry) : NULL; + enum vfs_mount_copy kind=prior ? VFS_COPY_PEER : VFS_COPY_SLAVE; + for(struct vfs_mount *master=peer->master;!prior && master;master=master->master) + prior=vfs_staged_peer(batch,master,point.dentry); + /* Depth guarantees a staged ancestor; the origin always exists. */ + if(!prior)return -EINVAL; + struct vfs_path view={prior,prior->root}; + struct vfs_mount *copy; + int rc=vfs_stage_bind_tree(batch,&view,&point,batch->pending,recursive,peer->peer_group!=0, + kind,fresh,©); + if(rc)return rc; + } + if(!deeper)return 0; + } +} + +/** @brief Publish a new mount and its downstream copies in one transaction. + * @param ns Borrowed execution-owned namespace. + * @param mount Caller-retained unpublished mount; membership takes its own ref. + * @param target Borrowed retained directory path in ns. + * @return Zero or negative errno, without consuming IDs or modifying the + * mount on failure. Already covered receiver slots are unsupported. + */ +int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const struct vfs_path *target) +{ + if(!ns || !ns->root || !mount || !vfs_path_valid(target))return -EINVAL; + if(target->mount->ns!=ns)return -EXDEV; + if(target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; + if(target->dentry->disconnected)return -ENOENT; + if(mount->ns || mount->point.mount || mount->lazy_detached || vfs_covering(ns,target))return -EBUSY; + if(!ns->next_id)return -EOVERFLOW; + struct vfs_mount_batch batch={.next_id=ns->next_id,.next_peer_id=ns->next_peer_id}; + uint64_t old_id=mount->id,old_group=mount->peer_group; + if(target->mount->peer_group) { + if(!batch.next_peer_id)return -EOVERFLOW; + mount->peer_group=batch.next_peer_id++; + } + ++mount->references; + vfs_stage_mount(&batch,mount,target); + int rc=vfs_stage_propagation(ns,&batch,mount,false,true); + rc=vfs_finish_mount_batch(ns,&batch,rc); + if(rc){mount->id=old_id;mount->peer_group=old_group;} + return rc; +} + +/** @brief Publish a directory bind and all its downstream copies atomically. * @param ns Borrowed execution-owned namespace. * @param source Borrowed retained source directory in ns. * @param target Borrowed retained destination directory in ns. @@ -523,18 +613,8 @@ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, struct vfs_mount_batch batch={.next_id=ns->next_id,.next_peer_id=ns->next_peer_id}; struct vfs_mount *first; bool shared=target->mount->peer_group!=0; - int rc=vfs_stage_bind_tree(&batch,source,target,ns->mounts,recursive,shared,false,&first); - if(!rc && shared) { - struct vfs_mount *inventory=batch.pending; - struct vfs_path view={first,first->root}; - for(struct vfs_mount *peer=ns->mounts;!rc && peer;peer=peer->next) { - if(!vfs_mount_receiver(target,peer))continue; - struct vfs_path point={peer,target->dentry}; - if(vfs_covering(ns,&point)){rc=-EOPNOTSUPP;break;} - struct vfs_mount *copy; - rc=vfs_stage_bind_tree(&batch,&view,&point,inventory,recursive,false,true,©); - } - } + int rc=vfs_stage_bind_tree(&batch,source,target,ns->mounts,recursive,shared,VFS_COPY_BIND,false,&first); + if(!rc)rc=vfs_stage_propagation(ns,&batch,first,recursive,false); return vfs_finish_mount_batch(ns,&batch,rc); } @@ -584,26 +664,27 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path old=mount->point;mount->point=replacement;vfs_path_put(&old);return 0; } -/** @brief Disconnect a single leaf during namespace destruction. +/** @brief Disconnect a single leaf and relink its propagation receivers. * @param ns Borrowed execution-owned namespace. * @param mount Live leaf with no remaining dependents in ns. */ static void vfs_mount_detach(struct vfs_namespace *ns,struct vfs_mount *mount) { + vfs_leave_peer_group(ns,mount); struct vfs_mount **link=&ns->mounts; while(*link && *link!=mount)link=&(*link)->next; if(*link)*link=mount->next; struct vfs_path old=mount->point;mount->point=(struct vfs_path){0}; - mount->ns=NULL;mount->next=NULL;mount->peer_group=0;mount->unbindable=false; + mount->ns=NULL;mount->next=NULL;mount->master=NULL;mount->unbindable=false; vfs_path_put(&old);vfs_mount_put(mount); } -/** @brief Mark origin mounts and the matching slots of their shared parents. +/** @brief Mark origin mounts and the matching slots of propagation receivers. * @param ns Borrowed namespace under execution ownership. * @param root Root of the requested unmount. * @param subtree True to send events for the entire original subtree. - * Only parents' groups determine delivery. A receiver which has any child - * outside the batch is kept, even if other children of that receiver detach. + * The parents' peer groups and downstream edges determine delivery. A receiver + * with a child outside the batch stays, even if other children detach. */ static void vfs_select_unmounts(struct vfs_namespace *ns,struct vfs_mount *root,bool subtree) { @@ -616,8 +697,9 @@ static void vfs_select_unmounts(struct vfs_namespace *ns,struct vfs_mount *root, if(!parent || !parent->peer_group)continue; for(struct vfs_mount *receiver=ns->mounts;receiver;receiver=receiver->next) { const struct vfs_path *point=&receiver->point; - if(point->mount && point->mount!=parent && point->mount->peer_group==parent->peer_group && - point->dentry==event->point.dentry) { + uint64_t depth; + if(point->mount && point->mount!=parent && point->dentry==event->point.dentry && + vfs_propagation_depth(parent,point->mount,&depth)) { receiver->unmount_selected=true;propagated=true; } } @@ -671,7 +753,8 @@ static int vfs_unmount_preflight(const struct vfs_namespace *ns,const struct vfs /** @brief Unlink the entire selected graph before dropping retained edges. * @param ns Borrowed execution-owned namespace with selected mounts marked. * @param lazy True to keep external paths walkable and defer final teardown. - * No allocation, and lazy unmount invokes no synchronous backend finish. + * Repair weak propagation edges before removing each member. No allocation, + * and lazy unmount invokes no synchronous backend finish. */ static void vfs_disconnect_unmounts(struct vfs_namespace *ns,bool lazy) { @@ -679,9 +762,10 @@ static void vfs_disconnect_unmounts(struct vfs_namespace *ns,bool lazy) while(*link) { struct vfs_mount *mount=*link; if(!mount->unmount_selected){link=&mount->next;continue;} + vfs_leave_peer_group(ns,mount); *link=mount->next;mount->next=detached;detached=mount; mount->ns=NULL;mount->lazy_detached=lazy; - mount->peer_group=0;mount->unbindable=false;mount->unmount_selected=false; + mount->master=NULL;mount->unbindable=false;mount->unmount_selected=false; } while(detached) { struct vfs_mount *mount=detached;detached=mount->next;mount->next=NULL; @@ -711,7 +795,7 @@ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path) return rc; } -/** @brief Disconnect a visible subtree and its removable shared counterparts. +/** @brief Disconnect a visible subtree and its removable propagated counterparts. * @param ns Borrowed namespace under execution ownership. * @param path Held selected mount root, excluding the permanent anchor. * @return Zero or negative errno before mutation. Retained paths keep their diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 5f3b75f9..f000109d 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -533,7 +533,7 @@ int vfs_namespace_destroy(struct vfs_namespace *ns); * @return Zero or negative errno. Serialized task context. */ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out); -/** @brief Attach an unpublished mount and propagate to eligible shared peers. +/** @brief Attach an unpublished mount and propagate to eligible peers and slaves. * @param ns Shared namespace under execution ownership. * @param mount Unpublished mount; caller retains its own handle. * @param target Held directory path in ns; an already covered slot is busy. @@ -547,8 +547,9 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount, * @param path Held root of an attached mount in ns, not an interior dentry. * @param flags Exactly one propagation type, optionally with MS_REC. * @return Zero or negative errno without partial changes. MS_SHARED assigns - * peer groups to nonshared mounts; MS_PRIVATE and MS_UNBINDABLE leave a group. - * No backend or access policy changes. MS_SLAVE is not yet supported. + * peer groups to nonshared mounts. MS_SLAVE leaves a peer group while retaining + * an upstream group if available. MS_PRIVATE and MS_UNBINDABLE clear both. + * No backend or access policy changes. */ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *path,uint64_t flags); /** @brief Bind one directory inode into a separate nonrecursive attachment. @@ -557,9 +558,9 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa * @param target Destination directory, required in the same namespace. * @return Zero or negative errno without a partial attachment. Inherits * source mount policy; shares inode identities and backend lifetime without - * duplicating provider destruction. Joins the source's shared group and - * propagates under a shared destination. Child mounts are not copied and an - * unbindable source returns EINVAL. + * duplicating provider destruction. Inherits the source's peer and master + * groups, and propagates under a shared destination. Child mounts are not + * copied and an unbindable source returns EINVAL. */ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); @@ -569,7 +570,7 @@ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, * @param target Uncovered destination directory in the same namespace. * @return Zero or negative errno without publishing a partial tree. Each clone * has an independent ID and mount policy but pins the original backing objects. - * Each eligible shared destination peer receives the same bindable tree. + * Eligible destination peers and slaves each receive a bindable tree. * Unbindable descendant branches are skipped; an unbindable source is rejected. */ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *source, @@ -584,7 +585,7 @@ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *sou */ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); -/** @brief Unmount one root and its removable shared propagation counterparts. +/** @brief Unmount one root and its removable peer and slave counterparts. * @param ns Namespace under execution ownership. * @param path The caller's sole external path to the mounted root. * @return Zero or negative errno. The origin must have no child mounts; a diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 599b4b0f..d6711e01 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -45,7 +45,7 @@ static int mount_bind(struct vfs_namespace *ns,struct task *task,uint64_t source vfs_path_put(&from.path);vfs_path_put(&to.path);return rc; } -/** @brief Detach the selected visible mount and applicable shared counterparts. +/** @brief Detach the selected visible mount and applicable propagation receivers. * @param ns Borrowed execution-owned namespace. * @param task Authorized caller retaining any retry scope. * @param target User target pathname pointer, required. diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 2ba85889..248e149b 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2939,6 +2939,8 @@ static void runtime_unbindable(struct vfs_namespace *ns,const struct vfs_path *r assert(strstr(table," /rbind-source/view/child rw,nosuid - tmpfs ")); assert(strstr(table," /rbind-source/view/child/deep rw,nodev unbindable - tmpfs ")); assert(!scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,ignored,to,ignored,MS_UNBINDABLE,ignored)); + /* Making an already nonshared mount a slave preserves its type. */ + assert(!scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,ignored,to,ignored,MS_SLAVE,ignored)); strcpy(source,"/rbind-source/view/child");strcpy(target,"/rbind-target"); uint64_t before=ns->next_id; @@ -3033,21 +3035,38 @@ static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_pat puts("PASS recursive bind: subdirectory boundary, sibling/nested topology, distinct policies and OOM rollback"); } -/** @brief Read one mountinfo row's shared peer ID, or zero for a private mount. +/** @brief Read one optional numeric mountinfo field from an exact mountpoint. * @param ns Borrowed namespace. @param root Retained mount table viewer root. * @param point Expected absolute mountpoint, with no mountinfo escapes. - * @return The parsed peer group ID; the fixture requires a matching row. + * @param tag Optional field prefix, including a leading space and colon. + * @return The parsed group ID or zero if the field is absent. */ -static unsigned long long fixture_shared_id(struct vfs_namespace *ns,const struct vfs_path *root, - const char *point) +static unsigned long long fixture_mount_tag(struct vfs_namespace *ns,const struct vfs_path *root, + const char *point,const char *tag) { char table[6144],field[128];uint32_t count=0; assert(!vfs_read_mount_table(ns,root,true,0,table,sizeof(table)-1,&count));table[count]=0; - assert(snprintf(field,sizeof(field)," %s ",point)<(int)sizeof(field)); - char *row=strstr(table,field);assert(row); - char *separator=strstr(row," - ");assert(separator); - char *tag=strstr(row," shared:"); - return tag && tagnext_id,group=ns->next_peer_id; + test_fail_heap_after=9; + assert(vfs_mount_bind_recursive(ns,&a,&b)==-ENOMEM); + test_fail_heap_after=-1; + assert(ns->next_id==id && ns->next_peer_id==group); + assert(vfs_path_lookup(ns,root,root,"/slave-d/rec/child",0,&found)==-ENOENT); + vfs_path_put(&a);vfs_path_put(&b); + strcpy(user.source,"/slave-source");strcpy(user.target,"/slave-a/rec"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_BIND|MS_REC,0)); + const unsigned long long src_child=fixture_shared_id(ns,root,"/slave-source/child"); + const unsigned long long slave_child=fixture_shared_id(ns,root,"/slave-b/rec/child"); + assert(src_child && slave_child && src_child!=slave_child); + assert(fixture_shared_id(ns,root,"/slave-a/rec/child")==src_child); + assert(fixture_mount_tag(ns,root,"/slave-b/rec/child"," master:")==src_child); + assert(fixture_mount_tag(ns,root,"/slave-c/rec/child"," master:")==slave_child); + assert(fixture_mount_tag(ns,root,"/slave-d/rec/child"," master:")==slave_child); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,MNT_DETACH,0,0,0)); + assert(vfs_path_lookup(ns,root,root,"/slave-d/rec/child/inside",0,&found)==-ENOENT); + while(vfs_reclaim_mounts(32)){} + + /* If only a narrower peer survives, events outside its view can still + * reach deeper slaves. In-range events use the surviving intermediate group. */ + strcpy(user.source,"/slave-b/narrow");strcpy(user.target,"/slave-peer"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_BIND,0)); + strcpy(user.target,"/slave-b"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_PRIVATE,0)); + assert(!fixture_mount_tag(ns,root,"/slave-b"," master:")); + assert(fixture_mount_tag(ns,root,"/slave-c"," master:")==middle); + strcpy(user.target,"/slave-a/narrow/slot"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,type,0,0)); + const unsigned long long narrowed=fixture_shared_id(ns,root,"/slave-peer/slot"); + assert(narrowed && fixture_mount_tag(ns,root,"/slave-d/narrow/slot"," master:")==narrowed); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + strcpy(user.target,"/slave-a/late"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,type,0,0)); + assert(fixture_mount_tag(ns,root,"/slave-d/late"," master:")==fixture_shared_id(ns,root,"/slave-a/late")); + assert(!vfs_kernel_mkdir(ns,"/slave-c/late/forwarded",0755)); + assert(vfs_path_lookup(ns,root,root,"/slave-b/late/forwarded",0,&found)==-ENOENT); + assert(!vfs_path_lookup(ns,root,root,"/slave-d/late/forwarded",0,&b));vfs_path_put(&b); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + strcpy(user.target,"/slave-peer"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,MNT_DETACH,0,0,0)); + assert(fixture_mount_tag(ns,root,"/slave-c"," master:")==upstream); + strcpy(user.target,"/slave-a"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,MNT_DETACH,0,0,0)); + assert(!fixture_mount_tag(ns,root,"/slave-c"," master:") && !fixture_mount_tag(ns,root,"/slave-d"," master:")); + const char *cleanup[]={"/slave-d","/slave-c","/slave-b","/slave-source"}; + for(unsigned i=0;i Date: Sun, 29 Nov 2026 01:01:24 +0800 Subject: [PATCH 11/97] feat(vfs): preserve mount stacks at propagation receivers --- .../en/LC_MESSAGES/userspace-api/abi.po | 8 +- .../ja/LC_MESSAGES/userspace-api/abi.po | 8 +- Documentation/userspace-api/abi.rst | 12 +-- fs/vfs/mount_internal.h | 3 + fs/vfs/mount_tree.c | 86 +++++++++++++++---- include/reliefnt/mount.h | 13 +-- tools/tests/mount_backend_test.c | 60 +++++++++++-- 7 files changed, 147 insertions(+), 43 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 372578e5..d755f3a6 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -108,11 +108,11 @@ msgstr "``MS_PRIVATE`` removes the target from its peer and master groups. ``MS_ msgid "``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。" msgstr "``MS_REC`` applies the selected type to the mount and its existing descendants without putting distinct submounts into one group or changing existing shared group IDs. A type change requires ``CAP_SYS_ADMIN`` and an exact mount root, and does not change mount access policy or filesystem state. ``/proc/self/mountinfo`` reports the optional tags ``shared:``, ``master:``, or ``unbindable``. It does not yet report ``propagate_from``." -msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出共享父挂载返回 EINVAL。目前仅支持同一挂载命名空间内的传播。" -msgstr "New mounts and binds (including recursive binds) under a shared parent are copied to peers and downstream slaves at the same directory object. Events do not go upstream. A receiver whose bind root excludes the target is skipped, but its downstream mounts with matching directories can still receive a copy. Copies within one receiving peer group share an ID and follow the nearest upstream copy group. New filesystem mounts under nonshared parents are private by default. All copies are published together; allocation failure leaves none attached. A covered receiving slot or a move into a shared parent returns EOPNOTSUPP. Moving out of a shared parent returns EINVAL. Propagation is supported only within a single mount namespace." +msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 保持不变。移入共享父挂载时返回 EOPNOTSUPP,移出共享父挂载返回 EINVAL。 目前仅支持同一挂载命名空间内的传播。" +msgstr "New mounts and binds (including recursive binds) under a shared parent are copied to peers and downstream slaves at the same directory object. Events do not go upstream. A receiver whose bind root excludes the target is skipped, but its downstream mounts with matching directories can still receive a copy. Copies within one receiving peer group share an ID and follow the nearest upstream copy group. New filesystem mounts under nonshared parents are private by default. All copies are published together; allocation failure leaves none attached. At an occupied receiving slot, the copy is inserted beneath the existing mount without changing what is visible. Moving into a shared parent returns EOPNOTSUPP; moving out of one returns EINVAL. Propagation is supported only within a single mount namespace." -msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。存在不随事件卸载的子挂载时保留该接收分支。 延迟卸载为目标子树中的每个挂载传播事件,不因打开路径阻塞,仍保留接收方的无关 子挂载。接收方保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" -msgstr "An unmount propagates from the target’s parent to the matching mountpoints. An ordinary unmount returns EBUSY without removing any mount if a removable receiver still has an open path. A receiver is kept when it has submounts that are not being removed. Lazy unmount propagates each mount in the requested subtree without waiting for open paths and preserves unrelated submounts at receivers. A retained receiver can still use its backing even after the initiating attachment is detached." +msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。与事件无关的子挂载通常使该接收分支保留;但覆盖 副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标子树中的 每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方保留的 挂载可以继续使用其后端,即使发起挂载已被摘除。" +msgstr "An unmount propagates from the target’s parent to the matching mountpoints. An ordinary unmount returns EBUSY without removing any mount if a removable receiver still has an open path. Unrelated submounts normally keep a receiver attached, but an overmount on the copy's root does not prevent removal of the copy and stays visible. Lazy unmount propagates each mount in the requested subtree without waiting for open paths and likewise preserves unrelated receiver mounts. A retained receiver can still use its backing even after the initiating attachment is detached." msgid "延迟卸载" msgstr "Lazy Unmount" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 4f8b77d8..0bb3e7cd 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -101,11 +101,11 @@ msgstr "``MS_PRIVATE`` は対象のピアグループと上流グループとの msgid "``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。" msgstr "``MS_REC`` は選択した種別を対象と既存の子マウントに適用しますが、別々の子マウントを同じグループにまとめたり、既存の共有グループ ID を変更したりしません。種別の変更には ``CAP_SYS_ADMIN`` が必要で、対象はマウントのルートでなければなりません。アクセス方針やファイルシステムの状態は変わりません。``/proc/self/mountinfo`` はオプションフィールド ``shared:``、``master:``、``unbindable`` を表示します。``propagate_from`` はまだ表示しません。" -msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 EOPNOTSUPP;移出共享父挂载返回 EINVAL。目前仅支持同一挂载命名空间内的传播。" -msgstr "共有の親マウントの下でマウントやバインド(再帰バインドを含む)を作成すると、ピアと下流のスレーブは同じディレクトリオブジェクトの位置にコピーを受け取ります。イベントは上流には伝わりません。対象をバインドルートに含まない受信側はスキップされますが、対応するディレクトリを含む下流には伝播します。同じ受信ピアグループ内のコピーは ID を共有し、最も近い上流のコピーグループに従います。非共有の親の下の新規ファイルシステムマウントは既定でプライベートです。コピーはすべて一括して公開され、割り当てに失敗しても一部だけが残ることはありません。すでに別のマウントがある受信位置や共有の親への移動は EOPNOTSUPP、共有の親からの移動は EINVAL になります。伝播は単一のマウント名前空間内に限られます。" +msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 保持不变。移入共享父挂载时返回 EOPNOTSUPP,移出共享父挂载返回 EINVAL。 目前仅支持同一挂载命名空间内的传播。" +msgstr "共有の親マウントの下でマウントやバインド(再帰バインドを含む)を作成すると、ピアと下流のスレーブは同じディレクトリオブジェクトの位置にコピーを受け取ります。イベントは上流には伝わりません。対象をバインドルートに含まない受信側はスキップされますが、対応するディレクトリを含む下流には伝播します。同じ受信ピアグループ内のコピーは ID を共有し、最も近い上流のコピーグループに従います。非共有の親の下の新規ファイルシステムマウントは既定でプライベートです。コピーはすべて一括して公開され、割り当てに失敗しても一部だけが残ることはありません。受信位置に既存のマウントがある場合、コピーはその下に挿入され、見える内容は変わりません。共有の親への移動は EOPNOTSUPP、共有の親からの移動は EINVAL になります。伝播は単一のマウント名前空間内に限られます。" -msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。存在不随事件卸载的子挂载时保留该接收分支。 延迟卸载为目标子树中的每个挂载传播事件,不因打开路径阻塞,仍保留接收方的无关 子挂载。接收方保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" -msgstr "アンマウントは対象の親から対応するマウントポイントへ伝播します。通常のアンマウントでは、取り外し対象となる受信側に開いたパスがあれば、どのマウントも取り外さず EBUSY を返します。イベントで取り外されない子マウントがあれば、その受信側は残ります。遅延アンマウントは開いたパスを待たずに対象サブツリー内の各マウントのイベントを伝播し、受信側の無関係な子マウントを残します。受信側に残ったマウントは、操作元が切り離された後もバックエンドを使えます。" +msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。与事件无关的子挂载通常使该接收分支保留;但覆盖 副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标子树中的 每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方保留的 挂载可以继续使用其后端,即使发起挂载已被摘除。" +msgstr "アンマウントは対象の親から対応するマウントポイントへ伝播します。通常のアンマウントでは、取り外し対象となる受信側に開いたパスがあれば、どのマウントも取り外さず EBUSY を返します。通常は無関係な子マウントがある受信側を残しますが、コピーのルートを覆うマウントはコピーの取り外しを妨げず、引き続き見えます。遅延アンマウントは開いたパスを待たずに対象サブツリー内の各マウントのイベントを伝播し、同様に受信側の無関係なマウントを残します。受信側に残ったマウントは、操作元が切り離された後もバックエンドを使えます。" msgid "延迟卸载" msgstr "遅延アンマウント" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index d3b778e0..263c6035 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -82,13 +82,15 @@ bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; -分配失败不留下部分挂载。接收位置已有覆盖挂载时以及移入共享父挂载时返回 -EOPNOTSUPP;移出共享父挂载返回 EINVAL。目前仅支持同一挂载命名空间内的传播。 +分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 +保持不变。移入共享父挂载时返回 EOPNOTSUPP,移出共享父挂载返回 EINVAL。 +目前仅支持同一挂载命名空间内的传播。 卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 -时返回 EBUSY,不移除任何挂载。存在不随事件卸载的子挂载时保留该接收分支。 -延迟卸载为目标子树中的每个挂载传播事件,不因打开路径阻塞,仍保留接收方的无关 -子挂载。接收方保留的挂载可以继续使用其后端,即使发起挂载已被摘除。 +时返回 EBUSY,不移除任何挂载。与事件无关的子挂载通常使该接收分支保留;但覆盖 +副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标子树中的 +每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方保留的 +挂载可以继续使用其后端,即使发起挂载已被摘除。 延迟卸载 ======== diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 276c2c69..893f2c39 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -26,6 +26,7 @@ struct vfs_mount { struct vfs_mount *next,*notify_next; struct vfs_mount **notify_link; struct vfs_mount *master; /* Weak edge to a live member of the upstream peer group. */ + struct vfs_mount *staged_cover; /* Existing receiver cover; only set before batch commit. */ struct vfs_path point,bind_source; struct vfs_dentry *root; const struct vfs_backend_ops *ops; @@ -36,6 +37,8 @@ struct vfs_mount { uint64_t writers; /* Open writable file descriptions on this attachment. */ bool propagation_backing; /* This bind_source is a replica lifetime pin. */ bool unmount_selected; /* Scratch under the namespace execution writer. */ + bool lift_cover; /* Scratch: retain this overmount above a removed receiver. */ + bool propagation_copy; /* Receiver can detach beneath an unrelated root cover. */ bool unbindable; /* Pruned by recursive bind; never a valid bind source. */ bool lazy_detached; /* No namespace edges; retained paths still work. */ char *source,*filesystem; diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index 76d254f5..d7d18294 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -232,7 +232,11 @@ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root) ns->root=root;ns->mounts=root;ns->next_id=2;ns->next_peer_id=1;return 0; } -/* Mountpoint identity is a retained parent mount + dentry, never text. */ +/** @brief Find the attachment immediately covering an exact retained slot. + * @param ns Borrowed execution-owned namespace. + * @param path Borrowed parent mount/dentry pair, never a textual pathname. + * @return Borrowed immediate cover or NULL; does not follow the mount stack. + */ static struct vfs_mount *vfs_covering(const struct vfs_namespace *ns,const struct vfs_path *path) { for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) @@ -377,12 +381,24 @@ static void vfs_stage_mount(struct vfs_mount_batch *batch,struct vfs_mount *moun mount->next=batch->pending;batch->pending=mount; } +/** @brief Transfer an attachment to another exact parent slot. + * @param mount Live or staged mount whose old mountpoint is retained. + * @param point Borrowed new slot, retained before releasing the old one. + * Caller excludes topology cycles and holds both graphs through the update. + */ +static void vfs_replace_mountpoint(struct vfs_mount *mount,const struct vfs_path *point) +{ + struct vfs_path replacement={0},old=mount->point; + vfs_path_get(point,&replacement);mount->point=replacement;vfs_path_put(&old); +} + /** @brief Roll back all staged mounts or publish them together without allocation. * @param ns Borrowed execution-owned namespace. * @param batch Owned unpublished mounts and tentative ID counters. * @param status Nonzero to discard, zero to commit all changes. * @return The supplied status. Rollback releases descendants before parents; - * neither graph nor namespace counters change on error. + * neither graph nor namespace counters change on error. At commit, rehang + * any existing receiver stack on its newly inserted mount's root. */ static int vfs_finish_mount_batch(struct vfs_namespace *ns,struct vfs_mount_batch *batch,int status) { @@ -396,6 +412,11 @@ static int vfs_finish_mount_batch(struct vfs_namespace *ns,struct vfs_mount_batc struct vfs_mount **tail=&batch->pending; for(;*tail;tail=&(*tail)->next) { struct vfs_mount *mount=*tail;mount->ns=ns; + if(mount->staged_cover) { + struct vfs_path root={mount,mount->root}; + vfs_replace_mountpoint(mount->staged_cover,&root); + mount->staged_cover=NULL; + } if(!mount->notify_link && vfs_notify_mount_created)vfs_notify_mount_created(mount); } *tail=ns->mounts;ns->mounts=batch->pending; @@ -502,6 +523,7 @@ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_pa if(rc)return rc; copy->peer_group=group; copy->master=kind==VFS_COPY_SLAVE ? view.mount : view.mount->master; + copy->propagation_copy=kind!=VFS_COPY_BIND; vfs_stage_mount(batch,copy,&point); if(!*out)*out=copy; if(!recursive)return 0; @@ -530,7 +552,8 @@ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_pa * @return Zero or negative errno. Parents are visited before their slaves; * each receiving peer group shares one new group per copied attachment. * A group with no matching directory view is skipped as a recipient but - * does not block eligible descendants from receiving the event. + * does not block eligible descendants from receiving the event. An existing + * cover is reparented only at commit so it remains visible above the copy. */ static int vfs_stage_propagation(struct vfs_namespace *ns,struct vfs_mount_batch *batch, struct vfs_mount *origin,bool recursive,bool fresh) @@ -546,7 +569,6 @@ static int vfs_stage_propagation(struct vfs_namespace *ns,struct vfs_mount_batch if(depth>level){deeper=true;continue;} if(depth!=level)continue; struct vfs_path point={peer,target->dentry}; - if(vfs_covering(ns,&point))return -EOPNOTSUPP; struct vfs_mount *prior=peer->peer_group ? vfs_staged_peer(batch,peer,point.dentry) : NULL; enum vfs_mount_copy kind=prior ? VFS_COPY_PEER : VFS_COPY_SLAVE; @@ -559,6 +581,7 @@ static int vfs_stage_propagation(struct vfs_namespace *ns,struct vfs_mount_batch int rc=vfs_stage_bind_tree(batch,&view,&point,batch->pending,recursive,peer->peer_group!=0, kind,fresh,©); if(rc)return rc; + copy->staged_cover=vfs_covering(ns,&point); } if(!deeper)return 0; } @@ -569,7 +592,7 @@ static int vfs_stage_propagation(struct vfs_namespace *ns,struct vfs_mount_batch * @param mount Caller-retained unpublished mount; membership takes its own ref. * @param target Borrowed retained directory path in ns. * @return Zero or negative errno, without consuming IDs or modifying the - * mount on failure. Already covered receiver slots are unsupported. + * mount on failure. An existing receiving stack stays above the new copy. */ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const struct vfs_path *target) { @@ -660,8 +683,7 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const for(struct vfs_mount *backing=ancestor;backing;backing=backing->bind_source.mount) if(backing==mount)return -ELOOP; if(vfs_covering(ns,target))return -EBUSY; - struct vfs_path replacement={0};vfs_path_get(target,&replacement); - struct vfs_path old=mount->point;mount->point=replacement;vfs_path_put(&old);return 0; + vfs_replace_mountpoint(mount,target);return 0; } /** @brief Disconnect a single leaf and relink its propagation receivers. @@ -676,15 +698,27 @@ static void vfs_mount_detach(struct vfs_namespace *ns,struct vfs_mount *mount) if(*link)*link=mount->next; struct vfs_path old=mount->point;mount->point=(struct vfs_path){0}; mount->ns=NULL;mount->next=NULL;mount->master=NULL;mount->unbindable=false; + mount->propagation_copy=false; vfs_path_put(&old);vfs_mount_put(mount); } +/** @brief Identify a surviving cover that can be lifted out of an unmount batch. + * @param mount Borrowed candidate mount, whose visible parent might detach. + * @return True if the candidate covers the root of a propagation receiver and + * its retained parent edge can be transferred to the receiver's old slot. + */ +static bool vfs_removable_cover_edge(const struct vfs_mount *mount) +{ + const struct vfs_mount *parent=mount->point.mount; + return parent && parent->propagation_copy && mount->point.dentry==parent->root; +} + /** @brief Mark origin mounts and the matching slots of propagation receivers. * @param ns Borrowed namespace under execution ownership. * @param root Root of the requested unmount. * @param subtree True to send events for the entire original subtree. * The parents' peer groups and downstream edges determine delivery. A receiver - * with a child outside the batch stays, even if other children detach. + * with an unrelated child stays, except a root cover that can be lifted. */ static void vfs_select_unmounts(struct vfs_namespace *ns,struct vfs_mount *root,bool subtree) { @@ -707,8 +741,17 @@ static void vfs_select_unmounts(struct vfs_namespace *ns,struct vfs_mount *root, if(propagated) { for(struct vfs_mount *child=ns->mounts;child;child=child->next) { if(child->unmount_selected)continue; - for(struct vfs_mount *parent=child->point.mount;parent && parent->unmount_selected; - parent=parent->point.mount)parent->unmount_selected=false; + struct vfs_mount *parent=child->point.mount; + if(!vfs_removable_cover_edge(child)) + while(parent && parent->unmount_selected) { + parent->unmount_selected=false; + if(vfs_removable_cover_edge(parent))break; + parent=parent->point.mount; + } + } + for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { + mount->lift_cover=!mount->unmount_selected && vfs_removable_cover_edge(mount) && + mount->point.mount->unmount_selected; } } } @@ -717,8 +760,8 @@ static void vfs_select_unmounts(struct vfs_namespace *ns,struct vfs_mount *root, * @param ns Borrowed execution-owned namespace with selected mounts marked. * @param root Origin mount with the caller's lookup reference. * @return Zero or negative busy/provider errno. Replica lifetime pins and - * edges disappearing in this batch are not external path references. A - * regular bind outside the batch still pins its source as before. + * edges disappearing or being reparented in this batch are not external path + * references. A regular bind outside the batch still pins its source as before. */ static int vfs_unmount_preflight(const struct vfs_namespace *ns,const struct vfs_mount *root) { @@ -729,8 +772,8 @@ static int vfs_unmount_preflight(const struct vfs_namespace *ns,const struct vfs uint64_t replicas=0; bool first_replica=true; for(struct vfs_mount *other=ns->mounts;other;other=other->next) { + if((other->unmount_selected || other->lift_cover) && other->point.mount==mount)++expected; if(!other->unmount_selected)continue; - if(other->point.mount==mount)++expected; if(other->bind_source.mount==mount && !other->propagation_backing)++expected; if(other->bind_source.mount==backing && other->propagation_backing) { ++replicas; @@ -753,11 +796,18 @@ static int vfs_unmount_preflight(const struct vfs_namespace *ns,const struct vfs /** @brief Unlink the entire selected graph before dropping retained edges. * @param ns Borrowed execution-owned namespace with selected mounts marked. * @param lazy True to keep external paths walkable and defer final teardown. - * Repair weak propagation edges before removing each member. No allocation, - * and lazy unmount invokes no synchronous backend finish. + * Reparent preserved covers and repair weak propagation edges before removing + * each member. No allocation, and lazy unmount invokes no backend finish. */ static void vfs_disconnect_unmounts(struct vfs_namespace *ns,bool lazy) { + for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { + if(!mount->lift_cover)continue; + const struct vfs_path *point=&mount->point.mount->point; + while(point->mount->unmount_selected)point=&point->mount->point; + vfs_replace_mountpoint(mount,point); + mount->lift_cover=false; + } struct vfs_mount *detached=NULL,**link=&ns->mounts; while(*link) { struct vfs_mount *mount=*link; @@ -765,7 +815,8 @@ static void vfs_disconnect_unmounts(struct vfs_namespace *ns,bool lazy) vfs_leave_peer_group(ns,mount); *link=mount->next;mount->next=detached;detached=mount; mount->ns=NULL;mount->lazy_detached=lazy; - mount->master=NULL;mount->unbindable=false;mount->unmount_selected=false; + mount->master=NULL;mount->unbindable=false; + mount->unmount_selected=false;mount->propagation_copy=false; } while(detached) { struct vfs_mount *mount=detached;detached=mount->next;mount->next=NULL; @@ -791,7 +842,8 @@ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path) vfs_select_unmounts(ns,root,false); int rc=vfs_unmount_preflight(ns,root); if(!rc)vfs_disconnect_unmounts(ns,false); - else for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next)mount->unmount_selected=false; + else for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) + mount->unmount_selected=mount->lift_cover=false; return rc; } diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index f000109d..0cc5355b 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -538,7 +538,7 @@ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out); * @param mount Unpublished mount; caller retains its own handle. * @param target Held directory path in ns; an already covered slot is busy. * @return Zero or negative errno without partial publication or ID use on - * failure. Covered receiver insertion is not supported. Task context. + * failure. Existing receiver covers remain visible above the copy. Task context. */ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount, const struct vfs_path *target); @@ -589,16 +589,17 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source, * @param ns Namespace under execution ownership. * @param path The caller's sole external path to the mounted root. * @return Zero or negative errno. The origin must have no child mounts; a - * receiver with children is skipped. Other held paths on selected mounts - * keep the entire operation busy. Success does not consume the caller's path. + * receiver with unrelated children is skipped, except root covers that can be + * reparented. Other held paths on selected mounts keep the entire operation + * busy. Success does not consume the caller's path. */ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path); /** @brief Lazily disconnect a subtree and eligible propagated attachments. * @param ns Borrowed namespace under execution ownership. * @param path Retained visible root of a mount, not the namespace anchor. - * @return Zero or negative errno. Receivers with unrelated children remain - * attached. Held paths remain usable and final cleanup is deferred. No new - * allocations or synchronous backend flush on detach. + * @return Zero or negative errno. Receivers with unrelated children stay, + * except root covers that can be reparented. Held paths remain usable and + * final cleanup is deferred. No allocations or synchronous backend flush. */ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path); /** @brief Prepare retained directory-name changes before a backend rename. diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 248e149b..bfdc5e19 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -3091,6 +3091,7 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_kernel_mkdir(ns,"/shared-a/covered",0755)); strcpy(user.target,"/shared-a/covered"); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,0,0)); + assert(!vfs_kernel_mkdir(ns,"/shared-a/covered/local",0755)); strcpy(user.target,"/shared-a"); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,UINT64_MAX,to,UINT64_MAX,MS_SHARED,UINT64_MAX)); unsigned long long group=fixture_shared_id(ns,root,"/shared-a");assert(group); @@ -3102,12 +3103,34 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path struct vfs_path a={0},b={0},point={0},found={0};struct vfs_mount *mount=NULL; strcpy(user.target,"/shared-b/covered"); + assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&a)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&point)); + assert(!storage_new_tmpfs_mount("stacked event",0,NULL,1000,1000,&mount)); const uint64_t covered_id=ns->next_id,covered_peer_id=ns->next_peer_id; - assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,type,0,0)==-EOPNOTSUPP); + test_fail_heap_after=1; + assert(vfs_mount_attach(ns,mount,&point)==-ENOMEM); + test_fail_heap_after=-1; assert(ns->next_id==covered_id && ns->next_peer_id==covered_peer_id); - assert(!vfs_path_lookup(ns,root,root,"/shared-b/covered",0,&point)); - assert(!vfs_path_lookup(ns,root,root,"/shared-b",0,&b)); - assert(vfs_path_mount_id(&point)==vfs_path_mount_id(&b));vfs_path_put(&point);vfs_path_put(&b); + assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&found)); + assert(vfs_path_equal(&a,&found));vfs_path_put(&found); + assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); + assert(ns->next_id==covered_id+2 && ns->next_peer_id==covered_peer_id+1); + assert(!vfs_kernel_mkdir(ns,"/shared-b/covered/incoming",0755)); + assert(vfs_path_lookup(ns,root,root,"/shared-a/covered/incoming",0,&found)==-ENOENT); + assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&found)); + assert(vfs_path_equal(&a,&found));vfs_path_put(&found); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&b)); + struct vfs_path interior={0}; + vfs_path_get(&a.mount->point,&interior); + assert(vfs_path_same_inode(&interior,&b));vfs_path_put(&b); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)==-EBUSY); + vfs_path_put(&interior); + /* A held path to the unrelated top mount is not a busy reference on + * the inserted event. Unmount removes only the event, not the cover. */ + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered/local",0,&found));vfs_path_put(&found); + assert(vfs_path_lookup(ns,root,root,"/shared-a/covered/incoming",0,&found)==-ENOENT); + vfs_path_put(&a); strcpy(user.target,"/shared-a/covered"); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); @@ -3234,7 +3257,7 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path } vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); lookup_user_base=lookup_user_bytes=0; - puts("PASS shared propagation: group IDs, bounded peer roots, rollback, busy peers, retained local branches and recursive detach"); + puts("PASS shared propagation: bounded peers, covered receiver insertion, rollback, busy peers and recursive detach"); } /** @brief Verify one-way and transitive mount propagation through slave groups. @@ -3255,7 +3278,7 @@ static void runtime_slave_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!fixture_shared_id(ns,root,"/slave-a") && !fixture_mount_tag(ns,root,"/slave-a"," master:")); const char *child[]={"/slave-a/old","/slave-a/event","/slave-a/rec","/slave-a/local","/slave-a/late", - "/slave-a/narrow","/slave-a/narrow/slot"}; + "/slave-a/narrow","/slave-a/narrow/slot","/slave-a/post-cover"}; for(unsigned i=0;inext_id,group=ns->next_peer_id; @@ -3341,7 +3382,12 @@ static void runtime_slave_mounts(struct vfs_namespace *ns,const struct vfs_path assert(fixture_mount_tag(ns,root,"/slave-b/rec/child"," master:")==src_child); assert(fixture_mount_tag(ns,root,"/slave-c/rec/child"," master:")==slave_child); assert(fixture_mount_tag(ns,root,"/slave-d/rec/child"," master:")==slave_child); + assert(!vfs_path_lookup(ns,root,root,"/slave-d/rec/local",0,&b));vfs_path_put(&b); + assert(vfs_path_lookup(ns,root,root,"/slave-d/rec/child/inside",0,&found)==-ENOENT); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,MNT_DETACH,0,0,0)); + assert(!vfs_path_lookup(ns,root,root,"/slave-d/rec/local",0,&b));vfs_path_put(&b); + strcpy(user.target,"/slave-d/rec"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); assert(vfs_path_lookup(ns,root,root,"/slave-d/rec/child/inside",0,&found)==-ENOENT); while(vfs_reclaim_mounts(32)){} @@ -3379,7 +3425,7 @@ static void runtime_slave_mounts(struct vfs_namespace *ns,const struct vfs_path while(vfs_reclaim_mounts(32)){} vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); lookup_user_base=lookup_user_bytes=0; - puts("PASS slave propagation: recursive demotion, directional propagation, reparenting, unmount and bind rollback"); + puts("PASS slave propagation: recursive demotion, directional propagation, covered and lazy detach, bind rollback"); } /** @brief Verify lazy detach hides a mount tree without revoking retained paths. From 15fd1dd9b849371de8390e0d983858f26fb331ca Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 01:16:40 +0800 Subject: [PATCH 12/97] feat(vfs): propagate moves into shared mounts --- .../en/LC_MESSAGES/userspace-api/abi.po | 7 +- .../ja/LC_MESSAGES/userspace-api/abi.po | 7 +- Documentation/userspace-api/abi.rst | 8 +- fs/vfs/mount_internal.h | 1 + fs/vfs/mount_tree.c | 98 +++++++++----- include/reliefnt/mount.h | 7 +- kernel/syscall/fs/mount.c | 4 +- tools/tests/mount_backend_test.c | 121 +++++++++++++++++- 8 files changed, 209 insertions(+), 44 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index d755f3a6..934f55f9 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -108,8 +108,11 @@ msgstr "``MS_PRIVATE`` removes the target from its peer and master groups. ``MS_ msgid "``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。" msgstr "``MS_REC`` applies the selected type to the mount and its existing descendants without putting distinct submounts into one group or changing existing shared group IDs. A type change requires ``CAP_SYS_ADMIN`` and an exact mount root, and does not change mount access policy or filesystem state. ``/proc/self/mountinfo`` reports the optional tags ``shared:``, ``master:``, or ``unbindable``. It does not yet report ``propagate_from``." -msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 保持不变。移入共享父挂载时返回 EOPNOTSUPP,移出共享父挂载返回 EINVAL。 目前仅支持同一挂载命名空间内的传播。" -msgstr "New mounts and binds (including recursive binds) under a shared parent are copied to peers and downstream slaves at the same directory object. Events do not go upstream. A receiver whose bind root excludes the target is skipped, but its downstream mounts with matching directories can still receive a copy. Copies within one receiving peer group share an ID and follow the nearest upstream copy group. New filesystem mounts under nonshared parents are private by default. All copies are published together; allocation failure leaves none attached. At an occupied receiving slot, the copy is inserted beneath the existing mount without changing what is visible. Moving into a shared parent returns EOPNOTSUPP; moving out of one returns EINVAL. Propagation is supported only within a single mount namespace." +msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 保持不变。目前仅支持同一挂载命名空间内的传播。" +msgstr "New mounts and binds (including recursive binds) under a shared parent are copied to peers and downstream slaves at the same directory object. Events do not go upstream. A receiver whose bind root excludes the target is skipped, but its downstream mounts with matching directories can still receive a copy. Copies within one receiving peer group share an ID and follow the nearest upstream copy group. New filesystem mounts under nonshared parents are private by default. All copies are published together; allocation failure leaves none attached. At an occupied receiving slot, the copy is inserted beneath the existing mount without changing what is visible. Propagation is supported only within a single mount namespace." + +msgid "``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, 为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable 挂载的子树移入共享父挂载, 返回 EINVAL。" +msgstr "``MS_MOVE`` into a shared parent preserves the original tree’s mount IDs, existing peer groups, upstream relationships, and held paths. It assigns a separate peer group to each original that is not already shared and copies the entire tree to receivers. Allocation failure leaves locations, groups, and receiver covers unchanged. Moving out of a shared parent, or moving a subtree containing an unbindable mount into one, returns EINVAL." msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。与事件无关的子挂载通常使该接收分支保留;但覆盖 副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标子树中的 每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方保留的 挂载可以继续使用其后端,即使发起挂载已被摘除。" msgstr "An unmount propagates from the target’s parent to the matching mountpoints. An ordinary unmount returns EBUSY without removing any mount if a removable receiver still has an open path. Unrelated submounts normally keep a receiver attached, but an overmount on the copy's root does not prevent removal of the copy and stays visible. Lazy unmount propagates each mount in the requested subtree without waiting for open paths and likewise preserves unrelated receiver mounts. A retained receiver can still use its backing even after the initiating attachment is detached." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 0bb3e7cd..60ed3f14 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -101,8 +101,11 @@ msgstr "``MS_PRIVATE`` は対象のピアグループと上流グループとの msgid "``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。" msgstr "``MS_REC`` は選択した種別を対象と既存の子マウントに適用しますが、別々の子マウントを同じグループにまとめたり、既存の共有グループ ID を変更したりしません。種別の変更には ``CAP_SYS_ADMIN`` が必要で、対象はマウントのルートでなければなりません。アクセス方針やファイルシステムの状態は変わりません。``/proc/self/mountinfo`` はオプションフィールド ``shared:``、``master:``、``unbindable`` を表示します。``propagate_from`` はまだ表示しません。" -msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 保持不变。移入共享父挂载时返回 EOPNOTSUPP,移出共享父挂载返回 EINVAL。 目前仅支持同一挂载命名空间内的传播。" -msgstr "共有の親マウントの下でマウントやバインド(再帰バインドを含む)を作成すると、ピアと下流のスレーブは同じディレクトリオブジェクトの位置にコピーを受け取ります。イベントは上流には伝わりません。対象をバインドルートに含まない受信側はスキップされますが、対応するディレクトリを含む下流には伝播します。同じ受信ピアグループ内のコピーは ID を共有し、最も近い上流のコピーグループに従います。非共有の親の下の新規ファイルシステムマウントは既定でプライベートです。コピーはすべて一括して公開され、割り当てに失敗しても一部だけが残ることはありません。受信位置に既存のマウントがある場合、コピーはその下に挿入され、見える内容は変わりません。共有の親への移動は EOPNOTSUPP、共有の親からの移動は EINVAL になります。伝播は単一のマウント名前空間内に限られます。" +msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 保持不变。目前仅支持同一挂载命名空间内的传播。" +msgstr "共有の親マウントの下でマウントやバインド(再帰バインドを含む)を作成すると、ピアと下流のスレーブは同じディレクトリオブジェクトの位置にコピーを受け取ります。イベントは上流には伝わりません。対象をバインドルートに含まない受信側はスキップされますが、対応するディレクトリを含む下流には伝播します。同じ受信ピアグループ内のコピーは ID を共有し、最も近い上流のコピーグループに従います。非共有の親の下の新規ファイルシステムマウントは既定でプライベートです。コピーはすべて一括して公開され、割り当てに失敗しても一部だけが残ることはありません。受信位置に既存のマウントがある場合、コピーはその下に挿入され、見える内容は変わりません。伝播は単一のマウント名前空間内に限られます。" + +msgid "``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, 为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable 挂载的子树移入共享父挂载, 返回 EINVAL。" +msgstr "``MS_MOVE`` で共有の親の下へ移動しても、元のサブツリーのマウント ID、既存のピアグループ、上流関係、保持中のパスは変わりません。まだ共有されていない元のマウントごとに別々のピアグループを割り当て、受信側にはサブツリー全体をコピーします。割り当てに失敗しても、位置、グループ、受信側の既存のオーバーマウントは変わりません。共有の親から移動する場合や、バインド不可のマウントを含むサブツリーを共有の親の下へ移動する場合は、EINVAL を返します。" msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。与事件无关的子挂载通常使该接收分支保留;但覆盖 副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标子树中的 每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方保留的 挂载可以继续使用其后端,即使发起挂载已被摘除。" msgstr "アンマウントは対象の親から対応するマウントポイントへ伝播します。通常のアンマウントでは、取り外し対象となる受信側に開いたパスがあれば、どのマウントも取り外さず EBUSY を返します。通常は無関係な子マウントがある受信側を残しますが、コピーのルートを覆うマウントはコピーの取り外しを妨げず、引き続き見えます。遅延アンマウントは開いたパスを待たずに対象サブツリー内の各マウントのイベントを伝播し、同様に受信側の無関係なマウントを残します。受信側に残ったマウントは、操作元が切り離された後もバックエンドを使えます。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 263c6035..af0beaa3 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -83,8 +83,12 @@ bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 -保持不变。移入共享父挂载时返回 EOPNOTSUPP,移出共享父挂载返回 EINVAL。 -目前仅支持同一挂载命名空间内的传播。 +保持不变。目前仅支持同一挂载命名空间内的传播。 + +``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, +为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 +接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable 挂载的子树移入共享父挂载, +返回 EINVAL。 卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。与事件无关的子挂载通常使该接收分支保留;但覆盖 diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 893f2c39..e764f277 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -33,6 +33,7 @@ struct vfs_mount { void *context; struct module *owner; uint64_t references,id,policy,peer_group; /* Zero group is not shared. */ + uint64_t staged_peer_group; /* Tentative group of an original mount during MS_MOVE. */ uint64_t propagation_pins; /* Replica lifetime references, not open paths. */ uint64_t writers; /* Open writable file descriptions on this attachment. */ bool propagation_backing; /* This bind_source is a replica lifetime pin. */ diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index d7d18294..07ea61c1 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -338,7 +338,7 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa /** @brief Prepare an unattached directory view of an existing filesystem. * @param view Valid source directory; supplies the root and attachment policy. * @param backing Retained path to the same dentry, pinned for this view's lifetime. - * @param propagation True for a fresh mount's replica-only backing reference. + * @param propagation True for a replica-only backing reference. * @param out Receives the privately owned clone on success, NULL on failure. * @return Zero or negative provider/admission/allocation errno. No new backend * is created, and the clone has no namespace membership or inotify registration. @@ -419,7 +419,7 @@ static int vfs_finish_mount_batch(struct vfs_namespace *ns,struct vfs_mount_batc } if(!mount->notify_link && vfs_notify_mount_created)vfs_notify_mount_created(mount); } - *tail=ns->mounts;ns->mounts=batch->pending; + if(batch->pending){*tail=ns->mounts;ns->mounts=batch->pending;} ns->next_id=batch->next_id;ns->next_peer_id=batch->next_peer_id; return 0; } @@ -455,16 +455,19 @@ static bool vfs_propagation_depth(const struct vfs_mount *origin,const struct vf /** @brief Find a staged view from a particular receiver's peer group. * @param batch Borrowed batch for this single propagation event. * @param receiver Borrowed live shared destination parent. - * @param dentry Exact event mountpoint, identical in all receiving parents. - * @return A staged event root, or NULL if this group has no prepared view. + * @param origin Event root; a move leaves it live at its old mountpoint until commit. + * @param target Exact future mountpoint of the event root. + * @return The event root for the origin group, a prepared receiver, or NULL. * Submounts of staged trees cannot match a live destination parent. */ static struct vfs_mount *vfs_staged_peer(const struct vfs_mount_batch *batch, - const struct vfs_mount *receiver,const struct vfs_dentry *dentry) + const struct vfs_mount *receiver,struct vfs_mount *origin, + const struct vfs_path *target) { + if(receiver->peer_group==target->mount->peer_group)return origin; for(struct vfs_mount *mount=batch->pending;mount;mount=mount->next) { const struct vfs_mount *parent=mount->point.mount; - if(mount->point.dentry==dentry && parent->ns==receiver->ns && + if(mount->point.dentry==target->dentry && parent->ns==receiver->ns && parent->peer_group==receiver->peer_group)return mount; } return NULL; @@ -495,31 +498,32 @@ enum vfs_mount_copy { VFS_COPY_BIND,VFS_COPY_PEER,VFS_COPY_SLAVE }; * @param recursive True to copy bindable child mounts. * @param shared True if the destination parent is shared. * @param kind A direct bind, or a replay sharing or following the source group. - * @param fresh True for replicas of a new mount; their backing pins are internal. * @param out Receives the staged tree root, possibly NULL on failure. * @return Zero or negative errno. No backend graph changes or path replay. */ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_path *source, const struct vfs_path *target,struct vfs_mount *mounts, bool recursive,bool shared,enum vfs_mount_copy kind, - bool fresh,struct vfs_mount **out) + struct vfs_mount **out) { struct vfs_path view=*source,point=*target; *out=NULL; for(;;) { if(!batch->next_id)return -EOVERFLOW; - uint64_t group=kind==VFS_COPY_SLAVE ? 0 : view.mount->peer_group; + uint64_t group=kind==VFS_COPY_SLAVE ? 0 : + (view.mount->peer_group ? view.mount->peer_group : view.mount->staged_peer_group); if(shared && !group) { if(!batch->next_peer_id)return -EOVERFLOW; group=batch->next_peer_id++; } struct vfs_mount *copy; - /* All parallel bind views retain the actual source, not another - * destination which may be unmounted independently. */ - bool replay=kind!=VFS_COPY_BIND && (fresh ? view.mount->propagation_backing : - view.mount->bind_source.mount!=NULL); + /* Parallel views retain the same backing with the same pin type. + * A replica of a native tree holds an internal lifetime pin, not an + * ordinary bind that would make the moved mount busy. */ + bool replay=kind!=VFS_COPY_BIND && view.mount->bind_source.mount; + bool propagation=kind!=VFS_COPY_BIND && (!replay || view.mount->propagation_backing); const struct vfs_path *backing=replay ? &view.mount->bind_source : &view; - int rc=vfs_bind_clone(&view,backing,fresh,©); + int rc=vfs_bind_clone(&view,backing,propagation,©); if(rc)return rc; copy->peer_group=group; copy->master=kind==VFS_COPY_SLAVE ? view.mount : view.mount->master; @@ -545,10 +549,10 @@ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_pa /** @brief Stage the peers and downstream receivers of one mount tree. * @param ns Borrowed execution-owned namespace; live inventory stays fixed. - * @param batch Owns the already staged origin and all prepared replicas. - * @param origin Borrowed event root in the batch. - * @param recursive True to copy the prepared bindable descendants. - * @param fresh True for a new filesystem, false for a regular bind. + * @param batch Owns all prepared replicas and, for an attach or bind, the origin. + * @param origin Borrowed event root, live at its old location for a move. + * @param target Exact destination for the event root. + * @param recursive True to copy the origin's bindable descendants. * @return Zero or negative errno. Parents are visited before their slaves; * each receiving peer group shares one new group per copied attachment. * A group with no matching directory view is skipped as a recipient but @@ -556,9 +560,8 @@ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_pa * cover is reparented only at commit so it remains visible above the copy. */ static int vfs_stage_propagation(struct vfs_namespace *ns,struct vfs_mount_batch *batch, - struct vfs_mount *origin,bool recursive,bool fresh) + struct vfs_mount *origin,const struct vfs_path *target,bool recursive) { - const struct vfs_path *target=&origin->point; if(!target->mount->peer_group)return 0; for(uint64_t level=0;;++level) { bool deeper=false; @@ -570,18 +573,20 @@ static int vfs_stage_propagation(struct vfs_namespace *ns,struct vfs_mount_batch if(depth!=level)continue; struct vfs_path point={peer,target->dentry}; - struct vfs_mount *prior=peer->peer_group ? vfs_staged_peer(batch,peer,point.dentry) : NULL; + struct vfs_mount *prior=peer->peer_group ? vfs_staged_peer(batch,peer,origin,target) : NULL; enum vfs_mount_copy kind=prior ? VFS_COPY_PEER : VFS_COPY_SLAVE; for(struct vfs_mount *master=peer->master;!prior && master;master=master->master) - prior=vfs_staged_peer(batch,master,point.dentry); + prior=vfs_staged_peer(batch,master,origin,target); /* Depth guarantees a staged ancestor; the origin always exists. */ if(!prior)return -EINVAL; struct vfs_path view={prior,prior->root}; struct vfs_mount *copy; - int rc=vfs_stage_bind_tree(batch,&view,&point,batch->pending,recursive,peer->peer_group!=0, - kind,fresh,©); + struct vfs_mount *inventory=prior->ns ? ns->mounts : batch->pending; + int rc=vfs_stage_bind_tree(batch,&view,&point,inventory,recursive,peer->peer_group!=0, + kind,©); if(rc)return rc; - copy->staged_cover=vfs_covering(ns,&point); + struct vfs_mount *cover=vfs_covering(ns,&point); + if(cover!=origin)copy->staged_cover=cover; } if(!deeper)return 0; } @@ -610,7 +615,7 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const stru } ++mount->references; vfs_stage_mount(&batch,mount,target); - int rc=vfs_stage_propagation(ns,&batch,mount,false,true); + int rc=vfs_stage_propagation(ns,&batch,mount,target,false); rc=vfs_finish_mount_batch(ns,&batch,rc); if(rc){mount->id=old_id;mount->peer_group=old_group;} return rc; @@ -636,8 +641,8 @@ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, struct vfs_mount_batch batch={.next_id=ns->next_id,.next_peer_id=ns->next_peer_id}; struct vfs_mount *first; bool shared=target->mount->peer_group!=0; - int rc=vfs_stage_bind_tree(&batch,source,target,ns->mounts,recursive,shared,VFS_COPY_BIND,false,&first); - if(!rc)rc=vfs_stage_propagation(ns,&batch,first,recursive,false); + int rc=vfs_stage_bind_tree(&batch,source,target,ns->mounts,recursive,shared,VFS_COPY_BIND,&first); + if(!rc)rc=vfs_stage_propagation(ns,&batch,first,target,recursive); return vfs_finish_mount_batch(ns,&batch,rc); } @@ -662,12 +667,42 @@ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *sou return vfs_bind_tree(ns,source,target,true); } -/** @brief Move a subtree only when neither parent needs propagation. +/** @brief Stage and publish a move into a shared parent and all its receivers. + * @param ns Borrowed execution-owned namespace. + * @param origin Live move root in ns; its old parent must not be shared. + * @param target Retained uncovered directory on a shared mount outside the tree. + * @return Zero or negative errno; no mountpoints, live groups or ID counters + * change on failure. The original mounts retain their IDs, policy and pins. + */ +static int vfs_move_into_shared(struct vfs_namespace *ns,struct vfs_mount *origin, + const struct vfs_path *target) +{ + for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) + if(mount->unbindable && vfs_mount_below(origin,mount))return -EINVAL; + + struct vfs_mount_batch batch={.next_id=ns->next_id,.next_peer_id=ns->next_peer_id}; + int rc=0; + for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { + if(mount->peer_group || !vfs_mount_below(origin,mount))continue; + if(!batch.next_peer_id){rc=-EOVERFLOW;break;} + mount->staged_peer_group=batch.next_peer_id++; + } + if(!rc)rc=vfs_stage_propagation(ns,&batch,origin,target,true); + for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { + if(!mount->staged_peer_group)continue; + if(!rc)mount->peer_group=mount->staged_peer_group; + mount->staged_peer_group=0; + } + if(!rc)vfs_replace_mountpoint(origin,target); + return vfs_finish_mount_batch(ns,&batch,rc); +} + +/** @brief Relocate a mount tree intact, propagating it under a shared parent. * @param ns Borrowed execution-owned namespace. * @param source Retained mounted root, excluding the namespace anchor. * @param target Retained destination directory in ns. * @return Zero or negative errno before mutation. Moving out of a shared - * parent is invalid; moving into one needs not-yet-supported propagation. + * parent or moving any unbindable mount into a shared parent is invalid. */ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path *target) { @@ -678,11 +713,12 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const if(mount==ns->root || !mount->point.mount)return -EBUSY; if(target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; if(mount->point.mount->peer_group)return -EINVAL; - if(target->mount->peer_group)return -EOPNOTSUPP; + if(target->dentry->disconnected)return -ENOENT; for(struct vfs_mount *ancestor=target->mount;ancestor;ancestor=ancestor->point.mount) for(struct vfs_mount *backing=ancestor;backing;backing=backing->bind_source.mount) if(backing==mount)return -ELOOP; if(vfs_covering(ns,target))return -EBUSY; + if(target->mount->peer_group)return vfs_move_into_shared(ns,mount,target); vfs_replace_mountpoint(mount,target);return 0; } diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 0cc5355b..b823d4a1 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -579,9 +579,10 @@ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *sou * @param ns Namespace under execution ownership. * @param source Held root of an attached mount, never the namespace base root. * @param target Held destination directory path in the same namespace. - * @return Zero or negative errno; moving out of a shared parent gives EINVAL, - * moving into one is unsupported. Rejected moves leave the attachment intact. - * No callbacks or allocation during commit. + * @return Zero or negative errno without partial moves or replicas. Moving + * out of a shared parent, or moving an unbindable branch into one, gives + * EINVAL. A shared destination publishes peer and slave copies of the tree. + * The original subtree moves intact; allocations finish before commit. */ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index d6711e01..b2b58db2 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -7,12 +7,12 @@ #include #include -/** @brief Resolve both exact endpoints of a mount move and commit the graph. +/** @brief Resolve both endpoints of a mount move, including propagated moves. * @param ns Borrowed execution-owned namespace. * @param task Authorized caller with actual root/cwd and optional retry scope. * @param source User source pathname pointer, required. * @param target User destination pathname pointer, required. - * @return Zero or lookup/type/cycle/busy errno; EAGAIN preserves scoped + * @return Zero or lookup/type/cycle/busy/allocation errno; EAGAIN preserves scoped * operands. Local references retire on every path; no graph lock spans I/O. */ static int mount_move(struct vfs_namespace *ns,struct task *task,uint64_t source,uint64_t target) diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index bfdc5e19..c307c384 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -3197,8 +3197,6 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_path_namespace(&b));vfs_path_put(&b); while(vfs_reclaim_mounts(32)){} - strcpy(user.source,"/shared-source"); - assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_MOVE,0)==-EOPNOTSUPP); for(unsigned lazy=0;lazy<2;++lazy) { strcpy(user.source,"peer with local child");strcpy(user.target,"/shared-a/p/event"); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,0,0)); @@ -3428,6 +3426,124 @@ static void runtime_slave_mounts(struct vfs_namespace *ns,const struct vfs_path puts("PASS slave propagation: recursive demotion, directional propagation, covered and lazy detach, bind rollback"); } +/** @brief Relocate a live tree and its propagation receivers in one transaction. + * @param ns Borrowed fixture namespace. @param root Retained namespace root. + */ +static void runtime_shared_move(struct vfs_namespace *ns,const struct vfs_path *root) +{ + const char *outer[]={"/move-a","/move-b","/move-s","/move-t","/move-src","/move-up"}; + for(unsigned i=0;i1)assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_SLAVE,0)); + } + strcpy(user.source,"move fixture");strcpy(user.target,"/move-s/slot"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,0,0)); + struct vfs_path cover={0},original={0},child={0},target={0},found={0}; + assert(!vfs_path_lookup(ns,root,root,user.target,0,&cover)); + strcpy(user.target,"/move-up"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,MS_NODEV,0)); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_SHARED,0)); + const unsigned long long upstream=fixture_shared_id(ns,root,"/move-up"); + strcpy(user.source,"/move-up");strcpy(user.target,"/move-src"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_BIND,0)); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_SLAVE,0)); + assert(!vfs_kernel_mkdir(ns,"/move-src/child",0755)); + strcpy(user.source,"move child");strcpy(user.target,"/move-src/child"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,type,MS_NOSUID,0)); + assert(!vfs_kernel_mkdir(ns,"/move-src/child/data",0755)); + assert(!vfs_path_lookup(ns,root,root,"/move-src",0,&original)); + assert(!vfs_path_lookup(ns,root,root,"/move-src/child",0,&child)); + assert(!vfs_path_lookup(ns,root,root,"/move-a/slot",0,&target)); + const uint64_t id=vfs_path_mount_id(&original),child_id=vfs_path_mount_id(&child); + const uint64_t next=ns->next_id,next_group=ns->next_peer_id; + strcpy(user.source,"/move-src"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_UNBINDABLE,0)); + strcpy(user.target,"/move-a/slot"); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_MOVE,0)==-EINVAL); + strcpy(user.target,"/move-src/child"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_PRIVATE,0)); + + /* Force failure after a receiver tree has been partially prepared. */ + test_fail_heap_after=5; + assert(vfs_mount_move(ns,&original,&target)==-ENOMEM); + test_fail_heap_after=-1; + assert(ns->next_id==next && ns->next_peer_id==next_group); + assert(!fixture_shared_id(ns,root,"/move-src") && !fixture_shared_id(ns,root,"/move-src/child")); + assert(fixture_mount_tag(ns,root,"/move-src"," master:")==upstream); + assert(!vfs_path_lookup(ns,root,root,"/move-a/slot",0,&found) && vfs_path_equal(&found,&target)); + vfs_path_put(&found);vfs_path_put(&target); + assert(vfs_path_lookup(ns,root,root,"/move-b/slot/child",0,&found)==-ENOENT); + + strcpy(user.target,"/move-a/slot"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,UINT64_MAX,MS_MOVE,UINT64_MAX)); + assert(ns->next_id==next+6 && ns->next_peer_id==next_group+2); + assert(!vfs_path_lookup(ns,root,root,"/move-a/slot",0,&found)); + assert(vfs_path_equal(&found,&original) && vfs_path_mount_id(&found)==id);vfs_path_put(&found); + assert(!vfs_path_lookup(ns,root,root,"/move-a/slot/child",0,&found)); + assert(vfs_path_equal(&found,&child) && vfs_path_mount_id(&found)==child_id);vfs_path_put(&found); + char name[64]; + assert(!vfs_path_format_link(ns,root,&child,name,sizeof(name)) && !strcmp(name,"/move-a/slot/child")); + assert(vfs_path_lookup(ns,root,root,"/move-src/child",0,&found)==-ENOENT); + assert(!vfs_path_lookup(ns,root,root,"/move-b/slot/child",0,&found)); + assert(vfs_path_mount_id(&found)!=child_id && vfs_path_same_inode(&found,&child)); + assert(vfs_path_mount_flags(&found)&MS_NOSUID);vfs_path_put(&found); + assert(!vfs_path_lookup(ns,root,root,"/move-t/slot/child/data",0,&found));vfs_path_put(&found); + assert(!vfs_path_lookup(ns,root,root,"/move-s/slot",0,&found) && vfs_path_equal(&found,&cover)); + vfs_path_put(&found); + const unsigned long long group=fixture_shared_id(ns,root,"/move-a/slot"); + const unsigned long long child_group=fixture_shared_id(ns,root,"/move-a/slot/child"); + assert(group && child_group && group!=child_group); + assert(fixture_shared_id(ns,root,"/move-b/slot")==group); + assert(fixture_shared_id(ns,root,"/move-b/slot/child")==child_group); + assert(fixture_mount_tag(ns,root,"/move-a/slot"," master:")==upstream); + assert(fixture_mount_tag(ns,root,"/move-b/slot"," master:")==upstream); + assert(fixture_mount_tag(ns,root,"/move-t/slot"," master:")==group); + assert(fixture_mount_tag(ns,root,"/move-t/slot/child"," master:")==child_group); + strcpy(user.source,"/move-a/slot");strcpy(user.target,"/move-src"); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_MOVE,0)==-EINVAL); + vfs_path_put(&original);vfs_path_put(&child); + strcpy(user.target,"/move-a/slot"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,MNT_DETACH,0,0,0)); + assert(vfs_path_lookup(ns,root,root,"/move-b/slot/child",0,&found)==-ENOENT); + assert(!vfs_path_lookup(ns,root,root,"/move-s/slot",0,&found) && vfs_path_equal(&found,&cover)); + vfs_path_put(&found);vfs_path_put(&cover); + strcpy(user.target,"/move-s/slot"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + while(vfs_reclaim_mounts(32)){} + + /* The source can itself occupy the receiver slot it is about to vacate. */ + strcpy(user.target,"/move-s/relocate"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,type,0,0)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&original)); + strcpy(user.source,user.target);strcpy(user.target,"/move-a/relocate"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_MOVE,0)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&found) && vfs_path_equal(&found,&original)); + vfs_path_put(&found); + assert(!vfs_path_lookup(ns,root,root,"/move-s/relocate",0,&found)); + assert(!vfs_path_equal(&found,&original) && vfs_path_same_inode(&found,&original)); + vfs_path_put(&found);vfs_path_put(&original); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + for(unsigned i=sizeof(outer)/sizeof(outer[0]);i--;) { + if(i==4)continue; + strcpy(user.target,outer[i]);assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + } + vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + lookup_user_base=lookup_user_bytes=0; + puts("PASS shared MS_MOVE: subtree identity, peer/slave replicas, covered slots and atomic failure"); +} + /** @brief Verify lazy detach hides a mount tree without revoking retained paths. * @param ns Borrowed namespace under fixture execution ownership. * @param root Retained namespace anchor. @param fs Base tmpfs for the fixture. @@ -3709,6 +3825,7 @@ int main(int argc,char **argv) runtime_recursive_bind(&ns,&root,fs); runtime_shared_mounts(&ns,&root); runtime_slave_mounts(&ns,&root); + runtime_shared_move(&ns,&root); runtime_bind_remount(&ns,&root,fs); runtime_lazy_unmount(&ns,&root,fs); device_mount_objects(&ns,&root,fs); From a209521228e1e4f079694a9dfa066be7d30e9119 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 01:45:18 +0800 Subject: [PATCH 13/97] feat(vfs): snapshot and retire mount namespaces --- Documentation/core-api/index.rst | 1 + Documentation/core-api/mount-namespaces.rst | 19 ++ .../LC_MESSAGES/core-api/mount-namespaces.po | 59 +++++++ .../LC_MESSAGES/core-api/mount-namespaces.po | 51 ++++++ fs/vfs/mount_internal.h | 9 +- fs/vfs/mount_tree.c | 166 ++++++++++++++++-- include/reliefnt/mount.h | 23 ++- tools/tests/mount_backend_test.c | 46 ++--- tools/tests/mount_tree_test.c | 147 ++++++++++++++-- tools/tests/procfs_directories_test.c | 24 ++- 10 files changed, 487 insertions(+), 58 deletions(-) create mode 100644 Documentation/core-api/mount-namespaces.rst create mode 100644 Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po create mode 100644 Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po diff --git a/Documentation/core-api/index.rst b/Documentation/core-api/index.rst index 398a3cd8..2abe6f56 100644 --- a/Documentation/core-api/index.rst +++ b/Documentation/core-api/index.rst @@ -14,6 +14,7 @@ kthread memory path-cache + mount-namespaces resource-limits drivers storage-completion diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst new file mode 100644 index 00000000..1fdcb8c1 --- /dev/null +++ b/Documentation/core-api/mount-namespaces.rst @@ -0,0 +1,19 @@ +================ +挂载命名空间快照 +================ + +``vfs_namespace_snapshot()`` 在独占 VFS 执行权下,将活动挂载树复制到地址固定、 +由调用方管理的空命名空间中。它保留覆盖层、不可绑定挂载和图内传播关系;新旧 +命名空间之间不会建立传播关系。各副本直接持有原生文件系统后端,共享目录项和 +文件内容,但挂载策略和写入者计数独立。挂载 ID 从 VFS 全局序列分配,传播组号 +仍仅在各自的命名空间内有意义。 + +可选的 root 和 cwd 引用按原挂载对象和目录项重新绑定,而不是重新查找路径; +即使路径已被其他挂载覆盖,所指目录项也不变。已摘除的路径保持原样,其他活动 +命名空间的路径返回 ``EXDEV``。所有分配完成后才发布新树并替换路径;失败时 +不改变原树、目标、路径或 ID 游标。 + +最后一个图使用者离开时,``vfs_namespace_retire()`` 摘除整棵树而不传播卸载。 +已持有的路径继续有效,后端由现有的延迟清理队列处理。与之不同,严格的 +``vfs_namespace_destroy()`` 在仍有外部引用时拒绝销毁。此接口用于内核内部; +当前没有向用户态开放挂载命名空间创建或切换。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po new file mode 100644 index 00000000..ada3a037 --- /dev/null +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -0,0 +1,59 @@ +# ReliefNT core API documentation translations. +# Copyright (C) 2021-2026, ReliefOS contributors +# This file is distributed under the same license as the ReliefNT package. +msgid "" +msgstr "" +"Project-Id-Version: ReliefNT 5.3.4\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-11-29 01:43+0800\n" +"PO-Revision-Date: 2026-11-14 00:00+0800\n" +"Last-Translator: ReliefOS contributors\n" +"Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "挂载命名空间快照" +msgstr "Mount namespace snapshots" + +msgid "" +"``vfs_namespace_snapshot()`` 在独占 VFS 执行权下,将活动挂载树复制到地址固定、 " +"由调用方管理的空命名空间中。它保留覆盖层、不可绑定挂载和图内传播关系;新旧 " +"命名空间之间不会建立传播关系。各副本直接持有原生文件系统后端,共享目录项和 文件内容,但挂载策略和写入者计数独立。挂载 ID 从 VFS " +"全局序列分配,传播组号 仍仅在各自的命名空间内有意义。" +msgstr "" +"With exclusive VFS execution ownership, ``vfs_namespace_snapshot()`` " +"copies an active mount tree into an empty namespace at a stable address " +"owned by the caller. It preserves overmounts, unbindable mounts, and " +"propagation relationships within the graph. There is no propagation " +"between the original and copied namespaces. Each copy directly pins the " +"native filesystem backend and shares dentries and file contents, but " +"keeps its own mount policy and writer count. The VFS assigns mount IDs " +"from a global sequence; propagation group IDs remain namespace-local." + +msgid "" +"可选的 root 和 cwd 引用按原挂载对象和目录项重新绑定,而不是重新查找路径; " +"即使路径已被其他挂载覆盖,所指目录项也不变。已摘除的路径保持原样,其他活动 命名空间的路径返回 " +"``EXDEV``。所有分配完成后才发布新树并替换路径;失败时 不改变原树、目标、路径或 ID 游标。" +msgstr "" +"Optional root and cwd references are rebound by original attachment and " +"dentry identity, not by looking up the pathname again. An overmount does " +"not change the referenced dentry. Detached paths stay unchanged; a path " +"in another live namespace returns ``EXDEV``. The new tree and path " +"replacements are published only after all allocations succeed. Failure " +"leaves the original tree, destination, paths, and ID cursor unchanged." + +msgid "" +"最后一个图使用者离开时,``vfs_namespace_retire()`` 摘除整棵树而不传播卸载。 " +"已持有的路径继续有效,后端由现有的延迟清理队列处理。与之不同,严格的 ``vfs_namespace_destroy()`` " +"在仍有外部引用时拒绝销毁。此接口用于内核内部; 当前没有向用户态开放挂载命名空间创建或切换。" +msgstr "" +"After the last graph user leaves, ``vfs_namespace_retire()`` detaches the" +" entire tree without propagating unmounts. Held paths remain valid and " +"the existing deferred queue handles backend teardown. The stricter " +"``vfs_namespace_destroy()`` instead rejects destruction while external " +"references remain. These are internal kernel interfaces; creation and " +"switching of mount namespaces are not yet exposed to userspace." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po new file mode 100644 index 00000000..64c58fae --- /dev/null +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -0,0 +1,51 @@ +# ReliefNT core API documentation translations. +# Copyright (C) 2021-2026, ReliefOS contributors +# This file is distributed under the same license as the ReliefNT package. +msgid "" +msgstr "" +"Project-Id-Version: ReliefNT 5.3.4\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-11-29 01:43+0800\n" +"PO-Revision-Date: 2026-11-14 00:00+0800\n" +"Last-Translator: ReliefOS contributors\n" +"Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "挂载命名空间快照" +msgstr "マウント名前空間のスナップショット" + +msgid "" +"``vfs_namespace_snapshot()`` 在独占 VFS 执行权下,将活动挂载树复制到地址固定、 " +"由调用方管理的空命名空间中。它保留覆盖层、不可绑定挂载和图内传播关系;新旧 " +"命名空间之间不会建立传播关系。各副本直接持有原生文件系统后端,共享目录项和 文件内容,但挂载策略和写入者计数独立。挂载 ID 从 VFS " +"全局序列分配,传播组号 仍仅在各自的命名空间内有意义。" +msgstr "" +"``vfs_namespace_snapshot()`` は VFS " +"の排他的な実行権を保持した状態で、稼働中のマウントツリーを、呼び出し側が管理する固定アドレスの空の名前空間にコピーします。重ね掛け、バインド不可のマウント、グラフ内の伝播関係を保持しますが、コピー元とコピー先の名前空間の間では伝播しません。各コピーはネイティブのファイルシステムバックエンドを直接参照し、ディレクトリエントリとファイルの内容を共有します。マウントポリシーと書き込み参照数は独立しています。マウント" +" ID は VFS 全体で一意の連番から割り当て、伝播グループ ID は名前空間内だけで有効です。" + +msgid "" +"可选的 root 和 cwd 引用按原挂载对象和目录项重新绑定,而不是重新查找路径; " +"即使路径已被其他挂载覆盖,所指目录项也不变。已摘除的路径保持原样,其他活动 命名空间的路径返回 " +"``EXDEV``。所有分配完成后才发布新树并替换路径;失败时 不改变原树、目标、路径或 ID 游标。" +msgstr "" +"オプションの root と cwd " +"は、パス名を再検索せず、元のマウントとディレクトリエントリの対応に従って付け替えます。他のマウントに覆われていても、参照するディレクトリエントリは変わりません。切り離されたパスはそのまま保持し、別の稼働中の名前空間に属するパスには" +" ``EXDEV`` " +"を返します。すべての割り当てに成功してから、新しいツリーを公開しパスを差し替えます。失敗しても元のツリー、コピー先、パス、ID " +"のカーソルは変わりません。" + +msgid "" +"最后一个图使用者离开时,``vfs_namespace_retire()`` 摘除整棵树而不传播卸载。 " +"已持有的路径继续有效,后端由现有的延迟清理队列处理。与之不同,严格的 ``vfs_namespace_destroy()`` " +"在仍有外部引用时拒绝销毁。此接口用于内核内部; 当前没有向用户态开放挂载命名空间创建或切换。" +msgstr "" +"グラフの最後の利用者が離れると、``vfs_namespace_retire()`` " +"はアンマウントを伝播させずにツリー全体を切り離します。保持中のパスは有効なままで、既存の遅延処理キューがバックエンドの後処理を行います。これに対し、厳格な" +" ``vfs_namespace_destroy()`` " +"は外部参照が残っている間は破棄を拒否します。これらはカーネル内部インターフェースであり、名前空間の作成と切り替えはまだユーザー空間に公開されていません。" diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index e764f277..b94ad5f3 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -34,9 +34,9 @@ struct vfs_mount { struct module *owner; uint64_t references,id,policy,peer_group; /* Zero group is not shared. */ uint64_t staged_peer_group; /* Tentative group of an original mount during MS_MOVE. */ - uint64_t propagation_pins; /* Replica lifetime references, not open paths. */ + uint64_t propagation_pins; /* Shared backend lifetime references, not open paths. */ uint64_t writers; /* Open writable file descriptions on this attachment. */ - bool propagation_backing; /* This bind_source is a replica lifetime pin. */ + bool propagation_backing; /* This bind_source is a replica or snapshot lifetime pin. */ bool unmount_selected; /* Scratch under the namespace execution writer. */ bool lift_cover; /* Scratch: retain this overmount above a removed receiver. */ bool propagation_copy; /* Receiver can detach beneath an unrelated root cover. */ @@ -45,6 +45,11 @@ struct vfs_mount { char *source,*filesystem; uint64_t device; }; +/** @brief Read the VFS-wide attachment ID cursor under execution ownership. + * @return Next unassigned mount ID, or zero after exhaustion. Failing a mount + * publication or snapshot never advances this cursor. + */ +uint64_t vfs_mount_next_id(void); bool vfs_path_valid(const struct vfs_path *path); /** @brief Admit a held path for pathname access, not mount topology changes. * @param ns Borrowed execution-owned lookup namespace. diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index 07ea61c1..afc36d49 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -8,6 +8,7 @@ static struct vfs_mount *retired_mounts,**retired_tail=&retired_mounts; static uint64_t retired_count; static bool reclaim_active; +static uint64_t next_mount_id=1; /** @brief Append one detached, rootless mount to the execution-owned FIFO. * @param mount Privately owned final mount, not already queued; next is unused. @@ -221,15 +222,23 @@ int vfs_path_anonymous(struct vfs_mount *mount,const struct storage_node *node,s struct vfs_path value={mount,dentry};vfs_path_get(&value,out);return 0; } +/** @brief Observe the next attachment ID without reserving it. + * @return VFS-wide publication cursor, or zero when exhausted. The caller + * holds execution ownership, as for all mount graph operations. + */ +uint64_t vfs_mount_next_id(void) {return next_mount_id;} + /** @brief Retain an unpublished mount as the permanent namespace anchor. * @param ns Borrowed empty namespace. @param root Borrowed unpublished root. - * @return Zero or negative errno. Previously lazily detached roots are rejected. + * @return Zero or negative errno, including exhaustion of VFS-wide mount IDs. + * Previously lazily detached roots are rejected. */ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root) { if(!ns || ns->root || ns->mounts || !root || root->ns || root->point.mount || root->lazy_detached)return -EINVAL; - ++root->references;root->ns=ns;root->id=1;root->next=NULL; - ns->root=root;ns->mounts=root;ns->next_id=2;ns->next_peer_id=1;return 0; + if(!next_mount_id)return -EOVERFLOW; + ++root->references;root->ns=ns;root->id=next_mount_id++;root->next=NULL; + ns->root=root;ns->mounts=root;ns->next_peer_id=1;return 0; } /** @brief Find the attachment immediately covering an exact retained slot. @@ -338,7 +347,7 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa /** @brief Prepare an unattached directory view of an existing filesystem. * @param view Valid source directory; supplies the root and attachment policy. * @param backing Retained path to the same dentry, pinned for this view's lifetime. - * @param propagation True for a replica-only backing reference. + * @param propagation True for a replica or snapshot backend lifetime reference. * @param out Receives the privately owned clone on success, NULL on failure. * @return Zero or negative provider/admission/allocation errno. No new backend * is created, and the clone has no namespace membership or inotify registration. @@ -397,7 +406,7 @@ static void vfs_replace_mountpoint(struct vfs_mount *mount,const struct vfs_path * @param batch Owned unpublished mounts and tentative ID counters. * @param status Nonzero to discard, zero to commit all changes. * @return The supplied status. Rollback releases descendants before parents; - * neither graph nor namespace counters change on error. At commit, rehang + * neither graph nor the ID cursors change on error. At commit, rehang * any existing receiver stack on its newly inserted mount's root. */ static int vfs_finish_mount_batch(struct vfs_namespace *ns,struct vfs_mount_batch *batch,int status) @@ -420,7 +429,102 @@ static int vfs_finish_mount_batch(struct vfs_namespace *ns,struct vfs_mount_batc if(!mount->notify_link && vfs_notify_mount_created)vfs_notify_mount_created(mount); } if(batch->pending){*tail=ns->mounts;ns->mounts=batch->pending;} - ns->next_id=batch->next_id;ns->next_peer_id=batch->next_peer_id; + next_mount_id=batch->next_id;ns->next_peer_id=batch->next_peer_id; + return 0; +} + +/** @brief Find a copied attachment by walking two lists in the same order. + * @param source Parallel original inventory, unchanged during the snapshot. + * @param copies Prepared mount inventory in the same order as source. + * @param match Original attachment to map, or NULL. + * @return Borrowed corresponding copy; NULL for a detached or absent mount. + * Uses no source scratch fields or depth-dependent stack. + */ +static struct vfs_mount *vfs_snapshot_mount(const struct vfs_mount *source, + struct vfs_mount *copies,const struct vfs_mount *match) +{ + if(!match)return NULL; + for(;source;source=source->next,copies=copies->next) + if(source==match)return copies; + return NULL; +} + +/** @brief Validate an optional task path before preparing a snapshot. + * @param source Live source graph, borrowed. + * @param path Optional owned path slot, borrowed for validation. + * @return Zero for a source member, already detached path or empty slot; + * otherwise EINVAL or EXDEV. No reference or state changes. + */ +static int vfs_snapshot_path_check(const struct vfs_namespace *source,const struct vfs_path *path) +{ + if(!path || (!path->mount && !path->dentry))return 0; + if(!vfs_path_valid(path))return -EINVAL; + return vfs_path_walkable(source,path) ? 0 : -EXDEV; +} + +/** @brief Replace a held task path with the matching snapshot attachment. + * @param path Optional owned path, unchanged if it has no copy. + * @param copy Borrowed published attachment for the same held dentry, or NULL. + * Retains the new pair before releasing the source reference. + */ +static void vfs_snapshot_rebind(struct vfs_path *path,struct vfs_mount *copy) +{ + if(!copy)return; + struct vfs_path old=*path,replacement={copy,old.dentry}; + vfs_path_get(&replacement,path);vfs_path_put(&old); +} + +/** @brief Clone every attachment and then publish exact graph relationships. + * @param dest Empty caller-owned namespace at its final address. + * @param source Live source graph, stable under execution ownership. + * @param root Optional owned task root to rebind, empty or detached allowed. + * @param cwd Optional owned working directory to rebind, empty or detached allowed. + * @return Zero or negative errno before publishing any change. Copies retain + * the native backing, not intermediate attachment references. Topology and + * weak propagation edges are translated only after every allocation succeeds. + */ +int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace *source, + struct vfs_path *root,struct vfs_path *cwd) +{ + if(!dest || !source || dest->root || dest->mounts || !source->root)return -EINVAL; + if(root==cwd)cwd=NULL; + int rc=vfs_snapshot_path_check(source,root); + if(!rc)rc=vfs_snapshot_path_check(source,cwd); + if(rc)return rc; + + struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=source->next_peer_id}; + struct vfs_mount **tail=&batch.pending; + for(struct vfs_mount *mount=source->mounts;mount;mount=mount->next) { + if(!batch.next_id){rc=-EOVERFLOW;break;} + struct vfs_mount *backing=mount; + while(backing->bind_source.mount)backing=backing->bind_source.mount; + struct vfs_path view={mount,mount->root},pin={backing,mount->root}; + struct vfs_mount *copy; + rc=vfs_bind_clone(&view,&pin,true,©); + if(rc)break; + *tail=copy;tail=©->next;++batch.next_id; + } + if(rc)return vfs_finish_mount_batch(dest,&batch,rc); + + /* Preserve the list's newest-first ID order, not just its topology. A + * move can leave an attachment under a parent with a higher ID. */ + uint64_t id=batch.next_id; + struct vfs_mount *copy=batch.pending; + for(const struct vfs_mount *mount=source->mounts;mount;mount=mount->next,copy=copy->next) { + copy->id=--id; + copy->peer_group=mount->peer_group; + copy->unbindable=mount->unbindable; + copy->propagation_copy=mount->propagation_copy; + copy->master=vfs_snapshot_mount(source->mounts,batch.pending,mount->master); + struct vfs_path point={vfs_snapshot_mount(source->mounts,batch.pending,mount->point.mount), + mount->point.dentry}; + vfs_path_get(&point,©->point); + } + struct vfs_mount *root_copy=root ? vfs_snapshot_mount(source->mounts,batch.pending,root->mount) : NULL; + struct vfs_mount *cwd_copy=cwd ? vfs_snapshot_mount(source->mounts,batch.pending,cwd->mount) : NULL; + dest->root=vfs_snapshot_mount(source->mounts,batch.pending,source->root); + vfs_finish_mount_batch(dest,&batch,0); + vfs_snapshot_rebind(root,root_copy);vfs_snapshot_rebind(cwd,cwd_copy); return 0; } @@ -606,8 +710,8 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const stru if(target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; if(target->dentry->disconnected)return -ENOENT; if(mount->ns || mount->point.mount || mount->lazy_detached || vfs_covering(ns,target))return -EBUSY; - if(!ns->next_id)return -EOVERFLOW; - struct vfs_mount_batch batch={.next_id=ns->next_id,.next_peer_id=ns->next_peer_id}; + if(!next_mount_id)return -EOVERFLOW; + struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=ns->next_peer_id}; uint64_t old_id=mount->id,old_group=mount->peer_group; if(target->mount->peer_group) { if(!batch.next_peer_id)return -EOVERFLOW; @@ -638,7 +742,7 @@ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, if(source->dentry->disconnected || target->dentry->disconnected)return -ENOENT; if(vfs_covering(ns,target))return -EBUSY; - struct vfs_mount_batch batch={.next_id=ns->next_id,.next_peer_id=ns->next_peer_id}; + struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=ns->next_peer_id}; struct vfs_mount *first; bool shared=target->mount->peer_group!=0; int rc=vfs_stage_bind_tree(&batch,source,target,ns->mounts,recursive,shared,VFS_COPY_BIND,&first); @@ -680,7 +784,7 @@ static int vfs_move_into_shared(struct vfs_namespace *ns,struct vfs_mount *origi for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) if(mount->unbindable && vfs_mount_below(origin,mount))return -EINVAL; - struct vfs_mount_batch batch={.next_id=ns->next_id,.next_peer_id=ns->next_peer_id}; + struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=ns->next_peer_id}; int rc=0; for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { if(mount->peer_group || !vfs_mount_below(origin,mount))continue; @@ -795,7 +899,7 @@ static void vfs_select_unmounts(struct vfs_namespace *ns,struct vfs_mount *root, /** @brief Reject busy mounts before changing any member of an unmount batch. * @param ns Borrowed execution-owned namespace with selected mounts marked. * @param root Origin mount with the caller's lookup reference. - * @return Zero or negative busy/provider errno. Replica lifetime pins and + * @return Zero or negative busy/provider errno. Backing lifetime pins and * edges disappearing or being reparented in this batch are not external path * references. A regular bind outside the batch still pins its source as before. */ @@ -817,8 +921,8 @@ static int vfs_unmount_preflight(const struct vfs_namespace *ns,const struct vfs } } if(mount->references!=expected)return -EBUSY; - /* Check native backing users once only when origin and all lifetime - * replicas are going away. The origin may already be detached. */ + /* Check native backing users once only when the origin and all + * backing views are going away. The origin may already be detached. */ bool final_check=mount->propagation_backing ? !backing->ns && first_replica && backing->references==backing->propagation_pins : !mount->bind_source.mount; if(final_check && replicas==backing->propagation_pins && backing->ops->can_unmount) { @@ -829,6 +933,19 @@ static int vfs_unmount_preflight(const struct vfs_namespace *ns,const struct vfs return 0; } +/** @brief Release mountpoint and membership references after disconnecting a list. + * @param detached List of formerly published attachments, owned and consumed. + * No namespace edges still reach the list. Lazy attachments queue their + * final backend teardown; ordinary unmount can finish in this caller. + */ +static void vfs_release_detached_mounts(struct vfs_mount *detached) +{ + while(detached) { + struct vfs_mount *mount=detached;detached=mount->next;mount->next=NULL; + vfs_path_put(&mount->point);vfs_mount_put(mount); + } +} + /** @brief Unlink the entire selected graph before dropping retained edges. * @param ns Borrowed execution-owned namespace with selected mounts marked. * @param lazy True to keep external paths walkable and defer final teardown. @@ -854,10 +971,7 @@ static void vfs_disconnect_unmounts(struct vfs_namespace *ns,bool lazy) mount->master=NULL;mount->unbindable=false; mount->unmount_selected=false;mount->propagation_copy=false; } - while(detached) { - struct vfs_mount *mount=detached;detached=mount->next;mount->next=NULL; - vfs_path_put(&mount->point);vfs_mount_put(mount); - } + vfs_release_detached_mounts(detached); } /** @brief Detach one idle mount and all removable counterparts atomically. @@ -899,6 +1013,24 @@ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path) vfs_disconnect_unmounts(ns,true);return 0; } +/** @brief Retire the complete graph locally, including the namespace anchor. + * @param ns Last-owner namespace storage, or NULL, under VFS execution. + * Clears membership and weak propagation links before releasing paths. + * Does not propagate unmount or wait for open objects or backend finish. + */ +void vfs_namespace_retire(struct vfs_namespace *ns) +{ + if(!ns)return; + struct vfs_mount *mounts=ns->mounts; + *ns=(struct vfs_namespace){0}; + for(struct vfs_mount *mount=mounts;mount;mount=mount->next) { + mount->ns=NULL;mount->lazy_detached=true; + mount->master=NULL;mount->peer_group=0; + mount->unbindable=false;mount->propagation_copy=false; + } + vfs_release_detached_mounts(mounts); +} + int vfs_namespace_destroy(struct vfs_namespace *ns) { if(!ns)return -EINVAL; diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index b823d4a1..10fb773b 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -194,7 +194,7 @@ bool vfs_path_same_filesystem(const struct vfs_path *left,const struct vfs_path * graph traversal, locking or ownership transfer occurs. */ struct vfs_namespace *vfs_path_namespace(const struct vfs_path *path); -struct vfs_namespace {struct vfs_mount *root,*mounts;uint64_t next_id,next_peer_id;}; +struct vfs_namespace {struct vfs_mount *root,*mounts;uint64_t next_peer_id;}; /** @brief Assign immutable diagnostic identity before publishing a mount. * @param mount Owned detached mount, required; attachment returns EBUSY. * @param source Nonempty kernel source label, copied with PATH_MAX bounds. @@ -521,6 +521,27 @@ int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags); * @return Zero or negative errno, no change on failure. Serialized task context. */ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root); +/** @brief Publish a separate snapshot of a live namespace, sharing backends. + * @param dest Caller-owned empty namespace at its final address. + * @param source Live namespace, borrowed under exclusive VFS execution. + * @param root Optional owned task root slot to rebind, or NULL. + * @param cwd Optional owned working directory slot to rebind, or NULL. + * @return Zero or negative errno, leaving dest and both paths unchanged on + * failure. Held paths in source retain the same dentry on the corresponding + * new mount, even under an overmount; detached paths and empty slots remain + * unchanged. Live paths outside source are rejected. Mount IDs and policy + * are independent; propagation relations are copied locally, not connected + * between namespaces. No filesystem lookup or backend creation is needed. + */ +int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace *source, + struct vfs_path *root,struct vfs_path *cwd); +/** @brief Disconnect all mounts for last-owner namespace teardown. + * @param ns Caller-owned namespace with no remaining graph users, or NULL. + * Serialized VFS execution. Clears ns without propagating, checking busy + * paths or flushing backends. Held paths survive as detached objects; + * final backend cleanup is deferred. The caller owns the namespace storage. + */ +void vfs_namespace_retire(struct vfs_namespace *ns); /** @brief Destroy a namespace only when every external path/handle has gone. * @param ns Namespace to clear; NULL is invalid. * @return Zero or -EBUSY without partial detach on an external reference. diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index c307c384..123ae40a 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -1,6 +1,8 @@ /* SPDX-License-Identifier: Apache-2.0 */ /* Existing whole VFS composition supplies the real tmpfs/inode adapters and * physical-I/O boundary stubs. Production code is independently compiled. */ +#include + #define RELIEFNT_FIXTURE_REGISTER_TYPES #define RELIEFNT_FIXTURE_OWN_IRQ_LOCKS #define RELIEFNT_FIXTURE_ISO_READER @@ -171,14 +173,16 @@ uint64_t mm_total_memory_kib(void){return 65536;} static void real_mount_description(struct vfs_namespace *ns,const struct vfs_path *root, const char *type,const char *flags) { - char text[1024],wanted[80];uint32_t count=0; + char text[1024],wanted[128];uint32_t count=0; assert(!vfs_read_mount_table(ns,root,true,0,text,sizeof(text)-1,&count));text[count]=0; uint32_t major=0,minor=1; if(strcmp(type,"tmpfs")) { const struct test_memory_disk *disk=test_memory_disk(vfs_path_context(root)); major=1;minor=disk->registration.info.controller; } - snprintf(wanted,sizeof(wanted),"1 1 %u:%u / / %s - %s ",major,minor,flags,type); + const uint64_t id=vfs_path_mount_id(root); + snprintf(wanted,sizeof(wanted),"%" PRIu64 " %" PRIu64 " %u:%u / / %s - %s ", + id,id,major,minor,flags,type); assert(strstr(text,wanted)); } /* This inode-only fixture creates no VMAs. Observe the real tmpfs resize @@ -2943,13 +2947,13 @@ static void runtime_unbindable(struct vfs_namespace *ns,const struct vfs_path *r assert(!scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,ignored,to,ignored,MS_SLAVE,ignored)); strcpy(source,"/rbind-source/view/child");strcpy(target,"/rbind-target"); - uint64_t before=ns->next_id; + uint64_t before=vfs_mount_next_id(); for(unsigned i=0;i<2;++i) assert(scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,from,to,ignored,MS_BIND|(i ? MS_REC : 0),ignored)==-EINVAL); - assert(ns->next_id==before); + assert(vfs_mount_next_id()==before); strcpy(source,"/rbind-source/view"); assert(!scoped_mount_call(ns,actor,LINUX_SYS_MOUNT,from,to,ignored,MS_BIND|MS_REC,ignored)); - assert(ns->next_id==before+2); + assert(vfs_mount_next_id()==before+2); struct vfs_path found={0}; assert(vfs_path_lookup(ns,root,root,"/rbind-target/child/deep",0,&found)==-ENOENT); assert(!vfs_path_lookup(ns,root,root,"/rbind-target/peer",0,&found)); @@ -2996,7 +3000,7 @@ static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_pat lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); uint64_t source=(uintptr_t)user.source,target=(uintptr_t)user.target; assert(!vfs_path_lookup(ns,root,root,user.target,0,&point)); - const uint64_t next_id=ns->next_id; + const uint64_t next_id=vfs_mount_next_id(); bool attached=false; for(int budget=0;budget<64;++budget) { test_fail_heap_after=budget; @@ -3006,11 +3010,11 @@ static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_pat if(!rc){attached=true;break;} assert(rc==-ENOMEM); struct vfs_path unchanged={0}; - assert(ns->next_id==next_id && !actor.lookup_scope.armed); + assert(vfs_mount_next_id()==next_id && !actor.lookup_scope.armed); assert(!vfs_path_lookup(ns,root,root,user.target,0,&unchanged)); assert(vfs_path_equal(&unchanged,&point));vfs_path_put(&unchanged); } - assert(attached && ns->next_id==next_id+4); + assert(attached && vfs_mount_next_id()==next_id+4); struct vfs_path bound={0},copy[3]={0}; const char *copy_names[]={"/rbind-target/child","/rbind-target/child/deep","/rbind-target/peer"}; assert(!vfs_path_lookup(ns,root,root,user.target,0,&bound)); @@ -3106,15 +3110,15 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&a)); assert(!vfs_path_lookup(ns,root,root,user.target,0,&point)); assert(!storage_new_tmpfs_mount("stacked event",0,NULL,1000,1000,&mount)); - const uint64_t covered_id=ns->next_id,covered_peer_id=ns->next_peer_id; + const uint64_t covered_id=vfs_mount_next_id(),covered_peer_id=ns->next_peer_id; test_fail_heap_after=1; assert(vfs_mount_attach(ns,mount,&point)==-ENOMEM); test_fail_heap_after=-1; - assert(ns->next_id==covered_id && ns->next_peer_id==covered_peer_id); + assert(vfs_mount_next_id()==covered_id && ns->next_peer_id==covered_peer_id); assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&found)); assert(vfs_path_equal(&a,&found));vfs_path_put(&found); assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); - assert(ns->next_id==covered_id+2 && ns->next_peer_id==covered_peer_id+1); + assert(vfs_mount_next_id()==covered_id+2 && ns->next_peer_id==covered_peer_id+1); assert(!vfs_kernel_mkdir(ns,"/shared-b/covered/incoming",0755)); assert(vfs_path_lookup(ns,root,root,"/shared-a/covered/incoming",0,&found)==-ENOENT); assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&found)); @@ -3136,17 +3140,17 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_path_lookup(ns,root,root,"/shared-a/outside",0,&point)); assert(!storage_new_tmpfs_mount("shared event",0,NULL,1000,1000,&mount)); - const uint64_t next_id=ns->next_id,peer_id=ns->next_peer_id; + const uint64_t next_id=vfs_mount_next_id(),peer_id=ns->next_peer_id; test_fail_heap_after=1; assert(vfs_mount_attach(ns,mount,&point)==-ENOMEM); test_fail_heap_after=-1; - assert(ns->next_id==next_id && ns->next_peer_id==peer_id); + assert(vfs_mount_next_id()==next_id && ns->next_peer_id==peer_id); assert(!vfs_path_lookup(ns,root,root,"/shared-a/outside",0,&found)); assert(vfs_path_equal(&found,&point));vfs_path_put(&found); assert(!vfs_path_lookup(ns,root,root,"/shared-b/outside",0,&found)); assert(vfs_path_same_inode(&found,&point));vfs_path_put(&found); assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); - assert(ns->next_id==next_id+2); + assert(vfs_mount_next_id()==next_id+2); unsigned long long event=fixture_shared_id(ns,root,"/shared-a/outside"); assert(event && event!=group && fixture_shared_id(ns,root,"/shared-b/outside")==event); assert(vfs_path_lookup(ns,root,root,"/shared-narrow/outside",0,&found)==-ENOENT); @@ -3168,12 +3172,12 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_kernel_mkdir(ns,"/shared-source/child/nested",0755)); assert(!vfs_path_lookup(ns,root,root,"/shared-source",0,&a)); assert(!vfs_path_lookup(ns,root,root,"/shared-a/p/event",0,&point)); - const uint64_t bind_id=ns->next_id,bind_peer_id=ns->next_peer_id; + const uint64_t bind_id=vfs_mount_next_id(),bind_peer_id=ns->next_peer_id; /* The first tree and one receiver tree fit, but not the final receiver. */ test_fail_heap_after=8; assert(vfs_mount_bind_recursive(ns,&a,&point)==-ENOMEM); test_fail_heap_after=-1; - assert(ns->next_id==bind_id && ns->next_peer_id==bind_peer_id); + assert(vfs_mount_next_id()==bind_id && ns->next_peer_id==bind_peer_id); assert(!fixture_shared_id(ns,root,"/shared-source")); assert(vfs_path_lookup(ns,root,root,"/shared-a/p/event/child",0,&found)==-ENOENT); assert(vfs_path_lookup(ns,root,root,"/shared-b/p/event/child",0,&found)==-ENOENT); @@ -3364,11 +3368,11 @@ static void runtime_slave_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_kernel_mkdir(ns,"/slave-d/rec/local",0755)); assert(!vfs_path_lookup(ns,root,root,"/slave-source",0,&a)); assert(!vfs_path_lookup(ns,root,root,"/slave-a/rec",0,&b)); - const uint64_t id=ns->next_id,group=ns->next_peer_id; + const uint64_t id=vfs_mount_next_id(),group=ns->next_peer_id; test_fail_heap_after=9; assert(vfs_mount_bind_recursive(ns,&a,&b)==-ENOMEM); test_fail_heap_after=-1; - assert(ns->next_id==id && ns->next_peer_id==group); + assert(vfs_mount_next_id()==id && ns->next_peer_id==group); assert(vfs_path_lookup(ns,root,root,"/slave-d/rec/child",0,&found)==-ENOENT); vfs_path_put(&a);vfs_path_put(&b); strcpy(user.source,"/slave-source");strcpy(user.target,"/slave-a/rec"); @@ -3467,7 +3471,7 @@ static void runtime_shared_move(struct vfs_namespace *ns,const struct vfs_path * assert(!vfs_path_lookup(ns,root,root,"/move-src/child",0,&child)); assert(!vfs_path_lookup(ns,root,root,"/move-a/slot",0,&target)); const uint64_t id=vfs_path_mount_id(&original),child_id=vfs_path_mount_id(&child); - const uint64_t next=ns->next_id,next_group=ns->next_peer_id; + const uint64_t next=vfs_mount_next_id(),next_group=ns->next_peer_id; strcpy(user.source,"/move-src"); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_UNBINDABLE,0)); strcpy(user.target,"/move-a/slot"); @@ -3479,7 +3483,7 @@ static void runtime_shared_move(struct vfs_namespace *ns,const struct vfs_path * test_fail_heap_after=5; assert(vfs_mount_move(ns,&original,&target)==-ENOMEM); test_fail_heap_after=-1; - assert(ns->next_id==next && ns->next_peer_id==next_group); + assert(vfs_mount_next_id()==next && ns->next_peer_id==next_group); assert(!fixture_shared_id(ns,root,"/move-src") && !fixture_shared_id(ns,root,"/move-src/child")); assert(fixture_mount_tag(ns,root,"/move-src"," master:")==upstream); assert(!vfs_path_lookup(ns,root,root,"/move-a/slot",0,&found) && vfs_path_equal(&found,&target)); @@ -3488,7 +3492,7 @@ static void runtime_shared_move(struct vfs_namespace *ns,const struct vfs_path * strcpy(user.target,"/move-a/slot"); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,UINT64_MAX,MS_MOVE,UINT64_MAX)); - assert(ns->next_id==next+6 && ns->next_peer_id==next_group+2); + assert(vfs_mount_next_id()==next+6 && ns->next_peer_id==next_group+2); assert(!vfs_path_lookup(ns,root,root,"/move-a/slot",0,&found)); assert(vfs_path_equal(&found,&original) && vfs_path_mount_id(&found)==id);vfs_path_put(&found); assert(!vfs_path_lookup(ns,root,root,"/move-a/slot/child",0,&found)); diff --git a/tools/tests/mount_tree_test.c b/tools/tests/mount_tree_test.c index f96c0378..559b3f67 100644 --- a/tools/tests/mount_tree_test.c +++ b/tools/tests/mount_tree_test.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -289,6 +290,113 @@ static void mount_failed_teardown(struct module *owner) assert(!context_release_owner->users && allocations==before && !vfs_reclaim_mounts(8)); puts("PASS failed detached backend cleanup pins actual module until bounded retry and final destroy"); } + +/** @brief Snapshot an exact covered graph and retire either view without losing its provider. + * @param owner Live fixture module supplying the covered child filesystem. + */ +static void namespace_snapshot_objects(struct module *owner) +{ + struct vfs_namespace source={0},copy={0},later={0}; + struct vfs_mount *base=mount_new(&a,NULL),*mount=NULL; + assert(!vfs_namespace_init(&source,base));vfs_mount_put(base); + struct vfs_path root={0};assert(!vfs_namespace_root(&source,&root)); + struct vfs_path slot=find(&source,&root,&root,"mnt",2); + mount=mount_new(&b,NULL); + assert(!vfs_mount_set_flags(mount,MS_NODEV|MS_NOATIME)); + assert(!vfs_mount_attach(&source,mount,&slot));vfs_mount_put(mount); + struct vfs_path lower=find(&source,&root,&root,"mnt",1); + struct vfs_path inner=find(&source,&root,&lower,"child",3); + struct vfs_path writer=find(&source,&root,&lower,"new",2); + assert(!vfs_path_write_get(&writer)); + + struct vfs_backend_ops owned=ops;owned.finish=finish_context;owned.destroy=release_context; + struct storage_node child_node=node(&c_entries[0]); + assert(!vfs_mount_new(&owned,&c,owner,&child_node,&mount)); + assert(!vfs_mount_attach(&source,mount,&inner));vfs_mount_put(mount); + struct vfs_path child=find(&source,&root,&lower,"child",1); + assert(!vfs_mount_set_propagation(&source,&child,MS_UNBINDABLE)); + + mount=mount_new(&a,NULL); + assert(!vfs_mount_attach(&source,mount,&lower));vfs_mount_put(mount); + struct vfs_path upper=find(&source,&root,&root,"mnt",1); + assert(vfs_path_context(&upper)==&a); + struct vfs_path other=find(&source,&root,&root,"other",3); + assert(!vfs_mount_set_propagation(&source,&lower,MS_SHARED)); + assert(!vfs_mount_bind(&source,&inner,&other)); + struct vfs_path slave=find(&source,&root,&root,"other",3); + assert(!vfs_mount_set_propagation(&source,&slave,MS_SLAVE)); + struct vfs_path task_root={0},cwd={0}; + vfs_path_get(&lower,&task_root);vfs_path_get(&inner,&cwd); + + const size_t before=allocations; + const uint64_t last=vfs_path_mount_id(&slave); + unsigned failed=0; + for(unsigned nth=1;nth<=16;++nth) { + fail_after=nth;allocation_attempts=0; + int rc=vfs_namespace_snapshot(©,&source,&task_root,&cwd); + fail_after=0; + if(!rc)break; + assert(rc==-ENOMEM && !copy.root && !copy.mounts && !copy.next_peer_id); + assert(vfs_path_equal(&task_root,&lower) && vfs_path_equal(&cwd,&inner)); + assert(allocations==before && context_release_owner->users==1);++failed; + } + assert(failed>=5 && vfs_path_namespace(&task_root)==© && vfs_path_namespace(&cwd)==©); + assert(task_root.mount==cwd.mount && task_root.mount!=lower.mount); + assert(task_root.dentry==lower.dentry && cwd.dentry==inner.dentry); + assert(vfs_path_mount_id(&task_root)>last && vfs_path_same_filesystem(&task_root,&lower)); + + struct vfs_path visible={0};assert(!vfs_namespace_root(©,&visible)); + assert(vfs_path_mount_id(&visible)==last+1); + struct vfs_path top=find(©,&visible,&visible,"mnt",1); + assert(vfs_path_same_inode(&top,&upper) && vfs_path_mount_id(&top)!=vfs_path_mount_id(&upper)); + struct vfs_path branch=find(©,&task_root,&task_root,"child",1); + assert(vfs_path_same_inode(&branch,&child)); + struct vfs_path parent=find(©,&task_root,&cwd,"..",1); + assert(vfs_path_equal(&parent,&task_root));vfs_path_put(&parent); + struct vfs_path bound=find(©,&visible,&visible,"other",3); + assert(vfs_path_same_inode(&bound,&cwd) && !vfs_path_equal(&bound,&cwd)); + assert(vfs_mount_bind(©,&branch,&bound)==-EINVAL); + assert(vfs_path_mount_flags(&task_root)==(MS_NODEV|MS_NOATIME)); + assert(!vfs_path_bind_remount(&task_root,MS_RDONLY)); + assert(vfs_path_mount_flags(&task_root)==(MS_RDONLY|MS_NOATIME)); + assert(vfs_path_mount_flags(&lower)==(MS_NODEV|MS_NOATIME)); + assert(vfs_namespace_snapshot(©,&source,NULL,NULL)==-EINVAL); + assert(vfs_namespace_snapshot(&later,&source,&visible,NULL)==-EXDEV && !later.root); + + char table[2048];uint32_t read=0; + assert(!vfs_read_mount_table(©,&visible,true,0,table,sizeof(table)-1,&read));table[read]=0; + assert(strstr(table,"/mnt ro,noatime shared:1 ") && strstr(table,"/other rw,nodev,noatime master:1 ")); + assert(strstr(table,"/mnt/child rw unbindable ")); + + /* A backend-only snapshot pin is not a busy reference to the original. */ + assert(!vfs_mount_unmount(&source,&upper));vfs_path_put(&upper); + struct vfs_path found=find(&source,&root,&root,"mnt",1); + assert(vfs_path_equal(&found,&lower));vfs_path_put(&found); + found=find(©,&visible,&visible,"mnt",1); + assert(vfs_path_equal(&found,&top));vfs_path_put(&found); + vfs_path_write_put(&writer);vfs_path_put(&writer); + + unsigned released=context_releases;finish_attempts=0;finish_failures=1; + assert(vfs_namespace_destroy(&source)==-EBUSY); + vfs_namespace_retire(&source); + assert(!source.root && !source.mounts && !vfs_path_namespace(&child) && !finish_attempts); + found=find(©,&visible,&child,"nested",2);vfs_path_put(&found); + found=find(©,&task_root,&task_root,"child/nested",2);vfs_path_put(&found); + assert(!vfs_namespace_snapshot(&later,©,NULL,&child)); + assert(!vfs_path_namespace(&child)); /* Already detached cwd stays on the old mount. */ + vfs_namespace_retire(&later);vfs_namespace_retire(©); + assert(!copy.root && !copy.mounts && !vfs_path_namespace(&branch) && !finish_attempts); + assert(vfs_path_context(&branch)==&c && vfs_path_node(&branch)->first_cluster==1); + vfs_path_put(&branch);vfs_path_put(&bound);vfs_path_put(&top);vfs_path_put(&visible); + vfs_path_put(&cwd);vfs_path_put(&task_root);vfs_path_put(&slave);vfs_path_put(&other); + vfs_path_put(&child);vfs_path_put(&inner);vfs_path_put(&lower);vfs_path_put(&slot);vfs_path_put(&root); + assert(!finish_attempts && context_releases==released && vfs_reclaim_pending()); + for(unsigned i=0;i<8 && vfs_reclaim_pending();++i)(void)vfs_reclaim_mounts(32); + assert(finish_attempts==2 && context_releases==released+1 && !vfs_reclaim_pending()); + assert(!context_release_owner->users);no_pins(&a);no_pins(&b);no_pins(&c); + puts("PASS mount namespace snapshot: covered task paths, independent policy and IDs, atomic rollback and deferred retirement"); +} + static unsigned pseudo_lookup_calls; static int owned_pseudo_lookup(const char *name,struct storage_node *out) { @@ -345,16 +453,21 @@ static void mount_table_objects(void) struct vfs_path child=find(&ns,&root,&inside,"child",3); mounted=mount_new(&c,NULL);assert(!vfs_mount_describe(mounted,"nested","testfs",0x110304)); assert(!vfs_mount_attach(&ns,mounted,&child));vfs_mount_put(mounted); + struct vfs_path moved=find(&ns,&root,&inside,"child",1); + const uint64_t root_id=vfs_path_mount_id(&root),inside_id=vfs_path_mount_id(&inside); + const uint64_t nested_id=vfs_path_mount_id(&moved); + char base_row[128],inside_row[128],nested_row[128]; + snprintf(base_row,sizeof(base_row),"%" PRIu64 " %" PRIu64 " 8:0 / / rw - testfs rootfs rw\n",root_id,root_id); + snprintf(inside_row,sizeof(inside_row),"%" PRIu64 " %" PRIu64 " 0:2 / /mnt rw - tmpfs a\\040b\\134c\\011d\\012e rw\n",inside_id,root_id); + snprintf(nested_row,sizeof(nested_row),"%" PRIu64 " %" PRIu64 " 259:260 / /mnt/child rw - testfs nested rw\n",nested_id,inside_id); char text[4096]={0},chunks[4096]={0};uint32_t count=0,got=0; char diagnostic[64]; assert(!vfs_namespace_context_mountpoint(&ns,&b,diagnostic,sizeof(diagnostic)) && !strcmp(diagnostic,"/mnt")); assert(!vfs_namespace_context_mountpoint(&ns,&c,diagnostic,sizeof(diagnostic)) && !strcmp(diagnostic,"/mnt/child")); assert(vfs_namespace_context_mountpoint(&ns,&ns,diagnostic,sizeof(diagnostic))==-ENOENT && !diagnostic[0]); assert(!vfs_read_mount_table(&ns,&root,true,0,text,sizeof(text)-1,&count));text[count]=0; - assert(strstr(text,"1 1 8:0 / / rw - testfs rootfs rw\n")); - assert(strstr(text,"2 1 0:2 / /mnt rw - tmpfs a\\040b\\134c\\011d\\012e rw\n")); - assert(strstr(text,"3 2 259:260 / /mnt/child rw - testfs nested rw\n")); - assert(strstr(text,"2 1 0:2 ")users);runtime->state=MODULE_LIVE; context_release_owner=runtime;mount_context_lifetime(&owner);mount_failed_teardown(&owner); pseudo_provider_lifetime(&owner); + namespace_snapshot_objects(&owner);assert(allocations==1); for(unsigned nth=1;nth<=2;++nth) { fail_after=nth;allocation_attempts=0; assert(vfs_mount_new(&ops,&b,&owner,&root_node,&unpublished)==-ENOMEM && !unpublished); diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index f2443a79..b5ff374b 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -351,6 +352,20 @@ static void test_proc_fd_object_link(void) assert(proc_fd_get_path(¤t,3,&target)==-RELIEFOS_ENOENT && !target.mount); puts("PASS proc FD magic target owns the anonymous file object without replaying display names"); } +/** @brief Assert one mountinfo record with IDs from the retained attachments. + * @param table NUL-terminated output from the proc mountinfo view. + * @param mount Retained proc attachment. @param parent Retained actual parent. + * @param point Expected mountpoint relative to the view's captured root. + */ +static void assert_proc_mount_row(const char *table,const struct vfs_path *mount, + const struct vfs_path *parent,const char *point) +{ + char expected[128]; + snprintf(expected,sizeof(expected),"%" PRIu64 " %" PRIu64 " 0:201 / %s rw - proc proc rw\n", + vfs_path_mount_id(mount),vfs_path_mount_id(parent),point); + assert(strstr(table,expected)); +} + static void test_proc_mount_objects(void) { static const struct vfs_backend_ops ops={.lookup=proc_path_lookup,.retain=proc_path_retain, @@ -380,7 +395,7 @@ static void test_proc_mount_objects(void) struct vfs_path mounts_view={0};char mount_text[512]; assert(!vfs_path_lookup(&ns,&root,&root,"/procdir/self/mountinfo",VFS_LOOKUP_FOLLOW,&mounts_view)); assert(!vfs_path_read(&mounts_view,0,mount_text,sizeof(mount_text)-1,&got));mount_text[got]=0; - assert(strstr(mount_text,"2 1 0:201 / /procdir rw - proc proc rw\n")); + assert_proc_mount_row(mount_text,&mounted,&root,"/procdir"); struct vfs_open_file *old_view=NULL,*new_view=NULL; unsigned open_baseline=proc_allocations; for(int budget=0;budget<3;++budget) { @@ -426,11 +441,11 @@ static void test_proc_mount_objects(void) assert(!vfs_path_lookup(&ns,&root,&old_process,"status",VFS_LOOKUP_FOLLOW,&old_status)); assert(!vfs_mount_move(&ns,&mounted,&destination)); assert(!vfs_path_read(&mounts_view,0,mount_text,sizeof(mount_text)-1,&got));mount_text[got]=0; - assert(strstr(mount_text,"2 1 0:201 / /else rw - proc proc rw\n") && !strstr(mount_text,"/procdir")); + assert_proc_mount_row(mount_text,&mounted,&root,"/else");assert(!strstr(mount_text,"/procdir")); assert(!vfs_file_read(old_view,0,mount_text,sizeof(mount_text)-1,&got));mount_text[got]=0; assert(strstr(mount_text,"/else rw - proc proc rw\n") && !strstr(mount_text,"/procdir")); assert(!vfs_file_read(new_view,0,mount_text,sizeof(mount_text)-1,&got));mount_text[got]=0; - assert(strstr(mount_text,"2 1 0:201 / / rw - proc proc rw\n")); + assert_proc_mount_row(mount_text,&mounted,&root,"/"); vfs_path_put(&mounts_view); const char *actual_executable="/else/sys/kernel/osrelease"; assert(proc_readlink("/proc/self/exe",bytes,sizeof(bytes))==(int)strlen(actual_executable) && @@ -451,7 +466,7 @@ static void test_proc_mount_objects(void) assert(!vfs_file_read(old_view,0,mount_text,sizeof(mount_text)-1,&got));mount_text[got]=0; assert(strstr(mount_text,"/else rw - proc proc rw\n")); assert(!vfs_file_read(new_view,0,mount_text,sizeof(mount_text)-1,&got));mount_text[got]=0; - assert(strstr(mount_text,"2 1 0:201 / / rw - proc proc rw\n")); + assert_proc_mount_row(mount_text,&mounted,&root,"/"); vfs_file_close(old_view);vfs_file_close(new_view); assert(!vfs_path_lookup(&ns,&root,&root,"/else/42",0,&target)); assert(!vfs_path_equal(&old_process,&target));vfs_path_put(&target); @@ -612,6 +627,7 @@ int main(void) } assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "oom_score") && entry.type == RELIEFOS_FS_TYPE_FILE); assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "oom_score_adj") && entry.type == RELIEFOS_FS_TYPE_FILE); + assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "cgroup") && entry.type == RELIEFOS_FS_TYPE_FILE); assert(proc_readdir("/proc/42", &offset, &entry) == 0); offset = 0; /* Anonymous descriptors must survive proc inode lookup during getdents. From a4e2d51ba3905e83909967bebebe6b0cca6cee7e Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 02:51:45 +0800 Subject: [PATCH 14/97] feat(vfs): retain mount namespaces in task filesystem state --- Documentation/core-api/mount-namespaces.rst | 32 +++++++-- .../LC_MESSAGES/core-api/mount-namespaces.po | 69 ++++++++++++++++--- .../LC_MESSAGES/core-api/mount-namespaces.po | 56 +++++++++++++-- fs/proc/procfs.c | 22 +++--- fs/vfs/mount_table.c | 6 +- fs/vfs/mount_tree.c | 33 +++++++++ fs/vfs/path.c | 11 +-- include/reliefnt/elf.h | 6 +- include/reliefnt/mount.h | 51 ++++++++++++-- include/reliefnt/syscall_internal.h | 24 +++++-- include/reliefnt/task/accessors.h | 21 ++++-- include/reliefnt/task/types.h | 2 + include/reliefnt/userland.h | 3 +- kernel/exec/elf.c | 17 +++-- kernel/exec/userland.c | 26 +++---- kernel/sched/clone.c | 4 +- kernel/sched/fs.c | 29 ++++---- kernel/sched/session.c | 4 +- kernel/syscall/dispatch.c | 51 +++++++------- kernel/syscall/event/inotify.c | 2 +- kernel/syscall/fs/filesystem.c | 4 +- kernel/syscall/fs/fs.c | 6 +- kernel/syscall/fs/legacy_filesystem.c | 6 +- kernel/syscall/fs/lookup_state.c | 10 +-- kernel/syscall/fs/mount.c | 4 ++ kernel/syscall/fs/path.c | 22 +++--- kernel/syscall/ipc/socket.c | 7 +- kernel/syscall/memory/swap_area.c | 2 +- kernel/syscall/process/exec.c | 5 +- kernel/syscall/process/legacy_process.c | 2 +- tools/test_memory_pressure_mincore_fix4.py | 2 +- tools/test_memory_pressure_open_path.py | 2 +- tools/test_memory_pressure_regular_read.py | 2 +- tools/tests/futimens_test.c | 9 ++- .../memory_pressure_fault_integration_test.c | 2 + .../tests/memory_pressure_mincore_fix4_test.c | 14 +++- tools/tests/memory_pressure_open_path_test.c | 7 +- .../tests/memory_pressure_regular_read_test.c | 13 ---- tools/tests/mount_backend_test.c | 16 +++-- tools/tests/mount_tree_test.c | 52 ++++++++++++++ tools/tests/procfs_directories_test.c | 37 +++++++++- tools/tests/rootfs_paths_test.c | 2 + tools/tests/swap_activation_test.c | 8 +-- tools/tests/sysv_shm_test.c | 39 ++++++----- tools/tests/task8_lookup_text_test.c | 1 + 45 files changed, 542 insertions(+), 201 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 1fdcb8c1..cfa698e3 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -13,7 +13,31 @@ 命名空间的路径返回 ``EXDEV``。所有分配完成后才发布新树并替换路径;失败时 不改变原树、目标、路径或 ID 游标。 -最后一个图使用者离开时,``vfs_namespace_retire()`` 摘除整棵树而不传播卸载。 -已持有的路径继续有效,后端由现有的延迟清理队列处理。与之不同,严格的 -``vfs_namespace_destroy()`` 在仍有外部引用时拒绝销毁。此接口用于内核内部; -当前没有向用户态开放挂载命名空间创建或切换。 +任务、路径查找与 proc 视图 +========================== + +任务文件系统状态同时持有挂载图、root 和 cwd。普通 fork 及 exec 准备态各自 +取得图引用;``CLONE_FS`` 共享同一份状态,最后一个共享者负责释放。打开文件等 +持有的普通路径只固定挂载对象和目录项,不延长图的寿命。 + +用户路径查找使用任务所属的图,而不是从 root 或可执行文件的挂载反推。系统 +调用重试状态在保存首个路径参数时持有该图,包括 ``open()`` 尚未建立路径遍历器 +就进入内存回收的情况。挂起的遍历器也持有自己的图;重试在原图中继续,不因调用 +方的文件系统状态变化而重新选图。shebang 和 ``PT_INTERP`` 同样按调用方的图 +查找解释器,即使可执行文件来自已摘除的挂载或继承的文件描述符。 + +打开 ``/proc//mounts`` 或 ``/proc//mountinfo`` 时,文件描述保存的是 +目标任务的图和查看根,不是读取者的图。后续读取仍反映所持图的当前状态,不需要 +重新查找 PID,因此目标退出后也可继续读取。若所持查看根已被延迟摘除,读取返回 +空列表;若传入属于其他活动图的查看根,渲染器返回 ``EXDEV``。 + +引用释放 +======== + +``vfs_namespace_clone()`` 返回一个受管理的图引用。最后一个图引用释放时, +``vfs_namespace_retire()`` 就地摘除整棵树而不传播卸载,随后释放图本身。已持有 +的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 +管理;严格的 ``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。 + +这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换,也未实现跨图 +peer/slave 传播或 ``mountinfo`` 的 ``propagate_from`` 字段。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index ada3a037..80063f78 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -46,14 +46,65 @@ msgstr "" "replacements are published only after all allocations succeed. Failure " "leaves the original tree, destination, paths, and ID cursor unchanged." +msgid "任务、路径查找与 proc 视图" +msgstr "Tasks, pathname lookup, and proc views" + +msgid "" +"任务文件系统状态同时持有挂载图、root 和 cwd。普通 fork 及 exec 准备态各自 取得图引用;``CLONE_FS`` " +"共享同一份状态,最后一个共享者负责释放。打开文件等 持有的普通路径只固定挂载对象和目录项,不延长图的寿命。" +msgstr "" +"Task filesystem state owns the mount graph, root, and cwd. An ordinary fork " +"and a prepared exec each take a graph reference. ``CLONE_FS`` shares the " +"whole state, which the last sharer releases. Ordinary held paths, such as " +"those in open files, pin only their mount and dentry and do not extend the " +"lifetime of the graph." + +msgid "" +"用户路径查找使用任务所属的图,而不是从 root 或可执行文件的挂载反推。系统 调用重试状态在保存首个路径参数时持有该图,包括 ``open()`` " +"尚未建立路径遍历器 就进入内存回收的情况。挂起的遍历器也持有自己的图;重试在原图中继续,不因调用 方的文件系统状态变化而重新选图。shebang 和 " +"``PT_INTERP`` 同样按调用方的图 查找解释器,即使可执行文件来自已摘除的挂载或继承的文件描述符。" +msgstr "" +"User pathname lookup uses the task’s graph rather than inferring it from the" +" mount of its root or executable. Syscall retry state holds the graph when " +"it saves the first pathname operand, including when ``open()`` enters memory" +" reclaim before it can create a walker. A suspended walker also owns a graph" +" reference. Retries continue in the original graph even if the caller’s " +"filesystem state changes. Shebang and ``PT_INTERP`` look up interpreters in " +"the caller’s graph, even if the executable came from a detached mount or an " +"inherited file descriptor." + +msgid "" +"打开 ``/proc//mounts`` 或 ``/proc//mountinfo`` 时,文件描述保存的是 " +"目标任务的图和查看根,不是读取者的图。后续读取仍反映所持图的当前状态,不需要 重新查找 " +"PID,因此目标退出后也可继续读取。若所持查看根已被延迟摘除,读取返回 空列表;若传入属于其他活动图的查看根,渲染器返回 ``EXDEV``。" +msgstr "" +"Opening ``/proc//mounts`` or ``/proc//mountinfo`` retains the " +"target task’s graph and viewing root, not the reader’s graph. Reads reflect " +"the current state of that graph and do not look up the PID again, so the " +"file remains readable after the target exits. A lazily detached viewing root" +" yields an empty listing. The renderer rejects a viewing root from a " +"different live graph with ``EXDEV``." + +msgid "引用释放" +msgstr "Reference release" + +msgid "" +"``vfs_namespace_clone()`` 返回一个受管理的图引用。最后一个图引用释放时, ``vfs_namespace_retire()``" +" 就地摘除整棵树而不传播卸载,随后释放图本身。已持有 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 " +"``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。" +msgstr "" +"``vfs_namespace_clone()`` returns one managed graph reference. On the last " +"put, ``vfs_namespace_retire()`` detaches the whole tree locally without " +"propagating unmounts, then the graph itself is freed. Held paths remain " +"valid and the existing deferred queue handles backend teardown. Callers " +"still own storage for boot and test graphs. The strict " +"``vfs_namespace_destroy()`` refuses to destroy a graph with outstanding " +"graph or external path references." + msgid "" -"最后一个图使用者离开时,``vfs_namespace_retire()`` 摘除整棵树而不传播卸载。 " -"已持有的路径继续有效,后端由现有的延迟清理队列处理。与之不同,严格的 ``vfs_namespace_destroy()`` " -"在仍有外部引用时拒绝销毁。此接口用于内核内部; 当前没有向用户态开放挂载命名空间创建或切换。" +"这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换,也未实现跨图 peer/slave 传播或 ``mountinfo`` 的 " +"``propagate_from`` 字段。" msgstr "" -"After the last graph user leaves, ``vfs_namespace_retire()`` detaches the" -" entire tree without propagating unmounts. Held paths remain valid and " -"the existing deferred queue handles backend teardown. The stricter " -"``vfs_namespace_destroy()`` instead rejects destruction while external " -"references remain. These are internal kernel interfaces; creation and " -"switching of mount namespaces are not yet exposed to userspace." +"These interfaces are internal to the kernel. Userspace cannot yet create or " +"switch mount namespaces. Cross-graph peer/slave propagation and the " +"``mountinfo`` field ``propagate_from`` are not implemented." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 64c58fae..c56d64d3 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -40,12 +40,54 @@ msgstr "" "を返します。すべての割り当てに成功してから、新しいツリーを公開しパスを差し替えます。失敗しても元のツリー、コピー先、パス、ID " "のカーソルは変わりません。" +msgid "任务、路径查找与 proc 视图" +msgstr "タスク、パス検索と proc のビュー" + +msgid "" +"任务文件系统状态同时持有挂载图、root 和 cwd。普通 fork 及 exec 准备态各自 取得图引用;``CLONE_FS`` " +"共享同一份状态,最后一个共享者负责释放。打开文件等 持有的普通路径只固定挂载对象和目录项,不延长图的寿命。" +msgstr "" +"タスクのファイルシステム状態は、マウントグラフと root、cwd を保持します。通常の fork と exec " +"の準備状態は、それぞれグラフの参照を取得します。 ``CLONE_FS`` " +"では状態全体を共有し、最後の共有者が解放します。開いているファイルなどが保持する通常のパスはマウントとディレクトリエントリだけを参照し、グラフの寿命を延ばしません。" + +msgid "" +"用户路径查找使用任务所属的图,而不是从 root 或可执行文件的挂载反推。系统 调用重试状态在保存首个路径参数时持有该图,包括 ``open()`` " +"尚未建立路径遍历器 就进入内存回收的情况。挂起的遍历器也持有自己的图;重试在原图中继续,不因调用 方的文件系统状态变化而重新选图。shebang 和 " +"``PT_INTERP`` 同样按调用方的图 查找解释器,即使可执行文件来自已摘除的挂载或继承的文件描述符。" +msgstr "" +"ユーザーのパス検索では、root " +"や実行ファイルのマウントから推定せず、タスクが属するグラフを使います。システムコールの再試行状態は、最初のパス引数を保存した時点でグラフを保持します。 " +"``open()`` " +"がパスの走査を開始する前にメモリ回収に入る場合も同様です。中断した走査もグラフの参照を保持します。呼び出し元のファイルシステム状態が変わっても、再試行は元のグラフで続きます。実行ファイルが切り離されたマウントや継承したファイル記述子に由来していても、shebang" +" と ``PT_INTERP`` のインタープリタは呼び出し元のグラフで検索します。" + +msgid "" +"打开 ``/proc//mounts`` 或 ``/proc//mountinfo`` 时,文件描述保存的是 " +"目标任务的图和查看根,不是读取者的图。后续读取仍反映所持图的当前状态,不需要 重新查找 " +"PID,因此目标退出后也可继续读取。若所持查看根已被延迟摘除,读取返回 空列表;若传入属于其他活动图的查看根,渲染器返回 ``EXDEV``。" +msgstr "" +"``/proc//mounts`` または ``/proc//mountinfo`` " +"を開くと、読み取り側ではなく、対象タスクのグラフと表示ルートを保持します。読み取りは保持したグラフの現在の状態を反映し、PID " +"を再検索しないため、対象が終了した後も読み取れます。表示ルートが遅延アンマウントで切り離された場合は空の一覧になります。別の稼働中のグラフに属する表示ルートには" +" ``EXDEV`` を返します。" + +msgid "引用释放" +msgstr "参照の解放" + +msgid "" +"``vfs_namespace_clone()`` 返回一个受管理的图引用。最后一个图引用释放时, ``vfs_namespace_retire()``" +" 就地摘除整棵树而不传播卸载,随后释放图本身。已持有 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 " +"``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。" +msgstr "" +"``vfs_namespace_clone()`` は管理対象グラフへの参照を一つ返します。最後の参照を解放すると、 " +"``vfs_namespace_retire()`` " +"がアンマウントを伝播させずにツリー全体を切り離し、その後グラフ自体を解放します。保持中のパスは有効なままで、既存の遅延処理キューがバックエンドを後処理します。起動時とテスト用のグラフの記憶領域は引き続き呼び出し側が管理します。厳格な" +" ``vfs_namespace_destroy()`` はグラフの参照や外部パス参照が残っている間は破棄を拒否します。" + msgid "" -"最后一个图使用者离开时,``vfs_namespace_retire()`` 摘除整棵树而不传播卸载。 " -"已持有的路径继续有效,后端由现有的延迟清理队列处理。与之不同,严格的 ``vfs_namespace_destroy()`` " -"在仍有外部引用时拒绝销毁。此接口用于内核内部; 当前没有向用户态开放挂载命名空间创建或切换。" +"这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换,也未实现跨图 peer/slave 传播或 ``mountinfo`` 的 " +"``propagate_from`` 字段。" msgstr "" -"グラフの最後の利用者が離れると、``vfs_namespace_retire()`` " -"はアンマウントを伝播させずにツリー全体を切り離します。保持中のパスは有効なままで、既存の遅延処理キューがバックエンドの後処理を行います。これに対し、厳格な" -" ``vfs_namespace_destroy()`` " -"は外部参照が残っている間は破棄を拒否します。これらはカーネル内部インターフェースであり、名前空間の作成と切り替えはまだユーザー空間に公開されていません。" +"これらはカーネル内部のインターフェースです。ユーザー空間からマウント名前空間を作成したり切り替えたりすることはまだできません。グラフ間の " +"peer/slave 伝播や、 ``mountinfo`` の ``propagate_from`` フィールドも未実装です。" diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 96e8f133..8b6aae4a 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -445,7 +445,7 @@ struct proc_open_view { * @param flags Sanitized status flags, borrowed and unchanged. * @param out Required owned output; legacy stateless files return NULL. * @return Zero or negative errno with empty output on failure. Mount views - * retain a root path; generated leaves and diagnostic readers capture bytes, + * retain the target's graph and root; generated leaves and diagnostics capture bytes, * while inotify controls retain a static key and read the current policy. * Namespace ownership outlives its retained paths; final release drops this * path even after task exit. Execution-owned, without graph locks across @@ -531,10 +531,11 @@ int proc_file_open(const char *name,uint32_t flags,void **out) return 0; } struct task *task=NULL;int view=proc_mount_view(name,&task);if(!view)return 0; - const struct vfs_path *root=&sched_task_paths(task)->root; - struct vfs_namespace *ns=vfs_path_namespace(root);if(!ns)return -RELIEFOS_ENOENT; + const struct task_fs_paths *paths=sched_task_paths(task); + if(!paths->ns || !vfs_path_node(&paths->root))return -RELIEFOS_ENOENT; struct proc_open_view *state=kernel_malloc(sizeof(*state));if(!state)return -RELIEFOS_ENOMEM; - *state=(struct proc_open_view){.ns=ns,.mountinfo=view==2};vfs_path_get(root,&state->root);*out=state;return 0; + *state=(struct proc_open_view){.ns=vfs_namespace_get(paths->ns),.mountinfo=view==2}; + vfs_path_get(&paths->root,&state->root);*out=state;return 0; } /** @brief Read a captured mount view, live control or diagnostic snapshot. @@ -584,8 +585,8 @@ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,ui /** @brief Release an open view after the final shared OFD reference. * @param value Owned optional captured state; NULL is ignored. - * @return None. Root/provider release can perform I/O; caller holds execution - * ownership without a graph, scheduler or module-table spinlock. + * Drops the retained viewing root and graph, even if the target already exited. + * Caller holds execution ownership without a graph, scheduler or module lock. */ void proc_file_close(void *value) { @@ -597,7 +598,7 @@ void proc_file_close(void *value) #endif kernel_free(state->text); vfs_path_put(&state->root); - kernel_free(state); + vfs_namespace_put(state->ns);kernel_free(state); } /** @brief Map scheduler states to Linux proc characters, never expose private enums. */ @@ -1089,10 +1090,9 @@ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, struct task *mount_task=NULL; int view=proc_mount_view(path,&mount_task); if(view) { - const struct vfs_path *root=&sched_task_paths(mount_task)->root; - struct vfs_namespace *ns=vfs_path_namespace(root); - if(!ns)return -RELIEFOS_ENOENT; - return vfs_read_mount_table(ns,root,view==2,offset,buffer,length,out_read); + const struct task_fs_paths *paths=sched_task_paths(mount_task); + if(!paths->ns || !vfs_path_node(&paths->root))return -RELIEFOS_ENOENT; + return vfs_read_mount_table(paths->ns,&paths->root,view==2,offset,buffer,length,out_read); } char content[PROCFS_CONTENT_MAX]; uint32_t len = 0; diff --git a/fs/vfs/mount_table.c b/fs/vfs/mount_table.c index d3d85d76..3a5fbd3d 100644 --- a/fs/vfs/mount_table.c +++ b/fs/vfs/mount_table.c @@ -140,7 +140,7 @@ static const struct vfs_mount *mount_successor(const struct vfs_namespace *ns, /** @brief Stream visible mounts with every visible parent before its children. * @param ns Required execution-owned namespace; graph mutation is serialized. - * @param root Retained viewing root; attachments outside it are omitted. + * @param root Retained viewing root; a lazily detached root renders no rows. * @param mountinfo True for mountinfo, false for escaped mntent records. * @param offset Byte offset into this live graph view. * @param buffer Output storage, nullable only when capacity is zero. @@ -156,7 +156,9 @@ int vfs_read_mount_table(const struct vfs_namespace *ns,const struct vfs_path *r { if(read)*read=0; if(!ns || !ns->root || !vfs_path_valid(root) || (!buffer && capacity))return -EINVAL; - if(root->mount->ns!=ns)return -EXDEV; + /* A held viewing root can be lazily detached. None of this graph's + * mounts are reachable below that root, so the listing is empty. */ + if(root->mount->ns!=ns)return root->mount->lazy_detached ? 0 : -EXDEV; if(!capacity)return 0; char *workspace=kernel_malloc(2*VFS_PATH_MAX);if(!workspace)return -ENOMEM; struct mount_text text={.offset=offset,.bytes=buffer,.capacity=capacity}; diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index afc36d49..23fc590a 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -528,6 +528,33 @@ int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace return 0; } +/** @brief Retire and free a heap-owned graph when its last reference is gone. + * @param ns Managed namespace with zero remaining references, execution-owned. + * Mounts and backends may outlive it through ordinary paths and deferred puts. + */ +static void vfs_namespace_release_snapshot(struct vfs_namespace *ns) +{ + vfs_namespace_retire(ns);kernel_free(ns); +} + +/** @brief Prepare a managed snapshot without exposing a partially copied graph. + * @param source Borrowed live source graph. @param root Optional owned root slot. + * @param cwd Optional owned cwd slot. @param out Required owned graph output. + * @return Zero or negative errno; publication transfers one graph reference. + * Paths are unchanged on failure. Requires VFS execution ownership. + */ +int vfs_namespace_clone(const struct vfs_namespace *source,struct vfs_path *root, + struct vfs_path *cwd,struct vfs_namespace **out) +{ + if(!out)return -EINVAL;*out=NULL; + struct vfs_namespace *ns=kernel_malloc(sizeof(*ns));if(!ns)return -ENOMEM; + *ns=(struct vfs_namespace){0}; + int rc=vfs_namespace_snapshot(ns,source,root,cwd); + if(rc){kernel_free(ns);return rc;} + ns->release=vfs_namespace_release_snapshot; + *out=vfs_namespace_get(ns);return 0; +} + /** @brief Test whether one connected dentry lies inside a directory view. * @param dentry Borrowed candidate. @param root Borrowed directory boundary. * @return True for the boundary itself or a descendant connected to it. @@ -1031,9 +1058,15 @@ void vfs_namespace_retire(struct vfs_namespace *ns) vfs_release_detached_mounts(mounts); } +/** @brief Destroy an externally owned graph only if no paths or users remain. + * @param ns Boot/fixture storage with stable address, under execution ownership. + * @return Zero, EINVAL for invalid storage, EBUSY for live references, or the + * provider's preflight error. Failure leaves the entire graph attached. + */ int vfs_namespace_destroy(struct vfs_namespace *ns) { if(!ns)return -EINVAL; + if(ns->references)return -EBUSY; /* Preflight the entire graph so a busy child cannot cause partial detach. */ for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { uint64_t expected=1; diff --git a/fs/vfs/path.c b/fs/vfs/path.c index 1057c881..e3aa0ef6 100644 --- a/fs/vfs/path.c +++ b/fs/vfs/path.c @@ -28,11 +28,11 @@ void vfs_walk_cancel(struct vfs_walk **state) struct vfs_walk *walk=*state;*state=NULL; kernel_free(walk->pending);kernel_free(walk->replacement); vfs_path_put(&walk->child);vfs_path_put(&walk->current);vfs_path_put(&walk->root); - kernel_free(walk); + vfs_namespace_put(walk->ns);kernel_free(walk); } /** @brief Own cursor text and paths before the first backend search/lookup. - * @param ns Borrowed execution-owned namespace. + * @param ns Borrowed execution-owned namespace; retained by the walk. * @param root Retained absolute lookup boundary, including detached roots. * @param start Retained cwd or dirfd; relative access survives lazy detach. * @param name Borrowed pathname. @param flags Validated lookup mode. @@ -50,9 +50,10 @@ static int vfs_walk_new(struct vfs_namespace *ns,const struct vfs_path *root, if(!length)return -ENOENT; struct vfs_walk *walk=kernel_malloc(sizeof(*walk)); if(!walk){return -ENOMEM;} - *walk=(struct vfs_walk){.ns=ns,.flags=flags}; + *walk=(struct vfs_walk){.flags=flags}; walk->pending=kernel_malloc(VFS_PATH_MAX); if(!walk->pending){kernel_free(walk);return -ENOMEM;} + walk->ns=vfs_namespace_get(ns); __builtin_memcpy(walk->pending,name,length+1); vfs_path_get(root,&walk->root);vfs_path_get(name[0]=='/' ? root : start,&walk->current); *state=walk;return 0; @@ -67,7 +68,7 @@ int vfs_path_resolve_resume(struct vfs_namespace *ns,const struct vfs_path *root *result=(struct vfs_lookup_result){0}; unsigned flags=policy ? policy->flags : VFS_LOOKUP_FOLLOW; int rc=flags&~(VFS_LOOKUP_FOLLOW|VFS_LOOKUP_PARENT|VFS_LOOKUP_MISSING|VFS_LOOKUP_STAT) ? -EINVAL : 0; - if(!rc && *state && ((*state)->ns!=ns || (*state)->flags!=flags))rc=-EINVAL; + if(!rc && *state && (*state)->flags!=flags)rc=-EINVAL; if(!rc && !*state)rc=vfs_walk_new(ns,root,start,name,flags,state); if(rc){vfs_walk_cancel(state);return rc;} struct vfs_walk *walk=*state;bool done=false; @@ -122,7 +123,7 @@ int vfs_path_resolve_resume(struct vfs_namespace *ns,const struct vfs_path *root result->trailing=walk->pending[walk->after]!=0;result->missing=true;rc=0;done=true;break; } if(rc)break; - vfs_follow_mounts(ns,&walk->child); + vfs_follow_mounts(walk->ns,&walk->child); if(walk->child.dentry->node.type==RELIEFOS_FS_TYPE_SYMLINK && (walk->pending[walk->after] || flags&VFS_LOOKUP_FOLLOW)) { if(++walk->links>VFS_SYMLINK_MAX){rc=-ELOOP;break;} diff --git a/include/reliefnt/elf.h b/include/reliefnt/elf.h index e1e225f7..53d5da2d 100644 --- a/include/reliefnt/elf.h +++ b/include/reliefnt/elf.h @@ -40,7 +40,9 @@ bool elf64_load_address_space(struct address_space *as, const void *image, size_ struct elf_image_info *out); /** * @brief Map an executable and PT_INTERP from retained filesystem objects. - * @param task Staged task owning its MM and actual root/cwd, required. + * @param task Staged task owning the new MM, required. + * @param lookup_task Task providing the graph, credentials and retry scope: + * the real exec caller, or the unpublished task for a delayed launch. * @param image Borrowed main executable path retaining its provider. * @param out Receives successful entry/auxiliary-vector metadata. * @return Zero or negative executable/provider/permission errno. Caller rolls @@ -48,6 +50,6 @@ bool elf64_load_address_space(struct address_space *as, const void *image, size_ * provider source. Execution/loader ownership is required; no graph/module * lock spans I/O. Interpreter operands survive active syscall retries. */ -int elf64_map_task_image(struct task *task, const struct vfs_path *image, +int elf64_map_task_image(struct task *task, struct task *lookup_task, const struct vfs_path *image, struct elf_image_info *out); #endif diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 10fb773b..a2ccabaf 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -189,12 +189,39 @@ bool vfs_path_same_inode(const struct vfs_path *left,const struct vfs_path *righ bool vfs_path_same_filesystem(const struct vfs_path *left,const struct vfs_path *right); /** @brief Borrow the shared namespace containing an owned path. * @param path Borrowed retained path, nullable; serialized task context. - * @return Namespace or NULL for an invalid path or detached mount. The - * caller must retain its path and may not persist the bare pointer. No I/O, + * @return Attachment membership, or NULL for an invalid or detached path. + * A path does not keep its graph alive; callers must not persist this pointer + * without taking a separate graph reference under execution ownership. No I/O, * graph traversal, locking or ownership transfer occurs. */ struct vfs_namespace *vfs_path_namespace(const struct vfs_path *path); -struct vfs_namespace {struct vfs_mount *root,*mounts;uint64_t next_peer_id;}; +/** @brief Mount graph plus its execution-owned lifetime, independent of paths. */ +struct vfs_namespace { + struct vfs_mount *root,*mounts; + uint64_t next_peer_id,references; + /* Only managed snapshots have a finalizer; boot/fixture storage is external. */ + void (*release)(struct vfs_namespace *ns); +}; + +/** @brief Retain a live graph while holding VFS execution ownership. + * @param ns Borrowed namespace whose owner guarantees liveness, or NULL. + * @return An owned graph reference, or NULL. Does not pin a specific path. + */ +static inline struct vfs_namespace *vfs_namespace_get(struct vfs_namespace *ns) +{ + if(ns)++ns->references; + return ns; +} + +/** @brief Drop one retained graph reference under VFS execution ownership. + * @param ns Owned reference, or NULL. The last managed reference retires + * the entire graph locally and frees it; caller-owned graphs are not freed. + * No scheduler or module lock may span a final put. + */ +static inline void vfs_namespace_put(struct vfs_namespace *ns) +{ + if(ns && !--ns->references && ns->release)ns->release(ns); +} /** @brief Assign immutable diagnostic identity before publishing a mount. * @param mount Owned detached mount, required; attachment returns EBUSY. * @param source Nonempty kernel source label, copied with PATH_MAX bounds. @@ -207,7 +234,8 @@ struct vfs_namespace {struct vfs_mount *root,*mounts;uint64_t next_peer_id;}; int vfs_mount_describe(struct vfs_mount *mount,const char *source,const char *filesystem,uint64_t device); /** @brief Render proc mounts/mountinfo from the actual referenced mount graph. * @param ns Borrowed execution-owned namespace, required. - * @param root Retained viewing root; mounts outside it are omitted. + * @param root Retained viewing root; mounts outside it are omitted. A lazily + * detached root has no rows; an unrelated live or unpublished root is EXDEV. * @param mountinfo True for mountinfo, false for mntent format. * @param offset Byte offset into this live view. * @param buffer Destination, nullable only for zero capacity. @@ -450,7 +478,8 @@ int vfs_path_resolve(struct vfs_namespace *ns,const struct vfs_path *root, const struct vfs_path *start,const char *name, const struct vfs_lookup_policy *policy,struct vfs_lookup_result *out); /** @brief Resolve or resume the same component walk across pre-I/O EAGAIN. - * @param ns Shared namespace under execution ownership. + * @param ns Initial namespace, borrowed and retained by a new walk. + * An existing walk ignores this argument and uses its own graph. * @param root Initial held task root, borrowed and retained by a new walk. * @param start Initial held cwd/dirfd, borrowed and retained as current position. * @param name Initial copied input; a resumed walk uses its own pending text. @@ -469,7 +498,7 @@ int vfs_path_resolve_resume(struct vfs_namespace *ns,const struct vfs_path *root const struct vfs_path *start,const char *name, const struct vfs_lookup_policy *policy,struct vfs_walk **state, struct vfs_lookup_result *out); -/** @brief Cancel one pending walk and release every retained object and buffer. +/** @brief Cancel one pending walk and release its graph, paths and buffers. * @param state Owned walk pointer, nullable; cleared before backend final puts. * Serialized task context without scheduler, graph or module-table locks. * Providers may perform I/O during final release; no caller input is retained. @@ -535,6 +564,16 @@ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root); */ int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace *source, struct vfs_path *root,struct vfs_path *cwd); +/** @brief Allocate and snapshot a graph whose lifetime is reference-counted. + * @param source Borrowed live source, serialized under VFS execution ownership. + * @param root Optional owned root to rebind by attachment/dentry identity. + * @param cwd Optional owned cwd to rebind by attachment/dentry identity. + * @param out Receives one owned namespace reference, NULL on failure. + * @return Zero or negative errno with both path slots unchanged on error. + * Release the result with vfs_namespace_put(), not retire or destroy. + */ +int vfs_namespace_clone(const struct vfs_namespace *source,struct vfs_path *root, + struct vfs_path *cwd,struct vfs_namespace **out); /** @brief Disconnect all mounts for last-owner namespace teardown. * @param ns Caller-owned namespace with no remaining graph users, or NULL. * Serialized VFS execution. Clears ns without propagating, checking busy diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index b1e0fc0f..6ab4e666 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -43,7 +43,7 @@ bool syscall_resume_parked(struct task *task); * @param task Current task under sole outer execution ownership. * @param frame Original syscall registers, borrowed only for this call. * @return Zero to retry, a blocked marker, or terminal ENOMEM. The scoped - * root/cwd references remain owned through waits and cancellation. + * graph and root/cwd references remain owned through waits and cancellation. */ int64_t syscall_open_path_reclaim(struct task *task, const struct trap_frame *frame); /** @brief Reclaim before a scalar regular read's unsubmitted output slice. @@ -105,7 +105,7 @@ int task_transfer_prepare_interrupt(struct task *task); * @param task Current task under execution ownership, nullable. * @param frame Borrowed current syscall registers, required with a task. * Matching number/arguments reset the operand cursor while retaining copied - * names and exact root/dirfd objects. A different call retires former operands. + * names, the graph and exact root/dirfd objects. A different call retires them. * Non-path calls allocate/pin nothing. No scheduler/module lock may span final * retirement callbacks; this function performs no new filesystem I/O. */ @@ -163,7 +163,7 @@ _Static_assert(METADATA_RESULT_STATFS < SOCKET_BATCH_META_KIND && * @param state Owned private scope, nullable; no stale MM pointer is followed. */ void task_process_vm_scope_release(void *state); -/** @brief Retire all copied lookup inputs and held directory objects once. +/** @brief Retire copied lookup inputs, held paths and the graph once. * @param task Owner under execution ownership, nullable; empty scopes are cheap. * Detaches state before releasing references, so signals, changed calls, exit * and final syscall return share one cleanup. Final backend puts may perform @@ -171,7 +171,7 @@ void task_process_vm_scope_release(void *state); */ void task_lookup_scope_cancel(struct task *task); /** @brief Resolve a kernel-owned at-path using actual task root/cwd/OFD objects. - * @param ns Shared live namespace under execution ownership. + * @param ns Initial live namespace under execution ownership; retained by a scope. * @param task Borrowed current task with initialized root/cwd references. * @param dirfd Linux descriptor or AT_FDCWD, ignored for absolute input. * @param raw Borrowed NUL-terminated kernel input, bounded by VFS_PATH_MAX. @@ -184,8 +184,8 @@ void task_lookup_scope_cancel(struct task *task); * the unresolved component and trailing-slash state. * @return Zero or negative errno with no references transferred on error. * Directory search checks run before consuming components, including dot-dot. - * An active syscall scope owns an independent input/root/dirfd snapshot across - * EAGAIN, retiring it through task_release_syscall_file on final return/cancel. + * An active syscall scope owns the graph and a snapshot of the input, root and + * starting path across EAGAIN; final return or cancellation releases them. * No pathname display cache or global text-prefix routing participates. */ int resolve_kernel_object_at_flags(struct vfs_namespace *ns,struct task *task,int32_t dirfd, @@ -307,6 +307,18 @@ struct task_file *task_file_for_io(struct task *task, int fd); #include +/** @brief Borrow the graph for current or resumed syscall pathname operations. + * @param task Execution-owned caller, or NULL. + * @return The retained scope graph, or the caller's filesystem graph before + * its first captured operand. A caller that cancels the scope must first pin + * the graph if it still needs it. No I/O or reference transfer occurs here. + */ +static inline struct vfs_namespace *task_lookup_namespace(const struct task *task) +{ + if(task && task->lookup_scope.ns)return task->lookup_scope.ns; + return sched_task_namespace(task); +} + /** * @brief Transfer regular-file or genuine block-node data, retaining progress across retries. * @param task Current task, with dispatcher-owned retry state. diff --git a/include/reliefnt/task/accessors.h b/include/reliefnt/task/accessors.h index 24b7cd56..61a898c1 100644 --- a/include/reliefnt/task/accessors.h +++ b/include/reliefnt/task/accessors.h @@ -196,18 +196,27 @@ static inline struct task_fs_paths *sched_task_paths(const struct task *task) return task->shared_fs ? &task->shared_fs->paths : (struct task_fs_paths *)&task->fs_paths; } -/** @brief Initialize a new unpublished task's root/cwd from the shared namespace. +/** @brief Borrow the task's graph without inferring membership from its paths. + * @param task Stable task under execution ownership, or NULL. + * @return Its filesystem state's namespace or NULL, without taking a reference. + */ +static inline struct vfs_namespace *sched_task_namespace(const struct task *task) +{ + return task ? sched_task_paths(task)->ns : NULL; +} + +/** @brief Initialize an unpublished task's graph and root/cwd. * @param task Fresh filesystem state under execution ownership. - * @param ns Published shared namespace; borrowed for this call. + * @param ns Published fallback namespace, retained unless state was inherited. * @return Zero, ENODEV before namespace publication, or EINVAL for partial * state. Fully initialized inherited state is preserved. No allocation/I/O; * may run while the scheduler excludes publication of the new task. */ int sched_task_fs_start(struct task *task,struct vfs_namespace *ns); -/** @brief Copy independent root/cwd references when creating an unshared task. +/** @brief Copy independent graph and path references when creating an unshared task. * @param task New task with private filesystem state under execution ownership. - * @param parent Stable source task whose root/cwd references are borrowed. + * @param parent Stable source task whose graph and path references are borrowed. * No allocation; new pins are acquired before any old destination pins drop. */ void sched_task_fs_inherit(struct task *task,const struct task *parent); @@ -219,10 +228,10 @@ void sched_task_fs_inherit(struct task *task,const struct task *parent); */ bool sched_task_fs_shared_outside_group(const struct task *task); -/** @brief Retire task root/cwd pins or its one shared CLONE_FS reference. +/** @brief Retire task graph/path pins or its one shared CLONE_FS reference. * @param task Quiescent task under execution ownership; nullable. * Clears ownership before final backend release, which may perform I/O. - * Only the final shared holder releases the underlying paths and state. + * Only the final shared holder releases the underlying graph, paths and state. */ void sched_task_fs_release(struct task *task); diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index 54e203bb..9e8f1dbe 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -339,6 +339,7 @@ struct task_fd_table_state { }; struct task_fs_paths { + struct vfs_namespace *ns; /* Owned independently of root/cwd attachment membership. */ struct vfs_path root,cwd; }; @@ -518,6 +519,7 @@ struct task_lookup_extra; struct task_lookup_scope { struct task_lookup_path paths[2]; struct task_lookup_extra *extra; + struct vfs_namespace *ns; /* Owned from the first retained pathname operand. */ uint64_t number,args[6]; uint64_t ioctl_deadline_us; /* Absolute deadline of a suspended driver wait. */ uint64_t ioctl_target_sequence; diff --git a/include/reliefnt/userland.h b/include/reliefnt/userland.h index 10577fb6..08e08fcb 100644 --- a/include/reliefnt/userland.h +++ b/include/reliefnt/userland.h @@ -41,7 +41,8 @@ void userland_process_exit(uint64_t code); * @param data Packed NUL-terminated argument and environment strings. * @param data_len Number of valid data bytes. * @return Zero on success, or negative errno with the old image intact. - * Caller owns execution; temporary MM/root/cwd references retire on failure. + * Caller owns execution; temporary MM and filesystem state retire on failure. + * Interpreter lookup uses the original task and its syscall retry scope. * Diagnostic names never reopen the image or authorize metadata callbacks. */ int userland_exec_current_path(const struct vfs_path *image,const char *execfn, diff --git a/kernel/exec/elf.c b/kernel/exec/elf.c index 7c472082..ec94ea1b 100644 --- a/kernel/exec/elf.c +++ b/kernel/exec/elf.c @@ -804,7 +804,8 @@ static int elf64_map_one(struct task *task, struct vfs_exec_source *source, /** * @brief Map ELF LOADs and resolve PT_INTERP through actual task paths. - * @param task Staged or unpublished task with owned MM/root/cwd state. + * @param task Staged or unpublished task owning the new MM. + * @param lookup_task Real exec syscall owner or the unpublished launch task. * @param image_path Borrowed main executable retaining its actual provider. * @param out Receives metadata only after every image is mapped successfully. * @return Zero or negative executable/provider/permission errno. Failure leaves @@ -813,7 +814,7 @@ static int elf64_map_one(struct task *task, struct vfs_exec_source *source, * syscall operands retain interpreter lookup/guards across EAGAIN; no graph or * module lock spans I/O. No diagnostic path or legacy text router is consulted. */ -int elf64_map_task_image(struct task *task, const struct vfs_path *image_path, +int elf64_map_task_image(struct task *task, struct task *lookup_task, const struct vfs_path *image_path, struct elf_image_info *out) { const void *image,*interp_image; @@ -825,7 +826,7 @@ int elf64_map_task_image(struct task *task, const struct vfs_path *image_path, uint64_t main_bias=0,interp_bias; bool entry_found=false; int ret; - if(!task || !image_path || !out)return -22; + if(!task || !lookup_task || !image_path || !out)return -22; ret=vfs_exec_source_open(image_path,&main_source); if(ret)return ret; const struct storage_node *node=vfs_exec_source_node(main_source); @@ -850,18 +851,16 @@ int elf64_map_task_image(struct task *task, const struct vfs_path *image_path, if(!main_info.interp[0]) { main_info.interpreter_entry=main_info.entry;*out=main_info;goto done; } - /* A staged exec task has no syscall scope. The actual caller retains the - * same pre-commit root/cwd plus entered components on I/O retries. */ - struct task *caller=sched_current_task(); - if(!caller || caller->kind!=TASK_KIND_USER)caller=task; - ret=resolve_kernel_object_at_flags(vfs_path_namespace(image_path),caller,LINUX_AT_FDCWD, + /* The executable may be a detached or inherited FD. Its attachment is + * not the lookup graph for the program's PT_INTERP path. */ + ret=resolve_kernel_object_at_flags(task_lookup_namespace(lookup_task),lookup_task,LINUX_AT_FDCWD, main_info.interp,false,false,VFS_LOOKUP_FOLLOW,&interpreter); if(ret)goto done; ret=fs_permissions_check_path(task,&interpreter.path,FS_ACCESS_EXEC,false); if(ret)goto done; if(fs_permissions_check_path(task,&interpreter.path,FS_ACCESS_READ,false)<0) sched_task_mm(task)->nondumpable=true; - ret=task_lookup_exec_guard(caller,&interpreter.path,&temporary); + ret=task_lookup_exec_guard(lookup_task,&interpreter.path,&temporary); if(ret)goto done; ret=vfs_exec_source_open(&interpreter.path,&interp_source); if(ret)goto done; diff --git a/kernel/exec/userland.c b/kernel/exec/userland.c index 3b5b7a16..dc6d1126 100644 --- a/kernel/exec/userland.c +++ b/kernel/exec/userland.c @@ -555,7 +555,7 @@ static int userland_prepare_exec_credentials(struct task *next, const struct tas /** @brief Map a pre-bound image and prepare the new MM's native entry stack. * @param task Prepared/unstarted task retaining its actual executable path. - * @param old Previous credential source, or NULL for first launch. + * @param old Exec syscall owner and previous credentials, or NULL for launch. * @param execfn Original AT_EXECFN string, or NULL for the diagnostic default. * @return Zero or negative load/metadata/entropy/stack errno. Caller owns the * execution transaction and loader serialization; pathname diagnostics never @@ -563,7 +563,7 @@ static int userland_prepare_exec_credentials(struct task *next, const struct tas * after final credentials are set. Failed staging keeps all arguments, paths * and MM references cleanup-owned before any started-task publication. */ -static int userland_load_task_image_locked(struct task *task, const struct task *old, const char *execfn) +static int userland_load_task_image_locked(struct task *task, struct task *old, const char *execfn) { struct elf_image_info loaded; @@ -601,7 +601,7 @@ static int userland_load_task_image_locked(struct task *task, const struct task if(!ret)sched_task_mm(task)->executable_denied_write=true; } if (ret < 0) return ret; - ret = elf64_map_task_image(task, image, &loaded); + ret = elf64_map_task_image(task, old ? old : task, image, &loaded); if (ret < 0) { console_error("[reliefnt] failed to map executable %s\n", task->name); return ret; @@ -693,7 +693,7 @@ static int userland_image_search(void *context,const struct vfs_path *directory) {return fs_permissions_check_path(context,directory,FS_ACCESS_EXEC,false);} /** @brief Bind an unpublished task to its actual authorized executable inode. - * @param task New task with owned root/cwd, stable under execution ownership. + * @param task New task with owned graph/root/cwd under execution ownership. * @param path Borrowed kernel pathname, needed only through this resolution. * @return Zero or lookup/type/DAC errno with the old binding intact on error. * Rebinding is only for an unstarted task before its MM acquired an inode. @@ -705,7 +705,7 @@ static int userland_bind_pending_image(struct task *task,const char *path) if(!task || !path || sched_task_mm(task)->executable_inode)return -22; struct vfs_lookup_result found={0};const struct task_fs_paths *paths=sched_task_paths(task); struct vfs_lookup_policy policy={.flags=VFS_LOOKUP_FOLLOW,.search=userland_image_search,.context=task}; - int rc=vfs_path_resolve(vfs_system_namespace(),&paths->root,&paths->cwd,path,&policy,&found); + int rc=vfs_path_resolve(paths->ns,&paths->root,&paths->cwd,path,&policy,&found); if(!rc && vfs_path_node(&found.path)->type!=RELIEFOS_FS_TYPE_FILE)rc=-13; if(!rc)rc=fs_permissions_check_path(task,&found.path,FS_ACCESS_EXEC,false); if(!rc) { @@ -729,9 +729,9 @@ static int userland_bind_pending_image(struct task *task,const char *path) * @param stdout_fd Parent output descriptor, or negative for default setup. * @param stderr_fd Parent error descriptor, or negative for default setup. * @param make_ready Nonzero to publish after all references/parameters attach. - * @return PID or negative errno. Requires the published shared namespace; - * initializes fresh root/cwd before publication without resetting inherited - * objects. Runnable publication checks the current cgroup PID quota. + * @return PID or negative errno. Uses inherited filesystem state or initializes + * a fresh graph/root/cwd from the published boot namespace before binding the + * image. Runnable publication checks the current cgroup PID quota. * Execution-owned task context; no scheduler lock spans backend I/O. */ static int64_t spawn_pending_image_ex(const char *path, const char *task_name, @@ -740,12 +740,10 @@ static int64_t spawn_pending_image_ex(const char *path, const char *task_name, int stdin_fd, int stdout_fd, int stderr_fd, int make_ready) { - struct vfs_namespace *namespace=vfs_system_namespace(); - if(!namespace)return -19; int64_t prepared = sched_create_user_task(task_name, 0, USER_STACK_TOP, parent, flags); if (prepared < 0) return prepared; uint32_t pid = (uint32_t)prepared; - int fs_ret=sched_task_fs_start(sched_find(pid),namespace); + int fs_ret=sched_task_fs_start(sched_find(pid),vfs_system_namespace()); if(fs_ret<0){sched_exit(pid,127);return fs_ret;} sched_set_task_path(pid, path); fs_ret=userland_bind_pending_image(sched_find(pid),path); @@ -1249,7 +1247,9 @@ int userland_exec_continue(struct task *task) * @param envp Kernel-owned envp pointers into data. * @param data Packed argument/environment storage copied from user memory. * @param data_len Number of valid data bytes. - * @return Zero after committing the new image, or a negative errno-style value with no change. + * @return Zero after committing the new image, or a negative errno with the + * old image intact. The prepared task owns an independent filesystem state; + * interpreter lookup uses the caller's graph and active retry scope. */ int userland_exec_current_path(const struct vfs_path *image,const char *execfn, uint32_t argc, char *const argv[], @@ -1280,7 +1280,7 @@ int userland_exec_current_path(const struct vfs_path *image,const char *execfn, const char *leaf=vfs_path_name(image); task_name_from_path(leaf && leaf[0] ? leaf : execfn,task_name,sizeof(task_name)); char display[RELIEFOS_FS_PATH_LEN]; - if(vfs_path_format_link(vfs_path_namespace(image),&sched_task_paths(task)->root,image,display,sizeof(display))) + if(vfs_path_format_link(task_lookup_namespace(task),&sched_task_paths(task)->root,image,display,sizeof(display))) copy_text(display,sizeof(display),execfn); prepared = kernel_malloc(sizeof(*prepared)); if (!prepared) return -12; diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index f1c220ac..24c075bf 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -56,8 +56,8 @@ static int task_promote_shared(struct task *task, uint64_t flags) fs->umask = *sched_task_umask(task); for (unsigned i = 0; i < sizeof(fs->cwd); ++i) fs->cwd[i] = sched_task_cwd(task)[i]; task_copy_identity_text(fs->root_dir, sizeof(fs->root_dir), sched_task_root(task)); - /* Transfer the two owned paths to the shared state, without a second - * self-reference or a stale inline owner after CLONE_FS promotion. */ + /* Transfer the owned graph and both paths, without an extra reference + * or a stale inline owner after CLONE_FS promotion. */ fs->paths=task->fs_paths; task->fs_paths=(struct task_fs_paths){0}; fs->references = 1; diff --git a/kernel/sched/fs.c b/kernel/sched/fs.c index 1a02a355..3f0e37e4 100644 --- a/kernel/sched/fs.c +++ b/kernel/sched/fs.c @@ -1,37 +1,38 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "internal.h" -/** @brief Attach initial shared-namespace root/cwd to an unpublished task. +/** @brief Attach the fallback graph and root/cwd to an unpublished task. * @param task New task under execution ownership, not yet runnable. - * @param ns Published namespace, borrowed and never retained as a bare pointer. - * @return Zero, EINVAL for partial state or ENODEV without a namespace. Existing - * fully inherited paths remain unchanged. Only mount/dentry reference counts - * change: no allocation, I/O, provider callback or scheduler-lock inversion. + * @param ns Borrowed published namespace, retained for fresh state only. + * @return Zero, EINVAL for partial state or ENODEV without a namespace. Fully + * inherited state remains unchanged. No allocation or filesystem I/O. */ int sched_task_fs_start(struct task *task,struct vfs_namespace *ns) { if(!task)return -22; struct task_fs_paths *paths=sched_task_paths(task); bool root=vfs_path_node(&paths->root)!=NULL,cwd=vfs_path_node(&paths->cwd)!=NULL; - if(root && cwd)return 0; - if(root || cwd)return -22; + if(root && cwd && paths->ns)return 0; + if(root || cwd || paths->ns)return -22; if(!ns || !ns->root)return -19; struct vfs_path initial={0};int rc=vfs_namespace_root(ns,&initial);if(rc)return rc; + paths->ns=vfs_namespace_get(ns); paths->root=initial;vfs_path_get(&initial,&paths->cwd);return 0; } -/** @brief Retain independent root/cwd objects, including covered or removed dirs. +/** @brief Retain a graph and exact root/cwd, including covered or detached paths. * @param task New task with private filesystem state; execution-owned. * @param parent Stable source task, borrowed, including shared CLONE_FS state. - * Acquires both pins before releasing old destination handles. No allocation; + * Acquires all references before releasing old destination handles. No allocation; * source lifetime remains independent of child creation or later rollback. */ void sched_task_fs_inherit(struct task *task,const struct task *parent) { struct task_fs_paths next={0},*source=sched_task_paths(parent),*target=sched_task_paths(task); + next.ns=vfs_namespace_get(source->ns); vfs_path_get(&source->root,&next.root);vfs_path_get(&source->cwd,&next.cwd); struct task_fs_paths old=*target;*target=next; - vfs_path_put(&old.root);vfs_path_put(&old.cwd); + vfs_path_put(&old.root);vfs_path_put(&old.cwd);vfs_namespace_put(old.ns); } /** @brief Check whether a separate process can change a task's CLONE_FS state. @@ -53,10 +54,10 @@ bool sched_task_fs_shared_outside_group(const struct task *task) return false; } -/** @brief Release the task's root/cwd ownership exactly once, honoring CLONE_FS. +/** @brief Release the task's graph and path ownership, honoring CLONE_FS. * @param task Quiescent task under execution ownership, or NULL. - * Detaches state before dropping final backend paths, which may perform I/O. - * Nonfinal shared holders only drop their state reference; no paths are freed. + * Detaches state before final path and graph puts, which may perform I/O. + * Nonfinal shared holders drop only their shared state reference. */ void sched_task_fs_release(struct task *task) { @@ -65,6 +66,6 @@ void sched_task_fs_release(struct task *task) if(shared && __atomic_sub_fetch(&shared->references,1,__ATOMIC_SEQ_CST))return; struct task_fs_paths *paths=shared ? &shared->paths : &task->fs_paths; struct task_fs_paths old=*paths;*paths=(struct task_fs_paths){0}; - vfs_path_put(&old.root);vfs_path_put(&old.cwd); + vfs_path_put(&old.root);vfs_path_put(&old.cwd);vfs_namespace_put(old.ns); if(shared)kernel_free(shared); } diff --git a/kernel/sched/session.c b/kernel/sched/session.c index 0161eaed..ebfd6287 100644 --- a/kernel/sched/session.c +++ b/kernel/sched/session.c @@ -49,10 +49,10 @@ void task_clear_identity(struct task *task) } /** - * @brief Inherit identity and independent held root/cwd paths from a parent. + * @brief Inherit identity and independent filesystem references from a parent. * @param task New task with private filesystem state under execution ownership. * @param parent Stable source task; NULL leaves the destination unchanged. - * Retains group and mount/dentry references, without allocating or resolving + * Retains group, namespace and mount/dentry references without allocating or resolving * cached path strings. Caller serializes task publication with scheduler_lock. */ void task_copy_identity_from_parent(struct task *task, const struct task *parent) diff --git a/kernel/syscall/dispatch.c b/kernel/syscall/dispatch.c index 11f6b1d7..b3e5a5a3 100644 --- a/kernel/syscall/dispatch.c +++ b/kernel/syscall/dispatch.c @@ -552,20 +552,21 @@ int64_t syscall_dispatch_regs_legacy(uint64_t number, uint64_t a0, uint64_t a1, return syscall_fallocate_object(sched_current_task(), (int32_t)a0, (uint32_t)a1, a2, a3); if (number == LINUX_SYS_SYNC_FILE_RANGE) return syscall_legacy_filesystem(number, a0, a1, a2, a3, a4, a5); + struct task *actor = sched_current_task(); if (number == LINUX_SYS_SYNC) - return syscall_sync_object(vfs_system_namespace(), sched_current_task(), number, (int32_t)a0); + return syscall_sync_object(vfs_system_namespace(), actor, number, (int32_t)a0); if (number == LINUX_SYS_SYNCFS) - return syscall_sync_object(vfs_system_namespace(), sched_current_task(), number, (int32_t)a0); + return syscall_sync_object(task_lookup_namespace(actor), actor, number, (int32_t)a0); if (number == LINUX_SYS_FCHMODAT || number == LINUX_SYS_FCHMODAT2 || number == LINUX_SYS_FCHOWNAT || number == LINUX_SYS_FACCESSAT || number == LINUX_SYS_FACCESSAT2) - return syscall_permissions(vfs_system_namespace(), sched_current_task(), number, a0, a1, a2, a3, a4); + return syscall_permissions(task_lookup_namespace(actor), actor, number, a0, a1, a2, a3, a4); if (number == LINUX_SYS_GETGROUPS || number == LINUX_SYS_SETGROUPS) return syscall_legacy_filesystem(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_CHMOD || number == LINUX_SYS_CHOWN || number == LINUX_SYS_LCHOWN) - return syscall_permissions(vfs_system_namespace(), sched_current_task(), number, a0, a1, a2, a3, a4); + return syscall_permissions(task_lookup_namespace(actor), actor, number, a0, a1, a2, a3, a4); if (number == LINUX_SYS_FCHMOD || number == LINUX_SYS_FCHOWN) - return syscall_permissions(vfs_system_namespace(), sched_current_task(), number, a0, a1, a2, a3, a4); + return syscall_permissions(task_lookup_namespace(actor), actor, number, a0, a1, a2, a3, a4); if (number == LINUX_SYS_WRITE) return syscall_legacy_io(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_READ) @@ -583,15 +584,15 @@ int64_t syscall_dispatch_regs_legacy(uint64_t number, uint64_t a0, uint64_t a1, uint32_t type=mode&LINUX_S_IFMT;if(!type)type=LINUX_S_IFREG; if(type!=LINUX_S_IFREG && type!=LINUX_S_IFIFO && type!=LINUX_S_IFSOCK) return type==LINUX_S_IFCHR || type==LINUX_S_IFBLK ? -RELIEFOS_EOPNOTSUPP : -RELIEFOS_EINVAL; - return syscall_create_object(vfs_system_namespace(),sched_current_task(), + return syscall_create_object(task_lookup_namespace(actor), actor, number==__NR_mknodat ? (int32_t)a0 : LINUX_AT_FDCWD, number==__NR_mknodat ? a1 : a0,type,mode,NULL); } if (number == LINUX_SYS_CREAT) - return syscall_open_object(vfs_system_namespace(), sched_current_task(), LINUX_AT_FDCWD, + return syscall_open_object(task_lookup_namespace(actor), actor, LINUX_AT_FDCWD, a0, LINUX_O_CREAT | LINUX_O_WRONLY | LINUX_O_TRUNC, a1); if (number == LINUX_SYS_OPEN || number == LINUX_SYS_OPENAT) - return syscall_open_object(vfs_system_namespace(), sched_current_task(), + return syscall_open_object(task_lookup_namespace(actor), actor, number == LINUX_SYS_OPENAT ? (int32_t)a0 : LINUX_AT_FDCWD, number == LINUX_SYS_OPENAT ? a1 : a0, number == LINUX_SYS_OPENAT ? a2 : a1, @@ -603,7 +604,7 @@ int64_t syscall_dispatch_regs_legacy(uint64_t number, uint64_t a0, uint64_t a1, if (number == LINUX_SYS_CLOSE) return syscall_legacy_descriptors(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_FTRUNCATE) - return syscall_truncate_object(vfs_system_namespace(), sched_current_task(), number, a0, a1); + return syscall_truncate_object(task_lookup_namespace(actor), actor, number, a0, a1); if (number == LINUX_SYS_DUP3) return syscall_legacy_descriptors(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_DUP || number == LINUX_SYS_DUP2 || number == LINUX_SYS_FCNTL) @@ -611,42 +612,42 @@ int64_t syscall_dispatch_regs_legacy(uint64_t number, uint64_t a0, uint64_t a1, if (number == LINUX_SYS_FLOCK) return syscall_legacy_descriptors(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_STATFS || number == LINUX_SYS_FSTATFS) - return syscall_metadata(vfs_system_namespace(), sched_current_task(), number, a0, a1, a2, a3, a4); + return syscall_metadata(task_lookup_namespace(actor), actor, number, a0, a1, a2, a3, a4); if (number == LINUX_SYS_STAT || number == LINUX_SYS_LSTAT || number == LINUX_SYS_NEWFSTATAT) - return syscall_metadata(vfs_system_namespace(), sched_current_task(), number, a0, a1, a2, a3, a4); + return syscall_metadata(task_lookup_namespace(actor), actor, number, a0, a1, a2, a3, a4); if (number == LINUX_SYS_STATX) - return syscall_metadata(vfs_system_namespace(), sched_current_task(), number, a0, a1, a2, a3, a4); + return syscall_metadata(task_lookup_namespace(actor), actor, number, a0, a1, a2, a3, a4); if (number == LINUX_SYS_SENDFILE) return syscall_legacy_io(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_COPY_FILE_RANGE) return syscall_legacy_io(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_FSTAT) - return syscall_metadata(vfs_system_namespace(), sched_current_task(), number, a0, a1, a2, a3, a4); + return syscall_metadata(task_lookup_namespace(actor), actor, number, a0, a1, a2, a3, a4); if (number == LINUX_SYS_ACCESS) - return syscall_permissions(vfs_system_namespace(), sched_current_task(), number, a0, a1, a2, a3, a4); + return syscall_permissions(task_lookup_namespace(actor), actor, number, a0, a1, a2, a3, a4); if (number == LINUX_SYS_SYMLINK || number == LINUX_SYS_SYMLINKAT) - return syscall_symlink_object(vfs_system_namespace(),sched_current_task(),a0, + return syscall_symlink_object(task_lookup_namespace(actor), actor,a0, number==LINUX_SYS_SYMLINKAT ? (int32_t)a1 : LINUX_AT_FDCWD, number==LINUX_SYS_SYMLINKAT ? a2 : a1); if (number == LINUX_SYS_LINK || number == LINUX_SYS_LINKAT) - return syscall_link_object(vfs_system_namespace(),sched_current_task(), + return syscall_link_object(task_lookup_namespace(actor), actor, number==LINUX_SYS_LINK ? LINUX_AT_FDCWD : (int32_t)a0, number==LINUX_SYS_LINK ? a0 : a1, number==LINUX_SYS_LINK ? LINUX_AT_FDCWD : (int32_t)a2, number==LINUX_SYS_LINK ? a1 : a3, number==LINUX_SYS_LINKAT ? (uint32_t)a4 : 0); if (number == LINUX_SYS_READLINK || number == LINUX_SYS_READLINKAT) - return syscall_readlink_object(vfs_system_namespace(), sched_current_task(), + return syscall_readlink_object(task_lookup_namespace(actor), actor, number == LINUX_SYS_READLINKAT ? (int32_t)a0 : LINUX_AT_FDCWD, number == LINUX_SYS_READLINKAT ? a1 : a0, number == LINUX_SYS_READLINKAT ? a2 : a1, (int32_t)(number == LINUX_SYS_READLINKAT ? a3 : a2), number == LINUX_SYS_READLINKAT); if (number == LINUX_SYS_FCHDIR) - return syscall_directory(vfs_system_namespace(), sched_current_task(), number, a0, a1); + return syscall_directory(task_lookup_namespace(actor), actor, number, a0, a1); if (number == LINUX_SYS_TRUNCATE) - return syscall_truncate_object(vfs_system_namespace(), sched_current_task(), number, a0, a1); + return syscall_truncate_object(task_lookup_namespace(actor), actor, number, a0, a1); if (number == LINUX_SYS_FSYNC || number == LINUX_SYS_FDATASYNC) - return syscall_sync_object(vfs_system_namespace(), sched_current_task(), number, (int32_t)a0); + return syscall_sync_object(task_lookup_namespace(actor), actor, number, (int32_t)a0); if (number == LINUX_SYS_UMASK) return syscall_legacy_filesystem(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_PREAD64 || number == LINUX_SYS_PWRITE64) @@ -666,23 +667,23 @@ int64_t syscall_dispatch_regs_legacy(uint64_t number, uint64_t a0, uint64_t a1, if (number == LINUX_SYS_LSEEK) return syscall_legacy_io(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_GETCWD) - return syscall_directory(vfs_system_namespace(), sched_current_task(), number, a0, a1); + return syscall_directory(task_lookup_namespace(actor), actor, number, a0, a1); if (number == LINUX_SYS_CHDIR || number == LINUX_SYS_CHROOT) - return syscall_directory(vfs_system_namespace(), sched_current_task(), number, a0, a1); + return syscall_directory(task_lookup_namespace(actor), actor, number, a0, a1); if (number == LINUX_SYS_MKDIR || number == LINUX_SYS_MKDIRAT) - return syscall_create_object(vfs_system_namespace(),sched_current_task(), + return syscall_create_object(task_lookup_namespace(actor), actor, number==LINUX_SYS_MKDIRAT ? (int32_t)a0 : LINUX_AT_FDCWD, number==LINUX_SYS_MKDIRAT ? a1 : a0,LINUX_S_IFDIR, (uint32_t)(number==LINUX_SYS_MKDIRAT ? a2 : a1),NULL); if (number == LINUX_SYS_UNLINK || number == LINUX_SYS_RMDIR || number == LINUX_SYS_UNLINKAT) { if(number==LINUX_SYS_UNLINKAT && ((uint32_t)a2&~LINUX_AT_REMOVEDIR))return -RELIEFOS_EINVAL; - return syscall_remove_object(vfs_system_namespace(),sched_current_task(), + return syscall_remove_object(task_lookup_namespace(actor), actor, number==LINUX_SYS_UNLINKAT ? (int32_t)a0 : LINUX_AT_FDCWD, number==LINUX_SYS_UNLINKAT ? a1 : a0, number==LINUX_SYS_RMDIR || (number==LINUX_SYS_UNLINKAT && ((uint32_t)a2&LINUX_AT_REMOVEDIR))); } if (number == LINUX_SYS_RENAME || number == LINUX_SYS_RENAMEAT || number == LINUX_SYS_RENAMEAT2) - return syscall_rename_object(vfs_system_namespace(),sched_current_task(), + return syscall_rename_object(task_lookup_namespace(actor), actor, number==LINUX_SYS_RENAME ? LINUX_AT_FDCWD : (int32_t)a0, number==LINUX_SYS_RENAME ? a0 : a1, number==LINUX_SYS_RENAME ? LINUX_AT_FDCWD : (int32_t)a2, diff --git a/kernel/syscall/event/inotify.c b/kernel/syscall/event/inotify.c index 89a81869..e7ff5536 100644 --- a/kernel/syscall/event/inotify.c +++ b/kernel/syscall/event/inotify.c @@ -74,7 +74,7 @@ int64_t syscall_inotify_add_watch(int fd, uint64_t pathname, uint32_t mask) return -RELIEFOS_EINVAL; rc = inotify_instance_for_fd(task, fd, &instance); if (rc) return rc; - rc = resolve_user_object_at_flags(vfs_system_namespace(), task, LINUX_AT_FDCWD, + rc = resolve_user_object_at_flags(task_lookup_namespace(task), task, LINUX_AT_FDCWD, pathname, false, false, mask & IN_DONT_FOLLOW ? 0 : VFS_LOOKUP_FOLLOW, &found); if (rc) return rc; const struct storage_node *node = vfs_path_node(&found.path); diff --git a/kernel/syscall/fs/filesystem.c b/kernel/syscall/fs/filesystem.c index 232df90a..2286c5cb 100644 --- a/kernel/syscall/fs/filesystem.c +++ b/kernel/syscall/fs/filesystem.c @@ -82,9 +82,9 @@ int64_t syscall_update_path_times(struct task *task, int32_t dirfd, uint64_t pat if (flags) return -RELIEFOS_EINVAL; struct task_file *file = task_file_for_io(task, dirfd); if (!file || (file->flags & TASK_FILE_FLAG_PATH)) return -RELIEFOS_EBADF; - ret=resolve_kernel_object_at_flags(vfs_system_namespace(),task,dirfd,"",true,false,0,&found); + ret=resolve_kernel_object_at_flags(task_lookup_namespace(task), task,dirfd,"",true,false,0,&found); } else { - ret=resolve_user_object_at_flags(vfs_system_namespace(),task,dirfd,path_ptr, + ret=resolve_user_object_at_flags(task_lookup_namespace(task), task,dirfd,path_ptr, (flags&LINUX_AT_EMPTY_PATH)!=0,false,flags&LINUX_AT_SYMLINK_NOFOLLOW ? 0 : VFS_LOOKUP_FOLLOW,&found); } if (ret < 0) return ret; diff --git a/kernel/syscall/fs/fs.c b/kernel/syscall/fs/fs.c index 39048197..220aa596 100644 --- a/kernel/syscall/fs/fs.c +++ b/kernel/syscall/fs/fs.c @@ -74,7 +74,9 @@ int syscall_fs_owns(uint64_t number) int64_t syscall_fs_dispatch(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) { - if (number >= __NR_setxattr && number <= __NR_fremovexattr) - return syscall_xattr(vfs_system_namespace(), sched_current_task(), number, a0, a1, a2, a3, a4); + if (number >= __NR_setxattr && number <= __NR_fremovexattr) { + struct task *task = sched_current_task(); + return syscall_xattr(task_lookup_namespace(task), task, number, a0, a1, a2, a3, a4); + } return syscall_dispatch_regs_legacy(number, a0, a1, a2, a3, a4, a5); } diff --git a/kernel/syscall/fs/legacy_filesystem.c b/kernel/syscall/fs/legacy_filesystem.c index 19c21f68..34265c6d 100644 --- a/kernel/syscall/fs/legacy_filesystem.c +++ b/kernel/syscall/fs/legacy_filesystem.c @@ -98,8 +98,10 @@ int64_t syscall_legacy_filesystem(uint64_t number, uint64_t a0, uint64_t a1, uin return old; } - if(number==LINUX_SYS_MOUNT || number==LINUX_SYS_UMOUNT2) - return syscall_mount_control(vfs_system_namespace(),sched_current_task(),number,a0,a1,a2,a3,a4); + if(number==LINUX_SYS_MOUNT || number==LINUX_SYS_UMOUNT2) { + struct task *task=sched_current_task(); + return syscall_mount_control(task_lookup_namespace(task),task,number,a0,a1,a2,a3,a4); + } return -RELIEFOS_ENOSYS; } diff --git a/kernel/syscall/fs/lookup_state.c b/kernel/syscall/fs/lookup_state.c index 2544f86b..ad324148 100644 --- a/kernel/syscall/fs/lookup_state.c +++ b/kernel/syscall/fs/lookup_state.c @@ -102,7 +102,7 @@ static void lookup_path_release(struct task_lookup_path *path) vfs_path_put(&path->root);vfs_path_put(&path->start); } -/** @brief Cancel task-owned path snapshots before any final backend release. +/** @brief Cancel task-owned lookup snapshots and release the retained graph. * @param task Owner under execution ownership, nullable. * An empty scope performs no work. Detaches the entire list first so nested * cleanup cannot release it twice. Removes a parked wait and drains owned @@ -138,6 +138,7 @@ void task_lookup_scope_cancel(struct task *task) struct task_lookup_extra *entry=old.extra;old.extra=entry->next; lookup_path_release(&entry->path);kernel_free(entry); } + vfs_namespace_put(old.ns); } /** @brief Match a retry's original registers or start a fresh lookup scope. @@ -270,8 +271,8 @@ int task_lookup_exec_guard(struct task *task,const struct vfs_path *path, * @param task Current scoped open caller. @param saved Its first lookup slot. * @param user_ptr Original pathname operand. @param kind Expected import kind. * @return True only for open or openat(AT_FDCWD) before any pathname copy, - * lookup, provider callback or side effect. Existing paths remain task-owned - * across waits and are released by common lookup cancellation. + * lookup, provider callback or side effect. The graph and paths are scope-owned + * across waits and released by common lookup cancellation. */ static bool open_import_pin_paths(struct task *task,struct task_lookup_path *saved, uint64_t user_ptr,uint32_t kind) @@ -290,7 +291,8 @@ static bool open_import_pin_paths(struct task *task,struct task_lookup_path *sav if(saved->root.mount || saved->start.mount) return saved->flags==kind && saved->root.mount && saved->start.mount; struct task_fs_paths *paths=sched_task_paths(task); - if(!vfs_path_node(&paths->root) || !vfs_path_node(&paths->cwd))return false; + if(!paths->ns || !vfs_path_node(&paths->root) || !vfs_path_node(&paths->cwd))return false; + scope->ns=vfs_namespace_get(paths->ns); vfs_path_get(&paths->root,&saved->root);vfs_path_get(&paths->cwd,&saved->start); saved->flags=kind;saved->dirfd=LINUX_AT_FDCWD; return saved->root.mount && saved->start.mount; diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index b2b58db2..5df5259a 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -66,8 +66,12 @@ static int mount_unmount(struct vfs_namespace *ns,struct task *task,uint64_t tar flags&UMOUNT_NOFOLLOW ? 0 : VFS_LOOKUP_FOLLOW,&found); if(!rc && !(flags&MNT_DETACH))rc=vfs_path_sync(&found.path,true,false); if(!rc) { + /* Dropping the redundant path references may drop the scope's graph + * too. Hold our own graph reference until the detach is complete. */ + vfs_namespace_get(ns); task_lookup_scope_cancel(task); rc=flags&MNT_DETACH ? vfs_mount_unmount_lazy(ns,&found.path) : vfs_mount_unmount(ns,&found.path); + vfs_namespace_put(ns); } vfs_path_put(&found.path);return rc; } diff --git a/kernel/syscall/fs/path.c b/kernel/syscall/fs/path.c index d7bbdef3..49ade2eb 100644 --- a/kernel/syscall/fs/path.c +++ b/kernel/syscall/fs/path.c @@ -42,7 +42,7 @@ static bool object_open_walk_scope(struct task *task,struct task_lookup_path *sa #endif /** @brief Resolve a retained operand or capture its input before retryable I/O. - * @param ns Borrowed shared namespace under execution ownership. + * @param ns Initial namespace under execution ownership; a scope can retain it. * @param task Borrowed calling task and its stable credentials. * @param dirfd Directory descriptor or AT_FDCWD, ignored by absolute input. * @param raw Borrowed kernel input; NULL only when saved already owns its copy. @@ -52,9 +52,9 @@ static bool object_open_walk_scope(struct task *task,struct task_lookup_path *sa * @param saved Optional task-owned retry operand; populated before VFS I/O. * @param out Empty result owning one path on success. * @return Zero or negative errno with empty output on failure. A populated - * saved operand retains names and root/start paths across EAGAIN, independently - * of later CLONE_FS changes, fd close/reuse or caller memory changes. No graph, - * scheduler or module-table lock may span the walker/provider callbacks. + * saved operand retains names and root/start paths with the scope's graph + * across EAGAIN, independently of CLONE_FS path changes, fd close/reuse or + * user memory changes. No graph, scheduler or module lock spans callbacks. */ static int object_lookup_run(struct vfs_namespace *ns,struct task *task,int32_t dirfd, const char *raw,bool allow_empty,bool real_ids,uint32_t lookup_flags, @@ -63,6 +63,7 @@ static int object_lookup_run(struct vfs_namespace *ns,struct task *task,int32_t if(!out)return -RELIEFOS_EINVAL; *out=(struct vfs_lookup_result){0}; if(!task || lookup_flags&~(VFS_LOOKUP_FOLLOW|VFS_LOOKUP_PARENT|VFS_LOOKUP_MISSING|VFS_LOOKUP_STAT))return -RELIEFOS_EINVAL; + if(saved && task->lookup_scope.ns)ns=task->lookup_scope.ns; if(!ns || !ns->root)return -RELIEFOS_ENODEV; const struct vfs_path *root,*start; if(saved && saved->name) { @@ -109,6 +110,7 @@ static int object_lookup_run(struct vfs_namespace *ns,struct task *task,int32_t char *copy=kernel_malloc(length+1); if(!copy){return -RELIEFOS_ENOMEM;} __builtin_memcpy(copy,raw,length+1); + if(!task->lookup_scope.ns)task->lookup_scope.ns=vfs_namespace_get(ns); if(!pinned_import) { vfs_path_get(root,&saved->root);vfs_path_get(start,&saved->start); } @@ -159,7 +161,7 @@ static int object_lookup_run(struct vfs_namespace *ns,struct task *task,int32_t } /** @brief Resolve a kernel-owned at-path against stable task/OFD objects. - * @param ns Shared namespace under execution ownership. + * @param ns Initial namespace under execution ownership; a scope can retain it. * @param task Borrowed current task with initialized root/cwd paths. * @param dirfd Directory descriptor or AT_FDCWD; absolute input ignores it. * @param raw Borrowed NUL-terminated input, bounded by VFS_PATH_MAX. @@ -168,8 +170,8 @@ static int object_lookup_run(struct vfs_namespace *ns,struct task *task,int32_t * @param lookup_flags VFS_LOOKUP_FOLLOW/PARENT/MISSING bits. * @param out Empty result receiving one owned path or creation parent. * @return Zero or negative errno with empty output on failure. An active - * syscall scope owns a copy and both directory references across I/O retries; - * unscoped trusted calls retain only the returned path. No text-prefix route + * syscall scope owns the graph, copied name and directory references across I/O + * retries; unscoped trusted calls retain only the returned path. No text-prefix route * or diagnostic name is consulted; no graph lock spans backend callbacks. */ int resolve_kernel_object_at_flags(struct vfs_namespace *ns,struct task *task,int32_t dirfd, @@ -183,7 +185,7 @@ int resolve_kernel_object_at_flags(struct vfs_namespace *ns,struct task *task,in } /** @brief Copy user text once per syscall operand and resolve retained objects. - * @param ns Borrowed shared namespace under execution ownership. + * @param ns Initial namespace under execution ownership; a scope can retain it. * @param task Borrowed current task with root/cwd and serialized descriptor state. * @param dirfd Directory descriptor or AT_FDCWD, ignored for absolute input. * @param user_ptr User pathname address, checked including terminating NUL. @@ -191,8 +193,8 @@ int resolve_kernel_object_at_flags(struct vfs_namespace *ns,struct task *task,in * @param real_ids Use real credentials for directory search. * @param lookup_flags VFS_LOOKUP_FOLLOW/PARENT/MISSING policy. * @param out Empty output receiving one owned path or a creation parent. - * @return Zero or negative errno. An active retry scope owns the checked copy - * and original roots/dirfd until final syscall cleanup, never a user pointer. + * @return Zero or negative errno. An active retry scope owns the checked copy, + * graph and original root/start until syscall cleanup, never a user pointer. * On EAGAIN a retry uses that copy even if user memory was changed/unmapped. * Unscoped copies and all per-call temporaries are released before return. */ diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 6738f993..27253068 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -843,7 +843,8 @@ static int unix_packet_peer(struct unix_socket *socket, const void *address, : -LINUX_ENOTCONN; } struct unix_address target={0}; - int result=syscall_unix_address(vfs_system_namespace(),sched_current_task(), + struct task *task=sched_current_task(); + int result=syscall_unix_address(task_lookup_namespace(task),task, (uintptr_t)address,length,false,&target); if(result)return result; if(!target.length)return -RELIEFOS_EINVAL; @@ -2819,7 +2820,7 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, if (number == __NR_bind) { struct unix_address target={0}; if(socket->path_len)return -RELIEFOS_EINVAL; - int ret=syscall_unix_address(vfs_system_namespace(),task,a1,(uint32_t)a2,true,&target); + int ret=syscall_unix_address(task_lookup_namespace(task), task,a1,(uint32_t)a2,true,&target); if(ret)return ret; if(!target.length){unix_autobind(socket);return 0;} if(!vfs_path_node(&target.object) && unix_find_path(target.path,target.length,NULL)) @@ -2869,7 +2870,7 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, struct unix_address target={0}; struct unix_socket *listener,*server; if(socket->state!=UNIX_SOCKET_OPEN)return -RELIEFOS_EISCONN; - int ret=syscall_unix_address(vfs_system_namespace(),task,a1,(uint32_t)a2,false,&target); + int ret=syscall_unix_address(task_lookup_namespace(task), task,a1,(uint32_t)a2,false,&target); if (ret == -RELIEFOS_EAGAIN) return KERNEL_SYSCALL_UNIX_CONNECT_IO_WAIT; if(ret)return ret; if(!target.length)return -RELIEFOS_EINVAL; diff --git a/kernel/syscall/memory/swap_area.c b/kernel/syscall/memory/swap_area.c index 4ee5882e..1c7fe4ad 100644 --- a/kernel/syscall/memory/swap_area.c +++ b/kernel/syscall/memory/swap_area.c @@ -148,7 +148,7 @@ static int swap_open_path(const char *path,struct swap_backing *backing) { struct task *task=sched_current_task(); struct vfs_lookup_result found={0}; - int rc=resolve_kernel_object_at_flags(vfs_system_namespace(),task,LINUX_AT_FDCWD, + int rc=resolve_kernel_object_at_flags(task_lookup_namespace(task), task,LINUX_AT_FDCWD, path,false,false,VFS_LOOKUP_FOLLOW,&found); if (rc) return rc; backing->path=found.path; diff --git a/kernel/syscall/process/exec.c b/kernel/syscall/process/exec.c index b28b759f..0a1bb187 100644 --- a/kernel/syscall/process/exec.c +++ b/kernel/syscall/process/exec.c @@ -399,7 +399,8 @@ static int exec_script_arguments(struct exec_params_kernel *params, const char * * @param inaccessible Original execveat script FD would close on exec. * @param params Owned argument staging, rebuilt within the existing stack budget. * @return Zero for an ELF candidate or negative lookup/format/copy errno. - * Reads and authorizes actual held objects; diagnostics never reopen images. + * Resolves interpreters in the lookup task's graph, not the image attachment. + * Reads and authorizes held objects; diagnostic names never reopen images. * Temporary names/paths retire on every outcome, without locks across I/O. */ int exec_resolve_scripts(struct task *task,struct vfs_path *image,const char *execfn, @@ -421,7 +422,7 @@ int exec_resolve_scripts(struct task *task,struct vfs_path *image,const char *ex rc=exec_script_arguments(params,interpreter,argument,script);if(rc)break; copy_text(script,VFS_PATH_MAX+32,interpreter); struct vfs_lookup_result next={0}; - rc=resolve_kernel_object_at_flags(vfs_system_namespace(),task,LINUX_AT_FDCWD,interpreter, + rc=resolve_kernel_object_at_flags(task_lookup_namespace(task), task,LINUX_AT_FDCWD,interpreter, false,false,VFS_LOOKUP_FOLLOW,&next); if(rc)break; if(temporary_guard) { diff --git a/kernel/syscall/process/legacy_process.c b/kernel/syscall/process/legacy_process.c index c5963321..fa0c3fb5 100644 --- a/kernel/syscall/process/legacy_process.c +++ b/kernel/syscall/process/legacy_process.c @@ -87,7 +87,7 @@ int64_t syscall_legacy_process(uint64_t number, uint64_t a0, uint64_t a1, uint64 int32_t dirfd=at ? (int32_t)a0 : LINUX_AT_FDCWD; struct task_user_text raw={0};struct vfs_lookup_result found={0}; int rc=task_lookup_user_text(task,at ? a1 : a0,VFS_PATH_MAX,false,&raw);if(rc)return rc; - rc=resolve_kernel_object_at_flags(vfs_system_namespace(),task,dirfd,raw.text, + rc=resolve_kernel_object_at_flags(task_lookup_namespace(task), task,dirfd,raw.text, (flags&LINUX_AT_EMPTY_PATH)!=0,false,flags&LINUX_AT_SYMLINK_NOFOLLOW ? 0 : VFS_LOOKUP_FOLLOW,&found); if(!rc && vfs_path_node(&found.path)->type==RELIEFOS_FS_TYPE_SYMLINK)rc=-LINUX_ELOOP; char *execfn=NULL; diff --git a/tools/test_memory_pressure_mincore_fix4.py b/tools/test_memory_pressure_mincore_fix4.py index 2bfa267e..98c95ba2 100644 --- a/tools/test_memory_pressure_mincore_fix4.py +++ b/tools/test_memory_pressure_mincore_fix4.py @@ -46,7 +46,7 @@ def main(): sources = ["tools/tests/memory_pressure_mincore_fix4_test.c", "kernel/exec/usercopy.c", "kernel/syscall/fs/lookup_state.c", "kernel/sched/core.c", "kernel/sched/accounting.c", "kernel/sched/wait.c", - "kernel/sched/oom.c", "kernel/sync/wait.c", + "kernel/sched/oom.c", "kernel/sync/wait.c", "block/core/storage_wait.c", "mm/reclaim/pressure.c", "mm/reclaim/wait.c", "mm/cache/page_cache.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/attributes.c", "fs/vfs/exec_file.c", "mm/swap/area.c", "mm/swap/slot.c", "mm/swap/paging.c", diff --git a/tools/test_memory_pressure_open_path.py b/tools/test_memory_pressure_open_path.py index 11d1ad52..ed1561c1 100644 --- a/tools/test_memory_pressure_open_path.py +++ b/tools/test_memory_pressure_open_path.py @@ -42,7 +42,7 @@ def main(): sources = ["tools/tests/memory_pressure_open_path_test.c", "kernel/exec/usercopy.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fs/path.c", "kernel/sched/core.c", "kernel/sched/accounting.c", "kernel/sched/wait.c", - "kernel/sched/oom.c", "kernel/sync/wait.c", + "kernel/sched/oom.c", "kernel/sync/wait.c", "block/core/storage_wait.c", "mm/reclaim/pressure.c", "mm/reclaim/wait.c", "mm/cache/page_cache.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/attributes.c", "fs/vfs/exec_file.c", "mm/swap/area.c", "mm/swap/slot.c", "mm/swap/paging.c", diff --git a/tools/test_memory_pressure_regular_read.py b/tools/test_memory_pressure_regular_read.py index a8da4c14..069cefe7 100644 --- a/tools/test_memory_pressure_regular_read.py +++ b/tools/test_memory_pressure_regular_read.py @@ -41,7 +41,7 @@ def main(): "tools/tests/task8_host_stubs/device_page_unreached.c", "kernel/syscall/fs/lookup_state.c", "kernel/sched/core.c", "kernel/sched/accounting.c", "kernel/sched/wait.c", - "kernel/sched/oom.c", "kernel/sync/wait.c", "mm/reclaim/pressure.c", + "kernel/sched/oom.c", "kernel/sync/wait.c", "block/core/storage_wait.c", "mm/reclaim/pressure.c", "mm/reclaim/wait.c", "mm/cache/page_cache.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/attributes.c", "fs/vfs/exec_file.c", "mm/swap/area.c", "mm/swap/slot.c", "mm/swap/paging.c", diff --git a/tools/tests/futimens_test.c b/tools/tests/futimens_test.c index 8158c5a4..c4c1efa7 100644 --- a/tools/tests/futimens_test.c +++ b/tools/tests/futimens_test.c @@ -33,6 +33,12 @@ bool user_range_ok(uint64_t address,uint64_t bytes) return (address>=timestamp_input && bytes<=timestamp_bytes && address-timestamp_input<=timestamp_bytes-bytes) || (address>=timestamp_name && bytes<=timestamp_name_bytes && address-timestamp_name<=timestamp_name_bytes-bytes); } +/** @brief Check fixture input without accessing host memory. + * @param address First byte. @param bytes Length of the range. + * @return Zero for an empty or readable range, otherwise negative EFAULT. + */ +int user_range_readable(uint64_t address,uint64_t bytes) +{return !bytes || user_range_ok(address,bytes) ? 0 : -RELIEFOS_EFAULT;} size_t user_strlen(const char *text,size_t maximum) {for(size_t i=0;ipid=51;task->euid=task->fsuid=1000;task->egid=task->fsgid=1000; - assert(!vfs_namespace_root(ns,&task->fs_paths.root)); - vfs_path_get(&task->fs_paths.root,&task->fs_paths.cwd); + assert(!sched_task_fs_start(task,ns)); struct vfs_path path={0}; assert(!vfs_path_lookup(ns,&task->fs_paths.root,&task->fs_paths.cwd,"original",0,&path)); struct task_file *file=&task->files[0]; diff --git a/tools/tests/memory_pressure_fault_integration_test.c b/tools/tests/memory_pressure_fault_integration_test.c index ce2bb674..3f11f130 100644 --- a/tools/tests/memory_pressure_fault_integration_test.c +++ b/tools/tests/memory_pressure_fault_integration_test.c @@ -36,7 +36,9 @@ int memory_oom_advance(uint32_t budget) { return pressure_fixture_no_victim(budg int memory_oom_advance(uint32_t budget) { (void)budget; abort(); } #endif void sched_set_memory_release_notify(void (*notify)(void)) { retirement_notify=notify; } +#ifndef PRESSURE_SYSCALL_ENTRY_FIXTURE uint64_t storage_completion_generation(void) { return 0; } +#endif #ifndef PRESSURE_INTEGRATION_FIXTURE_ENTRY #define PRESSURE_INTEGRATION_FIXTURE_ENTRY main diff --git a/tools/tests/memory_pressure_mincore_fix4_test.c b/tools/tests/memory_pressure_mincore_fix4_test.c index b9547e16..fb0abb3f 100644 --- a/tools/tests/memory_pressure_mincore_fix4_test.c +++ b/tools/tests/memory_pressure_mincore_fix4_test.c @@ -4,6 +4,7 @@ * wakeup and swap transport are bounded host models. The host output buffer * and simulated physical frame are distinct; byte restoration is checked * separately from the actual C-store results. */ +#define PRESSURE_SYSCALL_ENTRY_FIXTURE 1 #define PRESSURE_FIX4_VECTOR_FIXTURE 1 #define PRESSURE_FIX5_FIXTURE_ENTRY pressure_fix5_unused_main #include "memory_pressure_fix5_test.c" @@ -15,7 +16,11 @@ #include #include #include +#include +#include #include +#include +#include /* The runner links the real usercopy implementation; host output bytes and * modeled physical frames remain distinct, as described above. */ @@ -96,6 +101,12 @@ void task_release_syscall_file(struct task *task) #endif void task_process_vm_scope_release(void *state) { (void)state; abort(); } void sched_task_identity_put(struct task_identity *identity) { (void)identity; abort(); } +/** @brief No fixture descriptor belongs to a pipe. + * @param frame Borrowed syscall frame. @param resume Unchanged task output. + * @return False so the production slow dispatcher executes the tested syscall. + */ +static bool syscall_try_pipe_io(struct trap_frame *frame,struct task **resume) +{ (void)frame; (void)resume; return false; } int64_t kernel_signal_rt_sigreturn(struct task *t,struct trap_frame *f) { (void)t; (void)f; abort(); } int64_t syscall_clone_prepared(const struct trap_frame *f,uint64_t a,uint64_t b, @@ -333,7 +344,8 @@ static void storage_contention(void) struct trap_frame f=case_frame(&c);unsigned attempts=0,writes_before=gate_writes; invoke_one(&f,&attempts); assert(f.rax==LINUX_SYS_MINCORE && c.task->state==TASK_BLOCKED && - !c.task->waiting_queue && mm_swap_record_lookup(sched_task_as(c.task),c.page)==c.token && + c.task->waiting_queue && c.task->wake_tick==pressure_fixture_tick+1 && + mm_swap_record_lookup(sched_task_as(c.task),c.page)==c.token && !gate_reads && gate_writes==writes_before); gate_contended=false; assert(!invoke(&f,&attempts) && attempts==2 && gate_reads==1 && gate_writes==writes_before); diff --git a/tools/tests/memory_pressure_open_path_test.c b/tools/tests/memory_pressure_open_path_test.c index 4bd938a9..149cc021 100644 --- a/tools/tests/memory_pressure_open_path_test.c +++ b/tools/tests/memory_pressure_open_path_test.c @@ -113,7 +113,7 @@ static int64_t pressure_fixture_open(struct task *task,uint64_t nr,uint64_t a,ui int32_t dirfd=nr==LINUX_SYS_OPEN ? LINUX_AT_FDCWD : (int32_t)a; uint64_t pathname=nr==LINUX_SYS_OPEN ? a : b; struct vfs_lookup_result result={0}; - int rc=resolve_user_object_at_flags(&fixture_ns,task,dirfd,pathname,false,false, + int rc=resolve_user_object_at_flags(task_lookup_namespace(task),task,dirfd,pathname,false,false, VFS_LOOKUP_FOLLOW,&result); if(rc)return rc; vfs_path_put(&result.path);return 42; @@ -160,6 +160,7 @@ int main(void) assert(!vfs_path_lookup_child(&old_root,"new-cwd",&new_cwd)); vfs_mount_put(mount); /* The namespace now owns its retained mount. */ struct task_fs_paths *paths=sched_task_paths(task); + paths->ns=vfs_namespace_get(&fixture_ns); vfs_path_get(&old_root,&paths->root);vfs_path_get(&old_cwd,&paths->cwd); expected_root=old_root;expected_cwd=old_cwd;track_lookup=true; fixture_volume=(struct storage_volume){.fs_ops=&fixture_fs_ops,.filesystem=STORAGE_FILESYSTEM_EXT4, @@ -171,13 +172,14 @@ int main(void) pressure_regular_contend_writes=true;unsigned attempts=0; invoke_open_one(&frame,&attempts); assert(frame.rax==LINUX_SYS_OPEN && task->waiting_queue && import_denials && !lookup_calls); + assert(task->lookup_scope.ns==&fixture_ns && fixture_ns.references==2); assert(vfs_path_equal(&task->lookup_scope.paths[0].root,&old_root) && vfs_path_equal(&task->lookup_scope.paths[0].start,&old_cwd)); vfs_path_put(&paths->root);vfs_path_put(&paths->cwd); vfs_path_get(&new_root,&paths->root);vfs_path_get(&new_cwd,&paths->cwd); pressure_regular_contend_writes=false; assert(invoke_open(&frame,&attempts)==42 && lookup_calls==2 && gate_writes>=2); - assert(!task->lookup_scope.armed && !task->waiting_queue); + assert(!task->lookup_scope.armed && !task->waiting_queue && fixture_ns.references==1); /* Fail the real walker's pending allocation before any search/backend. * Retain the captured name and identities across a pressure wait, then @@ -278,6 +280,7 @@ int main(void) restore_victims(task,victims,8); vfs_path_put(&paths->root);vfs_path_put(&paths->cwd); + assert(fixture_ns.references==1);vfs_namespace_put(paths->ns);paths->ns=NULL; vfs_path_put(&old_root);vfs_path_put(&old_cwd); vfs_path_put(&new_root);vfs_path_put(&new_cwd); assert(!vfs_namespace_destroy(&fixture_ns)); diff --git a/tools/tests/memory_pressure_regular_read_test.c b/tools/tests/memory_pressure_regular_read_test.c index 89690e86..11355bcf 100644 --- a/tools/tests/memory_pressure_regular_read_test.c +++ b/tools/tests/memory_pressure_regular_read_test.c @@ -1,12 +1,5 @@ /* SPDX-License-Identifier: Apache-2.0 */ #define _POSIX_C_SOURCE 200809L -#include -#include -#include -#include -struct trap_frame; -struct task; -static bool syscall_try_pipe_io(struct trap_frame *frame,struct task **resume); /* Real scalar-read staging, syscall entry, PTE/swap and pressure recovery. * The fixture models finite physical-page/heap availability and swap transport. */ #define PRESSURE_REGULAR_IO_FIXTURE 1 @@ -37,12 +30,6 @@ static bool pressure_fixture_heap_admitted(size_t size) uint64_t time_uptime_us(void) { return 0; } uint64_t time_work_counter_us(void) { return time_uptime_us(); } -/* Pipe admission and storage-provider waits are outside this scalar-reclaim - * fixture; its provider completes immediately and pressure owns every wait. */ -static bool syscall_try_pipe_io(struct trap_frame *frame,struct task **resume) -{ assert(frame && resume);return false; } -uint64_t storage_wait_begin(void) { return 0; } -void storage_wait_sleep(uint64_t generation) { (void)generation;abort(); } int kernel_signal_queue_task(struct task *task,int signal_number) { (void)task;(void)signal_number;abort(); } int storage_disk_block_read(uint32_t d,int32_t p,uint64_t o,void *b,uint32_t n,uint32_t *r) diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 123ae40a..dba8e8a9 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -3721,15 +3721,19 @@ static void runtime_bind_remount(struct vfs_namespace *ns,const struct vfs_path puts("PASS bind remount: local policy, shared readonly, and stateless writer until final OFD put"); } -/** @brief Check real deferred-script rewriting, final DAC and OOM ownership. - * @param fs Borrowed initial memory filesystem with no published namespace. - * @return None. Uses actual namei/inodes/script parser, retires every task - * argument and path on success/error, and leaves no global namespace behind. +/** @brief Resolve pending scripts and their interpreters in a noninitial task graph. + * @param fs Borrowed memory filesystem with no global namespace published. + * Uses actual namei/inodes/script parser, tests final DAC, and retires every + * task argument and path on success or allocation failure. */ static void pending_script_launch(struct tmpfs_super *fs) { - assert(!vfs_system_bootstrap(initial_volume,&g_volumes[0],NULL,0)); - struct vfs_namespace *ns=vfs_system_namespace();struct vfs_path root={0},script={0},interpreter={0}; + struct vfs_namespace graph={0},*ns=&graph; + struct vfs_mount *base=NULL; + assert(!vfs_system_namespace()); + assert(!initial_volume(&g_volumes[0],&base)); + assert(!vfs_namespace_init(ns,base));vfs_mount_put(base); + struct vfs_path root={0},script={0},interpreter={0}; assert(!vfs_namespace_root(ns,&root)); struct reliefos_permissions mode={0755,1000,1000}; assert(!vfs_path_create_node(&root,"init-script",LINUX_S_IFREG,&mode,NULL,&script)); diff --git a/tools/tests/mount_tree_test.c b/tools/tests/mount_tree_test.c index 559b3f67..f94e7406 100644 --- a/tools/tests/mount_tree_test.c +++ b/tools/tests/mount_tree_test.c @@ -397,6 +397,57 @@ static void namespace_snapshot_objects(struct module *owner) puts("PASS mount namespace snapshot: covered task paths, independent policy and IDs, atomic rollback and deferred retirement"); } +/** @brief Pause a walk before resolving a component. + * @param context Pointer to the fixture's paused flag. + * @param path Directory in the retained graph. + * @return EAGAIN while paused, otherwise zero. + */ +static int pause_namespace_walk(void *context,const struct vfs_path *path) +{ + assert(vfs_path_namespace(path));return *(const bool *)context ? -EAGAIN : 0; +} + +/** @brief A suspended walk is a graph owner, but ordinary paths are not. */ +static void managed_namespace_walks(void) +{ + struct vfs_namespace base={0};struct vfs_mount *mount=mount_new(&a,NULL); + assert(!vfs_namespace_init(&base,mount));vfs_mount_put(mount); + struct vfs_path root={0};assert(!vfs_namespace_root(&base,&root)); + struct vfs_path point=find(&base,&root,&root,"mnt",2); + mount=mount_new(&b,NULL);assert(!vfs_mount_attach(&base,mount,&point));vfs_mount_put(mount); + vfs_path_put(&point); + + for(unsigned cancel=0;cancel<2;++cancel) { + struct vfs_path copy_root={0};vfs_path_get(&root,©_root); + struct vfs_namespace *copy=NULL; + assert(!vfs_namespace_clone(&base,©_root,NULL,©)); + struct vfs_path copy_mount=find(copy,©_root,©_root,"mnt",1); + struct vfs_lookup_result found={0};struct vfs_walk *walk=NULL; + bool paused=true; + struct vfs_lookup_policy policy={.search=pause_namespace_walk,.context=&paused}; + assert(vfs_path_resolve_resume(copy,©_root,©_root,"/mnt/new",&policy,&walk,&found)==-EAGAIN); + assert(walk && !found.path.mount); + vfs_namespace_put(copy); /* The walk now holds the only graph reference. */ + assert(vfs_path_namespace(©_root)==copy); + char text[64];uint32_t got=123; + assert(vfs_read_mount_table(&base,©_root,true,0,text,sizeof(text),&got)==-EXDEV && !got); + if(cancel)vfs_walk_cancel(&walk); + else { + paused=false; + assert(!vfs_path_resolve_resume(&base,&root,&root,"/file",&policy,&walk,&found)); + assert(found.path.mount==copy_mount.mount && vfs_path_node(&found.path)->first_cluster==2); + vfs_path_put(&found.path); + } + assert(!walk && !vfs_path_namespace(©_root) && !vfs_path_namespace(©_mount)); + got=123; + assert(!vfs_read_mount_table(&base,©_root,true,0,text,sizeof(text),&got) && !got); + vfs_path_put(©_mount);vfs_path_put(©_root); + } + assert(vfs_reclaim_mounts(8)==4 && !vfs_reclaim_pending()); + vfs_path_put(&root);assert(!vfs_namespace_destroy(&base)); + puts("PASS pending walk retains its original graph; resume and cancel retire it independently of path pins"); +} + static unsigned pseudo_lookup_calls; static int owned_pseudo_lookup(const char *name,struct storage_node *out) { @@ -592,6 +643,7 @@ int main(void) { bound_directory_objects(); mount_table_objects(); + managed_namespace_walks(); magic_link_objects(); renamed_paths(); struct module owner={0};strcpy(owner.name,"test_fs"); diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index b5ff374b..465f4ad5 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -366,6 +366,38 @@ static void assert_proc_mount_row(const char *table,const struct vfs_path *mount assert(strstr(table,expected)); } +/** @brief Open a foreign task's graph and read it after that task is reaped. + * @param ns Reader's live graph with a proc attachment at /else. + * @param root Reader's retained root. + */ +static void test_foreign_proc_mount_view(struct vfs_namespace *ns,const struct vfs_path *root) +{ + struct task_fs_paths *paths=&foreign.fs_paths; + assert(!paths->ns && !expose_foreign); + vfs_path_get(root,&paths->root);vfs_path_get(root,&paths->cwd); + assert(!vfs_namespace_clone(ns,&paths->root,&paths->cwd,&paths->ns)); + struct vfs_path target_mount={0},target_root={0},view={0}; + vfs_path_get(&paths->root,&target_root); + assert(!vfs_path_lookup(paths->ns,&target_root,&target_root,"/else",0,&target_mount)); + expose_foreign=true; + char name[64],text[512];uint32_t got=0; + snprintf(name,sizeof(name),"/else/%u/mountinfo",foreign.pid); + assert(!vfs_path_lookup(ns,root,root,name,VFS_LOOKUP_FOLLOW,&view)); + struct vfs_open_file *opened=NULL; + assert(!vfs_file_open(&view,0,&opened) && opened); + vfs_path_put(&view); + expose_foreign=false;sched_task_identity_detach(&foreign); + vfs_path_put(&paths->root);vfs_path_put(&paths->cwd); + vfs_namespace_put(paths->ns);*paths=(struct task_fs_paths){0}; + assert(sched_task_namespace(¤t)==ns && !sched_find(foreign.pid)); + assert(!vfs_file_read(opened,0,text,sizeof(text)-1,&got));text[got]=0; + assert_proc_mount_row(text,&target_mount,&target_root,"/else"); + vfs_file_close(opened); + assert(!vfs_path_namespace(&target_root) && !vfs_path_namespace(&target_mount)); + vfs_path_put(&target_mount);vfs_path_put(&target_root); + assert(vfs_reclaim_mounts(2)==2 && !vfs_reclaim_pending()); +} + static void test_proc_mount_objects(void) { static const struct vfs_backend_ops ops={.lookup=proc_path_lookup,.retain=proc_path_retain, @@ -391,6 +423,7 @@ static void test_proc_mount_objects(void) *file=(struct task_file){.used=1,.node={.type=RELIEFOS_FS_TYPE_FILE,.first_cluster=17}}; strcpy(file->path,"/memfd:held (deleted)"); assert(!vfs_path_anonymous(root.mount,&file->node,&file->path_ref)); + current.fs_paths.ns=vfs_namespace_get(&ns); vfs_path_get(&root,¤t.fs_paths.root);vfs_path_get(&destination,¤t.fs_paths.cwd); struct vfs_path mounts_view={0};char mount_text[512]; assert(!vfs_path_lookup(&ns,&root,&root,"/procdir/self/mountinfo",VFS_LOOKUP_FOLLOW,&mounts_view)); @@ -440,6 +473,7 @@ static void test_proc_mount_objects(void) assert(!vfs_path_lookup(&ns,&root,&root,"/procdir/42",VFS_LOOKUP_FOLLOW,&old_process)); assert(!vfs_path_lookup(&ns,&root,&old_process,"status",VFS_LOOKUP_FOLLOW,&old_status)); assert(!vfs_mount_move(&ns,&mounted,&destination)); + test_foreign_proc_mount_view(&ns,&root); assert(!vfs_path_read(&mounts_view,0,mount_text,sizeof(mount_text)-1,&got));mount_text[got]=0; assert_proc_mount_row(mount_text,&mounted,&root,"/else");assert(!strstr(mount_text,"/procdir")); assert(!vfs_file_read(old_view,0,mount_text,sizeof(mount_text)-1,&got));mount_text[got]=0; @@ -474,10 +508,11 @@ static void test_proc_mount_objects(void) vfs_path_put(&file->path_ref);*file=(struct task_file){0}; vfs_path_put(&sched_task_mm(¤t)->executable_path); vfs_path_put(¤t.fs_paths.root);vfs_path_put(¤t.fs_paths.cwd); + vfs_namespace_put(current.fs_paths.ns);current.fs_paths.ns=NULL; vfs_path_put(&mounted);vfs_path_put(&destination);vfs_path_put(&point);vfs_path_put(&root); assert(!vfs_namespace_destroy(&ns) && !proc_path_pins); sched_task_identity_detach(¤t); - puts("PASS real proc mount: moved attachment, held-node read/readdir, FD/root/cwd magic links and dead PID identity isolation"); + puts("PASS real proc mount: moved attachments, magic links and target graph retained across PID exit"); } static void test_proc_mount_failures(void) { diff --git a/tools/tests/rootfs_paths_test.c b/tools/tests/rootfs_paths_test.c index 8263996b..07e187f5 100644 --- a/tools/tests/rootfs_paths_test.c +++ b/tools/tests/rootfs_paths_test.c @@ -44,6 +44,7 @@ int main(void) assert(!vfs_path_lookup(&ns,&root,&root,"/proc",0,&point)); assert(!proc_create_vfs_mount(&proc) && !vfs_mount_attach(&ns,proc,&point));vfs_mount_put(proc); assert(!vfs_path_lookup(&ns,&root,&root,"/home/test",0,&cwd)); + current.fs_paths.ns=vfs_namespace_get(&ns); vfs_path_get(&root,¤t.fs_paths.root);vfs_path_get(&cwd,¤t.fs_paths.cwd); strcpy(sched_task_cwd(¤t),"/deliberately-stale-name"); const char *inputs[]={"/etc/mtab","/proc/self/mountinfo","/proc/self/cwd","/proc/self"}; @@ -57,6 +58,7 @@ int main(void) vfs_path_put(&found.path); } vfs_path_put(¤t.fs_paths.root);vfs_path_put(¤t.fs_paths.cwd); + vfs_namespace_put(current.fs_paths.ns);current.fs_paths.ns=NULL; vfs_path_put(&cwd);vfs_path_put(&point);vfs_path_put(&root); assert(!vfs_namespace_destroy(&ns));sched_task_identity_detach(¤t); assert(!proc_path_pins && proc_allocations==before); diff --git a/tools/tests/swap_activation_test.c b/tools/tests/swap_activation_test.c index e808757f..f8063f15 100644 --- a/tools/tests/swap_activation_test.c +++ b/tools/tests/swap_activation_test.c @@ -27,7 +27,9 @@ extern int swap_activate_user(uint64_t path,uint32_t flags) __attribute__((weak) /** @brief Resolve and deactivate a backing. @param path User pointer. * @return Zero or negative errno. */ extern int swap_deactivate_user(uint64_t path) __attribute__((weak)); -static struct task task={.kind=TASK_KIND_USER,.pid=3,.cap_effective=1ULL<active);t->active=0;return 0; } /** @brief Fail invariant. @param message Diagnostic. */ __attribute__((noreturn)) void panic(const char *message) { fprintf(stderr,"%s\n",message);abort(); } -/** @brief Shared namespace. @return Non-NULL namespace. */ -struct vfs_namespace *vfs_system_namespace(void) { return (void *)(uintptr_t)1; } /** @brief Resolve and retain a test path. @param ns Namespace. @param t Task. * @param dirfd Directory. @param user User string. @param empty Empty policy. * @param ids Real ID policy. @param flags Lookup flags. @param out Result. @return Status. */ int resolve_kernel_object_at_flags(struct vfs_namespace *ns,struct task *t,int32_t dirfd, const char *name,bool empty,bool ids,uint32_t flags,struct vfs_lookup_result *out) { - assert(ns && t==&task && dirfd==LINUX_AT_FDCWD && !empty && !ids && flags==VFS_LOOKUP_FOLLOW); + assert(ns==&swap_namespace && t==&task && dirfd==LINUX_AT_FDCWD && !empty && !ids && flags==VFS_LOOKUP_FOLLOW); if(!name)return -EFAULT; int i=!strcmp(name,"one") || !strcmp(name,"alias") ? 0 : !strcmp(name,"two") ? 1 : !strcmp(name,"raw") ? 2 : -1; diff --git a/tools/tests/sysv_shm_test.c b/tools/tests/sysv_shm_test.c index 155b0e1f..6a46f92b 100644 --- a/tools/tests/sysv_shm_test.c +++ b/tools/tests/sysv_shm_test.c @@ -225,7 +225,8 @@ static void clone_pending_operands(struct task *parent,struct task *child,struct char *name=kernel_malloc(32);assert(name);strcpy(name,"original-owned-operand"); parent->vector_io=vector;parent->syscall_file=&borrowed_mapping; parent->regular_io.active=true;parent->regular_io.done=1; - parent->lookup_scope=(struct task_lookup_scope){.armed=true,.number=__NR_openat,.cursor=1}; + parent->lookup_scope=(struct task_lookup_scope){.armed=true,.number=__NR_openat,.cursor=1, + .ns=vfs_namespace_get(ns)}; struct task_lookup_path *operand=&parent->lookup_scope.paths[0];operand->name=name;operand->complete=true; vfs_path_get(&parent->fs_paths.root,&operand->root);vfs_path_get(&parent->fs_paths.cwd,&operand->start); vfs_path_get(&parent->fs_paths.root,&operand->result.path);assert(ns->root->references==6); @@ -238,13 +239,14 @@ static void clone_pending_operands(struct task *parent,struct task *child,struct int64_t pid=sched_clone_current(&parent->frame,flags,0,0,0,0); shm_physical_budget=-1;shm_fail_heap=-1; assert(!child->vector_io && !child->syscall_file && !child->regular_io.active && !child->regular_io.done); - assert(!child->lookup_scope.armed && !child->lookup_scope.paths[0].name && !child->lookup_scope.paths[0].root.mount && + assert(!child->lookup_scope.armed && !child->lookup_scope.ns && + !child->lookup_scope.paths[0].name && !child->lookup_scope.paths[0].root.mount && !child->lookup_scope.paths[0].start.mount && !child->lookup_scope.paths[0].result.path.mount); assert(parent->vector_io==vector && vector->completed==3 && parent->syscall_file==&borrowed_mapping && parent->regular_io.active && parent->regular_io.done==1 && borrowed_mapping.references==1); assert(parent->lookup_scope.armed && operand->name==name && !strcmp(name,"original-owned-operand") && operand->root.mount==ns->root && operand->start.mount==ns->root && operand->result.path.mount==ns->root); - if(mode<2)assert(pid==-LINUX_ENOMEM && ns->root->references==6); + if(mode<2)assert(pid==-LINUX_ENOMEM && ns->root->references==6 && ns->references==2); else { assert(pid>0 && child->pid==(uint32_t)pid && child->state==TASK_READY); for (uint32_t i = 0; i < sched_task_vma_capacity(child); ++i) { @@ -254,9 +256,11 @@ static void clone_pending_operands(struct task *parent,struct task *child,struct } assert(!mm_lock_flags(sched_task_as(child))); assert(mm_lock_flags(sched_task_as(parent)) == (LINUX_MCL_FUTURE | LINUX_MCL_ONFAULT)); - assert(sched_task_paths(child)->root.mount==ns->root && sched_task_paths(child)->cwd.mount==ns->root); + assert(sched_task_namespace(child)==ns && sched_task_paths(child)->root.mount==ns->root && + sched_task_paths(child)->cwd.mount==ns->root); if(mode==3)assert(child->shared_fs==parent->shared_fs && parent->shared_fs->references==2 && ns->root->references==6); else assert(!child->shared_fs && ns->root->references==8); + assert(ns->references==(mode==3 ? 2 : 3)); syscall_release_task_files(child);address_space_destroy(sched_task_as(child));sched_task_vma_release(child); sched_task_fs_release(child);task_groups_release(child); kernel_free(child->exec_argv);kernel_free(child->exec_envp);kernel_free(child->exec_data); @@ -264,21 +268,23 @@ static void clone_pending_operands(struct task *parent,struct task *child,struct task_zero(child);child->state=TASK_EXITED;child->running_cpu=SCHED_CPU_NONE;child->flags=TASK_FLAG_RESOURCES_RELEASED; if (parent->shared_fs) { sched_task_fs_release(parent); + parent->fs_paths.ns=vfs_namespace_get(ns); vfs_path_get(&operand->root, &parent->fs_paths.root); vfs_path_get(&operand->start, &parent->fs_paths.cwd); } - assert(ns->root->references == 6); + assert(ns->root->references==6 && ns->references==2); } empty_clone_boundary=false;assert(live_pages()==pages_before && shm_heap_live==heap_before); } vfs_path_put(&operand->root);vfs_path_put(&operand->start);vfs_path_put(&operand->result.path); + vfs_namespace_put(parent->lookup_scope.ns); kernel_free(name);kernel_free(vector);parent->lookup_scope=(struct task_lookup_scope){0}; parent->vector_io=NULL;parent->syscall_file=NULL;parent->regular_io.active=false;parent->regular_io.done=0; locked->flags &= ~(TASK_VMA_FLAG_LOCKED | TASK_VMA_FLAG_LOCKONFAULT); *sched_task_vma_at(parent, SCHED_TASK_VMA_MAX) = (struct task_vma){0}; mm_context_set_lock_flags(sched_task_as(parent), 0); - assert(ns->root->references==3); - puts("PASS actual fork/CLONE_FS and page/SHM OOM keep pending operand/vector ownership only in parent"); + assert(ns->root->references==3 && ns->references==1); + puts("PASS actual fork/CLONE_FS: graph and path ownership, rollback, and no inherited pending operands"); } #ifdef TASK8_CLONE_TID_TEST @@ -367,8 +373,7 @@ int main(void) struct storage_node root_node={.type=RELIEFOS_FS_TYPE_DIR,.first_cluster=1}; assert(!vfs_mount_new(&fs_ops,NULL,NULL,&root_node,&root_mount)); assert(!vfs_namespace_init(&namespace,root_mount));vfs_mount_put(root_mount); - assert(!vfs_namespace_root(&namespace,&parent->fs_paths.root)); - vfs_path_get(&parent->fs_paths.root,&parent->fs_paths.cwd); + assert(!sched_task_fs_start(parent,&namespace)); assert(namespace.root->references==3 && fs_backend_pins==1); clone_pending_operands(parent,child,&namespace); /* Exec stages scalar credentials independently of root/cwd ownership. @@ -376,10 +381,10 @@ int main(void) * live task's FS pins when prepared credentials are committed. */ struct task staged_exec={0};staged_exec.credentials=parent->credentials; sched_task_fs_inherit(&staged_exec,parent); - assert(namespace.root->references==5); + assert(sched_task_namespace(&staged_exec)==&namespace && namespace.references==2 && namespace.root->references==5); parent->credentials=staged_exec.credentials; sched_task_fs_release(&staged_exec); - assert(namespace.root->references==3 && parent->fs_paths.root.mount==namespace.root && + assert(namespace.references==1 && namespace.root->references==3 && parent->fs_paths.root.mount==namespace.root && parent->fs_paths.cwd.mount==namespace.root); parent->vmas[SCHED_TASK_VMA_MAX-1]=(struct task_vma){.used=1, @@ -393,7 +398,7 @@ int main(void) assert(!child->fs_paths.root.mount && !child->fs_paths.cwd.mount && !child->shared_fs); assert(!task_promote_shared(parent,CLONE_FS)); assert(parent->shared_fs && parent->shared_fs->references==1); - assert(!parent->fs_paths.root.mount && !parent->fs_paths.cwd.mount); + assert(!parent->fs_paths.ns && !parent->fs_paths.root.mount && !parent->fs_paths.cwd.mount); struct task fs_sibling={.shared_fs=parent->shared_fs};++fs_sibling.shared_fs->references; assert(!sched_prepare_exec_current(parent)); assert(parent->shared_fs == fs_sibling.shared_fs); @@ -402,18 +407,18 @@ int main(void) assert(fs_sibling.shared_fs->references == 2 && namespace.root->references == 3); sched_task_fs_release(parent); assert(fs_sibling.shared_fs->references==1 && namespace.root->references==3); - assert(sched_task_paths(&fs_sibling)->root.mount==namespace.root); + assert(sched_task_namespace(&fs_sibling)==&namespace && namespace.references==1 && + sched_task_paths(&fs_sibling)->root.mount==namespace.root); sched_task_fs_release(&fs_sibling); - assert(namespace.root->references==1); + assert(namespace.root->references==1 && !namespace.references); /* Exec by the last CLONE_FS holder preserves root/cwd and umask. */ - assert(!vfs_namespace_root(&namespace,&parent->fs_paths.root)); - vfs_path_get(&parent->fs_paths.root,&parent->fs_paths.cwd); + assert(!sched_task_fs_start(parent,&namespace)); task_copy_cwd(parent,"/kept"); task_copy_identity_text(parent->root_dir,sizeof(parent->root_dir),"/private"); parent->umask=0027; assert(!task_promote_shared(parent,CLONE_FS)); assert(!sched_prepare_exec_current(parent)); - assert(namespace.root->references == 3); + assert(namespace.root->references==3 && namespace.references==1); assert(!strcmp(sched_task_cwd(parent), "/kept") && !strcmp(sched_task_root(parent), "/private") && *sched_task_umask(parent) == 0027); sched_task_fs_release(parent); diff --git a/tools/tests/task8_lookup_text_test.c b/tools/tests/task8_lookup_text_test.c index d9d51171..d1467855 100644 --- a/tools/tests/task8_lookup_text_test.c +++ b/tools/tests/task8_lookup_text_test.c @@ -111,6 +111,7 @@ int main(int argc,char **argv) return 0; } struct vfs_namespace ns={.root=(void *)1}; + current.fs_paths.ns=&ns; current.fs_paths.root=(struct vfs_path){.mount=(void *)1,.dentry=(void *)1}; current.fs_paths.cwd=current.fs_paths.root; char *text=(char *)memory+4092; From 1fecb0e452b7a8713286ceabc033526be131bb86 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 03:18:24 +0800 Subject: [PATCH 15/97] feat(vfs): propagate mount events across namespaces --- Documentation/core-api/mount-namespaces.rst | 23 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 58 ++- .../en/LC_MESSAGES/userspace-api/abi.po | 55 ++- .../LC_MESSAGES/core-api/mount-namespaces.po | 42 ++- .../ja/LC_MESSAGES/userspace-api/abi.po | 39 +- Documentation/userspace-api/abi.rst | 22 +- fs/vfs/mount_internal.h | 19 +- fs/vfs/mount_table.c | 8 +- fs/vfs/mount_tree.c | 351 +++++++++++------- include/reliefnt/mount.h | 45 ++- tools/tests/mount_backend_test.c | 24 +- tools/tests/mount_tree_test.c | 177 ++++++++- 12 files changed, 635 insertions(+), 228 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index cfa698e3..6b36beae 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -3,16 +3,28 @@ ================ ``vfs_namespace_snapshot()`` 在独占 VFS 执行权下,将活动挂载树复制到地址固定、 -由调用方管理的空命名空间中。它保留覆盖层、不可绑定挂载和图内传播关系;新旧 -命名空间之间不会建立传播关系。各副本直接持有原生文件系统后端,共享目录项和 -文件内容,但挂载策略和写入者计数独立。挂载 ID 从 VFS 全局序列分配,传播组号 -仍仅在各自的命名空间内有意义。 +由调用方管理的空命名空间中。它保留覆盖层和不可绑定挂载。共享挂载的副本加入 +原对等组;slave 副本保留指向活动上游组成员的弱引用。各副本直接持有原生文件 +系统后端,共享目录项和文件内容,但挂载策略和写入者计数独立。挂载 ID 和对等 +组号各自从 VFS 全局序列分配。 可选的 root 和 cwd 引用按原挂载对象和目录项重新绑定,而不是重新查找路径; 即使路径已被其他挂载覆盖,所指目录项也不变。已摘除的路径保持原样,其他活动 命名空间的路径返回 ``EXDEV``。所有分配完成后才发布新树并替换路径;失败时 不改变原树、目标、路径或 ID 游标。 +跨命名空间传播 +============== + +VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载图的寿命;成员 +退出或摘除时,其他命名空间的下游挂载也会改接到剩余对等成员,或在组消失时 +改接到原上游组。没有上游时清除该关系。 + +跨图的挂载、bind 与 move 副本作为一个批次发布;分配失败时所有图和两个 ID +游标保持不变。普通卸载先检查所有图中选中的挂载是否有忙引用,再检查最终后端 +是否允许卸载;失败时不摘除任何挂载。延迟卸载不分配内存,保留接收方无关的 +覆盖挂载。挂载表的传播字段见 :doc:`../userspace-api/abi`。 + 任务、路径查找与 proc 视图 ========================== @@ -39,5 +51,4 @@ 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 ``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。 -这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换,也未实现跨图 -peer/slave 传播或 ``mountinfo`` 的 ``propagate_from`` 字段。 +这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 80063f78..ed972a43 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -21,18 +21,18 @@ msgstr "Mount namespace snapshots" msgid "" "``vfs_namespace_snapshot()`` 在独占 VFS 执行权下,将活动挂载树复制到地址固定、 " -"由调用方管理的空命名空间中。它保留覆盖层、不可绑定挂载和图内传播关系;新旧 " -"命名空间之间不会建立传播关系。各副本直接持有原生文件系统后端,共享目录项和 文件内容,但挂载策略和写入者计数独立。挂载 ID 从 VFS " -"全局序列分配,传播组号 仍仅在各自的命名空间内有意义。" +"由调用方管理的空命名空间中。它保留覆盖层和不可绑定挂载。共享挂载的副本加入 原对等组;slave " +"副本保留指向活动上游组成员的弱引用。各副本直接持有原生文件 系统后端,共享目录项和文件内容,但挂载策略和写入者计数独立。挂载 ID 和对等 " +"组号各自从 VFS 全局序列分配。" msgstr "" -"With exclusive VFS execution ownership, ``vfs_namespace_snapshot()`` " -"copies an active mount tree into an empty namespace at a stable address " -"owned by the caller. It preserves overmounts, unbindable mounts, and " -"propagation relationships within the graph. There is no propagation " -"between the original and copied namespaces. Each copy directly pins the " -"native filesystem backend and shares dentries and file contents, but " -"keeps its own mount policy and writer count. The VFS assigns mount IDs " -"from a global sequence; propagation group IDs remain namespace-local." +"Under exclusive VFS execution ownership, ``vfs_namespace_snapshot()`` " +"copies the active mount tree into an empty, caller-owned namespace at a " +"stable address. It preserves overmounts and unbindable mounts. A shared " +"mount's copy joins the original peer group; a slave's copy retains a weak" +" link to a live member of its upstream group. Each copy directly pins the" +" native filesystem backend and shares dentries and file contents, but has" +" its own mount policy and writer count. Mount IDs and peer group IDs are " +"allocated from separate VFS-wide sequences." msgid "" "可选的 root 和 cwd 引用按原挂载对象和目录项重新绑定,而不是重新查找路径; " @@ -46,6 +46,33 @@ msgstr "" "replacements are published only after all allocations succeed. Failure " "leaves the original tree, destination, paths, and ID cursor unchanged." +msgid "跨命名空间传播" +msgstr "Propagation across namespaces" + +msgid "" +"VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载图的寿命;成员 " +"退出或摘除时,其他命名空间的下游挂载也会改接到剩余对等成员,或在组消失时 改接到原上游组。没有上游时清除该关系。" +msgstr "" +"The VFS tracks only published shared and slave mounts. Propagation links " +"do not extend the lifetime of a mount graph. When a member leaves or is " +"detached, downstream mounts in other namespaces also switch to a " +"surviving peer, or to the old upstream group if the group disappears. " +"Without an upstream group, the link is cleared." + +msgid "" +"跨图的挂载、bind 与 move 副本作为一个批次发布;分配失败时所有图和两个 ID " +"游标保持不变。普通卸载先检查所有图中选中的挂载是否有忙引用,再检查最终后端 " +"是否允许卸载;失败时不摘除任何挂载。延迟卸载不分配内存,保留接收方无关的 覆盖挂载。挂载表的传播字段见 :doc:`../userspace-" +"api/abi`。" +msgstr "" +"Mount, bind, and move copies spanning multiple graphs are published as a " +"single batch. Allocation failure leaves every graph and both ID cursors " +"unchanged. Ordinary unmount checks busy references on selected mounts in " +"every graph before asking the final backends whether they can unmount. If" +" either check fails, nothing is detached. Lazy unmount allocates no " +"memory and preserves unrelated overmounts on receivers. See :doc" +":`../userspace-api/abi` for the mount table fields." + msgid "任务、路径查找与 proc 视图" msgstr "Tasks, pathname lookup, and proc views" @@ -101,10 +128,7 @@ msgstr "" "``vfs_namespace_destroy()`` refuses to destroy a graph with outstanding " "graph or external path references." -msgid "" -"这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换,也未实现跨图 peer/slave 传播或 ``mountinfo`` 的 " -"``propagate_from`` 字段。" +msgid "这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换。" msgstr "" -"These interfaces are internal to the kernel. Userspace cannot yet create or " -"switch mount namespaces. Cross-graph peer/slave propagation and the " -"``mountinfo`` field ``propagate_from`` are not implemented." +"These interfaces are internal to the kernel. Userspace cannot yet create " +"or switch mount namespaces." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 934f55f9..1c4f4995 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -80,7 +80,6 @@ msgstr "A readonly transition returns EBUSY without changing policy while any re msgid "文件绑定尚不支持,返回明确错误。" msgstr "File binds are not yet supported and return an explicit error." - msgid "按任务选择 uname 系统名" msgstr "Selecting the uname system name per task" @@ -105,17 +104,59 @@ msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` creates a peer group for msgid "``MS_PRIVATE`` 清除目标的对等组和上游关系;``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员时,其下游改接到该组 原来的上游组,若无上游则不再接收传播。" msgstr "``MS_PRIVATE`` removes the target from its peer and master groups. ``MS_UNBINDABLE`` also rejects the target as a bind source and prunes the subtree during recursive bind. When an upstream group loses its last member, its receivers follow that group's previous master or stop receiving events if there is none." -msgid "``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。" -msgstr "``MS_REC`` applies the selected type to the mount and its existing descendants without putting distinct submounts into one group or changing existing shared group IDs. A type change requires ``CAP_SYS_ADMIN`` and an exact mount root, and does not change mount access policy or filesystem state. ``/proc/self/mountinfo`` reports the optional tags ``shared:``, ``master:``, or ``unbindable``. It does not yet report ``propagate_from``." +msgid "" +"``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 " +"``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。对等组号在 VFS 中全局分配。挂载信息报告 " +"``shared:``、``master:`` 或 ``unbindable``。对 slave,``master:`` " +"始终指向即时上游组;如果查看根下可见的最近上游组与该组不同,另报告 ``propagate_from:``。如果没有可见上游组,则不报告 " +"``propagate_from``。" +msgstr "" +"``MS_REC`` applies the requested type to the target and its existing " +"submounts. It neither merges different submounts into one group nor " +"changes an existing shared group ID. Changing the type requires " +"``CAP_SYS_ADMIN`` and a mount root; it does not alter mount access policy" +" or filesystem state. The VFS assigns peer group IDs globally. Mount info" +" reports ``shared:``, ``master:``, or ``unbindable``. For a " +"slave, ``master:`` always names the immediate upstream group. If the " +"nearest upstream group visible below the viewing root differs from it, " +"``propagate_from:`` names that group. With no visible upstream group," +" ``propagate_from`` is omitted." -msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 保持不变。目前仅支持同一挂载命名空间内的传播。" -msgstr "New mounts and binds (including recursive binds) under a shared parent are copied to peers and downstream slaves at the same directory object. Events do not go upstream. A receiver whose bind root excludes the target is skipped, but its downstream mounts with matching directories can still receive a copy. Copies within one receiving peer group share an ID and follow the nearest upstream copy group. New filesystem mounts under nonshared parents are private by default. All copies are published together; allocation failure leaves none attached. At an occupied receiving slot, the copy is inserted beneath the existing mount without changing what is visible. Propagation is supported only within a single mount namespace." +msgid "" +"在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 " +"bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 " +"上游副本组。接收方可以位于其他活动挂载命名空间。非共享父挂载下创建的新文件 系统挂载默认是 " +"private。所有副本一起发布;分配失败不留下部分挂载。接收位置 已有挂载时,副本插入已有挂载下方,原可见内容保持不变。" +msgstr "" +"When a mount or bind (including recursive bind) is created under a shared" +" parent, peers and downstream slaves receive copies at the same directory" +" object. Events do not propagate upstream. A receiver whose bind root " +"excludes the directory is skipped, without blocking downstream receivers " +"that contain it. Copies in a receiving peer group share an ID and follow " +"the nearest upstream copy group. Receivers may be in other active mount " +"namespaces. A new filesystem mount under a nonshared parent is private by" +" default. All copies publish together; an allocation failure leaves no " +"partial mounts. A copy received at an already mounted location goes below" +" the existing mount, leaving the visible content unchanged." msgid "``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, 为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable 挂载的子树移入共享父挂载, 返回 EINVAL。" msgstr "``MS_MOVE`` into a shared parent preserves the original tree’s mount IDs, existing peer groups, upstream relationships, and held paths. It assigns a separate peer group to each original that is not already shared and copies the entire tree to receivers. Allocation failure leaves locations, groups, and receiver covers unchanged. Moving out of a shared parent, or moving a subtree containing an unbindable mount into one, returns EINVAL." -msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。与事件无关的子挂载通常使该接收分支保留;但覆盖 副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标子树中的 每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方保留的 挂载可以继续使用其后端,即使发起挂载已被摘除。" -msgstr "An unmount propagates from the target’s parent to the matching mountpoints. An ordinary unmount returns EBUSY without removing any mount if a removable receiver still has an open path. Unrelated submounts normally keep a receiver attached, but an overmount on the copy's root does not prevent removal of the copy and stays visible. Lazy unmount propagates each mount in the requested subtree without waiting for open paths and likewise preserves unrelated receiver mounts. A retained receiver can still use its backing even after the initiating attachment is detached." +msgid "" +"卸载从目标挂载的父挂载传播到对应位置;普通卸载在任一选中的挂载仍有忙引用, " +"或最终后端拒绝卸载时失败,且不移除任何挂载。与事件无关的子挂载通常使该接收 " +"分支保留;但覆盖副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标 " +"子树中的每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方 保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" +msgstr "" +"Unmount propagates from the target mount's parent to the corresponding " +"locations. Ordinary unmount fails without detaching anything if any " +"selected mount has a busy reference or a final backend rejects the " +"unmount. Unrelated child mounts normally keep a receiving branch " +"attached, but an overmount at a copy's root stays visible without " +"blocking that copy's removal. Lazy unmount propagates an event for every " +"mount in the target subtree, does not wait for open paths, and also " +"preserves unrelated mounts on receivers. Preserved mounts continue to use" +" the backend even after the initiating mount is detached." msgid "延迟卸载" msgstr "Lazy Unmount" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index c56d64d3..267fced5 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -21,13 +21,15 @@ msgstr "マウント名前空間のスナップショット" msgid "" "``vfs_namespace_snapshot()`` 在独占 VFS 执行权下,将活动挂载树复制到地址固定、 " -"由调用方管理的空命名空间中。它保留覆盖层、不可绑定挂载和图内传播关系;新旧 " -"命名空间之间不会建立传播关系。各副本直接持有原生文件系统后端,共享目录项和 文件内容,但挂载策略和写入者计数独立。挂载 ID 从 VFS " -"全局序列分配,传播组号 仍仅在各自的命名空间内有意义。" +"由调用方管理的空命名空间中。它保留覆盖层和不可绑定挂载。共享挂载的副本加入 原对等组;slave " +"副本保留指向活动上游组成员的弱引用。各副本直接持有原生文件 系统后端,共享目录项和文件内容,但挂载策略和写入者计数独立。挂载 ID 和对等 " +"组号各自从 VFS 全局序列分配。" msgstr "" -"``vfs_namespace_snapshot()`` は VFS " -"の排他的な実行権を保持した状態で、稼働中のマウントツリーを、呼び出し側が管理する固定アドレスの空の名前空間にコピーします。重ね掛け、バインド不可のマウント、グラフ内の伝播関係を保持しますが、コピー元とコピー先の名前空間の間では伝播しません。各コピーはネイティブのファイルシステムバックエンドを直接参照し、ディレクトリエントリとファイルの内容を共有します。マウントポリシーと書き込み参照数は独立しています。マウント" -" ID は VFS 全体で一意の連番から割り当て、伝播グループ ID は名前空間内だけで有効です。" +"VFS の排他的実行権を保持した状態で、``vfs_namespace_snapshot()`` " +"は稼働中のマウントツリーを、呼び出し側が管理する固定アドレスの空の名前空間に複製します。上に重なったマウントとバインド不可のマウントは維持されます。共有マウントの複製は元のピアグループに加わり、slave" +" " +"の複製は稼働中の上流グループのメンバーへの弱参照を維持します。各複製はネイティブのファイルシステムバックエンドを直接保持し、ディレクトリエントリとファイル内容を共有しますが、マウントポリシーと書き込み元の数は独立しています。マウント" +" ID とピアグループ ID はそれぞれ VFS 全体の連番で割り当てられます。" msgid "" "可选的 root 和 cwd 引用按原挂载对象和目录项重新绑定,而不是重新查找路径; " @@ -40,6 +42,26 @@ msgstr "" "を返します。すべての割り当てに成功してから、新しいツリーを公開しパスを差し替えます。失敗しても元のツリー、コピー先、パス、ID " "のカーソルは変わりません。" +msgid "跨命名空间传播" +msgstr "名前空間をまたぐ伝播" + +msgid "" +"VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载图的寿命;成员 " +"退出或摘除时,其他命名空间的下游挂载也会改接到剩余对等成员,或在组消失时 改接到原上游组。没有上游时清除该关系。" +msgstr "" +"VFS は公開済みの shared および slave " +"マウントのみを登録します。伝播の関係はマウントグラフの寿命を延ばしません。メンバーが離脱または切り離されると、他の名前空間の下流マウントも残っているピアに切り替わり、グループが消滅した場合は元の上流グループに切り替わります。上流がなければ関係を解除します。" + +msgid "" +"跨图的挂载、bind 与 move 副本作为一个批次发布;分配失败时所有图和两个 ID " +"游标保持不变。普通卸载先检查所有图中选中的挂载是否有忙引用,再检查最终后端 " +"是否允许卸载;失败时不摘除任何挂载。延迟卸载不分配内存,保留接收方无关的 覆盖挂载。挂载表的传播字段见 :doc:`../userspace-" +"api/abi`。" +msgstr "" +"複数のグラフにまたがる mount、bind、move の複製は一括して公開されます。割り当てに失敗しても、すべてのグラフと両方の ID " +"採番位置は変わりません。通常のアンマウントでは全グラフで対象マウントに使用中の参照がないことを確認してから、最後のバックエンドがアンマウントを許可するかを確認します。どちらかの確認に失敗すると何も切り離しません。遅延アンマウントはメモリを割り当てず、受信側で無関係な上層マウントを維持します。マウント表の伝播フィールドは" +" :doc:`../userspace-api/abi` を参照してください。" + msgid "任务、路径查找与 proc 视图" msgstr "タスク、パス検索と proc のビュー" @@ -85,9 +107,5 @@ msgstr "" "がアンマウントを伝播させずにツリー全体を切り離し、その後グラフ自体を解放します。保持中のパスは有効なままで、既存の遅延処理キューがバックエンドを後処理します。起動時とテスト用のグラフの記憶領域は引き続き呼び出し側が管理します。厳格な" " ``vfs_namespace_destroy()`` はグラフの参照や外部パス参照が残っている間は破棄を拒否します。" -msgid "" -"这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换,也未实现跨图 peer/slave 传播或 ``mountinfo`` 的 " -"``propagate_from`` 字段。" -msgstr "" -"これらはカーネル内部のインターフェースです。ユーザー空間からマウント名前空間を作成したり切り替えたりすることはまだできません。グラフ間の " -"peer/slave 伝播や、 ``mountinfo`` の ``propagate_from`` フィールドも未実装です。" +msgid "这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换。" +msgstr "これらのインターフェイスはカーネル内部専用です。ユーザー空間からマウント名前空間を作成または切り替えることはまだできません。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 60ed3f14..c4d483b6 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -73,7 +73,6 @@ msgstr "対象マウント上の通常ファイルが書き込み用に開かれ msgid "文件绑定尚不支持,返回明确错误。" msgstr "ファイルのバインドにはまだ対応せず、明示的なエラーを返します。" - msgid "按任务选择 uname 系统名" msgstr "タスクごとの uname システム名の選択" @@ -98,17 +97,43 @@ msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` は、共有されてい msgid "``MS_PRIVATE`` 清除目标的对等组和上游关系;``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员时,其下游改接到该组 原来的上游组,若无上游则不再接收传播。" msgstr "``MS_PRIVATE`` は対象のピアグループと上流グループとの関係を解除します。``MS_UNBINDABLE`` はさらにバインド元としての使用を禁止し、再帰バインドからそのサブツリーを除外します。上流グループの最後のメンバーが離脱すると、その下流は以前の上流グループを引き継ぎ、上流がなければイベントを受け取らなくなります。" -msgid "``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 ``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。" -msgstr "``MS_REC`` は選択した種別を対象と既存の子マウントに適用しますが、別々の子マウントを同じグループにまとめたり、既存の共有グループ ID を変更したりしません。種別の変更には ``CAP_SYS_ADMIN`` が必要で、対象はマウントのルートでなければなりません。アクセス方針やファイルシステムの状態は変わりません。``/proc/self/mountinfo`` はオプションフィールド ``shared:``、``master:``、``unbindable`` を表示します。``propagate_from`` はまだ表示しません。" +msgid "" +"``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 " +"``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。对等组号在 VFS 中全局分配。挂载信息报告 " +"``shared:``、``master:`` 或 ``unbindable``。对 slave,``master:`` " +"始终指向即时上游组;如果查看根下可见的最近上游组与该组不同,另报告 ``propagate_from:``。如果没有可见上游组,则不报告 " +"``propagate_from``。" +msgstr "" +"``MS_REC`` は対象と既存の子マウントに指定のタイプを適用します。異なる子マウントを一つのグループにまとめたり、既存の共有グループの ID" +" を変更したりしません。タイプの変更には ``CAP_SYS_ADMIN`` " +"が必要で、対象はマウントルートでなければなりません。アクセスポリシーやファイルシステムの状態は変わりません。ピアグループ ID は VFS " +"全体で一意に割り当てられます。マウント情報には ``shared:``、``master:``、または " +"``unbindable`` が表示されます。slave の ``master:`` " +"は常に直近の上流グループを示します。表示ルートの下で見える最も近い上流グループがそれと異なる場合は、そのグループを " +"``propagate_from:`` で示します。見える上流グループがなければ ``propagate_from`` は表示されません。" -msgid "在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; 分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 保持不变。目前仅支持同一挂载命名空间内的传播。" -msgstr "共有の親マウントの下でマウントやバインド(再帰バインドを含む)を作成すると、ピアと下流のスレーブは同じディレクトリオブジェクトの位置にコピーを受け取ります。イベントは上流には伝わりません。対象をバインドルートに含まない受信側はスキップされますが、対応するディレクトリを含む下流には伝播します。同じ受信ピアグループ内のコピーは ID を共有し、最も近い上流のコピーグループに従います。非共有の親の下の新規ファイルシステムマウントは既定でプライベートです。コピーはすべて一括して公開され、割り当てに失敗しても一部だけが残ることはありません。受信位置に既存のマウントがある場合、コピーはその下に挿入され、見える内容は変わりません。伝播は単一のマウント名前空間内に限られます。" +msgid "" +"在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 " +"bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 " +"上游副本组。接收方可以位于其他活动挂载命名空间。非共享父挂载下创建的新文件 系统挂载默认是 " +"private。所有副本一起发布;分配失败不留下部分挂载。接收位置 已有挂载时,副本插入已有挂载下方,原可见内容保持不变。" +msgstr "" +"共有の親の下でマウントやバインド(再帰バインドを含む)を作成すると、ピアと下流の slave " +"は同じディレクトリオブジェクトで複製を受け取ります。イベントは上流には伝播しません。対象が受信側のバインドルートの外にある場合は、その受信側のみをスキップし、対象を含む下流の受信側は妨げません。同じ受信ピアグループの複製は同じ" +" ID " +"を持ち、最も近い上流の複製グループに従います。受信側は別の稼働中のマウント名前空間にあっても構いません。非共有の親の下で新しいファイルシステムをマウントすると、既定では" +" private " +"になります。複製は一括して公開され、割り当てに失敗しても一部だけが残ることはありません。受信位置に既存のマウントがある場合、複製はその下に挿入され、見えている内容は変わりません。" msgid "``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, 为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable 挂载的子树移入共享父挂载, 返回 EINVAL。" msgstr "``MS_MOVE`` で共有の親の下へ移動しても、元のサブツリーのマウント ID、既存のピアグループ、上流関係、保持中のパスは変わりません。まだ共有されていない元のマウントごとに別々のピアグループを割り当て、受信側にはサブツリー全体をコピーします。割り当てに失敗しても、位置、グループ、受信側の既存のオーバーマウントは変わりません。共有の親から移動する場合や、バインド不可のマウントを含むサブツリーを共有の親の下へ移動する場合は、EINVAL を返します。" -msgid "卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 时返回 EBUSY,不移除任何挂载。与事件无关的子挂载通常使该接收分支保留;但覆盖 副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标子树中的 每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方保留的 挂载可以继续使用其后端,即使发起挂载已被摘除。" -msgstr "アンマウントは対象の親から対応するマウントポイントへ伝播します。通常のアンマウントでは、取り外し対象となる受信側に開いたパスがあれば、どのマウントも取り外さず EBUSY を返します。通常は無関係な子マウントがある受信側を残しますが、コピーのルートを覆うマウントはコピーの取り外しを妨げず、引き続き見えます。遅延アンマウントは開いたパスを待たずに対象サブツリー内の各マウントのイベントを伝播し、同様に受信側の無関係なマウントを残します。受信側に残ったマウントは、操作元が切り離された後もバックエンドを使えます。" +msgid "" +"卸载从目标挂载的父挂载传播到对应位置;普通卸载在任一选中的挂载仍有忙引用, " +"或最终后端拒绝卸载时失败,且不移除任何挂载。与事件无关的子挂载通常使该接收 " +"分支保留;但覆盖副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标 " +"子树中的每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方 保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" +msgstr "アンマウントは対象マウントの親から対応する位置へ伝播します。通常のアンマウントは、対象のいずれかに使用中の参照があるか、最後のバックエンドがアンマウントを拒否すると、何も切り離さずに失敗します。無関係な子マウントがある受信側の枝は通常そのまま残ります。ただし、複製のルートに重なるマウントは複製の切り離しを妨げず、その後も表示されます。遅延アンマウントは対象サブツリー内のマウントごとにイベントを伝播し、開いているパスを待たず、受信側の無関係なマウントを残します。開始側のマウントが切り離された後も、残ったマウントはバックエンドを利用できます。" msgid "延迟卸载" msgstr "遅延アンマウント" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index af0beaa3..c12438aa 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -75,26 +75,28 @@ bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员 ``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 ``CAP_SYS_ADMIN`` 且目标为挂载根, -不改变挂载访问策略或文件系统状态。``/proc/self/mountinfo`` 报告可选字段 -``shared:``、``master:`` 或 ``unbindable``;``propagate_from`` 尚不报告。 +不改变挂载访问策略或文件系统状态。对等组号在 VFS 中全局分配。挂载信息报告 +``shared:``、``master:`` 或 ``unbindable``。对 slave,``master:`` +始终指向即时上游组;如果查看根下可见的最近上游组与该组不同,另报告 +``propagate_from:``。如果没有可见上游组,则不报告 ``propagate_from``。 在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 -上游副本组。非共享父挂载下创建的新文件系统挂载默认是 private。所有副本一起发布; -分配失败不留下部分挂载。接收位置已有挂载时,副本插入已有挂载下方,原可见内容 -保持不变。目前仅支持同一挂载命名空间内的传播。 +上游副本组。接收方可以位于其他活动挂载命名空间。非共享父挂载下创建的新文件 +系统挂载默认是 private。所有副本一起发布;分配失败不留下部分挂载。接收位置 +已有挂载时,副本插入已有挂载下方,原可见内容保持不变。 ``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, 为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable 挂载的子树移入共享父挂载, 返回 EINVAL。 -卸载从目标挂载的父挂载传播到对应位置;普通卸载在可移除的接收挂载仍有打开路径 -时返回 EBUSY,不移除任何挂载。与事件无关的子挂载通常使该接收分支保留;但覆盖 -副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标子树中的 -每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方保留的 -挂载可以继续使用其后端,即使发起挂载已被摘除。 +卸载从目标挂载的父挂载传播到对应位置;普通卸载在任一选中的挂载仍有忙引用, +或最终后端拒绝卸载时失败,且不移除任何挂载。与事件无关的子挂载通常使该接收 +分支保留;但覆盖副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标 +子树中的每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方 +保留的挂载可以继续使用其后端,即使发起挂载已被摘除。 延迟卸载 ======== diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index b94ad5f3..5397d1d3 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -25,7 +25,9 @@ struct vfs_mount { struct vfs_namespace *ns; struct vfs_mount *next,*notify_next; struct vfs_mount **notify_link; - struct vfs_mount *master; /* Weak edge to a live member of the upstream peer group. */ + struct vfs_mount *master; /* Weak edge to an upstream peer in any live graph. */ + struct vfs_mount *propagation_next,**propagation_link; /* Weak live participant list. */ + struct vfs_mount *unmount_next; /* Selected or vetoed candidates until batch end. */ struct vfs_mount *staged_cover; /* Existing receiver cover; only set before batch commit. */ struct vfs_path point,bind_source; struct vfs_dentry *root; @@ -37,8 +39,7 @@ struct vfs_mount { uint64_t propagation_pins; /* Shared backend lifetime references, not open paths. */ uint64_t writers; /* Open writable file descriptions on this attachment. */ bool propagation_backing; /* This bind_source is a replica or snapshot lifetime pin. */ - bool unmount_selected; /* Scratch under the namespace execution writer. */ - bool lift_cover; /* Scratch: retain this overmount above a removed receiver. */ + bool unmount_selected; /* Scratch under the VFS execution writer. */ bool propagation_copy; /* Receiver can detach beneath an unrelated root cover. */ bool unbindable; /* Pruned by recursive bind; never a valid bind source. */ bool lazy_detached; /* No namespace edges; retained paths still work. */ @@ -50,6 +51,18 @@ struct vfs_mount { * publication or snapshot never advances this cursor. */ uint64_t vfs_mount_next_id(void); +/** @brief Read the VFS-wide peer group ID cursor under execution ownership. + * @return Next unassigned peer group, or zero after exhaustion. Only a + * successful propagation change or mount transaction advances it. + */ +uint64_t vfs_mount_next_peer_id(void); +/** @brief Find the nearest upstream group represented below a viewing root. + * @param mount Live attachment whose weak master chain is borrowed. + * @param root Retained viewing root in the same namespace as mount. + * @return The group's global ID, or zero if none is visible in this view. + * Execution ownership required; no I/O, references or allocations. + */ +uint64_t vfs_mount_dominating_group(const struct vfs_mount *mount,const struct vfs_path *root); bool vfs_path_valid(const struct vfs_path *path); /** @brief Admit a held path for pathname access, not mount topology changes. * @param ns Borrowed execution-owned lookup namespace. diff --git a/fs/vfs/mount_table.c b/fs/vfs/mount_table.c index 3a5fbd3d..ffd0ab2c 100644 --- a/fs/vfs/mount_table.c +++ b/fs/vfs/mount_table.c @@ -67,7 +67,7 @@ static void mount_options(struct mount_text *text,uint64_t flags,bool mountinfo, * @param text Borrowed bounded stream state. @param workspace Two VFS_PATH_MAX buffers. * @return Zero, hidden-root success or negative path-format errno. No * allocation/I/O/ownership change; access flags and optional propagation - * tags are read from their actual owners. + * tags are read from their actual owners and scoped to the viewing root. */ static int mount_line(const struct vfs_namespace *ns,const struct vfs_path *root, const struct vfs_mount *mount,bool info,struct mount_text *text,char *workspace) @@ -100,7 +100,11 @@ static int mount_line(const struct vfs_namespace *ns,const struct vfs_path *root mount_emit(text," shared:");mount_number(text,mount->peer_group); } else if(mount->unbindable)mount_emit(text," unbindable"); if(mount->master) { - mount_emit(text," master:");mount_number(text,mount->master->peer_group); + uint64_t master=mount->master->peer_group,dominant=vfs_mount_dominating_group(mount,root); + mount_emit(text," master:");mount_number(text,master); + if(dominant && dominant!=master) { + mount_emit(text," propagate_from:");mount_number(text,dominant); + } } mount_emit(text," - ");mount_emit(text,filesystem);mount_emit(text," "); mount_field(text,source);mount_emit(text," ");mount_options(text,vfs_super_flags(mount),true,true);mount_emit(text,"\n"); diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index 23fc590a..f6fce996 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -8,7 +8,10 @@ static struct vfs_mount *retired_mounts,**retired_tail=&retired_mounts; static uint64_t retired_count; static bool reclaim_active; -static uint64_t next_mount_id=1; +static uint64_t next_mount_id=1,next_peer_id=1; +/* Only published shared/slave attachments participate, in any namespace. + * The kernel execution writer serializes every mutation and teardown. */ +static struct vfs_mount *propagation_mounts; /** @brief Append one detached, rootless mount to the execution-owned FIFO. * @param mount Privately owned final mount, not already queued; next is unused. @@ -228,6 +231,11 @@ int vfs_path_anonymous(struct vfs_mount *mount,const struct storage_node *node,s */ uint64_t vfs_mount_next_id(void) {return next_mount_id;} +/** @brief Observe the next globally unique peer group ID without reserving it. + * @return Next unassigned group or zero when exhausted; execution-owned. + */ +uint64_t vfs_mount_next_peer_id(void) {return next_peer_id;} + /** @brief Retain an unpublished mount as the permanent namespace anchor. * @param ns Borrowed empty namespace. @param root Borrowed unpublished root. * @return Zero or negative errno, including exhaustion of VFS-wide mount IDs. @@ -238,7 +246,7 @@ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root) if(!ns || ns->root || ns->mounts || !root || root->ns || root->point.mount || root->lazy_detached)return -EINVAL; if(!next_mount_id)return -EOVERFLOW; ++root->references;root->ns=ns;root->id=next_mount_id++;root->next=NULL; - ns->root=root;ns->mounts=root;ns->next_peer_id=1;return 0; + ns->root=root;ns->mounts=root;return 0; } /** @brief Find the attachment immediately covering an exact retained slot. @@ -281,21 +289,47 @@ static bool vfs_mount_below(const struct vfs_mount *root,const struct vfs_mount return false; } -/** @brief Leave a peer group without orphaning its downstream attachments. - * @param ns Borrowed execution-owned namespace. +/** @brief Synchronize one live or departing mount's weak list membership. + * @param mount Attachment with updated namespace and propagation fields. + * Only shared and slave mounts in a live namespace are registered; no mount + * or namespace reference is taken. Requires the VFS execution writer. + */ +static void vfs_update_propagation(struct vfs_mount *mount) +{ + if(mount->ns && (mount->peer_group || mount->master)) { + if(mount->propagation_link)return; + mount->propagation_next=propagation_mounts; + mount->propagation_link=&propagation_mounts; + if(propagation_mounts)propagation_mounts->propagation_link=&mount->propagation_next; + propagation_mounts=mount; + } else if(mount->propagation_link) { + *mount->propagation_link=mount->propagation_next; + if(mount->propagation_next)mount->propagation_next->propagation_link=mount->propagation_link; + mount->propagation_link=NULL;mount->propagation_next=NULL; + } +} + +/** @brief Leave a global peer group without orphaning downstream attachments. * @param mount Live departing member (a nonmember is unchanged). * @return A live peer, or the old master if no peer remains. If the group * survives, its receivers stay with the group; otherwise they inherit its - * master. These weak edges never pin a mount or a backend. + * master. The caller must finish updating the departing mount's membership. + * These weak edges never pin a mount or a namespace. */ -static struct vfs_mount *vfs_leave_peer_group(struct vfs_namespace *ns,struct vfs_mount *mount) +static struct vfs_mount *vfs_leave_peer_group(struct vfs_mount *mount) { struct vfs_mount *upstream=mount->master; if(!mount->peer_group)return upstream; - for(struct vfs_mount *peer=ns->mounts;peer;peer=peer->next) - if(peer!=mount && peer->peer_group==mount->peer_group){upstream=peer;break;} - for(struct vfs_mount *other=ns->mounts;other;other=other->next) - if(other->master==mount)other->master=upstream; + for(struct vfs_mount *peer=propagation_mounts;peer;peer=peer->propagation_next) { + if(peer==mount || peer->peer_group!=mount->peer_group)continue; + upstream=peer; + if(peer->root==mount->root)break; + } + for(struct vfs_mount *other=propagation_mounts,*next;other;other=next) { + next=other->propagation_next; + if(other->master!=mount)continue; + other->master=upstream;vfs_update_propagation(other); + } mount->peer_group=0; return upstream; } @@ -305,9 +339,10 @@ static struct vfs_mount *vfs_leave_peer_group(struct vfs_namespace *ns,struct vf * @param path Retained exact root of the selected live mount. * @param flags One propagation selector and optional MS_REC. * @return Zero or negative errno. The whole change is validated before - * editing any mount or advancing the group ID counter. Making a slave retains - * an upstream group if available; private and unbindable clear the selected - * attachment's propagation membership. + * editing any mount or advancing the global group ID counter. Making a slave + * retains an upstream group if available; private and unbindable clear the + * selected attachment's propagation membership. All downstream graphs are + * relinked before a selected mount loses its group. * No allocation, backend callback or access-policy change. */ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *path,uint64_t flags) @@ -318,7 +353,7 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa return -EINVAL; struct vfs_mount *root=path->mount; bool recursive=(flags&MS_REC)!=0; - uint64_t next=ns->next_peer_id; + uint64_t next=next_peer_id; if(type==MS_SHARED) { for(struct vfs_mount *mount=recursive ? ns->mounts : root;mount; mount=recursive ? mount->next : NULL) { @@ -331,15 +366,16 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa mount=recursive ? mount->next : NULL) { if(!vfs_mount_below(root,mount))continue; if(type==MS_SHARED) { - if(!mount->peer_group)mount->peer_group=ns->next_peer_id++; + if(!mount->peer_group)mount->peer_group=next_peer_id++; mount->unbindable=false; } else if(type==MS_SLAVE) { - if(mount->peer_group)mount->master=vfs_leave_peer_group(ns,mount); + if(mount->peer_group)mount->master=vfs_leave_peer_group(mount); } else { - vfs_leave_peer_group(ns,mount); + vfs_leave_peer_group(mount); mount->master=NULL; mount->unbindable=type==MS_UNBINDABLE; } + vfs_update_propagation(mount); } return 0; } @@ -402,14 +438,16 @@ static void vfs_replace_mountpoint(struct vfs_mount *mount,const struct vfs_path } /** @brief Roll back all staged mounts or publish them together without allocation. - * @param ns Borrowed execution-owned namespace. + * @param snapshot New graph when staging a namespace snapshot, otherwise NULL. * @param batch Owned unpublished mounts and tentative ID counters. * @param status Nonzero to discard, zero to commit all changes. * @return The supplied status. Rollback releases descendants before parents; - * neither graph nor the ID cursors change on error. At commit, rehang - * any existing receiver stack on its newly inserted mount's root. + * no graph or ID cursor changes on error. At commit, publish in reverse + * staging order so a new child can inherit its parent's namespace, or use + * the supplied snapshot namespace for the entire tree. Rehang existing + * receiver stacks on their newly inserted mount roots. */ -static int vfs_finish_mount_batch(struct vfs_namespace *ns,struct vfs_mount_batch *batch,int status) +static int vfs_finish_mount_batch(struct vfs_namespace *snapshot,struct vfs_mount_batch *batch,int status) { if(status) { while(batch->pending) { @@ -418,9 +456,16 @@ static int vfs_finish_mount_batch(struct vfs_namespace *ns,struct vfs_mount_batc } return status; } - struct vfs_mount **tail=&batch->pending; - for(;*tail;tail=&(*tail)->next) { - struct vfs_mount *mount=*tail;mount->ns=ns; + struct vfs_mount *ordered=NULL; + while(batch->pending) { + struct vfs_mount *mount=batch->pending;batch->pending=mount->next; + mount->next=ordered;ordered=mount; + } + while(ordered) { + struct vfs_mount *mount=ordered;ordered=mount->next; + struct vfs_namespace *ns=snapshot ? snapshot : mount->point.mount->ns; + mount->ns=ns;mount->next=ns->mounts;ns->mounts=mount; + vfs_update_propagation(mount); if(mount->staged_cover) { struct vfs_path root={mount,mount->root}; vfs_replace_mountpoint(mount->staged_cover,&root); @@ -428,8 +473,7 @@ static int vfs_finish_mount_batch(struct vfs_namespace *ns,struct vfs_mount_batc } if(!mount->notify_link && vfs_notify_mount_created)vfs_notify_mount_created(mount); } - if(batch->pending){*tail=ns->mounts;ns->mounts=batch->pending;} - next_mount_id=batch->next_id;ns->next_peer_id=batch->next_peer_id; + next_mount_id=batch->next_id;next_peer_id=batch->next_peer_id; return 0; } @@ -480,8 +524,9 @@ static void vfs_snapshot_rebind(struct vfs_path *path,struct vfs_mount *copy) * @param root Optional owned task root to rebind, empty or detached allowed. * @param cwd Optional owned working directory to rebind, empty or detached allowed. * @return Zero or negative errno before publishing any change. Copies retain - * the native backing, not intermediate attachment references. Topology and - * weak propagation edges are translated only after every allocation succeeds. + * the native backing, not intermediate attachment references. Topology is + * translated and the copies join their original peers and upstream groups + * only after every allocation succeeds. */ int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace *source, struct vfs_path *root,struct vfs_path *cwd) @@ -492,7 +537,7 @@ int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace if(!rc)rc=vfs_snapshot_path_check(source,cwd); if(rc)return rc; - struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=source->next_peer_id}; + struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=next_peer_id}; struct vfs_mount **tail=&batch.pending; for(struct vfs_mount *mount=source->mounts;mount;mount=mount->next) { if(!batch.next_id){rc=-EOVERFLOW;break;} @@ -515,7 +560,7 @@ int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace copy->peer_group=mount->peer_group; copy->unbindable=mount->unbindable; copy->propagation_copy=mount->propagation_copy; - copy->master=vfs_snapshot_mount(source->mounts,batch.pending,mount->master); + copy->master=mount->master; struct vfs_path point={vfs_snapshot_mount(source->mounts,batch.pending,mount->point.mount), mount->point.dentry}; vfs_path_get(&point,©->point); @@ -566,9 +611,40 @@ static bool vfs_dentry_below(const struct vfs_dentry *dentry,const struct vfs_de return false; } +/** @brief Check whether a live mount root lies under a retained viewing path. + * @param mount Borrowed attachment in the viewing root's namespace. + * @param root Borrowed viewing boundary, which may be inside a mount. + * @return Whether retained parent and dentry edges reach the boundary. + * Does not replay paths or follow overmounts. + */ +static bool vfs_mount_under_root(const struct vfs_mount *mount,const struct vfs_path *root) +{ + const struct vfs_dentry *dentry=mount->root; + for(;mount!=root->mount;mount=mount->point.mount) { + if(!mount->point.mount || !vfs_dentry_below(dentry,mount->root))return false; + dentry=mount->point.dentry; + } + return vfs_dentry_below(dentry,root->dentry); +} + +/** @brief Find the closest upstream peer group with a mount in this view. + * @param mount Borrowed live attachment in the viewing namespace. + * @param root Retained root of the mount table view. + * @return Global group ID, even if the master itself is abroad, or zero if + * no upstream member lies within the view. Requires VFS execution ownership. + */ +uint64_t vfs_mount_dominating_group(const struct vfs_mount *mount,const struct vfs_path *root) +{ + for(const struct vfs_mount *master=mount->master;master;master=master->master) + for(const struct vfs_mount *peer=propagation_mounts;peer;peer=peer->propagation_next) + if(peer->peer_group==master->peer_group && peer->ns==mount->ns && vfs_mount_under_root(peer,root)) + return master->peer_group; + return 0; +} + /** @brief Measure the downward propagation distance from a shared origin. * @param origin Borrowed attachment sending the event. - * @param receiver Borrowed candidate attachment in the same namespace. + * @param receiver Borrowed live candidate attachment in any namespace. * @param depth Receives zero for peers, positive for downstream groups. * @return True for a peer or downstream receiver, including origin itself * if shared. Following upstream edges cannot route an event back upstream. @@ -598,7 +674,7 @@ static struct vfs_mount *vfs_staged_peer(const struct vfs_mount_batch *batch, if(receiver->peer_group==target->mount->peer_group)return origin; for(struct vfs_mount *mount=batch->pending;mount;mount=mount->next) { const struct vfs_mount *parent=mount->point.mount; - if(mount->point.dentry==target->dentry && parent->ns==receiver->ns && + if(mount->point.dentry==target->dentry && parent->ns && parent->peer_group==receiver->peer_group)return mount; } return NULL; @@ -678,8 +754,7 @@ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_pa } } -/** @brief Stage the peers and downstream receivers of one mount tree. - * @param ns Borrowed execution-owned namespace; live inventory stays fixed. +/** @brief Stage the peers and downstream receivers in all live namespaces. * @param batch Owns all prepared replicas and, for an attach or bind, the origin. * @param origin Borrowed event root, live at its old location for a move. * @param target Exact destination for the event root. @@ -690,13 +765,13 @@ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_pa * does not block eligible descendants from receiving the event. An existing * cover is reparented only at commit so it remains visible above the copy. */ -static int vfs_stage_propagation(struct vfs_namespace *ns,struct vfs_mount_batch *batch, +static int vfs_stage_propagation(struct vfs_mount_batch *batch, struct vfs_mount *origin,const struct vfs_path *target,bool recursive) { if(!target->mount->peer_group)return 0; for(uint64_t level=0;;++level) { bool deeper=false; - for(struct vfs_mount *peer=ns->mounts;peer;peer=peer->next) { + for(struct vfs_mount *peer=propagation_mounts;peer;peer=peer->propagation_next) { uint64_t depth; if(peer==target->mount || !vfs_propagation_depth(target->mount,peer,&depth) || !vfs_dentry_below(target->dentry,peer->root))continue; @@ -712,11 +787,11 @@ static int vfs_stage_propagation(struct vfs_namespace *ns,struct vfs_mount_batch if(!prior)return -EINVAL; struct vfs_path view={prior,prior->root}; struct vfs_mount *copy; - struct vfs_mount *inventory=prior->ns ? ns->mounts : batch->pending; + struct vfs_mount *inventory=prior->ns ? prior->ns->mounts : batch->pending; int rc=vfs_stage_bind_tree(batch,&view,&point,inventory,recursive,peer->peer_group!=0, kind,©); if(rc)return rc; - struct vfs_mount *cover=vfs_covering(ns,&point); + struct vfs_mount *cover=vfs_covering(peer->ns,&point); if(cover!=origin)copy->staged_cover=cover; } if(!deeper)return 0; @@ -738,7 +813,7 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const stru if(target->dentry->disconnected)return -ENOENT; if(mount->ns || mount->point.mount || mount->lazy_detached || vfs_covering(ns,target))return -EBUSY; if(!next_mount_id)return -EOVERFLOW; - struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=ns->next_peer_id}; + struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=next_peer_id}; uint64_t old_id=mount->id,old_group=mount->peer_group; if(target->mount->peer_group) { if(!batch.next_peer_id)return -EOVERFLOW; @@ -746,8 +821,8 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const stru } ++mount->references; vfs_stage_mount(&batch,mount,target); - int rc=vfs_stage_propagation(ns,&batch,mount,target,false); - rc=vfs_finish_mount_batch(ns,&batch,rc); + int rc=vfs_stage_propagation(&batch,mount,target,false); + rc=vfs_finish_mount_batch(NULL,&batch,rc); if(rc){mount->id=old_id;mount->peer_group=old_group;} return rc; } @@ -769,12 +844,12 @@ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, if(source->dentry->disconnected || target->dentry->disconnected)return -ENOENT; if(vfs_covering(ns,target))return -EBUSY; - struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=ns->next_peer_id}; + struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=next_peer_id}; struct vfs_mount *first; bool shared=target->mount->peer_group!=0; int rc=vfs_stage_bind_tree(&batch,source,target,ns->mounts,recursive,shared,VFS_COPY_BIND,&first); - if(!rc)rc=vfs_stage_propagation(ns,&batch,first,target,recursive); - return vfs_finish_mount_batch(ns,&batch,rc); + if(!rc)rc=vfs_stage_propagation(&batch,first,target,recursive); + return vfs_finish_mount_batch(NULL,&batch,rc); } /** @brief Publish one directory view without copying submounts. @@ -811,21 +886,21 @@ static int vfs_move_into_shared(struct vfs_namespace *ns,struct vfs_mount *origi for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) if(mount->unbindable && vfs_mount_below(origin,mount))return -EINVAL; - struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=ns->next_peer_id}; + struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=next_peer_id}; int rc=0; for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { if(mount->peer_group || !vfs_mount_below(origin,mount))continue; if(!batch.next_peer_id){rc=-EOVERFLOW;break;} mount->staged_peer_group=batch.next_peer_id++; } - if(!rc)rc=vfs_stage_propagation(ns,&batch,origin,target,true); + if(!rc)rc=vfs_stage_propagation(&batch,origin,target,true); for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { if(!mount->staged_peer_group)continue; - if(!rc)mount->peer_group=mount->staged_peer_group; + if(!rc){mount->peer_group=mount->staged_peer_group;vfs_update_propagation(mount);} mount->staged_peer_group=0; } if(!rc)vfs_replace_mountpoint(origin,target); - return vfs_finish_mount_batch(ns,&batch,rc); + return vfs_finish_mount_batch(NULL,&batch,rc); } /** @brief Relocate a mount tree intact, propagating it under a shared parent. @@ -853,20 +928,26 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const vfs_replace_mountpoint(mount,target);return 0; } -/** @brief Disconnect a single leaf and relink its propagation receivers. - * @param ns Borrowed execution-owned namespace. - * @param mount Live leaf with no remaining dependents in ns. +/** @brief Clear a departing mount's membership and repair weak upstream edges. + * @param mount Attachment being unlinked under the VFS execution writer. + * Does not change its list link or release any references. */ -static void vfs_mount_detach(struct vfs_namespace *ns,struct vfs_mount *mount) +static void vfs_clear_mount_membership(struct vfs_mount *mount) { - vfs_leave_peer_group(ns,mount); - struct vfs_mount **link=&ns->mounts; - while(*link && *link!=mount)link=&(*link)->next; - if(*link)*link=mount->next; - struct vfs_path old=mount->point;mount->point=(struct vfs_path){0}; - mount->ns=NULL;mount->next=NULL;mount->master=NULL;mount->unbindable=false; - mount->propagation_copy=false; - vfs_path_put(&old);vfs_mount_put(mount); + vfs_leave_peer_group(mount); + mount->ns=NULL;mount->master=NULL;mount->unbindable=false;mount->propagation_copy=false; + vfs_update_propagation(mount); +} + +/** @brief Unlink one live mount without dropping its retained paths. + * @param mount Required live member of its namespace list; writer-owned. + */ +static void vfs_unlink_mount(struct vfs_mount *mount) +{ + struct vfs_mount **link=&mount->ns->mounts; + while(*link!=mount)link=&(*link)->next; + *link=mount->next;mount->next=NULL; + vfs_clear_mount_membership(mount); } /** @brief Identify a surviving cover that can be lifted out of an unmount batch. @@ -880,79 +961,96 @@ static bool vfs_removable_cover_edge(const struct vfs_mount *mount) return parent && parent->propagation_copy && mount->point.dentry==parent->root; } -/** @brief Mark origin mounts and the matching slots of propagation receivers. +/** @brief Add a mount to the current unmount batch once. + * @param pending Address of the batch head. @param mount Borrowed live mount. + * Only scratch fields change; no lookup or allocation. + */ +static void vfs_select_unmount(struct vfs_mount **pending,struct vfs_mount *mount) +{ + if(mount->unmount_selected)return; + mount->unmount_selected=true;mount->unmount_next=*pending;*pending=mount; +} + +/** @brief Mark origin mounts and their exact counterparts in every graph. * @param ns Borrowed namespace under execution ownership. * @param root Root of the requested unmount. * @param subtree True to send events for the entire original subtree. + * @return Intrusive list of candidates; clear all scratch before returning + * to the caller. Matching uses parents' groups and retained dentry identity. * The parents' peer groups and downstream edges determine delivery. A receiver * with an unrelated child stays, except a root cover that can be lifted. */ -static void vfs_select_unmounts(struct vfs_namespace *ns,struct vfs_mount *root,bool subtree) +static struct vfs_mount *vfs_select_unmounts(struct vfs_namespace *ns,struct vfs_mount *root,bool subtree) { - bool propagated=false; + struct vfs_mount *pending=NULL; for(struct vfs_mount *event=subtree ? ns->mounts : root;event; event=subtree ? event->next : NULL) { if(subtree && !vfs_mount_below(root,event))continue; - event->unmount_selected=true; + vfs_select_unmount(&pending,event); struct vfs_mount *parent=event->point.mount; if(!parent || !parent->peer_group)continue; - for(struct vfs_mount *receiver=ns->mounts;receiver;receiver=receiver->next) { - const struct vfs_path *point=&receiver->point; + for(struct vfs_mount *receiver=propagation_mounts;receiver;receiver=receiver->propagation_next) { uint64_t depth; - if(point->mount && point->mount!=parent && point->dentry==event->point.dentry && - vfs_propagation_depth(parent,point->mount,&depth)) { - receiver->unmount_selected=true;propagated=true; - } + if(receiver==parent || !vfs_propagation_depth(parent,receiver,&depth))continue; + struct vfs_path point={receiver,event->point.dentry}; + struct vfs_mount *cover=vfs_covering(receiver->ns,&point); + if(cover)vfs_select_unmount(&pending,cover); } } - if(propagated) { - for(struct vfs_mount *child=ns->mounts;child;child=child->next) { - if(child->unmount_selected)continue; - struct vfs_mount *parent=child->point.mount; - if(!vfs_removable_cover_edge(child)) - while(parent && parent->unmount_selected) { - parent->unmount_selected=false; - if(vfs_removable_cover_edge(parent))break; - parent=parent->point.mount; - } - } - for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { - mount->lift_cover=!mount->unmount_selected && vfs_removable_cover_edge(mount) && - mount->point.mount->unmount_selected; + + /* A veto walks upwards immediately, so it also handles a parent that was + * visited earlier in the batch. A root cover stops the veto at its edge. */ + for(struct vfs_mount *mount=pending;mount;mount=mount->unmount_next) { + if(!mount->unmount_selected)continue; + for(struct vfs_mount *child=mount->ns->mounts;child;child=child->next) { + if(child->point.mount!=mount || child->unmount_selected || vfs_removable_cover_edge(child))continue; + for(struct vfs_mount *parent=mount;parent && parent->unmount_selected;parent=parent->point.mount) { + parent->unmount_selected=false; + if(vfs_removable_cover_edge(parent))break; + } + break; } } + return pending; } /** @brief Reject busy mounts before changing any member of an unmount batch. - * @param ns Borrowed execution-owned namespace with selected mounts marked. + * @param pending Borrowed candidates across live graphs, including vetoes. * @param root Origin mount with the caller's lookup reference. * @return Zero or negative busy/provider errno. Backing lifetime pins and * edges disappearing or being reparented in this batch are not external path * references. A regular bind outside the batch still pins its source as before. */ -static int vfs_unmount_preflight(const struct vfs_namespace *ns,const struct vfs_mount *root) +static int vfs_unmount_preflight(const struct vfs_mount *pending,const struct vfs_mount *root) { - for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { + for(const struct vfs_mount *mount=pending;mount;mount=mount->unmount_next) { if(!mount->unmount_selected)continue; uint64_t expected=1+(mount==root)+mount->propagation_pins; - struct vfs_mount *backing=mount->propagation_backing ? mount->bind_source.mount : mount; + for(const struct vfs_mount *child=mount->ns->mounts;child;child=child->next) + if(child->point.mount==mount && (child->unmount_selected || vfs_removable_cover_edge(child)))++expected; + for(const struct vfs_mount *other=pending;other;other=other->unmount_next) + if(other->unmount_selected && other->bind_source.mount==mount && !other->propagation_backing)++expected; + if(mount->references!=expected)return -EBUSY; + } + + /* Check each final backend once, counting the selected lifetime views in + * all namespaces. The native attachment may already be detached. */ + for(const struct vfs_mount *mount=pending;mount;mount=mount->unmount_next) { + if(!mount->unmount_selected)continue; + const struct vfs_mount *backing=mount->propagation_backing ? mount->bind_source.mount : mount; + if(!backing->ops->can_unmount)continue; + if(mount->propagation_backing ? backing->ns || backing->references!=backing->propagation_pins : + mount->bind_source.mount!=NULL)continue; uint64_t replicas=0; bool first_replica=true; - for(struct vfs_mount *other=ns->mounts;other;other=other->next) { - if((other->unmount_selected || other->lift_cover) && other->point.mount==mount)++expected; + for(const struct vfs_mount *other=pending;other;other=other->unmount_next) { if(!other->unmount_selected)continue; - if(other->bind_source.mount==mount && !other->propagation_backing)++expected; if(other->bind_source.mount==backing && other->propagation_backing) { ++replicas; if(other->idid)first_replica=false; } } - if(mount->references!=expected)return -EBUSY; - /* Check native backing users once only when the origin and all - * backing views are going away. The origin may already be detached. */ - bool final_check=mount->propagation_backing ? !backing->ns && first_replica && - backing->references==backing->propagation_pins : !mount->bind_source.mount; - if(final_check && replicas==backing->propagation_pins && backing->ops->can_unmount) { + if((!mount->propagation_backing || first_replica) && replicas==backing->propagation_pins) { int rc=backing->ops->can_unmount(backing->context,backing->root->backend_pin); if(rc)return rc; } @@ -973,30 +1071,30 @@ static void vfs_release_detached_mounts(struct vfs_mount *detached) } } -/** @brief Unlink the entire selected graph before dropping retained edges. - * @param ns Borrowed execution-owned namespace with selected mounts marked. +/** @brief Commit or discard one cross-namespace unmount batch. + * @param pending Intrusive list of live candidates, consumed and cleared. + * @param status Nonzero to discard the batch without topology changes. * @param lazy True to keep external paths walkable and defer final teardown. - * Reparent preserved covers and repair weak propagation edges before removing - * each member. No allocation, and lazy unmount invokes no backend finish. + * Reparent preserved covers and repair weak propagation edges in all graphs + * before dropping any membership references. No allocation is needed. */ -static void vfs_disconnect_unmounts(struct vfs_namespace *ns,bool lazy) +static void vfs_finish_unmounts(struct vfs_mount *pending,int status,bool lazy) { - for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) { - if(!mount->lift_cover)continue; - const struct vfs_path *point=&mount->point.mount->point; + if(!status)for(struct vfs_mount *mount=pending;mount;mount=mount->unmount_next) { + if(!mount->unmount_selected)continue; + const struct vfs_path *point=&mount->point; while(point->mount->unmount_selected)point=&point->mount->point; - vfs_replace_mountpoint(mount,point); - mount->lift_cover=false; + for(struct vfs_mount *child=mount->ns->mounts;child;child=child->next) + if(child->point.mount==mount && !child->unmount_selected && vfs_removable_cover_edge(child)) + vfs_replace_mountpoint(child,point); } - struct vfs_mount *detached=NULL,**link=&ns->mounts; - while(*link) { - struct vfs_mount *mount=*link; - if(!mount->unmount_selected){link=&mount->next;continue;} - vfs_leave_peer_group(ns,mount); - *link=mount->next;mount->next=detached;detached=mount; - mount->ns=NULL;mount->lazy_detached=lazy; - mount->master=NULL;mount->unbindable=false; - mount->unmount_selected=false;mount->propagation_copy=false; + struct vfs_mount *detached=NULL; + while(pending) { + struct vfs_mount *mount=pending;pending=mount->unmount_next;mount->unmount_next=NULL; + bool selected=mount->unmount_selected;mount->unmount_selected=false; + if(status || !selected)continue; + vfs_unlink_mount(mount); + mount->lazy_detached=lazy;mount->next=detached;detached=mount; } vfs_release_detached_mounts(detached); } @@ -1016,11 +1114,9 @@ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path) for(struct vfs_mount *child=ns->mounts;child;child=child->next) if(child->point.mount==root)return -EBUSY; - vfs_select_unmounts(ns,root,false); - int rc=vfs_unmount_preflight(ns,root); - if(!rc)vfs_disconnect_unmounts(ns,false); - else for(struct vfs_mount *mount=ns->mounts;mount;mount=mount->next) - mount->unmount_selected=mount->lift_cover=false; + struct vfs_mount *pending=vfs_select_unmounts(ns,root,false); + int rc=vfs_unmount_preflight(pending,root); + vfs_finish_unmounts(pending,rc,false); return rc; } @@ -1036,25 +1132,22 @@ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path) struct vfs_mount *root=path->mount; if(root->ns!=ns || path->dentry!=root->root)return -EINVAL; if(root==ns->root || !root->point.mount)return -EBUSY; - vfs_select_unmounts(ns,root,true); - vfs_disconnect_unmounts(ns,true);return 0; + vfs_finish_unmounts(vfs_select_unmounts(ns,root,true),0,true);return 0; } /** @brief Retire the complete graph locally, including the namespace anchor. * @param ns Last-owner namespace storage, or NULL, under VFS execution. - * Clears membership and weak propagation links before releasing paths. + * Repairs other graphs' weak propagation links before releasing paths. * Does not propagate unmount or wait for open objects or backend finish. */ void vfs_namespace_retire(struct vfs_namespace *ns) { if(!ns)return; struct vfs_mount *mounts=ns->mounts; - *ns=(struct vfs_namespace){0}; for(struct vfs_mount *mount=mounts;mount;mount=mount->next) { - mount->ns=NULL;mount->lazy_detached=true; - mount->master=NULL;mount->peer_group=0; - mount->unbindable=false;mount->propagation_copy=false; + vfs_clear_mount_membership(mount);mount->lazy_detached=true; } + *ns=(struct vfs_namespace){0}; vfs_release_detached_mounts(mounts); } @@ -1084,7 +1177,7 @@ int vfs_namespace_destroy(struct vfs_namespace *ns) while(child && child->point.mount!=leaf && child->bind_source.mount!=leaf)child=child->next; if(!child)break;leaf=child; } - vfs_mount_detach(ns,leaf); + vfs_unlink_mount(leaf);vfs_release_detached_mounts(leaf); } *ns=(struct vfs_namespace){0};return 0; } diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index a2ccabaf..745f0b65 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -198,7 +198,7 @@ struct vfs_namespace *vfs_path_namespace(const struct vfs_path *path); /** @brief Mount graph plus its execution-owned lifetime, independent of paths. */ struct vfs_namespace { struct vfs_mount *root,*mounts; - uint64_t next_peer_id,references; + uint64_t references; /* Only managed snapshots have a finalizer; boot/fixture storage is external. */ void (*release)(struct vfs_namespace *ns); }; @@ -559,8 +559,8 @@ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root); * failure. Held paths in source retain the same dentry on the corresponding * new mount, even under an overmount; detached paths and empty slots remain * unchanged. Live paths outside source are rejected. Mount IDs and policy - * are independent; propagation relations are copied locally, not connected - * between namespaces. No filesystem lookup or backend creation is needed. + * are independent; shared copies join the same peer groups and slaves keep + * their upstream groups. No filesystem lookup or backend creation is needed. */ int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace *source, struct vfs_path *root,struct vfs_path *cwd); @@ -576,9 +576,10 @@ int vfs_namespace_clone(const struct vfs_namespace *source,struct vfs_path *root struct vfs_path *cwd,struct vfs_namespace **out); /** @brief Disconnect all mounts for last-owner namespace teardown. * @param ns Caller-owned namespace with no remaining graph users, or NULL. - * Serialized VFS execution. Clears ns without propagating, checking busy - * paths or flushing backends. Held paths survive as detached objects; - * final backend cleanup is deferred. The caller owns the namespace storage. + * Serialized VFS execution. Repairs weak propagation links in surviving + * graphs without sending unmount events, checking busy paths or flushing + * backends. Held paths survive; final backend cleanup is deferred. The caller + * owns the namespace storage. */ void vfs_namespace_retire(struct vfs_namespace *ns); /** @brief Destroy a namespace only when every external path/handle has gone. @@ -594,11 +595,12 @@ int vfs_namespace_destroy(struct vfs_namespace *ns); */ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out); /** @brief Attach an unpublished mount and propagate to eligible peers and slaves. - * @param ns Shared namespace under execution ownership. + * @param ns Origin namespace under execution ownership. * @param mount Unpublished mount; caller retains its own handle. * @param target Held directory path in ns; an already covered slot is busy. * @return Zero or negative errno without partial publication or ID use on - * failure. Existing receiver covers remain visible above the copy. Task context. + * failure anywhere in the propagation graph. Existing receiver covers remain + * visible above the copies. Task context. */ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount, const struct vfs_path *target); @@ -607,8 +609,10 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount, * @param path Held root of an attached mount in ns, not an interior dentry. * @param flags Exactly one propagation type, optionally with MS_REC. * @return Zero or negative errno without partial changes. MS_SHARED assigns - * peer groups to nonshared mounts. MS_SLAVE leaves a peer group while retaining - * an upstream group if available. MS_PRIVATE and MS_UNBINDABLE clear both. + * globally unique peer groups to nonshared mounts. MS_SLAVE leaves a peer + * group while retaining an upstream group if available. MS_PRIVATE and + * MS_UNBINDABLE clear both. A departing member repairs downstream edges even + * across namespace boundaries. * No backend or access policy changes. */ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *path,uint64_t flags); @@ -619,8 +623,8 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa * @return Zero or negative errno without a partial attachment. Inherits * source mount policy; shares inode identities and backend lifetime without * duplicating provider destruction. Inherits the source's peer and master - * groups, and propagates under a shared destination. Child mounts are not - * copied and an unbindable source returns EINVAL. + * groups, and propagates across eligible graphs under a shared destination. + * Child mounts are not copied and an unbindable source returns EINVAL. */ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); @@ -630,7 +634,8 @@ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, * @param target Uncovered destination directory in the same namespace. * @return Zero or negative errno without publishing a partial tree. Each clone * has an independent ID and mount policy but pins the original backing objects. - * Eligible destination peers and slaves each receive a bindable tree. + * Eligible destination peers and slaves, even in another namespace, each + * receive a bindable tree. * Unbindable descendant branches are skipped; an unbindable source is rejected. */ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *source, @@ -641,8 +646,9 @@ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *sou * @param target Held destination directory path in the same namespace. * @return Zero or negative errno without partial moves or replicas. Moving * out of a shared parent, or moving an unbindable branch into one, gives - * EINVAL. A shared destination publishes peer and slave copies of the tree. - * The original subtree moves intact; allocations finish before commit. + * EINVAL. A shared destination publishes peer and slave copies of the tree + * across eligible graphs. The original subtree moves intact; allocations + * finish before commit. */ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); @@ -651,16 +657,17 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source, * @param path The caller's sole external path to the mounted root. * @return Zero or negative errno. The origin must have no child mounts; a * receiver with unrelated children is skipped, except root covers that can be - * reparented. Other held paths on selected mounts keep the entire operation - * busy. Success does not consume the caller's path. + * reparented. Other held paths on selected mounts in any namespace keep the + * entire operation busy. Success does not consume the caller's path. */ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path); /** @brief Lazily disconnect a subtree and eligible propagated attachments. * @param ns Borrowed namespace under execution ownership. * @param path Retained visible root of a mount, not the namespace anchor. * @return Zero or negative errno. Receivers with unrelated children stay, - * except root covers that can be reparented. Held paths remain usable and - * final cleanup is deferred. No allocations or synchronous backend flush. + * except root covers that can be reparented. The whole batch spans eligible + * namespaces. Held paths remain usable and final cleanup is deferred. No + * allocations or synchronous backend flush. */ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path); /** @brief Prepare retained directory-name changes before a backend rename. diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index dba8e8a9..55f37991 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -3110,15 +3110,15 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&a)); assert(!vfs_path_lookup(ns,root,root,user.target,0,&point)); assert(!storage_new_tmpfs_mount("stacked event",0,NULL,1000,1000,&mount)); - const uint64_t covered_id=vfs_mount_next_id(),covered_peer_id=ns->next_peer_id; + const uint64_t covered_id=vfs_mount_next_id(),covered_peer_id=vfs_mount_next_peer_id(); test_fail_heap_after=1; assert(vfs_mount_attach(ns,mount,&point)==-ENOMEM); test_fail_heap_after=-1; - assert(vfs_mount_next_id()==covered_id && ns->next_peer_id==covered_peer_id); + assert(vfs_mount_next_id()==covered_id && vfs_mount_next_peer_id()==covered_peer_id); assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&found)); assert(vfs_path_equal(&a,&found));vfs_path_put(&found); assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); - assert(vfs_mount_next_id()==covered_id+2 && ns->next_peer_id==covered_peer_id+1); + assert(vfs_mount_next_id()==covered_id+2 && vfs_mount_next_peer_id()==covered_peer_id+1); assert(!vfs_kernel_mkdir(ns,"/shared-b/covered/incoming",0755)); assert(vfs_path_lookup(ns,root,root,"/shared-a/covered/incoming",0,&found)==-ENOENT); assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&found)); @@ -3140,11 +3140,11 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_path_lookup(ns,root,root,"/shared-a/outside",0,&point)); assert(!storage_new_tmpfs_mount("shared event",0,NULL,1000,1000,&mount)); - const uint64_t next_id=vfs_mount_next_id(),peer_id=ns->next_peer_id; + const uint64_t next_id=vfs_mount_next_id(),peer_id=vfs_mount_next_peer_id(); test_fail_heap_after=1; assert(vfs_mount_attach(ns,mount,&point)==-ENOMEM); test_fail_heap_after=-1; - assert(vfs_mount_next_id()==next_id && ns->next_peer_id==peer_id); + assert(vfs_mount_next_id()==next_id && vfs_mount_next_peer_id()==peer_id); assert(!vfs_path_lookup(ns,root,root,"/shared-a/outside",0,&found)); assert(vfs_path_equal(&found,&point));vfs_path_put(&found); assert(!vfs_path_lookup(ns,root,root,"/shared-b/outside",0,&found)); @@ -3172,12 +3172,12 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_kernel_mkdir(ns,"/shared-source/child/nested",0755)); assert(!vfs_path_lookup(ns,root,root,"/shared-source",0,&a)); assert(!vfs_path_lookup(ns,root,root,"/shared-a/p/event",0,&point)); - const uint64_t bind_id=vfs_mount_next_id(),bind_peer_id=ns->next_peer_id; + const uint64_t bind_id=vfs_mount_next_id(),bind_peer_id=vfs_mount_next_peer_id(); /* The first tree and one receiver tree fit, but not the final receiver. */ test_fail_heap_after=8; assert(vfs_mount_bind_recursive(ns,&a,&point)==-ENOMEM); test_fail_heap_after=-1; - assert(vfs_mount_next_id()==bind_id && ns->next_peer_id==bind_peer_id); + assert(vfs_mount_next_id()==bind_id && vfs_mount_next_peer_id()==bind_peer_id); assert(!fixture_shared_id(ns,root,"/shared-source")); assert(vfs_path_lookup(ns,root,root,"/shared-a/p/event/child",0,&found)==-ENOENT); assert(vfs_path_lookup(ns,root,root,"/shared-b/p/event/child",0,&found)==-ENOENT); @@ -3368,11 +3368,11 @@ static void runtime_slave_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_kernel_mkdir(ns,"/slave-d/rec/local",0755)); assert(!vfs_path_lookup(ns,root,root,"/slave-source",0,&a)); assert(!vfs_path_lookup(ns,root,root,"/slave-a/rec",0,&b)); - const uint64_t id=vfs_mount_next_id(),group=ns->next_peer_id; + const uint64_t id=vfs_mount_next_id(),group=vfs_mount_next_peer_id(); test_fail_heap_after=9; assert(vfs_mount_bind_recursive(ns,&a,&b)==-ENOMEM); test_fail_heap_after=-1; - assert(vfs_mount_next_id()==id && ns->next_peer_id==group); + assert(vfs_mount_next_id()==id && vfs_mount_next_peer_id()==group); assert(vfs_path_lookup(ns,root,root,"/slave-d/rec/child",0,&found)==-ENOENT); vfs_path_put(&a);vfs_path_put(&b); strcpy(user.source,"/slave-source");strcpy(user.target,"/slave-a/rec"); @@ -3471,7 +3471,7 @@ static void runtime_shared_move(struct vfs_namespace *ns,const struct vfs_path * assert(!vfs_path_lookup(ns,root,root,"/move-src/child",0,&child)); assert(!vfs_path_lookup(ns,root,root,"/move-a/slot",0,&target)); const uint64_t id=vfs_path_mount_id(&original),child_id=vfs_path_mount_id(&child); - const uint64_t next=vfs_mount_next_id(),next_group=ns->next_peer_id; + const uint64_t next=vfs_mount_next_id(),next_group=vfs_mount_next_peer_id(); strcpy(user.source,"/move-src"); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,to,0,MS_UNBINDABLE,0)); strcpy(user.target,"/move-a/slot"); @@ -3483,7 +3483,7 @@ static void runtime_shared_move(struct vfs_namespace *ns,const struct vfs_path * test_fail_heap_after=5; assert(vfs_mount_move(ns,&original,&target)==-ENOMEM); test_fail_heap_after=-1; - assert(vfs_mount_next_id()==next && ns->next_peer_id==next_group); + assert(vfs_mount_next_id()==next && vfs_mount_next_peer_id()==next_group); assert(!fixture_shared_id(ns,root,"/move-src") && !fixture_shared_id(ns,root,"/move-src/child")); assert(fixture_mount_tag(ns,root,"/move-src"," master:")==upstream); assert(!vfs_path_lookup(ns,root,root,"/move-a/slot",0,&found) && vfs_path_equal(&found,&target)); @@ -3492,7 +3492,7 @@ static void runtime_shared_move(struct vfs_namespace *ns,const struct vfs_path * strcpy(user.target,"/move-a/slot"); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,UINT64_MAX,MS_MOVE,UINT64_MAX)); - assert(vfs_mount_next_id()==next+6 && ns->next_peer_id==next_group+2); + assert(vfs_mount_next_id()==next+6 && vfs_mount_next_peer_id()==next_group+2); assert(!vfs_path_lookup(ns,root,root,"/move-a/slot",0,&found)); assert(vfs_path_equal(&found,&original) && vfs_path_mount_id(&found)==id);vfs_path_put(&found); assert(!vfs_path_lookup(ns,root,root,"/move-a/slot/child",0,&found)); diff --git a/tools/tests/mount_tree_test.c b/tools/tests/mount_tree_test.c index f94e7406..9626ffdd 100644 --- a/tools/tests/mount_tree_test.c +++ b/tools/tests/mount_tree_test.c @@ -7,6 +7,7 @@ #include #include #include +#include "../../fs/vfs/mount_internal.h" #include "../../kernel/module/internal.h" static size_t allocations; @@ -41,7 +42,8 @@ static struct entry a_entries[]={ {8,1,"loop",RELIEFOS_FS_TYPE_SYMLINK,"loop",0}, {9,1,"two",RELIEFOS_FS_TYPE_SYMLINK,"relative",0}, {10,1,"dirlink",RELIEFOS_FS_TYPE_SYMLINK,"mnt",0}, - {11,1,"slashfile",RELIEFOS_FS_TYPE_SYMLINK,"file/",0} + {11,1,"slashfile",RELIEFOS_FS_TYPE_SYMLINK,"file/",0}, + {12,1,"receiver",RELIEFOS_FS_TYPE_DIR,NULL,0} }; static struct entry b_entries[]={ {1,1,"",RELIEFOS_FS_TYPE_DIR,NULL,0}, {2,1,"new",RELIEFOS_FS_TYPE_FILE,NULL,0}, @@ -336,7 +338,7 @@ static void namespace_snapshot_objects(struct module *owner) int rc=vfs_namespace_snapshot(©,&source,&task_root,&cwd); fail_after=0; if(!rc)break; - assert(rc==-ENOMEM && !copy.root && !copy.mounts && !copy.next_peer_id); + assert(rc==-ENOMEM && !copy.root && !copy.mounts); assert(vfs_path_equal(&task_root,&lower) && vfs_path_equal(&cwd,&inner)); assert(allocations==before && context_release_owner->users==1);++failed; } @@ -365,10 +367,18 @@ static void namespace_snapshot_objects(struct module *owner) char table[2048];uint32_t read=0; assert(!vfs_read_mount_table(©,&visible,true,0,table,sizeof(table)-1,&read));table[read]=0; - assert(strstr(table,"/mnt ro,noatime shared:1 ") && strstr(table,"/other rw,nodev,noatime master:1 ")); + assert(lower.mount->peer_group && lower.mount->peer_group==task_root.mount->peer_group); + char expected[96];uint64_t group=lower.mount->peer_group; + snprintf(expected,sizeof(expected),"/mnt ro,noatime shared:%" PRIu64 " ",group); + assert(strstr(table,expected)); + snprintf(expected,sizeof(expected),"/other rw,nodev,noatime master:%" PRIu64 " ",group); + assert(strstr(table,expected)); assert(strstr(table,"/mnt/child rw unbindable ")); - /* A backend-only snapshot pin is not a busy reference to the original. */ + /* The peer's held upper is busy while the parents propagate. Separating + * the original parent leaves only a backend pin, which is not busy. */ + assert(vfs_mount_unmount(&source,&upper)==-EBUSY); + assert(!vfs_mount_set_propagation(&source,&lower,MS_PRIVATE)); assert(!vfs_mount_unmount(&source,&upper));vfs_path_put(&upper); struct vfs_path found=find(&source,&root,&root,"mnt",1); assert(vfs_path_equal(&found,&lower));vfs_path_put(&found); @@ -397,6 +407,163 @@ static void namespace_snapshot_objects(struct module *owner) puts("PASS mount namespace snapshot: covered task paths, independent policy and IDs, atomic rollback and deferred retirement"); } +static int cross_unmount_error; +static unsigned cross_unmount_checks; + +/** @brief Record a final unmount preflight for the propagated test backend. + * @param context Expected filesystem context. @param pin Its held root token. + * @return The configured provider error, or zero. + */ +static int cross_can_unmount(void *context,void *pin) +{ + assert(context==&c && pin==&c_entries[0]);++cross_unmount_checks;return cross_unmount_error; +} + +/** @brief Exercise transactional mount, move and unmount across three live graphs. */ +static void cross_namespace_events(void) +{ + struct vfs_namespace source={0},peer={0},slave={0}; + struct vfs_mount *mount=mount_new(&a,NULL); + assert(!vfs_namespace_init(&source,mount));vfs_mount_put(mount); + struct vfs_path root={0},peer_root={0},slave_root={0}; + assert(!vfs_namespace_root(&source,&root)); + struct vfs_path before=find(&source,&root,&root,"mnt",2); + mount=mount_new(&b,NULL); + assert(!vfs_mount_attach(&source,mount,&before));vfs_mount_put(mount);vfs_path_put(&before); + struct vfs_path parent=find(&source,&root,&root,"mnt",1); + assert(!vfs_mount_set_propagation(&source,&parent,MS_SHARED)); + assert(!vfs_namespace_snapshot(&peer,&source,NULL,NULL)); + assert(!vfs_namespace_snapshot(&slave,&source,NULL,NULL)); + assert(!vfs_namespace_root(&peer,&peer_root) && !vfs_namespace_root(&slave,&slave_root)); + struct vfs_path receiver=find(&slave,&slave_root,&slave_root,"mnt",1); + assert(!vfs_mount_set_propagation(&slave,&receiver,MS_SLAVE)); + struct vfs_path target=find(&source,&root,&parent,"child",3); + struct vfs_path slave_slot=find(&slave,&slave_root,&receiver,"child",3); + mount=mount_new(&a,NULL); + assert(!vfs_mount_attach(&slave,mount,&slave_slot));vfs_mount_put(mount); + struct vfs_path cover=find(&slave,&slave_root,&receiver,"child",1); + struct vfs_backend_ops event_ops=ops;event_ops.can_unmount=cross_can_unmount; + struct storage_node event_root=node(&c_entries[0]); + assert(!vfs_mount_new(&event_ops,&c,NULL,&event_root,&mount)); + + /* Both allocations for the foreign peer fit; the slave fails next. */ + size_t before_attach=allocations;uint64_t next=vfs_mount_next_id(),group=vfs_mount_next_peer_id(); + fail_after=3;allocation_attempts=0; + int rc=vfs_mount_attach(&source,mount,&target); + fail_after=0; + assert(rc==-ENOMEM && allocation_attempts==3); + assert(allocations==before_attach && vfs_mount_next_id()==next && vfs_mount_next_peer_id()==group); + assert(!mount->peer_group && !mount->propagation_pins); + assert(!mount->ns && !mount->id && vfs_path_equal(&cover.mount->point,&slave_slot)); + struct vfs_path found=find(&peer,&peer_root,&peer_root,"mnt/child",3);vfs_path_put(&found); + + assert(!vfs_mount_attach(&source,mount,&target));vfs_mount_put(mount); + assert(vfs_mount_next_id()==next+3 && vfs_mount_next_peer_id()==group+1); + struct vfs_path origin=find(&source,&root,&root,"mnt/child",1); + struct vfs_path replica=find(&peer,&peer_root,&peer_root,"mnt/child",1); + struct vfs_mount *hidden=cover.mount->point.mount; + assert(hidden->ns==&slave && hidden->point.mount==receiver.mount); + assert(vfs_path_same_inode(&origin,&replica) && replica.mount->peer_group==origin.mount->peer_group); + assert(origin.mount!=replica.mount && origin.mount->id!=replica.mount->id); + assert(hidden->master && hidden->master->peer_group==origin.mount->peer_group); + assert(vfs_mount_unmount(&source,&origin)==-EBUSY && replica.mount->ns==&peer); + assert(!cross_unmount_checks && cover.mount->point.mount==hidden); + vfs_path_put(&replica); + cross_unmount_error=-EIO; + assert(vfs_mount_unmount(&source,&origin)==-EIO && cross_unmount_checks==1); + found=find(&peer,&peer_root,&peer_root,"mnt/child",1);vfs_path_put(&found); + assert(cover.mount->point.mount==hidden); + cross_unmount_error=0; + assert(!vfs_mount_unmount(&source,&origin) && cross_unmount_checks==2);vfs_path_put(&origin); + assert(vfs_path_equal(&cover.mount->point,&slave_slot)); + found=find(&peer,&peer_root,&peer_root,"mnt/child",3);vfs_path_put(&found); + found=find(&slave,&slave_root,&receiver,"child",1); + assert(vfs_path_equal(&found,&cover));vfs_path_put(&found); + + struct vfs_path local=find(&source,&root,&root,"other",3); + mount=mount_new(&b,NULL); + assert(!vfs_mount_attach(&source,mount,&local));vfs_mount_put(mount);vfs_path_put(&local); + origin=find(&source,&root,&root,"other",1); + local=find(&source,&root,&origin,"child",3); + mount=mount_new(&c,NULL); + assert(!vfs_mount_attach(&source,mount,&local));vfs_mount_put(mount);vfs_path_put(&local); + struct vfs_path child=find(&source,&root,&origin,"child",1); + uint64_t id=vfs_path_mount_id(&origin); + assert(!vfs_mount_move(&source,&origin,&target)); + assert(vfs_path_mount_id(&origin)==id); + formatted(&source,&root,&child,"/mnt/child/child"); + replica=find(&peer,&peer_root,&peer_root,"mnt/child",1); + found=find(&peer,&peer_root,&replica,"child",1); + assert(vfs_path_same_inode(&child,&found));vfs_path_put(&found); + assert(!vfs_mount_unmount_lazy(&peer,&replica)); + assert(!vfs_path_namespace(&replica) && !vfs_path_namespace(&origin) && !vfs_path_namespace(&child)); + assert(vfs_path_equal(&cover.mount->point,&slave_slot)); + vfs_path_put(&replica);vfs_path_put(&child);vfs_path_put(&origin); + vfs_path_put(&cover);vfs_path_put(&slave_slot);vfs_path_put(&target); + vfs_path_put(&receiver);vfs_path_put(&parent); + vfs_path_put(&slave_root);vfs_path_put(&peer_root);vfs_path_put(&root); + vfs_namespace_retire(&slave);vfs_namespace_retire(&peer);vfs_namespace_retire(&source); + while(vfs_reclaim_mounts(32)){} + assert(!vfs_reclaim_pending() && !allocations);no_pins(&a);no_pins(&b);no_pins(&c); + puts("PASS cross-namespace mount/move/unmount: late OOM, remote busy, provider veto and preserved cover"); +} + +/** @brief Check scoped propagation tags and weak master repair after final graph put. */ +static void cross_namespace_master_lifetime(void) +{ + struct vfs_namespace view={0},*copy=NULL; + struct vfs_mount *mount=mount_new(&a,NULL); + assert(!vfs_namespace_init(&view,mount));vfs_mount_put(mount); + struct vfs_path root={0},foreign={0};assert(!vfs_namespace_root(&view,&root)); + struct vfs_path slot=find(&view,&root,&root,"mnt",2); + mount=mount_new(&b,NULL); + assert(!vfs_mount_attach(&view,mount,&slot));vfs_mount_put(mount);vfs_path_put(&slot); + struct vfs_path upstream=find(&view,&root,&root,"mnt",1); + assert(!vfs_mount_set_propagation(&view,&upstream,MS_SHARED)); + slot=find(&view,&root,&root,"other",3); + assert(!vfs_mount_bind(&view,&upstream,&slot));vfs_path_put(&slot); + struct vfs_path middle=find(&view,&root,&root,"other",1); + assert(!vfs_mount_set_propagation(&view,&middle,MS_SLAVE)); + assert(!vfs_mount_set_propagation(&view,&middle,MS_SHARED)); + slot=find(&view,&root,&root,"receiver",12); + assert(!vfs_mount_bind(&view,&middle,&slot));vfs_path_put(&slot); + struct vfs_path receiver=find(&view,&root,&root,"receiver",1); + assert(!vfs_mount_set_propagation(&view,&receiver,MS_SLAVE)); + const uint64_t master=middle.mount->peer_group,dom=upstream.mount->peer_group; + char table[2048],expected[128];uint32_t count; + assert(!vfs_read_mount_table(&view,&root,true,0,table,sizeof(table)-1,&count));table[count]=0; + assert(!strstr(table," propagate_from:")); + + vfs_path_get(&root,&foreign); + assert(!vfs_namespace_clone(&view,&foreign,NULL,©)); + assert(!vfs_mount_set_propagation(&view,&middle,MS_PRIVATE)); + assert(!vfs_mount_set_propagation(&view,&middle,MS_SHARED)); + assert(middle.mount->peer_group!=master && receiver.mount->master->ns==copy); + assert(!vfs_read_mount_table(&view,&root,true,0,table,sizeof(table)-1,&count));table[count]=0; + snprintf(expected,sizeof(expected),"/receiver rw master:%" PRIu64 " propagate_from:%" PRIu64 " ",master,dom); + assert(strstr(table,expected)); + assert(!vfs_read_mount_table(&view,&receiver,true,0,table,sizeof(table)-1,&count));table[count]=0; + snprintf(expected,sizeof(expected),"/ rw master:%" PRIu64 " ",master); + assert(strstr(table,expected) && !strstr(table," propagate_from:")); + + vfs_namespace_put(copy);vfs_path_put(&foreign); + while(vfs_reclaim_mounts(32)){} + assert(!vfs_reclaim_pending() && receiver.mount->master==upstream.mount); + assert(!vfs_read_mount_table(&view,&root,true,0,table,sizeof(table)-1,&count));table[count]=0; + snprintf(expected,sizeof(expected),"/receiver rw master:%" PRIu64 " ",dom); + assert(strstr(table,expected) && !strstr(table," propagate_from:")); + + slot=find(&view,&root,&upstream,"child",3); + mount=mount_new(&c,NULL); + assert(!vfs_mount_attach(&view,mount,&slot));vfs_mount_put(mount);vfs_path_put(&slot); + struct vfs_path event=find(&view,&root,&receiver,"child",1);vfs_path_put(&event); + event=find(&view,&root,&middle,"child",3);vfs_path_put(&event); + vfs_path_put(&receiver);vfs_path_put(&middle);vfs_path_put(&upstream);vfs_path_put(&root); + assert(!vfs_namespace_destroy(&view)); + assert(!allocations);no_pins(&a);no_pins(&b);no_pins(&c); + puts("PASS cross-namespace master repair and root-relative propagate_from tags"); +} + /** @brief Pause a walk before resolving a component. * @param context Pointer to the fixture's paused flag. * @param path Directory in the retained graph. @@ -643,6 +810,8 @@ int main(void) { bound_directory_objects(); mount_table_objects(); + cross_namespace_events(); + cross_namespace_master_lifetime(); managed_namespace_walks(); magic_link_objects(); renamed_paths(); From f8f016a661dda66d80215752d7c5f8435f5067a5 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 04:18:16 +0800 Subject: [PATCH 16/97] feat(vfs): create mount namespaces with clone and unshare --- Documentation/core-api/mount-namespaces.rst | 13 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 31 ++- .../en/LC_MESSAGES/userspace-api/abi.po | 37 +++ .../LC_MESSAGES/core-api/mount-namespaces.po | 27 ++- .../ja/LC_MESSAGES/userspace-api/abi.po | 34 +++ Documentation/userspace-api/abi.rst | 16 ++ include/reliefnt/syscall.h | 1 + include/reliefnt/syscall_internal.h | 8 + include/reliefnt/task/accessors.h | 12 +- kernel/sched/clone.c | 52 ++-- kernel/sched/fs.c | 100 +++++++- kernel/sched/internal.h | 16 +- kernel/syscall/dispatch.c | 3 + kernel/syscall/process/clone.c | 15 ++ tools/test_mount_namespace_task.py | 19 ++ tools/tests/Makefile | 2 +- tools/tests/audio_device_test.c | 8 +- tools/tests/host-suites.list | 1 + tools/tests/memory_pressure_fork_table_test.c | 1 + tools/tests/mount_namespace_task_test.c | 228 ++++++++++++++++++ 20 files changed, 578 insertions(+), 46 deletions(-) create mode 100644 tools/test_mount_namespace_task.py create mode 100644 tools/tests/mount_namespace_task_test.c diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 6b36beae..1c4adf19 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -43,6 +43,17 @@ VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载 重新查找 PID,因此目标退出后也可继续读取。若所持查看根已被延迟摘除,读取返回 空列表;若传入属于其他活动图的查看根,渲染器返回 ``EXDEV``。 +用户态创建 +========== + +``unshare(CLONE_NEWNS)`` 先用独立的 root/cwd 引用准备新图,再安装到调用任务。 +替换不会改变原来的 ``CLONE_FS`` 持有者。``unshare(CLONE_FS)`` 只分离共享的 +文件系统状态,仍留在原挂载图。两种操作都保留 umask 和路径诊断名。 + +带 ``CLONE_NEWNS`` 的 ``clone()`` 和 ``clone3()`` 在分配子任务 PID 前完成快照, +因此快照失败不写回 TID、不计入 cgroup,也不发布子任务。快照及其回滚不持有 +调度器自旋锁。接口的参数和权限见 :doc:`../userspace-api/abi`。 + 引用释放 ======== @@ -51,4 +62,4 @@ VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 ``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。 -这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换。 +尚不提供挂载命名空间句柄(``/proc//ns/mnt``)或 ``setns()`` 切换。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index ed972a43..530788ca 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -112,6 +112,31 @@ msgstr "" " yields an empty listing. The renderer rejects a viewing root from a " "different live graph with ``EXDEV``." +msgid "用户态创建" +msgstr "Creation from userspace" + +msgid "" +"``unshare(CLONE_NEWNS)`` 先用独立的 root/cwd 引用准备新图,再安装到调用任务。 替换不会改变原来的 " +"``CLONE_FS`` 持有者。``unshare(CLONE_FS)`` 只分离共享的 文件系统状态,仍留在原挂载图。两种操作都保留 " +"umask 和路径诊断名。" +msgstr "" +"``unshare(CLONE_NEWNS)`` prepares a new graph with independent root and " +"cwd references, then installs it in the calling task. The replacement " +"does not affect the original ``CLONE_FS`` sharers. ``unshare(CLONE_FS)`` " +"only separates shared filesystem state and stays in the original mount " +"graph. Both operations preserve the umask and diagnostic path names." + +msgid "" +"带 ``CLONE_NEWNS`` 的 ``clone()`` 和 ``clone3()`` 在分配子任务 PID 前完成快照, " +"因此快照失败不写回 TID、不计入 cgroup,也不发布子任务。快照及其回滚不持有 调度器自旋锁。接口的参数和权限见 :doc" +":`../userspace-api/abi`。" +msgstr "" +"With ``CLONE_NEWNS``, ``clone()`` and ``clone3()`` finish the snapshot " +"before allocating a child PID. If the snapshot fails, the operation does " +"not write back a TID, charge the cgroup, or publish a child task. Neither" +" snapshot creation nor rollback holds the scheduler spinlock. For flags " +"and permissions, see :doc:`../userspace-api/abi`." + msgid "引用释放" msgstr "Reference release" @@ -128,7 +153,7 @@ msgstr "" "``vfs_namespace_destroy()`` refuses to destroy a graph with outstanding " "graph or external path references." -msgid "这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换。" +msgid "尚不提供挂载命名空间句柄(``/proc//ns/mnt``)或 ``setns()`` 切换。" msgstr "" -"These interfaces are internal to the kernel. Userspace cannot yet create " -"or switch mount namespaces." +"Mount namespace handles (``/proc//ns/mnt``) and switching with " +"``setns()`` are not yet available." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 1c4f4995..f940cb5c 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -48,6 +48,43 @@ msgstr "" " across the kernel, exported headers, userspace wrappers, consumers, and necessary validation. " "Updating golden data does not replace layout or semantic review." +msgid "创建挂载命名空间" +msgstr "Creating a mount namespace" + +msgid "" +"``unshare(CLONE_NEWNS)`` 为调用任务复制挂载树并隐含 ``CLONE_FS``;显式同时 " +"传入两位也是有效的。``unshare(CLONE_FS)`` 只取消 root、cwd 和 umask 的共享, " +"不复制挂载树。零标志不改变状态。不支持的标志(包括 64 位参数的未知高位) 返回 ``EINVAL``,不会部分应用请求。" +msgstr "" +"``unshare(CLONE_NEWNS)`` copies the mount tree for the calling task and " +"implies ``CLONE_FS``; specifying both flags explicitly is also valid. " +"``unshare(CLONE_FS)`` stops sharing root, cwd, and umask without copying " +"the mount tree. Zero flags leave the state unchanged. Unsupported flags, " +"including unknown upper bits in the 64-bit argument, return ``EINVAL`` " +"without applying any part of the request." + +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` " +"同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 " +"``EPERM``。" +msgstr "" +"With ``CLONE_NEWNS``, ``clone()`` and ``clone3()`` copy the mount tree " +"only for the child. Combining it with ``CLONE_FS`` returns ``EINVAL``. " +"Creating a mount namespace with any of these calls requires effective " +"``CAP_SYS_ADMIN``; without it the call returns ``EPERM``." + +msgid "" +"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | " +"MS_PRIVATE`` 使子树停止传播。 目前不支持通过 ``setns()`` 加入既有挂载命名空间。参见 :doc:`../core-api" +"/mount-namespaces`。" +msgstr "" +"The old and new mount trees share file contents. Root and cwd retain " +"their directory identities, and existing open files are not rebound. " +"Shared mounts can still propagate events; use ``MS_REC | MS_PRIVATE`` to " +"stop propagation for a subtree. Joining an existing namespace with " +"``setns()`` is not yet supported. See :doc:`../core-api/mount-" +"namespaces`." + msgid "目录 bind mount" msgstr "Directory Bind Mounts" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 267fced5..50dc7962 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -94,6 +94,29 @@ msgstr "" "を再検索しないため、対象が終了した後も読み取れます。表示ルートが遅延アンマウントで切り離された場合は空の一覧になります。別の稼働中のグラフに属する表示ルートには" " ``EXDEV`` を返します。" +msgid "用户态创建" +msgstr "ユーザー空間からの作成" + +msgid "" +"``unshare(CLONE_NEWNS)`` 先用独立的 root/cwd 引用准备新图,再安装到调用任务。 替换不会改变原来的 " +"``CLONE_FS`` 持有者。``unshare(CLONE_FS)`` 只分离共享的 文件系统状态,仍留在原挂载图。两种操作都保留 " +"umask 和路径诊断名。" +msgstr "" +"``unshare(CLONE_NEWNS)`` は独立した root と cwd " +"の参照を持つ新しいグラフを準備し、呼び出し元タスクに設定します。この置き換えは従来の ``CLONE_FS`` の共有相手には影響しません。 " +"``unshare(CLONE_FS)`` は共有していたファイルシステム状態だけを分離し、元のマウントグラフにとどまります。どちらの操作も " +"umask と診断用のパス名を保持します。" + +msgid "" +"带 ``CLONE_NEWNS`` 的 ``clone()`` 和 ``clone3()`` 在分配子任务 PID 前完成快照, " +"因此快照失败不写回 TID、不计入 cgroup,也不发布子任务。快照及其回滚不持有 调度器自旋锁。接口的参数和权限见 :doc" +":`../userspace-api/abi`。" +msgstr "" +"``CLONE_NEWNS`` を指定した ``clone()`` と ``clone3()`` は、子タスクの PID " +"を割り当てる前にスナップショットを完成させます。スナップショットに失敗した場合、TID の書き戻し、cgroup " +"への計上、子タスクの公開は行いません。スナップショットの作成とロールバックでは、スケジューラのスピンロックを保持しません。フラグと権限については " +":doc:`../userspace-api/abi` を参照してください。" + msgid "引用释放" msgstr "参照の解放" @@ -107,5 +130,5 @@ msgstr "" "がアンマウントを伝播させずにツリー全体を切り離し、その後グラフ自体を解放します。保持中のパスは有効なままで、既存の遅延処理キューがバックエンドを後処理します。起動時とテスト用のグラフの記憶領域は引き続き呼び出し側が管理します。厳格な" " ``vfs_namespace_destroy()`` はグラフの参照や外部パス参照が残っている間は破棄を拒否します。" -msgid "这些接口仅用于内核内部。目前未开放用户态挂载命名空间创建或切换。" -msgstr "これらのインターフェイスはカーネル内部専用です。ユーザー空間からマウント名前空間を作成または切り替えることはまだできません。" +msgid "尚不提供挂载命名空间句柄(``/proc//ns/mnt``)或 ``setns()`` 切换。" +msgstr "マウント名前空間のハンドル( ``/proc//ns/mnt`` )と ``setns()`` による切り替えは、まだ利用できません。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index c4d483b6..fbc3cae7 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -43,6 +43,40 @@ msgstr "" "に見せかけてはなりません。利用可能とみなせるのは実装済みのインターフェースだけで、ヘッダーの存在は完全な実行時認証の代わりにはなりません。インターフェース変更はカーネル、公開ヘッダー、ユーザー空間ラッパー、利用側、必要な検証に同期して反映し、golden" " データの更新でレイアウトや意味の審査を代替しません。" +msgid "创建挂载命名空间" +msgstr "マウント名前空間の作成" + +msgid "" +"``unshare(CLONE_NEWNS)`` 为调用任务复制挂载树并隐含 ``CLONE_FS``;显式同时 " +"传入两位也是有效的。``unshare(CLONE_FS)`` 只取消 root、cwd 和 umask 的共享, " +"不复制挂载树。零标志不改变状态。不支持的标志(包括 64 位参数的未知高位) 返回 ``EINVAL``,不会部分应用请求。" +msgstr "" +"``unshare(CLONE_NEWNS)`` は呼び出し元タスクのマウントツリーを複製し、暗黙に ``CLONE_FS`` " +"も指定します。両方を明示的に指定しても構いません。 ``unshare(CLONE_FS)`` は root、cwd、umask " +"の共有だけを解除し、マウントツリーは複製しません。フラグがゼロなら状態は変わりません。64 " +"ビット引数の未知の上位ビットを含む未対応フラグを指定した場合は、要求を部分的に適用することなく ``EINVAL`` を返します。" + +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` " +"同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 " +"``EPERM``。" +msgstr "" +"``clone()`` と ``clone3()`` に ``CLONE_NEWNS`` " +"を指定すると、子タスクに対してのみマウントツリーを複製します。 ``CLONE_FS`` と同時に指定すると ``EINVAL`` " +"を返します。これらの呼び出しによるマウント名前空間の作成には有効な ``CAP_SYS_ADMIN`` が必要で、なければ ``EPERM`` " +"を返します。" + +msgid "" +"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | " +"MS_PRIVATE`` 使子树停止传播。 目前不支持通过 ``setns()`` 加入既有挂载命名空间。参见 :doc:`../core-api" +"/mount-namespaces`。" +msgstr "" +"新旧のマウントツリーはファイルの内容を共有します。root と cwd " +"は元のディレクトリを指し、既に開いているファイルの参照先は変わりません。共有マウントでは引き続きイベントが伝播します。サブツリーの伝播を止めるには" +" ``MS_REC | MS_PRIVATE`` を使用します。 ``setns()`` " +"による既存のマウント名前空間への参加には、まだ対応していません。 :doc:`../core-api/mount-namespaces` " +"を参照してください。" + msgid "目录 bind mount" msgstr "ディレクトリーの bind mount" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index c12438aa..e4f92fec 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -37,6 +37,22 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。 +创建挂载命名空间 +================ + +``unshare(CLONE_NEWNS)`` 为调用任务复制挂载树并隐含 ``CLONE_FS``;显式同时 +传入两位也是有效的。``unshare(CLONE_FS)`` 只取消 root、cwd 和 umask 的共享, +不复制挂载树。零标志不改变状态。不支持的标志(包括 64 位参数的未知高位) +返回 ``EINVAL``,不会部分应用请求。 + +``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 +``CLONE_FS`` 同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 +有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。 + +新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 +绑定。共享挂载仍可传播事件;可用 ``MS_REC | MS_PRIVATE`` 使子树停止传播。 +目前不支持通过 ``setns()`` 加入既有挂载命名空间。参见 :doc:`../core-api/mount-namespaces`。 + 目录 bind mount =============== diff --git a/include/reliefnt/syscall.h b/include/reliefnt/syscall.h index a8eb5e8a..2823a128 100644 --- a/include/reliefnt/syscall.h +++ b/include/reliefnt/syscall.h @@ -277,6 +277,7 @@ struct storage_node; #define LINUX_SYS_TIMES __NR_times #define LINUX_SYS_CLONE __NR_clone #define LINUX_SYS_CLONE3 __NR_clone3 +#define LINUX_SYS_UNSHARE __NR_unshare /* Open-status flags are declared by , which is included by the * storage and descriptor interfaces. Keep only the descriptor flag here. */ diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index 6ab4e666..22da0bf3 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -13,6 +13,14 @@ struct trap_frame; struct task_lookup_path; struct storage_inode_ref; +/** @brief Unshare filesystem state through either Linux syscall dispatcher. + * @param task Current execution-owned task, required. + * @param flags Full native unsigned long flag word, without truncation. + * @return Zero, EINVAL for unsupported flags, EPERM without effective + * CAP_SYS_ADMIN for CLONE_NEWNS, or the original snapshot error. + */ +int64_t syscall_unshare(struct task *task, uint64_t flags); + /* Entry-private marker for a retryable mmap file-metadata operation. */ #define KERNEL_MMAP_FILE_IO_RETRY (-4098LL) /* A competing task owns storage; no swap I/O was queued or accepted. */ diff --git a/include/reliefnt/task/accessors.h b/include/reliefnt/task/accessors.h index 61a898c1..ef03b108 100644 --- a/include/reliefnt/task/accessors.h +++ b/include/reliefnt/task/accessors.h @@ -228,6 +228,15 @@ void sched_task_fs_inherit(struct task *task,const struct task *parent); */ bool sched_task_fs_shared_outside_group(const struct task *task); +/** @brief Detach the caller's CLONE_FS state, optionally cloning its mount graph. + * @param task Live calling task under execution ownership; required. + * @param new_namespace True for CLONE_NEWNS (caller checks CAP_SYS_ADMIN). + * @return Zero or the original VFS error with the caller and peers unchanged. + * Called without scheduler_lock. Installs new path and scalar state before + * putting old references, which may retire the old mount graph. + */ +int sched_task_fs_unshare(struct task *task, bool new_namespace); + /** @brief Retire task graph/path pins or its one shared CLONE_FS reference. * @param task Quiescent task under execution ownership; nullable. * Clears ownership before final backend release, which may perform I/O. @@ -279,7 +288,7 @@ static inline struct kernel_sigqueue *sched_task_process_signal_queue(struct tas &task->process_signal_queue; } -/** @brief Validate supported clone flags and TLS before accessing TID operands. +/** @brief Validate clone flags, namespace privilege and TLS before TID access. * @param flags Linux clone flags and optional exit signal. @param tls TLS base. * @return Zero or the scheduler's original validation errno; no locks or I/O. */ @@ -294,6 +303,7 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls); * @return Child PID or negative errno; rollback releases only child ownership. * Execution transaction required; takes scheduler_lock. CLONE_FS shares the * actual root/cwd owner; ordinary fork retains independent path references. + * CLONE_NEWNS prepares a distinct graph before reserving a task ID. */ int64_t sched_clone_current(const struct trap_frame *frame, uint64_t flags, uint64_t stack, uint64_t parent_tid, diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index 24c075bf..3055b7d1 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -127,7 +127,7 @@ void sched_vfork_child_done(struct task *child) kernel_spin_unlock_irqrestore(&scheduler_lock, flags); } -/** @brief Validate clone flag combinations before inspecting TID outputs. +/** @brief Validate clone flags and namespace privilege before TID outputs. * @param flags Linux clone flags and exit signal. @param tls Requested TLS base. * @return Zero or the original clone validation errno; no allocation, locks, * user access or state changes occur. @@ -135,9 +135,10 @@ void sched_vfork_child_done(struct task *child) int sched_clone_validate_flags(uint64_t flags,uint64_t tls) { const uint64_t supported = CSIGNAL | CLONE_VM | CLONE_VFORK | CLONE_FS | - CLONE_FILES | CLONE_SIGHAND | CLONE_PARENT | CLONE_THREAD | CLONE_SYSVSEM | + CLONE_FILES | CLONE_SIGHAND | CLONE_PARENT | CLONE_THREAD | CLONE_SYSVSEM | CLONE_NEWNS | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED | CLONE_UNTRACED | CLONE_CHILD_SETTID | CLONE_CLEAR_SIGHAND; + if ((flags & CLONE_NEWNS) && (flags & CLONE_FS)) return -LINUX_EINVAL; if ((flags & CLONE_CLEAR_SIGHAND) && (flags & CLONE_SIGHAND)) return -22; if ((flags & CLONE_THREAD) && !(flags & CLONE_SIGHAND)) return -22; if ((flags & CLONE_SIGHAND) && !(flags & CLONE_VM)) return -22; @@ -154,6 +155,10 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) ? -LINUX_EINVAL : -LINUX_EPERM; } if (flags & ~supported) return -RELIEFOS_ENOSYS; + if (flags & CLONE_NEWNS) { + const struct task *parent = sched_current_task(); + if (!parent || !(parent->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; + } if ((flags & CLONE_SETTLS) && tls >= RELIEFNT_USER_TLS_LIMIT) return -RELIEFOS_EPERM; return 0; } @@ -167,9 +172,10 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) * @param child_tid Optional user address receiving the child ID in the child. * @param tls User TLS base when CLONE_SETTLS is requested. * @return Child process ID, or a negative errno if creation fails. Copies held - * root/cwd objects for fork, shares them for CLONE_FS, and releases only child - * ownership on rollback. Called under execution ownership; takes scheduler_lock. - * Checks cgroup admission before construction and charges only at publication. + * root/cwd objects for fork, shares them for CLONE_FS, or rebinds them in a + * CLONE_NEWNS snapshot. Called under execution ownership; takes scheduler_lock. + * Cgroup admission precedes construction and charges occur only at publication. + * Namespace preparation runs unlocked before taking a child slot or PID. * Rollback hides the reserved PID before unlocking for provider cleanup; the * blocked slot is not reusable until cleanup completes. * The child never borrows the parent's retained PID-identity object or pending @@ -198,6 +204,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag struct task *child; uint32_t child_pid; bool files_retained = false; + struct task_fs_paths snapshot = {0}; if (!parent || !parent_frame || parent->kind != TASK_KIND_USER || parent->state == TASK_EXITED || !(*sched_task_as(parent)).cr3) { kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); @@ -211,27 +218,26 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag return -LINUX_EAGAIN; } parent->nproc_exceeded = false; - if (task_promote_shared(parent, flags) < 0) { - + if (flags & CLONE_NEWNS) { + /* Execution ownership keeps admission and the source stable. VFS can + * call into providers on failure, so take no scheduler lock or PID. */ kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); - sched_task_identity_put(identity); - return -12; + int rc = sched_task_fs_snapshot(parent, &snapshot); + if (rc) { + sched_task_identity_put(identity); + return rc; + } + kernel_spin_lock_irqsave(&scheduler_lock, &lock_flags); } + if (task_promote_shared(parent, flags) < 0) goto fail_prepare; child = alloc_task_slot(); - if (!child) { - - kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); - sched_task_identity_put(identity); - return -12; - } + if (!child) goto fail_prepare; child_pid = task_allocate_pid(); if (!child_pid) { task_zero(child); child->state = TASK_EXITED; - kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); - sched_task_identity_put(identity); - return -12; + goto fail_prepare; } task_zero(child); *child = *parent; @@ -262,8 +268,8 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag child->vfork_child = NULL; child->shared_files = NULL; child->shared_fs = NULL; - child->fs_paths=(struct task_fs_paths){0}; - if(!(flags & CLONE_FS))sched_task_fs_inherit(child,parent); + child->fs_paths = snapshot; + if (!(flags & (CLONE_FS | CLONE_NEWNS))) sched_task_fs_inherit(child, parent); child->shared_sighand = NULL; child->address_space = *sched_task_mm(parent); child->address_space.as = (struct address_space){0}; @@ -604,6 +610,12 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_identity_put(identity); return -12; + +fail_prepare: + kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); + sched_task_fs_paths_put(&snapshot); + sched_task_identity_put(identity); + return -LINUX_ENOMEM; } #ifdef CONFIG_SWAP diff --git a/kernel/sched/fs.c b/kernel/sched/fs.c index 3f0e37e4..2ad009b7 100644 --- a/kernel/sched/fs.c +++ b/kernel/sched/fs.c @@ -20,6 +20,29 @@ int sched_task_fs_start(struct task *task,struct vfs_namespace *ns) paths->root=initial;vfs_path_get(&initial,&paths->cwd);return 0; } +/** @brief Release path and namespace ownership after detaching the state. + * @param paths Owned state, possibly empty. Final puts may invoke providers. + */ +void sched_task_fs_paths_put(struct task_fs_paths *paths) +{ + struct task_fs_paths old = *paths; + *paths = (struct task_fs_paths){0}; + vfs_path_put(&old.root); + vfs_path_put(&old.cwd); + vfs_namespace_put(old.ns); +} + +/** @brief Retain existing filesystem paths without copying their graph. + * @param source Borrowed filesystem state. @return Independent owned handles. + */ +static struct task_fs_paths task_fs_paths_get(const struct task_fs_paths *source) +{ + struct task_fs_paths paths = {.ns = vfs_namespace_get(source->ns)}; + vfs_path_get(&source->root, &paths.root); + vfs_path_get(&source->cwd, &paths.cwd); + return paths; +} + /** @brief Retain a graph and exact root/cwd, including covered or detached paths. * @param task New task with private filesystem state; execution-owned. * @param parent Stable source task, borrowed, including shared CLONE_FS state. @@ -28,11 +51,68 @@ int sched_task_fs_start(struct task *task,struct vfs_namespace *ns) */ void sched_task_fs_inherit(struct task *task,const struct task *parent) { - struct task_fs_paths next={0},*source=sched_task_paths(parent),*target=sched_task_paths(task); - next.ns=vfs_namespace_get(source->ns); - vfs_path_get(&source->root,&next.root);vfs_path_get(&source->cwd,&next.cwd); - struct task_fs_paths old=*target;*target=next; - vfs_path_put(&old.root);vfs_path_put(&old.cwd);vfs_namespace_put(old.ns); + struct task_fs_paths next = task_fs_paths_get(sched_task_paths(parent)); + struct task_fs_paths *target = sched_task_paths(task), old = *target; + *target = next; + sched_task_fs_paths_put(&old); +} + +/** @brief Stage a new mount namespace while retaining the exact source paths. + * @param task Borrowed source, including any CLONE_FS shared state. + * @param out Empty destination for the owned cloned state. + * @return Zero or negative errno. On failure all tentative references are put. + */ +int sched_task_fs_snapshot(const struct task *task, struct task_fs_paths *out) +{ + const struct task_fs_paths *source = sched_task_paths(task); + if (!source->ns) return -LINUX_ENODEV; + struct task_fs_paths paths = {0}; + vfs_path_get(&source->root, &paths.root); + vfs_path_get(&source->cwd, &paths.cwd); + int rc = vfs_namespace_clone(source->ns, &paths.root, &paths.cwd, &paths.ns); + if (rc) sched_task_fs_paths_put(&paths); + else *out = paths; + return rc; +} + +/** @brief Drop one shared filesystem-state reference, including its final pins. + * @param shared Detached shared state owned by this reference, or NULL. + */ +static void task_shared_fs_put(struct task_fs_state *shared) +{ + if (!shared || __atomic_sub_fetch(&shared->references, 1, __ATOMIC_SEQ_CST)) return; + sched_task_fs_paths_put(&shared->paths); + kernel_free(shared); +} + +/** @brief Replace only the calling task's filesystem state after preparation. + * @param task Execution-owned caller with validated flags and capability. + * @param new_namespace Snapshot the mount graph as well as separating CLONE_FS. + * @return Zero or negative errno; failures leave every old owner unchanged. + */ +int sched_task_fs_unshare(struct task *task, bool new_namespace) +{ + struct task_fs_state *shared = task->shared_fs; + struct task_fs_paths next = {0}; + if (new_namespace) { + int rc = sched_task_fs_snapshot(task, &next); + if (rc) return rc; + } else { + if (!shared) return 0; + next = task_fs_paths_get(&shared->paths); + } + + if (shared) { + task->umask = shared->umask; + __builtin_memcpy(task->cwd, shared->cwd, sizeof(task->cwd)); + __builtin_memcpy(task->root_dir, shared->root_dir, sizeof(task->root_dir)); + } + struct task_fs_paths old = task->fs_paths; + task->fs_paths = next; + task->shared_fs = NULL; + sched_task_fs_paths_put(&old); + task_shared_fs_put(shared); + return 0; } /** @brief Check whether a separate process can change a task's CLONE_FS state. @@ -62,10 +142,8 @@ bool sched_task_fs_shared_outside_group(const struct task *task) void sched_task_fs_release(struct task *task) { if(!task)return; - struct task_fs_state *shared=task->shared_fs;task->shared_fs=NULL; - if(shared && __atomic_sub_fetch(&shared->references,1,__ATOMIC_SEQ_CST))return; - struct task_fs_paths *paths=shared ? &shared->paths : &task->fs_paths; - struct task_fs_paths old=*paths;*paths=(struct task_fs_paths){0}; - vfs_path_put(&old.root);vfs_path_put(&old.cwd);vfs_namespace_put(old.ns); - if(shared)kernel_free(shared); + struct task_fs_state *shared = task->shared_fs; + task->shared_fs = NULL; + if (shared) task_shared_fs_put(shared); + else sched_task_fs_paths_put(&task->fs_paths); } diff --git a/kernel/sched/internal.h b/kernel/sched/internal.h index 4009b557..e4d75acb 100644 --- a/kernel/sched/internal.h +++ b/kernel/sched/internal.h @@ -682,9 +682,19 @@ void vfork_parent_exit_locked(struct task *parent); */ void sched_vfork_child_done(struct task *child); -int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flags, - uint64_t stack, uint64_t parent_tid, - uint64_t child_tid, uint64_t tls); +/** @brief Prepare independent paths in a new managed mount namespace. + * @param task Source task whose filesystem state is borrowed. + * @param out Empty output that owns the new namespace, root and cwd on success. + * @return Zero or the original VFS error, leaving the source and output intact. + * Requires execution ownership without scheduler_lock; rollback can put mounts. + */ +int sched_task_fs_snapshot(const struct task *task, struct task_fs_paths *out); + +/** @brief Detach and release owned namespace and path references. + * @param paths Owned state to clear before final provider puts. + * Requires execution ownership without scheduler_lock if state is not empty. + */ +void sched_task_fs_paths_put(struct task_fs_paths *paths); int64_t sched_fork_current(const struct trap_frame *frame); diff --git a/kernel/syscall/dispatch.c b/kernel/syscall/dispatch.c index b3e5a5a3..4687e72a 100644 --- a/kernel/syscall/dispatch.c +++ b/kernel/syscall/dispatch.c @@ -141,6 +141,8 @@ static int64_t syscall_dispatch_normalized_inner(const struct syscall_frame *fra } switch (frame->number) { + case LINUX_SYS_UNSHARE: + return syscall_unshare(sched_current_task(), frame->args[0]); case __NR_pidfd_open: case __NR_pidfd_send_signal: return syscall_dispatch_regs(sched_current_task(), frame->number, @@ -784,6 +786,7 @@ int64_t syscall_dispatch_regs(struct task *task, uint64_t number, uint64_t a0, u uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) { + if (number == LINUX_SYS_UNSHARE) return syscall_unshare(task, a0); if (number == __NR_pidfd_open) return syscall_pidfd_open(task, (int32_t)a0, (uint32_t)a1); if (number == __NR_pidfd_send_signal) return syscall_pidfd_send_signal(task, (int32_t)a0, (int32_t)a1, a2, (uint32_t)a3); diff --git a/kernel/syscall/process/clone.c b/kernel/syscall/process/clone.c index fae48838..0b8c0dec 100644 --- a/kernel/syscall/process/clone.c +++ b/kernel/syscall/process/clone.c @@ -132,3 +132,18 @@ int64_t syscall_clone3(const struct trap_frame *frame, uint64_t arguments, uint6 args.stack ? args.stack + args.stack_size : 0, args.parent_tid, args.child_tid, args.tls); } + +/** @brief Apply the supported Linux unshare flags without touching other tasks. + * @param task Current task under execution ownership, outside scheduler_lock. + * @param flags Native 64-bit flag word. CLONE_NEWNS implies CLONE_FS. + * @return Zero (including a no-op for flags=0), or negative Linux errno. + * Validate the entire request before preparing or publishing a snapshot. + */ +int64_t syscall_unshare(struct task *task, uint64_t flags) +{ + if (!task || (flags & ~(uint64_t)(CLONE_NEWNS | CLONE_FS))) return -LINUX_EINVAL; + if (!flags) return 0; + bool new_namespace = (flags & CLONE_NEWNS) != 0; + if (new_namespace && !(task->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; + return sched_task_fs_unshare(task, new_namespace); +} diff --git a/tools/test_mount_namespace_task.py b/tools/test_mount_namespace_task.py new file mode 100644 index 00000000..989e11e5 --- /dev/null +++ b/tools/test_mount_namespace_task.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +"""Exercise mount namespace creation through the real clone and unshare backends.""" +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[1] + +with tempfile.TemporaryDirectory(prefix="reliefnt-mount-namespace-task-") as directory: + output = str(Path(directory) / "mount_namespace_task") + subprocess.run([ + "cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", + "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", + "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", + "tools/tests/mount_namespace_task_test.c", "kernel/syscall/process/clone.c", + "kernel/device/mapping.c", "fs/security/access.c", "fs/vfs/lookup_cache.c", + "-o", output, + ], cwd=ROOT, check=True) + subprocess.run([output], cwd=ROOT, check=True, timeout=20) diff --git a/tools/tests/Makefile b/tools/tests/Makefile index 88a15a59..f7d291c7 100644 --- a/tools/tests/Makefile +++ b/tools/tests/Makefile @@ -15,7 +15,7 @@ test-host-smoke: --suite acpi_pm_timer --suite apic_timer --suite cpu_accounting \ --suite fat_async_read --suite fat_read_split \ --suite squashfs --suite squashfs_boot \ - --suite linux_pty --suite mount_backend --suite cgroup_scheduler \ + --suite linux_pty --suite mount_backend --suite mount_namespace_task --suite cgroup_scheduler \ --suite vdso_mapping --suite vdso_time test-smp-time: diff --git a/tools/tests/audio_device_test.c b/tools/tests/audio_device_test.c index a3cc161c..5227bbfa 100644 --- a/tools/tests/audio_device_test.c +++ b/tools/tests/audio_device_test.c @@ -28,13 +28,13 @@ #include "audio_device_fixture.h" /* Host allocator boundary; descriptor growth stays in the real scheduler. */ -#ifdef TASK12_FORK_RECLAIM_FIXTURE -extern bool task12_fork_heap_admit(uint64_t size); +#ifdef RELIEFNT_TEST_HEAP_ALLOC_GATE +extern bool RELIEFNT_TEST_HEAP_ALLOC_GATE(uint64_t size); #endif void *kernel_malloc(uint64_t size) { -#ifdef TASK12_FORK_RECLAIM_FIXTURE - if (!task12_fork_heap_admit(size)) return NULL; +#ifdef RELIEFNT_TEST_HEAP_ALLOC_GATE + if (!RELIEFNT_TEST_HEAP_ALLOC_GATE(size)) return NULL; #endif return malloc(size); } diff --git a/tools/tests/host-suites.list b/tools/tests/host-suites.list index 7cfebdd3..b06ceab5 100644 --- a/tools/tests/host-suites.list +++ b/tools/tests/host-suites.list @@ -159,6 +159,7 @@ usb_storage tools/test_usb_storage.py mbr_partitions tools/test_mbr_partitions.py mount_tree tools/test_mount_tree.py mount_backend tools/test_mount_backend.py +mount_namespace_task tools/test_mount_namespace_task.py cgroup_scheduler tools/test_cgroup_scheduler.py filesystem_registry tools/test_filesystem_registry.py filesystem_boundaries tools/test_filesystem_boundaries.py diff --git a/tools/tests/memory_pressure_fork_table_test.c b/tools/tests/memory_pressure_fork_table_test.c index 1fdea732..5b1ee833 100644 --- a/tools/tests/memory_pressure_fork_table_test.c +++ b/tools/tests/memory_pressure_fork_table_test.c @@ -1,6 +1,7 @@ /* Focused unpublished fork COW allocation failures: real scheduler, PTEs and * swap slots; modeled PMM admission and storage, with real swap eviction. */ #define TASK12_FORK_RECLAIM_FIXTURE 1 +#define RELIEFNT_TEST_HEAP_ALLOC_GATE task12_fork_heap_admit #define TASK8_FIX3_DEVICE_FORK 1 #define PAGING_PROTECTION_CUSTOM_FREE_MEMORY 1 #include "task8_clone_tid_real_test.c" diff --git a/tools/tests/mount_namespace_task_test.c b/tools/tests/mount_namespace_task_test.c new file mode 100644 index 00000000..97fb2029 --- /dev/null +++ b/tools/tests/mount_namespace_task_test.c @@ -0,0 +1,228 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +/** @file + * @brief Namespace creation through real scheduler, VFS and clone front ends. + */ +#define TASK8_CLONE_TID_TEST 1 +#define RELIEFNT_TEST_HEAP_ALLOC_GATE namespace_heap_admit +#include "sysv_shm_test.c" + +static int mount_budget = -1; +static unsigned mount_allocations, charges; +static const struct task *unpublished_child; + +/** @brief Fail the second snapshot attachment, after staging the first one. */ +bool namespace_heap_admit(uint64_t size) +{ + if (size != sizeof(struct vfs_mount) || mount_budget < 0) return true; + assert(!scheduler_lock.state && unpublished_child && !unpublished_child->pid); + ++mount_allocations; + return mount_budget-- > 0; +} + +/** @brief Count child publication charges without linking the cgroup backend. */ +void cgroup2_fork_commit(struct task *child, const struct task *parent) +{ + assert(child && child->pid && parent == sched_current_task() && scheduler_lock.state); + ++charges; +} + +struct clone_operands { + struct clone_args args; + uint32_t parent_tid, child_tid; +}; + +/** @brief Call the legacy clone frontend or decode a real clone3 argument block. */ +static int64_t clone_namespace(struct task *parent, struct clone_operands *user, + bool versioned, uint64_t flags) +{ + user->args = (struct clone_args){.flags = flags, .exit_signal = 17, + .parent_tid = (uintptr_t)&user->parent_tid, .child_tid = (uintptr_t)&user->child_tid}; + return versioned ? syscall_clone3(&parent->frame, (uintptr_t)&user->args, sizeof(user->args)) + : syscall_clone_prepared(&parent->frame, flags | 17, 0, + user->args.parent_tid, user->args.child_tid, 0); +} + +/** @brief Check distinct mount identities without replaying the diagnostic names. */ +static void assert_snapshot(const struct task *copy, const struct task *source) +{ + const struct task_fs_paths *paths = sched_task_paths(copy), *old = sched_task_paths(source); + assert(paths->ns && paths->ns != old->ns && paths->ns->references == 1); + assert(paths->root.mount == paths->ns->root && paths->root.mount != old->root.mount); + assert(paths->root.dentry == old->root.dentry && paths->cwd.dentry == old->cwd.dentry); + assert(paths->cwd.mount != old->cwd.mount && paths->cwd.mount->ns == paths->ns); + assert(paths->cwd.mount->point.mount == paths->root.mount); + assert(!strcmp(sched_task_root(copy), "/cached-root") && + !strcmp(sched_task_cwd(copy), "/cached-cwd") && *sched_task_umask(copy) == 0027); +} + +/** @brief Reap the successful fixture child with no external resources. */ +static void retire_child(struct task *child) +{ + sched_task_fs_release(child); + address_space_destroy(sched_task_as(child)); + sched_task_vma_release(child); + syscall_release_task_files(child); + task_groups_release(child); + kernel_free(child->exec_argv); + kernel_free(child->exec_envp); + kernel_free(child->exec_data); + sched_task_identity_detach(child); + task_zero(child); + child->state = TASK_EXITED; + child->running_cpu = SCHED_CPU_NONE; + child->flags = TASK_FLAG_RESOURCES_RELEASED; + vfs_reclaim_mounts(16); +} + +/** @brief Check unshare's capability, failure atomicity and implicit CLONE_FS. */ +static void check_unshare(struct task *task, const struct task *unpublished) +{ + uint64_t capability = task->cap_effective; + task->cap_effective = 0; + assert(syscall_unshare(task, CLONE_NEWNS) == -LINUX_EPERM); + task->cap_effective = capability; + assert(syscall_unshare(task, CLONE_NEWNS | (1ULL << 40)) == -LINUX_EINVAL); + assert(syscall_unshare(task, CLONE_NEWNS | CLONE_NEWNET) == -LINUX_EINVAL); + assert(!task_promote_shared(task, CLONE_FS)); + struct task sibling = {.shared_fs = task->shared_fs}; + ++sibling.shared_fs->references; + struct vfs_namespace *old = sched_task_namespace(task); + struct vfs_path root = sched_task_paths(task)->root, cwd = sched_task_paths(task)->cwd; + + assert(!syscall_unshare(task, 0) && task->shared_fs == sibling.shared_fs); + assert(!syscall_unshare(task, CLONE_FS) && !task->shared_fs && sched_task_namespace(task) == old); + assert(vfs_path_equal(&task->fs_paths.root, &root) && vfs_path_equal(&task->fs_paths.cwd, &cwd)); + sched_task_fs_release(&sibling); + assert(!task_promote_shared(task, CLONE_FS)); + sibling.shared_fs = task->shared_fs; + ++sibling.shared_fs->references; + + uint64_t mount_id = next_mount_id; + unsigned root_refs = root.mount->references, cwd_refs = cwd.mount->references; + unpublished_child = unpublished; + mount_budget = 1; + mount_allocations = 0; + assert(syscall_unshare(task, CLONE_NEWNS) == -LINUX_ENOMEM); + mount_budget = -1; + assert(mount_allocations == 2 && next_mount_id == mount_id); + assert(task->shared_fs == sibling.shared_fs && task->shared_fs->references == 2); + assert(old->references == 1 && root.mount->references == root_refs && cwd.mount->references == cwd_refs); + assert(vfs_path_equal(&task->shared_fs->paths.root, &root) && + vfs_path_equal(&task->shared_fs->paths.cwd, &cwd)); + + assert(!syscall_unshare(task, CLONE_NEWNS | CLONE_FS)); + assert(!task->shared_fs && sibling.shared_fs->references == 1); + assert(sched_task_namespace(&sibling) == old && old->references == 1); + assert(vfs_path_equal(&sibling.shared_fs->paths.root, &root) && + vfs_path_equal(&sibling.shared_fs->paths.cwd, &cwd)); + assert_snapshot(task, &sibling); + sched_task_fs_release(&sibling); +} + +int main(void) +{ + struct sched_task_object parent_object = {0}, child_object = {0}; + struct task *parent = &parent_object.task, *child = &child_object.task; + struct task *entries[] = {parent, child}; + task_zero(parent); + task_zero(child); + parent->pid = parent->tgid = 801; + parent->kind = TASK_KIND_USER; + parent->state = TASK_RUNNING; + parent->running_cpu = 0; + task_init_limits(parent); + child->state = TASK_EXITED; + child->running_cpu = SCHED_CPU_NONE; + child->flags = TASK_FLAG_RESOURCES_RELEASED; + tasks = entries; + task_count = task_capacity = 2; + current_pid[0] = parent->pid; + current_task[0] = parent; + empty_clone_boundary = true; + nx_enabled = true; + + uint64_t irq; + kernel_execution_lock_irqsave(&irq); + assert(address_space_create(sched_task_as(parent))); + uint64_t physical = mm_alloc_page(); + struct clone_operands *user = mm_phys_to_virt(physical); + assert(user && address_space_map_user_page(sched_task_as(parent), (uintptr_t)user, + physical, RELIEFNT_PAGE_WRITABLE)); + struct vfs_namespace ns = {0}; + struct vfs_mount *root, *volume; + struct storage_node node = {.type = RELIEFOS_FS_TYPE_DIR, .first_cluster = 1}; + assert(!vfs_mount_new(&fs_ops, NULL, NULL, &node, &root)); + assert(!vfs_namespace_init(&ns, root)); + vfs_mount_put(root); + assert(!sched_task_fs_start(parent, &ns)); + struct vfs_path jail = {0}, point = {0}; + node.first_cluster = 2; + assert(!vfs_bind_child(&parent->fs_paths.root, "jail", &node, &jail)); + node.first_cluster = 3; + assert(!vfs_bind_child(&jail, "work", &node, &point)); + node.first_cluster = 4; + assert(!vfs_mount_new(&fs_ops, NULL, NULL, &node, &volume)); + assert(!vfs_mount_attach(&ns, volume, &point)); + vfs_path_put(&point); + vfs_path_put(&parent->fs_paths.root); + parent->fs_paths.root = jail; + vfs_path_put(&parent->fs_paths.cwd); + vfs_path_get(&(struct vfs_path){volume, volume->root}, &parent->fs_paths.cwd); + vfs_mount_put(volume); + task_copy_cwd(parent, "/cached-cwd"); + task_copy_identity_text(parent->root_dir, sizeof(parent->root_dir), "/cached-root"); + parent->umask = 0027; + + /* Effective capability is required, even for UID 0 with permitted SYS_ADMIN. */ + uint64_t capability = 1ULL << CAP_SYS_ADMIN; + parent->cap_permitted = capability; + parent->cap_effective = capability; + for (unsigned versioned = 0; versioned < 2; ++versioned) { + parent->cap_effective = 0; + assert(clone_namespace(parent, user, versioned, CLONE_NEWNS) == -LINUX_EPERM); + parent->cap_effective = capability; + assert(clone_namespace(parent, user, versioned, CLONE_NEWNS | CLONE_FS) == -LINUX_EINVAL); + assert(!sched_clone_validate_flags(CLONE_NEWNS | CLONE_THREAD | CLONE_SIGHAND | CLONE_VM, 0)); + + uint64_t mount_id = next_mount_id, before = proc_created; + unsigned pages_before = live_pages(), root_refs = root->references, refs = volume->references; + unsigned pins = fs_backend_pins, old_charges = charges; + user->parent_tid = user->child_tid = 0x44444444; + unpublished_child = child; + mount_budget = 1; + mount_allocations = 0; + uint64_t flags = CLONE_NEWNS | CLONE_PARENT_SETTID | CLONE_CHILD_SETTID; + assert(clone_namespace(parent, user, versioned, flags) == -LINUX_ENOMEM); + mount_budget = -1; + assert(mount_allocations == 2 && next_mount_id == mount_id); + assert(!child->pid && child->state == TASK_EXITED && !child->identity_token); + assert(proc_created == before && charges == old_charges); + assert(user->parent_tid == 0x44444444 && user->child_tid == 0x44444444); + assert(ns.references == 1 && root->references == root_refs && volume->references == refs); + assert(fs_backend_pins == pins && live_pages() == pages_before); + + int64_t pid = clone_namespace(parent, user, versioned, flags); + assert(pid > 0 && child->pid == (uint32_t)pid && child->state == TASK_READY); + assert(user->parent_tid == (uint32_t)pid && user->child_tid == 0x44444444); + uint64_t tid = address_space_user_page_phys(sched_task_as(child), (uintptr_t)&user->child_tid); + assert(tid && tid != physical); + assert(((struct clone_operands *)mm_phys_to_virt(tid))->child_tid == (uint32_t)pid); + assert(proc_created == before + 1 && charges == old_charges + 1); + assert_snapshot(child, parent); + retire_child(child); + assert(ns.references == 1 && root->references == root_refs && volume->references == refs); + } + check_unshare(parent, child); + sched_task_fs_release(parent); + vfs_reclaim_mounts(16); + assert(!vfs_namespace_destroy(&ns) && !fs_backend_pins); + address_space_destroy(sched_task_as(parent)); + assert(!live_pages() && !writable_aliases && !vfs_reclaim_pending()); + current_task[0] = NULL; + current_pid[0] = 0; + tasks = NULL; + task_count = task_capacity = 0; + kernel_execution_unlock_irqrestore(irq); + puts("PASS mount namespace creation, exact root/cwd rebinding and late rollback"); + return 0; +} From f7201f7235d26d4c87b4343a565dd48aa64cc58c Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 06:33:47 +0800 Subject: [PATCH 17/97] feat(vfs): support mount namespace handles and setns --- Documentation/core-api/mount-namespaces.rst | 15 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 35 +++- .../en/LC_MESSAGES/userspace-api/abi.po | 49 +++++- .../LC_MESSAGES/core-api/mount-namespaces.po | 28 +++- .../ja/LC_MESSAGES/userspace-api/abi.po | 44 ++++- Documentation/userspace-api/abi.rst | 20 ++- configs/header-export.list | 1 + fs/Kbuild | 2 +- fs/nsfs/Kbuild | 4 + fs/nsfs/namespace.c | 153 ++++++++++++++++++ fs/proc/procfs.c | 70 +++++++- include/reliefnt/nsfs.h | 30 ++++ include/reliefnt/storage.h | 2 + include/reliefnt/syscall_internal.h | 9 ++ include/reliefnt/task/accessors.h | 8 + include/uapi/linux/nsfs.h | 9 ++ kernel/sched/fs.c | 21 +++ kernel/syscall/dispatch.c | 94 +++++++---- kernel/syscall/fd/open.c | 5 +- kernel/syscall/internal.h | 12 ++ kernel/syscall/io/io.c | 6 +- kernel/syscall/io/legacy_io.c | 3 + kernel/syscall/io/seek.c | 4 +- kernel/syscall/io/transfer.c | 4 +- kernel/syscall/io/vector.c | 6 +- kernel/syscall/process/Kbuild | 2 +- kernel/syscall/process/setns.c | 27 ++++ tools/test_linux_inventory.py | 2 +- tools/test_linux_ioctl_cloexec.py | 15 +- tools/test_lock_profile.py | 4 +- tools/test_memory_reporting.py | 2 +- tools/test_mount_backend.py | 7 +- tools/test_mount_namespace_task.py | 5 +- tools/test_procfs.py | 2 +- tools/test_rootfs.py | 2 +- tools/tests/lock_profile_sync_io_test.c | 3 + tools/tests/mount_backend_io_boundaries.c | 53 ++++++ tools/tests/mount_backend_test.c | 115 ++++++++++++- tools/tests/mount_namespace_task_test.c | 95 ++++++++++- tools/tests/procfs_directories_test.c | 99 ++++++++++++ tools/tests/task8_host_fixtures.json | 5 + tools/tests/task8_transfer_user_test.c | 5 + tools/tests/test-version.sh | 2 +- 43 files changed, 1001 insertions(+), 78 deletions(-) create mode 100644 fs/nsfs/Kbuild create mode 100644 fs/nsfs/namespace.c create mode 100644 include/reliefnt/nsfs.h create mode 100644 include/uapi/linux/nsfs.h create mode 100644 kernel/syscall/process/setns.c create mode 100644 tools/tests/mount_backend_io_boundaries.c diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 1c4adf19..15869f0c 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -54,6 +54,19 @@ VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载 因此快照失败不写回 TID、不计入 cgroup,也不发布子任务。快照及其回滚不持有 调度器自旋锁。接口的参数和权限见 :doc:`../userspace-api/abi`。 +句柄与切换 +========== + +``/proc//ns/mnt`` 是 proc magic link。读取链接或跟随它需要通过与 +``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 +PID 身份,旧链接不会因 PID 复用而指向新进程;每次成功跟随则取得目标当时的挂载图。 + +跟随链接得到分离的 nsfs inode,以挂载图锚点的 ID 作为 inode 号,并用 +``mnt:[ID]`` 显示。持有该路径或打开的文件描述会保留挂载图,而不依赖原进程存活。 +``setns()`` 依据文件描述所持的 nsfs 路径选择图,不使用路径文字或重新查找 PID。 +切换时 root 和 cwd 一起替换为目标图当前可见的根,不采用目标进程的 chroot 或 +cwd;已有文件描述符和 umask 不变。准备失败不会部分切换。 + 引用释放 ======== @@ -61,5 +74,3 @@ VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载 ``vfs_namespace_retire()`` 就地摘除整棵树而不传播卸载,随后释放图本身。已持有 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 ``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。 - -尚不提供挂载命名空间句柄(``/proc//ns/mnt``)或 ``setns()`` 切换。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 530788ca..09927146 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -137,6 +137,36 @@ msgstr "" " snapshot creation nor rollback holds the scheduler spinlock. For flags " "and permissions, see :doc:`../userspace-api/abi`." +msgid "句柄与切换" +msgstr "Handles and Switching" + +msgid "" +"``/proc//ns/mnt`` 是 proc magic link。读取链接或跟随它需要通过与 ``/proc//fd``" +" 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,旧链接不会因 PID " +"复用而指向新进程;每次成功跟随则取得目标当时的挂载图。" +msgstr "" +"``/proc//ns/mnt`` is a proc magic link. Reading or following it " +"requires the same ``PTRACE_MODE_READ_FSCREDS`` permission check as " +"``/proc//fd``. The link key retains the PID identity, so an old link" +" never resolves to a new process after PID reuse. Each successful follow " +"acquires the target’s current mount graph." + +msgid "" +"跟随链接得到分离的 nsfs inode,以挂载图锚点的 ID 作为 inode 号,并用 ``mnt:[ID]`` " +"显示。持有该路径或打开的文件描述会保留挂载图,而不依赖原进程存活。 ``setns()`` 依据文件描述所持的 nsfs " +"路径选择图,不使用路径文字或重新查找 PID。 切换时 root 和 cwd 一起替换为目标图当前可见的根,不采用目标进程的 chroot 或 " +"cwd;已有文件描述符和 umask 不变。准备失败不会部分切换。" +msgstr "" +"Following the link yields a detached nsfs inode whose inode number is the" +" mount graph anchor ID and whose display name is ``mnt:[ID]``. A held " +"path or open file description retains the graph independently of the " +"original process. ``setns()`` selects the graph from the file " +"description’s nsfs path, not from path text or a new PID lookup. It " +"replaces root and cwd together with the currently visible root of the " +"target graph, not the target process’s chroot or cwd. Existing file " +"descriptors and the umask are unchanged. Preparation failure leaves the " +"caller in the original namespace." + msgid "引用释放" msgstr "Reference release" @@ -152,8 +182,3 @@ msgstr "" "still own storage for boot and test graphs. The strict " "``vfs_namespace_destroy()`` refuses to destroy a graph with outstanding " "graph or external path references." - -msgid "尚不提供挂载命名空间句柄(``/proc//ns/mnt``)或 ``setns()`` 切换。" -msgstr "" -"Mount namespace handles (``/proc//ns/mnt``) and switching with " -"``setns()`` are not yet available." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index f940cb5c..f61fabc4 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -75,15 +75,54 @@ msgstr "" msgid "" "新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | " -"MS_PRIVATE`` 使子树停止传播。 目前不支持通过 ``setns()`` 加入既有挂载命名空间。参见 :doc:`../core-api" -"/mount-namespaces`。" +"MS_PRIVATE`` 使子树停止传播。" msgstr "" "The old and new mount trees share file contents. Root and cwd retain " "their directory identities, and existing open files are not rebound. " "Shared mounts can still propagate events; use ``MS_REC | MS_PRIVATE`` to " -"stop propagation for a subtree. Joining an existing namespace with " -"``setns()`` is not yet supported. See :doc:`../core-api/mount-" -"namespaces`." +"stop propagation for a subtree." + +msgid "加入挂载命名空间" +msgstr "Joining a Mount Namespace" + +msgid "" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 " +"``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 " +"``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 " +"``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 返回 ``EINVAL``。不支持 " +"pidfd、其他种类的命名空间或文件 bind mount。" +msgstr "" +"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNS)`` accept a " +"``/proc//ns/mnt`` handle opened as an ordinary read-only FD. The " +"caller needs effective ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` or the " +"call returns ``EPERM``. Invalid or ``O_PATH`` FDs return ``EBADF``. An " +"unsupported type, a non-nsfs FD, or ``CLONE_FS`` state still shared with " +"another task returns ``EINVAL``. Pidfds, other namespace types, and file " +"bind mounts are not supported." + +msgid "" +"切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。参见 " +":doc:`../core-api/mount-namespaces`。" +msgstr "" +"After switching, root and cwd both point to the visible root of the " +"target mount graph. Existing FDs and the umask are preserved. The handle " +"remains usable after the original process exits or changes namespaces. " +"See :doc:`../core-api/mount-namespaces`." + +msgid "" +"nsfs 句柄不是字节流。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 " +"FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 " +"``ESPIPE``。 ``NS_GET_NSTYPE`` 返回 ``CLONE_NEWNS``,``FIONREAD`` 写回零,不支持的 " +"namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" +msgstr "" +"An nsfs handle is not a byte stream. Opening it for writing or with " +"``O_TRUNC`` returns ``EPERM``; ``O_PATH`` ignores these open flags. " +"Scalar, positioned, and vectored reads on an ordinary FD return " +"``EINVAL``; writes return ``EBADF``. ``lseek()`` with a valid ``whence`` " +"returns ``ESPIPE``. ``NS_GET_NSTYPE`` returns ``CLONE_NEWNS``, " +"``FIONREAD`` writes back zero, and unsupported namespace ioctls return " +"``ENOTTY``. An ``O_PATH`` FD supports metadata queries but not read, " +"write, seek, or ioctl operations." msgid "目录 bind mount" msgstr "Directory Bind Mounts" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 50dc7962..e57daa7c 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -117,6 +117,31 @@ msgstr "" "への計上、子タスクの公開は行いません。スナップショットの作成とロールバックでは、スケジューラのスピンロックを保持しません。フラグと権限については " ":doc:`../userspace-api/abi` を参照してください。" +msgid "句柄与切换" +msgstr "ハンドルと名前空間の切り替え" + +msgid "" +"``/proc//ns/mnt`` 是 proc magic link。读取链接或跟随它需要通过与 ``/proc//fd``" +" 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,旧链接不会因 PID " +"复用而指向新进程;每次成功跟随则取得目标当时的挂载图。" +msgstr "" +"``/proc//ns/mnt`` は proc のマジックリンクです。リンクを読み取る場合もたどる場合も、 " +"``/proc//fd`` と同じ ``PTRACE_MODE_READ_FSCREDS`` の権限チェックが必要です。リンクのキーには" +" PID の識別情報が保持され、PID " +"が再利用されても古いリンクが新しいプロセスを指すことはありません。リンクをたどるたびに、その時点の対象のマウントグラフを取得します。" + +msgid "" +"跟随链接得到分离的 nsfs inode,以挂载图锚点的 ID 作为 inode 号,并用 ``mnt:[ID]`` " +"显示。持有该路径或打开的文件描述会保留挂载图,而不依赖原进程存活。 ``setns()`` 依据文件描述所持的 nsfs " +"路径选择图,不使用路径文字或重新查找 PID。 切换时 root 和 cwd 一起替换为目标图当前可见的根,不采用目标进程的 chroot 或 " +"cwd;已有文件描述符和 umask 不变。准备失败不会部分切换。" +msgstr "" +"リンクをたどると、マウントグラフのアンカー ID を inode 番号に持ち、 ``mnt:[ID]`` と表示される切り離された nsfs " +"inode が得られます。保持中のパスやオープンファイル記述がグラフを保持するため、元のプロセスが終了してもグラフは失われません。 " +"``setns()`` はパスの文字列や PID の再検索ではなく、オープンファイル記述が保持する nsfs " +"のパスからグラフを選びます。切り替え時には root と cwd を対象グラフで現在見えているルートに一緒に置き換え、対象プロセスの chroot" +" や cwd は引き継ぎません。既存のファイル記述子と umask は変わりません。準備に失敗した場合、名前空間は切り替わりません。" + msgid "引用释放" msgstr "参照の解放" @@ -129,6 +154,3 @@ msgstr "" "``vfs_namespace_retire()`` " "がアンマウントを伝播させずにツリー全体を切り離し、その後グラフ自体を解放します。保持中のパスは有効なままで、既存の遅延処理キューがバックエンドを後処理します。起動時とテスト用のグラフの記憶領域は引き続き呼び出し側が管理します。厳格な" " ``vfs_namespace_destroy()`` はグラフの参照や外部パス参照が残っている間は破棄を拒否します。" - -msgid "尚不提供挂载命名空间句柄(``/proc//ns/mnt``)或 ``setns()`` 切换。" -msgstr "マウント名前空間のハンドル( ``/proc//ns/mnt`` )と ``setns()`` による切り替えは、まだ利用できません。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index fbc3cae7..debed879 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -68,14 +68,48 @@ msgstr "" msgid "" "新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | " -"MS_PRIVATE`` 使子树停止传播。 目前不支持通过 ``setns()`` 加入既有挂载命名空间。参见 :doc:`../core-api" -"/mount-namespaces`。" +"MS_PRIVATE`` 使子树停止传播。" msgstr "" "新旧のマウントツリーはファイルの内容を共有します。root と cwd " "は元のディレクトリを指し、既に開いているファイルの参照先は変わりません。共有マウントでは引き続きイベントが伝播します。サブツリーの伝播を止めるには" -" ``MS_REC | MS_PRIVATE`` を使用します。 ``setns()`` " -"による既存のマウント名前空間への参加には、まだ対応していません。 :doc:`../core-api/mount-namespaces` " -"を参照してください。" +" ``MS_REC | MS_PRIVATE`` を使用します。" + +msgid "加入挂载命名空间" +msgstr "マウント名前空間への参加" + +msgid "" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 " +"``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 " +"``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 " +"``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 返回 ``EINVAL``。不支持 " +"pidfd、其他种类的命名空间或文件 bind mount。" +msgstr "" +"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNS)`` は、通常の読み取り専用 FD として開いた " +"``/proc//ns/mnt`` のハンドルを受け付けます。呼び出し元に実効 ``CAP_SYS_ADMIN`` と " +"``CAP_SYS_CHROOT`` が必要で、どちらかがなければ ``EPERM`` を返します。無効な FD や ``O_PATH`` FD " +"は ``EBADF`` を返します。未対応の型、nsfs 以外の FD、他のタスクとまだ共有されている ``CLONE_FS`` 状態では " +"``EINVAL`` を返します。pidfd、ほかの種類の名前空間、ファイルの bind mount には対応していません。" + +msgid "" +"切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。参见 " +":doc:`../core-api/mount-namespaces`。" +msgstr "" +"切り替え後の root と cwd はいずれも対象のマウントグラフで見えているルートを指し、既存の FD と umask " +"は保持されます。元のプロセスが終了した後や名前空間を切り替えた後でもハンドルは使用できます。 :doc:`../core-api/mount-" +"namespaces` を参照してください。" + +msgid "" +"nsfs 句柄不是字节流。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 " +"FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 " +"``ESPIPE``。 ``NS_GET_NSTYPE`` 返回 ``CLONE_NEWNS``,``FIONREAD`` 写回零,不支持的 " +"namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" +msgstr "" +"nsfs ハンドルはバイトストリームではありません。書き込み用または ``O_TRUNC`` 付きで開くと ``EPERM`` になり、 " +"``O_PATH`` はこれらのフラグを無視します。通常の FD では単一バッファ、位置指定、ベクトルの読み取りは " +"``EINVAL``、書き込みは ``EBADF`` を返します。有効な ``whence`` での ``lseek()`` は " +"``ESPIPE`` を返します。 ``NS_GET_NSTYPE`` は ``CLONE_NEWNS`` を返し、 ``FIONREAD`` " +"はゼロを書き戻し、未対応の namespace ioctl は ``ENOTTY`` を返します。 ``O_PATH`` FD " +"ではメタデータを取得できますが、読み書き、シーク、ioctl はできません。" msgid "目录 bind mount" msgstr "ディレクトリーの bind mount" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index e4f92fec..1cfd8bcf 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -51,7 +51,25 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | MS_PRIVATE`` 使子树停止传播。 -目前不支持通过 ``setns()`` 加入既有挂载命名空间。参见 :doc:`../core-api/mount-namespaces`。 + +加入挂载命名空间 +================ + +``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 +``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 +``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 +``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 +返回 ``EINVAL``。不支持 pidfd、其他种类的命名空间或文件 bind mount。 + +切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 +仍可在原进程退出或切换命名空间后使用。参见 :doc:`../core-api/mount-namespaces`。 + +nsfs 句柄不是字节流。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, +``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, +写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 +``NS_GET_NSTYPE`` 返回 ``CLONE_NEWNS``,``FIONREAD`` 写回零,不支持的 +namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 +读写、定位或执行 ioctl。 目录 bind mount =============== diff --git a/configs/header-export.list b/configs/header-export.list index c350005d..c3db0ad8 100644 --- a/configs/header-export.list +++ b/configs/header-export.list @@ -48,6 +48,7 @@ include/uapi/linux/mman.h include/uapi/linux/module.h include/uapi/linux/mount.h include/uapi/linux/msg.h +include/uapi/linux/nsfs.h include/uapi/linux/openat2.h include/uapi/linux/patchkey.h include/uapi/linux/pidfd.h diff --git a/fs/Kbuild b/fs/Kbuild index 17014fc1..53f0da56 100644 --- a/fs/Kbuild +++ b/fs/Kbuild @@ -1,6 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 # Objects are owned by this directory; child modules own their own lists. -obj-y := initramfs/ cgroup/ devfs/ devpts/ proc/ security/ sysfs/ tmpfs/ vfs/ notify/ +obj-y := initramfs/ cgroup/ devfs/ devpts/ nsfs/ proc/ security/ sysfs/ tmpfs/ vfs/ notify/ obj-$(CONFIG_EXT_FS_COMMON) += ext_common/ obj-$(CONFIG_EXT2_FS) += ext2/ obj-$(CONFIG_EXT3_FS) += ext3/ diff --git a/fs/nsfs/Kbuild b/fs/nsfs/Kbuild new file mode 100644 index 00000000..64af3d88 --- /dev/null +++ b/fs/nsfs/Kbuild @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: Apache-2.0 +obj-y := namespace.o + +include $(srctree)/scripts/Makefile.module diff --git a/fs/nsfs/namespace.c b/fs/nsfs/namespace.c new file mode 100644 index 00000000..e8b64003 --- /dev/null +++ b/fs/nsfs/namespace.c @@ -0,0 +1,153 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include +#include +#include +#include +#include "../vfs/mount_internal.h" + +#define NSFS_DEVICE 204u +#define NSFS_MAGIC 0x6e736673 +#define NSFS_LABEL_BYTES (sizeof("mnt:[]") + 20u) + +static const struct vfs_backend_ops nsfs_ops; + +/** @brief Test immutable namespace inode metadata in its own backend. */ +static bool nsfs_inode(const struct vfs_namespace *ns, const struct storage_node *node) +{ + return node->type == RELIEFOS_FS_TYPE_FILE && node->entry_id == ns->root->id; +} + +/** @copydoc nsfs_readlink */ +int nsfs_readlink(const struct vfs_namespace *ns, char *buffer, size_t capacity) +{ + if (!ns || !ns->root) return -ENOENT; + struct text_stream text = {.buffer = buffer, + .capacity = capacity > NSFS_LABEL_BYTES ? NSFS_LABEL_BYTES : (uint32_t)capacity}; + text_string(&text, "mnt:["); + text_unsigned(&text, ns->root->id); + text_string(&text, "]"); + return (int)text.written; +} + +/** @brief A detached namespace backend has no named children. */ +static int nsfs_lookup(void *context, const struct storage_node *parent, + const char *name, struct storage_node *out) +{ + (void)context; (void)parent; (void)name; (void)out; + return -ENOENT; +} + +/** @brief Mark a handle inode while its mount keeps the graph alive. */ +static int nsfs_retain(void *context, const struct storage_node *node, void **pin) +{ + *pin = NULL; + if (node->type == RELIEFOS_FS_TYPE_DIR && !node->entry_id) return 0; + if (!nsfs_inode(context, node)) return -ENOENT; + *pin = context; + return 0; +} + +/** @brief No per-dentry graph reference is needed while the backend is live. */ +static void nsfs_release(void *context, const struct storage_node *node, void *pin) +{ + (void)context; (void)node; (void)pin; +} + +/** @brief Compare inode identities in the same retained graph. */ +static bool nsfs_same(void *context, const struct storage_node *a, const struct storage_node *b) +{ + (void)context; + return a->type == b->type && a->entry_id == b->entry_id; +} + +/** @brief Final backend release drops its graph pin, never under a spinlock. */ +static void nsfs_destroy(void *context) +{ + vfs_namespace_put(context); +} + +/** @brief Namespace handles have metadata and ioctls, not a byte stream. */ +static int nsfs_read(void *context, const struct storage_node *node, uint64_t offset, + void *buffer, uint32_t capacity, uint32_t *read, uint64_t flags) +{ + (void)context; (void)node; (void)offset; (void)buffer; (void)capacity; (void)flags; + *read = 0; + return -EINVAL; +} + +/** @brief Report immutable root-owned permissions on the synthetic inode. */ +static int nsfs_permissions(void *context, const struct vfs_path *path, + struct reliefos_permissions *value, bool write) +{ + (void)context; + if (write) return -EPERM; + *value = (struct reliefos_permissions){vfs_path_node(path)->type == RELIEFOS_FS_TYPE_DIR ? 0555 : 0444, 0, 0}; + return 0; +} + +/** @brief Use the permanent anchor ID as the exported namespace inode number. */ +static int nsfs_getattr(void *context, const struct vfs_path *path, struct linux_stat_abi *out) +{ + (void)context; + int rc = vfs_stat_basic(vfs_path_node(path), out); + if (rc) return rc; + struct reliefos_permissions mode; + nsfs_permissions(context, path, &mode, false); + out->st_mode |= mode.mode; + out->st_dev = NSFS_DEVICE; + return 0; +} + +/** @brief Report the nsfs filesystem type without exposing a backing device. */ +static int nsfs_statfs(void *context, const struct storage_node *node, struct linux_statfs_abi *out) +{ + (void)context; (void)node; + *out = (struct linux_statfs_abi){.f_type = NSFS_MAGIC, .f_bsize = 4096, + .f_frsize = 4096, .f_namelen = VFS_NAME_MAX, .f_fsid = {NSFS_DEVICE, 0}}; + return 0; +} + +/** @brief Format a retained namespace inode for /proc//fd diagnostics. */ +static int nsfs_display(void *context, const struct storage_node *node, char *buffer, size_t capacity) +{ + if (!nsfs_inode(context, node)) return -ENOENT; + char label[NSFS_LABEL_BYTES]; + int length = nsfs_readlink(context, label, sizeof(label)); + if (length < 0) return length; + if ((size_t)length >= capacity) return -ENAMETOOLONG; + __builtin_memcpy(buffer, label, (size_t)length); + buffer[length] = 0; + return 0; +} + +static const struct vfs_backend_ops nsfs_ops = { + .lookup = nsfs_lookup, .retain = nsfs_retain, .release = nsfs_release, + .same_node = nsfs_same, .destroy = nsfs_destroy, .read = nsfs_read, + .permissions = nsfs_permissions, .getattr = nsfs_getattr, .statfs = nsfs_statfs, + .display_name = nsfs_display, +}; + +/** @copydoc nsfs_create_path */ +int nsfs_create_path(struct vfs_namespace *ns, struct vfs_path *out) +{ + if (!out) return -EINVAL; + *out = (struct vfs_path){0}; + if (!ns || !ns->root) return -ENOENT; + struct storage_node root = {.type = RELIEFOS_FS_TYPE_DIR}; + struct storage_node node = {.type = RELIEFOS_FS_TYPE_FILE, + .flags = STORAGE_NODE_FLAG_NSFS, .entry_id = ns->root->id}; + struct vfs_mount *mount; + int rc = vfs_mount_new(&nsfs_ops, vfs_namespace_get(ns), NULL, &root, &mount); + if (rc) { vfs_namespace_put(ns); return rc; } + rc = vfs_path_anonymous(mount, &node, out); + vfs_mount_put(mount); + return rc; +} + +/** @copydoc nsfs_path_namespace */ +struct vfs_namespace *nsfs_path_namespace(const struct vfs_path *path) +{ + if (!vfs_path_valid(path) || path->mount->ops != &nsfs_ops) return NULL; + struct vfs_namespace *ns = path->mount->context; + return path->dentry->backend_pin == ns && nsfs_inode(ns, &path->dentry->node) ? ns : NULL; +} diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 8b6aae4a..1a7ac03b 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -685,6 +686,11 @@ int proc_fd_get_path(struct task *target,int fd,struct vfs_path *out) vfs_path_get(path,out);return 0; } +/** @brief Retain the proc key's PID identity and classify exact magic links. + * @param name Intrinsic proc key. @param out Receives the owned identity, if any. + * @param magic True for a link followed by object identity rather than text. + * @return Zero or negative errno. Reused PIDs cannot retarget a retained key. + */ int proc_mount_node_identity(const char *name,struct task_identity **out,bool *magic) { if(!out || !magic)return -RELIEFOS_EINVAL; @@ -698,7 +704,9 @@ int proc_mount_node_identity(const char *name,struct task_identity **out,bool *m struct task *task=kind==3 ? sched_current_task() : sched_find(pid); int rc=sched_task_identity_get(task,out); if(rc)return rc==-ESRCH ? -RELIEFOS_ENOENT : rc; - *magic=file && (proc_fd_number(file)>=0 || proc_text_eq(file,"cwd") || proc_text_eq(file,"root") || proc_text_eq(file,"exe")); + *magic = file && (proc_fd_number(file) >= 0 || proc_text_eq(file, "cwd") || + proc_text_eq(file, "root") || proc_text_eq(file, "exe") || + proc_text_eq(file, "ns/mnt")); return 0; } @@ -727,6 +735,12 @@ int proc_mount_magic_stat(const char *name,struct linux_stat_abi *out) return rc==-RELIEFOS_EBADF ? -RELIEFOS_ENOENT : rc; } +/** @brief Follow an authorized proc magic link to an owned object path. + * @param name Live intrinsic proc key, already checked against its retained PID. + * @param out Receives one owned path; empty on failure. + * @return Zero or negative errno. A namespace link captures the target's + * current graph, not the graph it had when the proc link was looked up. + */ int proc_mount_magic_target(const char *name,struct vfs_path *out) { if(!out)return -RELIEFOS_EINVAL; @@ -737,6 +751,7 @@ int proc_mount_magic_target(const char *name,struct vfs_path *out) if(!task)return -RELIEFOS_ENOENT; int fd=proc_fd_number(file);if(fd>=0)return proc_fd_get_path(task,fd,out); if(!proc_stat_mm_visible(sched_current_task(),task))return -RELIEFOS_EACCES; + if (proc_text_eq(file, "ns/mnt")) return nsfs_create_path(sched_task_namespace(task), out); struct task_fs_paths *paths=sched_task_paths(task); if(proc_text_eq(file,"cwd"))vfs_path_get(&paths->cwd,out); else if(proc_text_eq(file,"root"))vfs_path_get(&paths->root,out); @@ -828,6 +843,12 @@ static void proc_task_stat(struct task *task, struct text_stream *s, bool proces * @param out Optional caller-owned writable node metadata. * @return Zero or negative ENOENT. Execution-owned; no reference transfers. * Includes the unified cgroup membership file in process and thread views. */ +/** @brief Resolve a proc key, including live per-task namespace entries. + * @param path Required intrinsic absolute proc key. + * @param out Optional destination for node metadata, without ownership. + * @return Zero or negative errno; access to magic-link targets is checked + * separately at follow/readlink time. + */ int proc_lookup(const char *path, struct storage_node *out) { int extra = proc_extra_kind(path); @@ -930,6 +951,13 @@ int proc_lookup(const char *path, struct storage_node *out) const char *file = 0; uint32_t pid = 0; int kind = proc_path_kind(path, &file, &pid); + if ((kind == 2 || kind == 3) && + (proc_text_eq(file, "ns") || proc_text_eq(file, "ns/mnt"))) { + if (!(kind == 3 ? sched_current_task() : sched_find(pid))) return -RELIEFOS_ENOENT; + if (out) *out = (struct storage_node){.flags = STORAGE_NODE_FLAG_PROC, + .type = proc_text_eq(file, "ns") ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_SYMLINK}; + return 0; + } if ((kind == 2 || kind == 3) && file && proc_text_eq(file, "fd")) { struct task *task = kind == 3 ? sched_current_task() : sched_find(pid); if (!task) return -RELIEFOS_ENOENT; @@ -1117,6 +1145,13 @@ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, * @param capacity Nonzero destination capacity. * @return Copied byte count, EINVAL for non-links, ENOENT, or EACCES on cross-task denial. */ +/** @brief Read the visible label of a proc link without opening its target. + * @param path Intrinsic proc key subject to caller credential checks. + * @param buffer Required output; no terminating NUL is part of the result. + * @param capacity Maximum output bytes. + * @return Bytes written or negative errno. Namespace labels reflect the live + * target's current mount graph without taking an open handle reference. + */ int proc_readlink(const char *path, char *buffer, uint32_t capacity) { const char *file = NULL; @@ -1155,6 +1190,10 @@ int proc_readlink(const char *path, char *buffer, uint32_t capacity) } task = kind == 3 ? caller : sched_find(pid); if (!task) return -RELIEFOS_ENOENT; + if (proc_text_eq(file, "ns/mnt")) { + if (!proc_stat_mm_visible(caller, task)) return -RELIEFOS_EACCES; + return nsfs_readlink(sched_task_namespace(task), buffer, capacity); + } if (!file || (!proc_text_eq(file, "exe") && !proc_text_eq(file, "cwd") && !proc_text_eq(file, "root") && proc_fd_number(file) < 0)) return proc_lookup(path, NULL) == 0 ? -RELIEFOS_EINVAL : -RELIEFOS_ENOENT; if (!proc_stat_mm_visible(caller,task)) return -RELIEFOS_EACCES; @@ -1182,6 +1221,12 @@ int proc_readlink(const char *path, char *buffer, uint32_t capacity) * and retains the provider; no scheduler lock spans a generated-file callback. * The process entries include unified cgroup membership. */ +/** @brief Enumerate a proc directory, including the live task's ns/mnt link. + * @param path Required intrinsic proc directory key. + * @param offset Required in/out continuation cookie. + * @param entry Required output for the next entry. + * @return One for an entry, zero at end, or negative errno. + */ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry *entry) { uint32_t index; @@ -1272,6 +1317,13 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * uint32_t pid; int kind = proc_path_kind(path, &file, &pid); if (kind == 3) pid = sched_current_pid(); + if ((kind == 2 || kind == 3) && proc_text_eq(file, "ns")) { + if (!sched_find(pid)) return -RELIEFOS_ENOENT; + if (*offset) return 0; + *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_SYMLINK, .name = "mnt"}; + *offset = 1; + return 1; + } if ((kind == 2 || kind == 3) && file && proc_text_eq(file, "fd")) { struct task *task = sched_find(pid); struct task *caller = sched_current_task(); @@ -1300,13 +1352,14 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * "exe", "cwd", "root", "comm", "environ", "fd", "task", "fdinfo", "limits", "statm", "maps", "smaps", "smaps_rollup", "auxv", "io", - "oom_score", "oom_score_adj", "cgroup"}; + "oom_score", "oom_score_adj", "cgroup", "ns"}; if (*offset == 11 && (proc_thread_path(path) || sched_task_tgid(sched_find(pid)) != pid || !__builtin_strncmp(path, "/proc/thread-self", 17))) ++*offset; if (*offset >= sizeof(task_files) / sizeof(task_files[0])) return 0; *entry = (struct reliefos_dir_entry){ - .type = (*offset == 10 || *offset == 11 || *offset == 12) ? RELIEFOS_FS_TYPE_DIR + .type = (*offset == 10 || *offset == 11 || *offset == 12 || + proc_text_eq(task_files[*offset], "ns")) ? RELIEFOS_FS_TYPE_DIR : *offset >= 5 && *offset <= 7 ? RELIEFOS_FS_TYPE_SYMLINK : RELIEFOS_FS_TYPE_FILE}; proc_copy(entry->name, sizeof(entry->name), task_files[(*offset)++]); @@ -1366,6 +1419,17 @@ int proc_control_permissions(const char *name, const struct storage_node *node, #endif if (rc || write) return rc; if (proc_inotify_key && proc_inotify_key(name)) value->mode = 0644; + if (node->type == RELIEFOS_FS_TYPE_DIR || node->type == RELIEFOS_FS_TYPE_SYMLINK) { + const char *leaf = NULL; + struct task *owner = proc_view_task(name, &leaf); + if (owner && (proc_text_eq(leaf, "ns") || proc_text_eq(leaf, "ns/mnt"))) { + value->mode = node->type == RELIEFOS_FS_TYPE_DIR ? 0511 : 0777; + if (!sched_task_mm(owner)->nondumpable) { + value->uid = owner->euid; + value->gid = owner->egid; + } + } + } struct task *task = NULL; int which = proc_oom_key(name, &task); if (which) { if (!task || task->kind != TASK_KIND_USER || (task->flags & TASK_FLAG_RESOURCES_RELEASED)) diff --git a/include/reliefnt/nsfs.h b/include/reliefnt/nsfs.h new file mode 100644 index 00000000..1962113b --- /dev/null +++ b/include/reliefnt/nsfs.h @@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_NSFS_H +#define RELIEFNT_NSFS_H +#include + +struct vfs_namespace; +struct vfs_path; + +/** @brief Create a detached nsfs path retaining the actual mount graph. + * @param ns Borrowed live graph, stable under execution ownership. + * @param out Required empty destination for one owned namespace handle. + * @return Zero or negative errno; failure leaves the output empty. + */ +int nsfs_create_path(struct vfs_namespace *ns, struct vfs_path *out); + +/** @brief Identify the mount graph from an authentic retained nsfs inode. + * @param path Borrowed held path under execution ownership, nullable. + * @return Borrowed graph valid while the path is held, or NULL for another + * inode. Recorded names, device numbers and OFD kinds do not confer authority. + */ +struct vfs_namespace *nsfs_path_namespace(const struct vfs_path *path); + +/** @brief Generate a namespace magic-link label without allocating a handle. + * @param ns Borrowed live graph, nullable. + * @param buffer Required output, not NUL-terminated. + * @param capacity Maximum bytes to copy. + * @return Number of bytes copied (possibly truncated), or negative errno. + */ +int nsfs_readlink(const struct vfs_namespace *ns, char *buffer, size_t capacity); +#endif diff --git a/include/reliefnt/storage.h b/include/reliefnt/storage.h index 6268626a..27925c2b 100644 --- a/include/reliefnt/storage.h +++ b/include/reliefnt/storage.h @@ -297,6 +297,8 @@ struct storage_read_cursor { #define STORAGE_NODE_FLAG_DEVPTS 0x00400000u /* Generated cgroup2 controls, not regular-file data for RLIMIT_FSIZE. */ #define STORAGE_NODE_FLAG_CGROUP 0x00800000u +/* Metadata-only nsfs inode. Authority to join comes from the held VFS path. */ +#define STORAGE_NODE_FLAG_NSFS 0x01000000u #define STORAGE_SYSFS_DEVICE 202u #define STORAGE_NODE_FLAG_DEV_LINK 0x00000200u /* Anonymous filesystem device numbers, also exported in proc mountinfo. */ diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index 22da0bf3..a3bb423c 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -21,6 +21,15 @@ struct storage_inode_ref; */ int64_t syscall_unshare(struct task *task, uint64_t flags); +/** @brief Join the mount namespace pinned by a normal nsfs descriptor. + * @param task Live caller under exclusive kernel execution ownership. + * @param fd Native descriptor number, already reduced to 32 bits. + * @param type Zero or CLONE_NEWNS, already reduced to 32 bits. + * @return Zero, EBADF for an invalid/O_PATH FD, EINVAL for an unsupported + * type, FD or shared filesystem state, or EPERM for missing capabilities. + */ +int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type); + /* Entry-private marker for a retryable mmap file-metadata operation. */ #define KERNEL_MMAP_FILE_IO_RETRY (-4098LL) /* A competing task owns storage; no swap I/O was queued or accepted. */ diff --git a/include/reliefnt/task/accessors.h b/include/reliefnt/task/accessors.h index ef03b108..bbe9df4d 100644 --- a/include/reliefnt/task/accessors.h +++ b/include/reliefnt/task/accessors.h @@ -237,6 +237,14 @@ bool sched_task_fs_shared_outside_group(const struct task *task); */ int sched_task_fs_unshare(struct task *task, bool new_namespace); +/** @brief Install a borrowed mount graph at its current visible root. + * @param task Live caller under execution ownership, outside scheduler_lock. + * @param ns Borrowed live target graph, retained before the old pins retire. + * @return Zero, EINVAL if CLONE_FS has multiple holders, or the VFS root error. + * Root and cwd become the new visible root; umask and descriptors stay intact. + */ +int sched_task_fs_join_namespace(struct task *task, struct vfs_namespace *ns); + /** @brief Retire task graph/path pins or its one shared CLONE_FS reference. * @param task Quiescent task under execution ownership; nullable. * Clears ownership before final backend release, which may perform I/O. diff --git a/include/uapi/linux/nsfs.h b/include/uapi/linux/nsfs.h new file mode 100644 index 00000000..a97fb6c7 --- /dev/null +++ b/include/uapi/linux/nsfs.h @@ -0,0 +1,9 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFOS_UAPI_LINUX_NSFS_H +#define RELIEFOS_UAPI_LINUX_NSFS_H +#include + +#define NSIO 0xb7 +#define NS_GET_NSTYPE _IO(NSIO, 0x3) + +#endif diff --git a/kernel/sched/fs.c b/kernel/sched/fs.c index 2ad009b7..5a8c62ca 100644 --- a/kernel/sched/fs.c +++ b/kernel/sched/fs.c @@ -115,6 +115,27 @@ int sched_task_fs_unshare(struct task *task, bool new_namespace) return 0; } +/** @brief Replace the caller's graph and paths after pinning the target root. + * @param task Live caller under execution ownership outside scheduler_lock. + * @param ns Borrowed target graph. + * @return Zero or negative errno without changing paths on failure. + */ +int sched_task_fs_join_namespace(struct task *task, struct vfs_namespace *ns) +{ + if (task->shared_fs && task->shared_fs->references != 1) return -LINUX_EINVAL; + struct task_fs_paths next = {.ns = vfs_namespace_get(ns)}; + int rc = vfs_namespace_root(next.ns, &next.root); + if (rc) { sched_task_fs_paths_put(&next); return rc; } + vfs_path_get(&next.root, &next.cwd); + + struct task_fs_paths *paths = sched_task_paths(task), old = *paths; + *paths = next; + task_copy_identity_text(sched_task_root_dir(task), sizeof(task->root_dir), "/"); + task_copy_cwd(task, "/"); + sched_task_fs_paths_put(&old); + return 0; +} + /** @brief Check whether a separate process can change a task's CLONE_FS state. * @param task Current task under exclusive execution ownership; required. * @return True if any filesystem-state reference is held outside the task's diff --git a/kernel/syscall/dispatch.c b/kernel/syscall/dispatch.c index 4687e72a..1463f9ac 100644 --- a/kernel/syscall/dispatch.c +++ b/kernel/syscall/dispatch.c @@ -1,7 +1,10 @@ #include "internal.h" +#include #include #include #include +#include +#include /** * @brief Apply Linux' ioctl() descriptor-resolution rule for O_PATH files. @@ -121,6 +124,61 @@ static int64_t syscall_ioctl_nonblock(struct task *task, int fd, uint64_t argume return 0; } +/** @brief Handle ioctl on an already authenticated mount namespace inode. + * @param task Live caller under execution ownership. + * @param cmd Normalized 32-bit Linux request, after generic FD ioctls. + * @param argument User int output for FIONREAD, ignored for other requests. + * @return Namespace type, zero for a copied byte count, or negative errno + * (including the private swap retry result). + */ +static int64_t syscall_nsfs_ioctl(struct task *task, uint32_t cmd, uint64_t argument) +{ + if (cmd == NS_GET_NSTYPE) return CLONE_NEWNS; + if (cmd != FIONREAD) return -LINUX_ENOTTY; + int32_t available = 0; + int prep = swap_prepare_user_range(task, argument, sizeof(available), true); + if (prep == SWAP_STORAGE_CONTENDED) return KERNEL_SYSCALL_SWAP_CONTENDED; + if (prep < 0 || !argument || !user_range_writable(argument, sizeof(available))) return -LINUX_EFAULT; + __builtin_memcpy((void *)(uintptr_t)argument, &available, sizeof(available)); + return 0; +} + +/** @brief Admit the ioctl FD before generic, namespace or character requests. + * @param task Descriptor owner under syscall execution ownership. + * @param fd Normalized 32-bit Linux descriptor number. + * @param cmd Normalized 32-bit Linux request. + * @param argument Raw third argument, interpreted only by the selected handler. + * @param result Required output when the request is handled or rejected. + * @return True with a result, or false to continue to legacy device dispatch. + */ +bool syscall_ioctl_front(struct task *task, uint32_t fd, uint32_t cmd, + uint64_t argument, int64_t *result) +{ + int resolve = syscall_ioctl_resolve_fd(task, fd); + if (resolve < 0) { + *result = resolve; + return true; + } + if (cmd == FIOCLEX || cmd == FIONCLEX) { + *result = syscall_ioctl_descriptor_flags(task, fd, cmd); + return true; + } + if (cmd == FIONBIO) { + *result = syscall_ioctl_nonblock(task, (int32_t)fd, argument); + return true; + } + struct task_file *file = task_file_for_io(task, (int32_t)fd); + if (file && nsfs_path_namespace(&file->path_ref)) { + *result = syscall_nsfs_ioctl(task, cmd, argument); + return true; + } + if (file && file->character_file) { + *result = character_file_ioctl(file->character_file, task, file, cmd, argument); + return true; + } + return false; +} + void syscall_init(void) { console_info("[reliefnt] Linux x86_64 syscall ABI registered\n"); @@ -143,6 +201,8 @@ static int64_t syscall_dispatch_normalized_inner(const struct syscall_frame *fra switch (frame->number) { case LINUX_SYS_UNSHARE: return syscall_unshare(sched_current_task(), frame->args[0]); + case __NR_setns: + return syscall_setns(sched_current_task(), (int32_t)frame->args[0], (uint32_t)frame->args[1]); case __NR_pidfd_open: case __NR_pidfd_send_signal: return syscall_dispatch_regs(sched_current_task(), frame->number, @@ -787,6 +847,7 @@ int64_t syscall_dispatch_regs(struct task *task, uint64_t number, uint64_t a0, u uint64_t a5) { if (number == LINUX_SYS_UNSHARE) return syscall_unshare(task, a0); + if (number == __NR_setns) return syscall_setns(task, (int32_t)a0, (uint32_t)a1); if (number == __NR_pidfd_open) return syscall_pidfd_open(task, (int32_t)a0, (uint32_t)a1); if (number == __NR_pidfd_send_signal) return syscall_pidfd_send_signal(task, (int32_t)a0, (int32_t)a1, a2, (uint32_t)a3); @@ -835,38 +896,13 @@ int64_t syscall_dispatch_regs(struct task *task, uint64_t number, uint64_t a0, u } break; } - /* Linux ioctl's fd and cmd are unsigned int on native x86-64. */ + /* Normalize Linux ioctl's unsigned int operands before category routing. */ if (number == LINUX_SYS_IOCTL) { a0 = (uint32_t)a0; a1 = (uint32_t)a1; - } - - /* ioctl() resolves its descriptor with fdget(), which rejects FMODE_PATH, - * so every request on an open(O_PATH) descriptor fails with EBADF before - * any generic or device handler runs. fcntl() uses fdget_raw() and keeps - * working on the same descriptor, so this check stays ioctl-only. */ - if (number == LINUX_SYS_IOCTL) { - int resolve = syscall_ioctl_resolve_fd(sched_current_task(), a0); - if (resolve < 0) return resolve; - } - - /* Linux do_vfs_ioctl() resolves FIOCLEX/FIONCLEX in the generic VFS switch - * before any filesystem, GPU or device-specific handler, so the request - * works on every descriptor type and never reaches a device backend. The - * third argument is ignored and therefore never validated or dereferenced. */ - if (number == LINUX_SYS_IOCTL && - ((uint32_t)a1 == FIOCLEX || (uint32_t)a1 == FIONCLEX)) { - return syscall_ioctl_descriptor_flags(sched_current_task(), a0, - (uint32_t)a1); - } - if (number == LINUX_SYS_IOCTL && a1 == FIONBIO) { - return syscall_ioctl_nonblock(sched_current_task(), (int)a0, a2); - } - if (number == LINUX_SYS_IOCTL) { - struct task *task = sched_current_task(); - struct task_file *file = task_file_for_io(task, (int)a0); - if (file && file->character_file) - return character_file_ioctl(file->character_file,task,file,(uint32_t)a1,a2); + int64_t result; + if (syscall_ioctl_front(sched_current_task(), (uint32_t)a0, (uint32_t)a1, a2, &result)) + return result; } if (syscall_fs_owns(number)) { diff --git a/kernel/syscall/fd/open.c b/kernel/syscall/fd/open.c index 2bcaf3e9..f657cc80 100644 --- a/kernel/syscall/fd/open.c +++ b/kernel/syscall/fd/open.c @@ -81,7 +81,8 @@ static int open_inode_path(struct task *task,const struct vfs_path *path,uint32_ * @return Descriptor, negative errno or FIFO blocking sentinel. Existing * O_CREAT files keep their metadata; dangling links create at their actual * target, O_EXCL never follows the final link, and O_PATH avoids inode/device - * open side effects. A writable regular OFD holds a writer charge on its + * open side effects. Namespace handles reject write access and truncation + * before DAC. A writable regular OFD holds a writer charge on its * selected attachment until the last reference retires. */ int64_t syscall_open_object(struct vfs_namespace *ns,struct task *task,int32_t dirfd, @@ -124,6 +125,8 @@ int64_t syscall_open_object(struct vfs_namespace *ns,struct task *task,int32_t d if(!rc && (flags&LINUX_O_DIRECTORY) && node->type!=RELIEFOS_FS_TYPE_DIR)rc=-RELIEFOS_ENOTDIR; if(!rc && !(flags&TASK_FILE_FLAG_PATH) && node->type==RELIEFOS_FS_TYPE_SYMLINK)rc=-LINUX_ELOOP; if(!rc && !(flags&TASK_FILE_FLAG_PATH)) { + if((node->flags&STORAGE_NODE_FLAG_NSFS) && + (flags&(LINUX_O_ACCMODE|LINUX_O_TRUNC)))rc=-LINUX_EPERM; if(node->type==RELIEFOS_FS_TYPE_DIR && (flags&LINUX_O_ACCMODE)!=LINUX_O_RDONLY)rc=-RELIEFOS_EISDIR; uint32_t access=(flags&LINUX_O_ACCMODE)==LINUX_O_RDONLY ? FS_ACCESS_READ : (flags&LINUX_O_ACCMODE)==LINUX_O_WRONLY ? FS_ACCESS_WRITE : FS_ACCESS_READ|FS_ACCESS_WRITE; diff --git a/kernel/syscall/internal.h b/kernel/syscall/internal.h index 2f426508..5029d446 100644 --- a/kernel/syscall/internal.h +++ b/kernel/syscall/internal.h @@ -101,6 +101,18 @@ struct task_timerfd { uint64_t expirations; }; +/** @brief Resolve an ioctl FD, then handle generic and owned provider requests. + * @param task Descriptor owner under syscall execution ownership. + * @param fd Normalized 32-bit Linux descriptor number. + * @param cmd Normalized 32-bit Linux request. + * @param argument Raw third argument, interpreted only by the selected handler. + * @param result Required output when the request is handled or rejected. + * @return True with a result, or false to continue to legacy device dispatch. + * O_PATH is rejected before generic requests, which precede provider ioctls. + */ +bool syscall_ioctl_front(struct task *task, uint32_t fd, uint32_t cmd, + uint64_t argument, int64_t *result); + /** * @brief One Linux epoll registration, keyed by descriptor and OFD identity. * @note An empty interest mask still observes unconditional POLLERR/POLLHUP. diff --git a/kernel/syscall/io/io.c b/kernel/syscall/io/io.c index 4385533e..4f52235d 100644 --- a/kernel/syscall/io/io.c +++ b/kernel/syscall/io/io.c @@ -110,6 +110,7 @@ static int scalar_prepare_user(struct task *task,const struct task_file *file, * @param a2 Requested byte count; null writes accept up to Linux MAX_RW_COUNT. * @return Accepted byte count, negative errno, or internal blocking/retry result. * Null writes discard the full capped request without accessing its bytes. + * Namespace handles are never writable, even for empty requests. * Ordinary writes use the actual OFD provider independently of display text; * network datagrams use the staged socket send path as one complete message; * entry owns its lifetime through waits under execution ownership, without @@ -122,6 +123,7 @@ int64_t syscall_io_write(uint64_t a0, uint64_t a1, uint64_t a2) int pty_stream; struct task_file *signal_file = task_file_for_io(task, (int32_t)a0); if (signal_file && (signal_file->flags & TASK_FILE_FLAG_PATH)) return -RELIEFOS_EBADF; + if (signal_file && (signal_file->node.flags & STORAGE_NODE_FLAG_NSFS)) return -LINUX_EBADF; if (signal_file && (signal_file->kind == TASK_FILE_KIND_SIGNALFD || signal_file->kind == TASK_FILE_KIND_PIDFD)) return -LINUX_EINVAL; if (signal_file && signal_file->kind == TASK_FILE_KIND_INOTIFY) return -LINUX_EBADF; @@ -264,7 +266,8 @@ int64_t syscall_io_write(uint64_t a0, uint64_t a1, uint64_t a2) * @param a2 Requested byte count, subject to each backend's existing limits. * @param phase Optional in/out packet phase shared across readv segments. * @return Byte count, negative errno (including EISDIR for directories), or - * internal retry. Ordinary reads use the actual OFD provider/open capture; + * internal retry. Namespace handles reject even empty reads before buffer + * validation. Ordinary reads use the actual OFD provider/open capture; * diagnostic paths never select an inode. Entry owns the OFD through waits, * under execution ownership without graph/module locks across callbacks. */ @@ -278,6 +281,7 @@ int64_t syscall_io_read_iter(uint64_t a0, uint64_t a1, uint64_t a2, enum pty_rea int pty_stream; file = task_file_for_io(task, (int32_t)a0); if (file && (file->flags & TASK_FILE_FLAG_PATH)) return -RELIEFOS_EBADF; + if (file && (file->node.flags & STORAGE_NODE_FLAG_NSFS)) return -LINUX_EINVAL; if (file && file->kind == TASK_FILE_KIND_PIDFD) return -LINUX_EINVAL; if (file && file->kind == TASK_FILE_KIND_SIGNALFD) return task_signalfd_read(task, file, a1, a2); if (file && file->kind == TASK_FILE_KIND_INOTIFY) diff --git a/kernel/syscall/io/legacy_io.c b/kernel/syscall/io/legacy_io.c index ad787eda..b897dd43 100644 --- a/kernel/syscall/io/legacy_io.c +++ b/kernel/syscall/io/legacy_io.c @@ -26,6 +26,7 @@ static bool positional_address_valid(uint64_t address,uint64_t count) * @param a5 Sixth native ABI argument. * @return Original result, negative errno, or internal blocking/retry status. * @note The caller retains the kernel execution transaction and descriptor pins. + * Positional namespace-handle I/O fails before any user buffer access. */ int64_t syscall_legacy_io(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) { @@ -58,6 +59,8 @@ int64_t syscall_legacy_io(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2 if ((int64_t)a3 < 0) return -RELIEFOS_EINVAL; if (file && (file->flags & TASK_FILE_FLAG_PIPE)) return -LINUX_ESPIPE; if (!file || (file->flags & TASK_FILE_FLAG_PATH)) return -RELIEFOS_EBADF; + if (file->node.flags & STORAGE_NODE_FLAG_NSFS) + return number == LINUX_SYS_PWRITE64 ? -LINUX_EBADF : -LINUX_EINVAL; if (file->flags & TASK_FILE_FLAG_DEV_BLOCK) { bool writing = number == LINUX_SYS_PWRITE64; if (writing ? !file_can_write(file) : !file_can_read(file)) return -RELIEFOS_EBADF; diff --git a/kernel/syscall/io/seek.c b/kernel/syscall/io/seek.c index ff8b4965..a4cead1a 100644 --- a/kernel/syscall/io/seek.c +++ b/kernel/syscall/io/seek.c @@ -6,7 +6,8 @@ * @param fd Signed low-32-bit descriptor, resolved through syscall admission. * @param offset Signed Linux byte offset or opaque directory position cookie. * @param whence Linux SEEK_SET/CUR/END/DATA/HOLE selector, low 32 bits. - * @return New position, negative errno or internal metadata retry. Directories + * @return New position, negative errno or internal metadata retry. Namespace + * handles return ESPIPE for valid whence. Directories * preserve backend cookies without record-size conversion. Ordinary END/DATA/ * HOLE use fresh actual-provider metadata, with the conservative permitted * all-data/EOF-hole interpretation. The OFD position is reserved before any @@ -21,6 +22,7 @@ int64_t syscall_seek_object(struct task *task,int32_t fd,int64_t offset,uint32_t bool directory=file->node.type==RELIEFOS_FS_TYPE_DIR; if(!directory && file->node.type!=RELIEFOS_FS_TYPE_FILE)return -LINUX_ESPIPE; if(whence>4 || (directory && whence>RELIEFOS_SEEK_CUR))return -RELIEFOS_EINVAL; + if(file->node.flags&STORAGE_NODE_FLAG_NSFS)return -LINUX_ESPIPE; if(file->io_owner && file->io_owner!=task->pid)return -RELIEFOS_EAGAIN; file->io_owner=task->pid; int64_t base=whence==RELIEFOS_SEEK_CUR ? (int64_t)file->offset : 0; diff --git a/kernel/syscall/io/transfer.c b/kernel/syscall/io/transfer.c index ce472053..933a6bac 100644 --- a/kernel/syscall/io/transfer.c +++ b/kernel/syscall/io/transfer.c @@ -84,7 +84,8 @@ static int transfer_offset(struct task *task,uint64_t address,uint64_t *position * @param args Six kernel-owned native argument values, required. * @return Zero or negative fd/access/type/allocation/input errno. Failure * retires every acquired pin; no provider callback runs before both OFDs are - * retained. Matching retries use original objects after close/fd reuse. + * retained. Namespace handles are not sendfile sources, even for count zero. + * Matching retries use original objects after close/fd reuse. */ static int transfer_begin(struct task *task,bool range,const uint64_t args[6]) { @@ -108,6 +109,7 @@ static int transfer_begin(struct task *task,bool range,const uint64_t args[6]) if(range && (input->node.type==RELIEFOS_FS_TYPE_DIR || output->node.type==RELIEFOS_FS_TYPE_DIR))return -EISDIR; if(!file_can_read(input) || !file_can_write(output))return -EBADF; if(input->node.type!=RELIEFOS_FS_TYPE_FILE || (input->node.flags&STORAGE_NODE_FLAG_PROC))return -EINVAL; + if(!range && (input->node.flags&STORAGE_NODE_FLAG_NSFS))return -EINVAL; if(range && output->node.type!=RELIEFOS_FS_TYPE_FILE)return -EINVAL; if(!range && output->node.type!=RELIEFOS_FS_TYPE_FILE && !(output->flags&(TASK_FILE_FLAG_PIPE|TASK_FILE_FLAG_SOCKET_UNIX|TASK_FILE_FLAG_SOCKET_INET)))return -EINVAL; diff --git a/kernel/syscall/io/vector.c b/kernel/syscall/io/vector.c index 11cef700..18f5a34a 100644 --- a/kernel/syscall/io/vector.c +++ b/kernel/syscall/io/vector.c @@ -150,7 +150,8 @@ static int64_t regular_vector_io(struct task *task,struct task_file *file,uint64 * @param a5 Low32bit v2 RWF flags, ignored for older variants. * @return Accepted bytes, negative errno or internal retry. Ordinary FS files * own imported iovec metadata and accepted progress until completion/common - * cancellation. Specialized device/socket APIs preserve their own handling. + * cancellation. Namespace and O_PATH descriptors reject even empty vectors. + * Specialized device/socket APIs preserve their own handling. * All backend work runs under execution ownership without graph/module locks. */ int64_t syscall_vector_io(struct task *task,uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, @@ -184,6 +185,9 @@ int64_t syscall_vector_io(struct task *task,uint64_t number,uint64_t a0,uint64_t } if (positional && !current_position && (int64_t)position < 0) return -RELIEFOS_EINVAL; + if (file && (file->flags & TASK_FILE_FLAG_PATH)) return -LINUX_EBADF; + if (file && (file->node.flags & STORAGE_NODE_FLAG_NSFS)) + return writing ? -LINUX_EBADF : -LINUX_EINVAL; if (positional_flags && !provider_readv) return -RELIEFOS_EOPNOTSUPP; if (file ? !(writing ? file_can_write(file) : file_can_read(file)) : diff --git a/kernel/syscall/process/Kbuild b/kernel/syscall/process/Kbuild index ad477ab3..6f7d56c3 100644 --- a/kernel/syscall/process/Kbuild +++ b/kernel/syscall/process/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := clone.o exec.o legacy_process.o pidfd.o process.o process_vm.o resources.o security.o session.o +obj-y := clone.o exec.o legacy_process.o pidfd.o process.o process_vm.o resources.o security.o session.o setns.o include $(srctree)/scripts/Makefile.module diff --git a/kernel/syscall/process/setns.c b/kernel/syscall/process/setns.c new file mode 100644 index 00000000..c94d0644 --- /dev/null +++ b/kernel/syscall/process/setns.c @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "../internal.h" +#include +#include +#include +#include + +/** @brief Join a mount graph through an authentic namespace FD. + * @param task Live caller; execution ownership keeps its FD table stable. + * @param fd Descriptor number (not O_PATH or a pidfd). + * @param type Zero or CLONE_NEWNS. + * @return Zero or a negative descriptor, capability or graph error. + */ +int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) +{ + if (task_fd_descriptor_flags(task, fd) < 0) return -LINUX_EBADF; + struct task_file *file = task_file_for_fd(task, fd); + if (!file) return -LINUX_EINVAL; /* Existing PTY or implicit stdio. */ + if (file->flags & TASK_FILE_FLAG_PATH) return -LINUX_EBADF; + if (type && type != CLONE_NEWNS) return -LINUX_EINVAL; + struct vfs_namespace *ns = nsfs_path_namespace(&file->path_ref); + if (!ns) return -LINUX_EINVAL; + const uint64_t required = (1ULL << CAP_SYS_ADMIN) | (1ULL << CAP_SYS_CHROOT); + /* Only the initial user namespace exists, shared by caller and target. */ + if ((task->cap_effective & required) != required) return -LINUX_EPERM; + return sched_task_fs_join_namespace(task, ns); +} diff --git a/tools/test_linux_inventory.py b/tools/test_linux_inventory.py index 92302ede..f4f6af76 100644 --- a/tools/test_linux_inventory.py +++ b/tools/test_linux_inventory.py @@ -11,7 +11,7 @@ def host(): run(['cc','-std=c11','-O1','-g','-fsanitize=address,undefined','-ffunction-sections','-fdata-sections','-Wl,--gc-sections', '-Iinclude','-Iinclude','-Iinclude/uapi', '-Iinclude','tools/tests/linux_inventory_test.c','fs/vfs/mount_tree.c', 'fs/vfs/lookup_cache.c', - 'fs/vfs/path.c','fs/vfs/mount_table.c','fs/vfs/file.c','fs/vfs/pseudo.c', 'fs/vfs/attributes.c','fs/proc/mount.c','fs/proc/views.c','kernel/syscall/fd/proc.c','fs/vfs/exec_file.c', + 'fs/vfs/path.c','fs/vfs/mount_table.c','fs/vfs/file.c','fs/vfs/pseudo.c', 'fs/vfs/attributes.c','fs/proc/mount.c','fs/nsfs/namespace.c','fs/proc/views.c','kernel/syscall/fd/proc.c','fs/vfs/exec_file.c', 'fs/sysfs/mount.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','fs/security/access.c','-o',executable]) run([executable]) diff --git a/tools/test_linux_ioctl_cloexec.py b/tools/test_linux_ioctl_cloexec.py index ee52b155..6c7d47e0 100644 --- a/tools/test_linux_ioctl_cloexec.py +++ b/tools/test_linux_ioctl_cloexec.py @@ -37,11 +37,13 @@ def test_kernel_dispatch_contract() -> None: sched_h = read("include/reliefnt/task/types.h") + read("include/reliefnt/sched.h") # The generic requests must be resolved before any category/device routing. dispatch = syscall_c.rindex("int64_t syscall_dispatch_regs(") - generic = syscall_c.index("syscall_ioctl_descriptor_flags(sched_current_task(), a0") + front = syscall_c.rindex("bool syscall_ioctl_front(") + generic = syscall_c.index("syscall_ioctl_descriptor_flags(task, fd, cmd)", front) owned = syscall_c.index("if (syscall_fs_owns(number))", dispatch) - assert dispatch < generic < owned, "FIOCLEX/FIONCLEX must precede device dispatch" - path_rule = syscall_c.index("syscall_ioctl_resolve_fd(sched_current_task(), a0)") - assert dispatch < path_rule < generic, "the O_PATH rule must run before generic ioctls" + front_call = syscall_c.index("syscall_ioctl_front(sched_current_task()", dispatch) + assert dispatch < front_call < owned, "generic ioctl admission must precede device dispatch" + path_rule = syscall_c.index("syscall_ioctl_resolve_fd(task, fd)", front) + assert front < path_rule < generic, "the O_PATH rule must run before generic ioctls" # Unknown requests keep the Linux generic error instead of ENOSYS. assert "return -RELIEFOS_ENOTTY;\n }\n\n return -RELIEFOS_ENOSYS;" in syscall_c # The signalfd branch must no longer carry a private implementation: the @@ -50,8 +52,9 @@ def test_kernel_dispatch_contract() -> None: socket_dispatch = syscall_c.index("if (file && (file->flags & TASK_FILE_FLAG_SOCKET_UNIX))", signalfd) signalfd_block = syscall_c[signalfd:socket_dispatch] assert "FIOCLEX" not in signalfd_block and "FIONCLEX" not in signalfd_block - nonblock = syscall_c.index("return syscall_ioctl_nonblock(sched_current_task()", dispatch) - assert path_rule < nonblock < owned, "FIONBIO must use the shared generic VFS path" + nonblock = syscall_c.index("syscall_ioctl_nonblock(task, (int32_t)fd, argument)", front) + character = syscall_c.index("character_file_ioctl(", front) + assert path_rule < nonblock < character, "FIONBIO must precede provider requests" # fcntl(F_GETFD/F_SETFD) shares one storage with ioctl(FIOCLEX/FIONCLEX). assert "return task_fd_descriptor_flags(task, (int)a0);" in syscall_c assert "task_fd_set_descriptor_flags(task, (int)a0, (uint32_t)a2)" in syscall_c diff --git a/tools/test_lock_profile.py b/tools/test_lock_profile.py index b9431227..4b573a6a 100644 --- a/tools/test_lock_profile.py +++ b/tools/test_lock_profile.py @@ -23,7 +23,7 @@ binary = str(Path(directory) / "proc") sources = ["tools/tests/lock_profile_proc_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", - "fs/proc/mount.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "fs/security/access.c"] + "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "fs/security/access.c"] if (ROOT / "kernel/sync/profile.c").exists(): sources.append("kernel/sync/profile.c") subprocess.run(["cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", @@ -50,7 +50,7 @@ "-DCONFIG_LOCK_STAT", "-DRELIEFNT_LOCK_PROFILE_TEST", "-Iinclude", "-Iinclude/uapi", "tools/tests/lock_profile_sync_io_test.c", "tools/tests/task8_host_stubs/writable_alias_model.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "tools/tests/task8_host_stubs/user_ram_unreached.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", - "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", + "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "fs/security/access.c", "kernel/sync/profile.c", "-o", binary], cwd=ROOT, check=True) subprocess.run([binary], cwd=ROOT, check=True, timeout=10) diff --git a/tools/test_memory_reporting.py b/tools/test_memory_reporting.py index 5bca1b78..dc1ff647 100644 --- a/tools/test_memory_reporting.py +++ b/tools/test_memory_reporting.py @@ -72,7 +72,7 @@ def run_cases(output, cases): binary = str(output / "memory_reporting_proc") proc_sources = ["tools/tests/memory_reporting_proc_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", - "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", + "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/oom.c", "fs/security/access.c", "fs/proc/memory.c", "mm/reclaim/stats.c", "mm/reclaim/oom.c"] diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index e466539e..08ae7346 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -22,7 +22,12 @@ def test_real_tmpfs_without_text_routing(self): "cc", "-std=gnu11", "-O1", "-g", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Wl,--wrap=storage_ext4_read_inode", "-Wl,--wrap=storage_read_device", "-Wl,--wrap=storage_inode_stat", "-Wl,--wrap=storage_backend_commit_rename_metadata", "-Wl,--wrap=storage_cluster_write", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_backend_test.c", "kernel/dma/buffer.c", "drivers/storage/ahci/dma.c", "drivers/storage/ahci/interrupt.c", "drivers/storage/nvme/queue.c", "block/partition/mbr.c", - "fs/cgroup/filesystem.c", "fs/cgroup/hierarchy.c", "fs/vfs/notify.c", + "fs/cgroup/filesystem.c", "fs/cgroup/hierarchy.c", "fs/vfs/notify.c", "fs/nsfs/namespace.c", + "kernel/syscall/dispatch.c", "kernel/syscall/io/legacy_io.c", "kernel/syscall/io/io.c", + "kernel/syscall/io/file_io.c", "kernel/syscall/io/seek.c", "kernel/syscall/io/transfer.c", + "kernel/syscall/io/directory.c", "tools/tests/mount_backend_io_boundaries.c", + "tools/tests/task8_host_stubs/device_page_unreached.c", + "tools/tests/task8_host_stubs/writable_alias_model.c", "fs/notify/core.c", "fs/notify/limits.c", "fs/notify/queue.c", "fs/notify/watch.c", "fs/vfs/filesystems.c", "fs/vfs/filesystem_instance.c", "fs/ext_common/journal.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/kernel_file.c", "fs/vfs/kernel_path.c", "fs/vfs/exec_file.c", "fs/vfs/attributes.c", "fs/vfs/initial.c", "fs/vfs/storage_initial.c", "fs/vfs/storage_attributes.c", "fs/vfs/storage_access.c", "fs/vfs/storage_backend.c", "fs/vfs/mutation.c", "fs/vfs/storage_mutation.c", "fs/vfs/storage_create.c", "fs/vfs/storage_security.c", "fs/vfs/write_access.c", "fs/devpts/devpts.c", "drivers/tty/pty/core.c", "drivers/tty/pty/ring.c", "drivers/tty/pty/line_discipline.c", "drivers/tty/pty/session.c", "drivers/tty/pty/vt.c", "kernel/syscall/device/device_open.c", "kernel/syscall/device/device_io.c", "kernel/syscall/fs/stat.c", "fs/vfs/storage_mount.c", "fs/vfs/fat_options.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/security/access.c", "lib/text_utf16.c", "fs/devfs/mount.c", "fs/devfs/devtmpfs.c", "fs/devfs/devtmpfs_nodes.c", "fs/devfs/device.c", "fs/devfs/identity.c", "fs/vfs/pseudo.c", "kernel/exec/runtime.c", "kernel/exec/pending.c", "kernel/syscall/process/exec.c", "kernel/syscall/system/user_string.c", diff --git a/tools/test_mount_namespace_task.py b/tools/test_mount_namespace_task.py index 989e11e5..39f355c7 100644 --- a/tools/test_mount_namespace_task.py +++ b/tools/test_mount_namespace_task.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Exercise mount namespace creation through the real clone and unshare backends.""" +"""Exercise mount namespace creation and switching with the real scheduler.""" from pathlib import Path import subprocess import tempfile @@ -13,7 +13,8 @@ "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_namespace_task_test.c", "kernel/syscall/process/clone.c", - "kernel/device/mapping.c", "fs/security/access.c", "fs/vfs/lookup_cache.c", + "kernel/syscall/process/setns.c", "kernel/device/mapping.c", "fs/security/access.c", + "fs/vfs/lookup_cache.c", "fs/vfs/attributes.c", "fs/nsfs/namespace.c", "-o", output, ], cwd=ROOT, check=True) subprocess.run([output], cwd=ROOT, check=True, timeout=20) diff --git a/tools/test_procfs.py b/tools/test_procfs.py index 131176d6..10c6ab3e 100644 --- a/tools/test_procfs.py +++ b/tools/test_procfs.py @@ -18,7 +18,7 @@ def test_real_procfs_directory_lookup_and_enumeration(self): "-Iinclude", "-Iinclude/uapi", f"tools/tests/{fixture}.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", - "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/proc/views.c", + "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "fs/security/access.c", "-o", executable], cwd=ROOT, check=True) diff --git a/tools/test_rootfs.py b/tools/test_rootfs.py index 5391ed9b..12aeb635 100644 --- a/tools/test_rootfs.py +++ b/tools/test_rootfs.py @@ -17,7 +17,7 @@ def test_kernel_modules(self): # This shared fixture now exercises actual retained proc # mounts as well as its original directory contract. extra = (["fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", - "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/proc/views.c", + "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "fs/security/access.c"] if name in ("procfs_directories", "rootfs_paths") else []) if name in ("linux_permissions", "chroot_paths"): diff --git a/tools/tests/lock_profile_sync_io_test.c b/tools/tests/lock_profile_sync_io_test.c index afbab509..bc9f8492 100644 --- a/tools/tests/lock_profile_sync_io_test.c +++ b/tools/tests/lock_profile_sync_io_test.c @@ -27,6 +27,9 @@ bool user_range_writable(uint64_t p, uint64_t n) { return p || !n; } void storage_release_task_io(uint32_t pid) { (void)pid; } void storage_drain_task_io(uint32_t pid) { (void)pid; } void kernel_wait_queue_remove(struct kernel_wait_queue *q, struct task *t) { (void)q; (void)t; } +/** @brief The fixture never exceeds the file size limit. */ +int kernel_signal_queue_task(struct task *task, int signal_number) +{ (void)task; (void)signal_number; abort(); } void task_file_put(struct task_file *file) { (void)file; } int user_copy_to_task(struct task *task, uint64_t address, const void *source, uint64_t size) { (void)task; (void)address; (void)source; (void)size; abort(); } diff --git a/tools/tests/mount_backend_io_boundaries.c b/tools/tests/mount_backend_io_boundaries.c new file mode 100644 index 00000000..2e38bce3 --- /dev/null +++ b/tools/tests/mount_backend_io_boundaries.c @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +/** @file + * @brief Trap unrelated provider calls from the mount backend's FD tests. + * The namespace handle has no data plane. Its front ends must answer before + * reaching socket/terminal providers, file page staging or user page aliases. + */ +#include "../../kernel/syscall/internal.h" +#include +#include +#include + +#define UNREACHED(type, name, args) type name args { abort(); } +UNREACHED(int64_t, syscall_socket_dispatch, + (uint64_t n, uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e, uint64_t f)) +UNREACHED(int, task_pipe_read, (struct task_file *f, void *b, uint32_t n)) +UNREACHED(int, task_pipe_write, (struct task_file *f, const void *b, uint32_t n)) +UNREACHED(int, task_socket_read, (struct task_file *f, void *b, uint32_t n)) +UNREACHED(int, task_socket_write, (struct task_file *f, const void *b, uint32_t n)) +UNREACHED(int, task_socket_vector, + (struct task_file *f, const struct iovec *v, uint32_t n, uint64_t total, bool write)) +UNREACHED(int, task_inet_read, (struct task_file *f, void *b, uint32_t n)) +UNREACHED(int, task_inet_write, (struct task_file *f, const void *b, uint32_t n)) +UNREACHED(int64_t, task_inet_vector_user, + (struct task *t, struct task_file *f, uint64_t v, uint32_t n, bool write)) +UNREACHED(int64_t, task_signalfd_read, (struct task *t, struct task_file *f, uint64_t a, uint64_t n)) +UNREACHED(int64_t, task_signalfd_readv, + (struct task *t, struct task_file *f, uint64_t a, uint64_t n, uint32_t flags)) +UNREACHED(int, sched_signal_user_task, (uint32_t pid, int sig)) +UNREACHED(void, task_timerfd_update, (struct task_timerfd *timer)) +UNREACHED(int, task_shm_read, (struct task_file *f, void *b, uint32_t n)) +UNREACHED(int, task_shm_write, (struct task_file *f, const void *b, uint32_t n)) +UNREACHED(int, kernel_random_fill, (void *b, size_t n)) +UNREACHED(void, task_evdev_bind_vt, (struct task *t, struct task_file *f)) +UNREACHED(int, input_evdev_read_vt, + (uint32_t kind, uint64_t *cursor, void *b, uint32_t n, uint64_t grab, uint32_t vt)) +UNREACHED(int, input_evdev_write, (uint32_t kind, const void *b, uint32_t n)) +UNREACHED(int, serial_tx_user, (const void *b, size_t n)) +UNREACHED(void, console_serial_write_len, (const char *b, size_t n)) +UNREACHED(void, console_write_len, (const char *b, size_t n)) +UNREACHED(int, user_copy_to_task, (struct task *t, uint64_t a, const void *b, uint64_t n)) +UNREACHED(uint64_t, address_space_user_page_phys, (const struct address_space *as, uint64_t address)) +UNREACHED(uint64_t, address_space_user_page_flags, (const struct address_space *as, uint64_t address)) +UNREACHED(uint32_t, mm_page_refcount, (uint64_t phys)) +UNREACHED(void, mm_retain_page, (uint64_t phys)) +UNREACHED(int, page_cache_retain, (uint64_t phys)) +UNREACHED(void, page_cache_release, (uint64_t phys)) +UNREACHED(bool, paging_kernel_direct_cache_flags, (uint64_t phys, uint64_t *flags)) +UNREACHED(void *, paging_kernel_direct_map, (uint64_t phys)) +UNREACHED(void *, paging_ioremap_device_page, (uint64_t phys, uint64_t cache_bits)) +#undef UNREACHED + +/** @brief Supply a deterministic clock for the regular engine's zero-length path. */ +uint64_t time_work_counter_us(void) { return 0; } diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 55f37991..738c99e6 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -35,7 +35,9 @@ int kernel_signal_queue_task(struct task *task,int signal_number) #include #include #include +#include #include +#include #include #include #include @@ -46,6 +48,8 @@ int kernel_signal_queue_task(struct task *task,int signal_number) #include "../../kernel/exec/runtime.h" #include "../../kernel/exec/pending.h" #include +#include +#include #include #include "../../fs/vfs/mount_internal.h" #include "../../fs/operations.h" @@ -237,7 +241,6 @@ void task_epoll_remove_pty_description(struct task_pty_description *description) * @param id Internal session being detached. */ void sched_clear_controlling_pty(uint32_t id) { if (devpts_actor && devpts_actor->controlling_pty_id == id) devpts_actor->controlling_pty_id = 0; } -struct reliefos_flock_entry reliefos_flocks[RELIEFOS_FLOCK_MAX]; /** @brief Model the empty advisory-lock and epoll registries in this fixture. * @param owner Borrowed open description with no registered watches or locks. */ void syscall_flock_release_owner(struct task_file *owner) { (void)owner; } @@ -3782,6 +3785,115 @@ static void pending_script_launch(struct tmpfs_super *fs) puts("PASS pending /init scripts share execve parsing, one optional argument, final script/interpreter DAC and complete OOM ownership"); } +static struct vfs_namespace *namespace_handle_target; + +/** @brief Model a proc magic link and its searchable parent directory. */ +static int namespace_handle_lookup(const char *name, struct storage_node *node) +{ + bool root = !strcmp(name, "/handles"); + if (!root && strcmp(name, "/handles/mnt")) return -ENOENT; + *node = (struct storage_node){.type = root ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_SYMLINK, + .flags = STORAGE_NODE_FLAG_PROC | (root ? 0 : STORAGE_NODE_FLAG_MAGIC_LINK)}; + return 0; +} + +/** @brief Resolve the fixture magic link to a real anonymous nsfs inode. */ +static int namespace_handle_follow(const char *name, struct vfs_path *out) +{ + assert(!strcmp(name, "/handles/mnt")); + return nsfs_create_path(namespace_handle_target, out); +} + +/** @brief Open a retained nsfs handle through real pathname, DAC and FD logic. */ +static void runtime_namespace_handle_open(struct vfs_namespace *ns, const struct vfs_path *root) +{ + static const struct vfs_pseudo_provider provider = { + .root = "/handles", .lookup = namespace_handle_lookup, .follow = namespace_handle_follow, + .permissions = fs_virtual_permissions}; + struct reliefos_permissions mode = {0755, 1000, 1000}; + struct vfs_path point = {0}, top = {0}; + struct vfs_mount *mount = NULL; + assert(!vfs_path_create_node(root, "namespace-handles", LINUX_S_IFDIR, &mode, NULL, &point)); + assert(!vfs_pseudo_mount_new(&provider, &mount)); + assert(!vfs_mount_attach(ns, mount, &point)); + vfs_mount_put(mount); + assert(!vfs_path_lookup(ns, root, root, "/namespace-handles", VFS_LOOKUP_FOLLOW, &top)); + assert(top.mount == mount); + + struct task actor = {.pid = 905, .fsuid = 1000, .fsgid = 1000}; + sched_task_limits(&actor)->nofile.rlim_cur = 32; + vfs_path_get(root, &actor.fs_paths.root); + vfs_path_get(root, &actor.fs_paths.cwd); + char name[] = "/namespace-handles/mnt"; + lookup_user_base = (uintptr_t)name; + lookup_user_bytes = sizeof(name); + namespace_handle_target = ns; + unsigned refs = ns->references; + int fd = syscall_open_object(ns, &actor, LINUX_AT_FDCWD, (uintptr_t)name, LINUX_O_RDONLY | LINUX_O_CLOEXEC, 0); + int pathfd = syscall_open_object(ns, &actor, LINUX_AT_FDCWD, (uintptr_t)name, + LINUX_O_PATH | LINUX_O_RDWR | LINUX_O_TRUNC, 0); + assert(fd >= 0 && pathfd >= 0 && fd != pathfd); + struct task_file *handle = task_file_for_fd(&actor, fd); + assert(nsfs_path_namespace(&handle->path_ref) == ns); + assert(nsfs_path_namespace(&task_file_for_fd(&actor, pathfd)->path_ref) == ns); + assert(task_fd_descriptor_flags(&actor, fd) == RELIEFOS_FD_CLOEXEC); + assert(task_file_for_fd(&actor, pathfd)->flags & TASK_FILE_FLAG_PATH); + + const uint64_t reads[] = {LINUX_SYS_READ, LINUX_SYS_PREAD64, LINUX_SYS_READV, LINUX_SYS_PREADV, LINUX_SYS_PREADV2}; + const uint64_t writes[] = {LINUX_SYS_WRITE, LINUX_SYS_PWRITE64, LINUX_SYS_WRITEV, LINUX_SYS_PWRITEV, LINUX_SYS_PWRITEV2}; + assert(!cgroup_tasks[0]); + cgroup_tasks[0] = &actor; + for (unsigned i = 0; i < sizeof(reads) / sizeof(reads[0]); ++i) { + assert(syscall_legacy_io(reads[i], fd, 0, 0, 0, 0, 0) == -EINVAL); + assert(syscall_legacy_io(reads[i], pathfd, 0, 0, 0, 0, 0) == -EBADF); + assert(syscall_legacy_io(writes[i], fd, 0, 0, 0, 0, 0) == -EBADF); + assert(syscall_legacy_io(writes[i], pathfd, 0, 0, 0, 0, 0) == -EBADF); + } + actor.syscall_fd = fd; + actor.syscall_file = handle; + actor.syscall_file_number = LINUX_SYS_LSEEK; + assert(syscall_legacy_io(LINUX_SYS_LSEEK, fd, 0, RELIEFOS_SEEK_SET, 0, 0, 0) == -ESPIPE); + assert(syscall_legacy_io(LINUX_SYS_LSEEK, fd, 0, 6, 0, 0, 0) == -EINVAL); + assert(!handle->offset && !handle->io_owner); + actor.syscall_file = NULL; + assert(syscall_legacy_io(LINUX_SYS_LSEEK, pathfd, 0, RELIEFOS_SEEK_SET, 0, 0, 0) == -EBADF); + cgroup_tasks[0] = NULL; + + int64_t result = 0; + assert(syscall_ioctl_front(&actor, fd, NS_GET_NSTYPE, UINT64_MAX, &result) && result == CLONE_NEWNS); + assert(syscall_ioctl_front(&actor, fd, NSIO << 8 | 0xff, 0, &result) && result == -ENOTTY); + assert(syscall_ioctl_front(&actor, fd, FIONREAD, UINT64_MAX, &result) && result == -EFAULT); + int32_t value = 1; + lookup_user_base = (uintptr_t)&value; + lookup_user_bytes = sizeof(value); + assert(syscall_ioctl_front(&actor, fd, FIONBIO, (uintptr_t)&value, &result) && !result); + assert(handle->flags & LINUX_O_NONBLOCK); + assert(syscall_ioctl_front(&actor, fd, FIONREAD, (uintptr_t)&value, &result) && !result && !value); + assert(syscall_ioctl_front(&actor, fd, FIONCLEX, UINT64_MAX, &result) && !result); + assert(!task_fd_descriptor_flags(&actor, fd)); + assert(syscall_ioctl_front(&actor, pathfd, NS_GET_NSTYPE, 0, &result) && result == -EBADF); + + lookup_user_base = (uintptr_t)name; + lookup_user_bytes = sizeof(name); + const uint32_t denied[] = {LINUX_O_WRONLY, LINUX_O_RDWR, LINUX_O_RDONLY | LINUX_O_TRUNC}; + unsigned opened_refs = ns->references; + for (unsigned i = 0; i < sizeof(denied) / sizeof(denied[0]); ++i) + assert(syscall_open_object(ns, &actor, LINUX_AT_FDCWD, (uintptr_t)name, denied[i], 0) == -EPERM); + assert(ns->references == opened_refs); + task_discard_file_fd(&actor, pathfd); + task_discard_file_fd(&actor, fd); + assert(ns->references == refs); + + namespace_handle_target = NULL; + lookup_user_base = lookup_user_bytes = 0; + sched_task_fs_release(&actor); + assert(!vfs_mount_unmount(ns, &top)); + vfs_path_put(&top); + assert(!vfs_path_remove(ns, &point, true)); + vfs_path_put(&point); + puts("PASS nsfs descriptors: open, I/O, seek, ioctl and graph release"); +} + int main(int argc,char **argv) { storage_fixture_register_filesystems(); @@ -3812,6 +3924,7 @@ int main(int argc,char **argv) assert(!vfs_namespace_init(&ns,mount));vfs_mount_put(mount); struct vfs_path root={0},old_dir={0},old_file={0},top={0},file={0}; assert(!vfs_namespace_root(&ns,&root)); + runtime_namespace_handle_open(&ns, &root); real_mount_description(&ns,&root,"tmpfs","rw"); /* A registered storage codec without the audited epoch capability must * remain live even when it uses the common native VFS adapter. */ diff --git a/tools/tests/mount_namespace_task_test.c b/tools/tests/mount_namespace_task_test.c index 97fb2029..d87e1c9b 100644 --- a/tools/tests/mount_namespace_task_test.c +++ b/tools/tests/mount_namespace_task_test.c @@ -1,11 +1,32 @@ /* SPDX-License-Identifier: Apache-2.0 */ /** @file - * @brief Namespace creation through real scheduler, VFS and clone front ends. + * @brief Namespace creation and switching through the real scheduler and VFS. */ #define TASK8_CLONE_TID_TEST 1 #define RELIEFNT_TEST_HEAP_ALLOC_GATE namespace_heap_admit #include "sysv_shm_test.c" +#include + +static struct task_file handle_file, ordinary_file; + +/** @brief Resolve the two modeled file descriptions through the fixture FD boundary. */ +struct task_file *task_file_for_fd(struct task *task, int fd) +{ + assert(task == sched_current_task()); + return fd == 3 ? &handle_file : fd == 4 ? &ordinary_file : NULL; +} + +/** @brief Model implicit stdio, file descriptors and a separate PTY endpoint. */ +int task_fd_descriptor_flags(struct task *task, int fd) +{ + assert(task == sched_current_task()); + if (fd == 0) return 0; + if (fd == 5) return RELIEFOS_FD_CLOEXEC; + struct task_file *file = task_file_for_fd(task, fd); + return file ? (int)file->fd_flags : -LINUX_EBADF; +} + static int mount_budget = -1; static unsigned mount_allocations, charges; static const struct task *unpublished_child; @@ -119,6 +140,77 @@ static void check_unshare(struct task *task, const struct task *unpublished) sched_task_fs_release(&sibling); } +/** @brief Check FD admission, graph ownership and atomic visible-root selection. */ +static void check_setns(struct task *task) +{ + assert(syscall_setns(task, -1, 0) == -LINUX_EBADF); + assert(syscall_setns(task, 0, 0) == -LINUX_EINVAL); /* implicit stdin */ + assert(syscall_setns(task, 5, 0) == -LINUX_EINVAL); /* PTY */ + ordinary_file.kind = TASK_FILE_KIND_PIDFD; + assert(syscall_setns(task, 4, CLONE_NEWNS) == -LINUX_EINVAL); + ordinary_file.kind = 0; + + struct vfs_namespace *old = sched_task_namespace(task), *target = NULL; + struct vfs_path root = sched_task_paths(task)->root, cwd = sched_task_paths(task)->cwd; + assert(!vfs_namespace_clone(old, NULL, NULL, &target)); + assert(!nsfs_create_path(target, &handle_file.path_ref)); + handle_file.node = *vfs_path_node(&handle_file.path_ref); + handle_file.fd_flags = RELIEFOS_FD_CLOEXEC; + assert(target->references == 2); + vfs_namespace_put(target); /* The handle is now the graph's sole owner. */ + + /* Matching metadata and diagnostic labels are not namespace authority. */ + ordinary_file.node = handle_file.node; + strcpy(ordinary_file.path, "mnt:[fake]"); + ordinary_file.offset = 17; + assert(!vfs_path_anonymous(old->root, &ordinary_file.node, &ordinary_file.path_ref)); + assert(syscall_setns(task, 4, CLONE_NEWNS) == -LINUX_EINVAL); + handle_file.flags = TASK_FILE_FLAG_PATH; + assert(syscall_setns(task, 3, CLONE_NEWNS) == -LINUX_EBADF); + handle_file.flags = 0; + assert(syscall_setns(task, 3, CLONE_NEWNS | CLONE_NEWNET) == -LINUX_EINVAL); + + const uint64_t admin = 1ULL << CAP_SYS_ADMIN, chroot = 1ULL << CAP_SYS_CHROOT; + task->cap_permitted = admin | chroot; + task->cap_effective = admin; + assert(syscall_setns(task, 3, 0) == -LINUX_EPERM); + task->cap_effective = chroot; + assert(syscall_setns(task, 3, CLONE_NEWNS) == -LINUX_EPERM); + task->cap_effective = admin | chroot; + assert(!task_promote_shared(task, CLONE_FS)); + struct task sibling = {.tgid = task->tgid, .shared_fs = task->shared_fs}; + ++sibling.shared_fs->references; + assert(syscall_setns(task, 3, CLONE_NEWNS) == -LINUX_EINVAL); + assert(task->shared_fs == sibling.shared_fs && sibling.shared_fs->references == 2); + assert(sched_task_namespace(task) == old && target->references == 1); + assert(vfs_path_equal(&sched_task_paths(task)->root, &root)); + assert(vfs_path_equal(&sched_task_paths(task)->cwd, &cwd)); + assert(!strcmp(sched_task_root(task), "/cached-root")); + assert(!strcmp(sched_task_cwd(task), "/cached-cwd")); + sched_task_fs_release(&sibling); /* A sole remaining CLONE_FS owner may join. */ + + struct vfs_path anchor = {0}; + struct vfs_mount *cover = NULL; + struct storage_node node = {.type = RELIEFOS_FS_TYPE_DIR, .first_cluster = 202}; + assert(!vfs_namespace_root(target, &anchor) && anchor.mount == target->root); + assert(!vfs_mount_new(&fs_ops, NULL, NULL, &node, &cover)); + assert(!vfs_mount_attach(target, cover, &anchor)); + vfs_path_put(&anchor); + vfs_mount_put(cover); + assert(!syscall_setns(task, 3, CLONE_NEWNS)); + assert(sched_task_namespace(task) == target && target->references == 2); + assert(sched_task_paths(task)->root.mount == cover); + assert(vfs_path_equal(&sched_task_paths(task)->root, &sched_task_paths(task)->cwd)); + assert(!strcmp(sched_task_root(task), "/") && !strcmp(sched_task_cwd(task), "/")); + assert(*sched_task_umask(task) == 0027 && handle_file.fd_flags == RELIEFOS_FD_CLOEXEC); + assert(task_file_for_fd(task, 4) == &ordinary_file && ordinary_file.offset == 17); + assert(!syscall_setns(task, 3, 0) && target->references == 2); + vfs_path_put(&ordinary_file.path_ref); + vfs_path_put(&handle_file.path_ref); + assert(target->references == 1); + puts("PASS mount namespace FD admission, covered root and lifetime"); +} + int main(void) { struct sched_task_object parent_object = {0}, child_object = {0}; @@ -213,6 +305,7 @@ int main(void) assert(ns.references == 1 && root->references == root_refs && volume->references == refs); } check_unshare(parent, child); + check_setns(parent); sched_task_fs_release(parent); vfs_reclaim_mounts(16); assert(!vfs_namespace_destroy(&ns) && !fs_backend_pins); diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index 465f4ad5..49b0f591 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -548,12 +548,110 @@ static void test_proc_mount_failures(void) puts("PASS real proc mount allocation failures: context, inode keys, weak cache and PID references reclaimed"); } +/** @brief Exercise namespace links and persistent paths using the real proc provider. */ +static void test_proc_mount_namespace_handles(void) +{ + unsigned before = proc_allocations; + struct vfs_namespace ns = {0}; + struct vfs_path root = {0}; + struct vfs_mount *mount = NULL; + assert(!proc_create_vfs_mount(&mount) && !vfs_namespace_init(&ns, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns, &root)); + current.fs_paths.ns = vfs_namespace_get(&ns); + expose_foreign = true; + assert(!vfs_namespace_clone(&ns, NULL, NULL, &foreign.fs_paths.ns)); + struct vfs_namespace *old = foreign.fs_paths.ns; + uint32_t old_euid = foreign.euid, old_egid = foreign.egid; + foreign.euid = foreign.egid = 2000; + uint64_t old_caps = current.cap_effective; + current.cap_effective = 0; + + uint64_t cursor = 0; + struct reliefos_dir_entry entry; + assert(proc_readdir("/proc/43/ns", &cursor, &entry) == 1); + assert(entry.type == RELIEFOS_FS_TYPE_SYMLINK && !strcmp(entry.name, "mnt")); + assert(!proc_readdir("/proc/43/ns", &cursor, &entry)); + cursor = 0; + bool listed = false; + while (proc_readdir("/proc/43", &cursor, &entry) == 1) + if (!strcmp(entry.name, "ns")) listed = entry.type == RELIEFOS_FS_TYPE_DIR; + assert(listed); + + struct vfs_path dir = {0}, link = {0}, handle = {0}, fresh = {0}; + struct linux_stat_abi st; + struct linux_statfs_abi fs; + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns", 0, &dir)); + assert(!vfs_path_stat(&dir, &st) && st.st_mode == (LINUX_S_IFDIR | 0511)); + assert(st.st_uid == 2000 && st.st_gid == 2000); + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/mnt", 0, &link)); + assert(!vfs_path_stat(&link, &st) && st.st_mode == (LINUX_S_IFLNK | 0777)); + assert(vfs_path_lookup(&ns, &root, &root, "43/ns/mnt", VFS_LOOKUP_FOLLOW, &handle) == -EACCES); + char label[32] = {0}, expected[32]; + size_t length; + assert(vfs_path_readlink(&link, label, sizeof(label), &length) == -EACCES); + current.cap_effective = 1ULL << CAP_SYS_PTRACE; + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/mnt", VFS_LOOKUP_FOLLOW, &handle)); + assert(!vfs_path_stat(&handle, &st) && st.st_ino && st.st_mode == (LINUX_S_IFREG | 0444)); + assert(!vfs_path_statfs(&handle, &fs) && fs.f_type == 0x6e736673); + uint64_t ino = st.st_ino, device = st.st_dev; + snprintf(expected, sizeof(expected), "mnt:[%" PRIu64 "]", ino); + proc_allocation_budget = 0; + int count = proc_readlink("/proc/43/ns/mnt", label, sizeof(label)); + proc_allocation_budget = -1; + assert(count == (int)strlen(expected) && !memcmp(label, expected, count)); + assert(proc_readlink("/proc/43/ns/mnt", label, 5) == 5 && !memcmp(label, "mnt:[", 5)); + assert(old->references == 2); + + /* A live proc link follows the current graph, unlike an already held handle. */ + foreign.fs_paths.ns = vfs_namespace_get(&ns); + vfs_namespace_put(old); + assert(old->references == 1); + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/mnt", VFS_LOOKUP_FOLLOW, &fresh)); + assert(!vfs_path_stat(&fresh, &st) && st.st_dev == device && st.st_ino != ino); + uint64_t current_ino = st.st_ino; + vfs_path_put(&fresh); + for (unsigned i = 0; i < 3; ++i) { + const char *const aliases[] = {"self/ns/mnt", "thread-self/ns/mnt", "42/task/42/ns/mnt"}; + assert(!vfs_path_lookup(&ns, &root, &root, aliases[i], VFS_LOOKUP_FOLLOW, &fresh)); + assert(!vfs_path_stat(&fresh, &st) && st.st_ino == current_ino); + vfs_path_put(&fresh); + } + + sched_task_identity_detach(&foreign); /* Retire the identity, reusing PID 43. */ + assert(vfs_path_readlink(&link, label, sizeof(label), &length) == -ENOENT); + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/mnt", VFS_LOOKUP_FOLLOW, &fresh)); + assert(!vfs_path_stat(&fresh, &st) && st.st_ino == current_ino); + vfs_path_put(&fresh); + assert(!vfs_path_stat(&handle, &st) && st.st_ino == ino); + assert(!vfs_path_format_link(&ns, &root, &handle, label, sizeof(label)) && !strcmp(label, expected)); + vfs_path_put(&handle); + vfs_path_put(&link); + vfs_path_put(&dir); + vfs_namespace_put(foreign.fs_paths.ns); foreign.fs_paths.ns = NULL; + vfs_namespace_put(current.fs_paths.ns); current.fs_paths.ns = NULL; + foreign.euid = old_euid; foreign.egid = old_egid; + current.cap_effective = old_caps; + expose_foreign = false; + sched_task_identity_detach(¤t); + sched_task_identity_detach(&foreign); + vfs_path_put(&root); + /* The last handle retires the cloned graph; drain its backing mount pins. */ + assert(vfs_reclaim_pending()); + while (vfs_reclaim_mounts(8)) {} + assert(!vfs_reclaim_pending()); + assert(!vfs_namespace_destroy(&ns)); + assert(proc_allocations == before); + puts("PASS proc namespace aliases, permissions, stable identity and PID reuse"); +} + int main(void) { test_proc_fd_metadata(); test_proc_fd_object_link(); test_proc_mount_objects(); test_proc_mount_failures(); + test_proc_mount_namespace_handles(); strcpy(current.path, "/usr/lib/reliefos/apps/procsys/procsys.elf"); struct storage_node node; assert(proc_lookup("/proc/42", &node) == 0 && node.type == RELIEFOS_FS_TYPE_DIR); @@ -663,6 +761,7 @@ int main(void) assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "oom_score") && entry.type == RELIEFOS_FS_TYPE_FILE); assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "oom_score_adj") && entry.type == RELIEFOS_FS_TYPE_FILE); assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "cgroup") && entry.type == RELIEFOS_FS_TYPE_FILE); + assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "ns") && entry.type == RELIEFOS_FS_TYPE_DIR); assert(proc_readdir("/proc/42", &offset, &entry) == 0); offset = 0; /* Anonymous descriptors must survive proc inode lookup during getdents. diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 6bdf09a4..7597d232 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -5350,6 +5350,7 @@ "tools/tests/task8_host_stubs/writable_alias_model.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "fs/vfs/mount_tree.c", + "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", @@ -5357,6 +5358,10 @@ "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", + "fs/nsfs/namespace.c", + "fs/proc/views.c", + "kernel/syscall/fd/proc.c", + "fs/vfs/exec_file.c", "kernel/sched/identity.c", "fs/security/access.c", "kernel/sync/profile.c", diff --git a/tools/tests/task8_transfer_user_test.c b/tools/tests/task8_transfer_user_test.c index 691e2f12..81763f96 100644 --- a/tools/tests/task8_transfer_user_test.c +++ b/tools/tests/task8_transfer_user_test.c @@ -77,6 +77,11 @@ int main(void) current.limits.fsize=(struct linux_rlimit64){LINUX_RLIM_INFINITY,LINUX_RLIM_INFINITY}; source = (struct task_file){.node.type = RELIEFOS_FS_TYPE_FILE}; destination = (struct task_file){.node.type = RELIEFOS_FS_TYPE_FILE}; + source.node.flags = STORAGE_NODE_FLAG_NSFS; + assert(syscall_sendfile(4, 3, 0, 0) == -EINVAL); + assert(syscall_sendfile(4, 3, 0, 1) == -EINVAL); + assert(!current.transfer_io && !refs && !allocations && !reads && !writes); + source.node.flags = 0; int64_t from = 1, to = 2; blocked = (uintptr_t)&from; contended = true; assert(syscall_copy_file_range(3, (uintptr_t)&from, 4, (uintptr_t)&to, 3, 0) == diff --git a/tools/tests/test-version.sh b/tools/tests/test-version.sh index bd5260f5..12955f33 100644 --- a/tools/tests/test-version.sh +++ b/tools/tests/test-version.sh @@ -43,7 +43,7 @@ ${HOSTCC:-cc} -std=c11 -O1 -g -fsanitize=address,undefined \ "$kernel/tools/tests/procfs_directories_test.c" \ "$kernel/fs/vfs/mount_tree.c" "$kernel/fs/vfs/lookup_cache.c" "$kernel/fs/vfs/mount_table.c" "$kernel/fs/vfs/path.c" \ "$kernel/fs/vfs/file.c" "$kernel/fs/vfs/open.c" "$kernel/fs/vfs/pseudo.c" \ - "$kernel/fs/vfs/attributes.c" "$kernel/fs/proc/mount.c" "$kernel/fs/proc/views.c" \ + "$kernel/fs/vfs/attributes.c" "$kernel/fs/proc/mount.c" "$kernel/fs/nsfs/namespace.c" "$kernel/fs/proc/views.c" \ "$kernel/kernel/syscall/fd/proc.c" "$kernel/fs/vfs/exec_file.c" \ "$kernel/kernel/sched/identity.c" "$kernel/fs/security/access.c" -o "$work/procfs" "$work/procfs" From 536b93d409a8c492d41226f219371e8a337c61bf Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 08:26:03 +0800 Subject: [PATCH 18/97] fix(vfs): publish boot mounts without requiring optical targets --- Documentation/userspace-api/descriptors.rst | 6 ++ fs/vfs/initial.c | 23 +++---- fs/vfs/mount_internal.h | 6 ++ fs/vfs/mount_tree.c | 26 ++++++-- fs/vfs/storage_initial.c | 30 ++++++---- include/reliefnt/mount.h | 14 +++-- tools/tests/mount_backend_test.c | 66 +++++++++++++++++---- 7 files changed, 127 insertions(+), 44 deletions(-) diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index b9efb747..62bdeb91 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -134,6 +134,12 @@ TCP 的 ``setsockopt/getsockopt(SOL_TCP, TCP_NODELAY)`` 接受原生整数标志 挂载实例,保留底层强制只读及既有其他标志,不修改共享卷、ESP 或光盘等 其他挂载角色的策略。 +启动时,探测到的 ISO9660 光盘按 ``/media/cdrom0``、``/media/cdrom1`` 等顺序 +尝试挂载。若 ``/media`` 不存在,跳过自动挂载,不创建它;仍可用对应的光盘块设备 +显式挂载。若父目录存在,只创建缺少的末级目录,不改变已有目录的元数据。其他 +查找、创建或挂载错误不会被忽略。启动挂载图发布前失败时会释放图内挂载点引用并 +返回原错误;后端若未能完成回收,将保留到重试。正常卸载的忙检查不变。 + 查看根之外的挂载根不出现在 chroot 视图中;可见记录保留实际 ID,因此其 parent ID 可能位于查看范围之外。路径字段转义空格、制表符、换行和反斜线。 分段读取使用同一图顺序和字节偏移,不依赖反向插入的内部链表布局。 diff --git a/fs/vfs/initial.c b/fs/vfs/initial.c index bc1ce6d0..6150919a 100644 --- a/fs/vfs/initial.c +++ b/fs/vfs/initial.c @@ -17,11 +17,12 @@ struct vfs_namespace *vfs_system_namespace(void) /** @brief Resolve an initial attachment and optionally create its final target. * @param root Retained shared namespace root, borrowed for synchronous lookup. * @param request Borrowed boot descriptor, valid for this call. - * @param point Empty output receiving one owned directory path on success. + * @param point Empty output receiving an owned directory path, only left empty + * on success if this descriptor opted into skipping an absent target. * @return Zero or negative lookup/type/creation errno. Existing metadata is - * preserved; a new target is root-owned 0755. Missing parents are errors. All - * temporary paths retire on failure; a successfully created empty directory - * may remain. Exclusive boot execution; no graph/module lock spans callbacks. + * preserved; a new target is root-owned 0755. Only ENOENT from lookup may be + * skipped. All temporary paths retire on failure; a successfully created empty + * directory may remain. Exclusive boot execution; no locks span callbacks. */ static int initial_mountpoint(const struct vfs_path *root, const struct vfs_boot_mount *request,struct vfs_path *point) @@ -30,6 +31,7 @@ static int initial_mountpoint(const struct vfs_path *root, (request->create_directory ? VFS_LOOKUP_MISSING : 0)}; struct vfs_lookup_result found={0}; int rc=vfs_path_resolve(&system_namespace,root,root,request->target,&policy,&found); + if(rc==-ENOENT && request->skip_missing_target)return 0; if(!rc && found.missing) { const struct reliefos_permissions mode={0755,0,0}; rc=vfs_path_create_node(&found.path,found.last,LINUX_S_IFDIR,&mode,NULL,point); @@ -47,9 +49,10 @@ static int initial_mountpoint(const struct vfs_path *root, * @param root_context Borrowed factory context. * @param mounts Ordered borrowed descriptors; parents precede children. * @param count Descriptor count; zero permits NULL mounts. - * @return Zero or negative errno. Failures retire all temporary mounts/paths; - * newly created empty target directories can remain. Existing publication is - * EBUSY. Exclusive early boot execution; no graph/module locks across I/O. + * @return Zero or the original negative assembly errno. Failures release all + * graph-owned paths and attempt final backend teardown. Failed finishes remain + * on the retry queue; created empty directories may remain. An existing graph + * returns EBUSY. Exclusive boot execution; no graph/module lock spans I/O. */ int vfs_system_bootstrap(int (*create_root)(void *,struct vfs_mount **),void *root_context, const struct vfs_boot_mount *mounts,size_t count) @@ -67,15 +70,15 @@ int vfs_system_bootstrap(int (*create_root)(void *,struct vfs_mount **),void *ro struct vfs_path root={0},point={0}; rc=vfs_namespace_root(&system_namespace,&root); if(!rc)rc=initial_mountpoint(&root,&mounts[i],&point); + if(!rc && !vfs_path_valid(&point)){vfs_path_put(&root);continue;} mount=NULL; - if(!rc && point.dentry->node.type!=RELIEFOS_FS_TYPE_DIR)rc=-ENOTDIR; if(!rc)rc=mounts[i].create(mounts[i].context,&mount); if(!rc)rc=vfs_mount_attach(&system_namespace,mount,&point); vfs_mount_put(mount);vfs_path_put(&point);vfs_path_put(&root); } if(rc) { - int cleanup=vfs_namespace_destroy(&system_namespace); - return cleanup ? cleanup : rc; + vfs_namespace_abort_bootstrap(&system_namespace); + return rc; } system_published=true;return 0; } diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 5397d1d3..284cdc87 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -51,6 +51,12 @@ struct vfs_mount { * publication or snapshot never advances this cursor. */ uint64_t vfs_mount_next_id(void); +/** @brief Discard an unpublished boot graph under exclusive execution. + * @param ns Builder-owned initial namespace, without external users. + * Drops graph-owned paths and attempts final backend teardown immediately; + * only a failed finish is deferred. Not for published namespace removal. + */ +void vfs_namespace_abort_bootstrap(struct vfs_namespace *ns); /** @brief Read the VFS-wide peer group ID cursor under execution ownership. * @return Next unassigned peer group, or zero after exhaustion. Only a * successful propagation change or mount transaction advances it. diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index f6fce996..113cad5c 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -1135,22 +1135,38 @@ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path) vfs_finish_unmounts(vfs_select_unmounts(ns,root,true),0,true);return 0; } -/** @brief Retire the complete graph locally, including the namespace anchor. +/** @brief Detach the complete graph and give up its mountpoint and membership pins. * @param ns Last-owner namespace storage, or NULL, under VFS execution. - * Repairs other graphs' weak propagation links before releasing paths. - * Does not propagate unmount or wait for open objects or backend finish. + * @param lazy True to defer backend finish even after the last path is gone. + * Repairs weak propagation links before releasing paths. Does not propagate + * unmount or run provider busy checks against mountpoint pins from this graph. */ -void vfs_namespace_retire(struct vfs_namespace *ns) +static void vfs_detach_namespace(struct vfs_namespace *ns,bool lazy) { if(!ns)return; struct vfs_mount *mounts=ns->mounts; for(struct vfs_mount *mount=mounts;mount;mount=mount->next) { - vfs_clear_mount_membership(mount);mount->lazy_detached=true; + vfs_clear_mount_membership(mount);mount->lazy_detached=lazy; } *ns=(struct vfs_namespace){0}; vfs_release_detached_mounts(mounts); } +/** @brief Retire the complete graph locally, including the namespace anchor. + * @param ns Last-owner namespace storage, or NULL, under VFS execution. + * Held paths survive; does not wait for backend finish. + */ +void vfs_namespace_retire(struct vfs_namespace *ns) +{vfs_detach_namespace(ns,true);} + +/** @brief Roll back an initial graph that was never exposed to path users. + * @param ns Unpublished boot graph, exclusively owned by its builder. + * Retires graph-owned pins before finishing each backend. As with any final + * mount put, a failed backend finish retains the mount on the retry queue. + */ +void vfs_namespace_abort_bootstrap(struct vfs_namespace *ns) +{vfs_detach_namespace(ns,false);} + /** @brief Destroy an externally owned graph only if no paths or users remain. * @param ns Boot/fixture storage with stable address, under execution ownership. * @return Zero, EINVAL for invalid storage, EBUSY for live references, or the diff --git a/fs/vfs/storage_initial.c b/fs/vfs/storage_initial.c index eb92b585..fb3e6a6d 100644 --- a/fs/vfs/storage_initial.c +++ b/fs/vfs/storage_initial.c @@ -75,8 +75,10 @@ static int storage_initial_shm(struct storage_volume **created) * are all published, or negative errno after complete assembly rollback. A * failed constructor/attachment never publishes a partial system namespace. * The caller owns exclusive boot execution; no graph/module lock spans I/O. - * Reserved ESP identity and ready optical instances define initial roles; - * no stored mount-path label participates in selection or routing. + * Reserved ESP identity and ready optical instances define initial roles. + * Skip optical attachments when their mountpoint parent is absent; the + * discovered instance remains available for an explicit mount. No stored + * mount-path label participates in selection or routing. */ int storage_namespace_bootstrap(void) { @@ -84,28 +86,34 @@ int storage_namespace_bootstrap(void) if(!g_volumes[0].ready)return -ENODEV; struct storage_volume *created=NULL;int rc=storage_initial_shm(&created);if(rc)return rc; struct vfs_boot_mount mounts[STORAGE_MAX_VOLUMES+3]={ - {"/dev",storage_initial_devfs,NULL,false}, - {"/proc",storage_initial_procfs,NULL,false}, - {"/sys",storage_initial_sysfs,NULL,false} + {.target="/dev",.create=storage_initial_devfs}, + {.target="/proc",.create=storage_initial_procfs}, + {.target="/sys",.create=storage_initial_sysfs} }; size_t count=3;uint32_t optical_count=0; char optical_targets[STORAGE_MAX_VOLUMES][32]; if(g_volumes[STORAGE_VOLUME_BOOT].ready) - mounts[count++]=(struct vfs_boot_mount){"/boot",storage_initial_volume,&g_volumes[STORAGE_VOLUME_BOOT],false}; + mounts[count++]=(struct vfs_boot_mount){.target="/boot",.create=storage_initial_volume, + .context=&g_volumes[STORAGE_VOLUME_BOOT]}; for(uint32_t i=STORAGE_VOLUME_DYNAMIC_FIRST;ivolume_id))return -EBUSY; - tmpfs_destroy(created->tmpfs);*created=(struct storage_volume){0}; - storage_cache_invalidate(); + if(storage_inode_volume_busy(created->volume_id)) + console_error("[vfs] retained boot shm volume=%u after failed assembly\n",created->volume_id); + else { + tmpfs_destroy(created->tmpfs);*created=(struct storage_volume){0}; + storage_cache_invalidate(); + } } return rc; } diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 745f0b65..8139be21 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -295,6 +295,8 @@ struct vfs_boot_mount { /* Create only a missing final resolved directory, root-owned 0755. Parent * directories must already exist; existing inode metadata is preserved. */ bool create_directory; + /** Skip this attachment on ENOENT from target resolution, not its factory. */ + bool skip_missing_target; }; /** @brief Assemble and publish the system's shared initial mount namespace. * @param create_root Factory returning one owned detached initial root mount. @@ -302,12 +304,12 @@ struct vfs_boot_mount { * @param mounts Ordered initial attachments; parents must precede children, * NULL only with count zero. Target strings live through this call only. * @param count Number of attachment descriptors. - * @return Zero or negative errno. Publishes only after all factories and - * attachments succeed; failures retire every temporary path and mount. A newly - * created empty target directory may remain after a later assembly failure. - * Called - * before task creation under exclusive execution ownership, without scheduler, - * graph or module locks across I/O. An existing namespace returns EBUSY. + * @return Zero or the original negative errno. Publishes only after all + * required attachments succeed; absent opt-in targets are skipped before their + * factory runs. Failure releases every graph-owned path and mount membership; + * failed backend finishes are deferred and created empty directories may remain. + * Called before task creation under exclusive execution ownership, without + * scheduler, graph or module locks across I/O. An existing graph returns EBUSY. */ int vfs_system_bootstrap(int (*create_root)(void *,struct vfs_mount **),void *root_context, const struct vfs_boot_mount *mounts,size_t count); diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 738c99e6..597a78a5 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -452,8 +452,11 @@ int storage_read_iso_blocks(uint64_t lba,uint32_t blocks,void *buffer) if(offset>iso_image_size || length>iso_image_size-offset)return -5; memcpy(buffer,iso_image+offset,length);return 0; } -/* Exercise the production initial attachment with the real optical parser. - * The image owns /media but deliberately has no numbered optical directory. */ +/** @brief Exercise real ISO9660 boot attachments with and without /media. + * @return None. Boot without /media neither creates that directory nor mounts + * the disc. With /media present, bootstrap creates and covers the numbered + * target, exposing the exact read-only payload. Restores all fixture volumes. + */ static void initial_optical_namespace(void) { assert(!storage_inode_purge_volume(0)); @@ -467,12 +470,23 @@ static void initial_optical_namespace(void) g_volumes[slot]=(struct storage_volume){.volume_id=slot,.kind=STORAGE_VOLUME_ANONYMOUS, .ready=true,.filesystem=STORAGE_FILESYSTEM_TMPFS,.fs_ops=&storage_tmpfs_ops,.tmpfs=fs}; } - const char *directories[]={"/dev","/proc","/sys","/media"}; + const char *directories[]={"/dev","/proc","/sys"}; + struct tmpfs_super *fs=g_volumes[0].tmpfs; for(size_t i=0;itmpfs,"/child",LINUX_S_IFDIR|0755,NULL,NULL)); + const struct vfs_boot_mount mounts[]={ + {.target="/child",.create=initial_volume,.context=child}, + {.target="/absent",.create=initial_devices} + }; + assert(vfs_system_bootstrap(initial_volume,root,mounts,2)==-ENOENT); + assert(!vfs_system_namespace() && !vfs_reclaim_pending()); + assert(!root->ready && !root->vfs_mounts && !storage_inode_volume_busy(3)); + assert(!child->ready && !child->vfs_mounts && !storage_inode_volume_busy(4)); + puts("PASS initial managed mount rollback: preserves ENOENT and retires child and root after dropping graph-owned pins"); +} + static void initial_namespace(void) { struct vfs_boot_mount mounts[]={ - {"/mnt",initial_volume,&g_volumes[2]}, - {"/devices",initial_devices,NULL}, - {"/absent",initial_devices,NULL} + {.target="/mnt",.create=initial_volume,.context=&g_volumes[2]}, + {.target="/devices",.create=initial_devices}, + {.target="/absent",.create=initial_devices} }; assert(!vfs_system_namespace()); assert(vfs_system_bootstrap(initial_volume,&g_volumes[0],mounts,3)==-ENOENT); @@ -1439,11 +1480,11 @@ static void initial_namespace(void) assert(!storage_inode_volume_busy(0) && !storage_inode_volume_busy(2)); } assert(succeeded); - struct vfs_boot_mount generated={"/initial-generated",initial_devices,NULL,true}; - struct vfs_boot_mount missing_parent={"/initial-missing/child",initial_devices,NULL,true}; + struct vfs_boot_mount generated={.target="/initial-generated",.create=initial_devices,.create_directory=true}; + struct vfs_boot_mount missing_parent={.target="/initial-missing/child",.create=initial_devices,.create_directory=true}; assert(vfs_system_bootstrap(initial_volume,&g_volumes[0],&missing_parent,1)==-ENOENT); assert(!tmpfs_create(g_volumes[0].tmpfs,"/initial-not-directory",LINUX_S_IFREG|0600,NULL,NULL)); - struct vfs_boot_mount not_directory={"/initial-not-directory",initial_devices,NULL,true}; + struct vfs_boot_mount not_directory={.target="/initial-not-directory",.create=initial_devices,.create_directory=true}; assert(vfs_system_bootstrap(initial_volume,&g_volumes[0],¬_directory,1)==-ENOTDIR); assert(!tmpfs_unlink(g_volumes[0].tmpfs,"/initial-not-directory",false)); bool generated_success=false; @@ -4010,6 +4051,7 @@ int main(int argc,char **argv) assert(!vfs_namespace_destroy(&ns)); assert(!storage_inode_volume_busy(0) && !storage_inode_volume_busy(2)); assert(!tmpfs_create(fs,"/mnt",LINUX_S_IFDIR|0755,NULL,NULL)); + initial_managed_rollback(); initial_namespace(); production_initial_namespace(fs); tmpfs_destroy(fs);tmpfs_destroy(second); From df9af86c6507ff141f33c76dbc1690bf470e34b0 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 08:40:44 +0800 Subject: [PATCH 19/97] fix(vfs): report statx mount-root attributes --- Documentation/userspace-api/abi.rst | 10 ++++ fs/vfs/mount_tree.c | 4 ++ include/reliefnt/mount.h | 5 ++ include/uapi/linux/stat.h | 1 + kernel/syscall/fs/metadata.c | 54 +++++++++++++--------- tools/test_mount_backend.py | 2 +- tools/tests/mount_backend_test.c | 64 +++++++++++++++++++++++++- tools/tests/task8_metadata_user_test.c | 15 +++++- 8 files changed, 130 insertions(+), 25 deletions(-) diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 1cfd8bcf..fbc115e6 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -95,6 +95,16 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 文件绑定尚不支持,返回明确错误。 +statx 挂载根属性 +================ + +``statx()`` 成功时在 ``stx_attributes_mask`` 中报告支持 +``STATX_ATTR_MOUNT_ROOT``。只有实际查询到的路径是其所在挂载的根时,才在 +``stx_attributes`` 中设置该位。因此,目录绑定的目标是挂载根,同一 inode +经原挂载查询时不一定是。``AT_EMPTY_PATH`` 使用描述符持有的路径,不重新查找 +可见名称;没有路径的匿名描述符不设置该属性。输出页争用后重试时返回同一份 +已完成的元数据和属性。 + 挂载传播 ================== diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index 113cad5c..d3e3830d 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -78,6 +78,10 @@ bool vfs_path_valid(const struct vfs_path *path) bool vfs_path_equal(const struct vfs_path *left,const struct vfs_path *right) {return vfs_path_valid(left) && vfs_path_valid(right) && left->mount==right->mount && left->dentry==right->dentry;} +/** @copydoc vfs_path_is_mount_root */ +bool vfs_path_is_mount_root(const struct vfs_path *path) +{return vfs_path_valid(path) && path->dentry==path->mount->root;} + const struct storage_node *vfs_path_node(const struct vfs_path *path) {return vfs_path_valid(path) ? &path->dentry->node : NULL;} void *vfs_path_context(const struct vfs_path *path) diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 8139be21..82daca84 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -717,6 +717,11 @@ void vfs_path_put(struct vfs_path *path); * @return True for the same valid object pair. Caller keeps both stable. */ bool vfs_path_equal(const struct vfs_path *left,const struct vfs_path *right); +/** @brief Test whether the held dentry is the root of its own attachment. + * @param path Borrowed path under execution ownership, nullable. + * @return True for a mount root, including bind roots and retained detached roots. + */ +bool vfs_path_is_mount_root(const struct vfs_path *path); /** @brief Borrow the backend node held by a valid path. * @param path Held path, nullable. * @return Borrowed node or NULL, valid only through the held path lifetime. diff --git a/include/uapi/linux/stat.h b/include/uapi/linux/stat.h index eada7d1a..f9fe342e 100644 --- a/include/uapi/linux/stat.h +++ b/include/uapi/linux/stat.h @@ -26,6 +26,7 @@ #define LINUX_STATX_SIZE 0x00000200U #define LINUX_STATX_BLOCKS 0x00000400U #define LINUX_STATX_BASIC_STATS 0x000007ffU +#define LINUX_STATX_ATTR_MOUNT_ROOT 0x00002000ULL #define LINUX_S_IRWXU 0000700U #define LINUX_S_IRWXG 0000070U #define LINUX_S_IRWXO 0000007U diff --git a/kernel/syscall/fs/metadata.c b/kernel/syscall/fs/metadata.c index f9741e4a..e9a7c849 100644 --- a/kernel/syscall/fs/metadata.c +++ b/kernel/syscall/fs/metadata.c @@ -2,6 +2,13 @@ #include "../internal.h" #include +/* Retain attachment metadata alongside the completed inode snapshot while + * preparing user output. Neither value is collected again on copyout retry. */ +struct metadata_stat_result { + struct linux_stat_abi stat; + bool mount_root; +}; + /** @brief Borrow this operation's private, cancellation-owned result slot. * @param task Matching syscall owner. @param kind Expected result class. * @param slot Receives the borrowed slot, or NULL without a retry scope. @@ -123,14 +130,14 @@ static int metadata_fd_statfs(struct task *task,int fd,struct linux_statfs_abi * * @param dirfd Base descriptor or AT_FDCWD. * @param pathname Retained kernel snapshot, including any allowed empty name. * @param flags Validated AT_SYMLINK_NOFOLLOW/AT_EMPTY_PATH policy. - * @param out Caller-owned stat result. + * @param out Caller-owned inode and attachment snapshot. * @param slot Receives the optional retry-owned result slot. * @return Zero or negative errno. The common retry scope keeps the completed - * operand across metadata waits. Pathless descriptors have no yielding name - * operation and are inspected directly, never via proc display strings. + * operand across metadata waits. Only the actual resolved path determines + * mount-root status, not a proc link standing in for a pathless descriptor. */ static int metadata_at_stat(struct vfs_namespace *ns,struct task *task,int32_t dirfd, - const char *pathname,uint32_t flags,struct linux_stat_abi *out, + const char *pathname,uint32_t flags,struct metadata_stat_result *out, struct task_lookup_path **slot) { struct vfs_lookup_result found={0}; @@ -144,9 +151,13 @@ static int metadata_at_stat(struct vfs_namespace *ns,struct task *task,int32_t d if((*slot)->dirfd!=(int32_t)sizeof(*out))rc=-RELIEFOS_EINVAL; else __builtin_memcpy(out,(*slot)->name,sizeof(*out)); } else if(!rc) { - if(found.has_stat)*out=found.stat; - else rc=fallback ? linux_stat_from_fd(task,dirfd,false,out) : linux_stat_from_path(out,&found.path); - if(!rc)storage_release_task_io(task->pid); + if(found.has_stat)out->stat=found.stat; + else rc=fallback ? linux_stat_from_fd(task,dirfd,false,&out->stat) : + linux_stat_from_path(&out->stat,&found.path); + if(!rc) { + out->mount_root=!found.has_stat && !fallback && vfs_path_is_mount_root(&found.path); + storage_release_task_io(task->pid); + } } } vfs_path_put(&found.path);return rc; @@ -163,7 +174,8 @@ static int metadata_at_stat(struct vfs_namespace *ns,struct task *task,int32_t d * @param a4 Statx output address. * @return Zero or negative errno. Outputs are copied only after successful * metadata retrieval and writable-range validation. Provider waits retain the - * original inode/OFD; no graph/module spinlock spans I/O. + * original inode/OFD; no graph/module spinlock spans I/O. Statx advertises + * mount-root detection even when the queried object is not a mount root. */ int64_t syscall_metadata(struct vfs_namespace *ns,struct task *task,uint64_t number, uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4) @@ -195,14 +207,15 @@ int64_t syscall_metadata(struct vfs_namespace *ns,struct task *task,uint64_t num *(struct linux_statfs_abi *)(uintptr_t)a1=value;return 0; } const uint32_t result_kind=METADATA_RESULT_STAT; - struct linux_stat_abi value;struct task_lookup_path *slot=NULL;uint64_t output=a1;int rc; + struct metadata_stat_result value={0}; + struct task_lookup_path *slot=NULL;uint64_t output=a1;int rc; if(number==LINUX_SYS_FSTAT) { rc=metadata_result_slot(task,result_kind,&slot); if(!rc && slot && slot->name) { if(slot->dirfd!=(int32_t)sizeof(value))rc=-RELIEFOS_EINVAL; else __builtin_memcpy(&value,slot->name,sizeof(value)); } else if(!rc) { - rc=linux_stat_from_fd(task,(int32_t)a0,false,&value); + rc=linux_stat_from_fd(task,(int32_t)a0,false,&value.stat); if(!rc)storage_release_task_io(task->pid); } } @@ -227,19 +240,18 @@ int64_t syscall_metadata(struct vfs_namespace *ns,struct task *task,uint64_t num if(at)output=number==LINUX_SYS_STATX ? a4 : a2; } if(rc)return rc; - if(number==LINUX_SYS_STATX) { + bool statx=number==LINUX_SYS_STATX; + size_t output_size=statx ? sizeof(struct linux_statx) : sizeof(value.stat); + rc=metadata_prepare_result(task,output,output_size,slot,result_kind,&value,sizeof(value),NULL); + if(rc)return rc; + if(!user_range_writable(output,output_size))return -RELIEFOS_EFAULT; + if(statx) { struct linux_statx extended; - linux_statx_from_legacy(&extended,&value,LINUX_STATX_BASIC_STATS); - rc=metadata_prepare_result(task,output,sizeof(extended),slot,result_kind,&value,sizeof(value),NULL); - if(rc)return rc; - if(!user_range_writable(output,sizeof(extended)))return -RELIEFOS_EFAULT; + linux_statx_from_legacy(&extended,&value.stat,LINUX_STATX_BASIC_STATS); + extended.stx_attributes_mask |= LINUX_STATX_ATTR_MOUNT_ROOT; + if(value.mount_root)extended.stx_attributes |= LINUX_STATX_ATTR_MOUNT_ROOT; *(struct linux_statx *)(uintptr_t)output=extended; - } else { - rc=metadata_prepare_result(task,output,sizeof(value),slot,result_kind,&value,sizeof(value),NULL); - if(rc)return rc; - if(!user_range_writable(output,sizeof(value)))return -RELIEFOS_EFAULT; - *(struct linux_stat_abi *)(uintptr_t)output=value; - } + } else *(struct linux_stat_abi *)(uintptr_t)output=value.stat; return 0; } diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index 08ae7346..b2e5d057 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -25,7 +25,7 @@ def test_real_tmpfs_without_text_routing(self): "fs/cgroup/filesystem.c", "fs/cgroup/hierarchy.c", "fs/vfs/notify.c", "fs/nsfs/namespace.c", "kernel/syscall/dispatch.c", "kernel/syscall/io/legacy_io.c", "kernel/syscall/io/io.c", "kernel/syscall/io/file_io.c", "kernel/syscall/io/seek.c", "kernel/syscall/io/transfer.c", - "kernel/syscall/io/directory.c", "tools/tests/mount_backend_io_boundaries.c", + "kernel/syscall/io/directory.c", "kernel/syscall/fs/metadata.c", "tools/tests/mount_backend_io_boundaries.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "tools/tests/task8_host_stubs/writable_alias_model.c", "fs/notify/core.c", "fs/notify/limits.c", "fs/notify/queue.c", "fs/notify/watch.c", diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 597a78a5..4d54615b 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -296,6 +296,7 @@ uint32_t task_evdev_vt_hint(const struct task *task) { (void)task; abort(); } static uint64_t filesystem_sector_reads; static uintptr_t lookup_user_base; static size_t lookup_user_bytes; +static uintptr_t statx_wait_output; bool user_range_ok(uint64_t address,uint64_t length) { if(!length)return true; @@ -328,8 +329,12 @@ void sched_block_current(void){abort();} void sched_sleep_current_until(uint64_t wake_tick){(void)wake_tick;abort();} bool user_range_writable(uint64_t address,uint64_t length) {return user_range_ok(address,length);} +/** @brief Model a resident input and one contended statx output page. */ int user_range_readable(uint64_t address,uint64_t length) -{return user_range_ok(address,length) ? 0 : -EFAULT;} +{ + if(statx_wait_output && address==statx_wait_output)return -EAGAIN; + return user_range_ok(address,length) ? 0 : -EFAULT; +} static unsigned readlink_waits; static struct storage_node sync_expected; static unsigned sync_errors; @@ -3013,6 +3018,61 @@ static void runtime_unbindable(struct vfs_namespace *ns,const struct vfs_path *r puts("PASS mount propagation types: root and capability checks, recursive private, unbindable mountinfo and bind pruning"); } +/** @brief Exercise statx on a mount and a subdirectory bind sharing inode identity. + * @param ns Test-owned namespace. @param actor Calling task with held root and cwd. + */ +static void runtime_statx_mount_root(struct vfs_namespace *ns,struct task *actor) +{ + struct { + const char source[32],bind[32],mounted[40],empty[1]; + struct linux_statx result; + } user={"/rbind-source/view","/rbind-target","/rbind-source/view/child","",{0}}; + const uint64_t root_attr=LINUX_STATX_ATTR_MOUNT_ROOT; + const uint32_t mask=LINUX_STATX_TYPE|LINUX_STATX_INO; + const uint32_t flags=LINUX_AT_NO_AUTOMOUNT|LINUX_AT_STATX_DONT_SYNC; + uintptr_t previous_base=lookup_user_base;size_t previous_bytes=lookup_user_bytes; + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + const uint64_t out=(uintptr_t)&user.result; + assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,LINUX_AT_FDCWD,(uintptr_t)user.source,flags,mask,out)); + assert((user.result.stx_mask&mask)==mask); + assert((user.result.stx_attributes_mask&root_attr) && !(user.result.stx_attributes&root_attr)); + struct linux_statx source=user.result; + assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,LINUX_AT_FDCWD,(uintptr_t)user.bind,flags,mask,out)); + assert((user.result.stx_attributes_mask&root_attr) && (user.result.stx_attributes&root_attr)); + assert(user.result.stx_ino==source.stx_ino && user.result.stx_dev_major==source.stx_dev_major && + user.result.stx_dev_minor==source.stx_dev_minor); + assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,LINUX_AT_FDCWD,(uintptr_t)user.mounted,flags,mask,out)); + assert((user.result.stx_attributes_mask&root_attr) && (user.result.stx_attributes&root_attr)); + + int fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.bind,LINUX_O_PATH,0); + assert(fd>=0); + assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,fd,0,LINUX_AT_EMPTY_PATH,0,out)); + struct linux_statx expected=user.result;user.result=(struct linux_statx){0}; + assert((expected.stx_attributes_mask&root_attr) && (expected.stx_attributes&root_attr)); + assert(expected.stx_ino==source.stx_ino); + + struct trap_frame frame={.rax=LINUX_SYS_STATX,.rdi=fd,.rsi=(uintptr_t)user.empty, + .rdx=LINUX_AT_EMPTY_PATH,.r8=out}; + task_lookup_scope_begin(actor,&frame);statx_wait_output=out; + assert(syscall_metadata(ns,actor,frame.rax,frame.rdi,frame.rsi,frame.rdx,frame.r10,frame.r8)== + KERNEL_SYSCALL_SWAP_CONTENDED); + assert(!user.result.stx_attributes_mask); + statx_wait_output=0;access_stat_failure=true; + task_lookup_scope_begin(actor,&frame); + assert(!syscall_metadata(ns,actor,frame.rax,frame.rdi,frame.rsi,frame.rdx,frame.r10,frame.r8)); + assert(!memcmp(&user.result,&expected,sizeof(expected))); + access_stat_failure=false;task_lookup_scope_cancel(actor);task_discard_file_fd(actor,fd); + + struct task_file *anonymous; + fd=task_allocate_fd(actor,3,&anonymous); + assert(fd>=0);anonymous->node.type=RELIEFOS_FS_TYPE_FILE; + assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,fd,0,LINUX_AT_EMPTY_PATH,mask,out)); + assert((user.result.stx_attributes_mask&root_attr) && !(user.result.stx_attributes&root_attr)); + task_discard_file_fd(actor,fd); + lookup_user_base=previous_base;lookup_user_bytes=previous_bytes; + puts("PASS statx mount root: native mount, bind identity, O_PATH and cached copyout"); +} + /** @brief Clone only the selected directory's mount topology, or publish none of it. * @param ns Borrowed test-owned namespace. @param root Held root in that namespace. * @param fs Base tmpfs in which to prepare the source, target and sibling points. @@ -3069,6 +3129,8 @@ static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_pat assert(vfs_path_mount_flags(©[i])==vfs_path_mount_flags(&original[i])); } assert(vfs_path_lookup(ns,root,root,"/rbind-target/outside",0,&(struct vfs_path){0})==-ENOENT); + sched_task_limits(&actor)->nofile.rlim_cur=32; + runtime_statx_mount_root(ns,&actor); assert(vfs_mount_unmount(ns,&bound)==-EBUSY); assert(!vfs_mount_unmount(ns,©[1]));vfs_path_put(©[1]); assert(!vfs_mount_unmount(ns,©[0]));vfs_path_put(©[0]); diff --git a/tools/tests/task8_metadata_user_test.c b/tools/tests/task8_metadata_user_test.c index b1ccd1f2..122b6ea3 100644 --- a/tools/tests/task8_metadata_user_test.c +++ b/tools/tests/task8_metadata_user_test.c @@ -78,8 +78,19 @@ struct task_file *task_file_for_io(struct task *task,int fd) { assert(task==¤t);return fd==3 ? &file : NULL; } struct task_pty_fd *task_pty_for_io(struct task *task,int fd) { (void)task;(void)fd;return NULL; } -int task_pty_node_for_fd(struct task *task,int fd,struct storage_node *out,const char **path) -{ (void)task;(void)fd;(void)out;(void)path;return -RELIEFOS_EBADF; } +/** @brief Reject unexpected live-table access from the metadata retry fixture. */ +struct task_file *task_file_for_fd(struct task *task,int fd) +{ (void)task;(void)fd;abort(); } +/** @brief Reject unexpected live PTY access from the metadata retry fixture. */ +struct task_pty_fd *task_pty_fd_for_fd(struct task *task,int fd) +{ (void)task;(void)fd;abort(); } +/** @brief The fixture has no PTY to describe. */ +int task_pty_node_from_endpoint(const struct task_pty_fd *endpoint,uint32_t implicit, + struct storage_node *out,const char **path) +{ (void)endpoint;(void)implicit;(void)out;(void)path;abort(); } +/** @brief Reject a mount-root check in the legacy fstat/readlink fixture. */ +bool vfs_path_is_mount_root(const struct vfs_path *path) +{ (void)path;abort(); } int task_pty_stream_for_fd(struct task *task,int fd) { (void)task;(void)fd;return -1; } const struct storage_node *vfs_path_node(const struct vfs_path *path) From d5c65a5f3e4da510601969ea6759228182b87d4d Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 08:51:37 +0800 Subject: [PATCH 20/97] fix(vfs): report statx mount attachment IDs --- Documentation/userspace-api/abi.rst | 13 +++++++---- include/uapi/linux/stat.h | 1 + kernel/syscall/fs/metadata.c | 19 +++++++++++---- tools/tests/mount_backend_test.c | 32 +++++++++++++++++++------- tools/tests/task8_metadata_user_test.c | 3 +++ 5 files changed, 51 insertions(+), 17 deletions(-) diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index fbc115e6..16a3c7ed 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -95,15 +95,20 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 文件绑定尚不支持,返回明确错误。 -statx 挂载根属性 -================ +statx 挂载标识和根属性 +====================== ``statx()`` 成功时在 ``stx_attributes_mask`` 中报告支持 ``STATX_ATTR_MOUNT_ROOT``。只有实际查询到的路径是其所在挂载的根时,才在 ``stx_attributes`` 中设置该位。因此,目录绑定的目标是挂载根,同一 inode 经原挂载查询时不一定是。``AT_EMPTY_PATH`` 使用描述符持有的路径,不重新查找 -可见名称;没有路径的匿名描述符不设置该属性。输出页争用后重试时返回同一份 -已完成的元数据和属性。 +可见名称;没有路径的匿名描述符不设置该属性。 + +实际路径有挂载 ID 时,``statx()`` 在 ``stx_mask`` 中设置 ``STATX_MNT_ID``, +并在 ``stx_mnt_id`` 中返回与 ``/proc/self/mountinfo`` 一致的 ID,即使请求掩码 +未指定该位。同一 inode 经不同挂载访问时可得到不同 ID。只有合成元数据、没有 +实际挂载路径的对象不报告 ID。不支持 ``STATX_MNT_ID_UNIQUE``,不会将旧式 ID +标记为唯一 ID。输出页争用后重试时沿用同一份已完成的 inode 元数据、ID 和属性。 挂载传播 ================== diff --git a/include/uapi/linux/stat.h b/include/uapi/linux/stat.h index f9fe342e..07a6b1d4 100644 --- a/include/uapi/linux/stat.h +++ b/include/uapi/linux/stat.h @@ -26,6 +26,7 @@ #define LINUX_STATX_SIZE 0x00000200U #define LINUX_STATX_BLOCKS 0x00000400U #define LINUX_STATX_BASIC_STATS 0x000007ffU +#define LINUX_STATX_MNT_ID 0x00001000U #define LINUX_STATX_ATTR_MOUNT_ROOT 0x00002000ULL #define LINUX_S_IRWXU 0000700U #define LINUX_S_IRWXG 0000070U diff --git a/kernel/syscall/fs/metadata.c b/kernel/syscall/fs/metadata.c index e9a7c849..42cc330d 100644 --- a/kernel/syscall/fs/metadata.c +++ b/kernel/syscall/fs/metadata.c @@ -3,9 +3,10 @@ #include /* Retain attachment metadata alongside the completed inode snapshot while - * preparing user output. Neither value is collected again on copyout retry. */ + * preparing user output. These values are not collected again on copyout retry. */ struct metadata_stat_result { struct linux_stat_abi stat; + uint64_t mount_id; bool mount_root; }; @@ -133,8 +134,8 @@ static int metadata_fd_statfs(struct task *task,int fd,struct linux_statfs_abi * * @param out Caller-owned inode and attachment snapshot. * @param slot Receives the optional retry-owned result slot. * @return Zero or negative errno. The common retry scope keeps the completed - * operand across metadata waits. Only the actual resolved path determines - * mount-root status, not a proc link standing in for a pathless descriptor. + * operand across metadata waits. Mount ID and root status describe the actual + * resolved path, not a proc link standing in for a pathless descriptor. */ static int metadata_at_stat(struct vfs_namespace *ns,struct task *task,int32_t dirfd, const char *pathname,uint32_t flags,struct metadata_stat_result *out, @@ -155,7 +156,10 @@ static int metadata_at_stat(struct vfs_namespace *ns,struct task *task,int32_t d else rc=fallback ? linux_stat_from_fd(task,dirfd,false,&out->stat) : linux_stat_from_path(&out->stat,&found.path); if(!rc) { - out->mount_root=!found.has_stat && !fallback && vfs_path_is_mount_root(&found.path); + if(!found.has_stat && !fallback) { + out->mount_id=vfs_path_mount_id(&found.path); + out->mount_root=vfs_path_is_mount_root(&found.path); + } storage_release_task_io(task->pid); } } @@ -175,7 +179,8 @@ static int metadata_at_stat(struct vfs_namespace *ns,struct task *task,int32_t d * @return Zero or negative errno. Outputs are copied only after successful * metadata retrieval and writable-range validation. Provider waits retain the * original inode/OFD; no graph/module spinlock spans I/O. Statx advertises - * mount-root detection even when the queried object is not a mount root. + * mount-root detection and reports the legacy mount ID when available, + * regardless of the requested mask. */ int64_t syscall_metadata(struct vfs_namespace *ns,struct task *task,uint64_t number, uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4) @@ -248,6 +253,10 @@ int64_t syscall_metadata(struct vfs_namespace *ns,struct task *task,uint64_t num if(statx) { struct linux_statx extended; linux_statx_from_legacy(&extended,&value.stat,LINUX_STATX_BASIC_STATS); + if(value.mount_id) { + extended.stx_mask |= LINUX_STATX_MNT_ID; + extended.stx_mnt_id=value.mount_id; + } extended.stx_attributes_mask |= LINUX_STATX_ATTR_MOUNT_ROOT; if(value.mount_root)extended.stx_attributes |= LINUX_STATX_ATTR_MOUNT_ROOT; *(struct linux_statx *)(uintptr_t)output=extended; diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 4d54615b..4219033e 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -3018,30 +3018,44 @@ static void runtime_unbindable(struct vfs_namespace *ns,const struct vfs_path *r puts("PASS mount propagation types: root and capability checks, recursive private, unbindable mountinfo and bind pruning"); } -/** @brief Exercise statx on a mount and a subdirectory bind sharing inode identity. +/** @brief Verify statx mount metadata against mountinfo, including a bind of the same inode. * @param ns Test-owned namespace. @param actor Calling task with held root and cwd. */ -static void runtime_statx_mount_root(struct vfs_namespace *ns,struct task *actor) +static void runtime_statx_mount_metadata(struct vfs_namespace *ns,struct task *actor) { struct { const char source[32],bind[32],mounted[40],empty[1]; struct linux_statx result; } user={"/rbind-source/view","/rbind-target","/rbind-source/view/child","",{0}}; + const char *mountpoints[]={"/",user.bind,user.mounted}; + uint64_t ids[3]={0};char table[6144];uint32_t count=0; + assert(!vfs_read_mount_table(ns,&actor->fs_paths.root,true,0,table,sizeof(table)-1,&count));table[count]=0; + for(const char *row=table;*row;) { + char point[128];uint64_t id; + assert(sscanf(row,"%" SCNu64 " %*s %*s %*s %127s",&id,point)==2); + for(unsigned i=0;i<3;++i)if(!strcmp(point,mountpoints[i]))ids[i]=id; + row=strchr(row,'\n');assert(row);++row; + } + assert(ids[0] && ids[1] && ids[2] && ids[0]!=ids[1]); const uint64_t root_attr=LINUX_STATX_ATTR_MOUNT_ROOT; - const uint32_t mask=LINUX_STATX_TYPE|LINUX_STATX_INO; + const uint32_t mask=LINUX_STATX_TYPE|LINUX_STATX_INO|LINUX_STATX_MNT_ID; + const uint32_t unique=0x00004000u; /* STATX_MNT_ID_UNIQUE, not implemented. */ const uint32_t flags=LINUX_AT_NO_AUTOMOUNT|LINUX_AT_STATX_DONT_SYNC; uintptr_t previous_base=lookup_user_base;size_t previous_bytes=lookup_user_bytes; lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); const uint64_t out=(uintptr_t)&user.result; assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,LINUX_AT_FDCWD,(uintptr_t)user.source,flags,mask,out)); - assert((user.result.stx_mask&mask)==mask); + assert((user.result.stx_mask&mask)==mask && user.result.stx_mnt_id==ids[0]); assert((user.result.stx_attributes_mask&root_attr) && !(user.result.stx_attributes&root_attr)); struct linux_statx source=user.result; - assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,LINUX_AT_FDCWD,(uintptr_t)user.bind,flags,mask,out)); + assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,LINUX_AT_FDCWD,(uintptr_t)user.bind,flags,mask|unique,out)); + assert((user.result.stx_mask&(mask|unique))==mask && user.result.stx_mnt_id==ids[1]); assert((user.result.stx_attributes_mask&root_attr) && (user.result.stx_attributes&root_attr)); assert(user.result.stx_ino==source.stx_ino && user.result.stx_dev_major==source.stx_dev_major && user.result.stx_dev_minor==source.stx_dev_minor); - assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,LINUX_AT_FDCWD,(uintptr_t)user.mounted,flags,mask,out)); + assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,LINUX_AT_FDCWD,(uintptr_t)user.mounted,flags,unique,out)); + assert((user.result.stx_mask&(LINUX_STATX_MNT_ID|unique))==LINUX_STATX_MNT_ID && + user.result.stx_mnt_id==ids[2]); assert((user.result.stx_attributes_mask&root_attr) && (user.result.stx_attributes&root_attr)); int fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.bind,LINUX_O_PATH,0); @@ -3050,6 +3064,7 @@ static void runtime_statx_mount_root(struct vfs_namespace *ns,struct task *actor struct linux_statx expected=user.result;user.result=(struct linux_statx){0}; assert((expected.stx_attributes_mask&root_attr) && (expected.stx_attributes&root_attr)); assert(expected.stx_ino==source.stx_ino); + assert((expected.stx_mask&LINUX_STATX_MNT_ID) && expected.stx_mnt_id==ids[1]); struct trap_frame frame={.rax=LINUX_SYS_STATX,.rdi=fd,.rsi=(uintptr_t)user.empty, .rdx=LINUX_AT_EMPTY_PATH,.r8=out}; @@ -3068,9 +3083,10 @@ static void runtime_statx_mount_root(struct vfs_namespace *ns,struct task *actor assert(fd>=0);anonymous->node.type=RELIEFOS_FS_TYPE_FILE; assert(!syscall_metadata(ns,actor,LINUX_SYS_STATX,fd,0,LINUX_AT_EMPTY_PATH,mask,out)); assert((user.result.stx_attributes_mask&root_attr) && !(user.result.stx_attributes&root_attr)); + assert(!(user.result.stx_mask&LINUX_STATX_MNT_ID) && !user.result.stx_mnt_id); task_discard_file_fd(actor,fd); lookup_user_base=previous_base;lookup_user_bytes=previous_bytes; - puts("PASS statx mount root: native mount, bind identity, O_PATH and cached copyout"); + puts("PASS statx mount metadata: mountinfo IDs, bind identity, O_PATH and cached copyout"); } /** @brief Clone only the selected directory's mount topology, or publish none of it. @@ -3130,7 +3146,7 @@ static void runtime_recursive_bind(struct vfs_namespace *ns,const struct vfs_pat } assert(vfs_path_lookup(ns,root,root,"/rbind-target/outside",0,&(struct vfs_path){0})==-ENOENT); sched_task_limits(&actor)->nofile.rlim_cur=32; - runtime_statx_mount_root(ns,&actor); + runtime_statx_mount_metadata(ns,&actor); assert(vfs_mount_unmount(ns,&bound)==-EBUSY); assert(!vfs_mount_unmount(ns,©[1]));vfs_path_put(©[1]); assert(!vfs_mount_unmount(ns,©[0]));vfs_path_put(©[0]); diff --git a/tools/tests/task8_metadata_user_test.c b/tools/tests/task8_metadata_user_test.c index 122b6ea3..4a582856 100644 --- a/tools/tests/task8_metadata_user_test.c +++ b/tools/tests/task8_metadata_user_test.c @@ -91,6 +91,9 @@ int task_pty_node_from_endpoint(const struct task_pty_fd *endpoint,uint32_t impl /** @brief Reject a mount-root check in the legacy fstat/readlink fixture. */ bool vfs_path_is_mount_root(const struct vfs_path *path) { (void)path;abort(); } +/** @brief Reject a mount ID lookup in the legacy fstat/readlink fixture. */ +uint64_t vfs_path_mount_id(const struct vfs_path *path) +{ (void)path;abort(); } int task_pty_stream_for_fd(struct task *task,int fd) { (void)task;(void)fd;return -1; } const struct storage_node *vfs_path_node(const struct vfs_path *path) From 19f136b387f2846a85e91ba7c707cba70f69e700 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 09:05:47 +0800 Subject: [PATCH 21/97] fix(net): support SO_REUSEADDR on UNIX and netlink sockets --- .../LC_MESSAGES/userspace-api/descriptors.po | 13 +++++ .../LC_MESSAGES/userspace-api/descriptors.po | 11 ++++ Documentation/userspace-api/descriptors.rst | 5 ++ kernel/syscall/ipc/socket.c | 13 ++++- net/socket/netlink.c | 20 ++++--- tools/tests/Makefile | 1 + tools/tests/ipv6_control_test.c | 36 ++++++++++++ tools/tests/socket_batch_unix_test.c | 58 ++++++++++++++++++- 8 files changed, 145 insertions(+), 12 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index 43501d1b..731e5b53 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -252,6 +252,19 @@ msgstr "" "`_" " for flag definitions." +msgid "" +"``AF_UNIX`` 和 ``AF_NETLINK`` 的 ``SOL_SOCKET/SO_REUSEADDR`` 使用原生 32 位 " +"整数,默认读回 0;设置非零值后读回 1,设置 0 清除。该状态不改变地址绑定规则: " +"UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 " +"监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。" +msgstr "" +"``SOL_SOCKET/SO_REUSEADDR`` on ``AF_UNIX`` and ``AF_NETLINK`` uses a native " +"32-bit integer. It reads as 0 by default, reads as 1 after setting a nonzero " +"value, and is cleared by setting 0. This state does not change binding rules: " +"UNIX addresses and netlink ports within the same protocol still cannot be bound " +"twice. UNIX ``accept`` does not inherit the listener's option. Netlink group " +"membership, permissions, and filtering are unchanged." + msgid "" "TCP 的 ``setsockopt/getsockopt(SOL_TCP, TCP_NODELAY)`` 接受原生整数标志, " "默认关闭并由监听套接字传给新连接。关闭时,尚有未确认数据的小段等待确认或 完整 MSS " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index eac91138..75cbce78 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -217,6 +217,17 @@ msgstr "" "`_" " を参照してください。" +msgid "" +"``AF_UNIX`` 和 ``AF_NETLINK`` 的 ``SOL_SOCKET/SO_REUSEADDR`` 使用原生 32 位 " +"整数,默认读回 0;设置非零值后读回 1,设置 0 清除。该状态不改变地址绑定规则: " +"UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 " +"监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。" +msgstr "" +"``AF_UNIX`` と ``AF_NETLINK`` の ``SOL_SOCKET/SO_REUSEADDR`` はネイティブの 32 ビット整数を使用します。" +"既定値は 0 で、非ゼロの値を設定すると 1 が返り、0 を設定すると解除されます。" +"バインド規則は変わらず、UNIX アドレスと同一プロトコル内の netlink ポートの重複バインドはできません。" +"UNIX の ``accept`` はリスナーの設定を継承しません。netlink のグループへの参加、権限、フィルタリングは変わりません。" + msgid "" "TCP 的 ``setsockopt/getsockopt(SOL_TCP, TCP_NODELAY)`` 接受原生整数标志, " "默认关闭并由监听套接字传给新连接。关闭时,尚有未确认数据的小段等待确认或 完整 MSS " diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index 62bdeb91..8a1e423c 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -109,6 +109,11 @@ TCP 的 ``recvfrom/recvmsg`` 支持 ``MSG_PEEK``:重复预读保留相同的 或把短读冒充所请求的完整语义。UDP、packet 和 UNIX 的标志支持由各协议处理。 标志定义参见 `POSIX socket 头文件 `_。 +``AF_UNIX`` 和 ``AF_NETLINK`` 的 ``SOL_SOCKET/SO_REUSEADDR`` 使用原生 32 位 +整数,默认读回 0;设置非零值后读回 1,设置 0 清除。该状态不改变地址绑定规则: +UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 +监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。 + TCP 的 ``setsockopt/getsockopt(SOL_TCP, TCP_NODELAY)`` 接受原生整数标志, 默认关闭并由监听套接字传给新连接。关闭时,尚有未确认数据的小段等待确认或 完整 MSS 后发送;启用时立即尝试发送已排队的小段,仍遵守对端窗口、拥塞窗口 diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 27253068..25ba6cda 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -131,6 +131,7 @@ struct unix_socket { uint32_t passcred; uint32_t receive_lowwater; bool bound; + bool reuse_address; /* Socket option state; UNIX names remain exclusive. */ uint32_t unaccepted; uint64_t receive_timeout; uint64_t send_timeout; @@ -2989,6 +2990,8 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, * @note SO_*TIMEO uses scheduler ticks, rounds positive values up, maps an * all-zero timeval to an infinite wait, and maps negative seconds to an * immediate timeout that getsockopt reports as (0, 0). + * SO_REUSEADDR records a boolean without changing name ownership or being + * inherited by accepted sockets. */ static int unix_socket_option(struct unix_socket *socket, bool setting, int level, int option, uint64_t address, uint64_t length) @@ -3023,13 +3026,16 @@ static int unix_socket_option(struct unix_socket *socket, bool setting, int leve else socket->send_timeout = ticks; return 0; } - if (option != SO_PASSCRED && option != SO_RCVLOWAT) return -LINUX_ENOPROTOOPT; - if (length < sizeof(int32_t)) return -RELIEFOS_EINVAL; + if (option != SO_PASSCRED && option != SO_RCVLOWAT && option != SO_REUSEADDR) + return -LINUX_ENOPROTOOPT; + if ((uint32_t)length < sizeof(int32_t)) return -RELIEFOS_EINVAL; int prep=socket_user_prepare(sched_current_task(),address,sizeof(int32_t),false); if(prep)return prep; if (!user_range_ok(address, sizeof(int32_t))) return -RELIEFOS_EFAULT; - int32_t value = *(const int32_t *)(uintptr_t)address; + int32_t value; + __builtin_memcpy(&value, (const void *)(uintptr_t)address, sizeof(value)); if (option == SO_PASSCRED) socket->passcred = value != 0; + else if (option == SO_REUSEADDR) socket->reuse_address = value != 0; else socket->receive_lowwater = value < 0 ? INT32_MAX : value ? (uint32_t)value : 1; return 0; } @@ -3051,6 +3057,7 @@ static int unix_socket_option(struct unix_socket *socket, bool setting, int leve case SO_TYPE: value = (int32_t)socket->type; break; case SO_ERROR: value = socket->error; socket->error = 0; break; case SO_PASSCRED: value = (int32_t)socket->passcred; break; + case SO_REUSEADDR: value = socket->reuse_address; break; case SO_RCVLOWAT: value = (int32_t)socket->receive_lowwater; break; case SO_SNDLOWAT: value = 1; break; case SO_ACCEPTCONN: value = socket->state == UNIX_SOCKET_LISTEN; break; diff --git a/net/socket/netlink.c b/net/socket/netlink.c index 9feae659..8d437416 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -35,6 +35,7 @@ struct netlink_socket { uint32_t port, queued_bytes, groups; int type, protocol; bool bound, connected, overrun, passcred; + bool reuse_address; /* Socket option state; port ownership is unchanged. */ }; struct nl_builder { struct netlink_message *message, *completion; @@ -1166,7 +1167,8 @@ static int nl_export_address(struct task *task,uint64_t address,uint64_t length, /** @brief Dispatch socket creation, bind, connect, name and supported options. * @param number Native syscall. @param a0 First argument. @param a1 Second argument. * @param a2 Third argument. @param a3 Fourth argument. @param a4 Fifth argument. - * @param a5 Sixth argument. @return Syscall result or negative errno. */ + * @param a5 Sixth argument. @return Syscall result or negative errno. + * @note SO_REUSEADDR stores per-socket state without allowing duplicate ports. */ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, uint64_t a3,uint64_t a4,uint64_t a5) { @@ -1235,20 +1237,22 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, } if (a1!=SOL_SOCKET) return -LINUX_ENOPROTOOPT; if (number == __NR_setsockopt) { - if (a2 != SO_PASSCRED || s->protocol != NETLINK_KOBJECT_UEVENT) + if (a2 != SO_REUSEADDR && (a2 != SO_PASSCRED || s->protocol != NETLINK_KOBJECT_UEVENT)) return -LINUX_ENOPROTOOPT; - if (a4 < sizeof(int)) + if ((int32_t)a4 < (int32_t)sizeof(int32_t)) return -LINUX_EINVAL; - int enable; + int32_t enable; int ret = socket_user_import(task, a3, &enable, sizeof(enable)); - if (!ret) - s->passcred = enable != 0; - return ret; + if (ret) return ret; + if (a2 == SO_REUSEADDR) s->reuse_address = enable != 0; + else s->passcred = enable != 0; + return 0; } - int value; + int32_t value; if (a2==SO_TYPE) value=s->type; else if (a2==SO_DOMAIN) value=AF_NETLINK; else if (a2==SO_PROTOCOL) value=s->protocol; + else if (a2==SO_REUSEADDR) value=s->reuse_address; else if (a2==SO_PASSCRED && s->protocol == NETLINK_KOBJECT_UEVENT) value=s->passcred; else if (a2==SO_ERROR) value=s->overrun ? LINUX_ENOBUFS : 0; else return -LINUX_ENOPROTOOPT; diff --git a/tools/tests/Makefile b/tools/tests/Makefile index f7d291c7..1774226f 100644 --- a/tools/tests/Makefile +++ b/tools/tests/Makefile @@ -16,6 +16,7 @@ test-host-smoke: --suite fat_async_read --suite fat_read_split \ --suite squashfs --suite squashfs_boot \ --suite linux_pty --suite mount_backend --suite mount_namespace_task --suite cgroup_scheduler \ + --suite linux_socket_batches --suite ipv6_control \ --suite vdso_mapping --suite vdso_time test-smp-time: diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 100820b4..59125658 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -171,8 +171,44 @@ static void check_dump_boundaries(int fd) assert(nl_socket(&files[fd])->queued_bytes==0); } +/** @brief Verify SO_REUSEADDR state without changing netlink port exclusivity. */ +static void check_netlink_reuseaddr(void) +{ + const int protocols[] = {NETLINK_ROUTE, NETLINK_KOBJECT_UEVENT}; + for (unsigned i = 0; i < sizeof(protocols) / sizeof(protocols[0]); ++i) { + int fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[i], 0, 0); + int other = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[i], 0, 0); + assert(fd >= 0 && other >= 0 && fd != other); + int32_t value = -1; + uint32_t size = sizeof(value); + const uintptr_t data = (uintptr_t)&value, length = (uintptr_t)&size; + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_REUSEADDR, data, length) && value == 0); + value = -7; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_REUSEADDR, data, sizeof(value))); + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_REUSEADDR, 0, sizeof(value)) == -LINUX_EFAULT); + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_REUSEADDR, data, sizeof(value) - 1) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_REUSEADDR, data, UINT32_MAX) == -LINUX_EINVAL); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_REUSEADDR, data, length) && value == 1); + assert(size == sizeof(value)); + assert(!call(__NR_getsockopt, other, SOL_SOCKET, SO_REUSEADDR, data, length) && value == 0); + value = 1; + assert(!call(__NR_setsockopt, other, SOL_SOCKET, SO_REUSEADDR, data, sizeof(value))); + struct sockaddr_nl addr = {.nl_family = AF_NETLINK, .nl_pid = 42, .nl_groups = i != 0}; + assert(!call(__NR_bind, fd, (uintptr_t)&addr, sizeof(addr), 0, 0)); + assert(call(__NR_bind, other, (uintptr_t)&addr, sizeof(addr), 0, 0) == -LINUX_EADDRINUSE); + value = 0; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_REUSEADDR, data, sizeof(value))); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_REUSEADDR, data, length) && value == 0); + task_netlink_release(&files[other]); files[other] = (struct task_file){0}; + task_netlink_release(&files[fd]); files[fd] = (struct task_file){0}; + } + assert(!allocations); + puts("PASS route and kobject netlink SO_REUSEADDR: state and exclusive port binding"); +} + int main(void) { + check_netlink_reuseaddr(); assert(!net_interface_register(2)); net_config.local_ip=0x0a00020f; net_config.subnet_mask=0xffffff00; int fd = (int)call(__NR_socket,AF_NETLINK,SOCK_RAW|SOCK_NONBLOCK,NETLINK_ROUTE,0,0); diff --git a/tools/tests/socket_batch_unix_test.c b/tools/tests/socket_batch_unix_test.c index 683128dd..3dee98d9 100644 --- a/tools/tests/socket_batch_unix_test.c +++ b/tools/tests/socket_batch_unix_test.c @@ -15,7 +15,7 @@ static bool swap_replace_passed; static uint64_t readonly; static unsigned allocations; static unsigned pty_holds; -/* AF_UNIX cases must not cross into the IPv4 backend. */ +/* AF_UNIX cases must not cross into another socket family's backend. */ int task_udp_recv(struct task_file *f, void *b, uint32_t n, uint32_t flags, uint64_t a, uint64_t l) { (void)f; (void)b; (void)n; (void)flags; (void)a; (void)l; abort(); } int task_udp_send(struct task_file *f, const void *b, uint32_t n, uint32_t flags, uint64_t a, uint32_t l) @@ -28,6 +28,37 @@ int task_packet_recv(struct task_file *file, void *data, uint32_t length, int task_packet_send(struct task_file *file, const void *data, uint32_t length, uint32_t flags, uint64_t address, uint32_t address_length) { (void)file; (void)data; (void)length; (void)flags; (void)address; (void)address_length; abort(); } +/** @brief Fail if this UNIX fixture inspects a UDP address. */ +uint32_t task_udp_address_size(const struct task_file *file) +{ (void)file; abort(); } +/** @brief Fail if this UNIX fixture receives a UDP message. */ +int task_udp_recv_ex(struct task_file *file, void *data, uint32_t length, uint32_t flags, + void *source, uint32_t *source_length, struct net_udp_rx_info *info) +{ (void)file; (void)data; (void)length; (void)flags; (void)source; (void)source_length; (void)info; abort(); } +#ifndef CONFIG_SWAP /* Swap fixtures supply this boundary separately. */ +/** @brief Fail if this UNIX fixture inspects a packet socket address. */ +uint32_t task_packet_address_size(const struct task_file *file) +{ (void)file; abort(); } +#endif +/** @brief Fail if this UNIX fixture receives a packet socket message. */ +int task_packet_recv_ex(struct task_file *file, void *data, uint32_t length, uint32_t flags, + void *source, uint32_t *source_length, struct net_udp_rx_info *info) +{ (void)file; (void)data; (void)length; (void)flags; (void)source; (void)source_length; (void)info; abort(); } +/** @brief Fail if this UNIX fixture sends a netlink message. */ +int task_netlink_send(struct task_file *file, const void *data, uint32_t length, + uint32_t flags, uint64_t address, uint32_t address_length) +{ (void)file; (void)data; (void)length; (void)flags; (void)address; (void)address_length; abort(); } +/** @brief Fail if this UNIX fixture receives a netlink message. */ +int task_netlink_recv(struct task_file *file, void *data, uint32_t length, + uint32_t flags, uint64_t address, uint64_t address_length) +{ (void)file; (void)data; (void)length; (void)flags; (void)address; (void)address_length; abort(); } +/** @brief Fail if this UNIX fixture stages a netlink message. */ +int task_netlink_recv_staged(struct task_file *file, void *data, uint32_t length, uint32_t flags, + void *source, uint32_t *source_length) +{ (void)file; (void)data; (void)length; (void)flags; (void)source; (void)source_length; abort(); } +/** @brief Fail if this UNIX fixture reads netlink credential configuration. */ +bool task_netlink_passcred(const struct task_file *file) +{ (void)file; abort(); } int net_socket_error(int32_t h, bool c) { (void)h; (void)c; abort(); } int net_socket_recv(struct reliefos_net_socket_io *r, uint32_t p) { (void)r; (void)p; abort(); } int net_socket_send(struct reliefos_net_socket_io *r, uint32_t p) { (void)r; (void)p; abort(); } @@ -115,6 +146,30 @@ static int batch(bool receive, struct mmsghdr *messages, unsigned count, unsigne return syscall_socket_mmsg(receive, receive ? 4 : 3, (uintptr_t)messages, count, flags, 0); } +/** @brief Verify per-socket SO_REUSEADDR state and the integer option ABI. */ +static void check_unix_reuseaddr(void) +{ + int32_t value = -1; + socklen_t size = sizeof(value); + const uintptr_t data = (uintptr_t)&value, length = (uintptr_t)&size; + assert(!unix_socket_option(&peers[0], false, SOL_SOCKET, SO_REUSEADDR, data, length)); + assert(value == 0 && size == sizeof(value)); + value = -7; + assert(!unix_socket_option(&peers[0], true, SOL_SOCKET, SO_REUSEADDR, data, sizeof(value))); + assert(unix_socket_option(&peers[0], true, SOL_SOCKET, SO_REUSEADDR, 0, sizeof(value)) == -LINUX_EFAULT); + assert(unix_socket_option(&peers[0], true, SOL_SOCKET, SO_REUSEADDR, data, sizeof(value) - 1) == -LINUX_EINVAL); + assert(unix_socket_option(&peers[0], true, SOL_SOCKET, SO_REUSEADDR, data, UINT32_MAX) == -LINUX_EINVAL); + size = UINT32_MAX; + assert(unix_socket_option(&peers[0], false, SOL_SOCKET, SO_REUSEADDR, data, length) == -LINUX_EINVAL); + size = sizeof(value); + assert(unix_socket_option(&peers[0], false, SOL_SOCKET, SO_REUSEADDR, 0, length) == -LINUX_EFAULT); + assert(!unix_socket_option(&peers[0], false, SOL_SOCKET, SO_REUSEADDR, data, length) && value == 1); + assert(!unix_socket_option(&peers[1], false, SOL_SOCKET, SO_REUSEADDR, data, length) && value == 0); + assert(!unix_socket_option(&peers[0], true, SOL_SOCKET, SO_REUSEADDR, data, sizeof(value))); + assert(!unix_socket_option(&peers[0], false, SOL_SOCKET, SO_REUSEADDR, data, length) && value == 0); + puts("PASS AF_UNIX SO_REUSEADDR: per-socket state and invalid inputs"); +} + int main(void) { current.kind = TASK_KIND_USER; @@ -128,6 +183,7 @@ int main(void) endpoints[i] = (struct task_file){.used = 1, .references = 1, .aux = i + 1, .flags = TASK_FILE_FLAG_SOCKET | TASK_FILE_FLAG_SOCKET_UNIX | RELIEFOS_O_RDWR}; } + check_unix_reuseaddr(); /* Linux imports the outgoing header before blocking. A changed user * msg_name must not redirect or fault the already suspended send. */ char snapshot_data[]="pin",snapshot_received[4]={0}; From d36d3c52df31a139ef51d12ba20ba6def604f91e Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 12:24:26 +0800 Subject: [PATCH 22/97] feat(vfs): support file bind mounts --- .../en/LC_MESSAGES/userspace-api/abi.po | 46 ++----- .../ja/LC_MESSAGES/userspace-api/abi.po | 42 ++----- Documentation/userspace-api/abi.rst | 21 ++-- fs/vfs/mount_tree.c | 32 ++--- include/reliefnt/mount.h | 24 ++-- kernel/syscall/fs/mount.c | 2 +- tools/tests/mount_backend_test.c | 116 ++++++++++++++++++ 7 files changed, 181 insertions(+), 102 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index f61fabc4..a05961e2 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -85,20 +85,8 @@ msgstr "" msgid "加入挂载命名空间" msgstr "Joining a Mount Namespace" -msgid "" -"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 " -"``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 " -"``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 " -"``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 返回 ``EINVAL``。不支持 " -"pidfd、其他种类的命名空间或文件 bind mount。" -msgstr "" -"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNS)`` accept a " -"``/proc//ns/mnt`` handle opened as an ordinary read-only FD. The " -"caller needs effective ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` or the " -"call returns ``EPERM``. Invalid or ``O_PATH`` FDs return ``EBADF``. An " -"unsupported type, a non-nsfs FD, or ``CLONE_FS`` state still shared with " -"another task returns ``EINVAL``. Pidfds, other namespace types, and file " -"bind mounts are not supported." +msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 返回 ``EINVAL``。不支持 pidfd、其他种类的命名空间或 nsfs 句柄的 bind mount。" +msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNS)`` accept a ``/proc//ns/mnt`` handle opened as an ordinary read-only FD. The caller needs effective ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` or the call returns ``EPERM``. Invalid or ``O_PATH`` FDs return ``EBADF``. An unsupported type, a non-nsfs FD, or ``CLONE_FS`` state shared with another task returns ``EINVAL``. Pidfds, other namespace types, and bind mounts of nsfs handles are unsupported." msgid "" "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。参见 " @@ -124,28 +112,14 @@ msgstr "" "``ENOTTY``. An ``O_PATH`` FD supports metadata queries but not read, " "write, seek, or ioctl operations." -msgid "目录 bind mount" -msgstr "Directory Bind Mounts" +msgid "bind mount" +msgstr "Bind Mounts" -msgid "" -"``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录绑定。 新挂载保留源目录的实际 " -"inode、父链和文件系统生命周期,继承源挂载的 只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 " -"root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 " -"源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" -msgstr "" -"``mount(source, target, NULL, MS_BIND, NULL)`` supports nonrecursive " -"directory binds. The new mount retains the source directory's actual " -"inode, parent chain, and filesystem lifecycle, and inherits source mount " -"policies such as read-only, nosuid, and nodev. The root field of " -"``/proc/self/mountinfo`` reports the source directory's path within its " -"filesystem; namespace paths, ``..``, and chroot boundaries are computed " -"relative to the new mount. The source filesystem cannot be ordinarily " -"unmounted while the bind remains, and unbinding does not destroy it." +msgid "``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录与文件绑定。 源和目标必须同为目录或同为非目录,不匹配时返回 ``ENOTDIR``。普通文件、 设备和 FIFO 等非目录对象可以相互作为源或目标。新挂载保留源的实际 inode、 父链和文件系统生命周期,继承源挂载的只读、nosuid、nodev 等策略。 ``/proc/self/mountinfo`` 的 root 字段报告源 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" +msgstr "``mount(source, target, NULL, MS_BIND, NULL)`` supports nonrecursive directory and file binds. The source and destination must both be directories or both be nondirectories, otherwise the call returns ``ENOTDIR``. Nondirectories such as regular files, devices, and FIFOs may be bound to one another. The new mount retains the source inode, parent chain, and filesystem lifetime, and inherits source policies such as read-only, nosuid, and nodev. The root field of ``/proc/self/mountinfo`` reports the source path within its filesystem. Namespace paths, ``..``, and chroot boundaries are computed relative to the new mount. The source filesystem cannot be normally unmounted while the bind remains, and unbinding does not destroy it." -msgid "" -"``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 " -"inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" -msgstr "``MS_BIND | MS_REC`` also copies the mount topology beneath the source directory. The new attachments have their own mount IDs and policies but share their respective source inodes and filesystems. Mounts outside the source directory and unbindable subtrees are skipped. Preparation failure leaves the destination tree and existing mounts unchanged." +msgid "``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑,对非目录源则只绑定该对象。 子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" +msgstr "``MS_BIND | MS_REC`` also copies the mount topology beneath a source directory. A nondirectory source binds only that object. The copied mounts have independent mount IDs and policies, but share their source inodes and filesystems. Mounts outside the source directory and unbindable subtrees are skipped. Preparation failure leaves the destination tree and existing mounts unchanged." msgid "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` only changes the policy at the target mountpoint. It does not read the source, type, or filesystem options. The source mount, submounts, and shared filesystem are unchanged. Omitted atime options preserve the existing policy. If the shared filesystem is read-only, clearing the mountpoint's read-only flag does not make it writable." @@ -153,8 +127,8 @@ msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` on msgid "只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。" msgstr "A readonly transition returns EBUSY without changing policy while any regular file is open for writing on the target mount. References to the same open file description from dup, fork, and file mappings extend that restriction. Writers on other mounts and O_PATH-only handles do not block the transition." -msgid "文件绑定尚不支持,返回明确错误。" -msgstr "File binds are not yet supported and return an explicit error." +msgid "文件挂载的目标本身是挂载根,也可独立重新挂载、移动和卸载。移动时源挂载根 与目标必须同为目录或同为非目录,不匹配返回 ``EINVAL``。卸载后目标重新显示 被覆盖的原对象;原 inode、挂载 ID 和访问策略在移动期间保持不变。" +msgstr "The target of a file mount is itself a mount root and can be remounted, moved, or unmounted independently. For a move, the source mount root and target must both be directories or both be nondirectories, otherwise the call returns ``EINVAL``. Unmounting reveals the covered object. The original inode, mount ID, and access policy are preserved across the move." msgid "按任务选择 uname 系统名" msgstr "Selecting the uname system name per task" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index debed879..808dc5e2 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -77,18 +77,8 @@ msgstr "" msgid "加入挂载命名空间" msgstr "マウント名前空間への参加" -msgid "" -"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 " -"``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 " -"``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 " -"``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 返回 ``EINVAL``。不支持 " -"pidfd、其他种类的命名空间或文件 bind mount。" -msgstr "" -"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNS)`` は、通常の読み取り専用 FD として開いた " -"``/proc//ns/mnt`` のハンドルを受け付けます。呼び出し元に実効 ``CAP_SYS_ADMIN`` と " -"``CAP_SYS_CHROOT`` が必要で、どちらかがなければ ``EPERM`` を返します。無効な FD や ``O_PATH`` FD " -"は ``EBADF`` を返します。未対応の型、nsfs 以外の FD、他のタスクとまだ共有されている ``CLONE_FS`` 状態では " -"``EINVAL`` を返します。pidfd、ほかの種類の名前空間、ファイルの bind mount には対応していません。" +msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 返回 ``EINVAL``。不支持 pidfd、其他种类的命名空间或 nsfs 句柄的 bind mount。" +msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNS)`` は通常の読み取り専用 FD として開いた ``/proc//ns/mnt`` ハンドルを受け付けます。実効 ``CAP_SYS_ADMIN`` と ``CAP_SYS_CHROOT`` が必要で、なければ ``EPERM`` を返します。無効な FD または ``O_PATH`` FD は ``EBADF`` を返します。未対応の型、nsfs 以外の FD、ほかのタスクと共有されている ``CLONE_FS`` 状態では ``EINVAL`` を返します。pidfd、ほかの種類の名前空間、nsfs ハンドルの bind mount には対応していません。" msgid "" "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。参见 " @@ -111,26 +101,14 @@ msgstr "" "はゼロを書き戻し、未対応の namespace ioctl は ``ENOTTY`` を返します。 ``O_PATH`` FD " "ではメタデータを取得できますが、読み書き、シーク、ioctl はできません。" -msgid "目录 bind mount" -msgstr "ディレクトリーの bind mount" +msgid "bind mount" +msgstr "bind mount" -msgid "" -"``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录绑定。 新挂载保留源目录的实际 " -"inode、父链和文件系统生命周期,继承源挂载的 只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 " -"root 字段报告源目录 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 " -"源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" -msgstr "" -"``mount(source, target, NULL, MS_BIND, NULL)`` " -"は非再帰のディレクトリーバインドに対応します。新しいマウントは元ディレクトリーの実際の " -"inode、親チェーン、ファイルシステムのライフサイクルを保持し、元マウントの読み取り専用、nosuid、nodev " -"などの方針を継承します。``/proc/self/mountinfo`` の root " -"フィールドは元ディレクトリーのファイルシステム内のパスを報告し、名前空間のパス、``..``、chroot " -"境界は新マウントを基準に計算します。バインドが残る間は元ファイルシステムの通常のアンマウントはできず、バインド解除で元ファイルシステムを破棄することもありません。" +msgid "``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录与文件绑定。 源和目标必须同为目录或同为非目录,不匹配时返回 ``ENOTDIR``。普通文件、 设备和 FIFO 等非目录对象可以相互作为源或目标。新挂载保留源的实际 inode、 父链和文件系统生命周期,继承源挂载的只读、nosuid、nodev 等策略。 ``/proc/self/mountinfo`` 的 root 字段报告源 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" +msgstr "``mount(source, target, NULL, MS_BIND, NULL)`` はディレクトリーとファイルの非再帰 bind に対応します。ソースとターゲットはともにディレクトリーか、ともに非ディレクトリーである必要があり、不一致の場合は ``ENOTDIR`` を返します。通常ファイル、デバイス、FIFO などの非ディレクトリーは相互に bind できます。新しいマウントはソースの inode、親チェーン、ファイルシステムの寿命を保持し、読み取り専用、nosuid、nodev などのポリシーを継承します。``/proc/self/mountinfo`` の root フィールドはファイルシステム内のソースパスを示します。名前空間パス、``..``、chroot 境界は新しいマウントを基準に計算します。bind が残る間はソースファイルシステムを通常の方法でアンマウントできず、bind の解除ではソースファイルシステムは破棄されません。" -msgid "" -"``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 " -"inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" -msgstr "``MS_BIND | MS_REC`` は元ディレクトリー配下のマウント構造も複製します。複製されたマウントはそれぞれ独立したマウント ID とポリシーを持ち、元の inode とファイルシステムを共有します。元ディレクトリー外のマウントと unbindable のサブツリーは複製されません。準備に失敗しても複製先のツリーと既存のマウントは変化しません。" +msgid "``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑,对非目录源则只绑定该对象。 子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" +msgstr "``MS_BIND | MS_REC`` はソースディレクトリー配下のマウント構造も複製します。ソースが非ディレクトリーの場合はそのオブジェクトだけを bind します。複製先の子マウントは独立したマウント ID とポリシーを持ち、元の inode とファイルシステムを共有します。ソースディレクトリー外のマウントと unbindable サブツリーは複製されません。準備に失敗しても複製先ツリーと既存のマウントは変化しません。" msgid "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` は対象マウントポイントのポリシーだけを変更します。ソース、タイプ、ファイルシステムのオプションは読み取りません。元のマウント、子マウント、共有ファイルシステムは変化しません。atime オプションを省略すると既存のポリシーが維持されます。共有ファイルシステムが読み取り専用である場合、マウントポイントの読み取り専用フラグを解除しても書き込み可能にはなりません。" @@ -138,8 +116,8 @@ msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` msgid "只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。" msgstr "対象マウント上の通常ファイルが書き込み用に開かれている間、読み取り専用への切り替えはポリシーを変更せず EBUSY を返します。dup、fork、ファイルマッピングが同じオープンファイル記述を保持する間もこの制限は続きます。他のマウントの書き込み元や O_PATH だけのハンドルは切り替えを妨げません。" -msgid "文件绑定尚不支持,返回明确错误。" -msgstr "ファイルのバインドにはまだ対応せず、明示的なエラーを返します。" +msgid "文件挂载的目标本身是挂载根,也可独立重新挂载、移动和卸载。移动时源挂载根 与目标必须同为目录或同为非目录,不匹配返回 ``EINVAL``。卸载后目标重新显示 被覆盖的原对象;原 inode、挂载 ID 和访问策略在移动期间保持不变。" +msgstr "ファイルマウントのターゲット自体がマウントルートであり、個別に再マウント、移動、アンマウントできます。移動する場合、ソースのマウントルートとターゲットはともにディレクトリーか、ともに非ディレクトリーである必要があり、不一致では ``EINVAL`` を返します。アンマウント後は覆われていた元のオブジェクトが再び見えます。移動中も元の inode、マウント ID、アクセスポリシーは維持されます。" msgid "按任务选择 uname 系统名" msgstr "タスクごとの uname システム名の選択" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 16a3c7ed..be88eab9 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -59,7 +59,7 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 ``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 -返回 ``EINVAL``。不支持 pidfd、其他种类的命名空间或文件 bind mount。 +返回 ``EINVAL``。不支持 pidfd、其他种类的命名空间或 nsfs 句柄的 bind mount。 切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。参见 :doc:`../core-api/mount-namespaces`。 @@ -71,16 +71,19 @@ nsfs 句柄不是字节流。写入方式或带 ``O_TRUNC`` 的打开返回 ``EP namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。 -目录 bind mount -=============== +bind mount +========== -``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录绑定。 -新挂载保留源目录的实际 inode、父链和文件系统生命周期,继承源挂载的 -只读、nosuid、nodev 等策略。``/proc/self/mountinfo`` 的 root 字段报告源目录 +``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录与文件绑定。 +源和目标必须同为目录或同为非目录,不匹配时返回 ``ENOTDIR``。普通文件、 +设备和 FIFO 等非目录对象可以相互作为源或目标。新挂载保留源的实际 inode、 +父链和文件系统生命周期,继承源挂载的只读、nosuid、nodev 等策略。 +``/proc/self/mountinfo`` 的 root 字段报告源 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。 -``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑。子挂载在目的树中拥有新的 +``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑,对非目录源则只绑定该对象。 +子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。 @@ -93,7 +96,9 @@ unbindable 子树不复制。准备失败时目的树和现有挂载保持原样 dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。 -文件绑定尚不支持,返回明确错误。 +文件挂载的目标本身是挂载根,也可独立重新挂载、移动和卸载。移动时源挂载根 +与目标必须同为目录或同为非目录,不匹配返回 ``EINVAL``。卸载后目标重新显示 +被覆盖的原对象;原 inode、挂载 ID 和访问策略在移动期间保持不变。 statx 挂载标识和根属性 ====================== diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index d3e3830d..1a5962c6 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -384,8 +384,8 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa return 0; } -/** @brief Prepare an unattached directory view of an existing filesystem. - * @param view Valid source directory; supplies the root and attachment policy. +/** @brief Prepare an unattached inode view of an existing filesystem. + * @param view Valid source path; supplies the root and attachment policy. * @param backing Retained path to the same dentry, pinned for this view's lifetime. * @param propagation True for a replica or snapshot backend lifetime reference. * @param out Receives the privately owned clone on success, NULL on failure. @@ -701,7 +701,7 @@ static struct vfs_mount *vfs_bind_child_mount(const struct vfs_path *view,struct enum vfs_mount_copy { VFS_COPY_BIND,VFS_COPY_PEER,VFS_COPY_SLAVE }; -/** @brief Stage one bind tree using previously resolved directory identities. +/** @brief Stage one bind tree using previously resolved path identities. * @param batch Transaction owning all clones, including partial trees on error. * @param source Source view in the live graph or a previously staged tree. * @param target Borrowed retained destination for this tree. @@ -831,10 +831,10 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const stru return rc; } -/** @brief Publish a directory bind and all its downstream copies atomically. +/** @brief Publish a bind and all its downstream copies atomically. * @param ns Borrowed execution-owned namespace. - * @param source Borrowed retained source directory in ns. - * @param target Borrowed retained destination directory in ns. + * @param source Borrowed retained source path in ns. + * @param target Borrowed retained destination path in ns, of compatible type. * @param recursive True to copy the source's bindable descendant branches. * @return Zero or negative errno without consuming IDs or partially publishing. */ @@ -844,7 +844,8 @@ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, if(!ns || !ns->root || !vfs_path_valid(source) || !vfs_path_valid(target))return -EINVAL; if(source->mount->ns!=ns || target->mount->ns!=ns)return -EXDEV; if(source->mount->unbindable)return -EINVAL; - if(source->dentry->node.type!=RELIEFOS_FS_TYPE_DIR || target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; + if((source->dentry->node.type==RELIEFOS_FS_TYPE_DIR)!= + (target->dentry->node.type==RELIEFOS_FS_TYPE_DIR))return -ENOTDIR; if(source->dentry->disconnected || target->dentry->disconnected)return -ENOENT; if(vfs_covering(ns,target))return -EBUSY; @@ -856,9 +857,9 @@ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, return vfs_finish_mount_batch(NULL,&batch,rc); } -/** @brief Publish one directory view without copying submounts. - * @param ns Execution-owned namespace. @param source Retained source directory. - * @param target Retained destination directory. +/** @brief Publish one inode view without copying submounts. + * @param ns Execution-owned namespace. @param source Retained source path. + * @param target Retained destination path of compatible type. * @return Zero or negative errno without partial publication. */ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path *target) @@ -866,9 +867,9 @@ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source,const return vfs_bind_tree(ns,source,target,false); } -/** @brief Publish a directory view with independent copies of its bindable subtrees. +/** @brief Publish an inode view with independent copies of its bindable subtrees. * @param ns Execution-owned namespace. @param source Retained subtree root. - * @param target Retained destination directory. + * @param target Retained destination path of compatible type. * @return Zero or negative errno without partial publication. */ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *source, @@ -880,7 +881,7 @@ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *sou /** @brief Stage and publish a move into a shared parent and all its receivers. * @param ns Borrowed execution-owned namespace. * @param origin Live move root in ns; its old parent must not be shared. - * @param target Retained uncovered directory on a shared mount outside the tree. + * @param target Retained uncovered path on a shared mount outside the tree. * @return Zero or negative errno; no mountpoints, live groups or ID counters * change on failure. The original mounts retain their IDs, policy and pins. */ @@ -910,7 +911,7 @@ static int vfs_move_into_shared(struct vfs_namespace *ns,struct vfs_mount *origi /** @brief Relocate a mount tree intact, propagating it under a shared parent. * @param ns Borrowed execution-owned namespace. * @param source Retained mounted root, excluding the namespace anchor. - * @param target Retained destination directory in ns. + * @param target Retained destination path of compatible type in ns. * @return Zero or negative errno before mutation. Moving out of a shared * parent or moving any unbindable mount into a shared parent is invalid. */ @@ -921,7 +922,8 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const if(mount->ns!=ns || target->mount->ns!=ns)return -EXDEV; if(source->dentry!=mount->root)return -EINVAL; if(mount==ns->root || !mount->point.mount)return -EBUSY; - if(target->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; + if((source->dentry->node.type==RELIEFOS_FS_TYPE_DIR)!= + (target->dentry->node.type==RELIEFOS_FS_TYPE_DIR))return -EINVAL; if(mount->point.mount->peer_group)return -EINVAL; if(target->dentry->disconnected)return -ENOENT; for(struct vfs_mount *ancestor=target->mount;ancestor;ancestor=ancestor->point.mount) diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 82daca84..d9547801 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -618,11 +618,13 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount, * No backend or access policy changes. */ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *path,uint64_t flags); -/** @brief Bind one directory inode into a separate nonrecursive attachment. +/** @brief Bind one inode into a separate nonrecursive attachment. * @param ns Execution-owned namespace containing both retained paths. - * @param source Directory whose actual dentry/backend remain pinned. - * @param target Destination directory, required in the same namespace. - * @return Zero or negative errno without a partial attachment. Inherits + * @param source Path whose actual dentry/backend remain pinned. + * @param target Destination path in the same namespace, matching source's + * directory or non-directory kind. + * @return Zero or negative errno without a partial attachment; ENOTDIR if + * exactly one endpoint is a directory. Inherits * source mount policy; shares inode identities and backend lifetime without * duplicating provider destruction. Inherits the source's peer and master * groups, and propagates across eligible graphs under a shared destination. @@ -630,11 +632,12 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa */ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); -/** @brief Bind a directory and its bindable subtrees in one transaction. +/** @brief Bind an inode and its bindable subtrees in one transaction. * @param ns Execution-owned namespace containing both retained paths. - * @param source Directory that bounds the original mount subtree. - * @param target Uncovered destination directory in the same namespace. - * @return Zero or negative errno without publishing a partial tree. Each clone + * @param source Path that bounds the original mount subtree. + * @param target Uncovered destination path of compatible type in the same namespace. + * @return Zero or negative errno without publishing a partial tree; ENOTDIR + * if exactly one endpoint is a directory. Each clone * has an independent ID and mount policy but pins the original backing objects. * Eligible destination peers and slaves, even in another namespace, each * receive a bindable tree. @@ -645,8 +648,9 @@ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *sou /** @brief Atomically move an attached subtree, preserving held paths and IDs. * @param ns Namespace under execution ownership. * @param source Held root of an attached mount, never the namespace base root. - * @param target Held destination directory path in the same namespace. - * @return Zero or negative errno without partial moves or replicas. Moving + * @param target Held destination path of compatible type in the same namespace. + * @return Zero or negative errno without partial moves or replicas. Incompatible + * directory and non-directory kinds return EINVAL. Moving * out of a shared parent, or moving an unbindable branch into one, gives * EINVAL. A shared destination publishes peer and slave copies of the tree * across eligible graphs. The original subtree moves intact; allocations diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 5df5259a..8dd6343b 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -25,7 +25,7 @@ static int mount_move(struct vfs_namespace *ns,struct task *task,uint64_t source vfs_path_put(&from.path);vfs_path_put(&to.path);return rc; } -/** @brief Resolve and retain both endpoints of a directory bind. +/** @brief Resolve and retain both endpoints of a file or directory bind. * @param ns Authorized caller's execution-owned namespace. * @param task Caller with retry-stable user lookup operands. * @param source Required user source path. @param target Required user target. diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 4219033e..e9a184ad 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2965,6 +2965,93 @@ static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pat puts("PASS actual mount/remount/MS_MOVE/umount syscalls: scoped objects, capability, busy refs, atime preservation, ignored remount source/type and nofollow"); } +/** @brief Exercise file bind mounts through the actual mount syscall path. + * @param ns Borrowed test namespace. @param root Held namespace root. + * @param fs Base tmpfs used for source and destination objects. + */ +static void runtime_file_bind(struct vfs_namespace *ns,const struct vfs_path *root, + struct tmpfs_super *fs) +{ + struct { + char source[32],target[32],moved[32],directory[32],other_directory[32],fifo[32]; + } user={"/file-bind-source","/file-bind-target","/file-bind-moved", + "/file-bind-directory","/file-bind-other-directory","/file-bind-fifo"}; + assert(!tmpfs_create(fs,user.source,LINUX_S_IFREG|0644,NULL,NULL)); + assert(!tmpfs_create(fs,user.target,LINUX_S_IFREG|0644,NULL,NULL)); + assert(!tmpfs_create(fs,user.moved,LINUX_S_IFREG|0644,NULL,NULL)); + assert(!tmpfs_create(fs,user.directory,LINUX_S_IFDIR|0755,NULL,NULL)); + assert(!tmpfs_create(fs,user.other_directory,LINUX_S_IFDIR|0755,NULL,NULL)); + assert(!tmpfs_create(fs,user.fifo,LINUX_S_IFIFO|0644,NULL,NULL)); + struct task actor={.pid=906,.fsuid=1000,.fsgid=1000,.cap_effective=1ULL<nofile.rlim_cur=32; + vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + uint64_t source=(uintptr_t)user.source,target=(uintptr_t)user.target; + uint64_t moved=(uintptr_t)user.moved,directory=(uintptr_t)user.directory; + uint64_t other_directory=(uintptr_t)user.other_directory,fifo=(uintptr_t)user.fifo; + struct vfs_path original={0},covered={0},destination={0},bound={0},found={0}; + assert(!vfs_path_lookup(ns,root,root,user.source,0,&original)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&covered)); + assert(!vfs_path_lookup(ns,root,root,user.moved,0,&destination)); + uint32_t count=0; + assert(!vfs_path_write(&original,0,"source",6,&count) && count==6); + + for(unsigned recursive=0;recursive<2;++recursive) { + uint64_t flags=MS_BIND|(recursive ? MS_REC : 0); + uint64_t next_id=vfs_mount_next_id(); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,source,directory,0,flags,0)==-ENOTDIR); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,directory,target,0,flags,0)==-ENOTDIR); + assert(vfs_mount_next_id()==next_id); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,source,target,0,flags,0)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&bound)); + assert(vfs_path_is_mount_root(&bound) && vfs_path_same_inode(&bound,&original)); + assert(!vfs_path_same_inode(&bound,&covered)); + assert(vfs_path_mount_id(&bound)!=vfs_path_mount_id(&original)); + char bytes[8]={0}; + assert(!vfs_path_read(&bound,0,bytes,sizeof(bytes),&count) && count==6 && !memcmp(bytes,"source",6)); + char table[4096]; + assert(!vfs_read_mount_table(ns,root,true,0,table,sizeof(table)-1,&count));table[count]=0; + assert(strstr(table," /file-bind-source /file-bind-target ")); + + struct vfs_namespace snapshot={0};struct vfs_path snapshot_root={0},snapshot_file={0}; + assert(!vfs_namespace_snapshot(&snapshot,ns,NULL,NULL)); + assert(!vfs_namespace_root(&snapshot,&snapshot_root)); + assert(!vfs_path_lookup(&snapshot,&snapshot_root,&snapshot_root,user.target,0,&snapshot_file)); + assert(vfs_path_is_mount_root(&snapshot_file) && vfs_path_same_inode(&snapshot_file,&original)); + vfs_path_put(&snapshot_file);vfs_path_put(&snapshot_root); + assert(!vfs_namespace_destroy(&snapshot)); + + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,0,target,0,MS_BIND|MS_REMOUNT|MS_RDONLY,0)); + assert(vfs_path_mount_flags(&bound)&MS_RDONLY); + assert(syscall_open_object(ns,&actor,LINUX_AT_FDCWD,target,LINUX_O_WRONLY,0)==-EROFS); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,target,directory,0,MS_MOVE,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,target,moved,0,MS_MOVE,0)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&found)); + assert(vfs_path_equal(&found,&covered));vfs_path_put(&found); + assert(!vfs_path_lookup(ns,root,root,user.moved,0,&found)); + assert(vfs_path_equal(&found,&bound));vfs_path_put(&found);vfs_path_put(&bound); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,moved,0,0,0,0)); + assert(!vfs_path_lookup(ns,root,root,user.moved,0,&found)); + assert(vfs_path_equal(&found,&destination));vfs_path_put(&found); + } + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,source,fifo,0,MS_BIND,0)); + assert(!vfs_path_lookup(ns,root,root,user.fifo,0,&bound)); + assert(vfs_path_same_inode(&bound,&original));vfs_path_put(&bound); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,fifo,0,0,0,0)); + assert(!vfs_path_lookup(ns,root,root,user.fifo,0,&found)); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,fifo,target,0,MS_BIND,0)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&bound)); + assert(vfs_path_same_inode(&bound,&found));vfs_path_put(&bound);vfs_path_put(&found); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,target,0,0,0,0)); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,directory,other_directory,0,MS_BIND,0)); + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,other_directory,target,0,MS_MOVE,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,other_directory,0,0,0,0)); + vfs_path_put(&original);vfs_path_put(&covered);vfs_path_put(&destination); + vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + lookup_user_base=lookup_user_bytes=0; + puts("PASS file bind: recursive and ordinary, type checks, identity, mountinfo, snapshot, remount, move and unmount"); +} + /** @brief Check root-scoped propagation changes and unbindable bind pruning. * @param ns Borrowed test namespace. @param root Retained namespace root. * @param actor Privileged task with the fixture paths. @@ -3228,6 +3315,34 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(fixture_shared_id(ns,root,"/shared-b")==group && fixture_shared_id(ns,root,"/shared-narrow")==group); struct vfs_path a={0},b={0},point={0},found={0};struct vfs_mount *mount=NULL; + struct reliefos_permissions file_mode={0644,1000,1000}; + assert(!vfs_path_lookup(ns,root,root,"/shared-a/p",0,&point)); + assert(!vfs_path_create_node(&point,"file-source",LINUX_S_IFREG,&file_mode,NULL,&a)); + assert(!vfs_path_create_node(&point,"file-target",LINUX_S_IFREG,&file_mode,NULL,NULL)); + vfs_path_put(&point); + struct vfs_namespace snapshot={0};struct vfs_path snapshot_root={0}; + assert(!vfs_namespace_snapshot(&snapshot,ns,NULL,NULL)); + assert(!vfs_namespace_root(&snapshot,&snapshot_root)); + strcpy(user.source,"/shared-a/p/file-source");strcpy(user.target,"/shared-a/p/file-target"); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_BIND|MS_REC,0)); + const char *file_peers[]={"/shared-a/p/file-target","/shared-b/p/file-target","/shared-narrow/file-target"}; + for(unsigned i=0;i Date: Sun, 29 Nov 2026 12:39:30 +0800 Subject: [PATCH 23/97] feat(proc): notify mount view changes --- .../LC_MESSAGES/userspace-api/descriptors.po | 25 ++++++ .../LC_MESSAGES/userspace-api/descriptors.po | 22 ++++++ Documentation/userspace-api/descriptors.rst | 9 +++ fs/proc/internal.h | 9 +++ fs/proc/mount.c | 3 +- fs/proc/procfs.c | 27 ++++++- fs/vfs/file.c | 9 ++- fs/vfs/mount_internal.h | 6 ++ fs/vfs/mount_tree.c | 27 ++++++- fs/vfs/open.c | 21 +++++ fs/vfs/pseudo.c | 19 +++++ include/reliefnt/mount.h | 16 ++++ include/reliefnt/pseudo_fs.h | 2 + kernel/syscall/event/epoll.c | 15 +++- kernel/syscall/event/poll.c | 18 ++++- kernel/syscall/internal.h | 17 +++- tools/tests/epoll_capacity_test.c | 79 ++++++++++++++++++- tools/tests/mount_backend_test.c | 8 ++ tools/tests/procfs_directories_test.c | 54 +++++++++++++ tools/tests/select_bitmap_test.c | 38 +++++++++ tools/tests/task8_epoll_user_test.c | 34 +++++++- 21 files changed, 439 insertions(+), 19 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index 731e5b53..3995fd9b 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -309,6 +309,31 @@ msgstr "" "parentage. Device major/minor encoding agrees with ``stat.st_dev`` within" " the same mount." +msgid "" +"``/proc//mounts`` 与 ``/proc//mountinfo`` 在打开时捕获目标 " +"进程的挂载命名空间。命名空间中成功的挂载、移动、卸载、重新挂载及传播 " +"变化会使 ``poll`` 报告 ``POLLPRI`` 和 ``POLLERR``,并使 ``epoll`` 报告 " +"对应事件。传播到其他命名空间的变更也通知相应视图;失败的操作不产生通知。" +msgstr "" +"Opening ``/proc//mounts`` or ``/proc//mountinfo`` captures the " +"target process's mount namespace. Successful mounts, moves, unmounts, " +"remounts, and propagation changes in that namespace make ``poll`` report " +"``POLLPRI`` and ``POLLERR`` and ``epoll`` report the corresponding events. " +"Changes propagated to other namespaces also notify their views. Failed " +"operations do not generate notifications." + +msgid "" +"独立打开具有各自的通知状态,``dup`` 共享同一打开文件描述。读取挂载表不会 " +"确认通知,成功的就绪查询会确认观察到的变化。嵌套 epoll 的外层就绪查询不会 " +"提前确认内层事件;内层事件写入用户缓冲区后才确认。" +msgstr "" +"Independent opens have separate notification state, while ``dup`` shares " +"the same open file description. Reading the mount table does not " +"acknowledge notifications. A successful readiness query acknowledges the " +"observed changes. Readiness queries on an outer epoll do not prematurely " +"acknowledge inner events. Inner events are acknowledged after they are " +"written to the user buffer." + msgid "" "初始根挂载与 ``mount(2)`` 的默认访问时间策略一致:未显式选择策略时采用 ``relatime``。这包括直接挂载的物理根、安装器与 " "live 的内存块根,以及 早期用户态的初始 tmpfs 根。明确指定 ``MS_NOATIME`` 或 ``MS_STRICTATIME`` " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index 75cbce78..eaba945d 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -265,6 +265,28 @@ msgstr "" " ID の大小から親子関係を推定してはなりません。デバイスの major/minor は同じマウント内の ``stat.st_dev`` " "と一致する符号化を使います。" +msgid "" +"``/proc//mounts`` 与 ``/proc//mountinfo`` 在打开时捕获目标 " +"进程的挂载命名空间。命名空间中成功的挂载、移动、卸载、重新挂载及传播 " +"变化会使 ``poll`` 报告 ``POLLPRI`` 和 ``POLLERR``,并使 ``epoll`` 报告 " +"对应事件。传播到其他命名空间的变更也通知相应视图;失败的操作不产生通知。" +msgstr "" +"``/proc//mounts`` または ``/proc//mountinfo`` を開くと、対象プロセスの" +"マウント名前空間を捕捉します。その名前空間でマウント、移動、アンマウント、再マウント、" +"伝播の変更に成功すると、``poll`` は ``POLLPRI`` と ``POLLERR`` を、``epoll`` は" +"対応するイベントを報告します。他の名前空間へ伝播した変更も、そのビューへ通知します。" +"失敗した操作は通知を生成しません。" + +msgid "" +"独立打开具有各自的通知状态,``dup`` 共享同一打开文件描述。读取挂载表不会 " +"确认通知,成功的就绪查询会确认观察到的变化。嵌套 epoll 的外层就绪查询不会 " +"提前确认内层事件;内层事件写入用户缓冲区后才确认。" +msgstr "" +"独立して開いたファイルはそれぞれ通知状態を持ち、``dup`` は同じオープンファイル記述を" +"共有します。マウント表の読み取りは通知を確認せず、成功した準備状態の問い合わせが" +"観測した変更を確認します。ネストした epoll の外側の準備状態問い合わせは内側のイベントを" +"先に確認しません。内側のイベントはユーザーバッファーに書き込まれた後に確認されます。" + msgid "" "初始根挂载与 ``mount(2)`` 的默认访问时间策略一致:未显式选择策略时采用 ``relatime``。这包括直接挂载的物理根、安装器与 " "live 的内存块根,以及 早期用户态的初始 tmpfs 根。明确指定 ``MS_NOATIME`` 或 ``MS_STRICTATIME`` " diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index 8a1e423c..24fa71a0 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -132,6 +132,15 @@ TCP 的 ``setsockopt/getsockopt(SOL_TCP, TCP_NODELAY)`` 接受原生整数标志 到较新挂载之下时也保持此顺序,不能以 mount ID 的大小推断父子关系。 设备 major/minor 与同一挂载内 ``stat.st_dev`` 的编码一致。 +``/proc//mounts`` 与 ``/proc//mountinfo`` 在打开时捕获目标 +进程的挂载命名空间。命名空间中成功的挂载、移动、卸载、重新挂载及传播 +变化会使 ``poll`` 报告 ``POLLPRI`` 和 ``POLLERR``,并使 ``epoll`` 报告 +对应事件。传播到其他命名空间的变更也通知相应视图;失败的操作不产生通知。 + +独立打开具有各自的通知状态,``dup`` 共享同一打开文件描述。读取挂载表不会 +确认通知,成功的就绪查询会确认观察到的变化。嵌套 epoll 的外层就绪查询不会 +提前确认内层事件;内层事件写入用户缓冲区后才确认。 + 初始根挂载与 ``mount(2)`` 的默认访问时间策略一致:未显式选择策略时采用 ``relatime``。这包括直接挂载的物理根、安装器与 live 的内存块根,以及 早期用户态的初始 tmpfs 根。明确指定 ``MS_NOATIME`` 或 ``MS_STRICTATIME`` diff --git a/fs/proc/internal.h b/fs/proc/internal.h index 89f49f22..6862ce85 100644 --- a/fs/proc/internal.h +++ b/fs/proc/internal.h @@ -130,6 +130,15 @@ int proc_file_open(const char *name,uint32_t flags,void **out); * @return Renderer status or negative errno; ownership is unchanged. * Execution-owned context; no graph/module lock spans renderer callbacks. */ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read); +/** @brief Poll a captured mount view without retargeting its namespace. + * @param value Borrowed open capture. @param events Requested poll bits. + * @param consume Acknowledge a pending graph change when true. + * @param generation Optional current namespace generation output. + * @param ready Required filtered readiness output. + * @return True for a mount view, false for other generated files. + * Execution ownership serializes observation with mount transactions. + */ +bool proc_file_poll(void *value,short events,bool consume,uint64_t *generation,short *ready); /** @brief Consume an open capture and release its root or diagnostic data. * @param value Owned optional capture; NULL is ignored. * @return None. Execution-owned final close, no graph/scheduler/module lock diff --git a/fs/proc/mount.c b/fs/proc/mount.c index 6c7203a0..0f855258 100644 --- a/fs/proc/mount.c +++ b/fs/proc/mount.c @@ -29,6 +29,7 @@ int proc_create_vfs_mount(struct vfs_mount **out) .get_identity=proc_key_identity,.identity_alive=proc_key_alive,.put_identity=proc_key_put, .follow=proc_mount_magic_target,.stat_link=proc_mount_magic_stat, .permissions=proc_control_permissions,.getattr=proc_getattr, - .open=proc_file_open,.read_open=proc_file_read,.close=proc_file_close}; + .open=proc_file_open,.read_open=proc_file_read,.close=proc_file_close, + .poll_open=proc_file_poll}; return vfs_pseudo_mount_new(&provider,out); } diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 1a7ac03b..3846a5ab 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -24,6 +24,7 @@ #include #include #include +#include #include "internal.h" #include @@ -431,6 +432,7 @@ static int proc_mount_view(const char *path,struct task **target) struct proc_open_view { struct vfs_namespace *ns; struct vfs_path root; bool mountinfo; + uint64_t mount_generation; void *memory; const char *inotify_control; bool score_valid; int score; @@ -535,7 +537,8 @@ int proc_file_open(const char *name,uint32_t flags,void **out) const struct task_fs_paths *paths=sched_task_paths(task); if(!paths->ns || !vfs_path_node(&paths->root))return -RELIEFOS_ENOENT; struct proc_open_view *state=kernel_malloc(sizeof(*state));if(!state)return -RELIEFOS_ENOMEM; - *state=(struct proc_open_view){.ns=vfs_namespace_get(paths->ns),.mountinfo=view==2}; + *state=(struct proc_open_view){.ns=vfs_namespace_get(paths->ns),.mountinfo=view==2, + .mount_generation=paths->ns->mount_generation}; vfs_path_get(&paths->root,&state->root);*out=state;return 0; } @@ -584,6 +587,28 @@ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,ui return vfs_read_mount_table(state->ns,&state->root,state->mountinfo,offset,buffer,capacity,read); } +/** @brief Report mount graph readiness for one captured open description. + * @param value Borrowed capture, including non-mount generated files. + * @param events Requested poll bits. @param consume Acknowledge graph changes. + * @param generation Optional output for the current graph generation. + * @param ready Required output with filtered readiness and unconditional errors. + * @return True for mount views; false asks VFS for ordinary readiness. + * Each dup shares this capture. Reads leave its pending notification intact. + */ +bool proc_file_poll(void *value,short events,bool consume,uint64_t *generation,short *ready) +{ + struct proc_open_view *state=value; + if(!state || !state->ns)return false; + uint64_t current=state->ns->mount_generation; + if(generation)*generation=current; + *ready=events&(POLLIN|POLLRDNORM); + if(state->mount_generation!=current) { + *ready|=POLLERR|(events&POLLPRI); + if(consume)state->mount_generation=current; + } + return true; +} + /** @brief Release an open view after the final shared OFD reference. * @param value Owned optional captured state; NULL is ignored. * Drops the retained viewing root and graph, even if the target already exited. diff --git a/fs/vfs/file.c b/fs/vfs/file.c index f80cefcb..a53f3414 100644 --- a/fs/vfs/file.c +++ b/fs/vfs/file.c @@ -160,7 +160,9 @@ int vfs_path_bind_remount(const struct vfs_path *path,uint64_t flags) else flags|=MS_RELATIME; uint64_t policy=vfs_policy_bits(flags); if(mount->writers && (policy&MS_RDONLY) && !(vfs_path_mount_flags(path)&MS_RDONLY))return -EBUSY; - mount->policy=policy;return 0; + mount->policy=policy; + vfs_namespace_changed(mount->ns); + return 0; } /** @brief Reconfigure the selected attachment after shared backend preparation. @@ -185,7 +187,10 @@ static int vfs_remount(const struct vfs_path *path,uint64_t flags,const char *op else if(options && options[0])rc=-EOPNOTSUPP; else if(mount->ops->remount)rc=mount->ops->remount(mount->context,shared); else if(shared!=vfs_super_flags(mount))rc=(vfs_super_flags(mount)&MS_RDONLY) && !(shared&MS_RDONLY) ? -EROFS : -EOPNOTSUPP; - if(!rc)mount->policy=policy; + if(!rc) { + mount->policy=policy; + vfs_namespace_changed(mount->ns); + } return rc; } diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 284cdc87..c0f2f6e3 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -10,6 +10,12 @@ struct vfs_lookup_cache_entry; +/** @brief Publish one committed change to a live mount graph. + * @param ns Borrowed graph under execution ownership, NULL is ignored. + * Advances its mount-view generation and wakes poll waiters without allocation. + */ +void vfs_namespace_changed(struct vfs_namespace *ns); + struct vfs_dentry { struct vfs_dentry *parent,*children,*next,*notify_next; struct vfs_dentry **notify_link; diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index 1a5962c6..3d1f6251 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -2,6 +2,21 @@ #include "mount_internal.h" #include #include +#include + +/* Standalone VFS fixtures can omit the scheduler's poll wait queue. */ +extern void kernel_poll_readiness_notify(void) __attribute__((weak)); + +/** @brief Publish a committed graph change to its captured proc views. + * @param ns Borrowed live namespace, NULL is ignored. + * Execution ownership serializes the generation with every observer. + */ +void vfs_namespace_changed(struct vfs_namespace *ns) +{ + if(!ns)return; + ++ns->mount_generation; + if(kernel_poll_readiness_notify)kernel_poll_readiness_notify(); +} /* Detached mounts reuse next only after losing namespace membership. The * private queue retains context/ops/module lifetime without any public path. */ @@ -333,6 +348,7 @@ static struct vfs_mount *vfs_leave_peer_group(struct vfs_mount *mount) next=other->propagation_next; if(other->master!=mount)continue; other->master=upstream;vfs_update_propagation(other); + vfs_namespace_changed(other->ns); } mount->peer_group=0; return upstream; @@ -381,6 +397,7 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa } vfs_update_propagation(mount); } + vfs_namespace_changed(ns); return 0; } @@ -476,6 +493,7 @@ static int vfs_finish_mount_batch(struct vfs_namespace *snapshot,struct vfs_moun mount->staged_cover=NULL; } if(!mount->notify_link && vfs_notify_mount_created)vfs_notify_mount_created(mount); + vfs_namespace_changed(ns); } next_mount_id=batch->next_id;next_peer_id=batch->next_peer_id; return 0; @@ -905,7 +923,9 @@ static int vfs_move_into_shared(struct vfs_namespace *ns,struct vfs_mount *origi mount->staged_peer_group=0; } if(!rc)vfs_replace_mountpoint(origin,target); - return vfs_finish_mount_batch(NULL,&batch,rc); + rc=vfs_finish_mount_batch(NULL,&batch,rc); + if(!rc)vfs_namespace_changed(ns); + return rc; } /** @brief Relocate a mount tree intact, propagating it under a shared parent. @@ -931,7 +951,9 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const if(backing==mount)return -ELOOP; if(vfs_covering(ns,target))return -EBUSY; if(target->mount->peer_group)return vfs_move_into_shared(ns,mount,target); - vfs_replace_mountpoint(mount,target);return 0; + vfs_replace_mountpoint(mount,target); + vfs_namespace_changed(ns); + return 0; } /** @brief Clear a departing mount's membership and repair weak upstream edges. @@ -1099,6 +1121,7 @@ static void vfs_finish_unmounts(struct vfs_mount *pending,int status,bool lazy) struct vfs_mount *mount=pending;pending=mount->unmount_next;mount->unmount_next=NULL; bool selected=mount->unmount_selected;mount->unmount_selected=false; if(status || !selected)continue; + vfs_namespace_changed(mount->ns); vfs_unlink_mount(mount); mount->lazy_detached=lazy;mount->next=detached;detached=mount; } diff --git a/fs/vfs/open.c b/fs/vfs/open.c index 8573b4d5..86b0f2b0 100644 --- a/fs/vfs/open.c +++ b/fs/vfs/open.c @@ -50,6 +50,27 @@ int vfs_file_read(struct vfs_open_file *file,uint64_t offset,void *buffer,uint32 return rc; } +/** @brief Query a retained provider's optional OFD readiness. + * @param file Borrowed capture or NULL. @param events Requested poll bits. + * @param consume Acknowledge pending events after the query when true. + * @param generation Optional provider input generation output. + * @param ready Required filtered readiness output. + * @return True when handled; false preserves the regular-file fallback. + * Runs under execution ownership, with no graph lock across the callback. + */ +bool vfs_file_poll(struct vfs_open_file *file,short events,bool consume, + uint64_t *generation,short *ready) +{ + if(generation)*generation=0; + if(!ready)return false; + *ready=0; + if(!file)return false; + const struct vfs_path *path=&file->path; + if(!path->mount->ops->file_poll)return false; + return path->mount->ops->file_poll(path->mount->context,&path->dentry->node, + file->state,events,consume,generation,ready); +} + /** @brief Retire private open state before releasing its provider path/code. * @param file Owned optional handle; NULL does nothing. Caller clears its * stored pointer before entry so nested cleanup cannot release it twice. diff --git a/fs/vfs/pseudo.c b/fs/vfs/pseudo.c index ce84e04e..a62e53f3 100644 --- a/fs/vfs/pseudo.c +++ b/fs/vfs/pseudo.c @@ -201,6 +201,24 @@ static int pseudo_file_read(void *value,const struct storage_node *node,void *st return context->provider->read_open(state,offset,buffer,capacity,read); } +/** @brief Query readiness through an independently retained open capture. + * @param value Borrowed pseudo mount context. @param node Retained inode key. + * @param state Borrowed successful capture. @param events Requested poll bits. + * @param consume Acknowledge provider changes when true. + * @param generation Optional input-generation output. + * @param ready Required filtered poll output. + * @return True when the provider handles the query, otherwise false. + * Execution ownership preserves the capture and provider through the call. + */ +static bool pseudo_file_poll(void *value,const struct storage_node *node,void *state, + short events,bool consume,uint64_t *generation,short *ready) +{ + (void)node; + struct pseudo_mount *context=value; + return context->provider->poll_open && + context->provider->poll_open(state,events,consume,generation,ready); +} + /** @brief Consume captured generated-file state before its provider retires. * @param value Pinned pseudo provider context, borrowed. * @param node Intrinsic inode kept alive by the handle, borrowed. @@ -330,6 +348,7 @@ int vfs_pseudo_mount_new(const struct vfs_pseudo_provider *provider,struct vfs_m .read=pseudo_node_read,.write=pseudo_node_write,.truncate=pseudo_node_truncate, .readdir=pseudo_node_readdir,.permissions=pseudo_node_permissions, .file_open=pseudo_file_open,.file_read=pseudo_file_read,.file_close=pseudo_file_close, + .file_poll=pseudo_file_poll, .mount_flags=pseudo_mount_flags,.remount=pseudo_remount,.getattr=pseudo_node_getattr,.statfs=pseudo_node_statfs}; struct pseudo_mount *context=kernel_malloc(sizeof(*context));int rc=-ENOMEM; if(context) { diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index d9547801..078e0c2c 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -45,6 +45,17 @@ int vfs_file_read(struct vfs_open_file *file,uint64_t offset,void *buffer,uint32 * Execution ownership required; no graph/module lock spans provider cleanup. */ void vfs_file_close(struct vfs_open_file *file); +/** @brief Query optional per-open readiness without changing its ownership. + * @param file Borrowed captured handle, nullable for ordinary files. + * @param events Requested poll bits; error and hangup remain unconditional. + * @param consume True to acknowledge pending provider changes. + * @param generation Optional output identifying visible input progress. + * @param ready Required output receiving the filtered poll bits. + * @return True if the provider handles polling, false for ordinary fallback. + * Execution ownership serializes the state with changes and OFD cleanup. + */ +bool vfs_file_poll(struct vfs_open_file *file,short events,bool consume, + uint64_t *generation,short *ready); /* Native namespace objects. Callers serialize the graph with the reentrant * kernel execution transaction. No mount-registry spinlock spans backend I/O. @@ -123,6 +134,10 @@ struct vfs_backend_ops { int (*file_read)(void *context,const struct storage_node *node,void *state, uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read,uint64_t mount_flags); void (*file_close)(void *context,const struct storage_node *node,void *state); + /* Optional readiness and generation for a captured OFD. Probes with + * consume=false must preserve pending events for nested epoll watches. */ + bool (*file_poll)(void *context,const struct storage_node *node,void *state, + short events,bool consume,uint64_t *generation,short *ready); int (*readdir)(void *context,const struct storage_node *node,uint64_t *cursor, struct reliefos_dir_entry *entry,uint64_t mount_flags); /* The held parent/name is available for filesystems whose persistent @@ -199,6 +214,7 @@ struct vfs_namespace *vfs_path_namespace(const struct vfs_path *path); struct vfs_namespace { struct vfs_mount *root,*mounts; uint64_t references; + uint64_t mount_generation; /* Successful visible mount graph changes. */ /* Only managed snapshots have a finalizer; boot/fixture storage is external. */ void (*release)(struct vfs_namespace *ns); }; diff --git a/include/reliefnt/pseudo_fs.h b/include/reliefnt/pseudo_fs.h index faea13b9..3f8d13fd 100644 --- a/include/reliefnt/pseudo_fs.h +++ b/include/reliefnt/pseudo_fs.h @@ -39,6 +39,8 @@ struct vfs_pseudo_provider { int (*open)(const char *intrinsic,uint32_t flags,void **state); int (*read_open)(void *state,uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read); void (*close)(void *state); + /* Optional per-open poll state, valid after the inode identity retires. */ + bool (*poll_open)(void *state,short events,bool consume,uint64_t *generation,short *ready); /* Optional provider-specific attributes after generic metadata is filled. * The intrinsic key and its identity remain valid during the call. */ void (*getattr)(const char *name,struct linux_stat_abi *out); diff --git a/kernel/syscall/event/epoll.c b/kernel/syscall/event/epoll.c index 7a2d97f1..7e134257 100644 --- a/kernel/syscall/event/epoll.c +++ b/kernel/syscall/event/epoll.c @@ -4,12 +4,16 @@ /** * @brief Snapshot input progress for providers with edge-triggered readiness. * @param file Pinned watched description, or NULL for a PTY watch. - * @return Visible evdev sequence or the socket's existing receive generation. + * @return Provider, visible evdev or socket receive generation. * Execution-owned context. Evdev filtering matches read/poll and does not * expose other VTs, devices or exclusive grabs. No UAPI state is modified. */ static uint64_t epoll_event_generation(const struct task_file *file) { + uint64_t generation; + short ready; + if (file && vfs_file_poll(file->provider_file, 0, false, &generation, &ready)) + return generation; if (file && (file->flags & TASK_FILE_FLAG_DEV_NODE) && (file->node.first_cluster == STORAGE_DEV_KIND_MOUSE || file->node.first_cluster == STORAGE_DEV_KIND_KEYBOARD)) @@ -343,7 +347,7 @@ bool task_epoll_poll_ready(struct task *task, struct task_file *file) task->syscall_fd = entry->fd; task->syscall_file = watch->file; task->syscall_pty = watch->pty ? watch->pty_alias : (struct task_pty_fd){0}; - (void)syscall_poll_impl(task, &pollfd, 1, 0, poll_generation); + (void)syscall_poll_probe(task, &pollfd, 1, 0, poll_generation); task->syscall_file = saved_file; task->syscall_pty = saved_pty; task->syscall_fd = saved_fd; @@ -593,7 +597,7 @@ static int64_t syscall_epoll_wait_common(struct task *task, struct task_epoll *e task->syscall_fd = entry->fd; task->syscall_file = entry->watch ? entry->watch->file : NULL; task->syscall_pty = entry->watch ? entry->watch->pty_alias : (struct task_pty_fd){0}; - (void)syscall_poll_impl(task, &pollfd, 1, 0, poll_generation); + (void)syscall_poll_probe(task, &pollfd, 1, 0, poll_generation); task->syscall_file = saved_file; task->syscall_pty = saved_pty; task->syscall_fd = saved_fd; @@ -638,6 +642,11 @@ static int64_t syscall_epoll_wait_common(struct task *task, struct task_epoll *e } ((struct epoll_event *)(uintptr_t)events_ptr)[written++] = (struct epoll_event){.events = ready, .data = entry->data}; + if (entry->watch && entry->watch->file) { + short acknowledged; + (void)vfs_file_poll(entry->watch->file->provider_file, pollfd.events, + true, NULL, &acknowledged); + } if (entry->events & EPOLLET) { entry->ready = observed_ready; entry->generation = generation; diff --git a/kernel/syscall/event/poll.c b/kernel/syscall/event/poll.c index 4c8e4ee5..9d860e48 100644 --- a/kernel/syscall/event/poll.c +++ b/kernel/syscall/event/poll.c @@ -47,11 +47,13 @@ int64_t syscall_poll_park(struct task *task, int64_t timeout_ms, * @param nfds Number of entries. * @param timeout_ms Linux poll timeout, narrowed to signed 32 bits. * @param generation Readiness generation captured before scanning descriptors. + * @param consume Acknowledge provider events when true. + * @param scanned Optional output indicating whether the array was scanned. * @return Ready count, zero on timeout, negative errno or a blocked retry token. */ static int64_t syscall_poll_impl_core(struct task *task, struct pollfd *fds, uint32_t nfds, int64_t timeout_ms, - uint64_t generation, bool *scanned) + uint64_t generation, bool consume, bool *scanned) { uint64_t ready = 0; if (scanned) *scanned = false; @@ -115,6 +117,9 @@ static int64_t syscall_poll_impl_core(struct task *task, struct pollfd *fds, task_timerfd_update(timer); if ((events & (POLLIN | POLLRDNORM)) && timer && timer->expirations) revents |= POLLIN | POLLRDNORM; + } else if (file && vfs_file_poll(file->provider_file, events, consume, + NULL, &revents)) { + /* Captured providers supply their own readiness and error bits. */ } else if (file && file->character_file) { revents=character_file_poll(file->character_file,file,events); } else if (file && (file->flags & TASK_FILE_FLAG_DEV_NODE)) { @@ -197,7 +202,14 @@ int64_t syscall_poll_impl(struct task *task, struct pollfd *fds, uint32_t nfds, int64_t timeout_ms, uint64_t generation) { - return syscall_poll_impl_core(task, fds, nfds, timeout_ms, generation, NULL); + return syscall_poll_impl_core(task, fds, nfds, timeout_ms, generation, true, NULL); +} + +int64_t syscall_poll_probe(struct task *task, struct pollfd *fds, + uint32_t nfds, int64_t timeout_ms, + uint64_t generation) +{ + return syscall_poll_impl_core(task, fds, nfds, timeout_ms, generation, false, NULL); } #ifdef CONFIG_SWAP @@ -258,7 +270,7 @@ static int64_t syscall_poll_staged(struct task *task, uint64_t address, if (!state->finished) { uint64_t generation = kernel_poll_readiness_generation(); result = syscall_poll_impl_core(task, state->entries, count, timeout_ms, - generation, &state->scanned); + generation, true, &state->scanned); if (result < 0) goto poll_out; state->result = result; state->finished = true; diff --git a/kernel/syscall/internal.h b/kernel/syscall/internal.h index 5029d446..a779eeb5 100644 --- a/kernel/syscall/internal.h +++ b/kernel/syscall/internal.h @@ -1515,13 +1515,26 @@ int64_t syscall_poll_impl(struct task *task, struct pollfd *fds, uint32_t nfds, int64_t timeout_ms, uint64_t generation); +/** + * @brief Probe descriptor readiness without acknowledging provider events. + * @param task Calling task under the execution transaction. + * @param fds Validated in/out poll array; nullable when nfds is zero. + * @param nfds Number of entries. + * @param timeout_ms Linux poll timeout, narrowed to signed 32 bits. + * @param generation Readiness generation captured before scanning descriptors. + * @return Ready count, zero on timeout, negative errno or a blocked retry token. + */ +int64_t syscall_poll_probe(struct task *task, struct pollfd *fds, + uint32_t nfds, int64_t timeout_ms, + uint64_t generation); + /** * @brief Test an epoll OFD for eligible events without consuming its state. * @param task Calling task used for the underlying readiness probes. * @param file Epoll open-file description to inspect. * @return True when an armed registration is ready, otherwise false. - * @note Nested epoll registrations are unsupported; this reports only direct - * target readiness and preserves edge/one-shot state. + * @note Nested registrations are probed without advancing provider, edge or + * one-shot state. */ bool task_epoll_poll_ready(struct task *task, struct task_file *file); diff --git a/tools/tests/epoll_capacity_test.c b/tools/tests/epoll_capacity_test.c index 3d0fbb48..08eeafdb 100644 --- a/tools/tests/epoll_capacity_test.c +++ b/tools/tests/epoll_capacity_test.c @@ -120,9 +120,29 @@ int64_t syscall_poll_park(struct task *task, int64_t timeout_ms, return 0; } -int64_t syscall_poll_impl(struct task *task, struct pollfd *fds, - uint32_t nfds, int64_t timeout_ms, - uint64_t generation) +struct fixture_mount_view { + uint64_t generation; + uint64_t seen; +}; + +/** @brief Model a retained mount view with independent observation state. */ +bool vfs_file_poll(struct vfs_open_file *file,short events,bool consume, + uint64_t *generation,short *ready) +{ + if(!file)return false; + struct fixture_mount_view *view=(struct fixture_mount_view *)file; + if(generation)*generation=view->generation; + *ready=events&(POLLIN|POLLRDNORM); + if(view->seen!=view->generation) { + *ready|=POLLERR|(events&POLLPRI); + if(consume)view->seen=view->generation; + } + return true; +} + +static int64_t fixture_poll(struct task *task, struct pollfd *fds, + uint32_t nfds, int64_t timeout_ms, + uint64_t generation,bool consume) { (void)task; (void)timeout_ms; @@ -134,6 +154,8 @@ int64_t syscall_poll_impl(struct task *task, struct pollfd *fds, fds[i].revents = task_epoll_poll_ready(task, file) ? fds[i].events & POLLIN : 0; continue; } + if (vfs_file_poll(file->provider_file,fds[i].events,consume,NULL,&fds[i].revents)) + continue; if (file->flags & TASK_FILE_FLAG_EVENTFD) { fds[i].revents = file->aux ? fds[i].events & POLLIN : 0; continue; @@ -146,6 +168,18 @@ int64_t syscall_poll_impl(struct task *task, struct pollfd *fds, return nfds; } +int64_t syscall_poll_impl(struct task *task,struct pollfd *fds,uint32_t nfds, + int64_t timeout_ms,uint64_t generation) +{ + return fixture_poll(task,fds,nfds,timeout_ms,generation,true); +} + +int64_t syscall_poll_probe(struct task *task,struct pollfd *fds,uint32_t nfds, + int64_t timeout_ms,uint64_t generation) +{ + return fixture_poll(task,fds,nfds,timeout_ms,generation,false); +} + /** @brief Exercise real evdev refill edges without an intermediate epoll scan. */ static void test_evdev_edges(void) { @@ -272,6 +306,44 @@ static void test_nested_epoll(void) puts("PASS nested epoll readiness, oneshot, cycles, depth and close cleanup"); } +/** @brief Preserve each mount event across nested epoll readiness probes. */ +static void test_nested_mount_view(void) +{ + struct fixture_mount_view view={.generation=1,.seen=1}; + struct task_epoll *inner=calloc(1,sizeof(*inner)),*outer=calloc(1,sizeof(*outer)); + struct task_file source={.used=1,.node={.type=RELIEFOS_FS_TYPE_FILE}, + .provider_file=(struct vfs_open_file *)&view}; + struct task_file inner_file={.used=1,.flags=TASK_FILE_FLAG_EPOLL,.aux=(uintptr_t)inner}; + struct task_file outer_file={.used=1,.flags=TASK_FILE_FLAG_EPOLL,.aux=(uintptr_t)outer}; + struct epoll_event event={.events=EPOLLIN|EPOLLET,.data=31},output; + assert(inner && outer); + current.limits.nofile.rlim_cur=TEST_FD_MAX; + descriptors[30]=&inner_file;descriptors[31]=&outer_file;descriptors[32]=&source; + assert(!syscall_epoll_ctl(30,EPOLL_CTL_ADD,32,(uintptr_t)&event)); + event.events=EPOLLIN; + assert(!syscall_epoll_ctl(31,EPOLL_CTL_ADD,30,(uintptr_t)&event)); + assert(syscall_epoll_wait(30,(uintptr_t)&output,1,0)==1 && output.events==EPOLLIN); + assert(!task_epoll_poll_ready(¤t,&outer_file)); + ++view.generation; + assert(task_epoll_poll_ready(¤t,&outer_file)); + assert(task_epoll_poll_ready(¤t,&outer_file) && view.seen==1); + assert(syscall_epoll_wait(31,(uintptr_t)&output,1,0)==1); + assert(syscall_epoll_wait(31,(uintptr_t)&output,1,0)==1 && view.seen==1); + assert(syscall_epoll_wait(30,(uintptr_t)&output,1,0)==1); + assert((output.events&(EPOLLIN|EPOLLERR))==(EPOLLIN|EPOLLERR) && view.seen==2); + assert(!syscall_epoll_wait(30,(uintptr_t)&output,1,0)); + assert(!task_epoll_poll_ready(¤t,&outer_file)); + ++view.generation; + assert(syscall_epoll_wait(31,(uintptr_t)&output,1,0)==1); + assert(syscall_epoll_wait(30,(uintptr_t)&output,1,0)==1 && view.seen==3); + task_epoll_destroy(outer); + task_epoll_destroy(inner); + assert(!source.epoll_watches && !inner_file.epoll_watches); + descriptors[30]=descriptors[31]=descriptors[32]=NULL; + current=(struct task){0};kernel_free_calls=0; + puts("PASS nested epoll mount view: retained event, repeated changes and no duplicate edge"); +} + int main(void) { struct task_epoll *epoll; @@ -279,6 +351,7 @@ int main(void) struct epoll_event ready[TEST_WATCHES]; test_nested_epoll(); + test_nested_mount_view(); test_evdev_edges(); memset(¤t, 0, sizeof(current)); current.pid = 1; diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index e9a184ad..21936dd3 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -3324,7 +3324,13 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_namespace_snapshot(&snapshot,ns,NULL,NULL)); assert(!vfs_namespace_root(&snapshot,&snapshot_root)); strcpy(user.source,"/shared-a/p/file-source");strcpy(user.target,"/shared-a/p/file-target"); + uint64_t origin_generation=ns->mount_generation,snapshot_generation=snapshot.mount_generation; + test_fail_heap_after=0; + assert(scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_BIND|MS_REC,0)==-ENOMEM); + test_fail_heap_after=-1; + assert(ns->mount_generation==origin_generation && snapshot.mount_generation==snapshot_generation); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,from,to,0,MS_BIND|MS_REC,0)); + assert(ns->mount_generation!=origin_generation && snapshot.mount_generation!=snapshot_generation); const char *file_peers[]={"/shared-a/p/file-target","/shared-b/p/file-target","/shared-narrow/file-target"}; for(unsigned i=0;imount_generation;snapshot_generation=snapshot.mount_generation; assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,to,0,0,0,0)); + assert(ns->mount_generation!=origin_generation && snapshot.mount_generation!=snapshot_generation); for(unsigned i=0;i #include #include +#include #include "../../include/reliefnt/audio.h" int sound_service_card_snapshot(uint32_t index, uint32_t *out_id, struct audio_card_identity *identity) @@ -398,6 +399,58 @@ static void test_foreign_proc_mount_view(struct vfs_namespace *ns,const struct v assert(vfs_reclaim_mounts(2)==2 && !vfs_reclaim_pending()); } +/** @brief Exercise captured mount view notifications across graph operations. */ +static void test_proc_mount_notifications(struct vfs_namespace *ns, + const struct vfs_path *root, + const struct vfs_path *source, + const struct vfs_path *destination, + struct vfs_open_file *first, + struct vfs_open_file *second) +{ + uint64_t initial=0, generation=0; + short ready=0; + assert(vfs_file_poll(first,POLLIN|POLLPRI,false,&initial,&ready)); + assert(ready==POLLIN); + assert(vfs_file_poll(second,POLLPRI,true,&generation,&ready)); + assert(!ready && generation==initial); + assert(vfs_mount_move(ns,root,destination)==-EBUSY); + assert(vfs_file_poll(first,POLLPRI,true,&generation,&ready)); + assert(!ready && generation==initial); + + assert(!vfs_mount_bind(ns,source,destination)); + assert(vfs_file_poll(first,POLLPRI,false,&generation,&ready)); + assert(ready==(POLLPRI|POLLERR) && generation!=initial); + assert(vfs_file_poll(first,POLLPRI,false,NULL,&ready)); + assert(ready==(POLLPRI|POLLERR)); + assert(vfs_file_poll(first,POLLPRI,true,NULL,&ready)); + assert(ready==(POLLPRI|POLLERR)); + /* Another descriptor for the same OFD observes the consumed state. */ + struct vfs_open_file *alias=first; + assert(vfs_file_poll(alias,POLLPRI,true,NULL,&ready) && !ready); + assert(vfs_file_poll(second,POLLPRI,true,NULL,&ready)); + assert(ready==(POLLPRI|POLLERR)); + + struct vfs_path bound={0}; + assert(!vfs_path_lookup(ns,root,root,"/else",0,&bound)); + assert(!vfs_path_bind_remount(&bound,0)); + assert(vfs_file_poll(first,POLLPRI,true,NULL,&ready)); + assert(ready==(POLLPRI|POLLERR)); + assert(!vfs_path_remount(&bound,0)); + assert(vfs_file_poll(first,POLLPRI,true,NULL,&ready)); + assert(ready==(POLLPRI|POLLERR)); + assert(!vfs_mount_set_propagation(ns,&bound,MS_PRIVATE)); + assert(vfs_file_poll(first,POLLPRI,true,NULL,&ready)); + assert(ready==(POLLPRI|POLLERR)); + assert(vfs_path_remount(root,UINT64_MAX)==-EOPNOTSUPP); + assert(vfs_file_poll(first,POLLPRI,true,NULL,&ready) && !ready); + assert(!vfs_mount_unmount_lazy(ns,&bound)); + vfs_path_put(&bound); + assert(vfs_reclaim_mounts(1)==1); + assert(vfs_file_poll(first,POLLPRI,true,NULL,&ready)); + assert(ready==(POLLPRI|POLLERR)); + puts("PASS proc mount view: isolated OFD state, non-consuming probes, bind, remount, propagation, detach and failure"); +} + static void test_proc_mount_objects(void) { static const struct vfs_backend_ops ops={.lookup=proc_path_lookup,.retain=proc_path_retain, @@ -445,6 +498,7 @@ static void test_proc_mount_objects(void) assert(strstr(mount_text,"/procdir rw - proc proc rw\n")); assert(!vfs_file_read(new_view,0,mount_text,sizeof(mount_text)-1,&got) && !got); vfs_path_put(¤t.fs_paths.root);vfs_path_get(&root,¤t.fs_paths.root); + test_proc_mount_notifications(&ns,&root,&mounted,&destination,old_view,new_view); assert(!vfs_file_read(new_view,0,mount_text,sizeof(mount_text)-1,&got) && !got); vfs_path_get(&version,&sched_task_mm(¤t)->executable_path); memset(proc_long_directory,'a',255);memset(proc_long_file,'b',255); diff --git a/tools/tests/select_bitmap_test.c b/tools/tests/select_bitmap_test.c index fa98a026..5aabb0a8 100644 --- a/tools/tests/select_bitmap_test.c +++ b/tools/tests/select_bitmap_test.c @@ -15,6 +15,25 @@ static struct task current; static struct task_file files[TEST_FD_MAX]; static int allocation_budget = -1; +struct fixture_mount_view { + uint64_t generation; + uint64_t seen; +}; + +bool vfs_file_poll(struct vfs_open_file *file, short events, bool consume, + uint64_t *generation, short *ready) +{ + if (!file) return false; + struct fixture_mount_view *view = (struct fixture_mount_view *)file; + if (generation) *generation = view->generation; + *ready = events & (POLLIN | POLLRDNORM); + if (view->seen != view->generation) { + *ready |= POLLERR | (events & POLLPRI); + if (consume) view->seen = view->generation; + } + return true; +} + struct task *sched_current_task(void) { return ¤t; } struct task_file *task_file_for_fd(struct task *task, int fd) @@ -90,6 +109,8 @@ int kernel_poll_wait_current(uint64_t generation, uint64_t wake_tick) short task_signalfd_poll(struct task *task, const struct task_file *file) { (void)task; (void)file; return 0; } +short task_pidfd_poll(const struct task_file *file) +{ (void)file; assert(!"unexpected pidfd"); return 0; } short task_pipe_poll(const struct task_file *file, short events) { (void)file; (void)events; return 0; } short task_socket_poll(const struct task_file *file, short events) @@ -124,6 +145,22 @@ static void set_readable_file(uint32_t fd) }; } +/** @brief Check production poll dispatch and non-consuming provider probes. */ +static void test_mount_view_poll(void) +{ + struct fixture_mount_view view = {.generation = 2, .seen = 1}; + struct pollfd descriptor = {.fd = 6, .events = POLLIN | POLLPRI}; + set_readable_file(6); + files[6].provider_file = (struct vfs_open_file *)&view; + assert(syscall_poll_probe(¤t, &descriptor, 1, 0, 0) == 1); + assert(descriptor.revents == (POLLIN | POLLPRI | POLLERR) && view.seen == 1); + assert(syscall_poll_impl(¤t, &descriptor, 1, 0, 0) == 1); + assert(descriptor.revents == (POLLIN | POLLPRI | POLLERR) && view.seen == 2); + assert(syscall_poll_impl(¤t, &descriptor, 1, 0, 0) == 1); + assert(descriptor.revents == POLLIN); + files[6] = (struct task_file){0}; +} + static int test_high_descriptor_bitmap(void) { uint64_t read_set[HIGH_WORDS] = {0}; @@ -235,6 +272,7 @@ int main(void) current.kind = TASK_KIND_USER; current.limits.nofile.rlim_cur = TEST_FD_MAX; + test_mount_view_poll(); if (test_high_descriptor_bitmap()) return 1; if (test_error_preserves_masks()) return 1; if (test_allocation_failure_preserves_masks()) return 1; diff --git a/tools/tests/task8_epoll_user_test.c b/tools/tests/task8_epoll_user_test.c index ad19598e..fc9c137b 100644 --- a/tools/tests/task8_epoll_user_test.c +++ b/tools/tests/task8_epoll_user_test.c @@ -13,6 +13,7 @@ static struct epoll_event output[2]; static uint64_t swapped, invalid; static bool contended; static unsigned preparations; +struct fixture_mount_view { uint64_t generation, seen; }; int swap_prepare_user_range(struct task *task,uint64_t address,uint64_t length,bool writing) { assert(task==¤t && length==sizeof(struct epoll_event) && writing);++preparations; @@ -30,8 +31,25 @@ uint64_t task_socket_event_generation(const struct task_file *file) { (void)file uint64_t input_evdev_event_generation_vt(uint32_t kind,uint64_t token,uint32_t vt) { (void)kind;(void)token;(void)vt;return 0; } uint64_t time_ticks(void) { return 100; } -int64_t syscall_poll_impl(struct task *task,struct pollfd *p,uint32_t count,int64_t timeout,uint64_t generation) -{ assert(task==¤t && count==1 && !timeout);(void)generation;p->revents=POLLIN;return 1; } +bool vfs_file_poll(struct vfs_open_file *file,short events,bool consume,uint64_t *generation,short *ready) +{ + if(!file)return false; + struct fixture_mount_view *view=(struct fixture_mount_view *)file; + if(generation)*generation=view->generation; + *ready=events&POLLIN; + if(view->seen!=view->generation) { + *ready|=POLLERR|(events&POLLPRI); + if(consume)view->seen=view->generation; + } + return true; +} +int64_t syscall_poll_probe(struct task *task,struct pollfd *p,uint32_t count,int64_t timeout,uint64_t generation) +{ + assert(task==¤t && count==1 && !timeout);(void)generation; + if(!task->syscall_file || !vfs_file_poll(task->syscall_file->provider_file,p->events,false,NULL,&p->revents)) + p->revents=POLLIN; + return 1; +} int64_t syscall_poll_park(struct task *task,int64_t timeout,uint64_t generation,bool wait) { (void)task;(void)timeout;(void)generation;(void)wait;assert(0);return 0; } int main(void) @@ -57,5 +75,17 @@ int main(void) invalid=(uintptr_t)&output[1];memset(output,0,sizeof(output)); assert(syscall_epoll_wait_common(¤t,&epoll,(uintptr_t)output,1000000,0)==1); assert(items[0].disabled && !items[1].disabled && !items[1].ready && output[0].data==41); + struct fixture_mount_view view={.generation=2,.seen=1}; + struct task_file source={.provider_file=(struct vfs_open_file *)&view}; + struct task_epoll_watch watch={.file=&source}; + struct task_epoll_entry mount_entry={.fd=6,.events=EPOLLIN|EPOLLET,.active=1,.watch=&watch}; + struct task_epoll mount_epoll={.entries=1,.capacity=1,.item=&mount_entry}; + invalid=0;swapped=(uintptr_t)&output[0];contended=true; + assert(syscall_epoll_wait_common(¤t,&mount_epoll,(uintptr_t)output,1,0)==KERNEL_SYSCALL_SWAP_CONTENDED); + assert(view.seen==1 && !mount_entry.ready); + contended=false; + assert(syscall_epoll_wait_common(¤t,&mount_epoll,(uintptr_t)output,1,0)==1); + assert(view.seen==2 && output[0].events==(EPOLLIN|EPOLLERR)); + assert(!syscall_epoll_wait_common(¤t,&mount_epoll,(uintptr_t)output,1,0)); puts("PASS epoll: bounded output, first contention, edge/oneshot and partial copy"); } From 15cc22c5f59d4af0ba65e99379d57e8bfac0cbab Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 12:49:43 +0800 Subject: [PATCH 24/97] feat(vfs): expose detached mount roots --- Documentation/core-api/mount-namespaces.rst | 12 +++++ fs/vfs/file.c | 16 +++--- fs/vfs/mount_internal.h | 9 ++-- fs/vfs/mount_tree.c | 29 +++++++--- fs/vfs/path.c | 6 ++- include/reliefnt/mount.h | 22 +++++--- tools/tests/mount_backend_test.c | 59 ++++++++++++++++++++- 7 files changed, 127 insertions(+), 26 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 15869f0c..b5f340fb 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -25,6 +25,18 @@ VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载 是否允许卸载;失败时不摘除任何挂载。延迟卸载不分配内存,保留接收方无关的 覆盖挂载。挂载表的传播字段见 :doc:`../userspace-api/abi`。 +游离挂载路径 +============ + +``vfs_mount_detached_root()`` 显式暴露尚未附着的挂载根并返回持有路径。 +该路径及其子项可以进行常规查找、文件操作和根挂载重配置。游离根没有通向 +命名空间的父边,描述符链接和不可达的工作目录以该挂载根为基准显示。 +未暴露的内部挂载继续限制路径遍历;已经 lazy-unmount 的挂载不能重新发布。 + +``vfs_mount_attach()`` 成功后,挂载和已持有路径转入目标命名空间的正常生命周期。 +传播准备失败时保留游离状态、持有路径和原有策略,调用方可继续使用或重试。 +路径与挂载引用在最后一次释放后按现有后端清理规则回收。 + 任务、路径查找与 proc 视图 ========================== diff --git a/fs/vfs/file.c b/fs/vfs/file.c index a53f3414..160f99fa 100644 --- a/fs/vfs/file.c +++ b/fs/vfs/file.c @@ -126,7 +126,7 @@ uint64_t vfs_path_mount_flags(const struct vfs_path *path) } /** @brief Configure a detached attachment without mutating its shared backend. - * @param mount Owned mount never published in a namespace, required. + * @param mount Owned mount never exposed or published in a namespace. * @param flags Only per-mount bits and optional strictatime selector. * @return Zero or negative state/unsupported errno, preserving state on error. * A lazily detached attachment keeps its policy until retirement. @@ -135,7 +135,7 @@ uint64_t vfs_path_mount_flags(const struct vfs_path *path) int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags) { if(!mount || !mount->references)return -EINVAL; - if(mount->ns || mount->point.mount || mount->lazy_detached)return -EBUSY; + if(mount->ns || mount->point.mount || mount->lazy_detached || mount->exposed_detached)return -EBUSY; if(flags&~(VFS_MOUNT_POLICY_MASK|MS_STRICTATIME))return -EOPNOTSUPP; mount->policy=vfs_policy_bits(flags);return 0; } @@ -166,7 +166,7 @@ int vfs_path_bind_remount(const struct vfs_path *path,uint64_t flags) } /** @brief Reconfigure the selected attachment after shared backend preparation. - * @param path Borrowed actual attached filesystem root, required. + * @param path Borrowed attached or exposed unpublished filesystem root. * @param flags Requested supported MS flags; omitted atime preserves old bits. * @return Zero or input/unsupported/readonly/backend errno. Failed preparation * leaves mount policy unchanged. Execution ownership required; no graph/module @@ -175,7 +175,8 @@ int vfs_path_bind_remount(const struct vfs_path *path,uint64_t flags) */ static int vfs_remount(const struct vfs_path *path,uint64_t flags,const char *options) { - if(!vfs_path_valid(path) || !path->mount->ns || path->dentry!=path->mount->root)return -EINVAL; + if(!vfs_path_valid(path) || (!path->mount->ns && !path->mount->exposed_detached) || + path->dentry!=path->mount->root)return -EINVAL; if(flags&~(VFS_MOUNT_POLICY_MASK|VFS_SUPER_POLICY_MASK|MS_STRICTATIME))return -EOPNOTSUPP; struct vfs_mount *mount=path->mount; const uint64_t atime=MS_NOATIME|MS_NODIRATIME|MS_RELATIME; @@ -194,8 +195,8 @@ static int vfs_remount(const struct vfs_path *path,uint64_t flags,const char *op return rc; } -/** @brief Remount an attached filesystem without filesystem-specific options. - * @param path Retained mounted root. @param flags Requested Linux mount policy. +/** @brief Remount an attached or exposed unpublished filesystem. + * @param path Retained filesystem root. @param flags Requested Linux mount policy. * @return Zero or negative errno, preserving policy on failure. */ int vfs_path_remount(const struct vfs_path *path,uint64_t flags) @@ -204,7 +205,8 @@ int vfs_path_remount(const struct vfs_path *path,uint64_t flags) } /** @brief Reconfigure backend options and mount policy in one transaction. - * @param path Retained mounted root. @param flags Requested Linux mount policy. + * @param path Retained attached or exposed unpublished filesystem root. + * @param flags Requested Linux mount policy. * @param options Optional filesystem-specific data, validated by its backend. * @return Zero or negative errno, preserving options and policy on failure. * Execution ownership retains the provider and serializes validation/commit. diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index c0f2f6e3..87f7276c 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -49,6 +49,7 @@ struct vfs_mount { bool propagation_copy; /* Receiver can detach beneath an unrelated root cover. */ bool unbindable; /* Pruned by recursive bind; never a valid bind source. */ bool lazy_detached; /* No namespace edges; retained paths still work. */ + bool exposed_detached; /* Unpublished root explicitly handed to a caller. */ char *source,*filesystem; uint64_t device; }; @@ -79,12 +80,14 @@ bool vfs_path_valid(const struct vfs_path *path); /** @brief Admit a held path for pathname access, not mount topology changes. * @param ns Borrowed execution-owned lookup namespace. * @param path Borrowed retained path, nullable. - * @return True for a member or a previously attached mount now detached. - * Unpublished mounts and live mounts in an unrelated namespace are excluded. + * @return True for a member, an explicitly exposed unpublished mount, or a + * previously attached mount now detached. Other unpublished mounts and live + * mounts in an unrelated namespace are excluded. */ static inline bool vfs_path_walkable(const struct vfs_namespace *ns,const struct vfs_path *path) { - return ns && vfs_path_valid(path) && (path->mount->ns==ns || path->mount->lazy_detached); + return ns && vfs_path_valid(path) && (path->mount->ns==ns || path->mount->lazy_detached || + (!path->mount->ns && path->mount->exposed_detached)); } /** @brief Normalize supported attachment input independently of its backend. * @param flags Native MS inputs; unsupported bits have no representation here. diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index 3d1f6251..d4a1e600 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -173,16 +173,16 @@ void vfs_path_put(struct vfs_path *path) vfs_dentry_put(old.mount,old.dentry);vfs_mount_put(old.mount); } -/** @brief Set diagnostic identity on an unpublished mount. - * @param mount Owned mount never published in a namespace. +/** @brief Set diagnostic identity on a private unpublished mount. + * @param mount Owned mount never exposed or published in a namespace. * @param source Nonempty backing label. @param filesystem Nonempty type name. * @param device Linux encoded device number. - * @return Zero or negative errno; a lazily detached mount cannot be renamed. + * @return Zero or negative errno; exposed or lazily detached mounts are busy. */ int vfs_mount_describe(struct vfs_mount *mount,const char *source,const char *filesystem,uint64_t device) { if(!mount || !source || !source[0] || !filesystem || !filesystem[0])return -EINVAL; - if(mount->ns || mount->point.mount || mount->lazy_detached)return -EBUSY; + if(mount->ns || mount->point.mount || mount->lazy_detached || mount->exposed_detached)return -EBUSY; size_t source_length=0,type_length=0; while(source[source_length])if(++source_length>=VFS_PATH_MAX)return -ENAMETOOLONG; while(filesystem[type_length]) { @@ -258,13 +258,14 @@ uint64_t vfs_mount_next_peer_id(void) {return next_peer_id;} /** @brief Retain an unpublished mount as the permanent namespace anchor. * @param ns Borrowed empty namespace. @param root Borrowed unpublished root. * @return Zero or negative errno, including exhaustion of VFS-wide mount IDs. - * Previously lazily detached roots are rejected. + * Previously lazily detached roots are rejected; exposed roots are published. */ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root) { if(!ns || ns->root || ns->mounts || !root || root->ns || root->point.mount || root->lazy_detached)return -EINVAL; if(!next_mount_id)return -EOVERFLOW; - ++root->references;root->ns=ns;root->id=next_mount_id++;root->next=NULL; + ++root->references;root->ns=ns;root->exposed_detached=false; + root->id=next_mount_id++;root->next=NULL; ns->root=root;ns->mounts=root;return 0; } @@ -297,6 +298,19 @@ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out) vfs_follow_mounts(ns,out);return 0; } +/** @copydoc vfs_mount_detached_root */ +int vfs_mount_detached_root(struct vfs_mount *mount,struct vfs_path *out) +{ + if(!out)return -EINVAL; + *out=(struct vfs_path){0}; + if(!mount || !mount->root)return -EINVAL; + if(mount->ns || mount->point.mount || mount->lazy_detached)return -EBUSY; + struct vfs_path root={mount,mount->root}; + vfs_path_get(&root,out); + mount->exposed_detached=true; + return 0; +} + /** @brief Check mount ancestry by retained topology rather than pathname. * @param root Borrowed candidate subtree root. * @param mount Borrowed attachment to test. @@ -485,7 +499,8 @@ static int vfs_finish_mount_batch(struct vfs_namespace *snapshot,struct vfs_moun while(ordered) { struct vfs_mount *mount=ordered;ordered=mount->next; struct vfs_namespace *ns=snapshot ? snapshot : mount->point.mount->ns; - mount->ns=ns;mount->next=ns->mounts;ns->mounts=mount; + mount->ns=ns;mount->exposed_detached=false; + mount->next=ns->mounts;ns->mounts=mount; vfs_update_propagation(mount); if(mount->staged_cover) { struct vfs_path root={mount,mount->root}; diff --git a/fs/vfs/path.c b/fs/vfs/path.c index e3aa0ef6..2263d83b 100644 --- a/fs/vfs/path.c +++ b/fs/vfs/path.c @@ -260,7 +260,8 @@ int vfs_path_format_link(const struct vfs_namespace *ns,const struct vfs_path *r if(path->dentry!=path->mount->root && !path->dentry->name) return path->mount->ops->display_name ? path->mount->ops->display_name(path->mount->context, &path->dentry->node,buffer,capacity) : -EOPNOTSUPP; - bool detached=path->mount->lazy_detached; + bool detached=path->mount->lazy_detached || + (!path->mount->ns && path->mount->exposed_detached); if(!detached) { if(!ns || !ns->root || !vfs_path_valid(root))return -EINVAL; if(!vfs_path_walkable(ns,root) || path->mount->ns!=ns)return -EXDEV; @@ -305,7 +306,8 @@ int vfs_path_getcwd(const struct vfs_namespace *ns,const struct vfs_path *root, static const char marker[]="(unreachable)"; size_t prefix=sizeof(marker)-1; if(capacity<=prefix)return -ENAMETOOLONG; - struct vfs_mount *base=cwd->mount->lazy_detached ? cwd->mount : ns->root; + struct vfs_mount *base=(cwd->mount->lazy_detached || + (!cwd->mount->ns && cwd->mount->exposed_detached)) ? cwd->mount : ns->root; struct vfs_path anchor={base,base->root}; rc=vfs_path_format(ns,&anchor,cwd,buffer+prefix,capacity-prefix); if(!rc)__builtin_memcpy(buffer,marker,prefix); diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 078e0c2c..5948c859 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -239,12 +239,12 @@ static inline void vfs_namespace_put(struct vfs_namespace *ns) if(ns && !--ns->references && ns->release)ns->release(ns); } /** @brief Assign immutable diagnostic identity before publishing a mount. - * @param mount Owned detached mount, required; attachment returns EBUSY. + * @param mount Owned mount not yet exposed or attached, required. * @param source Nonempty kernel source label, copied with PATH_MAX bounds. * @param filesystem Nonempty kernel filesystem name, copied with NAME_MAX bounds. * @param device Linux encoded st_dev of this filesystem instance. - * @return Zero or negative input/allocation errno. Replacement is atomic on - * allocation failure. Names never select a backend or authorize operations. + * @return Zero or negative input/state/allocation errno. Replacement is atomic + * on allocation failure. Names never select a backend or authorize operations. * Serialized task context, no I/O or locks; mount retirement frees the copy. */ int vfs_mount_describe(struct vfs_mount *mount,const char *source,const char *filesystem,uint64_t device); @@ -277,7 +277,7 @@ int vfs_read_mount_table(const struct vfs_namespace *ns,const struct vfs_path *r */ int vfs_namespace_context_mountpoint(const struct vfs_namespace *ns,const void *context,char *buffer,size_t capacity); /** @brief Remount the exact retained attachment rather than a formatted name. - * @param path Retained mounted filesystem root, required. + * @param path Retained attached or exposed unpublished filesystem root. * @param flags Supported final filesystem/mount policy, excluding MS_REMOUNT. * @return Zero or negative type/unsupported/busy/provider errno. Provider * validates before committing; caller separately checks CAP_SYS_ADMIN. @@ -285,7 +285,7 @@ int vfs_namespace_context_mountpoint(const struct vfs_namespace *ns,const void * */ int vfs_path_remount(const struct vfs_path *path,uint64_t flags); /** @brief Validate filesystem-specific options before changing remount policy. - * @param path Retained mounted filesystem root, required. + * @param path Retained attached or exposed unpublished filesystem root. * @param flags Final policy excluding MS_REMOUNT. * @param options Optional copied filesystem-specific data validated by its backend. * @return Zero or negative option/type/provider errno. Unsupported data leaves @@ -555,7 +555,7 @@ uint32_t vfs_reclaim_mounts(uint32_t budget); */ bool vfs_reclaim_pending(void); /** @brief Set initial policy on one detached, owned mount without changing its backend. - * @param mount Owned unpublished mount, required; no namespace membership. + * @param mount Owned mount not yet exposed or published, required. * @param flags Per-attachment MS flags, with optional MS_STRICTATIME input. * @return Zero, EINVAL/EBUSY for invalid state, or EOPNOTSUPP for other flags. * Execution ownership required; pure field publication, no callbacks, I/O, @@ -565,6 +565,7 @@ int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags); /** @brief Initialize an empty namespace, retaining its initial root mount. * @param ns Zero-initialized namespace owned by the caller. * @param root Unpublished mount, borrowed and retained; caller keeps its handle. + * An explicitly exposed root and its held paths become namespace members. * @return Zero or negative errno, no change on failure. Serialized task context. */ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root); @@ -612,6 +613,15 @@ int vfs_namespace_destroy(struct vfs_namespace *ns); * @return Zero or negative errno. Serialized task context. */ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out); +/** @brief Retain and expose the root of an unpublished mount. + * @param mount Caller-owned mount that has never been attached. + * @param out Receives an owned root path, cleared on failure. + * @return Zero or negative input/state errno. The retained path can be used + * for ordinary filesystem access and reconfiguration before attachment. + * Direct attachment policy and diagnostic identity setters are then closed. + * Execution ownership is required; no allocation or I/O is performed. + */ +int vfs_mount_detached_root(struct vfs_mount *mount,struct vfs_path *out); /** @brief Attach an unpublished mount and propagate to eligible peers and slaves. * @param ns Origin namespace under execution ownership. * @param mount Unpublished mount; caller retains its own handle. diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 21936dd3..a18f3941 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2323,6 +2323,57 @@ static void runtime_failed_teardown(void) puts("PASS actual backend deferred teardown: raw-inode wait, failed device flush, no allocation, slot retention, revived membership and final retry"); } +/** @brief Exercise access, failed publication and final lifetime of a detached mount. */ +static void runtime_detached_mount(struct vfs_namespace *ns,const struct vfs_path *root) +{ + struct vfs_mount *mount=NULL; + struct vfs_path detached={0},file={0},found={0},point={0},mounted={0}; + assert(!storage_new_tmpfs_mount("detached",MS_NOSUID, + "size=8192,nr_inodes=16,mode=0700",1000,1000,&mount)); + struct storage_volume *volume=mount->context; + struct vfs_path private_root={mount,mount->root}; + assert(vfs_path_lookup(ns,root,&private_root,".",0,&found)==-EXDEV); + assert(!vfs_mount_detached_root(mount,&detached)); + assert(vfs_mount_set_flags(mount,0)==-EBUSY); + assert(vfs_mount_describe(mount,"changed","tmpfs",0)==-EBUSY); + assert(!vfs_path_lookup(ns,root,&detached,".",0,&found)); + assert(vfs_path_equal(&detached,&found));vfs_path_put(&found); + struct reliefos_permissions mode={0600,1000,1000}; + assert(!vfs_path_new_file(&detached,"credential",&mode,&file)); + assert(!vfs_path_lookup(ns,root,&detached,"credential",0,&found)); + assert(vfs_path_equal(&file,&found));vfs_path_put(&found); + char name[64]; + assert(!vfs_path_format_link(NULL,NULL,&file,name,sizeof(name)) && !strcmp(name,"/credential")); + assert(!vfs_path_getcwd(ns,root,&detached,name,sizeof(name)) && !strcmp(name,"(unreachable)/")); + assert(vfs_path_remount_options(&detached,MS_RDONLY|MS_NOSUID,"size=invalid")==-EINVAL); + assert(!(vfs_path_mount_flags(&detached)&MS_RDONLY)); + struct storage_inode_ref *writer=NULL; + assert(!storage_inode_get(vfs_path_node(&file),&writer)); + assert(!storage_inode_write_get(writer)); + assert(vfs_path_remount(&detached,MS_RDONLY|MS_NOSUID)==-EBUSY); + storage_inode_write_put(writer);assert(!storage_inode_put(writer)); + assert(!vfs_path_remount(&detached,MS_RDONLY|MS_NOSUID)); + uint32_t written=0; + assert(vfs_path_write(&file,0,"x",1,&written)==-EROFS && !written); + assert(!vfs_path_lookup(ns,root,root,"/mnt/old",0,&point)); + assert(vfs_mount_attach(ns,mount,&point)==-ENOTDIR); + vfs_path_put(&point); + assert(!vfs_path_lookup(ns,root,&detached,"credential",0,&found)); + vfs_path_put(&found); + assert(!vfs_path_lookup(ns,root,root,"/runtime-source",0,&point)); + assert(!vfs_mount_attach(ns,mount,&point)); + assert(vfs_mount_detached_root(mount,&found)==-EBUSY); + vfs_mount_put(mount); + assert(!vfs_path_lookup(ns,root,root,"/runtime-source",0,&mounted)); + assert(vfs_path_equal(&mounted,&detached)); + assert(vfs_path_mount_flags(&mounted)&MS_RDONLY); + vfs_path_put(&file);vfs_path_put(&detached); + assert(!vfs_mount_unmount(ns,&mounted)); + vfs_path_put(&mounted);vfs_path_put(&point); + assert(!volume->ready); + puts("PASS detached tmpfs access: reconfigure rollback, failed attachment, publication and final release"); +} + /* Linux keeps nosuid/nodev/noexec/atime on each attachment while the backing * filesystem and its readonly state are shared. Two real mounts of one tmpfs * context must not change each other's policy when one is remounted. */ @@ -3355,14 +3406,19 @@ static void runtime_shared_mounts(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&a)); assert(!vfs_path_lookup(ns,root,root,user.target,0,&point)); assert(!storage_new_tmpfs_mount("stacked event",0,NULL,1000,1000,&mount)); + struct vfs_path detached={0}; + assert(!vfs_mount_detached_root(mount,&detached)); const uint64_t covered_id=vfs_mount_next_id(),covered_peer_id=vfs_mount_next_peer_id(); test_fail_heap_after=1; assert(vfs_mount_attach(ns,mount,&point)==-ENOMEM); test_fail_heap_after=-1; assert(vfs_mount_next_id()==covered_id && vfs_mount_next_peer_id()==covered_peer_id); + assert(!vfs_path_lookup(ns,root,&detached,".",0,&found)); + assert(vfs_path_equal(&detached,&found));vfs_path_put(&found); assert(!vfs_path_lookup(ns,root,root,"/shared-a/covered",0,&found)); assert(vfs_path_equal(&a,&found));vfs_path_put(&found); - assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); + assert(!vfs_mount_attach(ns,mount,&point)); + vfs_path_put(&detached);vfs_mount_put(mount);vfs_path_put(&point); assert(vfs_mount_next_id()==covered_id+2 && vfs_mount_next_peer_id()==covered_peer_id+1); assert(!vfs_kernel_mkdir(ns,"/shared-b/covered/incoming",0755)); assert(vfs_path_lookup(ns,root,root,"/shared-a/covered/incoming",0,&found)==-ENOENT); @@ -4183,6 +4239,7 @@ int main(int argc,char **argv) runtime_boot_objects(&ns,&root,fs); runtime_mount_objects(&ns,&root,fs); runtime_failed_teardown(); + runtime_detached_mount(&ns,&root); runtime_attachment_policies(&ns,&root); runtime_mount_syscalls(&ns,&root,fs); runtime_file_bind(&ns,&root,fs); From 1315160e020fb8dc605890c2b22421a47b3c95a7 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 13:08:24 +0800 Subject: [PATCH 25/97] feat(vfs): implement tmpfs filesystem context mounts --- .../en/LC_MESSAGES/userspace-api/abi.po | 12 + .../ja/LC_MESSAGES/userspace-api/abi.po | 12 + Documentation/userspace-api/abi.rst | 20 ++ fs/tmpfs/core.c | 7 + fs/vfs/mount_tree.c | 19 ++ include/reliefnt/mount.h | 16 ++ include/reliefnt/task/types.h | 1 + include/reliefnt/tmpfs.h | 5 + include/uapi/linux/mount.h | 25 ++ kernel/sync/profile.c | 1 + kernel/syscall/dispatch.c | 6 +- kernel/syscall/entry.c | 1 + kernel/syscall/fd/descriptor.c | 4 + kernel/syscall/fs/Kbuild | 2 +- kernel/syscall/fs/fs.c | 1 + kernel/syscall/fs/legacy_filesystem.c | 3 +- kernel/syscall/fs/lookup_state.c | 1 + kernel/syscall/fs/mount.c | 2 + kernel/syscall/fs/mount_api.c | 265 ++++++++++++++++++ kernel/syscall/internal.h | 15 + tools/test_mount_backend.py | 2 +- tools/tests/mount_backend_test.c | 93 ++++++ 22 files changed, 507 insertions(+), 6 deletions(-) create mode 100644 kernel/syscall/fs/mount_api.c diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index a05961e2..221ad6ec 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -350,3 +350,15 @@ msgstr "" "specific checks are skipped when AVX is disabled. Applications and glibc versions outside " "this coverage still require individual validation. VMware validation is incomplete, and " "physical hardware has not been validated." + +msgid "文件系统上下文和游离挂载" +msgstr "Filesystem Contexts and Detached Mounts" + +msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" +msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` creates a filesystem context. The caller needs effective ``CAP_SYS_ADMIN``. ``FSCONFIG_SET_STRING`` in ``fsconfig`` accepts the existing tmpfs options, including ``size``, ``nr_blocks``, ``nr_inodes``, ``mode``, ``uid`` and ``gid``. ``FSCONFIG_SET_FLAG`` accepts ``ro`` and ``rw``. ``FSCONFIG_CMD_CREATE`` creates the filesystem using the configured options and may be retried after failure. The context belongs to the open-file description, is shared after dup or fork, and is released with the final reference." + +msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" +msgstr "``fsmount`` returns an ``O_PATH`` descriptor for the detached mount root. It supports ``FSMOUNT_CLOEXEC`` and the readonly, nosuid, nodev, noexec and atime attributes. Files can be accessed relative to this descriptor, and the directory can be reopened via ``/proc/self/fd``. After success, the context can set new options with ``fsconfig`` and update the shared filesystem with ``FSCONFIG_CMD_RECONFIGURE``. Pending options remain after a configuration failure, so the operation can be retried after closing write descriptors that prevent a readonly transition." + +msgid "``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 ``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" +msgstr "``move_mount`` attaches the held mount root at a destination and supports the empty-path and symbolic-link flags for both source and destination. Attachment follows the existing propagation rules when the destination mount is shared. ``MOUNT_ATTR_NOSYMFOLLOW`` and ``MOVE_MOUNT_BENEATH`` return ``EINVAL``, allowing callers to use their corresponding compatibility fallbacks." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 808dc5e2..d4e455f8 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -305,3 +305,15 @@ msgstr "" "構成をそれぞれ確認しました。動的 ELF、pthread/TLS、``posix_spawn``、``dlopen/dlsym``、localhost NSS、通常の robust " "ミューテックスも実行しました。AVX が無効な場合は AVX 固有の検査をスキップします。この範囲外のアプリケーションと glibc バージョンは個別の検証が必要です。VMware " "での検証は未完了で、実機ハードウェアは未検証です。" + +msgid "文件系统上下文和游离挂载" +msgstr "ファイルシステムコンテキストと未接続マウント" + +msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" +msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` はファイルシステムコンテキストを作成します。呼び出し元には有効な ``CAP_SYS_ADMIN`` が必要です。``fsconfig`` の ``FSCONFIG_SET_STRING`` は ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid``、``gid`` などの既存の tmpfs オプションを受け付けます。``FSCONFIG_SET_FLAG`` は ``ro`` と ``rw`` を受け付けます。``FSCONFIG_CMD_CREATE`` は設定済みオプションでファイルシステムを作成し、失敗後に再試行できます。コンテキストはオープンファイル記述に属し、dup または fork 後に共有され、最後の参照が解放されると破棄されます。" + +msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" +msgstr "``fsmount`` は未接続マウントのルートを指す ``O_PATH`` ディスクリプタを返し、``FSMOUNT_CLOEXEC`` と読み取り専用、nosuid、nodev、noexec、atime の属性をサポートします。このディスクリプタを基点にファイルへアクセスでき、``/proc/self/fd`` からディレクトリを開き直すこともできます。成功後、コンテキストは ``fsconfig`` で新しいオプションを設定し、``FSCONFIG_CMD_RECONFIGURE`` で共有ファイルシステムを更新できます。設定失敗時には保留中のオプションが保持されるため、読み取り専用への変更を妨げる書き込みディスクリプタを閉じて再試行できます。" + +msgid "``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 ``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" +msgstr "``move_mount`` は保持しているマウントルートを宛先に接続し、接続元と宛先の空パスおよびシンボリックリンクのフラグをサポートします。宛先のマウントが共有されている場合、接続には既存の伝播規則が適用されます。``MOUNT_ATTR_NOSYMFOLLOW`` と ``MOVE_MOUNT_BENEATH`` は ``EINVAL`` を返すため、呼び出し元はそれぞれの互換フォールバックを利用できます。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index be88eab9..3ea133e7 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -100,6 +100,26 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 与目标必须同为目录或同为非目录,不匹配返回 ``EINVAL``。卸载后目标重新显示 被覆盖的原对象;原 inode、挂载 ID 和访问策略在移动期间保持不变。 +文件系统上下文和游离挂载 +======================== + +``fsopen("tmpfs", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 +``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs +选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 +``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 +``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 +上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。 + +``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` +以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, +也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` +设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 +待处理选项保留,关闭阻止只读转换的写入描述符后可重试。 + +``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 +目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` +和 ``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。 + statx 挂载标识和根属性 ====================== diff --git a/fs/tmpfs/core.c b/fs/tmpfs/core.c index 501938bd..69a8d73e 100644 --- a/fs/tmpfs/core.c +++ b/fs/tmpfs/core.c @@ -303,6 +303,13 @@ static int tmpfs_parse_options(const char *options, struct tmpfs_options *parsed return 0; } +/** @copydoc tmpfs_validate_options */ +int tmpfs_validate_options(const char *options) +{ + struct tmpfs_options candidate = {0}; + return tmpfs_parse_options(options, &candidate); +} + /** @brief Validate or commit quota changes without reinitializing root metadata. * @param fs Live execution-owned filesystem. * @param options Optional Linux tmpfs mount data. diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index d4a1e600..de43798f 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -443,6 +443,15 @@ static int vfs_bind_clone(const struct vfs_path *view,const struct vfs_path *bac return rc; } +/** @copydoc vfs_mount_clone_root */ +int vfs_mount_clone_root(const struct vfs_path *root,struct vfs_mount **out) +{ + if(!out)return -EINVAL; + *out=NULL; + if(!vfs_path_valid(root) || root->dentry!=root->mount->root)return -EINVAL; + return vfs_bind_clone(root,root,false,out); +} + struct vfs_mount_batch { struct vfs_mount *pending; uint64_t next_id,next_peer_id; @@ -864,6 +873,16 @@ int vfs_mount_attach(struct vfs_namespace *ns,struct vfs_mount *mount,const stru return rc; } +/** @copydoc vfs_mount_attach_path */ +int vfs_mount_attach_path(struct vfs_namespace *ns,const struct vfs_path *source, + const struct vfs_path *target) +{ + if(!vfs_path_valid(source) || source->dentry!=source->mount->root)return -EINVAL; + if(source->mount->ns)return vfs_mount_move(ns,source,target); + if(!source->mount->exposed_detached || source->mount->lazy_detached)return -EINVAL; + return vfs_mount_attach(ns,source->mount,target); +} + /** @brief Publish a bind and all its downstream copies atomically. * @param ns Borrowed execution-owned namespace. * @param source Borrowed retained source path in ns. diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 5948c859..ce075c45 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -622,6 +622,22 @@ int vfs_namespace_root(const struct vfs_namespace *ns,struct vfs_path *out); * Execution ownership is required; no allocation or I/O is performed. */ int vfs_mount_detached_root(struct vfs_mount *mount,struct vfs_path *out); +/** @brief Clone a held filesystem root into an unpublished attachment. + * @param root Retained root of the source filesystem. + * @param out Receives one owned detached mount, or NULL on failure. + * @return Zero or negative allocation/provider/type errno. The clone pins the + * original filesystem and may acquire an independent attachment policy. + */ +int vfs_mount_clone_root(const struct vfs_path *root,struct vfs_mount **out); +/** @brief Attach an unpublished held root or move an attached mount root. + * @param ns Execution-owned destination namespace. + * @param source Retained source root, attached or exposed and unpublished. + * @param target Retained destination in the namespace. + * @return Zero or negative type/state/topology/provider errno; failure leaves + * both graphs unchanged. Interior dentries are rejected. + */ +int vfs_mount_attach_path(struct vfs_namespace *ns,const struct vfs_path *source, + const struct vfs_path *target); /** @brief Attach an unpublished mount and propagate to eligible peers and slaves. * @param ns Origin namespace under execution ownership. * @param mount Unpublished mount; caller retains its own handle. diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index 9e8f1dbe..864403c2 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -169,6 +169,7 @@ struct task_file { #define TASK_FILE_KIND_INOTIFY 5u #define TASK_FILE_KIND_DRM_SYNC 6u /* aux: OFD-owned Linux sync_file. */ #define TASK_FILE_KIND_PIDFD 7u /* aux: owned task_identity, aux2: identity inode. */ +#define TASK_FILE_KIND_FS_CONTEXT 8u /* aux: OFD-owned filesystem configuration. */ static inline struct task_file *task_file_description(struct task_file *file) { diff --git a/include/reliefnt/tmpfs.h b/include/reliefnt/tmpfs.h index 3b1ba8b7..3d990ddc 100644 --- a/include/reliefnt/tmpfs.h +++ b/include/reliefnt/tmpfs.h @@ -11,6 +11,11 @@ struct tmpfs_super; uint64_t tmpfs_lookup_generation(const struct tmpfs_super *fs); int tmpfs_new(uint32_t volume, uint64_t flags, const char *options, uint32_t uid, uint32_t gid, struct tmpfs_super **out); +/** @brief Validate tmpfs option syntax without creating or changing a filesystem. + * @param options Borrowed comma-separated option string, nullable. + * @return Zero or negative option errno. No allocation or state change occurs. + */ +int tmpfs_validate_options(const char *options); /** @brief Validate or apply Linux tmpfs quota reconfiguration atomically. * @param fs Live filesystem under execution ownership. @param options Mount data. * @param apply Commit quotas when true, validate without mutation when false. diff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h index 364ad258..af85df08 100644 --- a/include/uapi/linux/mount.h +++ b/include/uapi/linux/mount.h @@ -35,4 +35,29 @@ #define MNT_EXPIRE 4 #define UMOUNT_NOFOLLOW 8 +#define FSOPEN_CLOEXEC 0x00000001 +#define FSMOUNT_CLOEXEC 0x00000001 +#define FSCONFIG_SET_FLAG 0 +#define FSCONFIG_SET_STRING 1 +#define FSCONFIG_CMD_CREATE 6 +#define FSCONFIG_CMD_RECONFIGURE 7 + +#define MOVE_MOUNT_F_SYMLINKS 0x00000001 +#define MOVE_MOUNT_F_AUTOMOUNTS 0x00000002 +#define MOVE_MOUNT_F_EMPTY_PATH 0x00000004 +#define MOVE_MOUNT_T_SYMLINKS 0x00000010 +#define MOVE_MOUNT_T_AUTOMOUNTS 0x00000020 +#define MOVE_MOUNT_T_EMPTY_PATH 0x00000040 +#define MOVE_MOUNT_BENEATH 0x00000200 + +#define MOUNT_ATTR_RDONLY 0x00000001 +#define MOUNT_ATTR_NOSUID 0x00000002 +#define MOUNT_ATTR_NODEV 0x00000004 +#define MOUNT_ATTR_NOEXEC 0x00000008 +#define MOUNT_ATTR__ATIME 0x00000070 +#define MOUNT_ATTR_NOATIME 0x00000010 +#define MOUNT_ATTR_STRICTATIME 0x00000020 +#define MOUNT_ATTR_NODIRATIME 0x00000080 +#define MOUNT_ATTR_NOSYMFOLLOW 0x00200000 + #endif diff --git a/kernel/sync/profile.c b/kernel/sync/profile.c index caf332f5..d1fca51d 100644 --- a/kernel/sync/profile.c +++ b/kernel/sync/profile.c @@ -268,6 +268,7 @@ uint32_t lock_profile_syscall_scope(uint64_t number) case LINUX_SYS_CHOWN: case LINUX_SYS_FCHOWN: case LINUX_SYS_LCHOWN: case LINUX_SYS_FCHOWNAT: case LINUX_SYS_UTIME: case LINUX_SYS_UTIMES: case LINUX_SYS_FUTIMESAT: case LINUX_SYS_UTIMENSAT: case LINUX_SYS_MOUNT: case LINUX_SYS_UMOUNT2: + case __NR_fsopen: case __NR_fsconfig: case __NR_fsmount: case __NR_move_mount: return LOCK_SCOPE_SYSCALL_IO; case LINUX_SYS_CLONE: case LINUX_SYS_CLONE3: case LINUX_SYS_FORK: case LINUX_SYS_VFORK: case LINUX_SYS_EXECVE: case LINUX_SYS_EXECVEAT: case LINUX_SYS_EXIT: case LINUX_SYS_EXIT_GROUP: diff --git a/kernel/syscall/dispatch.c b/kernel/syscall/dispatch.c index 1463f9ac..0209fc63 100644 --- a/kernel/syscall/dispatch.c +++ b/kernel/syscall/dispatch.c @@ -751,9 +751,9 @@ int64_t syscall_dispatch_regs_legacy(uint64_t number, uint64_t a0, uint64_t a1, number==LINUX_SYS_RENAME ? LINUX_AT_FDCWD : (int32_t)a2, number==LINUX_SYS_RENAME ? a1 : a3, number==LINUX_SYS_RENAMEAT2 ? (uint32_t)a4 : 0); - if (number == LINUX_SYS_MOUNT) - return syscall_legacy_filesystem(number, a0, a1, a2, a3, a4, a5); - if (number == LINUX_SYS_UMOUNT2) + if (number == LINUX_SYS_MOUNT || number == LINUX_SYS_UMOUNT2 || + number == __NR_fsopen || number == __NR_fsconfig || + number == __NR_fsmount || number == __NR_move_mount) return syscall_legacy_filesystem(number, a0, a1, a2, a3, a4, a5); if (number == LINUX_SYS_GETPID || number == LINUX_SYS_GETPPID || number == LINUX_SYS_SETPGID || number == LINUX_SYS_GETPGRP || diff --git a/kernel/syscall/entry.c b/kernel/syscall/entry.c index 8bfcf4a8..4d83531b 100644 --- a/kernel/syscall/entry.c +++ b/kernel/syscall/entry.c @@ -156,6 +156,7 @@ static int task_begin_syscall_io(struct task *task, uint64_t number, int32_t fd, uint64_t arg2) { bool file_io = (number==LINUX_SYS_MMAP && !((uint32_t)arg2&LINUX_MAP_ANONYMOUS)) || + number == __NR_fsconfig || number == __NR_fsmount || number == __NR_move_mount || number == __NR_pidfd_send_signal || number == LINUX_SYS_WAITID || number == LINUX_SYS_READ || number == LINUX_SYS_WRITE || number == LINUX_SYS_FINIT_MODULE || diff --git a/kernel/syscall/fd/descriptor.c b/kernel/syscall/fd/descriptor.c index 3e418a9f..41749ea8 100644 --- a/kernel/syscall/fd/descriptor.c +++ b/kernel/syscall/fd/descriptor.c @@ -13,6 +13,8 @@ extern void memory_wait_cancel(struct task *) __attribute__((weak)); /* Standalone descriptor fixtures may omit the inotify core. */ extern void fsnotify_put(struct fsnotify_instance *) __attribute__((weak)); +/* Standalone descriptor fixtures may omit the filesystem context implementation. */ +extern void syscall_fs_context_release(void *) __attribute__((weak)); static uint64_t proc_files; @@ -107,6 +109,8 @@ int clear_task_file_result(struct task_file *file) fsnotify_put((struct fsnotify_instance *)(uintptr_t)file->aux); if (file->kind == TASK_FILE_KIND_PIDFD) sched_task_pidfd_put((struct task_identity *)(uintptr_t)file->aux); + if (file->kind == TASK_FILE_KIND_FS_CONTEXT && file->aux && syscall_fs_context_release) + syscall_fs_context_release((void *)(uintptr_t)file->aux); if ((file->flags & TASK_FILE_FLAG_DEV_NODE) && (file->node.first_cluster == STORAGE_DEV_KIND_KEYBOARD || file->node.first_cluster == STORAGE_DEV_KIND_MOUSE) && diff --git a/kernel/syscall/fs/Kbuild b/kernel/syscall/fs/Kbuild index 7557b54c..84df314f 100644 --- a/kernel/syscall/fs/Kbuild +++ b/kernel/syscall/fs/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := create.o directory.o filesystem.o fs.o legacy_filesystem.o locks.o lookup_state.o metadata.o mount.o mutation.o path.o permissions.o size.o stat.o sync.o timestamps.o xattr.o +obj-y := create.o directory.o filesystem.o fs.o legacy_filesystem.o locks.o lookup_state.o metadata.o mount.o mount_api.o mutation.o path.o permissions.o size.o stat.o sync.o timestamps.o xattr.o include $(srctree)/scripts/Makefile.module diff --git a/kernel/syscall/fs/fs.c b/kernel/syscall/fs/fs.c index 220aa596..08f99c63 100644 --- a/kernel/syscall/fs/fs.c +++ b/kernel/syscall/fs/fs.c @@ -65,6 +65,7 @@ int syscall_fs_owns(uint64_t number) case LINUX_SYS_FLOCK: case LINUX_SYS_MOUNT: case LINUX_SYS_UMOUNT2: + case __NR_fsopen: case __NR_fsconfig: case __NR_fsmount: case __NR_move_mount: return 1; default: return 0; diff --git a/kernel/syscall/fs/legacy_filesystem.c b/kernel/syscall/fs/legacy_filesystem.c index 34265c6d..382fb35b 100644 --- a/kernel/syscall/fs/legacy_filesystem.c +++ b/kernel/syscall/fs/legacy_filesystem.c @@ -98,7 +98,8 @@ int64_t syscall_legacy_filesystem(uint64_t number, uint64_t a0, uint64_t a1, uin return old; } - if(number==LINUX_SYS_MOUNT || number==LINUX_SYS_UMOUNT2) { + if(number==LINUX_SYS_MOUNT || number==LINUX_SYS_UMOUNT2 || + number==__NR_fsopen || number==__NR_fsconfig || number==__NR_fsmount || number==__NR_move_mount) { struct task *task=sched_current_task(); return syscall_mount_control(task_lookup_namespace(task),task,number,a0,a1,a2,a3,a4); } diff --git a/kernel/syscall/fs/lookup_state.c b/kernel/syscall/fs/lookup_state.c index ad324148..b8fc793e 100644 --- a/kernel/syscall/fs/lookup_state.c +++ b/kernel/syscall/fs/lookup_state.c @@ -57,6 +57,7 @@ static bool lookup_path_call(uint64_t number) case __NR_access: case __NR_faccessat: case __NR_faccessat2: case __NR_utime: case __NR_utimes: case __NR_futimesat: case __NR_utimensat: case __NR_mknod: case __NR_mknodat: case __NR_mount: case __NR_umount2: + case __NR_fsopen: case __NR_fsconfig: case __NR_fsmount: case __NR_move_mount: case __NR_statfs: case __NR_fstatfs: case __NR_execve: case __NR_execveat: case __NR_bind: case __NR_connect: case __NR_sendto: case __NR_sendmsg: case __NR_sendmmsg: case __NR_ppoll: diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 8dd6343b..f4632460 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -220,6 +220,8 @@ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_ { if(!task || !(task->cap_effective&(1ULL< + +/* A context belongs to one open-file description, including its duplicates. */ +struct syscall_fs_context { + struct vfs_path root; + uint32_t uid, gid; + bool created, mounted; + int readonly_change; + char options[VFS_PATH_MAX]; +}; + +/** @copydoc syscall_fs_context_release */ +void syscall_fs_context_release(void *object) +{ + struct syscall_fs_context *context = object; + if (!context) return; + vfs_path_put(&context->root); + kernel_free(context); +} + +/** @brief Create a tmpfs configuration owned by a new descriptor. + * @param task Calling descriptor-table owner. @param type_user User filesystem name. + * @param flags Native fsopen flags. @return Descriptor or negative errno. + * Text survives lookup retries and failed allocation leaves no descriptor. + */ +static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t flags) +{ + if (flags & ~FSOPEN_CLOEXEC) return -RELIEFOS_EINVAL; + struct task_user_text type = {0}; + int rc = task_lookup_user_text(task, type_user, VFS_NAME_MAX + 1, false, &type); + if (rc) return rc; + if (__builtin_strcmp(type.text, "tmpfs")) rc = -RELIEFOS_ENODEV; + struct syscall_fs_context *context = NULL; + if (!rc) { + context = kernel_malloc(sizeof(*context)); + if (!context) rc = -RELIEFOS_ENOMEM; + } + if (!rc) { + *context = (struct syscall_fs_context){.uid = task->fsuid, .gid = task->fsgid}; + struct task_file *file = NULL; + int fd = task_allocate_fd(task, 0, &file); + if (fd < 0) rc = fd; + else { + file->kind = TASK_FILE_KIND_FS_CONTEXT; + file->node.type = RELIEFOS_FS_TYPE_DEVICE; + file->fd_flags = flags & FSOPEN_CLOEXEC ? RELIEFOS_FD_CLOEXEC : 0; + file->aux = (uint64_t)(uintptr_t)context; + rc = fd; + } + if (rc < 0) kernel_free(context); + } + kernel_free(type.allocation); + return rc; +} + +/** @brief Resolve the context pinned for an in-flight descriptor operation. + * @param task Calling task. @param fd Native descriptor. + * @param out Receives a borrowed context on success. + * @return Zero, EBADF for a missing descriptor or EINVAL for another kind. + */ +static int mount_api_context(struct task *task, int32_t fd, struct syscall_fs_context **out) +{ + *out = NULL; + struct task_file *file = task_file_for_io(task, fd); + if (!file) return -RELIEFOS_EBADF; + if (file->kind != TASK_FILE_KIND_FS_CONTEXT || !file->aux) return -RELIEFOS_EINVAL; + *out = (struct syscall_fs_context *)(uintptr_t)file->aux; + return 0; +} + +/** @brief Validate and queue one tmpfs parameter without partial state changes. + * @param task Caller with an optional retry scope. @param context Live context. + * @param command SET_FLAG or SET_STRING. @param key_user Required key. + * @param value_user String value or NULL for a flag. + * @return Zero or input, option, allocation or retry errno. + */ +static int mount_api_parameter(struct task *task, struct syscall_fs_context *context, + uint32_t command, uint64_t key_user, uint64_t value_user) +{ + struct task_user_text key = {0}, value = {0}; + int rc = task_lookup_user_text(task, key_user, VFS_NAME_MAX + 1, false, &key); + if (!rc && command == FSCONFIG_SET_STRING) + rc = task_lookup_user_text(task, value_user, VFS_PATH_MAX, false, &value); + if (rc) goto done; + if (command == FSCONFIG_SET_FLAG) { + if (!__builtin_strcmp(key.text, "ro")) context->readonly_change = 1; + else if (!__builtin_strcmp(key.text, "rw")) context->readonly_change = -1; + else rc = -RELIEFOS_EINVAL; + goto done; + } + + size_t key_length = __builtin_strlen(key.text), value_length = __builtin_strlen(value.text); + char option[128]; + if (!key_length || key_length + value_length + 2 > sizeof(option)) { + rc = -RELIEFOS_EINVAL; + goto done; + } + for (size_t i = 0; i < key_length; ++i) { + if (key.text[i] == ',' || key.text[i] == '=') { rc = -RELIEFOS_EINVAL; goto done; } + } + for (size_t i = 0; i < value_length; ++i) { + if (value.text[i] == ',') { rc = -RELIEFOS_EINVAL; goto done; } + } + __builtin_memcpy(option, key.text, key_length); + option[key_length] = '='; + __builtin_memcpy(option + key_length + 1, value.text, value_length + 1); + rc = tmpfs_validate_options(option); + if (rc) goto done; + size_t used = __builtin_strlen(context->options); + size_t extra = key_length + value_length + 1; + if (used + (used != 0) + extra + 1 > sizeof(context->options)) { + rc = -RELIEFOS_EINVAL; + goto done; + } + if (used) context->options[used++] = ','; + __builtin_memcpy(context->options + used, option, extra + 1); +done: + kernel_free(key.allocation); + kernel_free(value.allocation); + return rc; +} + +/** @brief Create or reconfigure the context's tmpfs transactionally. + * @param context Borrowed context. @param command CREATE or RECONFIGURE. + * @return Zero or negative state, option, busy or resource errno. + * Pending parameters are consumed only after a successful operation. + */ +static int mount_api_commit(struct syscall_fs_context *context, uint32_t command) +{ + int rc; + if (command == FSCONFIG_CMD_CREATE) { + if (context->created) return -RELIEFOS_EBUSY; + struct vfs_mount *mount = NULL; + uint64_t flags = context->readonly_change > 0 ? MS_RDONLY : 0; + rc = storage_new_tmpfs_mount("none", flags, context->options, + context->uid, context->gid, &mount); + if (!rc) rc = vfs_mount_detached_root(mount, &context->root); + vfs_mount_put(mount); + if (!rc) context->created = true; + } else { + if (!context->mounted) return -RELIEFOS_EBUSY; + uint64_t flags = vfs_path_mount_flags(&context->root); + if (context->readonly_change > 0) flags |= MS_RDONLY; + else if (context->readonly_change < 0) flags &= ~MS_RDONLY; + rc = vfs_path_remount_options(&context->root, flags, context->options); + } + if (!rc) { + context->options[0] = 0; + context->readonly_change = 0; + } + return rc; +} + +/** @brief Process one filesystem configuration request. + * @param task Calling task. @param fd Context descriptor. + * @param command Native fsconfig command. @param key User key or NULL. + * @param value User value or NULL. @param aux Auxiliary argument, required zero. + * @return Zero, negative errno or retry status, preserving state on failure. + */ +static int64_t mount_api_config(struct task *task, int32_t fd, uint32_t command, + uint64_t key, uint64_t value, int32_t aux) +{ + struct syscall_fs_context *context; + int rc = mount_api_context(task, fd, &context); + if (rc) return rc; + if (aux) return -RELIEFOS_EINVAL; + if (command == FSCONFIG_SET_FLAG || command == FSCONFIG_SET_STRING) { + if (!key || (command == FSCONFIG_SET_FLAG && value) || + (command == FSCONFIG_SET_STRING && !value)) return -RELIEFOS_EINVAL; + if (context->created && !context->mounted) return -RELIEFOS_EBUSY; + return mount_api_parameter(task, context, command, key, value); + } + if (command == FSCONFIG_CMD_CREATE || command == FSCONFIG_CMD_RECONFIGURE) { + if (key || value) return -RELIEFOS_EINVAL; + return mount_api_commit(context, command); + } + return -RELIEFOS_EOPNOTSUPP; +} + +/** @brief Materialize a configured filesystem as an O_PATH mount descriptor. + * @param task Calling descriptor-table owner. @param fd Configuration descriptor. + * @param flags Native fsmount flags. @param attributes Linux mount attributes. + * @return Descriptor or negative errno. All failed publications retire the + * clone and its path; the original context remains available for retry. + */ +static int64_t mount_api_mount(struct task *task, int32_t fd, uint32_t flags, uint32_t attributes) +{ + if (flags & ~FSMOUNT_CLOEXEC) return -RELIEFOS_EINVAL; + const uint32_t supported = MOUNT_ATTR_RDONLY | MOUNT_ATTR_NOSUID | MOUNT_ATTR_NODEV | + MOUNT_ATTR_NOEXEC | MOUNT_ATTR__ATIME | MOUNT_ATTR_NODIRATIME; + if (attributes & ~supported) return -RELIEFOS_EINVAL; + uint32_t atime = attributes & MOUNT_ATTR__ATIME; + if (atime != 0 && atime != MOUNT_ATTR_NOATIME && atime != MOUNT_ATTR_STRICTATIME) + return -RELIEFOS_EINVAL; + struct syscall_fs_context *context; + int rc = mount_api_context(task, fd, &context); + if (rc) return rc; + if (!context->created) return -RELIEFOS_EINVAL; + if (context->mounted) return -RELIEFOS_EBUSY; + uint64_t policy = 0; + if (attributes & MOUNT_ATTR_RDONLY) policy |= MS_RDONLY; + if (attributes & MOUNT_ATTR_NOSUID) policy |= MS_NOSUID; + if (attributes & MOUNT_ATTR_NODEV) policy |= MS_NODEV; + if (attributes & MOUNT_ATTR_NOEXEC) policy |= MS_NOEXEC; + if (attributes & MOUNT_ATTR_NODIRATIME) policy |= MS_NODIRATIME; + if (atime == MOUNT_ATTR_NOATIME) policy |= MS_NOATIME; + else if (atime == MOUNT_ATTR_STRICTATIME) policy |= MS_STRICTATIME; + else policy |= MS_RELATIME; + struct vfs_mount *mount = NULL; + struct vfs_path root = {0}; + rc = vfs_mount_clone_root(&context->root, &mount); + if (!rc) rc = vfs_mount_set_flags(mount, policy); + if (!rc) rc = vfs_mount_detached_root(mount, &root); + if (!rc) { + uint32_t open_flags = TASK_FILE_FLAG_PATH | (flags & FSMOUNT_CLOEXEC ? LINUX_O_CLOEXEC : 0); + rc = alloc_task_fd(task, vfs_path_node(&root), open_flags, NULL); + if (rc >= 0) { + task_file_bind_path(task_file_for_fd(task, rc), &root); + context->mounted = true; + } + } + vfs_path_put(&root); + vfs_mount_put(mount); + return rc; +} + +/** @brief Resolve and attach or move a held mount root. + * @param ns Caller namespace. @param task Caller with retry-stable lookups. + * @param from_fd Source directory descriptor. @param from Source user path. + * @param to_fd Destination directory descriptor. @param to Destination user path. + * @param flags Native move_mount flags. @return Zero or negative errno/retry. + */ +static int64_t mount_api_move(struct vfs_namespace *ns, struct task *task, int32_t from_fd, + uint64_t from, int32_t to_fd, uint64_t to, uint32_t flags) +{ + const uint32_t supported = MOVE_MOUNT_F_SYMLINKS | MOVE_MOUNT_F_AUTOMOUNTS | + MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_SYMLINKS | MOVE_MOUNT_T_AUTOMOUNTS | + MOVE_MOUNT_T_EMPTY_PATH; + if (flags & ~supported) return -RELIEFOS_EINVAL; + struct vfs_lookup_result source = {0}, target = {0}; + int rc = resolve_user_object_at_flags(ns, task, from_fd, from, + (flags & MOVE_MOUNT_F_EMPTY_PATH) != 0, false, + flags & MOVE_MOUNT_F_SYMLINKS ? VFS_LOOKUP_FOLLOW : 0, &source); + if (!rc) storage_release_task_io(task->pid); + if (!rc) rc = resolve_user_object_at_flags(ns, task, to_fd, to, + (flags & MOVE_MOUNT_T_EMPTY_PATH) != 0, false, + flags & MOVE_MOUNT_T_SYMLINKS ? VFS_LOOKUP_FOLLOW : 0, &target); + if (!rc) rc = vfs_mount_attach_path(ns, &source.path, &target.path); + vfs_path_put(&source.path); + vfs_path_put(&target.path); + return rc; +} + +/** @copydoc syscall_new_mount_control */ +int64_t syscall_new_mount_control(struct vfs_namespace *ns, struct task *task, uint64_t number, + uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4) +{ + if (number == __NR_fsopen) return mount_api_open(task, a0, (uint32_t)a1); + if (number == __NR_fsconfig) return mount_api_config(task, (int32_t)a0, (uint32_t)a1, a2, a3, (int32_t)a4); + if (number == __NR_fsmount) return mount_api_mount(task, (int32_t)a0, (uint32_t)a1, (uint32_t)a2); + if (number == __NR_move_mount) return mount_api_move(ns, task, (int32_t)a0, a1, (int32_t)a2, a3, (uint32_t)a4); + return -RELIEFOS_ENOSYS; +} diff --git a/kernel/syscall/internal.h b/kernel/syscall/internal.h index a779eeb5..dfe44d93 100644 --- a/kernel/syscall/internal.h +++ b/kernel/syscall/internal.h @@ -1395,6 +1395,21 @@ int64_t syscall_sync_object(struct vfs_namespace *ns,struct task *task,uint64_t int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_t number, uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4); +/** @brief Execute an admitted Linux filesystem-context or mount-fd operation. + * @param ns Retained caller namespace. @param task Authorized calling task. + * @param number Native syscall number. @param a0 First ABI argument. + * @param a1 Second ABI argument. @param a2 Third ABI argument. + * @param a3 Fourth ABI argument. @param a4 Fifth ABI argument. + * @return Descriptor, zero, negative errno or internal retry status. + */ +int64_t syscall_new_mount_control(struct vfs_namespace *ns,struct task *task,uint64_t number, + uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4); + +/** @brief Release the filesystem context owned by a final open-file description. + * @param context Owned context, nullable. Releases its retained filesystem root. + */ +void syscall_fs_context_release(void *context); + /** @brief Open a pathname against the actual task root/cwd/dirfd objects. * @param ns Borrowed system namespace under execution ownership. * @param task Borrowed current task and descriptor table. diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index b2e5d057..5194fa38 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -31,7 +31,7 @@ def test_real_tmpfs_without_text_routing(self): "fs/notify/core.c", "fs/notify/limits.c", "fs/notify/queue.c", "fs/notify/watch.c", "fs/vfs/filesystems.c", "fs/vfs/filesystem_instance.c", "fs/ext_common/journal.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/kernel_file.c", "fs/vfs/kernel_path.c", "fs/vfs/exec_file.c", "fs/vfs/attributes.c", "fs/vfs/initial.c", "fs/vfs/storage_initial.c", "fs/vfs/storage_attributes.c", "fs/vfs/storage_access.c", "fs/vfs/storage_backend.c", "fs/vfs/mutation.c", "fs/vfs/storage_mutation.c", "fs/vfs/storage_create.c", "fs/vfs/storage_security.c", "fs/vfs/write_access.c", "fs/devpts/devpts.c", "drivers/tty/pty/core.c", "drivers/tty/pty/ring.c", "drivers/tty/pty/line_discipline.c", "drivers/tty/pty/session.c", "drivers/tty/pty/vt.c", "kernel/syscall/device/device_open.c", "kernel/syscall/device/device_io.c", "kernel/syscall/fs/stat.c", "fs/vfs/storage_mount.c", "fs/vfs/fat_options.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/security/access.c", "lib/text_utf16.c", "fs/devfs/mount.c", "fs/devfs/devtmpfs.c", "fs/devfs/devtmpfs_nodes.c", "fs/devfs/device.c", "fs/devfs/identity.c", "fs/vfs/pseudo.c", "kernel/exec/runtime.c", "kernel/exec/pending.c", "kernel/syscall/process/exec.c", "kernel/syscall/system/user_string.c", - "kernel/syscall/ipc/unix_path.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/create.c", "kernel/syscall/fs/mount.c", "kernel/syscall/fs/mutation.c", "kernel/syscall/fs/directory.c", "kernel/syscall/fs/size.c", "kernel/syscall/fs/sync.c", "kernel/syscall/fs/path.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fd/descriptor.c", "kernel/syscall/fd/open.c", "kernel/device/character.c", "kernel/syscall/io/vector.c", "kernel/syscall/fd/pty_descriptor.c", "kernel/sched/tables.c", "kernel/device/mapping.c", "kernel/sched/fs.c", "kernel/sync/wait.c", "-o", str(binary) + "kernel/syscall/ipc/unix_path.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/create.c", "kernel/syscall/fs/mount.c", "kernel/syscall/fs/mount_api.c", "kernel/syscall/fs/mutation.c", "kernel/syscall/fs/directory.c", "kernel/syscall/fs/size.c", "kernel/syscall/fs/sync.c", "kernel/syscall/fs/path.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fd/descriptor.c", "kernel/syscall/fd/open.c", "kernel/device/character.c", "kernel/syscall/io/vector.c", "kernel/syscall/fd/pty_descriptor.c", "kernel/sched/tables.c", "kernel/device/mapping.c", "kernel/sched/fs.c", "kernel/sync/wait.c", "-o", str(binary) ], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=20) for filesystem in ("ext2", "ext4"): diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index a18f3941..cd0da43c 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2500,6 +2500,98 @@ static int64_t scoped_mount_call(struct vfs_namespace *ns,struct task *task,uint return rc; } +/** @brief Exercise the detached tmpfs lifecycle used by systemd credentials. */ +static void runtime_new_mount_api(struct vfs_namespace *ns,const struct vfs_path *root, + struct tmpfs_super *fs) +{ + struct { + char type[8],other_type[8],inodes[16],size[8],mode[8],noswap[8],ro[4]; + char count[8],bytes[16],permissions[8],target[32],empty[1],dot[2],credential[16]; + } user={"tmpfs","ramfs","nr_inodes","size","mode","noswap","ro", + "1024","1048576","0700","/new-mount-api","",".","credential"}; + struct task actor={.pid=906,.fsuid=1000,.fsgid=1000,.cap_effective=1ULL<nofile.rlim_cur=32; + vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + assert(!tmpfs_create(fs,user.target,LINUX_S_IFDIR|0755,NULL,NULL)); + + assert(scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.other_type,0,0,0,0)==-ENODEV); + assert(scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.type,2,0,0,0)==-EINVAL); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,31,6,0,0,0)==-EBADF); + actor.cap_effective=0; + assert(scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.type,0,0,0,0)==-EPERM); + actor.cap_effective=1ULL<=0); + assert(task_descriptor_for_fd(&actor,context)->fd_flags & RELIEFOS_FD_CLOEXEC); + int duplicate=task_duplicate_file_fd(&actor,context,0,0); + assert(duplicate>=0); + struct task_file *pin=task_file_get(task_file_for_fd(&actor,context)); + assert(pin); + actor.syscall_fd=context;actor.syscall_file=pin;actor.syscall_file_number=__NR_fsconfig; + task_discard_file_fd(&actor,context); + int replacement=scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.type,0,0,0,0); + assert(replacement==context && task_file_for_fd(&actor,replacement)!=pin); + assert(task_file_for_fd(&actor,duplicate)==pin); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1,(uintptr_t)user.inodes,(uintptr_t)user.count,0)); + actor.syscall_file=NULL;task_file_put(pin); + task_discard_file_fd(&actor,replacement); + context=duplicate; + assert(scoped_mount_call(ns,&actor,__NR_fsmount,context,0,0,0,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1,(uintptr_t)user.size,(uintptr_t)user.bytes,0)); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.noswap,0,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1,(uintptr_t)user.mode,(uintptr_t)user.permissions,0)); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)==-EBUSY); + test_fail_heap_after=0; + assert(scoped_mount_call(ns,&actor,__NR_fsmount,context,1,0x0e,0,0)==-ENOMEM); + test_fail_heap_after=-1; + sched_task_limits(&actor)->nofile.rlim_cur=0; + assert(scoped_mount_call(ns,&actor,__NR_fsmount,context,1,0x0e,0,0)==-EMFILE); + sched_task_limits(&actor)->nofile.rlim_cur=32; + /* NOSYMFOLLOW is optional and systemd retries after EINVAL. */ + assert(scoped_mount_call(ns,&actor,__NR_fsmount,context,1,0x20000e,0,0)==-EINVAL); + int mountfd=scoped_mount_call(ns,&actor,__NR_fsmount,context,1,0x0e,0,0); + assert(mountfd>=0); + struct task_file *mount_file=task_file_for_fd(&actor,mountfd); + assert(mount_file && vfs_path_node(&mount_file->path_ref)); + assert((vfs_path_mount_flags(&mount_file->path_ref)&(MS_NODEV|MS_NOSUID|MS_NOEXEC))== + (MS_NODEV|MS_NOSUID|MS_NOEXEC)); + int reopened=syscall_open_object(ns,&actor,mountfd,(uintptr_t)user.dot,LINUX_O_DIRECTORY,0); + assert(reopened>=0); + assert(vfs_path_equal(&task_file_for_fd(&actor,reopened)->path_ref,&mount_file->path_ref)); + struct vfs_path file={0};struct reliefos_permissions mode={0600,1000,1000};uint32_t done=0; + assert(!vfs_path_new_file(&mount_file->path_ref,"credential",&mode,&file)); + assert(!vfs_path_write(&file,0,"secret",6,&done) && done==6); + task_discard_file_fd(&actor,reopened); + int writer=syscall_open_object(ns,&actor,mountfd,(uintptr_t)user.credential,LINUX_O_RDWR,0); + assert(writer>=0); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.ro,0,0)); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,7,0,0,0)==-EBUSY); + assert(!vfs_path_write(&file,0,"s",1,&done)); + task_discard_file_fd(&actor,writer); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,7,0,0,0)); + assert(vfs_path_write(&file,0,"x",1,&done)==-EROFS); + assert(scoped_mount_call(ns,&actor,__NR_move_mount,mountfd,(uintptr_t)user.empty, + (uint32_t)LINUX_AT_FDCWD,(uintptr_t)user.target,0x204)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,__NR_move_mount,mountfd,(uintptr_t)user.empty, + (uint32_t)LINUX_AT_FDCWD,(uintptr_t)user.target,4)); + struct vfs_path attached={0},found={0}; + assert(!vfs_path_lookup(ns,root,root,user.target,0,&attached)); + assert(vfs_path_equal(&attached,&mount_file->path_ref)); + assert(!vfs_path_lookup(ns,root,&attached,"credential",0,&found)); + char text[8];assert(!vfs_path_read(&found,0,text,sizeof(text),&done) && done==6 && !memcmp(text,"secret",6)); + vfs_path_put(&found);vfs_path_put(&file); + task_discard_file_fd(&actor,context);task_discard_file_fd(&actor,mountfd); + assert(!vfs_mount_unmount(ns,&attached));vfs_path_put(&attached); + assert(!tmpfs_unlink(fs,user.target,true)); + vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + lookup_user_base=lookup_user_bytes=0; + puts("PASS new mount API: FD reuse, failed publication, readonly retry, reopen and attach"); +} + /** @brief Read a generated cgroup control by its retained inode and check exact bytes. */ static void cgroup_check_text(const struct vfs_path *directory,const char *name,const char *expected) { @@ -4240,6 +4332,7 @@ int main(int argc,char **argv) runtime_mount_objects(&ns,&root,fs); runtime_failed_teardown(); runtime_detached_mount(&ns,&root); + runtime_new_mount_api(&ns,&root,fs); runtime_attachment_policies(&ns,&root); runtime_mount_syscalls(&ns,&root,fs); runtime_file_bind(&ns,&root,fs); From 0404f4e1e671fd958274a874db5b11397242116a Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 13:18:16 +0800 Subject: [PATCH 26/97] feat(net): support classic BPF netlink socket filters --- .../LC_MESSAGES/userspace-api/descriptors.po | 16 ++ .../LC_MESSAGES/userspace-api/descriptors.po | 15 ++ Documentation/userspace-api/descriptors.rst | 6 + include/uapi/linux/socket.h | 2 + net/socket/Kbuild | 2 +- net/socket/filter.c | 244 ++++++++++++++++++ net/socket/filter.h | 29 +++ net/socket/netlink.c | 46 +++- tools/test_ipv6_control.py | 3 +- tools/test_net_multi_interface.py | 2 +- tools/tests/ipv6_control_test.c | 141 +++++++++- 11 files changed, 495 insertions(+), 11 deletions(-) create mode 100644 net/socket/filter.c create mode 100644 net/socket/filter.h diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index 3995fd9b..29ff80a0 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -265,6 +265,22 @@ msgstr "" "twice. UNIX ``accept`` does not inherit the listener's option. Netlink group " "membership, permissions, and filtering are unchanged." +msgid "" +"``AF_NETLINK`` 的 ``SO_ATTACH_FILTER`` 接受最多 4096 条经典 BPF 指令, " +"``SO_DETACH_FILTER`` 移除当前过滤器。过滤器在单播回复和多播通知入队前执行, " +"零返回值丢弃数据报,其他返回值限制接收长度。报文整数按网络字节序读取, " +"越界读取会丢弃数据报。支持数据报加载、暂存器、算术和前向跳转指令; " +"Linux 特有的辅助数据加载尚未实现。过滤器验证失败或分配失败时保留原过滤器。" +msgstr "" +"``SO_ATTACH_FILTER`` on ``AF_NETLINK`` accepts up to 4096 classic BPF " +"instructions, and ``SO_DETACH_FILTER`` removes the current filter. The filter " +"runs before unicast replies and multicast notifications are queued. A zero " +"return drops the datagram, and other return values limit its received length. " +"Packet integers are read in network byte order, and out-of-bounds reads drop " +"the datagram. Datagram loads, scratch memory, arithmetic and forward jumps are " +"supported. Linux-specific ancillary data loads are not yet implemented. A " +"validation or allocation failure leaves the previous filter in place." + msgid "" "TCP 的 ``setsockopt/getsockopt(SOL_TCP, TCP_NODELAY)`` 接受原生整数标志, " "默认关闭并由监听套接字传给新连接。关闭时,尚有未确认数据的小段等待确认或 完整 MSS " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index eaba945d..7b6867bd 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -228,6 +228,21 @@ msgstr "" "バインド規則は変わらず、UNIX アドレスと同一プロトコル内の netlink ポートの重複バインドはできません。" "UNIX の ``accept`` はリスナーの設定を継承しません。netlink のグループへの参加、権限、フィルタリングは変わりません。" +msgid "" +"``AF_NETLINK`` 的 ``SO_ATTACH_FILTER`` 接受最多 4096 条经典 BPF 指令, " +"``SO_DETACH_FILTER`` 移除当前过滤器。过滤器在单播回复和多播通知入队前执行, " +"零返回值丢弃数据报,其他返回值限制接收长度。报文整数按网络字节序读取, " +"越界读取会丢弃数据报。支持数据报加载、暂存器、算术和前向跳转指令; " +"Linux 特有的辅助数据加载尚未实现。过滤器验证失败或分配失败时保留原过滤器。" +msgstr "" +"``AF_NETLINK`` の ``SO_ATTACH_FILTER`` は最大 4096 個のクラシック BPF 命令を受け付け、" +"``SO_DETACH_FILTER`` は現在のフィルターを解除します。ユニキャスト応答とマルチキャスト通知を" +"キューに入れる前にフィルターを実行します。戻り値が 0 の場合はデータグラムを破棄し、" +"それ以外の場合は受信長を制限します。パケット内の整数はネットワークバイト順で読み、" +"範囲外の読み取りではデータグラムを破棄します。データグラムのロード、スクラッチメモリー、" +"算術演算、前方ジャンプをサポートします。Linux 固有の補助データのロードは未実装です。" +"検証またはメモリー確保に失敗した場合、元のフィルターを維持します。" + msgid "" "TCP 的 ``setsockopt/getsockopt(SOL_TCP, TCP_NODELAY)`` 接受原生整数标志, " "默认关闭并由监听套接字传给新连接。关闭时,尚有未确认数据的小段等待确认或 完整 MSS " diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index 24fa71a0..227b465e 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -114,6 +114,12 @@ TCP 的 ``recvfrom/recvmsg`` 支持 ``MSG_PEEK``:重复预读保留相同的 UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。 +``AF_NETLINK`` 的 ``SO_ATTACH_FILTER`` 接受最多 4096 条经典 BPF 指令, +``SO_DETACH_FILTER`` 移除当前过滤器。过滤器在单播回复和多播通知入队前执行, +零返回值丢弃数据报,其他返回值限制接收长度。报文整数按网络字节序读取, +越界读取会丢弃数据报。支持数据报加载、暂存器、算术和前向跳转指令; +Linux 特有的辅助数据加载尚未实现。过滤器验证失败或分配失败时保留原过滤器。 + TCP 的 ``setsockopt/getsockopt(SOL_TCP, TCP_NODELAY)`` 接受原生整数标志, 默认关闭并由监听套接字传给新连接。关闭时,尚有未确认数据的小段等待确认或 完整 MSS 后发送;启用时立即尝试发送已排队的小段,仍遵守对端窗口、拥塞窗口 diff --git a/include/uapi/linux/socket.h b/include/uapi/linux/socket.h index ad1f51fc..5f2f66bf 100644 --- a/include/uapi/linux/socket.h +++ b/include/uapi/linux/socket.h @@ -58,6 +58,8 @@ struct sockaddr_un { #define SO_SNDTIMEO_NEW 67 #define SO_ACCEPTCONN 30 #define SO_BINDTODEVICE 25 +#define SO_ATTACH_FILTER 26 +#define SO_DETACH_FILTER 27 #define SO_PROTOCOL 38 #define SO_DOMAIN 39 diff --git a/net/socket/Kbuild b/net/socket/Kbuild index 40d7bf90..1b7fd5d0 100644 --- a/net/socket/Kbuild +++ b/net/socket/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := control.o netlink.o packet.o udp.o +obj-y := control.o filter.o netlink.o packet.o udp.o include $(srctree)/scripts/Makefile.module diff --git a/net/socket/filter.c b/net/socket/filter.c new file mode 100644 index 00000000..7e730f0c --- /dev/null +++ b/net/socket/filter.c @@ -0,0 +1,244 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "filter.h" +#include +#include +#include +#include + +struct socket_filter { + uint32_t length; + struct sock_filter code[]; +}; + +_Static_assert(sizeof(struct sock_filter) == 8, "classic BPF instruction ABI"); +_Static_assert(sizeof(struct sock_fprog) == 16 && + __builtin_offsetof(struct sock_fprog, filter) == 8, + "native socket filter ABI"); + +/** @brief Check that a forward BPF jump reaches another instruction. + * @param index Current instruction index. @param offset Jump displacement. + * @param length Program instruction count. @return True for an in-range target. + */ +static bool filter_jump_valid(size_t index, uint32_t offset, size_t length) +{ + return index + 1 < length && offset < length - index - 1; +} + +/** @brief Check supported classic BPF instructions and initialized scratch memory. + * @param code Candidate instructions. @param length Number of instructions. + * @param paths Caller-owned array of length scratch-initialization masks. + * @return Zero for an admissible program or negative EINVAL. + */ +static int filter_validate(const struct sock_filter *code, size_t length, uint16_t *paths) +{ + __builtin_memset(paths, 0xff, length * sizeof(*paths)); + uint16_t initialized = 0; + for (size_t i = 0; i < length; ++i) { + const struct sock_filter *insn = &code[i]; + uint16_t op = insn->code; + initialized &= paths[i]; + switch (BPF_CLASS(op)) { + case BPF_LD: + if (op == (BPF_LD | BPF_W | BPF_IMM) || + op == (BPF_LD | BPF_W | BPF_LEN)) break; + if ((op == (BPF_LD | BPF_W | BPF_ABS) || + op == (BPF_LD | BPF_H | BPF_ABS) || + op == (BPF_LD | BPF_B | BPF_ABS) || + op == (BPF_LD | BPF_W | BPF_IND) || + op == (BPF_LD | BPF_H | BPF_IND) || + op == (BPF_LD | BPF_B | BPF_IND)) && (int32_t)insn->k >= 0) + break; + if (op == (BPF_LD | BPF_MEM) && insn->k < BPF_MEMWORDS && + (initialized & (1u << insn->k))) break; + return -LINUX_EINVAL; + case BPF_LDX: + if (op == (BPF_LDX | BPF_W | BPF_IMM) || + op == (BPF_LDX | BPF_W | BPF_LEN) || + (op == (BPF_LDX | BPF_B | BPF_MSH) && (int32_t)insn->k >= 0) || + (op == (BPF_LDX | BPF_MEM) && insn->k < BPF_MEMWORDS && + (initialized & (1u << insn->k)))) break; + return -LINUX_EINVAL; + case BPF_ST: + case BPF_STX: + if (op != BPF_CLASS(op) || insn->k >= BPF_MEMWORDS) return -LINUX_EINVAL; + initialized |= (uint16_t)(1u << insn->k); + break; + case BPF_ALU: { + uint16_t operation = BPF_OP(op); + if (op == (BPF_ALU | BPF_NEG)) break; + if (op != (BPF_ALU | operation | BPF_SRC(op))) return -LINUX_EINVAL; + if (operation != BPF_ADD && operation != BPF_SUB && operation != BPF_MUL && + operation != BPF_DIV && operation != BPF_MOD && operation != BPF_OR && + operation != BPF_AND && operation != BPF_LSH && operation != BPF_RSH && + operation != BPF_XOR) return -LINUX_EINVAL; + if (BPF_SRC(op) == BPF_K && + (((operation == BPF_DIV || operation == BPF_MOD) && !insn->k) || + ((operation == BPF_LSH || operation == BPF_RSH) && insn->k >= 32))) + return -LINUX_EINVAL; + break; + } + case BPF_JMP: { + uint16_t operation = BPF_OP(op); + if (op == (BPF_JMP | BPF_JA)) { + if (!filter_jump_valid(i, insn->k, length)) return -LINUX_EINVAL; + paths[i + 1 + insn->k] &= initialized; + } else { + if (op != (BPF_JMP | operation | BPF_SRC(op)) || + (operation != BPF_JEQ && operation != BPF_JGT && + operation != BPF_JGE && operation != BPF_JSET) || + !filter_jump_valid(i, insn->jt, length) || + !filter_jump_valid(i, insn->jf, length)) return -LINUX_EINVAL; + paths[i + 1 + insn->jt] &= initialized; + paths[i + 1 + insn->jf] &= initialized; + } + initialized = UINT16_MAX; + break; + } + case BPF_RET: + if (op != (BPF_RET | BPF_K) && op != (BPF_RET | BPF_A)) + return -LINUX_EINVAL; + initialized = UINT16_MAX; + break; + case BPF_MISC: + if (op != (BPF_MISC | BPF_TAX) && op != (BPF_MISC | BPF_TXA)) + return -LINUX_EINVAL; + break; + default: + return -LINUX_EINVAL; + } + } + uint16_t last = code[length - 1].code; + return last == (BPF_RET | BPF_K) || last == (BPF_RET | BPF_A) ? 0 : -LINUX_EINVAL; +} + +/** @brief Import and verify a native filter without publishing partial state. + * @param task Current task. @param address User sock_fprog address. + * @param length Socket option length. @param result Receives ownership on success. + * @return Zero, Linux errno or a private usercopy retry result. + */ +int socket_filter_import(struct task *task, uint64_t address, uint64_t length, + struct socket_filter **result) +{ + if ((int32_t)length != (int32_t)sizeof(struct sock_fprog)) return -LINUX_EINVAL; + struct sock_fprog program; + int error = socket_user_import(task, address, &program, sizeof(program)); + if (error) return error; + if (!program.len || program.len > BPF_MAXINSNS || !program.filter) return -LINUX_EINVAL; + + size_t bytes = program.len * sizeof(struct sock_filter); + struct socket_filter *filter = kernel_malloc(sizeof(*filter) + bytes); + uint16_t *paths = filter ? kernel_malloc(program.len * sizeof(*paths)) : NULL; + if (!paths) { + kernel_free(filter); + return -LINUX_ENOMEM; + } + filter->length = program.len; + error = socket_user_import(task, (uintptr_t)program.filter, filter->code, (uint32_t)bytes); + if (!error) error = filter_validate(filter->code, filter->length, paths); + kernel_free(paths); + if (error) { + kernel_free(filter); + return error; + } + *result = filter; + return 0; +} + +/** @brief Read a network-order integer from a bounded packet offset. + * @param data Datagram bytes. @param length Datagram length. + * @param offset Byte offset. @param width Access width, one, two or four. + * @param value Receives the host-order value. @return True when fully in bounds. + */ +static bool filter_read(const uint8_t *data, uint32_t length, uint32_t offset, + uint32_t width, uint32_t *value) +{ + if (offset > length || width > length - offset) return false; + uint32_t result = 0; + for (uint32_t i = 0; i < width; ++i) result = (result << 8) | data[offset + i]; + *value = result; + return true; +} + +/** @brief Interpret a verified program and cap its return to the datagram length. + * @param filter Borrowed filter, or NULL to pass the datagram. + * @param data Kernel-owned datagram. @param length Byte length. + * @return Admitted byte length, or zero for a dropped datagram. + */ +uint32_t socket_filter_run(const struct socket_filter *filter, const void *data, uint32_t length) +{ + if (!filter) return length; + uint32_t accumulator = 0, index = 0, scratch[BPF_MEMWORDS] = {0}; + uint32_t pc = 0; + const uint8_t *bytes = data; + while (pc < filter->length) { + const struct sock_filter *insn = &filter->code[pc]; + uint16_t op = insn->code; + uint32_t operand = BPF_SRC(op) == BPF_X ? index : insn->k; + switch (BPF_CLASS(op)) { + case BPF_LD: + if (BPF_MODE(op) == BPF_ABS || BPF_MODE(op) == BPF_IND) { + uint32_t offset = insn->k; + if (BPF_MODE(op) == BPF_IND) { + if (offset > UINT32_MAX - index) return 0; + offset += index; + } + uint32_t width = BPF_SIZE(op) == BPF_W ? 4 : BPF_SIZE(op) == BPF_H ? 2 : 1; + if (!filter_read(bytes, length, offset, width, &accumulator)) return 0; + } else if (BPF_MODE(op) == BPF_MEM) accumulator = scratch[insn->k]; + else if (BPF_MODE(op) == BPF_LEN) accumulator = length; + else accumulator = insn->k; + break; + case BPF_LDX: + if (BPF_MODE(op) == BPF_MSH) { + if (!filter_read(bytes, length, insn->k, 1, &index)) return 0; + index = (index & 15u) << 2; + } else if (BPF_MODE(op) == BPF_MEM) index = scratch[insn->k]; + else if (BPF_MODE(op) == BPF_LEN) index = length; + else index = insn->k; + break; + case BPF_ST: scratch[insn->k] = accumulator; break; + case BPF_STX: scratch[insn->k] = index; break; + case BPF_ALU: + switch (BPF_OP(op)) { + case BPF_ADD: accumulator += operand; break; + case BPF_SUB: accumulator -= operand; break; + case BPF_MUL: accumulator *= operand; break; + case BPF_DIV: if (!operand) return 0; accumulator /= operand; break; + case BPF_MOD: if (!operand) return 0; accumulator %= operand; break; + case BPF_OR: accumulator |= operand; break; + case BPF_AND: accumulator &= operand; break; + case BPF_LSH: accumulator <<= operand & 31u; break; + case BPF_RSH: accumulator >>= operand & 31u; break; + case BPF_NEG: accumulator = 0u - accumulator; break; + case BPF_XOR: accumulator ^= operand; break; + default: return 0; + } + break; + case BPF_JMP: + if (op == (BPF_JMP | BPF_JA)) pc += insn->k; + else { + bool take; + switch (BPF_OP(op)) { + case BPF_JEQ: take = accumulator == operand; break; + case BPF_JGT: take = accumulator > operand; break; + case BPF_JGE: take = accumulator >= operand; break; + case BPF_JSET: take = (accumulator & operand) != 0; break; + default: return 0; + } + pc += take ? insn->jt : insn->jf; + } + break; + case BPF_RET: { + uint32_t admitted = BPF_RVAL(op) == BPF_A ? accumulator : insn->k; + return admitted < length ? admitted : length; + } + case BPF_MISC: + if (op == (BPF_MISC | BPF_TAX)) index = accumulator; + else accumulator = index; + break; + default: return 0; + } + ++pc; + } + return 0; +} diff --git a/net/socket/filter.h b/net/socket/filter.h new file mode 100644 index 00000000..d6c6e196 --- /dev/null +++ b/net/socket/filter.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_SOCKET_FILTER_H +#define RELIEFNT_SOCKET_FILTER_H + +#include + +struct socket_filter; +struct task; + +/** @brief Import and verify a native classic BPF socket filter. + * @param task Current task under execution ownership. + * @param address User address of a native sock_fprog. + * @param length Socket option length. + * @param result Receives the owned filter only on success. + * @return Zero, Linux errno or a private usercopy retry result. + */ +int socket_filter_import(struct task *task, uint64_t address, uint64_t length, + struct socket_filter **result); + +/** @brief Run a verified filter over a complete datagram. + * @param filter Borrowed filter, or NULL to admit the whole datagram. + * @param data Kernel-owned datagram bytes. + * @param length Datagram length. + * @return Admitted length, including zero for a dropped datagram. + */ +uint32_t socket_filter_run(const struct socket_filter *filter, const void *data, + uint32_t length); + +#endif diff --git a/net/socket/netlink.c b/net/socket/netlink.c index 8d437416..506ee1b6 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -1,4 +1,5 @@ /* SPDX-License-Identifier: Apache-2.0 */ +#include "filter.h" #include /* Netlink state is owned by the ordinary kernel execution context. */ #include @@ -32,6 +33,7 @@ struct netlink_message { struct netlink_message *next; uint32_t length, groups; struct netlink_socket { struct netlink_socket *next; struct netlink_message *head, *tail; + struct socket_filter *filter; uint32_t port, queued_bytes, groups; int type, protocol; bool bound, connected, overrun, passcred; @@ -419,22 +421,29 @@ static void nl_overrun(uint32_t group) kernel_poll_readiness_notify(); } +/** @brief Filter and queue one multicast datagram for each matching subscriber. + * @param protocol Netlink protocol. @param group Linux group bit. + * @param data Kernel-owned datagram. @param length Datagram length. + */ static void nl_multicast(int protocol, uint32_t group, const void *data, uint32_t length) { bool notified = false; for (struct netlink_socket *s = netlink_sockets; s; s = s->next) { if (s->protocol != protocol || !(s->groups & group)) continue; + uint32_t admitted = socket_filter_run(s->filter, data, length); + if (!admitted) + continue; notified = true; struct netlink_message *message = NULL; if (s->queued_bytes <= NL_QUEUE_BUDGET - NL_MESSAGE_MAX) - message = kernel_malloc(sizeof(*message) + length); + message = kernel_malloc(sizeof(*message) + admitted); if (!message) { s->overrun = true; continue; } - *message = (struct netlink_message){.length = length, .groups = group}; - __builtin_memcpy(message->data, data, length); + *message = (struct netlink_message){.length = admitted, .groups = group}; + __builtin_memcpy(message->data, data, admitted); if (s->tail) s->tail->next = message; else @@ -964,7 +973,7 @@ static int nl_request(struct nl_builder *b, const struct nlmsghdr *h) return 0; } -/** @brief Process one complete kernel-bound datagram and queue bounded replies. +/** @brief Process one complete kernel-bound datagram and filter bounded replies. * @param file Pinned OFD. @param data Validated bytes. @param length Input length. * @param flags Linux send flags. @param address Optional user destination. * @param address_length Address length. @return Bytes accepted or errno. */ @@ -1035,16 +1044,19 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui kernel_free(bytes); message->next=NULL; message->length=builder.used; message->groups=0; struct netlink_message *replies[2]={message,completion}; + bool published = false; for (unsigned i=0;i<2;++i) { struct netlink_message *reply=replies[i]; if (!reply) continue; + reply->length = socket_filter_run(s->filter, reply->data, reply->length); if (!reply->length) { s->queued_bytes-=NL_MESSAGE_MAX; kernel_free(reply); continue; } if (s->tail) s->tail->next=reply; else s->head=reply; s->tail=reply; + published = true; } - kernel_poll_readiness_notify(); + if (published) kernel_poll_readiness_notify(); return (int)length; } @@ -1125,7 +1137,7 @@ int task_netlink_available(const struct task_file *file) return !s ? -LINUX_EBADF : s->head ? (int)s->head->length : 0; } -/** @brief Free final socket ownership and its queue. +/** @brief Free final socket ownership, its filter and queued datagrams. * @param file Final OFD. */ void task_netlink_release(struct task_file *file) { @@ -1141,6 +1153,7 @@ void task_netlink_release(struct task_file *file) if (!subscribers) nl_forget_snapshot(); } while (s->head) { struct netlink_message *m=s->head; s->head=m->next; kernel_free(m); } + kernel_free(s->filter); kernel_free(s); file->aux=0; } @@ -1168,7 +1181,8 @@ static int nl_export_address(struct task *task,uint64_t address,uint64_t length, * @param number Native syscall. @param a0 First argument. @param a1 Second argument. * @param a2 Third argument. @param a3 Fourth argument. @param a4 Fifth argument. * @param a5 Sixth argument. @return Syscall result or negative errno. - * @note SO_REUSEADDR stores per-socket state without allowing duplicate ports. */ + * @note SO_REUSEADDR stores per-socket state without allowing duplicate ports. + * Filter replacement is published only after the candidate is fully validated. */ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, uint64_t a3,uint64_t a4,uint64_t a5) { @@ -1237,6 +1251,24 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, } if (a1!=SOL_SOCKET) return -LINUX_ENOPROTOOPT; if (number == __NR_setsockopt) { + if (a2 == SO_ATTACH_FILTER) { + struct socket_filter *filter; + int rc = socket_filter_import(task, a3, a4, &filter); + if (rc) return rc; + kernel_free(s->filter); + s->filter = filter; + return 0; + } + if (a2 == SO_DETACH_FILTER) { + if ((int32_t)a4 < (int32_t)sizeof(int32_t)) return -LINUX_EINVAL; + int32_t ignored; + int rc = socket_user_import(task, a3, &ignored, sizeof(ignored)); + if (rc) return rc; + if (!s->filter) return -LINUX_ENOENT; + kernel_free(s->filter); + s->filter = NULL; + return 0; + } if (a2 != SO_REUSEADDR && (a2 != SO_PASSCRED || s->protocol != NETLINK_KOBJECT_UEVENT)) return -LINUX_ENOPROTOOPT; if ((int32_t)a4 < (int32_t)sizeof(int32_t)) diff --git a/tools/test_ipv6_control.py b/tools/test_ipv6_control.py index 69ad5177..c7b7498d 100644 --- a/tools/test_ipv6_control.py +++ b/tools/test_ipv6_control.py @@ -12,5 +12,6 @@ "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", - "tools/tests/ipv6_control_test.c", "-o", str(binary)], cwd=root, check=True) + "tools/tests/ipv6_control_test.c", "net/socket/filter.c", + "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) diff --git a/tools/test_net_multi_interface.py b/tools/test_net_multi_interface.py index 76701707..fb10cdc2 100644 --- a/tools/test_net_multi_interface.py +++ b/tools/test_net_multi_interface.py @@ -11,6 +11,6 @@ "-fno-sanitize-recover=all", "-fno-pie", "-no-pie", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude/uapi", "tools/tests/net_multi_interface_test.c", "net/interface/state.c", - "net/interface/routes.c", "net/interface/ioctl.c", "net/utility.c", + "net/interface/routes.c", "net/interface/ioctl.c", "net/utility.c", "net/socket/filter.c", "-o", str(binary)], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=15) diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 59125658..a75951e9 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -3,6 +3,7 @@ #include #include #include +#include #if __has_include("../../net/socket/netlink.c") #include "../../net/socket/netlink.c" #include "../../net/interface/state.c" @@ -14,12 +15,20 @@ static struct task current; static struct task_file files[4]; static unsigned allocations, updates, link_changes; +static int allocation_fail_after = -1; static bool additional_address; static bool nic_ready=true; static bool nic_present=true; struct net_socket *net_sockets; struct task *sched_current_task(void) { return ¤t; } -void *kernel_malloc(size_t bytes) { ++allocations; return calloc(1, bytes); } +void *kernel_malloc(size_t bytes) +{ + if (allocation_fail_after == 0) return NULL; + if (allocation_fail_after > 0) --allocation_fail_after; + void *memory = calloc(1, bytes); + if (memory) ++allocations; + return memory; +} void kernel_free(void *p) { if (p) { assert(allocations); --allocations; free(p); } } uint64_t time_ticks(void) { return 100; } uint64_t time_uptime_ms(void) { return 1000; } @@ -206,10 +215,140 @@ static void check_netlink_reuseaddr(void) puts("PASS route and kobject netlink SO_REUSEADDR: state and exclusive port binding"); } +/** @brief Exercise filter installation and message delivery on both netlink protocols. */ +static void check_netlink_filter(void) +{ + int monitor = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT, 0, 0); + int route = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(monitor >= 0 && route >= 0); + struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_groups = 1}; + assert(!call(__NR_bind, monitor, (uintptr_t)&address, sizeof(address), 0, 0)); + + struct sock_filter match[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, 4), + BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xffff0000), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x12340000, 0, 1), + BPF_STMT(BPF_RET | BPF_K, 9), + BPF_STMT(BPF_RET | BPF_K, 0), + }; + struct sock_fprog program = {.len = sizeof(match) / sizeof(match[0]), .filter = match}; + uintptr_t data = (uintptr_t)&program; + int value = 0; + assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program) - 1) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, 0, sizeof(program)) == -LINUX_EFAULT); + assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_DETACH_FILTER, (uintptr_t)&value, 0) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_DETACH_FILTER, 0, sizeof(value)) == -LINUX_EFAULT); + assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_DETACH_FILTER, (uintptr_t)&value, sizeof(value)) == -LINUX_ENOENT); + assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program))); + + uint8_t payload[] = {0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0xaa, 0xbb, 0xcc, 0xdd}; + uint8_t output[64]; + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + assert(receive(monitor, output, sizeof(output)) == 9); + assert(!memcmp(output, payload, 9)); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, 7); + assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); + payload[4] = 0x21; + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); + payload[4] = 0x12; + + struct sock_filter arithmetic[] = { + BPF_STMT(BPF_LDX | BPF_W | BPF_IMM, 1), + BPF_STMT(BPF_LD | BPF_H | BPF_IND, 3), + BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 15), + BPF_STMT(BPF_ST, 0), + BPF_STMT(BPF_LD | BPF_W | BPF_LEN, 0), + BPF_STMT(BPF_LDX | BPF_MEM, 0), + BPF_STMT(BPF_ALU | BPF_SUB | BPF_X, 0), + BPF_STMT(BPF_ALU | BPF_ADD | BPF_K, 1), + BPF_STMT(BPF_RET | BPF_A, 0), + }; + struct sock_fprog expression = {.len = sizeof(arithmetic) / sizeof(arithmetic[0]), .filter = arithmetic}; + assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&expression, sizeof(expression))); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + assert(receive(monitor, output, sizeof(output)) == 9); + struct sock_filter invalid_path[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_IMM, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 1, 0), + BPF_STMT(BPF_ST, 0), + BPF_STMT(BPF_LD | BPF_MEM, 0), + BPF_STMT(BPF_RET | BPF_A, 0), + }; + struct sock_fprog bad_path = {.len = sizeof(invalid_path) / sizeof(invalid_path[0]), .filter = invalid_path}; + assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&bad_path, sizeof(bad_path)) == -LINUX_EINVAL); + struct sock_filter bad_jump[] = { + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 3, 0), + BPF_STMT(BPF_RET | BPF_K, 0), + }; + struct sock_fprog jump = {.len = 2, .filter = bad_jump}; + assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&jump, sizeof(jump)) == -LINUX_EINVAL); + struct sock_filter divide[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_IMM, 1), + BPF_STMT(BPF_LDX | BPF_W | BPF_IMM, 0), + BPF_STMT(BPF_ALU | BPF_DIV | BPF_X, 0), + BPF_STMT(BPF_RET | BPF_K, 9), + }; + struct sock_fprog zero_divisor = {.len = 4, .filter = divide}; + assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&zero_divisor, sizeof(zero_divisor))); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); + assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program))); + + struct sock_filter invalid[] = {BPF_STMT(BPF_LD | BPF_W | BPF_IMM, 0)}; + struct sock_fprog bad = {.len = 1, .filter = invalid}; + assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&bad, sizeof(bad)) == -LINUX_EINVAL); + for (int fail = 0; fail < 2; ++fail) { + allocation_fail_after = fail; + assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program)) == -LINUX_ENOMEM); + allocation_fail_after = -1; + } + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + assert(receive(monitor, output, sizeof(output)) == 9); + assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_DETACH_FILTER, (uintptr_t)&value, sizeof(value))); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + assert(receive(monitor, output, sizeof(output)) == (int)sizeof(payload)); + + struct sock_filter reject[] = {BPF_STMT(BPF_RET | BPF_K, 0)}; + struct sock_filter truncate[] = {BPF_STMT(BPF_RET | BPF_K, 4)}; + struct sock_fprog route_filter = {.len = 1, .filter = reject}; + struct { struct nlmsghdr header; struct ifinfomsg info; } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_GETLINK, + .nlmsg_flags = NLM_F_REQUEST}, + .info = {.ifi_index = 1}, + }; + address = (struct sockaddr_nl){.nl_family = AF_NETLINK, .nl_groups = RTMGRP_IPV6_IFADDR}; + assert(!call(__NR_bind, route, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(!call(__NR_setsockopt, route, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&route_filter, sizeof(route_filter))); + additional_address = true; + netlink_ipv6_changed(); + assert(receive(route, output, sizeof(output)) == -LINUX_EAGAIN); + assert(send_req(route, &request, sizeof(request)) == sizeof(request)); + assert(receive(route, output, sizeof(output)) == -LINUX_EAGAIN); + request.header.nlmsg_flags |= NLM_F_DUMP; + assert(send_req(route, &request, sizeof(request)) == sizeof(request)); + assert(receive(route, output, sizeof(output)) == -LINUX_EAGAIN); + assert(nl_socket(&files[route])->queued_bytes == 0); + request.header.nlmsg_flags = NLM_F_REQUEST; + route_filter.filter = truncate; + assert(!call(__NR_setsockopt, route, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&route_filter, sizeof(route_filter))); + additional_address = false; + netlink_ipv6_changed(); + assert(receive(route, output, sizeof(output)) == 4); + assert(send_req(route, &request, sizeof(request)) == sizeof(request)); + route_filter.filter = reject; + assert(!call(__NR_setsockopt, route, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&route_filter, sizeof(route_filter))); + assert(receive(route, output, sizeof(output)) == 4); + task_netlink_release(&files[route]); files[route] = (struct task_file){0}; + task_netlink_release(&files[monitor]); files[monitor] = (struct task_file){0}; + puts("PASS netlink socket filters: admission, multicast, unicast, rollback and release"); +} + int main(void) { check_netlink_reuseaddr(); assert(!net_interface_register(2)); + check_netlink_filter(); net_config.local_ip=0x0a00020f; net_config.subnet_mask=0xffffff00; int fd = (int)call(__NR_socket,AF_NETLINK,SOCK_RAW|SOCK_NONBLOCK,NETLINK_ROUTE,0,0); assert(fd >= 0 && files[fd].socket_ino); From b0988406f5b679c7e508788f845a8f5cd8634d3b Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 13:26:03 +0800 Subject: [PATCH 27/97] feat(process): support realtime priority resource limits --- .../en/LC_MESSAGES/userspace-api/procfs.po | 9 +++-- .../ja/LC_MESSAGES/userspace-api/procfs.po | 6 +-- Documentation/userspace-api/procfs.rst | 5 ++- fs/proc/views.c | 9 +++-- include/reliefnt/task/types.h | 1 + kernel/sched/task.c | 5 ++- kernel/syscall/process/process.c | 6 +++ tools/tests/Makefile | 2 +- tools/tests/procfs_views_test.c | 14 +++++++ tools/tests/resource_limits_test.c | 39 +++++++++++++++++++ tools/tests/task8_clone_tid_real_test.c | 24 ++++++++++-- tools/tests/task8_host_fixtures.json | 2 + 12 files changed, 103 insertions(+), 19 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po index ad1f4d99..a6158627 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po @@ -210,11 +210,12 @@ msgstr "" msgid "``limits``" msgstr "``limits``" -msgid "内核支持的八项资源限制:文件数、地址空间、待处理信号、栈、进程数、 core 大小、锁定内存和普通文件大小;不虚构其他 rlimit。" +msgid "展示内核支持的九项资源限制:文件数、地址空间、待处理信号、栈、进程数、 core 大小、锁定内存、普通文件大小和实时优先级。实时优先级限制支持查询、 修改与继承,实时调度策略尚未实现。" msgstr "" -"The eight resource limits supported by the kernel: file count, address space, pending signals, " -"stack, process count, core size, locked memory, and regular file size. No other rlimits are " -"fabricated." +"Displays nine resource limits supported by the kernel: file count, address space, pending " +"signals, stack, process count, core size, locked memory, regular file size, and realtime " +"priority. The realtime-priority limit can be queried, modified, and inherited. Realtime " +"scheduling policies have not yet been implemented." msgid "``auxv``" msgstr "``auxv``" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po index 7552872d..7a351c84 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po @@ -184,10 +184,10 @@ msgstr "" msgid "``limits``" msgstr "``limits``" -msgid "内核支持的八项资源限制:文件数、地址空间、待处理信号、栈、进程数、 core 大小、锁定内存和普通文件大小;不虚构其他 rlimit。" +msgid "展示内核支持的九项资源限制:文件数、地址空间、待处理信号、栈、进程数、 core 大小、锁定内存、普通文件大小和实时优先级。实时优先级限制支持查询、 修改与继承,实时调度策略尚未实现。" msgstr "" -"カーネルが対応する 8 つのリソース制限:ファイル数、アドレス空間、保留シグナル、スタック、プロセス数、core サイズ、ロック済みメモリー、通常ファイルサイズ。他の rlimit " -"は捏造しません。" +"カーネルが対応する 9 つのリソース制限を表示します。ファイル数、アドレス空間、保留シグナル、スタック、プロセス数、core サイズ、ロック済みメモリー、通常ファイルサイズ、リアルタイム優先度です。" +"リアルタイム優先度の制限は取得、変更、継承が可能です。リアルタイムスケジューリングポリシーはまだ実装されていません。" msgid "``auxv``" msgstr "``auxv``" diff --git a/Documentation/userspace-api/procfs.rst b/Documentation/userspace-api/procfs.rst index 55d87219..83612293 100644 --- a/Documentation/userspace-api/procfs.rst +++ b/Documentation/userspace-api/procfs.rst @@ -86,8 +86,9 @@ flush 的独立统计行/扩展字段。同步统计不分配内存;异步记 - 逐区域或汇总的 RSS/PSS、共享/私有 clean/dirty、Referenced、Anonymous、 Locked;swap 和未支持的匿名大页统计为零。 * - ``limits`` - - 内核支持的八项资源限制:文件数、地址空间、待处理信号、栈、进程数、 - core 大小、锁定内存和普通文件大小;不虚构其他 rlimit。 + - 展示内核支持的九项资源限制:文件数、地址空间、待处理信号、栈、进程数、 + core 大小、锁定内存、普通文件大小和实时优先级。实时优先级限制支持查询、 + 修改与继承,实时调度策略尚未实现。 * - ``auxv`` - exec 构造的二进制 ``uint64_t type, value`` 数组,包括 ``AT_NULL``; 不是文本,也不重新读取可能被用户修改的栈。 diff --git a/fs/proc/views.c b/fs/proc/views.c index 801bd757..3bfbe210 100644 --- a/fs/proc/views.c +++ b/fs/proc/views.c @@ -302,7 +302,7 @@ static void status(struct task *t, struct text_stream *s) text_string(s, "\n"); proc_task_identity_fields(t, s); } -/** @brief Emit the resource limits actually enforced/stored by the kernel. +/** @brief Emit the kernel's stored resource limits, including realtime priority. * @param t Live target. @param s Required stream; query never changes limits. */ static void limits(struct task *t, struct text_stream *s) @@ -310,10 +310,11 @@ static void limits(struct task *t, struct text_stream *s) struct task_rlimit_state *l = sched_task_limits(t); const char *names[] = {"Max open files", "Max address space", "Max pending signals", "Max stack size", "Max processes", "Max core file size", - "Max locked memory", "Max file size"}; - const char *units[] = {"files", "bytes", "signals", "bytes", "processes", "bytes", "bytes", "bytes"}; + "Max locked memory", "Max file size", "Max realtime priority"}; + const char *units[] = {"files", "bytes", "signals", "bytes", "processes", "bytes", "bytes", "bytes", ""}; struct linux_rlimit64 *values[] = {&l->nofile, &l->as, &l->sigpending, &l->stack, - &l->nproc, &l->core, &l->memlock, &l->fsize}; + &l->nproc, &l->core, &l->memlock, &l->fsize, + &l->rtprio}; text_string(s, "Limit Soft Limit Hard Limit Units\n"); for (unsigned i = 0; i < sizeof(values) / sizeof(values[0]); ++i) { text_string(s, names[i]); diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index 864403c2..b7f2f6a1 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -457,6 +457,7 @@ struct task_rlimit_state { struct linux_rlimit64 core; struct linux_rlimit64 memlock; struct linux_rlimit64 fsize; + struct linux_rlimit64 rtprio; }; struct sysv_sem_array; diff --git a/kernel/sched/task.c b/kernel/sched/task.c index 8b5d181a..09e7dd41 100644 --- a/kernel/sched/task.c +++ b/kernel/sched/task.c @@ -135,7 +135,8 @@ void task_release_limits(struct task *task) } /** - * @brief Initialize native resource defaults without allocating shared limit state. + * @brief Initialize native resource defaults, including a zero realtime limit. + * Does not allocate shared limit state. * @param task Fresh task whose private limits receive memory-scaled defaults. */ static void task_init_limits(struct task *task) @@ -152,6 +153,8 @@ static void task_init_limits(struct task *task) /* INIT_RLIMITS includes CORE even when CONFIG_COREDUMP is disabled. */ .core = {0, LINUX_RLIM_INFINITY}, .fsize = {LINUX_RLIM_INFINITY, LINUX_RLIM_INFINITY}, + /* Linux's initial realtime-priority limit is zero. */ + .rtprio = {0, 0}, /* Linux v6.14 resource.h MLOCK_LIMIT / INIT_RLIMITS. */ .memlock = {8ULL * 1024ULL * 1024ULL, 8ULL * 1024ULL * 1024ULL}, .as = {LINUX_RLIM_INFINITY, LINUX_RLIM_INFINITY}, diff --git a/kernel/syscall/process/process.c b/kernel/syscall/process/process.c index f043e657..b10a710f 100644 --- a/kernel/syscall/process/process.c +++ b/kernel/syscall/process/process.c @@ -59,6 +59,11 @@ static int process_prepare_user(struct task *task, uint64_t address, uint64_t si * @brief Implement Linux get/set/prlimit ordering and process-wide limit updates. * Input is captured before an overlapping old-limit output is written. Linux * commits the update before reporting an old-limit copy fault; preserve that. + * RTPRIO is stored and inherited even while realtime scheduling is unavailable. + * @param number Resource-limit syscall number. + * @param a0 First syscall argument. @param a1 Second syscall argument. + * @param a2 Third syscall argument. @param a3 Fourth syscall argument. + * @return Zero on success, or a negative Linux errno or retry sentinel. */ static int64_t process_resource_limit(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3) @@ -124,6 +129,7 @@ static int64_t process_resource_limit(uint64_t number, uint64_t a0, uint64_t a1, else if (resource == LINUX_RLIMIT_CORE) stored = &limits->core; else if (resource == LINUX_RLIMIT_MEMLOCK) stored = &limits->memlock; else if (resource == LINUX_RLIMIT_FSIZE) stored = &limits->fsize; + else if (resource == LINUX_RLIMIT_RTPRIO) stored = &limits->rtprio; else return -LINUX_ENOSYS; if (setting && next.rlim_max > stored->rlim_max && !(caller->cap_effective & (1ULL << CAP_SYS_RESOURCE))) return -LINUX_EPERM; diff --git a/tools/tests/Makefile b/tools/tests/Makefile index 1774226f..6006c10d 100644 --- a/tools/tests/Makefile +++ b/tools/tests/Makefile @@ -15,7 +15,7 @@ test-host-smoke: --suite acpi_pm_timer --suite apic_timer --suite cpu_accounting \ --suite fat_async_read --suite fat_read_split \ --suite squashfs --suite squashfs_boot \ - --suite linux_pty --suite mount_backend --suite mount_namespace_task --suite cgroup_scheduler \ + --suite linux_pty --suite linux_resources --suite mount_backend --suite mount_namespace_task --suite cgroup_scheduler \ --suite linux_socket_batches --suite ipv6_control \ --suite vdso_mapping --suite vdso_time diff --git a/tools/tests/procfs_views_test.c b/tools/tests/procfs_views_test.c index 8ffb33dc..06491e35 100644 --- a/tools/tests/procfs_views_test.c +++ b/tools/tests/procfs_views_test.c @@ -312,6 +312,20 @@ int main(void) assert(!strcmp(output, "2\t0\t18446744073709551615\n")); read_all("/proc/self/limits"); assert(strstr(output, "Max open files")); + const char *realtime = strstr(output, "Max realtime priority"); + unsigned long long realtime_soft, realtime_hard; + assert(realtime && sscanf(realtime, "Max realtime priority %llu %llu", + &realtime_soft, &realtime_hard) == 2); + assert(realtime_soft == 0 && realtime_hard == 0); + current.limits.rtprio = (struct linux_rlimit64){23, 45}; + extra_tasks[0] = (struct task){.pid = 100, .tgid = 42, .shared_limits = ¤t.limits}; + visible_tasks = 2; + read_all("/proc/42/task/100/limits"); + realtime = strstr(output, "Max realtime priority"); + assert(realtime && sscanf(realtime, "Max realtime priority %llu %llu", + &realtime_soft, &realtime_hard) == 2); + assert(realtime_soft == 23 && realtime_hard == 45); + visible_tasks = 1; current.proc_read_chars = 123; current.proc_write_calls = 3; current.proc_write_bytes = 4096; diff --git a/tools/tests/resource_limits_test.c b/tools/tests/resource_limits_test.c index fde2d5c8..e302367f 100644 --- a/tools/tests/resource_limits_test.c +++ b/tools/tests/resource_limits_test.c @@ -34,6 +34,45 @@ int main(void) task_credentials_prepare(&caller, 1000, 100, 1000, 100, 7); assert(shared.nondumpable); caller = (struct task){0}; + /* systemd RestrictRealtime queries and sets the process-wide RTPRIO limit. */ + struct linux_rlimit64 realtime = {0, 0}, realtime_old; + assert(process_resource_limit(LINUX_SYS_GETRLIMIT, LINUX_RLIMIT_RTPRIO, + (uintptr_t)&realtime_old, 0, 0) == 0); + assert(realtime_old.rlim_cur == 0 && realtime_old.rlim_max == 0); + assert(process_resource_limit(LINUX_SYS_PRLIMIT64, 0, LINUX_RLIMIT_RTPRIO, + (uintptr_t)&realtime, 0) == 0); + realtime = (struct linux_rlimit64){20, 40}; + assert(process_resource_limit(LINUX_SYS_SETRLIMIT, LINUX_RLIMIT_RTPRIO, + (uintptr_t)&realtime, 0, 0) == -LINUX_EPERM); + caller.cap_effective = 1ULL << CAP_SYS_RESOURCE; + assert(process_resource_limit(LINUX_SYS_SETRLIMIT, LINUX_RLIMIT_RTPRIO, + (uintptr_t)&realtime, 0, 0) == 0); + caller.cap_effective = 0; + target = caller; + target.shared_limits = &caller.limits; + realtime = (struct linux_rlimit64){15, 40}; + assert(process_resource_limit(LINUX_SYS_PRLIMIT64, 7, LINUX_RLIMIT_RTPRIO, + (uintptr_t)&realtime, (uintptr_t)&realtime_old) == 0); + assert(realtime_old.rlim_cur == 20 && realtime_old.rlim_max == 40); + assert(process_resource_limit(LINUX_SYS_GETRLIMIT, LINUX_RLIMIT_RTPRIO, + (uintptr_t)&realtime_old, 0, 0) == 0); + assert(realtime_old.rlim_cur == 15 && realtime_old.rlim_max == 40); + realtime = (struct linux_rlimit64){41, 40}; + assert(process_resource_limit(LINUX_SYS_SETRLIMIT, LINUX_RLIMIT_RTPRIO, + (uintptr_t)&realtime, 0, 0) == -LINUX_EINVAL); + realtime = (struct linux_rlimit64){16, 41}; + assert(process_resource_limit(LINUX_SYS_SETRLIMIT, LINUX_RLIMIT_RTPRIO, + (uintptr_t)&realtime, 0, 0) == -LINUX_EPERM); + target.limits = *sched_task_limits(&caller); + target.shared_limits = NULL; + realtime = (struct linux_rlimit64){0, 0}; + assert(process_resource_limit(LINUX_SYS_SETRLIMIT, LINUX_RLIMIT_RTPRIO, + (uintptr_t)&realtime, 0, 0) == 0); + assert(process_resource_limit(LINUX_SYS_PRLIMIT64, 7, LINUX_RLIMIT_RTPRIO, + 0, (uintptr_t)&realtime_old) == 0); + assert(realtime_old.rlim_cur == 15 && realtime_old.rlim_max == 40); + caller = (struct task){0}; + target = (struct task){0}; struct linux_rlimit64 core = {0, 0}, core_old; assert(process_resource_limit(LINUX_SYS_GETRLIMIT, LINUX_RLIMIT_CORE, (uintptr_t)&core_old, 0, 0) == 0); diff --git a/tools/tests/task8_clone_tid_real_test.c b/tools/tests/task8_clone_tid_real_test.c index bc889a2c..531d8c10 100644 --- a/tools/tests/task8_clone_tid_real_test.c +++ b/tools/tests/task8_clone_tid_real_test.c @@ -45,14 +45,17 @@ static uint32_t child_word(struct task *task,uint64_t address) * @param shared Clone shares the parent's address space. * @param vfork Clone also blocks the parent until child completion. * @param child_cross Child TID crosses two independently COW pages. + * @param thread Clone joins the parent's thread group and shares limits. */ -static void run_case(bool shared,bool vfork,bool child_cross) +static void run_case(bool shared,bool vfork,bool child_cross,bool thread) { struct sched_task_object parent_object={0},child_object={0}; struct task *parent=&parent_object.task,*child=&child_object.task; task_zero(parent);task_zero(child); parent->pid=parent->tgid=801;parent->kind=TASK_KIND_USER; parent->state=TASK_RUNNING;parent->running_cpu=0;task_init_limits(parent); + assert(parent->limits.rtprio.rlim_cur==0 && parent->limits.rtprio.rlim_max==0); + parent->limits.rtprio=(struct linux_rlimit64){7,30}; child->state=TASK_EXITED;child->running_cpu=SCHED_CPU_NONE; child->flags=TASK_FLAG_RESOURCES_RELEASED; struct task *entries[]={parent,child};tasks=entries;task_count=task_capacity=2; @@ -75,6 +78,7 @@ static void run_case(bool shared,bool vfork,bool child_cross) uint64_t clone_flags=17|CLONE_PARENT_SETTID|CLONE_CHILD_SETTID; if(shared)clone_flags|=CLONE_VM; if(vfork)clone_flags|=CLONE_VFORK; + if(thread)clone_flags=(clone_flags & ~(uint64_t)CSIGNAL)|CLONE_SIGHAND|CLONE_THREAD; uint64_t irq; if(!shared) { for(int budget=0;budget<5;++budget) { @@ -91,6 +95,10 @@ static void run_case(bool shared,bool vfork,bool child_cross) int64_t pid=syscall_clone_prepared(&parent->frame,clone_flags,0,parent_tid,child_tid,0); kernel_execution_unlock_irqrestore(irq); assert(pid>0 && child->pid==(uint32_t)pid && !writable_aliases); + assert(sched_task_limits(child)->rtprio.rlim_cur==7 && + sched_task_limits(child)->rtprio.rlim_max==30); + sched_task_limits(child)->rtprio.rlim_cur=5; + assert(sched_task_limits(parent)->rtprio.rlim_cur==(thread ? 5u : 7u)); uint32_t written;memcpy(&written,(void *)(uintptr_t)parent_tid,4);assert(written==(uint32_t)pid); assert(child_word(child,child_tid)==(uint32_t)pid); if(shared) { @@ -121,6 +129,13 @@ static void run_case(bool shared,bool vfork,bool child_cross) } sched_task_fs_release(child);task_groups_release(child); syscall_release_task_files(child); + if(thread) { + assert(child->shared_limits==parent->shared_limits && parent->shared_limits->references==2); + task_release_limits(child);task_release_limits(parent); + assert(child->shared_sighand==parent->shared_sighand && parent->shared_sighand->references==2); + kernel_free(parent->shared_sighand); + child->shared_sighand=parent->shared_sighand=NULL; + } kernel_free(child->exec_argv);kernel_free(child->exec_envp);kernel_free(child->exec_data); sched_task_identity_detach(child); free(clone_tid_pair);clone_tid_pair=NULL;clone_tid_pair_bytes=0; @@ -131,9 +146,10 @@ static void run_case(bool shared,bool vfork,bool child_cross) #ifndef TASK8_FIX3_DEVICE_FORK int main(void) { - run_case(false,false,false);run_case(false,false,true); - run_case(true,false,true);run_case(true,true,true); - puts("PASS actual clone scheduler and page tables: cross-page parent and child TIDs, COW, shared/vfork, OOM rollback"); + run_case(false,false,false,false);run_case(false,false,true,false); + run_case(true,false,true,false);run_case(true,true,true,false); + run_case(true,false,true,true); + puts("PASS actual clone scheduler and page tables: cross-page TIDs, COW, shared/vfork, OOM rollback, RTPRIO inheritance and thread sharing"); return 0; } #endif diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 7597d232..2760a14b 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -4589,6 +4589,7 @@ "kernel/syscall/process/clone.c", "kernel/device/mapping.c", "fs/security/access.c", + "fs/vfs/lookup_cache.c", "-o", "{tmp}/fix1-clone-tid-real-noswap" ] @@ -4619,6 +4620,7 @@ "kernel/syscall/process/clone.c", "kernel/device/mapping.c", "fs/security/access.c", + "fs/vfs/lookup_cache.c", "-o", "{tmp}/fix1-clone-tid-real-swap" ] From 112bd76e344c068c181bf3c19e435087620218e1 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 13:38:23 +0800 Subject: [PATCH 28/97] feat(socket): add AF_UNIX receive timestamps --- .../LC_MESSAGES/userspace-api/descriptors.po | 9 ++ .../LC_MESSAGES/userspace-api/descriptors.po | 9 ++ Documentation/userspace-api/descriptors.rst | 15 ++ include/uapi/linux/socket.h | 4 + kernel/syscall/ipc/socket.c | 143 ++++++++++++++---- tools/tests/socket_batch_unix_test.c | 102 ++++++++++++- tools/tests/task8_host_fixtures.json | 1 + ...-collector-green-2-socket_dispatch_stubs.c | 7 + tools/tests/task8_socket_receive_test.c | 71 ++++++++- 9 files changed, 326 insertions(+), 35 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index 29ff80a0..ee12c4d7 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -374,3 +374,12 @@ msgstr "" "the view. Path fields escape spaces, tabs, newlines, and backslashes. " "Fragmented reads use the same graph order and byte offsets, independently" " of reverse-insertion internal list layout." + +msgid "``AF_UNIX`` 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 使用原生整数 控制接收时间戳,默认关闭。启用任一选项会选定对应的控制消息类型,查询时仅 选中的选项返回 1,通过任一选项设置 0 均关闭。监听套接字的设置不由 ``accept`` 得到的套接字继承。" +msgstr "``AF_UNIX`` ``SO_TIMESTAMP_OLD`` and ``SO_TIMESTAMP_NEW`` use a native integer to control receive timestamps and are disabled by default. Enabling either option selects its control message type. Only the selected option returns 1 when queried, and setting either option to 0 disables timestamping. Sockets returned by ``accept`` do not inherit the listener setting." + +msgid "数据报和顺序数据包的 ``recvmsg`` 可返回 ``SOL_SOCKET`` 控制消息,类型为 选中的时间戳选项,载荷为 x86_64 的 64 位秒和微秒字段。接收方在入队前启用时 记录入队时间,否则在启用后的首次读取或 ``MSG_PEEK`` 时补记实时钟时间; 同一数据包的后续预读和接收保留该时间。流套接字接受选项,当前不产生时间戳 控制消息。" +msgstr "``recvmsg`` on datagram and sequenced-packet sockets can return a ``SOL_SOCKET`` control message of the selected timestamp type. Its x86_64 payload contains 64-bit seconds and microseconds. When enabled before enqueue, the receiver records enqueue time. Otherwise the realtime clock is sampled on the first read or ``MSG_PEEK`` after enabling. Subsequent peeks and receives retain the packet timestamp. Stream sockets accept the option and currently produce no timestamp control message." + +msgid "时间戳位于 ``SCM_CREDENTIALS`` 和 ``SCM_RIGHTS`` 之前。控制缓冲区不足时 按可用容量返回部分消息并设置 ``MSG_CTRUNC``。交换页等待后的重试保留已接收 数据包及其时间戳选项状态。" +msgstr "The timestamp precedes ``SCM_CREDENTIALS`` and ``SCM_RIGHTS``. A short control buffer receives the portion that fits and sets ``MSG_CTRUNC``. Retries after a swapped-page wait retain the accepted packet and timestamp option state." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index 7b6867bd..57bab4fc 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -320,3 +320,12 @@ msgid "" msgstr "" "参照元ルートの外にあるマウントルートは chroot ビューに表示しません。見えるレコードは実際の ID を保持するため、parent ID " "が表示範囲外にある場合があります。パスフィールドは空白、タブ、改行、バックスラッシュをエスケープします。分割読み取りは同じグラフ順序とバイトオフセットを使い、逆順挿入された内部リストの配置に依存しません。" + +msgid "``AF_UNIX`` 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 使用原生整数 控制接收时间戳,默认关闭。启用任一选项会选定对应的控制消息类型,查询时仅 选中的选项返回 1,通过任一选项设置 0 均关闭。监听套接字的设置不由 ``accept`` 得到的套接字继承。" +msgstr "``AF_UNIX`` の ``SO_TIMESTAMP_OLD`` と ``SO_TIMESTAMP_NEW`` はネイティブ整数で受信タイムスタンプを制御し、既定では無効です。どちらかを有効にすると対応する制御メッセージ型が選ばれます。問い合わせでは選択されたオプションだけが 1 を返し、どちらのオプションでも 0 を設定すると無効になります。``accept`` で得たソケットはリスナーの設定を継承しません。" + +msgid "数据报和顺序数据包的 ``recvmsg`` 可返回 ``SOL_SOCKET`` 控制消息,类型为 选中的时间戳选项,载荷为 x86_64 的 64 位秒和微秒字段。接收方在入队前启用时 记录入队时间,否则在启用后的首次读取或 ``MSG_PEEK`` 时补记实时钟时间; 同一数据包的后续预读和接收保留该时间。流套接字接受选项,当前不产生时间戳 控制消息。" +msgstr "データグラムとシーケンスパケットの ``recvmsg`` は、選択したタイムスタンプ型の ``SOL_SOCKET`` 制御メッセージを返せます。x86_64 のペイロードは 64 ビットの秒とマイクロ秒のフィールドです。受信側でキュー投入前に有効なら投入時刻を記録します。それ以外の場合は、有効にしてから最初の読み取りまたは ``MSG_PEEK`` でリアルタイムクロックを記録します。同じパケットの以後のプレビューと受信では時刻を保持します。ストリームソケットはオプションを受け付けますが、現在タイムスタンプ制御メッセージを生成しません。" + +msgid "时间戳位于 ``SCM_CREDENTIALS`` 和 ``SCM_RIGHTS`` 之前。控制缓冲区不足时 按可用容量返回部分消息并设置 ``MSG_CTRUNC``。交换页等待后的重试保留已接收 数据包及其时间戳选项状态。" +msgstr "タイムスタンプは ``SCM_CREDENTIALS`` と ``SCM_RIGHTS`` より前に置かれます。制御バッファーが不足すると収まる部分を返し、``MSG_CTRUNC`` を設定します。スワップページ待機後の再試行では受信済みパケットとタイムスタンプオプションの状態を保持します。" diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index 227b465e..de992611 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -114,6 +114,21 @@ TCP 的 ``recvfrom/recvmsg`` 支持 ``MSG_PEEK``:重复预读保留相同的 UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。 +``AF_UNIX`` 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 使用原生整数 +控制接收时间戳,默认关闭。启用任一选项会选定对应的控制消息类型,查询时仅 +选中的选项返回 1,通过任一选项设置 0 均关闭。监听套接字的设置不由 +``accept`` 得到的套接字继承。 + +数据报和顺序数据包的 ``recvmsg`` 可返回 ``SOL_SOCKET`` 控制消息,类型为 +选中的时间戳选项,载荷为 x86_64 的 64 位秒和微秒字段。接收方在入队前启用时 +记录入队时间,否则在启用后的首次读取或 ``MSG_PEEK`` 时补记实时钟时间; +同一数据包的后续预读和接收保留该时间。流套接字接受选项,当前不产生时间戳 +控制消息。 + +时间戳位于 ``SCM_CREDENTIALS`` 和 ``SCM_RIGHTS`` 之前。控制缓冲区不足时 +按可用容量返回部分消息并设置 ``MSG_CTRUNC``。交换页等待后的重试保留已接收 +数据包及其时间戳选项状态。 + ``AF_NETLINK`` 的 ``SO_ATTACH_FILTER`` 接受最多 4096 条经典 BPF 指令, ``SO_DETACH_FILTER`` 移除当前过滤器。过滤器在单播回复和多播通知入队前执行, 零返回值丢弃数据报,其他返回值限制接收长度。报文整数按网络字节序读取, diff --git a/include/uapi/linux/socket.h b/include/uapi/linux/socket.h index 5f2f66bf..f7afa2e2 100644 --- a/include/uapi/linux/socket.h +++ b/include/uapi/linux/socket.h @@ -60,11 +60,15 @@ struct sockaddr_un { #define SO_BINDTODEVICE 25 #define SO_ATTACH_FILTER 26 #define SO_DETACH_FILTER 27 +#define SO_TIMESTAMP_OLD 29 +#define SO_TIMESTAMP_NEW 63 +#define SO_TIMESTAMP SO_TIMESTAMP_OLD #define SO_PROTOCOL 38 #define SO_DOMAIN 39 #define SCM_RIGHTS 1 #define SCM_CREDENTIALS 2 +#define SCM_TIMESTAMP SO_TIMESTAMP #define MSG_CTRUNC 0x08 #define MSG_OOB 0x01 diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 25ba6cda..8b95560a 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -93,6 +93,8 @@ struct unix_packet { uint32_t length; uint32_t path_len; struct ucred credentials; + struct linux_timeval timestamp; + bool timestamp_valid; char path[109]; unsigned char data[]; }; @@ -102,6 +104,8 @@ struct unix_receive_result { uint32_t barrier; uint32_t path_len; struct ucred credentials; + struct linux_timeval timestamp; + bool timestamp_valid; char path[109]; }; @@ -129,6 +133,7 @@ struct unix_socket { uint32_t shutdown_write; int32_t error; uint32_t passcred; + uint32_t timestamp_option; uint32_t receive_lowwater; bool bound; bool reuse_address; /* Socket option state; UNIX names remain exclusive. */ @@ -291,6 +296,7 @@ struct socket_send_stage { uint64_t number,args[6]; bool explicit_credentials; bool receiving,accepted,progress_done,outputs_planned,passcred; + uint32_t timestamp_option; uint8_t *data; uint32_t data_length,copied,pin_count; uint64_t prior_done; @@ -651,6 +657,14 @@ void task_socket_collect(void) collecting = false; } +/** @brief Consume or peek UNIX data and retain packet metadata for recvmsg. + * @param file Borrowed socket description. @param buffer Kernel data output. + * @param length Available output bytes. @param flags Linux receive flags. + * @param ancillary Optional rights output. @param metadata Optional receive metadata. + * @return Bytes, negative errno, or a private wait marker. A queued packet + * first observed with timestamps enabled retains its realtime timestamp across + * peeks. The execution owner serializes packet and socket state. + */ static int unix_read_data(struct task_file *file, void *buffer, uint32_t length, uint32_t flags, struct unix_rights **ancillary, struct unix_receive_result *metadata) @@ -674,11 +688,19 @@ static int unix_read_data(struct task_file *file, void *buffer, uint32_t length, if (socket->type == SOCK_SEQPACKET && (!peer || peer->shutdown_write)) return 0; return unix_block(socket, file, &socket->wait_rx, true, flags); } + if (socket->timestamp_option && !p->timestamp_valid) { + struct linux_timespec now; + (void)time_clock_get(LINUX_CLOCK_REALTIME, &now); + p->timestamp = (struct linux_timeval){now.tv_sec, now.tv_nsec / 1000}; + p->timestamp_valid = true; + } uint32_t copied = length < p->length ? length : p->length; for (unsigned i = 0; i < copied; ++i) ((uint8_t *)buffer)[i] = p->data[i]; if (metadata) { metadata->flags = copied < p->length ? MSG_TRUNC : 0; metadata->credentials = p->credentials; + metadata->timestamp = p->timestamp; + metadata->timestamp_valid = p->timestamp_valid; metadata->path_len = p->path_len; for (unsigned i = 0; i < p->path_len; ++i) metadata->path[i] = p->path[i]; } @@ -856,6 +878,13 @@ static int unix_packet_peer(struct unix_socket *socket, const void *address, return 0; } +/** @brief Queue one UNIX datagram or sequenced packet with receive metadata. + * @param file Sending socket description. @param peer Borrowed destination. + * @param data Kernel-owned bytes. @param length Number of bytes. + * @param flags Linux send flags. @param credentials Optional explicit credentials. + * @return Accepted bytes, negative errno, or a private wait marker. When the + * destination has timestamping enabled, the packet owns its realtime sample. + */ static int unix_send_packet(struct task_file *file, struct unix_socket *peer, const void *data, uint32_t length, uint32_t flags, const struct ucred *credentials) @@ -875,6 +904,12 @@ static int unix_send_packet(struct task_file *file, struct unix_socket *peer, if (!packet) return -RELIEFOS_ENOMEM; *packet = (struct unix_packet){.length = length, .path_len = socket->path_len}; packet->credentials = unix_send_credentials(socket, peer, credentials); + if (peer->timestamp_option) { + struct linux_timespec now; + (void)time_clock_get(LINUX_CLOCK_REALTIME, &now); + packet->timestamp = (struct linux_timeval){now.tv_sec, now.tv_nsec / 1000}; + packet->timestamp_valid = true; + } for (unsigned i = 0; i < socket->path_len; ++i) packet->path[i] = socket->path[i]; for (unsigned i = 0; i < length; ++i) packet->data[i] = ((const uint8_t *)data)[i]; if (peer->packet_tail) peer->packet_tail->next = packet; @@ -1838,21 +1873,32 @@ int task_socket_send_user(struct task *task,struct task_file *file,uint64_t addr } #endif -static uint64_t unix_put_credentials(struct msghdr *message, uint64_t capacity, - const struct ucred *credentials) -{ - uint64_t length = CMSG_LEN(sizeof(*credentials)); - if (capacity < length) message->msg_flags |= MSG_CTRUNC; - if (capacity < CMSG_LEN(0)) return 0; - if (length > capacity) length = capacity; +/** @brief Append one socket ancillary item and report the written byte extent. + * @param message Mutable kernel header with its current control length. + * @param capacity Total available control bytes. @param type SCM type. + * @param data Kernel-owned payload. @param size Payload byte count. + * @return End offset of initialized bytes, excluding alignment padding. + * Insufficient capacity sets MSG_CTRUNC and emits a partial item when its + * header fits. The caller owns and validates the control buffer. + */ +static uint64_t unix_put_control(struct msghdr *message, uint64_t capacity, + int type, const void *data, uint32_t size) +{ + uint64_t offset = message->msg_controllen; + uint64_t available = capacity - offset; + uint64_t length = CMSG_LEN(size); + if (available < length) message->msg_flags |= MSG_CTRUNC; + if (available < CMSG_LEN(0)) return offset; + if (length > available) length = available; struct cmsghdr header = {.cmsg_len = length, .cmsg_level = SOL_SOCKET, - .cmsg_type = SCM_CREDENTIALS}; - uint8_t *out = message->msg_control; + .cmsg_type = type}; + uint8_t *out = (uint8_t *)message->msg_control + offset; for (unsigned i = 0; i < sizeof(header); ++i) out[i] = ((uint8_t *)&header)[i]; for (unsigned i = 0; i < length - CMSG_LEN(0); ++i) - out[CMSG_LEN(0) + i] = ((const uint8_t *)credentials)[i]; - uint64_t used = CMSG_SPACE(sizeof(*credentials)); - return used < capacity ? used : capacity; + out[CMSG_LEN(0) + i] = ((const uint8_t *)data)[i]; + uint64_t used = CMSG_SPACE(size); + message->msg_controllen += used < available ? used : available; + return offset + length; } #ifdef CONFIG_SWAP @@ -2025,7 +2071,9 @@ static int unix_recvmsg_staged(struct task *task,struct task_file *file,uint64_t stage->receive_result=ret; stage->data_length=(uint32_t)retpasscred=socket->passcred;stage->accepted=true; + stage->passcred=socket->passcred; + stage->timestamp_option=socket->timestamp_option; + stage->accepted=true; } uint64_t skip=stage->prior_done+stage->copied; for(uint64_t i=0;icopieddata_length;++i) { @@ -2077,18 +2125,31 @@ static int unix_recvmsg_staged(struct task *task,struct task_file *file,uint64_t uint64_t capacity=message.msg_controllen; uint32_t name_length=stage->metadata.path_len?stage->metadata.path_len+2:0; uint32_t name_bytes=message.msg_name?(message.msg_namelenpasscred && capacity>=CMSG_LEN(0)) { - credential_bytes=(uint32_t)(capacitymetadata.flags | (flags & MSG_CMSG_CLOEXEC); + uint32_t control_bytes=0,timestamp_end=0,credential_start,credential_end=0; + if(stage->timestamp_option && stage->metadata.timestamp_valid) + timestamp_end=(uint32_t)unix_put_control(&prepared,capacity,stage->timestamp_option, + &stage->metadata.timestamp,sizeof(stage->metadata.timestamp)); + control_bytes=timestamp_end; + credential_start=(uint32_t)prepared.msg_controllen; + if(stage->passcred) { + credential_end=(uint32_t)unix_put_control(&prepared,capacity,SCM_CREDENTIALS, + &stage->metadata.credentials,sizeof(stage->metadata.credentials)); + if(credential_end>control_bytes)control_bytes=credential_end; + } + uint64_t ancillary_used=prepared.msg_controllen; + uint64_t remaining_control=capacity-ancillary_used; uint64_t rights_limit=remaining_control>=CMSG_LEN(0)?(remaining_control-CMSG_LEN(0))/sizeof(int):0; uint32_t possible=stage->rights && rights_limitrights->count?(uint32_t)rights_limit: stage->rights?stage->rights->count:0; - uint32_t control_bytes=credential_bytes; - if(possible && credential_used+CMSG_LEN(possible*sizeof(int))>control_bytes) - control_bytes=credential_used+CMSG_LEN(possible*sizeof(int)); + if(possible && ancillary_used+CMSG_LEN(possible*sizeof(int))>control_bytes) + control_bytes=(uint32_t)(ancillary_used+CMSG_LEN(possible*sizeof(int))); if(!stage->outputs_planned) { if(user_msg && user_msg>UINT64_MAX-sizeof(struct msghdr)) { socket_receive_finish(task,stage,scoped,false);return -LINUX_EFAULT; @@ -2110,23 +2171,21 @@ static int unix_recvmsg_staged(struct task *task,struct task_file *file,uint64_t unsigned char name[111]={AF_UNIX,0}; if(stage->metadata.path_len)__builtin_memcpy(name+2,stage->metadata.path,stage->metadata.path_len); if(name_bytes)socket_output_copy(stage,0,0,name,name_bytes); - unsigned char control[CMSG_SPACE(sizeof(struct ucred))+CMSG_SPACE(UNIX_SOCKET_FD_TRANSFER_MAX*sizeof(int))]={0}; - struct msghdr prepared=message;prepared.msg_control=control;prepared.msg_controllen=0; - prepared.msg_flags=stage->metadata.flags | (flags & MSG_CMSG_CLOEXEC); - if(stage->passcred)prepared.msg_controllen=unix_put_credentials(&prepared,capacity,&stage->metadata.credentials); - if(credential_bytes)socket_output_copy(stage,1,0,control,credential_bytes); + if(timestamp_end)socket_output_copy(stage,1,0,control,timestamp_end); + if(credential_end>credential_start) + socket_output_copy(stage,1,credential_start,control+credential_start,credential_end-credential_start); uint32_t count=0; while(stage->rights && countrights->files[count]?unix_clone_fd_to_task(task,stage->rights->files[count]): task_pty_import_fd(task,&stage->rights->ptys[count],flags & MSG_CMSG_CLOEXEC?RELIEFOS_FD_CLOEXEC:0); if(fd<0)break; if((flags & MSG_CMSG_CLOEXEC) && stage->rights->files[count])task_descriptor_for_fd(task,fd)->fd_flags=RELIEFOS_FD_CLOEXEC; - __builtin_memcpy(control+credential_used+CMSG_LEN(0)+count*sizeof(int),&fd,sizeof(fd));++count; + __builtin_memcpy(control+ancillary_used+CMSG_LEN(0)+count*sizeof(int),&fd,sizeof(fd));++count; } if(count) { struct cmsghdr header={.cmsg_len=CMSG_LEN(count*sizeof(int)),.cmsg_level=SOL_SOCKET,.cmsg_type=SCM_RIGHTS}; - __builtin_memcpy(control+credential_used,&header,sizeof(header)); - socket_output_copy(stage,1,credential_used,control+credential_used,CMSG_LEN(count*sizeof(int))); + __builtin_memcpy(control+ancillary_used,&header,sizeof(header)); + socket_output_copy(stage,1,ancillary_used,control+ancillary_used,CMSG_LEN(count*sizeof(int))); uint64_t size=CMSG_SPACE(count*sizeof(int)); prepared.msg_controllen+=sizetimestamp_option && metadata.timestamp_valid) + (void)unix_put_control(&message, capacity, socket->timestamp_option, + &metadata.timestamp, sizeof(metadata.timestamp)); + if (passcred) + (void)unix_put_control(&message, capacity, SCM_CREDENTIALS, + &metadata.credentials, sizeof(metadata.credentials)); uint8_t *control = (uint8_t *)message.msg_control + message.msg_controllen; capacity -= message.msg_controllen; if (rights) { @@ -2991,7 +3062,8 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, * all-zero timeval to an infinite wait, and maps negative seconds to an * immediate timeout that getsockopt reports as (0, 0). * SO_REUSEADDR records a boolean without changing name ownership or being - * inherited by accepted sockets. + * inherited by accepted sockets. Timestamp old/new options share enablement + * and select the emitted control-message ABI. */ static int unix_socket_option(struct unix_socket *socket, bool setting, int level, int option, uint64_t address, uint64_t length) @@ -3026,7 +3098,8 @@ static int unix_socket_option(struct unix_socket *socket, bool setting, int leve else socket->send_timeout = ticks; return 0; } - if (option != SO_PASSCRED && option != SO_RCVLOWAT && option != SO_REUSEADDR) + if (option != SO_PASSCRED && option != SO_RCVLOWAT && option != SO_REUSEADDR && + option != SO_TIMESTAMP_OLD && option != SO_TIMESTAMP_NEW) return -LINUX_ENOPROTOOPT; if ((uint32_t)length < sizeof(int32_t)) return -RELIEFOS_EINVAL; int prep=socket_user_prepare(sched_current_task(),address,sizeof(int32_t),false); @@ -3036,6 +3109,8 @@ static int unix_socket_option(struct unix_socket *socket, bool setting, int leve __builtin_memcpy(&value, (const void *)(uintptr_t)address, sizeof(value)); if (option == SO_PASSCRED) socket->passcred = value != 0; else if (option == SO_REUSEADDR) socket->reuse_address = value != 0; + else if (option == SO_TIMESTAMP_OLD || option == SO_TIMESTAMP_NEW) + socket->timestamp_option = value ? (uint32_t)option : 0; else socket->receive_lowwater = value < 0 ? INT32_MAX : value ? (uint32_t)value : 1; return 0; } @@ -3058,6 +3133,8 @@ static int unix_socket_option(struct unix_socket *socket, bool setting, int leve case SO_ERROR: value = socket->error; socket->error = 0; break; case SO_PASSCRED: value = (int32_t)socket->passcred; break; case SO_REUSEADDR: value = socket->reuse_address; break; + case SO_TIMESTAMP_OLD: + case SO_TIMESTAMP_NEW: value = socket->timestamp_option == (uint32_t)option; break; case SO_RCVLOWAT: value = (int32_t)socket->receive_lowwater; break; case SO_SNDLOWAT: value = 1; break; case SO_ACCEPTCONN: value = socket->state == UNIX_SOCKET_LISTEN; break; diff --git a/tools/tests/socket_batch_unix_test.c b/tools/tests/socket_batch_unix_test.c index 3dee98d9..0ada6ef6 100644 --- a/tools/tests/socket_batch_unix_test.c +++ b/tools/tests/socket_batch_unix_test.c @@ -15,6 +15,7 @@ static bool swap_replace_passed; static uint64_t readonly; static unsigned allocations; static unsigned pty_holds; +static struct linux_timespec fixture_realtime = {100, 123456789}; /* AF_UNIX cases must not cross into another socket family's backend. */ int task_udp_recv(struct task_file *f, void *b, uint32_t n, uint32_t flags, uint64_t a, uint64_t l) { (void)f; (void)b; (void)n; (void)flags; (void)a; (void)l; abort(); } @@ -90,7 +91,11 @@ uint32_t sched_current_pid(void) { return current.pid; } struct task *sched_find(uint32_t pid) { return pid == current.pid ? ¤t : NULL; } uint64_t time_ticks(void) { return 100; } int time_clock_get(int32_t id, struct linux_timespec *out) -{ assert(id == LINUX_CLOCK_MONOTONIC); *out = (struct linux_timespec){1, 0}; return 0; } +{ + if (id == LINUX_CLOCK_REALTIME) *out = fixture_realtime; + else { assert(id == LINUX_CLOCK_MONOTONIC); *out = (struct linux_timespec){1, 0}; } + return 0; +} bool user_range_ok(uint64_t p, uint64_t size) { #ifdef TASK8_NOSWAP_APERTURE_TEST return !size || (p>=RELIEFNT_USER_BASE && pcmsg_type == timestamp_old && header->cmsg_level == SOL_SOCKET && + header->cmsg_len == CMSG_LEN(sizeof(stamp))); + memcpy(&stamp, CMSG_DATA(header), sizeof(stamp)); + assert(stamp.tv_sec == 100 && stamp.tv_usec == 123456); + receive.msg_hdr.msg_controllen = sizeof(control); + assert(batch(true, &receive, 1, 0) == 1); + memcpy(&stamp, CMSG_DATA((struct cmsghdr *)(void *)control), sizeof(stamp)); + assert(stamp.tv_sec == 100 && stamp.tv_usec == 123456 && !allocations); + + value = 0; + assert(!unix_socket_option(&peers[1], true, SOL_SOCKET, timestamp_new, + (uintptr_t)&value, sizeof(value))); + assert(unix_send_packet(&endpoints[0], &peers[1], "y", 1, 0, NULL) == 1); + value = 1; + assert(!unix_socket_option(&peers[1], true, SOL_SOCKET, timestamp_new, + (uintptr_t)&value, sizeof(value))); + fixture_realtime = (struct linux_timespec){102, 234567890}; + receive.msg_hdr.msg_controllen = sizeof(control); + assert(batch(true, &receive, 1, MSG_PEEK) == 1); + header = (void *)control; + assert(header->cmsg_type == timestamp_new); + memcpy(&stamp, CMSG_DATA(header), sizeof(stamp)); + assert(stamp.tv_sec == 102 && stamp.tv_usec == 234567); + fixture_realtime = (struct linux_timespec){103, 0}; + receive.msg_hdr.msg_controllen = sizeof(control); + assert(batch(true, &receive, 1, 0) == 1); + memcpy(&stamp, CMSG_DATA((struct cmsghdr *)(void *)control), sizeof(stamp)); + assert(stamp.tv_sec == 102 && stamp.tv_usec == 234567 && !allocations); + + peers[1].passcred = 1; + passed = (struct task_file){.used = 1, .references = 1}; + unsigned char outgoing[CMSG_SPACE(sizeof(int))] __attribute__((aligned(8))) = {0}; + header = (void *)outgoing; + *header = (struct cmsghdr){CMSG_LEN(sizeof(int)), SOL_SOCKET, SCM_RIGHTS}; + int fd = 5; + memcpy(CMSG_DATA(header), &fd, sizeof(fd)); + struct mmsghdr send = {.msg_hdr = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_control = outgoing, .msg_controllen = sizeof(outgoing)}}; + assert(batch(false, &send, 1, 0) == 1); + receive.msg_hdr.msg_controllen = sizeof(control); + assert(batch(true, &receive, 1, 0) == 1); + header = CMSG_FIRSTHDR(&receive.msg_hdr); + assert(header && header->cmsg_type == timestamp_new); + header = CMSG_NXTHDR(&receive.msg_hdr, header); + assert(header && header->cmsg_type == SCM_CREDENTIALS); + header = CMSG_NXTHDR(&receive.msg_hdr, header); + assert(header && header->cmsg_type == SCM_RIGHTS); + memcpy(&fd, CMSG_DATA(header), sizeof(fd)); + assert(fd == 6 && current.files[0].description == &passed); + clear_task_file(¤t.files[0]); + assert(passed.references == 1 && !allocations); + + peers[1].passcred = 0; + for (unsigned capacity = 0; capacity <= 32; capacity += 8) { + assert(unix_send_packet(&endpoints[0], &peers[1], "z", 1, 0, NULL) == 1); + receive.msg_hdr.msg_controllen = capacity; + assert(batch(true, &receive, 1, 0) == 1); + assert(!!(receive.msg_hdr.msg_flags & MSG_CTRUNC) == (capacity < 32)); + assert(receive.msg_hdr.msg_controllen == (capacity < 16 ? 0 : capacity)); + if (capacity >= 16) { + header = (void *)control; + assert(header->cmsg_type == timestamp_new && header->cmsg_len == capacity); + } + } + value = 0; + assert(!unix_socket_option(&peers[1], true, SOL_SOCKET, timestamp_old, + (uintptr_t)&value, sizeof(value))); + puts("PASS AF_UNIX timestamps: old/new, PEEK, queued enable, ordering and truncation"); +} + int main(void) { current.kind = TASK_KIND_USER; @@ -184,6 +283,7 @@ int main(void) .flags = TASK_FILE_FLAG_SOCKET | TASK_FILE_FLAG_SOCKET_UNIX | RELIEFOS_O_RDWR}; } check_unix_reuseaddr(); + check_unix_timestamps(); /* Linux imports the outgoing header before blocking. A changed user * msg_name must not redirect or fault the already suspended send. */ char snapshot_data[]="pin",snapshot_received[4]={0}; diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 2760a14b..4db2cdc6 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -2213,6 +2213,7 @@ "-Iinclude/uapi", "tools/tests/task8_socket_receive_test.c", "fs/vfs/mount_tree.c", + "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", diff --git a/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c b/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c index 5b604c4a..e410d7ae 100644 --- a/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c +++ b/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c @@ -7,3 +7,10 @@ TRAP(kernel_wait_queue_wake_one) TRAP(net_socket_address) TRAP(net_socket_connec TRAP(net_socket_get_timeout_ticks) TRAP(net_socket_open) TRAP(net_socket_pin_fd) TRAP(net_socket_set_timeout_ticks) TRAP(net_socket_shutdown_fd) TRAP(syscall_packet) TRAP(syscall_udp) TRAP(task_discard_file_fd) +TRAP(task_netlink_cancel_wait) TRAP(syscall_netlink) +TRAP(net_interface_device_option) TRAP(net_socket_accept_commit) +TRAP(net_socket_accept_peek) TRAP(net_socket_address6) TRAP(net_socket_bind6_fd) +TRAP(net_socket_bound_device) TRAP(net_socket_connect6_fd) TRAP(net_socket_family) +TRAP(net_socket_ipv6_option) TRAP(net_socket_is_listening) TRAP(net_socket_listen_fd) +TRAP(net_socket_nodelay) TRAP(net_socket_reuse) TRAP(net_socket_set_ipv6) +TRAP(net_socket_wait_readable) diff --git a/tools/tests/task8_socket_receive_test.c b/tools/tests/task8_socket_receive_test.c index 0bebf227..e7a621d7 100644 --- a/tools/tests/task8_socket_receive_test.c +++ b/tools/tests/task8_socket_receive_test.c @@ -12,7 +12,7 @@ #include static uint8_t incoming[128],output[128]; -static unsigned char control[CMSG_SPACE(sizeof(int))] __attribute__((aligned(4096))); +static unsigned char control[96] __attribute__((aligned(4096))); static unsigned char replacement[4096] __attribute__((aligned(4096))); static bool replace_control; static uintptr_t device_user_page,device_physical_page; @@ -130,6 +130,75 @@ int main(void) assert(unix_read_data(&endpoints[1],incoming,sizeof(incoming),0,NULL,&metadata)==sizeof(incoming)); assert(incoming[0]==0x71 && passed.references==1 && !allocations); + /* Timestamp, credentials and rights remain attached to the accepted packet + * when a control-output page waits and the socket option changes. */ + int timestamp_enabled=1; + assert(!unix_socket_option(&peers[1],true,SOL_SOCKET,SO_TIMESTAMP_NEW, + (uintptr_t)×tamp_enabled,sizeof(timestamp_enabled))); + peers[1].passcred=1; + fixture_realtime=(struct linux_timespec){200,456789123}; + send_one(0x55); + memset(control,0,sizeof(control)); + vector=(struct iovec){output,sizeof(output)}; + message=(struct msghdr){.msg_iov=&vector,.msg_iovlen=1, + .msg_control=control,.msg_controllen=sizeof(control)}; + frame=(struct trap_frame){.rax=LINUX_SYS_RECVMSG,.rdi=4,.rsi=(uintptr_t)&message}; + current.syscall_file=&endpoints[1]; + task_lookup_scope_begin(¤t,&frame);readonly=(uintptr_t)control;contended=true; + assert(task_socket_message(¤t,&endpoints[1],(uintptr_t)&message,0,true,false,&result)==KERNEL_SYSCALL_SWAP_CONTENDED); + assert(!peers[1].packet_count && owned_stage && passed.references==2); + timestamp_enabled=0; + assert(!unix_socket_option(&peers[1],true,SOL_SOCKET,SO_TIMESTAMP_OLD, + (uintptr_t)×tamp_enabled,sizeof(timestamp_enabled))); + fixture_realtime=(struct linux_timespec){201,0}; + contended=false;task_lookup_scope_begin(¤t,&frame); + assert(task_socket_message(¤t,&endpoints[1],(uintptr_t)&message,0,true,false,&result)==sizeof(output)); + struct cmsghdr *item=CMSG_FIRSTHDR(&message); + struct linux_timeval stamp; + assert(item && item->cmsg_type==SO_TIMESTAMP_NEW); + memcpy(&stamp,CMSG_DATA(item),sizeof(stamp)); + assert(stamp.tv_sec==200 && stamp.tv_usec==456789); + item=CMSG_NXTHDR(&message,item); + assert(item && item->cmsg_type==SCM_CREDENTIALS); + item=CMSG_NXTHDR(&message,item); + assert(item && item->cmsg_type==SCM_RIGHTS && current.files[0].description==&passed); + clear_task_file(¤t.files[0]);task_lookup_scope_cancel(¤t); + assert(passed.references==1 && !owned_stage && !allocations && !pins); + + timestamp_enabled=1; + assert(!unix_socket_option(&peers[1],true,SOL_SOCKET,SO_TIMESTAMP_NEW, + (uintptr_t)×tamp_enabled,sizeof(timestamp_enabled))); + const struct { uint32_t capacity,used; bool truncated,has_rights; } control_cases[]={ + {0,0,true,false}, {16,16,true,false}, {24,24,true,false}, + {32,32,true,false}, {48,48,true,false}, {60,60,true,false}, + {64,64,true,false}, {80,64,true,false}, {84,84,false,true}, + {96,88,false,true} + }; + for(unsigned i=0;icmsg_type==SCM_RIGHTS && current.files[0].description==&passed); + clear_task_file(¤t.files[0]); + } + task_lookup_scope_cancel(¤t); + assert(passed.references==1 && !owned_stage && !allocations && !pins); + } + timestamp_enabled=0; + assert(!unix_socket_option(&peers[1],true,SOL_SOCKET,SO_TIMESTAMP_NEW, + (uintptr_t)×tamp_enabled,sizeof(timestamp_enabled))); + peers[1].passcred=0; + __builtin_memcpy(peers[0].path,"abc",3);peers[0].path_len=3; assert(unix_send_packet(&endpoints[0],&peers[1],"xyz",3,0,NULL)==3); char name[111]={0};uint32_t name_length=sizeof(name);memset(output,0,sizeof(output)); From ee05d4472b122e8f9cbe58b34f6436733a44469c Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 13:58:12 +0800 Subject: [PATCH 29/97] feat(fs): support device node creation --- .../userspace-api/device-filesystems.po | 12 +++ .../userspace-api/device-filesystems.po | 12 +++ .../userspace-api/device-filesystems.rst | 8 ++ fs/ext_common/dir.c | 11 ++- fs/ext_common/internal.h | 2 +- fs/ext_common/native.c | 21 ++++- fs/ext_common/ops.c | 8 +- fs/operations.h | 3 + fs/tmpfs/native.c | 15 ++++ fs/vfs/file.c | 55 ++++++++++-- fs/vfs/storage_backend.c | 2 +- fs/vfs/storage_backend.h | 10 +++ fs/vfs/storage_create.c | 38 +++++++- include/reliefnt/mount.h | 16 ++++ kernel/syscall/dispatch.c | 7 +- kernel/syscall/fs/create.c | 48 ++++++++-- kernel/syscall/internal.h | 10 +++ tools/test_mount_backend.py | 8 ++ tools/tests/mount_backend_test.c | 87 +++++++++++++++++++ 19 files changed, 342 insertions(+), 31 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 3047796e..2c5bb45d 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -17,6 +17,18 @@ msgstr "" msgid "设备与控制组文件系统" msgstr "Device and control group filesystems" +msgid "设备节点创建" +msgstr "Device node creation" + +msgid "``mknod`` 和 ``mknodat`` 可在 tmpfs、devtmpfs、ext2 和 ext4 上创建字符及块 设备节点,保存 Linux 编码的设备号。新节点的所有者、组和权限遵循目录权限、 组继承及进程的 ``umask``。除字符设备 ``0:0`` 以外,创建设备需要有效的 ``CAP_MKNOD``;只读挂载拒绝创建。设备的后续打开遵循挂载的 ``nodev`` 策略。" +msgstr "" +"``mknod`` and ``mknodat`` create character and block device nodes on tmpfs, " +"devtmpfs, ext2 and ext4, retaining the Linux-encoded device number. The " +"owner, group and permissions follow directory access rules, group inheritance " +"and the process ``umask``. Creation requires effective ``CAP_MKNOD`` except " +"for character device ``0:0``. Read-only mounts reject creation. Subsequent " +"device opens obey the mount's ``nodev`` policy." + msgid "devtmpfs" msgstr "devtmpfs" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index d7b9c8af..c443c2e3 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -17,6 +17,18 @@ msgstr "" msgid "设备与控制组文件系统" msgstr "デバイスとコントロールグループのファイルシステム" +msgid "设备节点创建" +msgstr "デバイスノードの作成" + +msgid "``mknod`` 和 ``mknodat`` 可在 tmpfs、devtmpfs、ext2 和 ext4 上创建字符及块 设备节点,保存 Linux 编码的设备号。新节点的所有者、组和权限遵循目录权限、 组继承及进程的 ``umask``。除字符设备 ``0:0`` 以外,创建设备需要有效的 ``CAP_MKNOD``;只读挂载拒绝创建。设备的后续打开遵循挂载的 ``nodev`` 策略。" +msgstr "" +"``mknod`` と ``mknodat`` は tmpfs、devtmpfs、ext2、ext4 上にキャラクター " +"デバイスおよびブロックデバイスのノードを作成し、Linux 形式のデバイス番号を保存する。" +"新しいノードの所有者、グループ、権限はディレクトリのアクセス権、グループ継承、" +"プロセスの ``umask`` に従う。キャラクターデバイス ``0:0`` を除き、作成には " +"有効な ``CAP_MKNOD`` が必要である。読み取り専用マウントでは作成できない。" +"デバイスを開く際にはマウントの ``nodev`` ポリシーが適用される。" + msgid "devtmpfs" msgstr "devtmpfs" diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 8e6a8bbf..c51ade9c 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -2,6 +2,14 @@ 设备与控制组文件系统 ==================== +设备节点创建 +============ + +``mknod`` 和 ``mknodat`` 可在 tmpfs、devtmpfs、ext2 和 ext4 上创建字符及块 +设备节点,保存 Linux 编码的设备号。新节点的所有者、组和权限遵循目录权限、 +组继承及进程的 ``umask``。除字符设备 ``0:0`` 以外,创建设备需要有效的 +``CAP_MKNOD``;只读挂载拒绝创建。设备的后续打开遵循挂载的 ``nodev`` 策略。 + devtmpfs ======== diff --git a/fs/ext_common/dir.c b/fs/ext_common/dir.c index 415b6780..748310d6 100644 --- a/fs/ext_common/dir.c +++ b/fs/ext_common/dir.c @@ -500,7 +500,7 @@ uint8_t ed_type(uint16_t mode) case 0020000:return 3; case 0060000:return 4; case 0010000:return 5; case 0140000:return 6; default:return 1; } } static int ed_create(struct storage_volume *v,uint64_t parent,const char *name,uint16_t mode, - uint32_t uid,uint32_t gid,const char *target,uint64_t *out,struct storage_node *created) + uint32_t uid,uint32_t gid,const char *target,uint32_t device,uint64_t *out,struct storage_node *created) { int ret=ed_name(name,true); if (ret<0 || (!out && !created)) return ret<0?ret:-RELIEFOS_EINVAL; if (((mode&EXT2_S_IFMT)==EXT2_S_IFLNK)!=!!target || (target && !target[0])) return -RELIEFOS_EINVAL; @@ -522,6 +522,8 @@ static int ed_create(struct storage_volume *v,uint64_t parent,const char *name,u in.flags=EXT4_EXTENTS_FL; ext4_put_le16(in.i_block_raw,0xf30a); ext4_put_le16(in.i_block_raw+4,4); } if (target && target_len<60) { in.size=target_len; storage_memcpy(in.i_block_raw,target,target_len); } + if ((mode&EXT2_S_IFMT)==0020000 || (mode&EXT2_S_IFMT)==0060000) + ext4_put_le32(in.i_block_raw+4,device); ret=storage_ext4_write_inode(v,ino,&in); if (ret<0) goto done; if (dir) { uint64_t logical; uint8_t *buf=kernel_malloc(v->ext4.block_size); if (!buf) { ret=-RELIEFOS_ENOMEM; goto done; } @@ -551,7 +553,7 @@ static int ed_create(struct storage_volume *v,uint64_t parent,const char *name,u } int storage_ext4_create(struct storage_volume *v,uint64_t parent,const char *name,uint16_t mode, uint32_t uid,uint32_t gid,const char *target,uint64_t *out) -{return !out ? -RELIEFOS_EINVAL : ed_create(v,parent,name,mode,uid,gid,target,out,NULL);} +{return !out ? -RELIEFOS_EINVAL : ed_create(v,parent,name,mode,uid,gid,target,0,out,NULL);} /** @brief Return created inode identity from the same directory transaction. * @param v Borrowed selected filesystem under execution ownership. @@ -561,14 +563,15 @@ int storage_ext4_create(struct storage_volume *v,uint64_t parent,const char *nam * @param uid Final owner ID. * @param gid Final group ID. * @param target Borrowed symlink target, NULL for other types. + * @param device Encoded Linux device number for character/block inodes. * @param out Required borrowed metadata result; no inode reference transferred. * @return Zero or negative errno. No metadata lookup/allocation follows a * successful directory transaction, so publication cannot be reported as * failure merely because a second metadata read runs out of memory. */ int storage_ext4_create_node(struct storage_volume *v,uint64_t parent,const char *name,uint16_t mode, - uint32_t uid,uint32_t gid,const char *target,struct storage_node *out) -{return !out ? -RELIEFOS_EINVAL : ed_create(v,parent,name,mode,uid,gid,target,NULL,out);} + uint32_t uid,uint32_t gid,const char *target,uint32_t device,struct storage_node *out) +{return !out ? -RELIEFOS_EINVAL : ed_create(v,parent,name,mode,uid,gid,target,device,NULL,out);} int storage_ext4_link(struct storage_volume *v,uint64_t parent,const char *name,uint64_t ino) { struct storage_ext4_handle h; int ret=storage_ext4_journal_start(v,EXT4_JOURNAL_CREDITS,&h); if (ret<0) return ret; diff --git a/fs/ext_common/internal.h b/fs/ext_common/internal.h index e97dd0e4..15204aae 100644 --- a/fs/ext_common/internal.h +++ b/fs/ext_common/internal.h @@ -124,7 +124,7 @@ int storage_ext4_dir_lookup_prepared(struct storage_volume *v,uint64_t ino,const int storage_ext4_dir_insert(struct storage_volume *,uint64_t,const char *,uint64_t,uint8_t); int storage_ext4_dir_remove(struct storage_volume *,uint64_t,const char *,uint64_t *); int storage_ext4_create(struct storage_volume *,uint64_t,const char *,uint16_t,uint32_t,uint32_t,const char *,uint64_t *); -int storage_ext4_create_node(struct storage_volume *,uint64_t,const char *,uint16_t,uint32_t,uint32_t,const char *,struct storage_node *); +int storage_ext4_create_node(struct storage_volume *,uint64_t,const char *,uint16_t,uint32_t,uint32_t,const char *,uint32_t,struct storage_node *); int storage_ext4_link(struct storage_volume *,uint64_t,const char *,uint64_t); int storage_ext4_unlink(struct storage_volume *,uint64_t,const char *,bool); int storage_ext4_rename(struct storage_volume *,uint64_t,const char *,uint64_t,const char *); diff --git a/fs/ext_common/native.c b/fs/ext_common/native.c index 87b5edff..8a55aaac 100644 --- a/fs/ext_common/native.c +++ b/fs/ext_common/native.c @@ -321,7 +321,25 @@ static int ext_native_create(struct storage_volume *volume,const struct storage_ struct ext4_inode_view directory;int rc=storage_ext4_check_node(volume,parent,&directory); if(!rc && (directory.mode&LINUX_S_IFMT)!=LINUX_S_IFDIR)rc=-ENOTDIR; if(!rc && !directory.links_count)rc=-ENOENT; - if(!rc)rc=storage_ext4_create_node(volume,parent->first_cluster,name,(uint16_t)mode,value->uid,value->gid,target,out); + if(!rc)rc=storage_ext4_create_node(volume,parent->first_cluster,name,(uint16_t)mode,value->uid,value->gid,target,0,out); + return rc; +} +/** @brief Create a device inode and store its rdev in the creation transaction. + * @param volume Borrowed selected instance. @param parent Actual directory. + * @param name Literal component. @param mode Authorized type and permissions. + * @param value Authorized ownership. @param device Encoded Linux rdev. + * @param out Required metadata result. + * @return Zero or native errno. Execution/mutation admission is required; + * device metadata is written before the directory transaction commits. + */ +static int ext_native_create_device(struct storage_volume *volume,const struct storage_node *parent,const char *name, + uint32_t mode,const struct reliefos_permissions *value,uint32_t device, + struct storage_node *out) +{ + struct ext4_inode_view directory;int rc=storage_ext4_check_node(volume,parent,&directory); + if(!rc && (directory.mode&LINUX_S_IFMT)!=LINUX_S_IFDIR)rc=-ENOTDIR; + if(!rc && !directory.links_count)rc=-ENOENT; + if(!rc)rc=storage_ext4_create_node(volume,parent->first_cluster,name,(uint16_t)mode,value->uid,value->gid,NULL,device,out); return rc; } /** @brief Remove the exact verified native member, retaining open inode backing. @@ -495,6 +513,7 @@ const struct storage_filesystem_ops storage_ext_ops={ .sync=storage_ext4_sync, .invalidate_write=ext_native_invalidate_write, .create=ext_native_create, + .create_device=ext_native_create_device, .remove=ext_native_remove, .rename=ext_native_rename, .link=ext_native_link, diff --git a/fs/ext_common/ops.c b/fs/ext_common/ops.c index cbbe08c9..72704d04 100644 --- a/fs/ext_common/ops.c +++ b/fs/ext_common/ops.c @@ -2,13 +2,14 @@ #include "../../block/core/storage_internal.h" /** @brief Convert a Linux ext-family mode to the existing native node class. * @param mode Borrowed inode type/mode bits. - * @return Directory/link/FIFO/socket class, or the legacy regular-file default. + * @return Directory/link/FIFO/socket/device class, or the regular-file default. * Pure conversion with no ownership, allocation, locking or I/O. */ uint32_t storage_ext4_inode_type(uint16_t mode) { switch (mode&0170000) { case 0040000:return RELIEFOS_FS_TYPE_DIR; case 0120000:return RELIEFOS_FS_TYPE_SYMLINK; case 0010000:return RELIEFOS_FS_TYPE_FIFO; + case 0020000:case 0060000:return RELIEFOS_FS_TYPE_DEVICE; case 0140000:return RELIEFOS_FS_TYPE_SOCKET; default:return RELIEFOS_FS_TYPE_FILE; } } /** @brief Translate an already available inode view without another inode read. @@ -20,8 +21,11 @@ uint32_t storage_ext4_inode_type(uint16_t mode) */ void storage_ext4_node_from_inode(struct storage_volume *v,uint64_t ino,const struct ext4_inode_view *in,struct storage_node *out) { + uint32_t type=in->mode&LINUX_S_IFMT; + uint32_t device_flags=type==LINUX_S_IFCHR || type==LINUX_S_IFBLK ? + STORAGE_NODE_FLAG_DEV_NODE|STORAGE_NODE_FLAG_RDEV : 0; if (out) *out=(struct storage_node){.type=storage_ext4_inode_type(in->mode),.flags=STORAGE_NODE_FLAG_EXT_FAMILY| - (ino==2?STORAGE_NODE_FLAG_ROOT:0),.first_cluster=ino,.volume_id=v->volume_id,.size=in->size, + device_flags|(ino==2?STORAGE_NODE_FLAG_ROOT:0),.first_cluster=ino,.volume_id=v->volume_id,.size=in->size, .mount_generation=v->mount_generation,.inode_generation=in->generation}; } diff --git a/fs/operations.h b/fs/operations.h index cd5778fa..c3ecb754 100644 --- a/fs/operations.h +++ b/fs/operations.h @@ -65,6 +65,9 @@ struct storage_filesystem_ops { int (*truncate)(struct storage_volume *volume,struct storage_node *node,uint64_t length); int (*create)(struct storage_volume *volume,const struct storage_node *parent,const char *name,uint32_t mode, const struct reliefos_permissions *value,const char *target,struct storage_node *out); + /* Device creation follows create's atomic-publication contract. */ + int (*create_device)(struct storage_volume *volume,const struct storage_node *parent,const char *name,uint32_t mode, + const struct reliefos_permissions *value,uint32_t device,struct storage_node *out); int (*remove)(struct storage_volume *volume,const struct storage_node *parent,const char *name, const struct storage_node *node,bool directory); int (*rename)(struct storage_volume *volume,const struct storage_rename_args *args); diff --git a/fs/tmpfs/native.c b/fs/tmpfs/native.c index 39263a8a..101a1fbb 100644 --- a/fs/tmpfs/native.c +++ b/fs/tmpfs/native.c @@ -150,6 +150,20 @@ static int tmpfs_native_create(struct storage_volume *volume,const struct storag { return tmpfs_create_child(volume->tmpfs,parent->first_cluster,name,mode,target,value,out); } +/** @brief Create a tmpfs character or block inode with its final device number. + * @param volume Borrowed selected instance. @param parent Actual directory. + * @param name Literal component. @param mode Authorized type and permissions. + * @param value Authorized ownership. @param device Encoded Linux rdev. + * @param out Required metadata result. + * @return Zero or native errno. Execution and mutation admission are required; + * failed creation publishes no inode. + */ +static int tmpfs_native_create_device(struct storage_volume *volume,const struct storage_node *parent,const char *name, + uint32_t mode,const struct reliefos_permissions *value,uint32_t device, + struct storage_node *out) +{ + return tmpfs_mknod_child(volume->tmpfs,parent->first_cluster,name,mode,device,value,out); +} /** @brief Remove the exact verified native member, retaining open inode backing. * @param volume Borrowed selected/pinned instance. @param parent Actual directory. * @param name Literal component. @param node Verified victim metadata. @@ -188,6 +202,7 @@ static int tmpfs_native_link(struct storage_volume *volume,const struct storage_ const struct storage_filesystem_ops storage_tmpfs_ops={ .flags=STORAGE_FS_LOOKUP_EPOCH, .create=tmpfs_native_create, + .create_device=tmpfs_native_create_device, .remove=tmpfs_native_remove, .rename=tmpfs_native_rename, .link=tmpfs_native_link, diff --git a/fs/vfs/file.c b/fs/vfs/file.c index 160f99fa..48b97129 100644 --- a/fs/vfs/file.c +++ b/fs/vfs/file.c @@ -235,10 +235,18 @@ int vfs_path_new_file(const struct vfs_path *parent,const char *name, const struct reliefos_permissions *value,struct vfs_path *out) {return !out ? -EINVAL : vfs_path_create_node(parent,name,LINUX_S_IFREG,value,NULL,out);} -/** @brief Create a child only through a writable attachment and supported provider. - * No cached or returned inode is published before successful backend creation. */ -int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,const char *target,struct vfs_path *out) +/** @brief Create one member with the provider's ordinary or device callback. + * @param parent Held directory and attachment. @param name Literal component. + * @param type Linux inode type. @param value Final ownership and permissions. + * @param target Symlink target, otherwise NULL. @param device Encoded rdev. + * @param create_device Select device creation and validate its inode type. + * @param out Optional retained created path. + * @return Zero or negative errno. Reserve publication state before mutation; + * failures leave no dentry and provider pin failures roll back the inode. + */ +static int vfs_create_member(const struct vfs_path *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,const char *target, + uint32_t device,bool create_device,struct vfs_path *out) { if(out)*out=(struct vfs_path){0}; if(!vfs_path_valid(parent) || !name || !name[0] || !value || @@ -250,11 +258,16 @@ int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t } if(parent->dentry->node.type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; if(parent->dentry->disconnected)return -ENOENT; - if(type!=LINUX_S_IFREG && type!=LINUX_S_IFDIR && type!=LINUX_S_IFLNK && + bool special=type==LINUX_S_IFCHR || type==LINUX_S_IFBLK; + if(create_device && !special)return -EINVAL; + if(!create_device && special)return -EOPNOTSUPP; + if(!special && type!=LINUX_S_IFREG && type!=LINUX_S_IFDIR && type!=LINUX_S_IFLNK && type!=LINUX_S_IFIFO && type!=LINUX_S_IFSOCK)return -EOPNOTSUPP; if(type==LINUX_S_IFLNK && (!target || !target[0]))return -ENOENT; if(type!=LINUX_S_IFLNK && target)return -EINVAL; - if((vfs_path_mount_flags(parent)&MS_RDONLY) || !parent->mount->ops->create_node)return -EROFS; + if(vfs_path_mount_flags(parent)&MS_RDONLY)return -EROFS; + if(special && !parent->mount->ops->create_device)return -EOPNOTSUPP; + if(!special && !parent->mount->ops->create_node)return -EROFS; struct vfs_dentry *reserved=NULL; if(out) { reserved=kernel_malloc(sizeof(*reserved));if(!reserved)return -ENOMEM; @@ -264,8 +277,10 @@ int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t __builtin_memcpy(reserved->name,name,length+1); } struct storage_node node;void *pin=NULL; - int rc=parent->mount->ops->create_node(parent->mount->context,&parent->dentry->node,name,type,value,target,&node, - reserved ? &pin : NULL); + int rc=special ? parent->mount->ops->create_device(parent->mount->context,&parent->dentry->node, + name,type,value,device,&node,reserved ? &pin : NULL) : + parent->mount->ops->create_node(parent->mount->context,&parent->dentry->node,name,type,value,target,&node, + reserved ? &pin : NULL); if(rc) { if(reserved){kernel_free(reserved->name);kernel_free(reserved);} return rc; @@ -278,3 +293,27 @@ int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t if(vfs_notify_dentry_created)vfs_notify_dentry_created(parent->mount,reserved); struct vfs_path created={parent->mount,reserved};vfs_path_get(&created,out);return 0; } + +/** @brief Create a non-device member through the retained parent. + * @param parent Held directory and attachment. @param name Literal component. + * @param type Linux inode type. @param value Authorized owner and permissions. + * @param target Symlink target, otherwise NULL. @param out Optional retained path. + * @return Zero or negative errno. Failure publishes no child. + */ +int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,const char *target,struct vfs_path *out) +{ + return vfs_create_member(parent,name,type,value,target,0,false,out); +} + +/** @brief Create a character or block member through the retained parent. + * @param parent Held directory and attachment. @param name Literal component. + * @param type Linux device inode type. @param value Authorized owner and permissions. + * @param device Encoded Linux rdev. @param out Optional retained path. + * @return Zero or negative errno. Failure publishes no child. + */ +int vfs_path_create_device(const struct vfs_path *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,uint32_t device,struct vfs_path *out) +{ + return vfs_create_member(parent,name,type,value,NULL,device,true,out); +} diff --git a/fs/vfs/storage_backend.c b/fs/vfs/storage_backend.c index 6bffb12d..ee54b575 100644 --- a/fs/vfs/storage_backend.c +++ b/fs/vfs/storage_backend.c @@ -288,7 +288,7 @@ static const struct vfs_backend_ops storage_vfs_ops={ .finish=storage_vfs_finish,.destroy=storage_vfs_destroy,.can_unmount=storage_vfs_can_unmount,.remount=storage_vfs_remount, .remount_options=storage_vfs_remount_options, .read=storage_vfs_read,.read_cursor=storage_vfs_read_cursor,.readdir=storage_vfs_readdir,.permissions=storage_backend_permissions, - .mount_flags=storage_vfs_flags,.create_node=storage_backend_create_node, + .mount_flags=storage_vfs_flags,.create_node=storage_backend_create_node,.create_device=storage_backend_create_device, .getattr=storage_backend_getattr,.statfs=storage_backend_statfs, .getxattr=storage_vfs_getxattr,.listxattr=storage_vfs_listxattr, .readdir_name=storage_vfs_readdir_name, diff --git a/fs/vfs/storage_backend.h b/fs/vfs/storage_backend.h index b7e9e7e1..69301e8e 100644 --- a/fs/vfs/storage_backend.h +++ b/fs/vfs/storage_backend.h @@ -73,6 +73,16 @@ int storage_backend_store_child(struct storage_volume *volume,const struct stora */ int storage_backend_create_node(void *context,const struct storage_node *parent,const char *name,uint32_t type, const struct reliefos_permissions *value,const char *target,struct storage_node *out,void **pin); +/** @brief Create an authorized device inode with the normal publication rollback. + * @param context Borrowed native instance. @param parent Actual directory. + * @param name Validated component. @param type S_IFCHR or S_IFBLK. + * @param value Final owner/mode. @param device Encoded Linux rdev. + * @param out Required created node. @param pin Optional owned inode pin. + * @return Zero or negative errno. Execution ownership is required, and no + * graph lock spans provider I/O. Failure rolls back an unpublished member. + */ +int storage_backend_create_device(void *context,const struct storage_node *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,uint32_t device,struct storage_node *out,void **pin); /** * @brief Best-effort native disk access-time update for this exact attachment. * @param context Borrowed live native storage instance pinned by its mount. diff --git a/fs/vfs/storage_create.c b/fs/vfs/storage_create.c index 5d56f49f..148f5a75 100644 --- a/fs/vfs/storage_create.c +++ b/fs/vfs/storage_create.c @@ -51,20 +51,23 @@ int storage_cluster_drop_new(struct storage_volume *volume,const struct storage_ * @param context Borrowed pinned native instance. @param parent Actual directory. * @param name Validated literal component. @param type Authorized Linux inode type. * @param value Borrowed authorized ownership/mode. @param target Optional symlink target. + * @param device Encoded device number for a character or block inode. * @param out Required native node output. @param pin Optional owned inode-pin output. * @return Zero or input/readonly/provider/metadata errno. Execution ownership * required. Provider creation, sidecar persistence and final publication pins * roll back before exposing a VFS dentry; no graph/module lock spans native I/O. */ -int storage_backend_create_node(void *context,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,const char *target,struct storage_node *out,void **pin) +static int storage_backend_create_member(void *context,const struct storage_node *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,const char *target,uint32_t device, + struct storage_node *out,void **pin) { if(pin)*pin=NULL; struct storage_volume *volume=context; if(!volume || !parent || !name || !value || !out || parent->volume_id!=volume->volume_id)return -EINVAL; const struct storage_filesystem_ops *ops=volume->fs_ops; if(volume->mount_flags&MS_RDONLY || (ops && (ops->flags&STORAGE_FS_READONLY)))return -EROFS; - if(!ops || !ops->create)return -EOPNOTSUPP; + bool special=type==LINUX_S_IFCHR || type==LINUX_S_IFBLK; + if(!ops || (special ? !ops->create_device : !ops->create))return -EOPNOTSUPP; bool sidecar=ops->flags&STORAGE_FS_SIDECAR; if(sidecar && type!=LINUX_S_IFREG && type!=LINUX_S_IFDIR)return -EOPNOTSUPP; if(sidecar && storage_text_eq_ci(name,"LEONACL.SYS"))return -EPERM; @@ -72,7 +75,8 @@ int storage_backend_create_node(void *context,const struct storage_node *parent, parent=&directory; struct storage_volume *previous=NULL;rc=storage_select_node_volume(parent,&previous);if(rc)return rc; storage_begin_mutation(); - rc=ops->create(volume,parent,name,type|(value->mode&07777),value,target,out); + rc=special ? ops->create_device(volume,parent,name,type|(value->mode&07777),value,device,out) : + ops->create(volume,parent,name,type|(value->mode&07777),value,target,out); if(!rc && sidecar) { struct storage_inode_ref *metadata_pin=NULL;rc=storage_inode_get(out,&metadata_pin); if(!rc)rc=storage_backend_store_child(volume,parent,name,value); @@ -91,3 +95,29 @@ int storage_backend_create_node(void *context,const struct storage_node *parent, } storage_restore_volume(previous);return rc; } + +/** @brief Create a non-device native member with publication rollback. + * @param context Borrowed native instance. @param parent Actual directory. + * @param name Literal component. @param type Linux inode type. + * @param value Final permissions. @param target Symlink target, otherwise NULL. + * @param out Required node output. @param pin Optional owned inode pin. + * @return Zero or negative errno. Failed publication rolls back the member. + */ +int storage_backend_create_node(void *context,const struct storage_node *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,const char *target,struct storage_node *out,void **pin) +{ + return storage_backend_create_member(context,parent,name,type,value,target,0,out,pin); +} + +/** @brief Create a device native member with publication rollback. + * @param context Borrowed native instance. @param parent Actual directory. + * @param name Literal component. @param type Linux device inode type. + * @param value Final permissions. @param device Encoded Linux rdev. + * @param out Required node output. @param pin Optional owned inode pin. + * @return Zero or negative errno. Failed publication rolls back the member. + */ +int storage_backend_create_device(void *context,const struct storage_node *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,uint32_t device,struct storage_node *out,void **pin) +{ + return storage_backend_create_member(context,parent,name,type,value,NULL,device,out,pin); +} diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index ce075c45..88dcc658 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -153,6 +153,10 @@ struct vfs_backend_ops { * on failure. No namespace routing or EAGAIN after mutation commits. */ int (*create_node)(void *context,const struct storage_node *parent,const char *name,uint32_t type, const struct reliefos_permissions *value,const char *target,struct storage_node *out,void **pin); + /* Create a character/block inode with its independent Linux device number. + * The same publication and rollback contract as create_node applies. */ + int (*create_device)(void *context,const struct storage_node *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,uint32_t device,struct storage_node *out,void **pin); int (*getattr)(void *context,const struct vfs_path *path,struct linux_stat_abi *out); int (*statfs)(void *context,const struct storage_node *node,struct linux_statfs_abi *out); int (*write)(void *context,struct storage_node *node,uint64_t offset, @@ -889,6 +893,18 @@ int vfs_path_new_file(const struct vfs_path *parent,const char *name, */ int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t type, const struct reliefos_permissions *value,const char *target,struct vfs_path *out); +/** @brief Create a character or block inode through its retained parent. + * @param parent Held directory and attachment. + * @param name Literal child name. + * @param type Linux S_IFCHR or S_IFBLK. + * @param value Authorized final permissions and ownership. + * @param device Linux encoded device number. + * @param out Optional created path, retained on success. + * @return Zero or negative errno. Readonly and unsupported providers reject + * creation; allocation and provider failures leave no published member. + */ +int vfs_path_create_device(const struct vfs_path *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,uint32_t device,struct vfs_path *out); /** @brief Unlink/rmdir the exact retained directory member. * @param ns Borrowed shared namespace under execution ownership. * @param path Borrowed victim path retaining its parent, inode and provider. diff --git a/kernel/syscall/dispatch.c b/kernel/syscall/dispatch.c index 0209fc63..f4c652a7 100644 --- a/kernel/syscall/dispatch.c +++ b/kernel/syscall/dispatch.c @@ -643,12 +643,9 @@ int64_t syscall_dispatch_regs_legacy(uint64_t number, uint64_t a0, uint64_t a1, return syscall_legacy_process(number, a0, a1, a2, a3, a4, a5); if (number == __NR_mknod || number == __NR_mknodat) { uint32_t mode=(uint32_t)(number==__NR_mknodat ? a2 : a1); - uint32_t type=mode&LINUX_S_IFMT;if(!type)type=LINUX_S_IFREG; - if(type!=LINUX_S_IFREG && type!=LINUX_S_IFIFO && type!=LINUX_S_IFSOCK) - return type==LINUX_S_IFCHR || type==LINUX_S_IFBLK ? -RELIEFOS_EOPNOTSUPP : -RELIEFOS_EINVAL; - return syscall_create_object(task_lookup_namespace(actor), actor, + return syscall_mknod_object(task_lookup_namespace(actor), actor, number==__NR_mknodat ? (int32_t)a0 : LINUX_AT_FDCWD, - number==__NR_mknodat ? a1 : a0,type,mode,NULL); + number==__NR_mknodat ? a1 : a0,mode,(uint32_t)(number==__NR_mknodat ? a3 : a2)); } if (number == LINUX_SYS_CREAT) return syscall_open_object(task_lookup_namespace(actor), actor, LINUX_AT_FDCWD, diff --git a/kernel/syscall/fs/create.c b/kernel/syscall/fs/create.c index 9c939d88..f859ded9 100644 --- a/kernel/syscall/fs/create.c +++ b/kernel/syscall/fs/create.c @@ -34,19 +34,21 @@ int syscall_creation_mode(struct task *task,const struct vfs_path *parent,uint32 * @param task Borrowed current task with stable credentials and FS references. * @param dirfd Relative base descriptor or AT_FDCWD. * @param pathname User pathname captured once by the common retry scope. - * @param type S_IFREG/S_IFDIR/S_IFLNK/S_IFIFO/S_IFSOCK inode type. + * @param type Supported Linux inode type, including character/block devices. * @param mode Requested permission bits subject to umask/inheritance. * @param target Borrowed kernel symlink payload, NULL for other types. + * @param device Encoded device number, used only for character/block inodes. * @return Zero or negative errno. Existing entries return EEXIST before parent * write checks. A successful create has no following VFS allocation/open step; * retained operands survive retries without text replay or locks across I/O. */ -int64_t syscall_create_object(struct vfs_namespace *ns,struct task *task,int32_t dirfd, - uint64_t pathname,uint32_t type,uint32_t mode,const char *target) +static int64_t syscall_create_member(struct vfs_namespace *ns,struct task *task,int32_t dirfd, + uint64_t pathname,uint32_t type,uint32_t mode,const char *target,uint32_t device) { if(!task)return -RELIEFOS_ESRCH; + bool special=type==LINUX_S_IFCHR || type==LINUX_S_IFBLK; if(type!=LINUX_S_IFREG && type!=LINUX_S_IFDIR && type!=LINUX_S_IFLNK && - type!=LINUX_S_IFIFO && type!=LINUX_S_IFSOCK)return -RELIEFOS_EOPNOTSUPP; + type!=LINUX_S_IFIFO && type!=LINUX_S_IFSOCK && !special)return -RELIEFOS_EOPNOTSUPP; struct vfs_lookup_result parent={0}; int rc=resolve_user_object_at_flags(ns,task,dirfd,pathname,false,false,VFS_LOOKUP_PARENT,&parent); if(rc)return rc; @@ -62,10 +64,46 @@ int64_t syscall_create_object(struct vfs_namespace *ns,struct task *task,int32_t if(!rc && parent.trailing && type!=LINUX_S_IFDIR)rc=-RELIEFOS_ENOENT; struct reliefos_permissions value; if(!rc)rc=syscall_creation_mode(task,&parent.path,type,mode,&value); - if(!rc)rc=vfs_path_create_node(&parent.path,parent.last,type,&value,target,NULL); + if(!rc && special && !(type==LINUX_S_IFCHR && !device) && + !(task->cap_effective&(1ULL<mount->ns,&published,false));vfs_path_put(&published); } } + for(int budget=0;budget<12;++budget) { + struct vfs_path published={0},lookup={0}; + test_fail_heap_after=budget; + int rc=vfs_path_create_device(directory,"atomic-device",LINUX_S_IFCHR,&atomic_mode,0xabcabcde,&published); + test_fail_heap_after=-1; + if(rc) { + assert(rc==-ENOMEM && !published.mount); + assert(vfs_path_lookup_child(directory,"atomic-device",&lookup)==-ENOENT); + } else { + assert(!vfs_path_remove(directory->mount->ns,&published,false));vfs_path_put(&published); + } + } + struct vfs_path rejected=*directory; + assert(vfs_path_create_node(directory,"invalid-device",LINUX_S_IFCHR,&atomic_mode,NULL,&rejected)==-EOPNOTSUPP); + assert(!rejected.mount && !rejected.dentry); + rejected=*directory; + assert(vfs_path_create_device(directory,"invalid-device",LINUX_S_IFREG,&atomic_mode,0,&rejected)==-EINVAL); + assert(!rejected.mount && !rejected.dentry); } if(vfs_path_node(directory)->flags&STORAGE_NODE_FLAG_EXT2) { no_post_create_volume=&g_volumes[vfs_path_node(directory)->volume_id]; @@ -1163,6 +1181,37 @@ static void held_task_paths(struct vfs_namespace *ns,const struct vfs_path *root struct vfs_path made={0}; assert(!vfs_path_lookup_child(old_dir,"via-held-dir",&made)); assert(!vfs_path_stat(&made,&resized) && (resized.st_mode&07777)==02750 && resized.st_uid==0 && resized.st_gid==97); + char device_name[32]="zero-device"; + lookup_user_base=(uintptr_t)device_name;lookup_user_bytes=sizeof(device_name); + assert(!syscall_mknod_object(ns,&actor,3,(uintptr_t)device_name,LINUX_S_IFCHR|0666,0)); + struct vfs_path device={0}; + assert(!vfs_path_lookup_child(old_dir,device_name,&device)); + assert(!vfs_path_stat(&device,&resized) && resized.st_mode==(LINUX_S_IFCHR|0640) && + resized.st_uid==0 && resized.st_gid==97 && !resized.st_rdev); + assert(syscall_mknod_object(ns,&actor,3,(uintptr_t)device_name,LINUX_S_IFCHR|0666,0)==-EEXIST); + assert(!vfs_path_remove(ns,&device,false));vfs_path_put(&device); + strcpy(device_name,"wide-char"); + assert(syscall_mknod_object(ns,&actor,3,(uintptr_t)device_name,LINUX_S_IFCHR|0666,0xabcabcde)==-EPERM); + assert(vfs_path_lookup_child(old_dir,device_name,&device)==-ENOENT); + strcpy(device_name,"zero-block"); + assert(syscall_mknod_object(ns,&actor,3,(uintptr_t)device_name,LINUX_S_IFBLK|0666,0)==-EPERM); + actor.cap_effective=1ULL<flags&(STORAGE_NODE_FLAG_DEV_NODE|STORAGE_NODE_FLAG_RDEV))== + (STORAGE_NODE_FLAG_DEV_NODE|STORAGE_NODE_FLAG_RDEV)); + assert(!vfs_path_remove(ns,&device,false));vfs_path_put(&device); + } + strcpy(device_name,"invalid-type"); + assert(syscall_mknod_object(ns,&actor,3,(uintptr_t)device_name,LINUX_S_IFDIR|0755,0)==-EPERM); + assert(syscall_mknod_object(ns,&actor,3,(uintptr_t)device_name,LINUX_S_IFLNK|0777,0)==-EINVAL); + actor.cap_effective=0; struct {char old[32],name[32];} rename_names={"via-held-dir","renamed-held-dir"}; lookup_user_base=(uintptr_t)&rename_names;lookup_user_bytes=sizeof(rename_names); assert(!syscall_rename_object(ns,&actor,3,(uintptr_t)rename_names.old,3,(uintptr_t)rename_names.name,0)); @@ -2128,6 +2177,28 @@ static void ext_family(const char *input,const char *output) struct vfs_path root={0},directory={0},file={0},link={0}; assert(!vfs_namespace_root(&ns,&root)); real_mount_description(&ns,&root,volume->filesystem==STORAGE_FILESYSTEM_EXT4 ? "ext4" : "ext2","rw"); + const char *existing_names[]={"legacy-char","wide-existing-block"}; + const uint32_t existing_types[]={LINUX_S_IFCHR,LINUX_S_IFBLK}; + const uint32_t existing_devices[]={0x103,0xabcabcde}; + struct vfs_path device={0};struct linux_stat_abi device_status; + for(unsigned i=0;i<2;++i) { + assert(!vfs_path_lookup_child(&root,existing_names[i],&device)); + assert(!vfs_path_stat(&device,&device_status)); + assert((device_status.st_mode&LINUX_S_IFMT)==existing_types[i] && + device_status.st_rdev==existing_devices[i]); + assert((vfs_path_node(&device)->flags&(STORAGE_NODE_FLAG_DEV_NODE|STORAGE_NODE_FLAG_RDEV))== + (STORAGE_NODE_FLAG_DEV_NODE|STORAGE_NODE_FLAG_RDEV)); + vfs_path_put(&device); + } + const char *new_names[]={"new-wide-char","new-wide-block"}; + const struct reliefos_permissions device_mode={0640,1901,2901}; + for(unsigned i=0;i<2;++i) { + assert(!vfs_path_create_device(&root,new_names[i],existing_types[i],&device_mode,0xabcabcde,&device)); + assert(!vfs_path_stat(&device,&device_status)); + assert(device_status.st_mode==(existing_types[i]|0640) && device_status.st_uid==1901 && + device_status.st_gid==2901 && device_status.st_rdev==0xabcabcde); + vfs_path_put(&device); + } create_held_file(&root,true); assert(!vfs_path_lookup(&ns,&root,&root,"kept",VFS_LOOKUP_FOLLOW,&directory)); assert(!vfs_path_lookup(&ns,&root,&directory,"file",VFS_LOOKUP_FOLLOW,&file)); @@ -2165,6 +2236,21 @@ static void ext_family(const char *input,const char *output) assert(!fclose(result)); storage_ext4_journal_close(volume);test_memory_release(volume); *volume=(struct storage_volume){0};storage_cache_invalidate(); + load_volume(output,0); + assert(!storage_create_vfs_mount(volume,NULL,&mount)); + assert(!vfs_namespace_init(&ns,mount));vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns,&root)); + for(unsigned i=0;i<2;++i) { + assert(!vfs_path_lookup_child(&root,new_names[i],&device)); + assert(!vfs_path_stat(&device,&device_status)); + assert(device_status.st_mode==(existing_types[i]|0640) && device_status.st_uid==1901 && + device_status.st_gid==2901 && device_status.st_rdev==0xabcabcde); + vfs_path_put(&device); + } + vfs_path_put(&root);assert(!vfs_namespace_destroy(&ns) && !storage_inode_volume_busy(0)); + storage_ext4_journal_close(volume);test_memory_release(volume); + *volume=(struct storage_volume){0};storage_cache_invalidate(); + puts("PASS real ext-family device inodes: legacy and wide rdev reads, creation and reload"); puts("PASS real ext-family mount backend: inode-relative namei, native symlinks and held-unlink/removed-directory lifetime"); } @@ -2248,6 +2334,7 @@ static void runtime_mount_objects(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_path_remount(&mounted,MS_RDONLY|MS_NOSUID|MS_NODEV)); uint32_t written=99; assert(vfs_path_write(&file,0,"x",1,&written)==-EROFS && !written); + assert(vfs_path_create_device(&mounted,"readonly-device",LINUX_S_IFCHR,&mode,0x103,NULL)==-EROFS); /* The backend's original held physical identity still governs remounts, * including after disconnect; reject before changing either policy. */ struct block_device_registration physical={.info={.device=block_device_allocate_number(false), From 10ccd7a701ee2da2b35193b9c28fffaff65a3bb7 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 14:06:47 +0800 Subject: [PATCH 30/97] feat(fs): support proc filesystem contexts --- .../en/LC_MESSAGES/userspace-api/abi.po | 3 + .../ja/LC_MESSAGES/userspace-api/abi.po | 3 + Documentation/userspace-api/abi.rst | 5 ++ kernel/syscall/fs/mount_api.c | 31 ++++++++--- tools/tests/mount_backend_test.c | 55 +++++++++++++++++++ 5 files changed, 90 insertions(+), 7 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 221ad6ec..390a7ec1 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -357,6 +357,9 @@ msgstr "Filesystem Contexts and Detached Mounts" msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` creates a filesystem context. The caller needs effective ``CAP_SYS_ADMIN``. ``FSCONFIG_SET_STRING`` in ``fsconfig`` accepts the existing tmpfs options, including ``size``, ``nr_blocks``, ``nr_inodes``, ``mode``, ``uid`` and ``gid``. ``FSCONFIG_SET_FLAG`` accepts ``ro`` and ``rw``. ``FSCONFIG_CMD_CREATE`` creates the filesystem using the configured options and may be retried after failure. The context belongs to the open-file description, is shared after dup or fork, and is released with the final reference." +msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 当前 proc 上下文的参数(包括 ``hidepid``)返回 ``EINVAL``;挂载属性由 ``fsmount`` 指定。" +msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` also creates an independent proc context. ``FSCONFIG_CMD_CREATE``, ``fsmount`` and ``move_mount`` create and attach the mount. Proc context parameters, including ``hidepid``, currently return ``EINVAL``. Mount attributes are specified with ``fsmount``." + msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" msgstr "``fsmount`` returns an ``O_PATH`` descriptor for the detached mount root. It supports ``FSMOUNT_CLOEXEC`` and the readonly, nosuid, nodev, noexec and atime attributes. Files can be accessed relative to this descriptor, and the directory can be reopened via ``/proc/self/fd``. After success, the context can set new options with ``fsconfig`` and update the shared filesystem with ``FSCONFIG_CMD_RECONFIGURE``. Pending options remain after a configuration failure, so the operation can be retried after closing write descriptors that prevent a readonly transition." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index d4e455f8..0e281276 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -312,6 +312,9 @@ msgstr "ファイルシステムコンテキストと未接続マウント" msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` はファイルシステムコンテキストを作成します。呼び出し元には有効な ``CAP_SYS_ADMIN`` が必要です。``fsconfig`` の ``FSCONFIG_SET_STRING`` は ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid``、``gid`` などの既存の tmpfs オプションを受け付けます。``FSCONFIG_SET_FLAG`` は ``ro`` と ``rw`` を受け付けます。``FSCONFIG_CMD_CREATE`` は設定済みオプションでファイルシステムを作成し、失敗後に再試行できます。コンテキストはオープンファイル記述に属し、dup または fork 後に共有され、最後の参照が解放されると破棄されます。" +msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 当前 proc 上下文的参数(包括 ``hidepid``)返回 ``EINVAL``;挂载属性由 ``fsmount`` 指定。" +msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` でも独立した proc コンテキストを作成できます。``FSCONFIG_CMD_CREATE``、``fsmount``、``move_mount`` でマウントを作成して接続します。現在、``hidepid`` を含む proc コンテキストのパラメーターは ``EINVAL`` を返します。マウント属性は ``fsmount`` で指定します。" + msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" msgstr "``fsmount`` は未接続マウントのルートを指す ``O_PATH`` ディスクリプタを返し、``FSMOUNT_CLOEXEC`` と読み取り専用、nosuid、nodev、noexec、atime の属性をサポートします。このディスクリプタを基点にファイルへアクセスでき、``/proc/self/fd`` からディレクトリを開き直すこともできます。成功後、コンテキストは ``fsconfig`` で新しいオプションを設定し、``FSCONFIG_CMD_RECONFIGURE`` で共有ファイルシステムを更新できます。設定失敗時には保留中のオプションが保持されるため、読み取り専用への変更を妨げる書き込みディスクリプタを閉じて再試行できます。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 3ea133e7..7654d61c 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -110,6 +110,11 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。 +``fsopen("proc", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 +``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 +当前 proc 上下文的参数(包括 ``hidepid``)返回 ``EINVAL``;挂载属性由 +``fsmount`` 指定。 + ``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` diff --git a/kernel/syscall/fs/mount_api.c b/kernel/syscall/fs/mount_api.c index 0ed6251a..752b73bf 100644 --- a/kernel/syscall/fs/mount_api.c +++ b/kernel/syscall/fs/mount_api.c @@ -1,11 +1,18 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" +#include #include +enum syscall_fs_type { + SYSCALL_FS_TMPFS, + SYSCALL_FS_PROC, +}; + /* A context belongs to one open-file description, including its duplicates. */ struct syscall_fs_context { struct vfs_path root; uint32_t uid, gid; + enum syscall_fs_type type; bool created, mounted; int readonly_change; char options[VFS_PATH_MAX]; @@ -20,7 +27,7 @@ void syscall_fs_context_release(void *object) kernel_free(context); } -/** @brief Create a tmpfs configuration owned by a new descriptor. +/** @brief Create a supported filesystem configuration owned by a new descriptor. * @param task Calling descriptor-table owner. @param type_user User filesystem name. * @param flags Native fsopen flags. @return Descriptor or negative errno. * Text survives lookup retries and failed allocation leaves no descriptor. @@ -31,14 +38,17 @@ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t fl struct task_user_text type = {0}; int rc = task_lookup_user_text(task, type_user, VFS_NAME_MAX + 1, false, &type); if (rc) return rc; - if (__builtin_strcmp(type.text, "tmpfs")) rc = -RELIEFOS_ENODEV; + enum syscall_fs_type filesystem = SYSCALL_FS_TMPFS; + if (!__builtin_strcmp(type.text, "proc")) filesystem = SYSCALL_FS_PROC; + else if (__builtin_strcmp(type.text, "tmpfs")) rc = -RELIEFOS_ENODEV; struct syscall_fs_context *context = NULL; if (!rc) { context = kernel_malloc(sizeof(*context)); if (!context) rc = -RELIEFOS_ENOMEM; } if (!rc) { - *context = (struct syscall_fs_context){.uid = task->fsuid, .gid = task->fsgid}; + *context = (struct syscall_fs_context){.uid = task->fsuid, .gid = task->fsgid, + .type = filesystem}; struct task_file *file = NULL; int fd = task_allocate_fd(task, 0, &file); if (fd < 0) rc = fd; @@ -70,7 +80,7 @@ static int mount_api_context(struct task *task, int32_t fd, struct syscall_fs_co return 0; } -/** @brief Validate and queue one tmpfs parameter without partial state changes. +/** @brief Validate and queue one supported parameter without partial state changes. * @param task Caller with an optional retry scope. @param context Live context. * @param command SET_FLAG or SET_STRING. @param key_user Required key. * @param value_user String value or NULL for a flag. @@ -84,6 +94,10 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con if (!rc && command == FSCONFIG_SET_STRING) rc = task_lookup_user_text(task, value_user, VFS_PATH_MAX, false, &value); if (rc) goto done; + if (context->type == SYSCALL_FS_PROC) { + rc = -RELIEFOS_EINVAL; + goto done; + } if (command == FSCONFIG_SET_FLAG) { if (!__builtin_strcmp(key.text, "ro")) context->readonly_change = 1; else if (!__builtin_strcmp(key.text, "rw")) context->readonly_change = -1; @@ -122,7 +136,7 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con return rc; } -/** @brief Create or reconfigure the context's tmpfs transactionally. +/** @brief Create or reconfigure the context's filesystem transactionally. * @param context Borrowed context. @param command CREATE or RECONFIGURE. * @return Zero or negative state, option, busy or resource errno. * Pending parameters are consumed only after a successful operation. @@ -134,8 +148,11 @@ static int mount_api_commit(struct syscall_fs_context *context, uint32_t command if (context->created) return -RELIEFOS_EBUSY; struct vfs_mount *mount = NULL; uint64_t flags = context->readonly_change > 0 ? MS_RDONLY : 0; - rc = storage_new_tmpfs_mount("none", flags, context->options, - context->uid, context->gid, &mount); + if (context->type == SYSCALL_FS_PROC) + rc = proc_create_vfs_mount(&mount); + else + rc = storage_new_tmpfs_mount("none", flags, context->options, + context->uid, context->gid, &mount); if (!rc) rc = vfs_mount_detached_root(mount, &context->root); vfs_mount_put(mount); if (!rc) context->created = true; diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 3574a9bf..2fd3435b 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2679,6 +2679,60 @@ static void runtime_new_mount_api(struct vfs_namespace *ns,const struct vfs_path puts("PASS new mount API: FD reuse, failed publication, readonly retry, reopen and attach"); } +/** @brief Exercise proc contexts and reject options outside the proc backend. */ +static void runtime_proc_mount_api(struct vfs_namespace *ns,const struct vfs_path *root, + struct tmpfs_super *fs) +{ + struct tmpfs_super *proc_fixture=NULL; + assert(!g_volumes[4].ready); + assert(!tmpfs_new(4,0,NULL,0,0,&proc_fixture)); + g_volumes[4]=(struct storage_volume){.volume_id=4,.kind=STORAGE_VOLUME_ANONYMOUS, + .ready=true,.filesystem=STORAGE_FILESYSTEM_TMPFS,.fs_ops=&storage_tmpfs_ops, + .tmpfs=proc_fixture}; + struct { + char type[8], size[8], bytes[16], hidepid[8], invisible[16]; + char target[32], empty[1]; + } user={"proc","size","1048576","hidepid","invisible","/proc-new-api",""}; + struct task actor={.pid=907,.cap_effective=1ULL<nofile.rlim_cur=32; + vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + assert(!tmpfs_create(fs,user.target,LINUX_S_IFDIR|0755,NULL,NULL)); + + int context=scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.type,1,0,0,0); + assert(context>=0); + assert(task_descriptor_for_fd(&actor,context)->fd_flags & RELIEFOS_FD_CLOEXEC); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.size,(uintptr_t)user.bytes,0)==-EINVAL); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.hidepid,(uintptr_t)user.invisible,0)==-EINVAL); + test_fail_heap_after=0; + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)==-ENOMEM); + test_fail_heap_after=-1; + assert(scoped_mount_call(ns,&actor,__NR_fsmount,context,0,0,0,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)==-EBUSY); + int mountfd=scoped_mount_call(ns,&actor,__NR_fsmount,context,1,0x0e,0,0); + assert(mountfd>=0); + struct task_file *mount_file=task_file_for_fd(&actor,mountfd); + assert(mount_file && vfs_path_node(&mount_file->path_ref)->volume_id==4); + assert((vfs_path_mount_flags(&mount_file->path_ref)&(MS_NODEV|MS_NOSUID|MS_NOEXEC))== + (MS_NODEV|MS_NOSUID|MS_NOEXEC)); + assert(!scoped_mount_call(ns,&actor,__NR_move_mount,mountfd,(uintptr_t)user.empty, + (uint32_t)LINUX_AT_FDCWD,(uintptr_t)user.target,4)); + struct vfs_path attached={0}; + assert(!vfs_path_lookup(ns,root,root,user.target,0,&attached)); + assert(vfs_path_equal(&attached,&mount_file->path_ref)); + task_discard_file_fd(&actor,context);task_discard_file_fd(&actor,mountfd); + assert(!vfs_mount_unmount(ns,&attached));vfs_path_put(&attached); + assert(!tmpfs_unlink(fs,user.target,true)); + vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + assert(!g_volumes[4].vfs_mounts && !storage_inode_volume_busy(4)); + tmpfs_destroy(proc_fixture);g_volumes[4]=(struct storage_volume){0}; + lookup_user_base=lookup_user_bytes=0; + puts("PASS proc mount API: option rejection, create retry and attachment"); +} + /** @brief Read a generated cgroup control by its retained inode and check exact bytes. */ static void cgroup_check_text(const struct vfs_path *directory,const char *name,const char *expected) { @@ -4420,6 +4474,7 @@ int main(int argc,char **argv) runtime_failed_teardown(); runtime_detached_mount(&ns,&root); runtime_new_mount_api(&ns,&root,fs); + runtime_proc_mount_api(&ns,&root,fs); runtime_attachment_policies(&ns,&root); runtime_mount_syscalls(&ns,&root,fs); runtime_file_bind(&ns,&root,fs); From 82309f0398d410682bc0efe431246a102171bdb0 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 14:19:20 +0800 Subject: [PATCH 31/97] feat(procfs): add per-mount hidepid visibility policy --- .../en/LC_MESSAGES/userspace-api/abi.po | 4 +- .../en/LC_MESSAGES/userspace-api/procfs.po | 12 ++ .../ja/LC_MESSAGES/userspace-api/abi.po | 4 +- .../ja/LC_MESSAGES/userspace-api/procfs.po | 12 ++ Documentation/userspace-api/abi.rst | 4 +- Documentation/userspace-api/procfs.rst | 15 ++ fs/proc/mount.c | 136 +++++++++++++++++- fs/vfs/pseudo.c | 70 ++++++++- include/reliefnt/procfs.h | 14 ++ include/reliefnt/pseudo_fs.h | 18 +++ kernel/syscall/fs/mount.c | 9 +- kernel/syscall/fs/mount_api.c | 12 +- tools/tests/mount_backend_test.c | 39 +++-- tools/tests/procfs_directories_test.c | 134 +++++++++++++++++ 14 files changed, 449 insertions(+), 34 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 390a7ec1..8041b7b7 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -357,8 +357,8 @@ msgstr "Filesystem Contexts and Detached Mounts" msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` creates a filesystem context. The caller needs effective ``CAP_SYS_ADMIN``. ``FSCONFIG_SET_STRING`` in ``fsconfig`` accepts the existing tmpfs options, including ``size``, ``nr_blocks``, ``nr_inodes``, ``mode``, ``uid`` and ``gid``. ``FSCONFIG_SET_FLAG`` accepts ``ro`` and ``rw``. ``FSCONFIG_CMD_CREATE`` creates the filesystem using the configured options and may be retried after failure. The context belongs to the open-file description, is shared after dup or fork, and is released with the final reference." -msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 当前 proc 上下文的参数(包括 ``hidepid``)返回 ``EINVAL``;挂载属性由 ``fsmount`` 指定。" -msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` also creates an independent proc context. ``FSCONFIG_CMD_CREATE``, ``fsmount`` and ``move_mount`` create and attach the mount. Proc context parameters, including ``hidepid``, currently return ``EINVAL``. Mount attributes are specified with ``fsmount``." +msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 ``fsmount`` 指定。策略及重配置语义见 :doc:`procfs`。" +msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` also creates an independent proc context. ``FSCONFIG_CMD_CREATE``, ``fsmount`` and ``move_mount`` create and attach the mount. ``FSCONFIG_SET_STRING`` accepts supported ``hidepid`` and ``gid`` parameters. Mount attributes are specified with ``fsmount``. See :doc:`procfs` for the policy and reconfiguration semantics." msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" msgstr "``fsmount`` returns an ``O_PATH`` descriptor for the detached mount root. It supports ``FSMOUNT_CLOEXEC`` and the readonly, nosuid, nodev, noexec and atime attributes. Files can be accessed relative to this descriptor, and the directory can be reopened via ``/proc/self/fd``. After success, the context can set new options with ``fsconfig`` and update the shared filesystem with ``FSCONFIG_CMD_RECONFIGURE``. Pending options remain after a configuration failure, so the operation can be retried after closing write descriptors that prevent a readonly transition." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po index a6158627..35c84dd1 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po @@ -364,3 +364,15 @@ msgstr "" "printing results rather than exiting and triggering kernel panic. The host ``procfs`` suite runs " "the same source on Linux; queue checks accommodate Linux buffer occupancy versus ReliefNT payload-" "byte differences." + + +msgid "每次创建 proc 文件系统均获得独立的可见性策略。传统 ``mount`` 和 proc 文件系统 上下文接受 ``hidepid=off`` 或 ``hidepid=0``,以及 ``hidepid=invisible`` 或 ``hidepid=2``。默认值为 ``off``。``gid=`` 接受 0 至 4294967294 的十进制组 ID, 默认值为 0。其他 hidepid 模式、未知选项和无效组 ID 返回 ``EINVAL``。" +msgstr "Each newly created proc filesystem has an independent visibility policy. Legacy ``mount`` and proc filesystem contexts accept ``hidepid=off`` or ``hidepid=0`` and ``hidepid=invisible`` or ``hidepid=2``. The default is ``off``. ``gid=`` accepts a decimal group ID from 0 through 4294967294, defaulting to 0. Other hidepid modes, unknown options and invalid group IDs return ``EINVAL``." + + +msgid "启用 ``invisible`` 时,进程和线程目录仅对通过现有 FSCREDS、dumpable 与 ``CAP_SYS_PTRACE`` 检查的调用者及指定组成员可见。组成员包括调用者的 fsgid 和补充组。隐藏对象的查找、枚举及已持有路径的访问返回 ``ENOENT`` 或跳过条目。 组成员仍须通过各敏感文件已有的独立权限检查。" +msgstr "With ``invisible``, process and thread directories are visible to callers passing the existing FSCREDS, dumpable and ``CAP_SYS_PTRACE`` checks and to members of the specified group. Membership includes the caller’s fsgid and supplementary groups. Lookups and accesses through held paths return ``ENOENT`` for hidden objects, and enumeration skips them. Group members still need to pass the separate existing checks on sensitive files." + + +msgid "绑定和克隆挂载共享原实例的策略,单独创建的 proc 实例互不影响。重挂载及文件 系统上下文重配置只更新显式提供的选项,全部解析成功后才应用。失败时原策略与 挂载标志保持不变。已经打开并捕获的文件视图继续遵守原有的读取生命周期,重新 打开和后续路径操作检查当前策略。" +msgstr "Bind and cloned mounts share the original instance policy. Separately created proc instances are independent. Remount and filesystem-context reconfiguration update only explicitly supplied options and apply them after complete parsing succeeds. Failure preserves the previous policy and mount flags. Already opened and captured file views retain their existing read lifecycle. Reopening and later path operations check the current policy." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 0e281276..be7a8330 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -312,8 +312,8 @@ msgstr "ファイルシステムコンテキストと未接続マウント" msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` はファイルシステムコンテキストを作成します。呼び出し元には有効な ``CAP_SYS_ADMIN`` が必要です。``fsconfig`` の ``FSCONFIG_SET_STRING`` は ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid``、``gid`` などの既存の tmpfs オプションを受け付けます。``FSCONFIG_SET_FLAG`` は ``ro`` と ``rw`` を受け付けます。``FSCONFIG_CMD_CREATE`` は設定済みオプションでファイルシステムを作成し、失敗後に再試行できます。コンテキストはオープンファイル記述に属し、dup または fork 後に共有され、最後の参照が解放されると破棄されます。" -msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 当前 proc 上下文的参数(包括 ``hidepid``)返回 ``EINVAL``;挂载属性由 ``fsmount`` 指定。" -msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` でも独立した proc コンテキストを作成できます。``FSCONFIG_CMD_CREATE``、``fsmount``、``move_mount`` でマウントを作成して接続します。現在、``hidepid`` を含む proc コンテキストのパラメーターは ``EINVAL`` を返します。マウント属性は ``fsmount`` で指定します。" +msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 ``fsmount`` 指定。策略及重配置语义见 :doc:`procfs`。" +msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` でも独立した proc コンテキストを作成できます。``FSCONFIG_CMD_CREATE``、``fsmount``、``move_mount`` でマウントを作成して接続します。``FSCONFIG_SET_STRING`` は対応する ``hidepid`` と ``gid`` のパラメーターを受け付けます。マウント属性は ``fsmount`` で指定します。ポリシーと再設定の意味は :doc:`procfs` を参照してください。" msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" msgstr "``fsmount`` は未接続マウントのルートを指す ``O_PATH`` ディスクリプタを返し、``FSMOUNT_CLOEXEC`` と読み取り専用、nosuid、nodev、noexec、atime の属性をサポートします。このディスクリプタを基点にファイルへアクセスでき、``/proc/self/fd`` からディレクトリを開き直すこともできます。成功後、コンテキストは ``fsconfig`` で新しいオプションを設定し、``FSCONFIG_CMD_RECONFIGURE`` で共有ファイルシステムを更新できます。設定失敗時には保留中のオプションが保持されるため、読み取り専用への変更を妨げる書き込みディスクリプタを閉じて再試行できます。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po index 7a351c84..116ede41 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po @@ -318,3 +318,15 @@ msgstr "" "で起動でき、ノードの短い読み取り、seek/EOF、maps/PSS、auxv、スレッドディレクトリー、クローン後の ``thread-self``、fdinfo、実際の UDP " "受信キューの受け入れ結果をシリアルに出力します。PID 1 の場合は結果出力後に待機し、終了してカーネル panic を起こさないようにします。同じソースをホストの ``procfs`` " "スイートでも Linux 上で実行し、キュー検査は Linux のバッファー占有量と ReliefNT のペイロードバイト数の差を考慮します。" + + +msgid "每次创建 proc 文件系统均获得独立的可见性策略。传统 ``mount`` 和 proc 文件系统 上下文接受 ``hidepid=off`` 或 ``hidepid=0``,以及 ``hidepid=invisible`` 或 ``hidepid=2``。默认值为 ``off``。``gid=`` 接受 0 至 4294967294 的十进制组 ID, 默认值为 0。其他 hidepid 模式、未知选项和无效组 ID 返回 ``EINVAL``。" +msgstr "proc ファイルシステムを作成するたびに独立した可視性ポリシーが与えられます。従来の ``mount`` と proc ファイルシステムコンテキストは ``hidepid=off`` または ``hidepid=0``、および ``hidepid=invisible`` または ``hidepid=2`` を受け付けます。既定値は ``off`` です。``gid=`` は 0 から 4294967294 までの十進数のグループ ID を受け付け、既定値は 0 です。その他の hidepid モード、不明なオプション、無効なグループ ID は ``EINVAL`` を返します。" + + +msgid "启用 ``invisible`` 时,进程和线程目录仅对通过现有 FSCREDS、dumpable 与 ``CAP_SYS_PTRACE`` 检查的调用者及指定组成员可见。组成员包括调用者的 fsgid 和补充组。隐藏对象的查找、枚举及已持有路径的访问返回 ``ENOENT`` 或跳过条目。 组成员仍须通过各敏感文件已有的独立权限检查。" +msgstr "``invisible`` では、既存の FSCREDS、dumpable、``CAP_SYS_PTRACE`` の検査を通過した呼び出し元と指定グループのメンバーにプロセスおよびスレッドのディレクトリーが見えます。グループ所属には呼び出し元の fsgid と補助グループを含みます。隠れたオブジェクトの検索と保持済みパスからのアクセスは ``ENOENT`` を返し、列挙では項目を省きます。グループメンバーも機微なファイルに対する既存の個別の権限検査を通過する必要があります。" + + +msgid "绑定和克隆挂载共享原实例的策略,单独创建的 proc 实例互不影响。重挂载及文件 系统上下文重配置只更新显式提供的选项,全部解析成功后才应用。失败时原策略与 挂载标志保持不变。已经打开并捕获的文件视图继续遵守原有的读取生命周期,重新 打开和后续路径操作检查当前策略。" +msgstr "bind マウントとクローンされたマウントは元のインスタンスのポリシーを共有します。別々に作成した proc インスタンスは互いに独立しています。再マウントとファイルシステムコンテキストの再設定は明示されたオプションだけを更新し、すべての解析が成功してから適用します。失敗時は以前のポリシーとマウントフラグを保持します。すでに開いて取得したファイルビューは既存の読み取りライフサイクルに従い、再オープンと後続のパス操作は現在のポリシーを検査します。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 7654d61c..d71d8c64 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -112,8 +112,8 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 ``fsopen("proc", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 -当前 proc 上下文的参数(包括 ``hidepid``)返回 ``EINVAL``;挂载属性由 -``fsmount`` 指定。 +``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 +``fsmount`` 指定。策略及重配置语义见 :doc:`procfs`。 ``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, diff --git a/Documentation/userspace-api/procfs.rst b/Documentation/userspace-api/procfs.rst index 83612293..7713233d 100644 --- a/Documentation/userspace-api/procfs.rst +++ b/Documentation/userspace-api/procfs.rst @@ -115,6 +115,21 @@ sendfile 等全部 Linux I/O 记账,也不保留已回收线程的历史组内 权限与读取语义 ============== +每次创建 proc 文件系统均获得独立的可见性策略。传统 ``mount`` 和 proc 文件系统 +上下文接受 ``hidepid=off`` 或 ``hidepid=0``,以及 ``hidepid=invisible`` 或 +``hidepid=2``。默认值为 ``off``。``gid=`` 接受 0 至 4294967294 的十进制组 ID, +默认值为 0。其他 hidepid 模式、未知选项和无效组 ID 返回 ``EINVAL``。 + +启用 ``invisible`` 时,进程和线程目录仅对通过现有 FSCREDS、dumpable 与 +``CAP_SYS_PTRACE`` 检查的调用者及指定组成员可见。组成员包括调用者的 fsgid +和补充组。隐藏对象的查找、枚举及已持有路径的访问返回 ``ENOENT`` 或跳过条目。 +组成员仍须通过各敏感文件已有的独立权限检查。 + +绑定和克隆挂载共享原实例的策略,单独创建的 proc 实例互不影响。重挂载及文件 +系统上下文重配置只更新显式提供的选项,全部解析成功后才应用。失败时原策略与 +挂载标志保持不变。已经打开并捕获的文件视图继续遵守原有的读取生命周期,重新 +打开和后续路径操作检查当前策略。 + ``maps``、``smaps``、``smaps_rollup``、``auxv``、``io`` 和 ``fdinfo`` 复用 现有的 proc FSCREDS/dumpable/``CAP_SYS_PTRACE`` 检查。仅 UID 0 不构成绕过。 PID inode 保留任务身份令牌,PID 被复用后不会自动指向新任务。 diff --git a/fs/proc/mount.c b/fs/proc/mount.c index 0f855258..a5b75894 100644 --- a/fs/proc/mount.c +++ b/fs/proc/mount.c @@ -4,8 +4,126 @@ #include #include #include +#include #include +struct proc_mount_policy { + uint32_t gid; + bool invisible; +}; + +/** @brief Compare one comma-delimited option field to a literal. + * @param start First byte. @param length Field length. @param value Literal. + * @return True when the entire field matches. + */ +static bool proc_option_equal(const char *start,size_t length,const char *value) +{ + return __builtin_strlen(value)==length && !__builtin_memcmp(start,value,length); +} + +/** @brief Parse supported proc options into a temporary policy. + * @param options Comma-separated options or NULL. @param policy In/out policy. + * @return Zero or EINVAL; caller publishes the candidate only after success. + */ +static int proc_parse_options(const char *options,struct proc_mount_policy *policy) +{ + const char *item=options; + while(item && *item) { + while(*item==',')++item; + if(!*item)break; + const char *end=item; + while(*end && *end!=',')++end; + const char *equals=item; + while(equalsinvisible=false; + else if(proc_option_equal(value,value_length,"invisible") || proc_option_equal(value,value_length,"2")) + policy->invisible=true; + else return -EINVAL; + } else if(proc_option_equal(item,key_length,"gid")) { + if(!value_length)return -EINVAL; + uint32_t gid=0; + for(const char *p=value;p'9')return -EINVAL; + uint32_t digit=(uint32_t)(*p-'0'); + if(gid>(UINT32_MAX-digit)/10)return -EINVAL; + gid=gid*10+digit; + } + if(gid==UINT32_MAX)return -EINVAL; + policy->gid=gid; + } else return -EINVAL; + item=end; + } + return 0; +} + +/** @copydoc proc_validate_mount_options */ +int proc_validate_mount_options(const char *options) +{ + struct proc_mount_policy policy={0}; + return proc_parse_options(options,&policy); +} + +/** @brief Apply the proc visibility rule to one live target task. + * @param policy Borrowed instance policy. @param target Borrowed live task. + * @return True when the current caller may observe the target. + */ +static bool proc_task_visible(const struct proc_mount_policy *policy,struct task *target) +{ + if(!policy->invisible || !target)return true; + struct task *caller=sched_current_task(); + return task_in_group(caller,policy->gid,false) || proc_stat_mm_visible(caller,target); +} + +/** @brief Check an intrinsic proc key against its instance and live identity. + * @param instance Borrowed proc policy. @param name Intrinsic key. + * @param identity Optional pinned PID identity. @return Zero or ENOENT. + */ +static int proc_key_authorize(void *instance,const char *name,void *identity) +{ + const char *leaf=NULL; + struct task *task=identity ? sched_task_identity_task(identity) : proc_view_task(name,&leaf); + return proc_task_visible(instance,task) ? 0 : -ENOENT; +} + +/** @brief Filter process and thread names from instance-specific enumeration. + * @param instance Borrowed proc policy. @param directory Intrinsic directory. + * @param name Candidate entry. @return True when the entry is visible. + */ +static bool proc_entry_visible(void *instance,const char *directory,const char *name) +{ + const char *leaf=NULL; + if(__builtin_strcmp(directory,"/proc") && + (!proc_view_task(directory,&leaf) || !leaf || __builtin_strcmp(leaf,"task")))return true; + if(*name<'0' || *name>'9')return true; + uint32_t pid=0; + for(const char *p=name;*p;++p) { + if(*p<'0' || *p>'9')return true; + uint32_t digit=(uint32_t)(*p-'0'); + if(pid>(UINT32_MAX-digit)/10)return false; + pid=pid*10+digit; + } + struct task *task=sched_find(pid); + return task && proc_task_visible(instance,task); +} + +/** @brief Atomically update explicitly supplied proc instance options. + * @param instance Borrowed live policy. @param flags Already validated flags. + * @param options Comma-separated changes. @return Zero or EINVAL. + */ +static int proc_reconfigure(void *instance,uint64_t flags,const char *options) +{ + (void)flags; + struct proc_mount_policy *policy=instance,candidate=*policy; + int rc=proc_parse_options(options,&candidate); + if(!rc)*policy=candidate; + return rc; +} + static int proc_key_identity(const char *name,void **out,bool *magic) { struct task_identity *identity=NULL; @@ -20,7 +138,7 @@ static void proc_key_put(void *identity) * @param out Required empty output receiving one owned mount on success. * @return Zero or negative errno with provider/PID references rolled back. * Execution-owned task context; the configured diagnostic alone admits writes. */ -int proc_create_vfs_mount(struct vfs_mount **out) +int proc_create_vfs_mount_options(const char *options,struct vfs_mount **out) { static const struct vfs_pseudo_provider provider={.root="/proc",.filesystem="proc",.lookup=proc_lookup, .write=proc_control_write,.truncate=proc_control_truncate, @@ -30,6 +148,18 @@ int proc_create_vfs_mount(struct vfs_mount **out) .follow=proc_mount_magic_target,.stat_link=proc_mount_magic_stat, .permissions=proc_control_permissions,.getattr=proc_getattr, .open=proc_file_open,.read_open=proc_file_read,.close=proc_file_close, - .poll_open=proc_file_poll}; - return vfs_pseudo_mount_new(&provider,out); + .poll_open=proc_file_poll,.authorize=proc_key_authorize, + .entry_visible=proc_entry_visible,.reconfigure=proc_reconfigure}; + if(!out)return -EINVAL; + *out=NULL; + struct proc_mount_policy policy={0}; + int rc=proc_parse_options(options,&policy); + if(rc)return rc; + return vfs_pseudo_mount_new_with_state(&provider,&policy,sizeof(policy),out); +} + +/** @copydoc proc_create_vfs_mount */ +int proc_create_vfs_mount(struct vfs_mount **out) +{ + return proc_create_vfs_mount_options(NULL,out); } diff --git a/fs/vfs/pseudo.c b/fs/vfs/pseudo.c index a62e53f3..7c1eed3d 100644 --- a/fs/vfs/pseudo.c +++ b/fs/vfs/pseudo.c @@ -12,7 +12,22 @@ struct pseudo_key { struct storage_node node; char name[]; }; -struct pseudo_mount {const struct vfs_pseudo_provider *provider;struct pseudo_key *keys,*pending;uint64_t next_id;}; +struct pseudo_mount { + const struct vfs_pseudo_provider *provider; + struct pseudo_key *keys,*pending; + void *instance; + uint64_t next_id; +}; + +/** @brief Recheck a provider's instance policy for a held inode identity. + * @param context Borrowed execution-owned mount context. + * @param key Live retained key. @return Zero or the provider's access error. + */ +static int pseudo_key_authorize(struct pseudo_mount *context,const struct pseudo_key *key) +{ + return context->provider->authorize ? + context->provider->authorize(context->instance,key->name,key->identity) : 0; +} static struct pseudo_key *pseudo_key_find(struct pseudo_mount *context,uint64_t id) { @@ -38,7 +53,9 @@ static void pseudo_key_free(struct pseudo_mount *context,struct pseudo_key *key) static int pseudo_key_lookup(struct pseudo_mount *context,const char *name,struct storage_node *out) { const struct vfs_pseudo_provider *provider=context->provider; - struct storage_node node;int rc=provider->lookup(name,&node); + int rc=provider->authorize ? provider->authorize(context->instance,name,NULL) : 0; + if(rc)return rc; + struct storage_node node;rc=provider->lookup(name,&node); if(rc){return rc;} void *identity=NULL;bool magic=false; if(provider->get_identity) { @@ -67,6 +84,7 @@ static int pseudo_node_lookup(void *value,const struct storage_node *parent, { struct pseudo_mount *context=value;struct pseudo_key *key=pseudo_key_find(context,parent->entry_id); if(!pseudo_key_live(context,key))return -ENOENT; + int access=pseudo_key_authorize(context,key);if(access)return access; if(parent->type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; size_t prefix=__builtin_strlen(key->name),length=__builtin_strlen(name); if(prefix+length+1>=VFS_PATH_MAX)return -ENAMETOOLONG; @@ -94,6 +112,7 @@ static int pseudo_node_readlink(void *value,const struct storage_node *node, { *length=0;struct pseudo_mount *context=value;struct pseudo_key *key=pseudo_key_find(context,node->entry_id); if(!pseudo_key_live(context,key))return -ENOENT; + int access=pseudo_key_authorize(context,key);if(access)return access; if(capacity>UINT32_MAX)return -EINVAL; if(!context->provider->readlink)return -EINVAL; int rc=context->provider->readlink(key->name,buffer,(uint32_t)capacity); @@ -104,6 +123,7 @@ static int pseudo_node_follow(void *value,const struct storage_node *node,struct { *out=(struct vfs_path){0};struct pseudo_mount *context=value;struct pseudo_key *key=pseudo_key_find(context,node->entry_id); if(!pseudo_key_live(context,key))return -ENOENT; + int access=pseudo_key_authorize(context,key);if(access)return access; return context->provider->follow ? context->provider->follow(key->name,out) : -EOPNOTSUPP; } /** @brief Read a live generated inode without fabricating filesystem atime. @@ -134,6 +154,7 @@ static int pseudo_file_open(void *value,const struct storage_node *node,uint32_t *state=NULL;struct pseudo_mount *context=value; struct pseudo_key *key=pseudo_key_find(context,node->entry_id); if(!pseudo_key_live(context,key))return -ENOENT; + int access=pseudo_key_authorize(context,key);if(access)return access; return context->provider->open ? context->provider->open(key->name,flags,state) : 0; } @@ -243,7 +264,14 @@ static int pseudo_node_readdir(void *value,const struct storage_node *node,uint6 (void)mount_flags; struct pseudo_mount *context=value;struct pseudo_key *key=pseudo_key_find(context,node->entry_id); if(!pseudo_key_live(context,key))return -ENOENT; - return context->provider->readdir ? context->provider->readdir(key->name,cursor,entry) : -EOPNOTSUPP; + int access=pseudo_key_authorize(context,key);if(access)return access; + if(!context->provider->readdir)return -EOPNOTSUPP; + int rc; + do { + rc=context->provider->readdir(key->name,cursor,entry); + } while(rc>0 && context->provider->entry_visible && + !context->provider->entry_visible(context->instance,key->name,entry->name)); + return rc; } static void pseudo_context_destroy(void *value) { @@ -259,6 +287,7 @@ static int pseudo_node_permissions(void *value,const struct vfs_path *path, const struct storage_node *node=vfs_path_node(path); struct pseudo_key *key=pseudo_key_find(context,node->entry_id); if(!pseudo_key_live(context,key))return -ENOENT; + int access=pseudo_key_authorize(context,key);if(access)return access; return context->provider->permissions ? context->provider->permissions(key->name,node,permissions,write) : -EOPNOTSUPP; } @@ -284,6 +313,21 @@ static int pseudo_remount(void *value, uint64_t flags) return (current & MS_RDONLY) && !(flags & MS_RDONLY) ? -EROFS : -EOPNOTSUPP; } +/** @brief Reconfigure instance options before publishing attachment policy. + * @param value Borrowed execution-owned pseudo filesystem context. + * @param flags Requested shared policy. @param options Copied option string. + * @return Zero or negative errno, leaving policy untouched on failure. + */ +static int pseudo_remount_options(void *value,uint64_t flags,const char *options) +{ + struct pseudo_mount *mount=value; + int rc=pseudo_remount(value,flags); + if(rc)return rc; + if(mount->provider->reconfigure) + return mount->provider->reconfigure(mount->instance,flags,options); + return options && options[0] ? -EOPNOTSUPP : 0; +} + /** @brief Obtain a live magic target's metadata under its retained identity. * @param value Borrowed provider context. @param node Retained link inode. * @param out Caller-owned target attributes, valid only on success. @@ -295,6 +339,7 @@ static int pseudo_node_stat_link(void *value,const struct storage_node *node,str struct pseudo_mount *context=value; struct pseudo_key *key=pseudo_key_find(context,node->entry_id); if(!pseudo_key_live(context,key))return -ENOENT; + int access=pseudo_key_authorize(context,key);if(access)return access; return context->provider->stat_link ? context->provider->stat_link(key->name,out) : -EOPNOTSUPP; } @@ -333,11 +378,13 @@ static int pseudo_node_statfs(void *value,const struct storage_node *node,struct * @param out Required empty output receiving one owned detached mount. * @return Zero or negative errno with context, keys and provider pins balanced. * Execution-owned task context; callbacks run without graph/module spinlocks. */ -int vfs_pseudo_mount_new(const struct vfs_pseudo_provider *provider,struct vfs_mount **out) +int vfs_pseudo_mount_new_with_state(const struct vfs_pseudo_provider *provider, + const void *initial,size_t size,struct vfs_mount **out) { if(!out)return -EINVAL; *out=NULL; if(!provider || !provider->root || provider->root[0]!='/' || !provider->lookup || + (size && !initial) || size>SIZE_MAX-sizeof(struct pseudo_mount) || (provider->get_identity && (!provider->identity_alive || !provider->put_identity)) || ((provider->open || provider->read_open || provider->close) && (!provider->open || !provider->read_open || !provider->close)))return -EINVAL; @@ -349,10 +396,13 @@ int vfs_pseudo_mount_new(const struct vfs_pseudo_provider *provider,struct vfs_m .readdir=pseudo_node_readdir,.permissions=pseudo_node_permissions, .file_open=pseudo_file_open,.file_read=pseudo_file_read,.file_close=pseudo_file_close, .file_poll=pseudo_file_poll, - .mount_flags=pseudo_mount_flags,.remount=pseudo_remount,.getattr=pseudo_node_getattr,.statfs=pseudo_node_statfs}; - struct pseudo_mount *context=kernel_malloc(sizeof(*context));int rc=-ENOMEM; + .mount_flags=pseudo_mount_flags,.remount=pseudo_remount,.remount_options=pseudo_remount_options, + .getattr=pseudo_node_getattr,.statfs=pseudo_node_statfs}; + struct pseudo_mount *context=kernel_malloc(sizeof(*context)+size);int rc=-ENOMEM; if(context) { - *context=(struct pseudo_mount){.provider=provider,.next_id=1};struct storage_node root; + *context=(struct pseudo_mount){.provider=provider,.instance=size ? context+1 : NULL,.next_id=1}; + if(size)__builtin_memcpy(context->instance,initial,size); + struct storage_node root; rc=pseudo_key_lookup(context,provider->root,&root); if(!rc)rc=vfs_mount_new(&ops,context,provider->owner,&root,out); if(rc)pseudo_context_destroy(context); @@ -365,3 +415,9 @@ int vfs_pseudo_mount_new(const struct vfs_pseudo_provider *provider,struct vfs_m } module_put(provider->owner);return rc; } + +/** @copydoc vfs_pseudo_mount_new */ +int vfs_pseudo_mount_new(const struct vfs_pseudo_provider *provider,struct vfs_mount **out) +{ + return vfs_pseudo_mount_new_with_state(provider,NULL,0,out); +} diff --git a/include/reliefnt/procfs.h b/include/reliefnt/procfs.h index f205bda2..39fe279b 100644 --- a/include/reliefnt/procfs.h +++ b/include/reliefnt/procfs.h @@ -10,4 +10,18 @@ * inside proc remain independent of namespace attachment, overmount or MS_MOVE. */ int proc_create_vfs_mount(struct vfs_mount **out); + +/** @brief Validate proc mount options without changing an instance. + * @param options Comma-separated options, nullable for defaults. + * @return Zero or EINVAL for an unsupported or malformed option. + */ +int proc_validate_mount_options(const char *options); + +/** @brief Create an independent proc filesystem with selected visibility policy. + * @param options Comma-separated proc options, nullable for defaults. + * @param out Empty output receiving a detached mount, empty on failure. + * @return Zero or negative errno with all mount and identity references balanced. + * Task context under execution ownership; cloned attachments share the policy. + */ +int proc_create_vfs_mount_options(const char *options,struct vfs_mount **out); #endif diff --git a/include/reliefnt/pseudo_fs.h b/include/reliefnt/pseudo_fs.h index 3f8d13fd..20419d99 100644 --- a/include/reliefnt/pseudo_fs.h +++ b/include/reliefnt/pseudo_fs.h @@ -44,6 +44,12 @@ struct vfs_pseudo_provider { /* Optional provider-specific attributes after generic metadata is filled. * The intrinsic key and its identity remain valid during the call. */ void (*getattr)(const char *name,struct linux_stat_abi *out); + /* Optional instance policy. authorize returns zero or an access error; + * identity is NULL before a new key has acquired its provider pin. + * entry_visible returns false to skip an enumerated entry. */ + int (*authorize)(void *instance,const char *name,void *identity); + bool (*entry_visible)(void *instance,const char *directory,const char *name); + int (*reconfigure)(void *instance,uint64_t flags,const char *options); }; /** @brief Create a referenced generated-file filesystem with owned inode keys. @@ -56,4 +62,16 @@ struct vfs_pseudo_provider { * MS_MOVE do not alter intrinsic keys. No graph lock spans callbacks. */ int vfs_pseudo_mount_new(const struct vfs_pseudo_provider *provider,struct vfs_mount **out); + +/** @brief Create a generated filesystem with an independently copied policy. + * @param provider Persistent builtin/module descriptor with optional instance callbacks. + * @param initial Borrowed initial policy bytes, required when size is nonzero. + * @param size Policy size in bytes; the copy remains valid until final teardown. + * @param out Empty output receiving a detached mount, empty on failure. + * @return Zero or negative errno with provider and context ownership balanced. + * Cloned attachments share this instance. Execution ownership serializes its + * callbacks and reconfiguration without holding the mount graph lock. + */ +int vfs_pseudo_mount_new_with_state(const struct vfs_pseudo_provider *provider, + const void *initial,size_t size,struct vfs_mount **out); #endif diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index f4632460..346a3275 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -138,7 +138,7 @@ static int mount_remount(struct vfs_namespace *ns,struct task *task,uint64_t tar * @param source Copied kernel source label; its user pointer is passed separately. * @param source_user Original user source pathname for a disk filesystem. * @param type Copied filesystem type, empty for existing native detection. - * @param options Copied options for tmpfs, devpts, cgroup2, FAT or ext3. + * @param options Copied filesystem-specific options. * @param flags Final mount policy without operation bits. * @param out Receives one owned detached mount, empty on failure. * @return Zero or unsupported/device/lookup/provider errno. Source resolution @@ -152,6 +152,10 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * if(!__builtin_strcmp(type,"devpts"))return devpts_create_vfs_mount(source,flags,options,task->fsuid,task->fsgid,out); if(!__builtin_strcmp(type,"devtmpfs"))return devtmpfs_create_vfs_mount(source,flags,options,out); if(!__builtin_strcmp(type,"tmpfs"))return storage_new_tmpfs_mount(source,flags,options,task->fsuid,task->fsgid,out); + if(!__builtin_strcmp(type,"proc")) { + if(flags&(VFS_SUPER_POLICY_MASK&~MS_RDONLY))return -RELIEFOS_EOPNOTSUPP; + return proc_create_vfs_mount_options(options,out); + } /* The ext3 engine always uses ordered metadata transactions. Consume only * that supported mode before the common FAT option validation/application. */ if (!__builtin_strcmp(type,"ext3") && !__builtin_strcmp(options,"data=ordered")) @@ -164,8 +168,7 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * if (result) return result; } int rc; - if(!__builtin_strcmp(type,"proc"))rc=proc_create_vfs_mount(out); - else if(!__builtin_strcmp(type,"sysfs"))rc=sysfs_create_vfs_mount(out); + if(!__builtin_strcmp(type,"sysfs"))rc=sysfs_create_vfs_mount(out); else if(!__builtin_strcmp(type,"devfs"))rc=devfs_create_vfs_mount(out); else { struct vfs_lookup_result found={0}; diff --git a/kernel/syscall/fs/mount_api.c b/kernel/syscall/fs/mount_api.c index 752b73bf..59ece6f5 100644 --- a/kernel/syscall/fs/mount_api.c +++ b/kernel/syscall/fs/mount_api.c @@ -94,12 +94,9 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con if (!rc && command == FSCONFIG_SET_STRING) rc = task_lookup_user_text(task, value_user, VFS_PATH_MAX, false, &value); if (rc) goto done; - if (context->type == SYSCALL_FS_PROC) { - rc = -RELIEFOS_EINVAL; - goto done; - } if (command == FSCONFIG_SET_FLAG) { - if (!__builtin_strcmp(key.text, "ro")) context->readonly_change = 1; + if (context->type == SYSCALL_FS_PROC) rc = -RELIEFOS_EINVAL; + else if (!__builtin_strcmp(key.text, "ro")) context->readonly_change = 1; else if (!__builtin_strcmp(key.text, "rw")) context->readonly_change = -1; else rc = -RELIEFOS_EINVAL; goto done; @@ -120,7 +117,8 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con __builtin_memcpy(option, key.text, key_length); option[key_length] = '='; __builtin_memcpy(option + key_length + 1, value.text, value_length + 1); - rc = tmpfs_validate_options(option); + rc = context->type == SYSCALL_FS_PROC ? proc_validate_mount_options(option) : + tmpfs_validate_options(option); if (rc) goto done; size_t used = __builtin_strlen(context->options); size_t extra = key_length + value_length + 1; @@ -149,7 +147,7 @@ static int mount_api_commit(struct syscall_fs_context *context, uint32_t command struct vfs_mount *mount = NULL; uint64_t flags = context->readonly_change > 0 ? MS_RDONLY : 0; if (context->type == SYSCALL_FS_PROC) - rc = proc_create_vfs_mount(&mount); + rc = proc_create_vfs_mount_options(context->options,&mount); else rc = storage_new_tmpfs_mount("none", flags, context->options, context->uid, context->gid, &mount); diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 2fd3435b..17838430 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -1575,8 +1575,22 @@ static void initial_namespace(void) * bootstrap fixture. The procfs/inventory suites exercise the real providers; * this test composes the real root/devfs/volume/shm builder and its rollback. */ static bool initial_sysfs_error; +static char proc_fixture_options[128]; +/** @brief Validate the proc options used by this constructor-boundary fixture. */ +int proc_validate_mount_options(const char *options) +{ + return !strcmp(options,"hidepid=invisible") || !strcmp(options,"gid=77") ? 0 : -EINVAL; +} +/** @brief Capture proc options before the independent RAM-root fixture is built. */ +int proc_create_vfs_mount_options(const char *options,struct vfs_mount **out) +{ + assert(!vfs_system_namespace()); + assert(strlen(options)nofile.rlim_cur=32; vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); @@ -2704,13 +2719,16 @@ static void runtime_proc_mount_api(struct vfs_namespace *ns,const struct vfs_pat assert(task_descriptor_for_fd(&actor,context)->fd_flags & RELIEFOS_FD_CLOEXEC); assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, (uintptr_t)user.size,(uintptr_t)user.bytes,0)==-EINVAL); - assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, - (uintptr_t)user.hidepid,(uintptr_t)user.invisible,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.hidepid,(uintptr_t)user.invisible,0)); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.gid,(uintptr_t)user.group,0)); test_fail_heap_after=0; assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)==-ENOMEM); test_fail_heap_after=-1; assert(scoped_mount_call(ns,&actor,__NR_fsmount,context,0,0,0,0)==-EINVAL); assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)); + assert(!strcmp(proc_fixture_options,"hidepid=invisible,gid=77")); assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)==-EBUSY); int mountfd=scoped_mount_call(ns,&actor,__NR_fsmount,context,1,0x0e,0,0); assert(mountfd>=0); @@ -2725,12 +2743,17 @@ static void runtime_proc_mount_api(struct vfs_namespace *ns,const struct vfs_pat assert(vfs_path_equal(&attached,&mount_file->path_ref)); task_discard_file_fd(&actor,context);task_discard_file_fd(&actor,mountfd); assert(!vfs_mount_unmount(ns,&attached));vfs_path_put(&attached); + assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,(uintptr_t)user.type, + (uintptr_t)user.target,(uintptr_t)user.type,0,(uintptr_t)user.options)); + assert(!strcmp(proc_fixture_options,user.options)); + assert(!vfs_path_lookup(ns,root,root,user.target,0,&attached)); + assert(!vfs_mount_unmount(ns,&attached));vfs_path_put(&attached); assert(!tmpfs_unlink(fs,user.target,true)); vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); assert(!g_volumes[4].vfs_mounts && !storage_inode_volume_busy(4)); tmpfs_destroy(proc_fixture);g_volumes[4]=(struct storage_volume){0}; lookup_user_base=lookup_user_bytes=0; - puts("PASS proc mount API: option rejection, create retry and attachment"); + puts("PASS proc mount API: parameter validation, create retry, legacy options and attachment"); } /** @brief Read a generated cgroup control by its retained inode and check exact bytes. */ diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index 50f6486b..679afaa9 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -568,6 +568,139 @@ static void test_proc_mount_objects(void) sched_task_identity_detach(¤t); puts("PASS real proc mount: moved attachments, magic links and target graph retained across PID exit"); } +/** @brief Exercise per-instance process visibility through retained VFS paths. */ +static void test_proc_mount_hidepid(void) +{ + struct vfs_mount *first = NULL, *second = NULL, *created = NULL, *clone = NULL; + struct vfs_namespace first_ns = {0}, second_ns = {0}, created_ns = {0}, clone_ns = {0}; + struct vfs_path first_root = {0}, second_root = {0}, created_root = {0}, clone_root = {0}; + struct vfs_path held = {0}, held_file = {0}, held_link = {0}, found = {0}; + struct vfs_open_file *opened = NULL, *denied = NULL; + struct linux_stat_abi status; + struct reliefos_dir_entry entry; + uint64_t cursor; + uint32_t got; + size_t link_length; + char text[256]; + uint32_t old_fsuid = current.fsuid, old_fsgid = current.fsgid; + uint64_t old_caps = current.cap_effective; + + current.fsuid = current.fsgid = 1000; + current.cap_effective = 0; + extra_tasks[0] = (struct task){.pid = 43, .name = "hidden", + .uid = 2000, .euid = 2000, .suid = 2000, .fsuid = 2000, + .gid = 2000, .egid = 2000, .sgid = 2000, .fsgid = 2000}; + visible_tasks = 2; + + assert(!proc_create_vfs_mount(&first) && !proc_create_vfs_mount(&second)); + assert(!vfs_namespace_init(&first_ns, first) && !vfs_namespace_init(&second_ns, second)); + vfs_mount_put(first); + vfs_mount_put(second); + assert(!vfs_namespace_root(&first_ns, &first_root)); + assert(!vfs_namespace_root(&second_ns, &second_root)); + assert(!vfs_path_lookup_child(&first_root, "43", &held)); + assert(!vfs_path_lookup_child(&held, "status", &held_file)); + assert(!vfs_path_lookup_child(&held, "cwd", &held_link)); + assert(!vfs_file_open(&held_file, 0, &opened) && opened); + assert(!proc_create_vfs_mount_options("hidepid=2,gid=77", &created)); + assert(!vfs_namespace_init(&created_ns, created)); + vfs_mount_put(created); + assert(!vfs_namespace_root(&created_ns, &created_root)); + assert(vfs_path_lookup_child(&created_root, "43", &found) == -ENOENT); + assert(!vfs_mount_clone_root(&first_root, &clone)); + assert(!vfs_namespace_init(&clone_ns, clone)); + vfs_mount_put(clone); + assert(!vfs_namespace_root(&clone_ns, &clone_root)); + + assert(!vfs_path_remount_options(&first_root, 0, "hidepid=invisible,gid=77")); + assert(vfs_path_lookup_child(&first_root, "43", &found) == -ENOENT); + assert(!vfs_path_lookup_child(&second_root, "43", &found)); + vfs_path_put(&found); + assert(vfs_path_stat(&held, &status) == -ENOENT); + assert(vfs_path_stat(&held_file, &status) == -ENOENT); + assert(vfs_path_lookup_child(&held, "status", &found) == -ENOENT); + assert(vfs_path_lookup_child(&clone_root, "43", &found) == -ENOENT); + assert(vfs_path_readlink(&held_link, text, sizeof(text), &link_length) == -ENOENT); + assert(vfs_file_open(&held_file, 0, &denied) == -ENOENT && !denied); + assert(!vfs_file_read(opened, 0, text, sizeof(text) - 1, &got)); + text[got] = 0; + assert(strstr(text, "hidden")); + cursor = 0; + while (vfs_path_readdir(&first_root, &cursor, &entry) > 0) + assert(strcmp(entry.name, "43")); + cursor = 0; + assert(vfs_path_readdir(&held, &cursor, &entry) == -ENOENT); + + current.fsgid = 77; + assert(!vfs_path_lookup_child(&first_root, "43", &found)); + vfs_path_put(&found); + assert(!vfs_path_lookup_child(&created_root, "43", &found)); + vfs_path_put(&found); + assert(!vfs_path_stat(&held, &status)); + current.fsgid = 1000; + const uint32_t groups[] = {77}; + assert(!task_groups_set(¤t, groups, 1)); + assert(!vfs_path_stat(&held, &status)); + task_groups_release(¤t); + current.cap_effective = 1ULL << CAP_SYS_PTRACE; + assert(!vfs_path_stat(&held, &status)); + current.cap_effective = 0; + + assert(vfs_path_remount_options(&first_root, MS_NOEXEC, "gid=88,hidepid=bad") == -EINVAL); + assert(!(vfs_path_mount_flags(&first_root) & MS_NOEXEC)); + current.fsgid = 77; + assert(!vfs_path_stat(&held, &status)); + current.fsgid = 1000; + assert(!vfs_path_remount_options(&clone_root, 0, "gid=88")); + assert(vfs_path_stat(&held, &status) == -ENOENT); + current.fsgid = 88; + assert(!vfs_path_stat(&held, &status)); + current.fsgid = 1000; + assert(!vfs_path_remount_options(&first_root, 0, "hidepid=off")); + assert(!vfs_path_stat(&held, &status)); + assert(!vfs_path_lookup_child(&clone_root, "43", &found)); + vfs_path_put(&found); + + extra_tasks[0].uid = extra_tasks[0].euid = extra_tasks[0].suid = 1000; + extra_tasks[0].gid = extra_tasks[0].egid = extra_tasks[0].sgid = 1000; + extra_tasks[1] = (struct task){.pid = 44, .tgid = 43, .name = "hidden-thread", + .uid = 2000, .euid = 2000, .suid = 2000, + .gid = 2000, .egid = 2000, .sgid = 2000}; + visible_tasks = 3; + assert(!vfs_path_lookup_child(&created_root, "43", &found)); + struct vfs_path thread_dir = {0}; + assert(!vfs_path_lookup_child(&found, "task", &thread_dir)); + vfs_path_put(&found); + cursor = 0; + assert(vfs_path_readdir(&thread_dir, &cursor, &entry) == 1 && !strcmp(entry.name, "43")); + assert(!vfs_path_readdir(&thread_dir, &cursor, &entry)); + assert(vfs_path_lookup_child(&thread_dir, "44", &found) == -ENOENT); + current.fsgid = 77; + assert(!vfs_path_lookup_child(&thread_dir, "44", &found)); + vfs_path_put(&found); + vfs_path_put(&thread_dir); + + vfs_file_close(opened); + vfs_path_put(&held_link); + vfs_path_put(&held_file); + vfs_path_put(&held); + vfs_path_put(&first_root); + vfs_path_put(&second_root); + vfs_path_put(&created_root); + vfs_path_put(&clone_root); + assert(!vfs_namespace_destroy(&clone_ns) && !vfs_namespace_destroy(&created_ns)); + assert(!vfs_namespace_destroy(&first_ns) && !vfs_namespace_destroy(&second_ns)); + sched_task_identity_detach(&extra_tasks[0]); + sched_task_identity_detach(&extra_tasks[1]); + extra_tasks[0] = (struct task){0}; + extra_tasks[1] = (struct task){0}; + visible_tasks = 1; + current.fsuid = old_fsuid; + current.fsgid = old_fsgid; + current.cap_effective = old_caps; + puts("PASS proc hidepid: instance isolation, clones, threads, open views and remount rollback"); +} + static void test_proc_mount_failures(void) { unsigned before=proc_allocations,failed=0,passed=0; @@ -706,6 +839,7 @@ int main(void) test_proc_mount_objects(); test_proc_mount_failures(); test_proc_mount_namespace_handles(); + test_proc_mount_hidepid(); strcpy(current.path, "/usr/lib/reliefos/apps/procsys/procsys.elf"); struct storage_node node; assert(proc_lookup("/proc/42", &node) == 0 && node.type == RELIEFOS_FS_TYPE_DIR); From 1e14b4a80b186cc91cf87774c30f3f619738807c Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 14:28:29 +0800 Subject: [PATCH 32/97] fix(fs): accept source in filesystem contexts --- .../en/LC_MESSAGES/userspace-api/abi.po | 3 + .../ja/LC_MESSAGES/userspace-api/abi.po | 3 + Documentation/userspace-api/abi.rst | 7 +++ fs/vfs/mount_tree.c | 11 +++- include/reliefnt/mount.h | 9 ++- kernel/syscall/fs/mount_api.c | 31 +++++++++- tools/tests/mount_backend_test.c | 57 +++++++++++++++++-- 7 files changed, 112 insertions(+), 9 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 8041b7b7..bc0282df 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -360,6 +360,9 @@ msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` creates a filesystem context. The msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 ``fsmount`` 指定。策略及重配置语义见 :doc:`procfs`。" msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` also creates an independent proc context. ``FSCONFIG_CMD_CREATE``, ``fsmount`` and ``move_mount`` create and attach the mount. ``FSCONFIG_SET_STRING`` accepts supported ``hidepid`` and ``gid`` parameters. Mount attributes are specified with ``fsmount``. See :doc:`procfs` for the policy and reconfiguration semantics." +msgid "tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 ``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo 中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" +msgstr "Both tmpfs and proc contexts accept the ``source`` parameter with ``FSCONFIG_SET_STRING``. Its value may be empty or contain commas and is limited to 255 bytes. If unset, the source is displayed as ``none``. Setting it twice in the same configuration phase returns ``EINVAL``. Setting parameters after successful creation and before successful ``fsmount`` returns ``EBUSY``. After a successful ``fsmount`` and each successful reconfiguration, a new ``source`` may be set for the next configuration phase. Reconfiguration does not change the existing mount's source in mountinfo. If creation or reconfiguration fails, the pending source remains available for retry." + msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" msgstr "``fsmount`` returns an ``O_PATH`` descriptor for the detached mount root. It supports ``FSMOUNT_CLOEXEC`` and the readonly, nosuid, nodev, noexec and atime attributes. Files can be accessed relative to this descriptor, and the directory can be reopened via ``/proc/self/fd``. After success, the context can set new options with ``fsconfig`` and update the shared filesystem with ``FSCONFIG_CMD_RECONFIGURE``. Pending options remain after a configuration failure, so the operation can be retried after closing write descriptors that prevent a readonly transition." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index be7a8330..a8727f71 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -315,6 +315,9 @@ msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` はファイルシステムコン msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 ``fsmount`` 指定。策略及重配置语义见 :doc:`procfs`。" msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` でも独立した proc コンテキストを作成できます。``FSCONFIG_CMD_CREATE``、``fsmount``、``move_mount`` でマウントを作成して接続します。``FSCONFIG_SET_STRING`` は対応する ``hidepid`` と ``gid`` のパラメーターを受け付けます。マウント属性は ``fsmount`` で指定します。ポリシーと再設定の意味は :doc:`procfs` を参照してください。" +msgid "tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 ``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo 中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" +msgstr "tmpfs と proc のコンテキストはどちらも ``FSCONFIG_SET_STRING`` の ``source`` パラメーターを受け付けます。値は最大 255 バイトで、空文字列やカンマを含む文字列も使用できます。未設定の場合、ソースは ``none`` と表示されます。同じ設定段階で重複して設定すると ``EINVAL`` を返します。作成が成功した後、``fsmount`` が成功する前にパラメーターを設定すると ``EBUSY`` を返します。``fsmount`` の成功後と各再設定の成功後には、次の設定段階で新しい ``source`` を設定できます。再設定は既存マウントの mountinfo に表示されるソースを変更しません。作成または再設定に失敗した場合、保留中のソースは保持され、再試行できます。" + msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" msgstr "``fsmount`` は未接続マウントのルートを指す ``O_PATH`` ディスクリプタを返し、``FSMOUNT_CLOEXEC`` と読み取り専用、nosuid、nodev、noexec、atime の属性をサポートします。このディスクリプタを基点にファイルへアクセスでき、``/proc/self/fd`` からディレクトリを開き直すこともできます。成功後、コンテキストは ``fsconfig`` で新しいオプションを設定し、``FSCONFIG_CMD_RECONFIGURE`` で共有ファイルシステムを更新できます。設定失敗時には保留中のオプションが保持されるため、読み取り専用への変更を妨げる書き込みディスクリプタを閉じて再試行できます。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index d71d8c64..54c8db4c 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -115,6 +115,13 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 ``fsmount`` 指定。策略及重配置语义见 :doc:`procfs`。 +tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 +最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 +阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 +``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 +``source``;重配置不会改变已有挂载在 mountinfo 中的来源。创建或重配置失败时 +待处理的来源保留,调用方可重试。 + ``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index de43798f..b30c81d2 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -175,13 +175,13 @@ void vfs_path_put(struct vfs_path *path) /** @brief Set diagnostic identity on a private unpublished mount. * @param mount Owned mount never exposed or published in a namespace. - * @param source Nonempty backing label. @param filesystem Nonempty type name. + * @param source Backing label, which may be empty. @param filesystem Nonempty type name. * @param device Linux encoded device number. * @return Zero or negative errno; exposed or lazily detached mounts are busy. */ int vfs_mount_describe(struct vfs_mount *mount,const char *source,const char *filesystem,uint64_t device) { - if(!mount || !source || !source[0] || !filesystem || !filesystem[0])return -EINVAL; + if(!mount || !source || !filesystem || !filesystem[0])return -EINVAL; if(mount->ns || mount->point.mount || mount->lazy_detached || mount->exposed_detached)return -EBUSY; size_t source_length=0,type_length=0; while(source[source_length])if(++source_length>=VFS_PATH_MAX)return -ENAMETOOLONG; @@ -198,6 +198,13 @@ int vfs_mount_describe(struct vfs_mount *mount,const char *source,const char *fi mount->filesystem=identity+source_length+1;mount->device=device;kernel_free(old);return 0; } +/** @copydoc vfs_mount_set_source */ +int vfs_mount_set_source(struct vfs_mount *mount,const char *source) +{ + if(!mount)return -EINVAL; + return vfs_mount_describe(mount,source,mount->filesystem ? mount->filesystem : "none",mount->device); +} + /** @brief Construct an owned detached root after live provider admission. * @param ops Persistent callbacks with lookup/retain/release/same_node required. * @param context Borrowed backend transferred to final cleanup on success. diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 88dcc658..df869098 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -244,7 +244,7 @@ static inline void vfs_namespace_put(struct vfs_namespace *ns) } /** @brief Assign immutable diagnostic identity before publishing a mount. * @param mount Owned mount not yet exposed or attached, required. - * @param source Nonempty kernel source label, copied with PATH_MAX bounds. + * @param source Kernel source label, possibly empty, copied with PATH_MAX bounds. * @param filesystem Nonempty kernel filesystem name, copied with NAME_MAX bounds. * @param device Linux encoded st_dev of this filesystem instance. * @return Zero or negative input/state/allocation errno. Replacement is atomic @@ -252,6 +252,13 @@ static inline void vfs_namespace_put(struct vfs_namespace *ns) * Serialized task context, no I/O or locks; mount retirement frees the copy. */ int vfs_mount_describe(struct vfs_mount *mount,const char *source,const char *filesystem,uint64_t device); +/** @brief Replace an unpublished mount's diagnostic source label. + * @param mount Owned mount not yet exposed or attached, required. + * @param source Kernel source label, possibly empty, copied with PATH_MAX bounds. + * @return Zero or negative input/state/allocation errno. The filesystem name + * and device stay unchanged, and allocation failure retains the old identity. + */ +int vfs_mount_set_source(struct vfs_mount *mount,const char *source); /** @brief Render proc mounts/mountinfo from the actual referenced mount graph. * @param ns Borrowed execution-owned namespace, required. * @param root Retained viewing root; mounts outside it are omitted. A lazily diff --git a/kernel/syscall/fs/mount_api.c b/kernel/syscall/fs/mount_api.c index 59ece6f5..0965d220 100644 --- a/kernel/syscall/fs/mount_api.c +++ b/kernel/syscall/fs/mount_api.c @@ -11,6 +11,7 @@ enum syscall_fs_type { /* A context belongs to one open-file description, including its duplicates. */ struct syscall_fs_context { struct vfs_path root; + char *source; uint32_t uid, gid; enum syscall_fs_type type; bool created, mounted; @@ -24,6 +25,7 @@ void syscall_fs_context_release(void *object) struct syscall_fs_context *context = object; if (!context) return; vfs_path_put(&context->root); + kernel_free(context->source); kernel_free(context); } @@ -91,8 +93,11 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con { struct task_user_text key = {0}, value = {0}; int rc = task_lookup_user_text(task, key_user, VFS_NAME_MAX + 1, false, &key); - if (!rc && command == FSCONFIG_SET_STRING) - rc = task_lookup_user_text(task, value_user, VFS_PATH_MAX, false, &value); + bool source = !rc && !__builtin_strcmp(key.text, "source"); + if (!rc && command == FSCONFIG_SET_STRING) { + rc = task_lookup_user_text(task, value_user, source ? 256 : VFS_PATH_MAX, false, &value); + if (source && rc == -RELIEFOS_ENAMETOOLONG) rc = -RELIEFOS_EINVAL; + } if (rc) goto done; if (command == FSCONFIG_SET_FLAG) { if (context->type == SYSCALL_FS_PROC) rc = -RELIEFOS_EINVAL; @@ -101,6 +106,21 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con else rc = -RELIEFOS_EINVAL; goto done; } + if (source) { + if (context->source) { + rc = -RELIEFOS_EINVAL; + goto done; + } + size_t length = __builtin_strlen(value.text) + 1; + char *copy = kernel_malloc(length); + if (!copy) { + rc = -RELIEFOS_ENOMEM; + goto done; + } + __builtin_memcpy(copy, value.text, length); + context->source = copy; + goto done; + } size_t key_length = __builtin_strlen(key.text), value_length = __builtin_strlen(value.text); char option[128]; @@ -151,6 +171,7 @@ static int mount_api_commit(struct syscall_fs_context *context, uint32_t command else rc = storage_new_tmpfs_mount("none", flags, context->options, context->uid, context->gid, &mount); + if (!rc) rc = vfs_mount_set_source(mount, context->source ? context->source : "none"); if (!rc) rc = vfs_mount_detached_root(mount, &context->root); vfs_mount_put(mount); if (!rc) context->created = true; @@ -164,6 +185,10 @@ static int mount_api_commit(struct syscall_fs_context *context, uint32_t command if (!rc) { context->options[0] = 0; context->readonly_change = 0; + if (command == FSCONFIG_CMD_RECONFIGURE) { + kernel_free(context->source); + context->source = NULL; + } } return rc; } @@ -234,6 +259,8 @@ static int64_t mount_api_mount(struct task *task, int32_t fd, uint32_t flags, ui if (rc >= 0) { task_file_bind_path(task_file_for_fd(task, rc), &root); context->mounted = true; + kernel_free(context->source); + context->source = NULL; } } vfs_path_put(&root); diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 17838430..aa8a9729 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2608,8 +2608,10 @@ static void runtime_new_mount_api(struct vfs_namespace *ns,const struct vfs_path struct { char type[8],other_type[8],inodes[16],size[8],mode[8],noswap[8],ro[4]; char count[8],bytes[16],permissions[8],target[32],empty[1],dot[2],credential[16]; + char source[8],label[32],later[32],next[32],long_source[257]; } user={"tmpfs","ramfs","nr_inodes","size","mode","noswap","ro", - "1024","1048576","0700","/new-mount-api","",".","credential"}; + "1024","1048576","0700","/new-mount-api","",".","credential", + "source","example, source","later, source","next"}; struct task actor={.pid=906,.fsuid=1000,.fsgid=1000,.cap_effective=1ULL<nofile.rlim_cur=32; vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); @@ -2641,11 +2643,18 @@ static void runtime_new_mount_api(struct vfs_namespace *ns,const struct vfs_path task_discard_file_fd(&actor,replacement); context=duplicate; assert(scoped_mount_call(ns,&actor,__NR_fsmount,context,0,0,0,0)==-EINVAL); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.source,0,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.label,0)); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.later,0)==-EINVAL); assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1,(uintptr_t)user.size,(uintptr_t)user.bytes,0)); assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.noswap,0,0)==-EINVAL); assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1,(uintptr_t)user.mode,(uintptr_t)user.permissions,0)); assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)); assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)==-EBUSY); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.later,0)==-EBUSY); test_fail_heap_after=0; assert(scoped_mount_call(ns,&actor,__NR_fsmount,context,1,0x0e,0,0)==-ENOMEM); test_fail_heap_after=-1; @@ -2658,6 +2667,7 @@ static void runtime_new_mount_api(struct vfs_namespace *ns,const struct vfs_path assert(mountfd>=0); struct task_file *mount_file=task_file_for_fd(&actor,mountfd); assert(mount_file && vfs_path_node(&mount_file->path_ref)); + assert(!strcmp(mount_file->path_ref.mount->source,user.label)); assert((vfs_path_mount_flags(&mount_file->path_ref)&(MS_NODEV|MS_NOSUID|MS_NOEXEC))== (MS_NODEV|MS_NOSUID|MS_NOEXEC)); int reopened=syscall_open_object(ns,&actor,mountfd,(uintptr_t)user.dot,LINUX_O_DIRECTORY,0); @@ -2669,11 +2679,19 @@ static void runtime_new_mount_api(struct vfs_namespace *ns,const struct vfs_path task_discard_file_fd(&actor,reopened); int writer=syscall_open_object(ns,&actor,mountfd,(uintptr_t)user.credential,LINUX_O_RDWR,0); assert(writer>=0); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.later,0)); assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.ro,0,0)); assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,7,0,0,0)==-EBUSY); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.next,0)==-EINVAL); assert(!vfs_path_write(&file,0,"s",1,&done)); task_discard_file_fd(&actor,writer); assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,7,0,0,0)); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.next,0)); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,7,0,0,0)); + assert(!strcmp(mount_file->path_ref.mount->source,user.label)); assert(vfs_path_write(&file,0,"x",1,&done)==-EROFS); assert(scoped_mount_call(ns,&actor,__NR_move_mount,mountfd,(uintptr_t)user.empty, (uint32_t)LINUX_AT_FDCWD,(uintptr_t)user.target,0x204)==-EINVAL); @@ -2682,15 +2700,43 @@ static void runtime_new_mount_api(struct vfs_namespace *ns,const struct vfs_path struct vfs_path attached={0},found={0}; assert(!vfs_path_lookup(ns,root,root,user.target,0,&attached)); assert(vfs_path_equal(&attached,&mount_file->path_ref)); + char table[4096];uint32_t table_count=0; + assert(!vfs_read_mount_table(ns,root,true,0,table,sizeof(table)-1,&table_count)); + table[table_count]=0; + assert(strstr(table," - tmpfs example,\\040source ")); assert(!vfs_path_lookup(ns,root,&attached,"credential",0,&found)); char text[8];assert(!vfs_path_read(&found,0,text,sizeof(text),&done) && done==6 && !memcmp(text,"secret",6)); vfs_path_put(&found);vfs_path_put(&file); task_discard_file_fd(&actor,context);task_discard_file_fd(&actor,mountfd); assert(!vfs_mount_unmount(ns,&attached));vfs_path_put(&attached); assert(!tmpfs_unlink(fs,user.target,true)); + + context=scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.type,0,0,0,0); + assert(context>=0); + memset(user.long_source,'x',256);user.long_source[256]=0; + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.long_source,0)==-EINVAL); + user.long_source[255]=0; + test_fail_heap_after=2; + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.long_source,0)==-ENOMEM); + test_fail_heap_after=-1; + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.long_source,0)); + task_discard_file_fd(&actor,context); + context=scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.type,0,0,0,0); + assert(context>=0); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.empty,0)); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.later,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)); + mountfd=scoped_mount_call(ns,&actor,__NR_fsmount,context,0,0,0,0); + assert(mountfd>=0 && !strcmp(task_file_for_fd(&actor,mountfd)->path_ref.mount->source,"")); + task_discard_file_fd(&actor,context);task_discard_file_fd(&actor,mountfd); vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); lookup_user_base=lookup_user_bytes=0; - puts("PASS new mount API: FD reuse, failed publication, readonly retry, reopen and attach"); + puts("PASS new mount API: source, FD reuse, failed publication, readonly retry, reopen and attach"); } /** @brief Exercise proc context and legacy mount option forwarding. */ @@ -2705,9 +2751,9 @@ static void runtime_proc_mount_api(struct vfs_namespace *ns,const struct vfs_pat .tmpfs=proc_fixture}; struct { char type[8], size[8], bytes[16], hidepid[8], invisible[16], gid[8], group[8]; - char options[40], target[32], empty[1]; + char options[40], target[32], empty[1], source[8]; } user={"proc","size","1048576","hidepid","invisible","gid","77", - "hidepid=invisible,gid=77","/proc-new-api",""}; + "hidepid=invisible,gid=77","/proc-new-api","","source"}; struct task actor={.pid=907,.cap_effective=1ULL<nofile.rlim_cur=32; vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); @@ -2717,6 +2763,8 @@ static void runtime_proc_mount_api(struct vfs_namespace *ns,const struct vfs_pat int context=scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.type,1,0,0,0); assert(context>=0); assert(task_descriptor_for_fd(&actor,context)->fd_flags & RELIEFOS_FD_CLOEXEC); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.type,0)); assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, (uintptr_t)user.size,(uintptr_t)user.bytes,0)==-EINVAL); assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, @@ -2734,6 +2782,7 @@ static void runtime_proc_mount_api(struct vfs_namespace *ns,const struct vfs_pat assert(mountfd>=0); struct task_file *mount_file=task_file_for_fd(&actor,mountfd); assert(mount_file && vfs_path_node(&mount_file->path_ref)->volume_id==4); + assert(!strcmp(mount_file->path_ref.mount->source,"proc")); assert((vfs_path_mount_flags(&mount_file->path_ref)&(MS_NODEV|MS_NOSUID|MS_NOEXEC))== (MS_NODEV|MS_NOSUID|MS_NOEXEC)); assert(!scoped_mount_call(ns,&actor,__NR_move_mount,mountfd,(uintptr_t)user.empty, From 4527adfebe164cc2bf5a043e7fb6f0d1e5d5529d Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 14:46:49 +0800 Subject: [PATCH 33/97] fix(kbuild): include build metadata in module identity --- Documentation/kbuild/building.rst | 5 +++-- Documentation/kbuild/modules.rst | 4 ++++ .../locale/en/LC_MESSAGES/kbuild/building.po | 16 +++++++++------- .../locale/en/LC_MESSAGES/kbuild/modules.po | 8 ++++++++ .../locale/ja/LC_MESSAGES/kbuild/building.po | 10 ++++++---- .../locale/ja/LC_MESSAGES/kbuild/modules.po | 7 +++++++ scripts/Makefile.products | 2 +- scripts/module-abi.sh | 5 +++-- tools/test_kbuild_modules.py | 11 ++++++----- tools/test_module_identity.py | 10 +++++++--- 10 files changed, 54 insertions(+), 24 deletions(-) diff --git a/Documentation/kbuild/building.rst b/Documentation/kbuild/building.rst index d06df3e5..2b1e5844 100644 --- a/Documentation/kbuild/building.rst +++ b/Documentation/kbuild/building.rst @@ -40,6 +40,7 @@ install 发布带摘要的清单,不消费父仓私有实现。 版本来自 configs/build-version,数字宏与字符串须匹配,EXTRAVERSION、 LOCALVERSION 依次追加,再附加原生模块 ABI 身份后缀,完整版本最多 31 字节。 -ABI 身份由源码、配置、工具链和编译策略产生,不使用构建时钟或输出路径。 -SOURCE_DATE_EPOCH 默认为提交时间。 +ABI 身份由源码、配置、工具链、编译策略、写入内核的源码标识和 +SOURCE_DATE_EPOCH 产生,不使用构建时钟或输出路径。SOURCE_DATE_EPOCH 默认 +为提交时间。以相同源码标识和时间构建的源码归档可以得到相同的模块身份。 htmldocs 只生成 O/Documentation/html,不需要编译内核或初始化配置。 diff --git a/Documentation/kbuild/modules.rst b/Documentation/kbuild/modules.rst index 93a8cc81..3c73ebe8 100644 --- a/Documentation/kbuild/modules.rst +++ b/Documentation/kbuild/modules.rst @@ -35,6 +35,10 @@ O/include/config/module.abi。安装目录为 /lib/modules//kernel/, 和用户模块。覆盖已修改的受管文件会导致明确错误;不再生成的旧文件若被 用户修改则予以保留,不将它作为陈旧产物删除。 +内核构建标识及 SOURCE_DATE_EPOCH 纳入 ABI 摘要,构建信息变化会产生新的 +release。要从不包含 Git 元数据的源码归档重现原有 release,需要向 make +提供相同的 RELIEFNT_SOURCE_ID 和 SOURCE_DATE_EPOCH。 + 模块元数据 ========== diff --git a/Documentation/locale/en/LC_MESSAGES/kbuild/building.po b/Documentation/locale/en/LC_MESSAGES/kbuild/building.po index aecc7465..397e1382 100644 --- a/Documentation/locale/en/LC_MESSAGES/kbuild/building.po +++ b/Documentation/locale/en/LC_MESSAGES/kbuild/building.po @@ -77,12 +77,14 @@ msgstr "" msgid "" "版本来自 configs/build-version,数字宏与字符串须匹配,EXTRAVERSION、 LOCALVERSION 依次追加,再附加原生模块 ABI 身份后缀,完整版本最多 31 " -"字节。 ABI 身份由源码、配置、工具链和编译策略产生,不使用构建时钟或输出路径。 SOURCE_DATE_EPOCH 默认为提交时间。 htmldocs 只生成 " -"O/Documentation/html,不需要编译内核或初始化配置。" +"字节。 ABI 身份由源码、配置、工具链、编译策略、写入内核的源码标识和 SOURCE_DATE_EPOCH 产生,不使用构建时钟或输出路径。SOURCE_DATE_EPOCH 默认 " +"为提交时间。以相同源码标识和时间构建的源码归档可以得到相同的模块身份。 htmldocs 只生成 O/Documentation/html,不需要编译内核或初始化配置。" msgstr "" -"The version comes from configs/build-version. Numeric macros and strings must agree; EXTRAVERSION " -"and LOCALVERSION are appended in that order, followed by the native module ABI identity suffix. " +"The version comes from configs/build-version. Numeric macros and strings must agree. EXTRAVERSION" +" and LOCALVERSION are appended in that order, followed by the native module ABI identity suffix. " "The full version is limited to 31 bytes. ABI identity is derived from source, configuration, " -"toolchain, and compilation policy, not the build clock or output path. SOURCE_DATE_EPOCH defaults " -"to the commit time. htmldocs generates only O/Documentation/html and requires neither a kernel " -"build nor configuration initialization." +"toolchain, compilation policy, the source identifier embedded in the kernel, and " +"SOURCE_DATE_EPOCH. It does not use the build clock or output path. SOURCE_DATE_EPOCH defaults to " +"the commit time. Source archives built with the same source identifier and time can reproduce the" +" same module identity. htmldocs generates only O/Documentation/html and requires neither a kernel" +" build nor configuration initialization." \ No newline at end of file diff --git a/Documentation/locale/en/LC_MESSAGES/kbuild/modules.po b/Documentation/locale/en/LC_MESSAGES/kbuild/modules.po index 0e4a80a2..d854335b 100644 --- a/Documentation/locale/en/LC_MESSAGES/kbuild/modules.po +++ b/Documentation/locale/en/LC_MESSAGES/kbuild/modules.po @@ -65,6 +65,14 @@ msgstr "" "produces an explicit error. A formerly generated file modified by the user is preserved rather " "than removed as stale." +msgid "" +"内核构建标识及 SOURCE_DATE_EPOCH 纳入 ABI 摘要,构建信息变化会产生新的 release。要从不包含 Git 元数据的源码归档重现原有 release,需要向 make " +"提供相同的 RELIEFNT_SOURCE_ID 和 SOURCE_DATE_EPOCH。" +msgstr "" +"The kernel build identifier and SOURCE_DATE_EPOCH are included in the ABI digest, so changes to " +"build information produce a new release. To reproduce an existing release from a source archive " +"without Git metadata, provide the same RELIEFNT_SOURCE_ID and SOURCE_DATE_EPOCH to make." + msgid "模块元数据" msgstr "Module Metadata" diff --git a/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po b/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po index 4f0fa93f..ffe34d01 100644 --- a/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po +++ b/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po @@ -71,10 +71,12 @@ msgstr "" msgid "" "版本来自 configs/build-version,数字宏与字符串须匹配,EXTRAVERSION、 LOCALVERSION 依次追加,再附加原生模块 ABI 身份后缀,完整版本最多 31 " -"字节。 ABI 身份由源码、配置、工具链和编译策略产生,不使用构建时钟或输出路径。 SOURCE_DATE_EPOCH 默认为提交时间。 htmldocs 只生成 " -"O/Documentation/html,不需要编译内核或初始化配置。" +"字节。 ABI 身份由源码、配置、工具链、编译策略、写入内核的源码标识和 SOURCE_DATE_EPOCH 产生,不使用构建时钟或输出路径。SOURCE_DATE_EPOCH 默认 " +"为提交时间。以相同源码标识和时间构建的源码归档可以得到相同的模块身份。 htmldocs 只生成 O/Documentation/html,不需要编译内核或初始化配置。" msgstr "" "バージョンは configs/build-version に由来し、数値マクロと文字列は一致する必要があります。EXTRAVERSION、LOCALVERSION " "の順に追加し、続いてネイティブモジュール ABI の識別接尾辞を付けます。完全なバージョンは最大 31 バイトです。ABI " -"識別情報はソース、設定、ツールチェーン、コンパイル方針から生成し、ビルド時刻や出力パスは使いません。SOURCE_DATE_EPOCH のデフォルトはコミット時刻です。htmldocs は " -"O/Documentation/html だけを生成し、カーネルのコンパイルや設定の初期化は不要です。" +"識別情報はソース、設定、ツールチェーン、コンパイル方針、カーネルに埋め込むソース識別子と SOURCE_DATE_EPOCH " +"から生成し、ビルド時刻や出力パスは使いません。SOURCE_DATE_EPOCH " +"のデフォルトはコミット時刻です。同じソース識別子と時刻でビルドしたソースアーカイブでは、同じモジュール識別情報を再現できます。htmldocs は O/Documentation/html " +"だけを生成し、カーネルのコンパイルや設定の初期化は不要です。" \ No newline at end of file diff --git a/Documentation/locale/ja/LC_MESSAGES/kbuild/modules.po b/Documentation/locale/ja/LC_MESSAGES/kbuild/modules.po index 7493e244..60a6da36 100644 --- a/Documentation/locale/ja/LC_MESSAGES/kbuild/modules.po +++ b/Documentation/locale/ja/LC_MESSAGES/kbuild/modules.po @@ -60,6 +60,13 @@ msgstr "" "を使います。対応するインストールマニフェストが管理する古い成果物だけを削除し、他の release " "やユーザーモジュールは保持します。変更済みの管理ファイルを上書きすると明示的なエラーになります。生成されなくなった古いファイルもユーザーが変更していれば保持し、不要な成果物として削除しません。" +msgid "" +"内核构建标识及 SOURCE_DATE_EPOCH 纳入 ABI 摘要,构建信息变化会产生新的 release。要从不包含 Git 元数据的源码归档重现原有 release,需要向 make " +"提供相同的 RELIEFNT_SOURCE_ID 和 SOURCE_DATE_EPOCH。" +msgstr "" +"カーネルのビルド識別子と SOURCE_DATE_EPOCH は ABI ダイジェストに含まれるため、ビルド情報が変わると新しい release が生成されます。Git " +"メタデータを含まないソースアーカイブから既存の release を再現するには、同じ RELIEFNT_SOURCE_ID と SOURCE_DATE_EPOCH を make に指定します。" + msgid "模块元数据" msgstr "モジュールメタデータ" diff --git a/scripts/Makefile.products b/scripts/Makefile.products index 83b17b5d..65ed17fa 100644 --- a/scripts/Makefile.products +++ b/scripts/Makefile.products @@ -37,7 +37,7 @@ $(obj)/include/generated/build_info.h: \ quiet_cmd_reliefnt_module_abi = GEN $@ cmd_reliefnt_module_abi = $(CONFIG_SHELL) $(srctree)/scripts/module-abi.sh \ '$(srctree)' '$(objtree)' '$(RELIEFNT_MODULE_ABI_POLICY)' \ - '$(EXTRAVERSION)' '$(LOCALVERSION)' + '$(EXTRAVERSION)' '$(LOCALVERSION)' '$(RELIEFNT_SOURCE_ID)' '$(SOURCE_DATE_EPOCH)' $(obj)/include/generated/module_abi.h: FORCE $(call cmd,reliefnt_module_abi) diff --git a/scripts/module-abi.sh b/scripts/module-abi.sh index e751058a..2fc38eaa 100644 --- a/scripts/module-abi.sh +++ b/scripts/module-abi.sh @@ -2,11 +2,11 @@ # SPDX-License-Identifier: Apache-2.0 # Content identity only: this inventory never supplies compilation members. set -eu -[ "$#" = 5 ] || { echo 'usage: module-abi SRC O FLAGS EXTRA LOCAL' >&2; exit 2; } +[ "$#" = 7 ] || { echo 'usage: module-abi SRC O FLAGS EXTRA LOCAL SOURCE_ID EPOCH' >&2; exit 2; } src=$(CDPATH= cd -- "$1" && pwd -P) mkdir -p "$2" out=$(CDPATH= cd -- "$2" && pwd -P) -flags=$3 extra=$4 local=$5 +flags=$3 extra=$4 local=$5 source_id=$6 epoch=$7 case "$extra$local" in *[!a-zA-Z0-9._+-]*) echo 'unsafe kernel release suffix' >&2; exit 1 ;; esac version=$(sed -n 's/^release_version=//p' "$src/configs/build-version") printf '%s\n' "$version" | awk 'BEGIN { ok=0 } /^[0-9]+\.[0-9]+\.[0-9]+$/ { ok++ } END { exit !(NR==1 && ok==1) }' || { @@ -43,6 +43,7 @@ trap 'rm -rf "$work"' EXIT HUP INT TERM sha256sum -- "$input" done < "$work/inputs" printf 'native-module-abi=1\npolicy=%s\nextra=%s\nlocal=%s\n' "$flags" "$extra" "$local" + printf 'source-id=%s\nsource-date-epoch=%s\n' "$source_id" "$epoch" for tool in cc ar ld objcopy; do printf 'tool=%s\n' "$tool" cat "$out/.reliefnt-target-$tool.id" diff --git a/tools/test_kbuild_modules.py b/tools/test_kbuild_modules.py index d1240560..148eb249 100644 --- a/tools/test_kbuild_modules.py +++ b/tools/test_kbuild_modules.py @@ -228,12 +228,13 @@ def test_native_module_products_and_transition(self): self.make("defconfig", "O=" + str(second)) disabled_config = second / ".config" disabled_config.write_text(disabled_config.read_text().replace("CONFIG_MODULES=y", "# CONFIG_MODULES is not set")) - self.make("olddefconfig", "modules_install", "O=" + str(second), "INSTALL_MOD_PATH=" + str(stage)) + identity = ["RELIEFNT_SOURCE_ID=identity-check", "SOURCE_DATE_EPOCH=1700000000"] + self.make("olddefconfig", "modules_install", "O=" + str(second), "INSTALL_MOD_PATH=" + str(stage), *identity) self.assertEqual(saved_provider, (self.output / "generated/system/kernel.sys").read_bytes()) self.assertFalse((second / "modules.order").read_text().strip()) - self.make("modules", "O="+str(second), "M="+str(external), success=False) - # Building the same source archive without .git must retain the ABI - # identity. Offline dependencies remain explicit, shared read-only. + self.make("modules", "O="+str(second), "M="+str(external), *identity, success=False) + # A source archive without .git retains the ABI identity when the + # embedded build metadata is supplied explicitly. archive = self.directory / "archive" def archive_ignored(directory, names): excluded = {".git", "__pycache__"} @@ -245,7 +246,7 @@ def archive_ignored(directory, names): self.make("defconfig", "O=" + str(archived_out), "-C", str(archive)) (archived_out / ".config").write_text(disabled_config.read_text()) self.make("olddefconfig", "modules", "O=" + str(archived_out), "-C", str(archive), - "RELIEFNT_CACHE=" + str(ROOT / "cache/downloads")) + "RELIEFNT_CACHE=" + str(ROOT / "cache/downloads"), *identity) self.assertEqual((second / "include/config/module.abi").read_bytes(), (archived_out / "include/config/module.abi").read_bytes()) allmods = self.directory / "allmod" diff --git a/tools/test_module_identity.py b/tools/test_module_identity.py index 6502e436..fb777fdd 100644 --- a/tools/test_module_identity.py +++ b/tools/test_module_identity.py @@ -30,8 +30,9 @@ def test_reproducible_and_changes_invalidate(self): (out / ".config").write_text("# generated\nCONFIG_MODULES=y\n") for tool in ("cc", "ar", "ld", "objcopy"): (out / f".reliefnt-target-{tool}.id").write_text("a" * 64 + "\n") - def run(source=src, flags="release", extra=""): - result = subprocess.run(["sh", str(SCRIPT), str(source), str(out), flags, extra, ""], + def run(source=src, flags="release", extra="", source_id="abc1234", epoch="1795933709"): + result = subprocess.run(["sh", str(SCRIPT), str(source), str(out), flags, extra, "", + source_id, epoch], capture_output=True, text=True) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) return (out / "include/generated/module_abi.h").read_bytes() @@ -43,6 +44,8 @@ def run(source=src, flags="release", extra=""): archive = base / "relocated source" shutil.copytree(src, archive) self.assertEqual(before, run(archive)) + self.assertNotEqual(before, run(epoch="1795933710"), "build timestamp must invalidate identity") + self.assertNotEqual(before, run(source_id="def5678"), "build source ID must invalidate identity") for tool in ("cc", "ar", "ld", "objcopy"): identity_file = out / f".reliefnt-target-{tool}.id" identity_file.write_text("b" * 64 + "\n") @@ -55,7 +58,8 @@ def run(source=src, flags="release", extra=""): self.assertNotEqual(before, changed) (out / ".config").write_text("CONFIG_MODULES=y\nCONFIG_DRIVER_TEST=m\n") self.assertNotEqual(changed, run()) - result = subprocess.run(["sh", str(SCRIPT), str(src), str(out), "release", "-abcdefghijklmnopqrstuvwxyz", ""], + result = subprocess.run(["sh", str(SCRIPT), str(src), str(out), "release", + "-abcdefghijklmnopqrstuvwxyz", "", "abc1234", "1795933709"], capture_output=True) self.assertNotEqual(result.returncode, 0) release = (out / "include/config/kernel.release").read_text().strip() From 68a940e2506be1f960293dc5dd8ee890a0446a07 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 15:35:32 +0800 Subject: [PATCH 34/97] feat(kbuild): advertise built-in initramfs support --- Documentation/kbuild/building.rst | 4 ++++ Documentation/locale/en/LC_MESSAGES/kbuild/building.po | 5 ++++- Documentation/locale/ja/LC_MESSAGES/kbuild/building.po | 5 ++++- fs/Kbuild | 3 ++- fs/Kconfig | 7 +++++++ tools/test_module_config.py | 8 ++++++++ 6 files changed, 29 insertions(+), 3 deletions(-) diff --git a/Documentation/kbuild/building.rst b/Documentation/kbuild/building.rst index 2b1e5844..4b6c5b47 100644 --- a/Documentation/kbuild/building.rst +++ b/Documentation/kbuild/building.rst @@ -26,6 +26,10 @@ Kconfig 只提供内核实际消费的选项。生产 defconfig 默认将驱动 编译策略仍由 PROFILE=debug|release 控制,工具链、版本后缀和 SOURCE_DATE_EPOCH 使用独立 Make 参数。 +隐藏配置 ``CONFIG_BLK_DEV_INITRD`` 始终启用并构建内存根加载器。 +加载器接受名为 ``initramfs`` 的 Multiboot 模块,内容为未压缩的 +newc 或 crc CPIO 归档。生成 initramfs 时必须选择未压缩格式。 + 应用、系统镜像、激活策略和 QEMU 参数只属于 ReliefOS 主仓,内核不 source 主仓 Kconfig。从旧输出复制配置后运行 olddefconfig,会由原版 conf 移除外来符号。 ``make test-kconfig`` 使用隔离输出验证该边界与重复同步的稳定性,并属于默认 test。 diff --git a/Documentation/locale/en/LC_MESSAGES/kbuild/building.po b/Documentation/locale/en/LC_MESSAGES/kbuild/building.po index 397e1382..f4b42f6f 100644 --- a/Documentation/locale/en/LC_MESSAGES/kbuild/building.po +++ b/Documentation/locale/en/LC_MESSAGES/kbuild/building.po @@ -38,6 +38,9 @@ msgstr "" msgid "配置归属" msgstr "Configuration Ownership" +msgid "隐藏配置 ``CONFIG_BLK_DEV_INITRD`` 始终启用并构建内存根加载器。 加载器接受名为 ``initramfs`` 的 Multiboot 模块,内容为未压缩的 newc 或 crc CPIO 归档。生成 initramfs 时必须选择未压缩格式。" +msgstr "The hidden ``CONFIG_BLK_DEV_INITRD`` setting is always enabled and builds the memory-root loader. The loader accepts a Multiboot module named ``initramfs`` containing an uncompressed newc or crc CPIO archive. Generate initramfs images in the uncompressed format." + msgid "" "Kconfig 只提供内核实际消费的选项。生产 defconfig 默认将驱动内建, 已完成生命周期支持的部件可选择 m,构建为针对 ReliefNT 的原生 .ko。 调度、内存、VFS " "和启动基础保持内置;具体边界见 :doc:`../core-api/drivers`。 模块开发测试默认关闭;模块构建和 prepared SDK 见 :doc:`modules`。 编译策略仍由" @@ -87,4 +90,4 @@ msgstr "" "SOURCE_DATE_EPOCH. It does not use the build clock or output path. SOURCE_DATE_EPOCH defaults to " "the commit time. Source archives built with the same source identifier and time can reproduce the" " same module identity. htmldocs generates only O/Documentation/html and requires neither a kernel" -" build nor configuration initialization." \ No newline at end of file +" build nor configuration initialization." diff --git a/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po b/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po index ffe34d01..9db58ae8 100644 --- a/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po +++ b/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po @@ -37,6 +37,9 @@ msgstr "" msgid "配置归属" msgstr "設定の所属" +msgid "隐藏配置 ``CONFIG_BLK_DEV_INITRD`` 始终启用并构建内存根加载器。 加载器接受名为 ``initramfs`` 的 Multiboot 模块,内容为未压缩的 newc 或 crc CPIO 归档。生成 initramfs 时必须选择未压缩格式。" +msgstr "非表示の設定 ``CONFIG_BLK_DEV_INITRD`` は常に有効で、メモリールートローダーをビルドします。ローダーは ``initramfs`` という名前の Multiboot モジュールを受け付け、その内容は非圧縮の newc または crc CPIO アーカイブです。initramfs イメージは非圧縮形式で生成してください。" + msgid "" "Kconfig 只提供内核实际消费的选项。生产 defconfig 默认将驱动内建, 已完成生命周期支持的部件可选择 m,构建为针对 ReliefNT 的原生 .ko。 调度、内存、VFS " "和启动基础保持内置;具体边界见 :doc:`../core-api/drivers`。 模块开发测试默认关闭;模块构建和 prepared SDK 见 :doc:`modules`。 编译策略仍由" @@ -79,4 +82,4 @@ msgstr "" "識別情報はソース、設定、ツールチェーン、コンパイル方針、カーネルに埋め込むソース識別子と SOURCE_DATE_EPOCH " "から生成し、ビルド時刻や出力パスは使いません。SOURCE_DATE_EPOCH " "のデフォルトはコミット時刻です。同じソース識別子と時刻でビルドしたソースアーカイブでは、同じモジュール識別情報を再現できます。htmldocs は O/Documentation/html " -"だけを生成し、カーネルのコンパイルや設定の初期化は不要です。" \ No newline at end of file +"だけを生成し、カーネルのコンパイルや設定の初期化は不要です。" diff --git a/fs/Kbuild b/fs/Kbuild index 53f0da56..e33a7c30 100644 --- a/fs/Kbuild +++ b/fs/Kbuild @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # Objects are owned by this directory; child modules own their own lists. -obj-y := initramfs/ cgroup/ devfs/ devpts/ nsfs/ proc/ security/ sysfs/ tmpfs/ vfs/ notify/ +obj-$(CONFIG_BLK_DEV_INITRD) := initramfs/ +obj-y += cgroup/ devfs/ devpts/ nsfs/ proc/ security/ sysfs/ tmpfs/ vfs/ notify/ obj-$(CONFIG_EXT_FS_COMMON) += ext_common/ obj-$(CONFIG_EXT2_FS) += ext2/ obj-$(CONFIG_EXT3_FS) += ext3/ diff --git a/fs/Kconfig b/fs/Kconfig index 816688d9..924107f7 100644 --- a/fs/Kconfig +++ b/fs/Kconfig @@ -1,6 +1,13 @@ # SPDX-License-Identifier: Apache-2.0 menu "Filesystems" +config BLK_DEV_INITRD + bool + default y + help + Build the early memory-root loader for uncompressed newc and crc + archives supplied as the initramfs Multiboot module. + config FAT_FS tristate "FAT32 filesystem and formatter" default y diff --git a/tools/test_module_config.py b/tools/test_module_config.py index ec5389e0..0e066dfd 100644 --- a/tools/test_module_config.py +++ b/tools/test_module_config.py @@ -39,6 +39,14 @@ def test_default_is_builtin_and_loader_enabled(self): for symbol in ("DRM", "SND", "VMXNET3", "RTL8139", "FAT_FS", "EXFAT_FS", "EXT2_FS", "EXT3_FS", "EXT4_FS", "EXT_FS_COMMON", "ISO9660_FS"): self.assertIn("CONFIG_" + symbol + "=y\n", text) + def test_initramfs_capability_survives_configuration_updates(self): + self.assertIn("CONFIG_BLK_DEV_INITRD=y\n", (self.output / ".config").read_text()) + output = self.directory / "initramfs" + output.mkdir() + (output / ".config").write_text("# CONFIG_BLK_DEV_INITRD is not set\n") + run_config(["make", "-s", "-C", str(ROOT), "O=" + str(output), "olddefconfig"]) + self.assertIn("CONFIG_BLK_DEV_INITRD=y\n", (output / ".config").read_text()) + def test_native_dependency_and_disabled_modules(self): fixture = self.directory / "Kconfig.fixture" fixture.write_text(f'source "{ROOT}/kernel/module/Kconfig"\n' From 04cded7fbaf770b9a72ea309a625f3ddec191d42 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 18:19:52 +0800 Subject: [PATCH 35/97] feat(fs): support OFD byte-range locks Track record locks by the retained open file description and keep its identity across blocking retries and final close. Cover OFD/POSIX conflicts and descriptor reuse, and complete the existing gettext catalog backlog for the affected ABI checks. --- .../LC_MESSAGES/core-api/mount-namespaces.po | 9 + .../en/LC_MESSAGES/userspace-api/abi.po | 24 +++ .../LC_MESSAGES/userspace-api/descriptors.po | 3 + .../LC_MESSAGES/core-api/mount-namespaces.po | 9 + .../ja/LC_MESSAGES/userspace-api/abi.po | 24 +++ .../LC_MESSAGES/userspace-api/descriptors.po | 3 + Documentation/userspace-api/abi.rst | 23 +++ include/reliefnt/syscall_internal.h | 12 ++ include/reliefnt/task/types.h | 1 + include/uapi/linux/fcntl.h | 3 + kernel/syscall/entry.c | 17 +- kernel/syscall/fd/descriptor.c | 7 +- kernel/syscall/fd/legacy_descriptors.c | 4 +- kernel/syscall/fs/locks.c | 78 +++++++-- tools/test_linux_descriptors.py | 6 +- tools/tests/descriptor_table_test.c | 159 +++++++++++++++++- tools/tests/mount_backend_test.c | 3 + tools/tests/record_locks_test.c | 65 ++++++- tools/tests/task8_host_fixtures.json | 3 + .../task8_host_stubs/descriptor_unreached.c | 41 +++++ 20 files changed, 464 insertions(+), 30 deletions(-) create mode 100644 tools/tests/task8_host_stubs/descriptor_unreached.c diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 09927146..ccf696f6 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -182,3 +182,12 @@ msgstr "" "still own storage for boot and test graphs. The strict " "``vfs_namespace_destroy()`` refuses to destroy a graph with outstanding " "graph or external path references." + +msgid "游离挂载路径" +msgstr "Detached mount paths" + +msgid "``vfs_mount_detached_root()`` 显式暴露尚未附着的挂载根并返回持有路径。 该路径及其子项可以进行常规查找、文件操作和根挂载重配置。游离根没有通向 命名空间的父边,描述符链接和不可达的工作目录以该挂载根为基准显示。 未暴露的内部挂载继续限制路径遍历;已经 lazy-unmount 的挂载不能重新发布。" +msgstr "``vfs_mount_detached_root()`` explicitly exposes the root of a mount that has not yet been attached and returns a retained path. The path and its descendants support normal lookups, file operations and reconfiguration of the root mount. The detached root has no parent edge into a namespace. Descriptor links and unreachable working directories are rendered relative to that mount root. Internal mounts that have not been exposed still restrict traversal; a mount that has undergone lazy unmount cannot be published again." + +msgid "``vfs_mount_attach()`` 成功后,挂载和已持有路径转入目标命名空间的正常生命周期。 传播准备失败时保留游离状态、持有路径和原有策略,调用方可继续使用或重试。 路径与挂载引用在最后一次释放后按现有后端清理规则回收。" +msgstr "After ``vfs_mount_attach()`` succeeds, the mount and its retained paths enter the normal lifecycle of the target namespace. If propagation preparation fails, the detached state, retained paths and existing policy remain intact so that the caller can continue using the mount or retry. After the last path and mount references are released, cleanup follows the existing backend rules." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index bc0282df..8f066f57 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -368,3 +368,27 @@ msgstr "``fsmount`` returns an ``O_PATH`` descriptor for the detached mount root msgid "``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 ``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" msgstr "``move_mount`` attaches the held mount root at a destination and supports the empty-path and symbolic-link flags for both source and destination. Attachment follows the existing propagation rules when the destination mount is shared. ``MOUNT_ATTR_NOSYMFOLLOW`` and ``MOVE_MOUNT_BENEATH`` return ``EINVAL``, allowing callers to use their corresponding compatibility fallbacks." + +msgid "字节范围文件锁" +msgstr "Byte-range File Locks" + +msgid "``fcntl`` 支持 ``F_GETLK``、``F_SETLK``、``F_SETLKW`` 及 ``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW``。POSIX 锁归描述符表 所有,关闭该表中指向同一 inode 的任意描述符会释放其 POSIX 锁。OFD 锁归打开 文件描述所有,dup 和 fork 共享锁,最后一个引用释放时清锁并唤醒等待者。 在途系统调用和传递中的描述符引用也会延长 OFD 锁的生命周期。" +msgstr "``fcntl`` supports ``F_GETLK``, ``F_SETLK``, ``F_SETLKW``, ``F_OFD_GETLK``, ``F_OFD_SETLK`` and ``F_OFD_SETLKW``. POSIX locks belong to the descriptor table. Closing any descriptor for the same inode in that table releases its POSIX locks. OFD locks belong to the open-file description, are shared through dup and fork, and are released with the final reference, waking waiters. In-flight syscalls and descriptors in transit also extend the OFD lock lifetime." + +msgid "两类锁使用同一 inode 和范围冲突规则,包括同一进程持有的不同类型锁。相同 OFD 上的锁可转换、拆分和合并。OFD 请求的 ``l_pid`` 必须为零,否则返回 ``EINVAL``。查询到 OFD 冲突时 ``l_pid`` 为 -1,查询到 POSIX 冲突时为持锁 进程的 PID。``F_OFD_SETLK`` 遇到冲突返回 ``EAGAIN``。" +msgstr "Both lock classes use the same inode and range conflict rules, including different lock classes held by one process. Locks on the same OFD can be converted, split and merged. OFD requests require ``l_pid`` to be zero, otherwise they return ``EINVAL``. A query reports ``l_pid`` as -1 for an OFD conflict and as the owning process PID for a POSIX conflict. ``F_OFD_SETLK`` returns ``EAGAIN`` on conflict." + +msgid "``F_OFD_SETLKW`` 等待锁释放,信号处理沿用现有系统调用中断和重启规则。 OFD 等待不参与 POSIX 锁的死锁检测。六种锁命令均保留实际 OFD,阻塞期间其他 线程关闭并复用数字 FD 后,重试仍使用原打开文件描述。任务退出或调用取消会 移除待处理的锁请求,最终 OFD 引用释放后才能回收其锁。" +msgstr "``F_OFD_SETLKW`` waits for lock release and follows the existing syscall signal interruption and restart rules. OFD waits are excluded from POSIX lock deadlock detection. All six lock commands retain the actual OFD. If another thread closes and reuses the numeric FD while the operation blocks, retries continue using the original open-file description. Task exit or syscall cancellation removes the pending lock request. Held OFD locks survive until the final reference is released." + +msgid "``tools/test_record_locks.py`` 和 ``tools/test_linux_descriptors.py`` 覆盖范围 变更、冲突查询、内存不足回滚、dup/fork、最终引用释放及阻塞期间的 FD 复用。 ``tools/tests/record_locks_runtime_probe.c`` 提供原生用户态运行探针。" +msgstr "``tools/test_record_locks.py`` and ``tools/test_linux_descriptors.py`` cover range changes, conflict queries, allocation-failure rollback, dup/fork, final reference release and FD reuse during blocking. ``tools/tests/record_locks_runtime_probe.c`` provides a native userspace runtime probe." + +msgid "statx 挂载标识和根属性" +msgstr "statx mount ID and root attribute" + +msgid "``statx()`` 成功时在 ``stx_attributes_mask`` 中报告支持 ``STATX_ATTR_MOUNT_ROOT``。只有实际查询到的路径是其所在挂载的根时,才在 ``stx_attributes`` 中设置该位。因此,目录绑定的目标是挂载根,同一 inode 经原挂载查询时不一定是。``AT_EMPTY_PATH`` 使用描述符持有的路径,不重新查找 可见名称;没有路径的匿名描述符不设置该属性。" +msgstr "On success, ``statx()`` reports support for ``STATX_ATTR_MOUNT_ROOT`` in ``stx_attributes_mask``. The bit is set in ``stx_attributes`` only when the actual path being queried is the root of its mount. The target of a directory bind is therefore a mount root, while querying the same inode through the original mount need not report it as one. ``AT_EMPTY_PATH`` uses the path retained by the descriptor rather than looking up a visible name again. Anonymous descriptors without a path do not have this attribute set." + +msgid "实际路径有挂载 ID 时,``statx()`` 在 ``stx_mask`` 中设置 ``STATX_MNT_ID``, 并在 ``stx_mnt_id`` 中返回与 ``/proc/self/mountinfo`` 一致的 ID,即使请求掩码 未指定该位。同一 inode 经不同挂载访问时可得到不同 ID。只有合成元数据、没有 实际挂载路径的对象不报告 ID。不支持 ``STATX_MNT_ID_UNIQUE``,不会将旧式 ID 标记为唯一 ID。输出页争用后重试时沿用同一份已完成的 inode 元数据、ID 和属性。" +msgstr "If the actual path has a mount ID, ``statx()`` sets ``STATX_MNT_ID`` in ``stx_mask`` and returns the ID matching ``/proc/self/mountinfo`` in ``stx_mnt_id``, even if the request mask omits the bit. The same inode can have different IDs when accessed through different mounts. Objects with only synthetic metadata and no actual mount path do not report an ID. ``STATX_MNT_ID_UNIQUE`` is unsupported; legacy IDs are not marked as unique. A retry after output-page contention uses the same completed inode metadata, ID and attributes." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index ee12c4d7..ffecb996 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -383,3 +383,6 @@ msgstr "``recvmsg`` on datagram and sequenced-packet sockets can return a ``SOL_ msgid "时间戳位于 ``SCM_CREDENTIALS`` 和 ``SCM_RIGHTS`` 之前。控制缓冲区不足时 按可用容量返回部分消息并设置 ``MSG_CTRUNC``。交换页等待后的重试保留已接收 数据包及其时间戳选项状态。" msgstr "The timestamp precedes ``SCM_CREDENTIALS`` and ``SCM_RIGHTS``. A short control buffer receives the portion that fits and sets ``MSG_CTRUNC``. Retries after a swapped-page wait retain the accepted packet and timestamp option state." + +msgid "启动时,探测到的 ISO9660 光盘按 ``/media/cdrom0``、``/media/cdrom1`` 等顺序 尝试挂载。若 ``/media`` 不存在,跳过自动挂载,不创建它;仍可用对应的光盘块设备 显式挂载。若父目录存在,只创建缺少的末级目录,不改变已有目录的元数据。其他 查找、创建或挂载错误不会被忽略。启动挂载图发布前失败时会释放图内挂载点引用并 返回原错误;后端若未能完成回收,将保留到重试。正常卸载的忙检查不变。" +msgstr "At startup, detected ISO9660 discs are tried at ``/media/cdrom0``, ``/media/cdrom1`` and so on. If ``/media`` is absent, automount is skipped without creating it; the matching optical block device can still be mounted explicitly. If the parent exists, only missing leaf directories are created, leaving existing directory metadata unchanged. Other lookup, creation or mount failures are not ignored. A failure before the boot mount graph is published drops mountpoint references in that graph and returns the original error. Cleanup that the backend cannot finish is retained for retry. Normal unmount busy checks are unchanged." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index e57daa7c..ac7621eb 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -154,3 +154,12 @@ msgstr "" "``vfs_namespace_retire()`` " "がアンマウントを伝播させずにツリー全体を切り離し、その後グラフ自体を解放します。保持中のパスは有効なままで、既存の遅延処理キューがバックエンドを後処理します。起動時とテスト用のグラフの記憶領域は引き続き呼び出し側が管理します。厳格な" " ``vfs_namespace_destroy()`` はグラフの参照や外部パス参照が残っている間は破棄を拒否します。" + +msgid "游离挂载路径" +msgstr "切り離されたマウントのパス" + +msgid "``vfs_mount_detached_root()`` 显式暴露尚未附着的挂载根并返回持有路径。 该路径及其子项可以进行常规查找、文件操作和根挂载重配置。游离根没有通向 命名空间的父边,描述符链接和不可达的工作目录以该挂载根为基准显示。 未暴露的内部挂载继续限制路径遍历;已经 lazy-unmount 的挂载不能重新发布。" +msgstr "``vfs_mount_detached_root()`` はまだ接続されていないマウントのルートを明示的に公開し、参照を保持したパスを返す。このパスとその子要素では通常の検索、ファイル操作、ルートマウントの再設定が可能である。切り離されたルートには名前空間へ通じる親の辺がなく、ディスクリプターのリンクと到達不能な作業ディレクトリはこのマウントルートを基準に表示される。未公開の内部マウントでは引き続きパスの走査が制限される。遅延アンマウント済みのマウントは再公開できない。" + +msgid "``vfs_mount_attach()`` 成功后,挂载和已持有路径转入目标命名空间的正常生命周期。 传播准备失败时保留游离状态、持有路径和原有策略,调用方可继续使用或重试。 路径与挂载引用在最后一次释放后按现有后端清理规则回收。" +msgstr "``vfs_mount_attach()`` が成功すると、マウントと保持中のパスは対象の名前空間の通常のライフサイクルに入る。伝播の準備に失敗しても、切り離された状態、保持中のパス、既存のポリシーはそのままであり、呼び出し元は利用を継続するか再試行できる。パスとマウントの最後の参照が解放されると、既存のバックエンドの規則に従って回収される。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index a8727f71..d68908c3 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -323,3 +323,27 @@ msgstr "``fsmount`` は未接続マウントのルートを指す ``O_PATH`` デ msgid "``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 ``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" msgstr "``move_mount`` は保持しているマウントルートを宛先に接続し、接続元と宛先の空パスおよびシンボリックリンクのフラグをサポートします。宛先のマウントが共有されている場合、接続には既存の伝播規則が適用されます。``MOUNT_ATTR_NOSYMFOLLOW`` と ``MOVE_MOUNT_BENEATH`` は ``EINVAL`` を返すため、呼び出し元はそれぞれの互換フォールバックを利用できます。" + +msgid "字节范围文件锁" +msgstr "バイト範囲ファイルロック" + +msgid "``fcntl`` 支持 ``F_GETLK``、``F_SETLK``、``F_SETLKW`` 及 ``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW``。POSIX 锁归描述符表 所有,关闭该表中指向同一 inode 的任意描述符会释放其 POSIX 锁。OFD 锁归打开 文件描述所有,dup 和 fork 共享锁,最后一个引用释放时清锁并唤醒等待者。 在途系统调用和传递中的描述符引用也会延长 OFD 锁的生命周期。" +msgstr "``fcntl`` は ``F_GETLK``、``F_SETLK``、``F_SETLKW``、``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW`` をサポートします。POSIX ロックは記述子テーブルに属し、そのテーブル内で同じ inode を指す記述子を閉じると解放されます。OFD ロックはオープンファイル記述に属し、dup と fork で共有され、最後の参照の解放時に解除されて待機者を起こします。実行中のシステムコールと転送中の記述子の参照も OFD ロックの寿命を延長します。" + +msgid "两类锁使用同一 inode 和范围冲突规则,包括同一进程持有的不同类型锁。相同 OFD 上的锁可转换、拆分和合并。OFD 请求的 ``l_pid`` 必须为零,否则返回 ``EINVAL``。查询到 OFD 冲突时 ``l_pid`` 为 -1,查询到 POSIX 冲突时为持锁 进程的 PID。``F_OFD_SETLK`` 遇到冲突返回 ``EAGAIN``。" +msgstr "両種のロックは同じ inode と範囲の競合規則を使用し、同一プロセスが保持する異種ロックも競合します。同じ OFD 上のロックは変換、分割、結合できます。OFD 要求の ``l_pid`` はゼロである必要があり、それ以外は ``EINVAL`` を返します。競合照会の ``l_pid`` は OFD ロックでは -1、POSIX ロックでは所有プロセスの PID です。``F_OFD_SETLK`` は競合時に ``EAGAIN`` を返します。" + +msgid "``F_OFD_SETLKW`` 等待锁释放,信号处理沿用现有系统调用中断和重启规则。 OFD 等待不参与 POSIX 锁的死锁检测。六种锁命令均保留实际 OFD,阻塞期间其他 线程关闭并复用数字 FD 后,重试仍使用原打开文件描述。任务退出或调用取消会 移除待处理的锁请求,最终 OFD 引用释放后才能回收其锁。" +msgstr "``F_OFD_SETLKW`` はロック解放を待ち、既存のシステムコールのシグナル中断と再開規則に従います。OFD の待機は POSIX ロックのデッドロック検出対象外です。6 種のロック命令は実際の OFD を保持します。待機中に別スレッドが数値 FD を閉じて再利用しても、再試行は元のオープンファイル記述を使用します。タスク終了または呼び出しのキャンセルで保留中の要求を削除し、保持済み OFD ロックは最後の参照の解放まで存続します。" + +msgid "``tools/test_record_locks.py`` 和 ``tools/test_linux_descriptors.py`` 覆盖范围 变更、冲突查询、内存不足回滚、dup/fork、最终引用释放及阻塞期间的 FD 复用。 ``tools/tests/record_locks_runtime_probe.c`` 提供原生用户态运行探针。" +msgstr "``tools/test_record_locks.py`` と ``tools/test_linux_descriptors.py`` は範囲変更、競合照会、メモリ不足時のロールバック、dup/fork、最終参照の解放、待機中の FD 再利用を検証します。``tools/tests/record_locks_runtime_probe.c`` はネイティブユーザー空間の実行プローブです。" + +msgid "statx 挂载标识和根属性" +msgstr "statx のマウント ID とルート属性" + +msgid "``statx()`` 成功时在 ``stx_attributes_mask`` 中报告支持 ``STATX_ATTR_MOUNT_ROOT``。只有实际查询到的路径是其所在挂载的根时,才在 ``stx_attributes`` 中设置该位。因此,目录绑定的目标是挂载根,同一 inode 经原挂载查询时不一定是。``AT_EMPTY_PATH`` 使用描述符持有的路径,不重新查找 可见名称;没有路径的匿名描述符不设置该属性。" +msgstr "``statx()`` は成功時に ``stx_attributes_mask`` で ``STATX_ATTR_MOUNT_ROOT`` のサポートを報告する。実際に照会したパスが所属するマウントのルートである場合に限り、``stx_attributes`` にそのビットを設定する。したがってディレクトリのバインド先はマウントルートだが、同じ inode を元のマウントから照会してもルートとは限らない。``AT_EMPTY_PATH`` は可視の名前を再検索せず、ディスクリプターが保持するパスを使う。パスのない匿名ディスクリプターではこの属性を設定しない。" + +msgid "实际路径有挂载 ID 时,``statx()`` 在 ``stx_mask`` 中设置 ``STATX_MNT_ID``, 并在 ``stx_mnt_id`` 中返回与 ``/proc/self/mountinfo`` 一致的 ID,即使请求掩码 未指定该位。同一 inode 经不同挂载访问时可得到不同 ID。只有合成元数据、没有 实际挂载路径的对象不报告 ID。不支持 ``STATX_MNT_ID_UNIQUE``,不会将旧式 ID 标记为唯一 ID。输出页争用后重试时沿用同一份已完成的 inode 元数据、ID 和属性。" +msgstr "実際のパスにマウント ID がある場合、``statx()`` は要求マスクに該当ビットがなくても ``stx_mask`` に ``STATX_MNT_ID`` を設定し、``stx_mnt_id`` に ``/proc/self/mountinfo`` と一致する ID を返す。同じ inode でも異なるマウント経由では別の ID が返り得る。合成メタデータしかなく実際のマウントパスを持たないオブジェクトは ID を報告しない。``STATX_MNT_ID_UNIQUE`` は未対応であり、従来の ID を一意とはみなさない。出力ページの競合による再試行では、取得済みの inode メタデータ、ID、属性をそのまま使う。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index 57bab4fc..6c4e8098 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -329,3 +329,6 @@ msgstr "データグラムとシーケンスパケットの ``recvmsg`` は、 msgid "时间戳位于 ``SCM_CREDENTIALS`` 和 ``SCM_RIGHTS`` 之前。控制缓冲区不足时 按可用容量返回部分消息并设置 ``MSG_CTRUNC``。交换页等待后的重试保留已接收 数据包及其时间戳选项状态。" msgstr "タイムスタンプは ``SCM_CREDENTIALS`` と ``SCM_RIGHTS`` より前に置かれます。制御バッファーが不足すると収まる部分を返し、``MSG_CTRUNC`` を設定します。スワップページ待機後の再試行では受信済みパケットとタイムスタンプオプションの状態を保持します。" + +msgid "启动时,探测到的 ISO9660 光盘按 ``/media/cdrom0``、``/media/cdrom1`` 等顺序 尝试挂载。若 ``/media`` 不存在,跳过自动挂载,不创建它;仍可用对应的光盘块设备 显式挂载。若父目录存在,只创建缺少的末级目录,不改变已有目录的元数据。其他 查找、创建或挂载错误不会被忽略。启动挂载图发布前失败时会释放图内挂载点引用并 返回原错误;后端若未能完成回收,将保留到重试。正常卸载的忙检查不变。" +msgstr "起動時、検出された ISO9660 ディスクのマウントを ``/media/cdrom0``、``/media/cdrom1`` などの順に試みる。``/media`` がなければ作成せずに自動マウントを省略するが、対応する光学ブロックデバイスは明示的にマウントできる。親ディレクトリがあれば不足している末端ディレクトリだけを作成し、既存のメタデータは変更しない。他の検索、作成、マウントのエラーは無視しない。起動時のマウントグラフの公開前に失敗すると、そのグラフ内のマウントポイントへの参照を解放して元のエラーを返す。バックエンドが回収を完了できなければ再試行のために保持する。通常のアンマウントでの使用中チェックは変わらない。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 54c8db4c..387ad5b8 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -196,6 +196,29 @@ bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员 连接到任务根时,原始 ``getcwd`` 返回以 ``(unreachable)`` 开头的路径。 最后的引用释放后由 VFS 工作队列完成文件系统清理。 +字节范围文件锁 +============== + +``fcntl`` 支持 ``F_GETLK``、``F_SETLK``、``F_SETLKW`` 及 +``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW``。POSIX 锁归描述符表 +所有,关闭该表中指向同一 inode 的任意描述符会释放其 POSIX 锁。OFD 锁归打开 +文件描述所有,dup 和 fork 共享锁,最后一个引用释放时清锁并唤醒等待者。 +在途系统调用和传递中的描述符引用也会延长 OFD 锁的生命周期。 + +两类锁使用同一 inode 和范围冲突规则,包括同一进程持有的不同类型锁。相同 OFD +上的锁可转换、拆分和合并。OFD 请求的 ``l_pid`` 必须为零,否则返回 +``EINVAL``。查询到 OFD 冲突时 ``l_pid`` 为 -1,查询到 POSIX 冲突时为持锁 +进程的 PID。``F_OFD_SETLK`` 遇到冲突返回 ``EAGAIN``。 + +``F_OFD_SETLKW`` 等待锁释放,信号处理沿用现有系统调用中断和重启规则。 +OFD 等待不参与 POSIX 锁的死锁检测。六种锁命令均保留实际 OFD,阻塞期间其他 +线程关闭并复用数字 FD 后,重试仍使用原打开文件描述。任务退出或调用取消会 +移除待处理的锁请求,最终 OFD 引用释放后才能回收其锁。 + +``tools/test_record_locks.py`` 和 ``tools/test_linux_descriptors.py`` 覆盖范围 +变更、冲突查询、内存不足回滚、dup/fork、最终引用释放及阻塞期间的 FD 复用。 +``tools/tests/record_locks_runtime_probe.c`` 提供原生用户态运行探针。 + glibc 线程与 CPU 状态兼容 ========================= diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index a3bb423c..3faeb203 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -770,8 +770,20 @@ void task_pty_release_entry(struct task_pty_fd *entry); int task_pty_export_fd(struct task *task, int fd, struct task_pty_fd *out); int task_pty_import_fd(struct task *task, const struct task_pty_fd *source, uint32_t flags); void clear_task_file(struct task_file *file); +/** @brief Query/update POSIX or OFD byte-range locks using the syscall OFD pin. + * @param fd Signed descriptor number. @param command F_*LK or F_OFD_*LK command. + * @param pointer User native flock input/output, with l_pid=0 for OFD requests. + * @return Zero, blocking retry token or negative errno, under execution ownership. */ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer); +/** @brief Release a descriptor table's POSIX locks for the closing inode. + * @param task Execution-owned table owner, nullable. + * @param descriptor Borrowed closing descriptor/OFD, nullable. Wakes waiters. */ void syscall_record_locks_close(struct task *task, struct task_file *descriptor); +/** @brief Release OFD locks at final description close and wake waiters. + * @param file Retiring canonical OFD, nullable, under execution ownership. */ +void syscall_record_locks_release(struct task_file *file); +/** @brief Cancel a task's pending byte-range lock request. + * @param task Execution-owned task, nullable. Does not release held locks. */ void syscall_record_lock_cancel(struct task *task); /** @brief Execute a native realtime clock discipline request. */ diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index b7f2f6a1..5abd355b 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -122,6 +122,7 @@ struct task_file { uint32_t flags; uint32_t fd_flags; uint32_t flock_type; + uint64_t record_lock_owner; /* Stable OFD lock serial, preserved on promotion. */ uint32_t kind; uint32_t io_owner; /* Epoll watches borrow this stable OFD identity and detach before final free. */ diff --git a/include/uapi/linux/fcntl.h b/include/uapi/linux/fcntl.h index 3b1bf850..36a53641 100644 --- a/include/uapi/linux/fcntl.h +++ b/include/uapi/linux/fcntl.h @@ -34,6 +34,9 @@ #define LINUX_F_SETLKW 7 #define LINUX_F_SETOWN 8 #define LINUX_F_GETOWN 9 +#define LINUX_F_OFD_GETLK 36 +#define LINUX_F_OFD_SETLK 37 +#define LINUX_F_OFD_SETLKW 38 #define LINUX_F_DUPFD_CLOEXEC 1030 #define LINUX_F_SETPIPE_SZ 1031 #define LINUX_F_GETPIPE_SZ 1032 diff --git a/kernel/syscall/entry.c b/kernel/syscall/entry.c index 4d83531b..a1f17593 100644 --- a/kernel/syscall/entry.c +++ b/kernel/syscall/entry.c @@ -30,7 +30,8 @@ static bool syscall_trace_task(const struct task *task); * @param number Linux syscall number. * @param fd Descriptor argument as signed low-32 bits; mmap uses argument five. * @param arg2 Third syscall argument for finit_module flag preflight, or mmap - * fourth-argument flags so anonymous mappings ignore their numeric descriptor. + * fourth-argument flags so anonymous mappings ignore their numeric descriptor; + * fcntl uses its unsigned command to admit only byte-range lock operations. * @return Zero or negative authorization/validation/allocation errno. A matching * retry keeps the same object even if another thread closes/reuses fd; task_release_syscall_file ends ownership. */ @@ -148,14 +149,19 @@ static bool syscall_trace_task(const struct task *task) * @param number Linux syscall number. * @param fd Descriptor argument as signed low-32 bits; mmap uses argument five. * @param arg2 Third syscall argument for finit_module flag preflight, or mmap - * fourth-argument flags so anonymous mappings ignore their numeric descriptor. + * fourth-argument flags so anonymous mappings ignore their numeric descriptor; + * fcntl uses its unsigned command to admit only byte-range lock operations. * @return Zero or negative authorization/validation/allocation errno. A matching * retry keeps the same object even if another thread closes/reuses fd; task_release_syscall_file ends ownership. */ static int task_begin_syscall_io(struct task *task, uint64_t number, int32_t fd, uint64_t arg2) { + uint32_t command = (uint32_t)arg2; bool file_io = (number==LINUX_SYS_MMAP && !((uint32_t)arg2&LINUX_MAP_ANONYMOUS)) || + (number == LINUX_SYS_FCNTL && + ((command >= LINUX_F_GETLK && command <= LINUX_F_SETLKW) || + (command >= LINUX_F_OFD_GETLK && command <= LINUX_F_OFD_SETLKW))) || number == __NR_fsconfig || number == __NR_fsmount || number == __NR_move_mount || number == __NR_pidfd_send_signal || number == LINUX_SYS_WAITID || number == LINUX_SYS_READ || number == LINUX_SYS_WRITE || @@ -326,7 +332,8 @@ static bool syscall_execute_locked(struct task *calling_task, struct trap_frame int pin_error=task_begin_syscall_io(calling_task,number, (int32_t)(number==LINUX_SYS_MMAP ? frame->r8 : wait_pidfd ? frame->rsi : number==LINUX_SYS_WAITID ? (uint64_t)-1 : frame->rdi), - number==LINUX_SYS_MMAP ? frame->r10 : frame->rdx); + number==LINUX_SYS_MMAP ? frame->r10 : + number==LINUX_SYS_FCNTL ? frame->rsi : frame->rdx); task_lookup_scope_begin(calling_task,frame); uint64_t storage_generation=storage_wait_begin(); storage_set_io_async_context(true); @@ -434,7 +441,9 @@ static bool syscall_execute_locked(struct task *calling_task, struct trap_frame if ((number == LINUX_SYS_EXECVE || number == LINUX_SYS_EXECVEAT) && result == -RELIEFOS_EAGAIN && calling_task && calling_task->nproc_exceeded) eagain_from_nonblocking = 1; - if (number == LINUX_SYS_FCNTL && (uint32_t)frame->rsi == LINUX_F_SETLK && result == -RELIEFOS_EAGAIN) + if (number == LINUX_SYS_FCNTL && + ((uint32_t)frame->rsi == LINUX_F_SETLK || (uint32_t)frame->rsi == LINUX_F_OFD_SETLK) && + result == -RELIEFOS_EAGAIN) eagain_from_nonblocking = 1; /* Inactive VT presentation must return to the compositor, allowing its * loop to observe the switch and request a complete repaint on return. */ diff --git a/kernel/syscall/fd/descriptor.c b/kernel/syscall/fd/descriptor.c index 41749ea8..67647a79 100644 --- a/kernel/syscall/fd/descriptor.c +++ b/kernel/syscall/fd/descriptor.c @@ -49,7 +49,8 @@ static void clear_task_files(struct task *task); * @param file Descriptor slot or stable OFD to clear; null and unused entries are ignored. * @return Backing inode release result, or zero when no inode release is needed. * @note A final canonical release detaches weak epoll watches before releasing - * OFD-owned resources. SCM queue and in-flight I/O references use this same path. + * OFD-owned resources, including byte-range locks. SCM queue and in-flight I/O + * references use this same path, keeping locks until the last reference ends. * Captured provider state closes before its inode/path/code can retire. Caller * holds execution ownership without graph/scheduler/module locks across cleanup; * the attachment writer charge ends before its OFD-owned path is released. @@ -77,6 +78,7 @@ int clear_task_file_result(struct task_file *file) } if (file->references == 0) task_epoll_remove_file_description(file); syscall_flock_release_owner(file); + syscall_record_locks_release(file); if (file->notify_open && file->path_ref.mount && vfs_notify_event) { vfs_notify_event(&file->path_ref, file_can_write(file) ? IN_CLOSE_WRITE : IN_CLOSE_NOWRITE); file->notify_open = false; @@ -517,7 +519,7 @@ void task_fifo_cancel(struct task *task) * any provider reference can retire. Retires imported vectors after draining. * Drains/retires a two-OFD transfer and its staging bytes before copied * lookup text and root/dirfd references, then cancels module - * read denial before releasing the OFD/inode; final resource + * read denial and pending record-lock waits before releasing the OFD/inode; final resource * callbacks may perform I/O. Signals, call replacement and exit share this path. */ void task_release_syscall_file(struct task *task) @@ -540,6 +542,7 @@ void task_release_syscall_file(struct task *task) task_transfer_cancel(task); task_lookup_scope_cancel(task); module_file_cancel(task); + syscall_record_lock_cancel(task); task_sysv_msg_cancel(task); task_sysv_sem_cancel(task); task_fifo_cancel(task); diff --git a/kernel/syscall/fd/legacy_descriptors.c b/kernel/syscall/fd/legacy_descriptors.c index 03162cc5..0e0df577 100644 --- a/kernel/syscall/fd/legacy_descriptors.c +++ b/kernel/syscall/fd/legacy_descriptors.c @@ -92,7 +92,9 @@ int64_t syscall_legacy_descriptors(uint64_t number, uint64_t a0, uint64_t a1, ui struct task *task = sched_current_task(); /* fcntl's command is unsigned int; its argument remains unsigned long. */ if (number == LINUX_SYS_FCNTL) a1 = (uint32_t)a1; - if (number == LINUX_SYS_FCNTL && (a1 == LINUX_F_GETLK || a1 == LINUX_F_SETLK || a1 == LINUX_F_SETLKW)) + if (number == LINUX_SYS_FCNTL && + ((a1 >= LINUX_F_GETLK && a1 <= LINUX_F_SETLKW) || + (a1 >= LINUX_F_OFD_GETLK && a1 <= LINUX_F_OFD_SETLKW))) return syscall_record_lock((int32_t)a0, (uint32_t)a1, a2); if (number == LINUX_SYS_DUP) { struct task_file *source = task_file_for_fd(task, (int)a0); diff --git a/kernel/syscall/fs/locks.c b/kernel/syscall/fs/locks.c index f68e2daf..4e02d0bf 100644 --- a/kernel/syscall/fs/locks.c +++ b/kernel/syscall/fs/locks.c @@ -1,4 +1,4 @@ -/* Linux v6.12 fs/locks.c: POSIX byte-range locks owned by files_struct. */ +/* Linux byte-range locking ABI with descriptor-table and OFD ownership. */ #include #include #include @@ -13,7 +13,7 @@ #define LOCK_END 0x7fffffffffffffffLL struct record_lock { uint64_t owner; - uint32_t pid; + int32_t pid; /* -1 identifies an open-file-description lock. */ struct storage_node node; int64_t start, end; int16_t type; @@ -34,18 +34,28 @@ static struct record_lock_waiter { static uint32_t pending_count; static uint32_t pending_capacity; +/** @brief Compare stable filesystem inode identities. + * @param a First borrowed inode snapshot. @param b Second borrowed snapshot. + * @return True for the same volume, inode number and inode type. */ static bool same_inode(const struct storage_node *a, const struct storage_node *b) { return a->volume_id == b->volume_id && a->first_cluster == b->first_cluster && a->type == b->type; } -uint64_t syscall_record_lock_owner(struct task *task) +/** @brief Allocate a serial shared by tasks using one descriptor table. + * @param task Current execution-owned task with a live descriptor table. + * @return Nonzero lock owner unique among descriptor tables and OFDs. */ +static uint64_t syscall_record_lock_owner(struct task *task) { struct task_fd_table_state *table = sched_task_fds(task); if (!table->lock_owner) table->lock_owner = __atomic_add_fetch(&next_lock_owner, 1, __ATOMIC_RELAXED); return table->lock_owner; } +/** @brief Release this descriptor table's POSIX locks on a closing inode. + * @param task Execution-owned table owner, nullable. + * @param descriptor Borrowed closing descriptor or OFD, nullable. + * OFD locks survive this operation. Wakes waiters after dropping POSIX locks. */ void syscall_record_locks_close(struct task *task, struct task_file *descriptor) { struct task_file *file = task_file_description(descriptor); @@ -56,11 +66,30 @@ void syscall_record_locks_close(struct task *task, struct task_file *descriptor) kernel_wait_queue_wake_all(&record_waiters); } +/** @brief Release byte-range locks on the final close of an OFD. + * @param file Canonical OFD being retired under execution ownership, nullable. + * Clears its serial before storage reuse and wakes blocked lock requests. + * This does not allocate or dereference userspace. */ +void syscall_record_locks_release(struct task_file *file) +{ + if (!file || !file->record_lock_owner) return; + for (unsigned i = 0; i < RECORD_LOCK_MAX; ++i) + if (records[i].owner == file->record_lock_owner) records[i].owner = 0; + file->record_lock_owner = 0; + kernel_wait_queue_wake_all(&record_waiters); +} + +/** @brief Test inclusive byte-range intersection. + * @param a First borrowed normalized range. @param b Second borrowed range. + * @return True when at least one byte is shared. */ static bool overlap(const struct record_lock *a, const struct record_lock *b) { return a->start <= b->end && b->start <= a->end; } +/** @brief Check conflicting POSIX or OFD locks from distinct owners. + * @param a First borrowed record. @param b Second borrowed record. + * @return True for overlapping locks on one inode with at least one writer. */ static bool conflicts(const struct record_lock *a, const struct record_lock *b) { return a->owner && b->owner && a->owner != b->owner && same_inode(&a->node, &b->node) && @@ -118,7 +147,7 @@ static int pending_reserve_one(void) /* Linux bounds its POSIX lock deadlock walk to ten owners. */ /** - * @brief Search pending lock waits for a deadlock path to a target owner. + * @brief Search POSIX lock waits for a deadlock path, excluding OFD waits. * @param owner Owner whose pending requests are inspected. * @param target Owner sought by the wait-for walk. * @param depth Remaining owner edges allowed in this bounded search. @@ -129,13 +158,18 @@ static bool waits_for(uint64_t owner, uint64_t target, unsigned depth) if (owner == target) return true; if (!depth) return false; for (uint32_t i = 0; i < pending_count; ++i) { - if (!pending[i].task || pending[i].request.owner != owner) continue; + if (!pending[i].task || pending[i].request.pid == -1 || + pending[i].request.owner != owner) continue; for (unsigned j = 0; j < RECORD_LOCK_MAX; ++j) if (conflicts(&records[j], &pending[i].request) && waits_for(records[j].owner, target, depth - 1)) return true; } return false; } +/** @brief Append one lock to an unpublished replacement table. + * @param destination Writable RECORD_LOCK_MAX-entry table. + * @param count In/out occupied entry count. @param record Borrowed lock to copy. + * @return Zero or -ENOLCK without changing a full table. */ static int insert(struct record_lock *destination, unsigned *count, const struct record_lock *record) { if (*count == RECORD_LOCK_MAX) return -LINUX_ENOLCK; @@ -143,6 +177,10 @@ static int insert(struct record_lock *destination, unsigned *count, const struct return 0; } +/** @brief Atomically replace an owner's range, splitting and merging its locks. + * @param request Borrowed normalized POSIX or OFD lock/unlock request. + * @return Zero after publication and wakeup, or -ENOLCK preserving prior locks. + * Caller holds execution ownership; temporary storage can allocate. */ static int replace_range(const struct record_lock *request) { struct record_lock *next = kernel_malloc(sizeof(records)); @@ -191,24 +229,30 @@ static int replace_range(const struct record_lock *request) } /** - * @brief Query or update a POSIX byte-range lock for the current task. + * @brief Query or update POSIX or OFD byte-range locks for the current task. * @param fd Descriptor naming the regular file. - * @param command F_GETLK, F_SETLK, or F_SETLKW operation. + * @param command F_GETLK/F_SETLK/F_SETLKW or their F_OFD counterparts. * @param pointer User pointer to a native flock request/result. * @return Zero, a blocking retry token, or a negative Linux errno. + * Uses the syscall's retained OFD across descriptor close/reuse. Caller holds + * execution ownership. OFD requests require l_pid=0 and report conflicts owned + * by an OFD with l_pid=-1; only POSIX requests participate in deadlock detection. */ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer) { struct task *task = sched_current_task(); syscall_record_lock_cancel(task); if (task && task->waiting_queue == &record_waiters) kernel_wait_queue_remove(&record_waiters, task); - struct task_file *file = task_file_for_fd(task, fd); + struct task_file *file = task_file_for_io(task, fd); if (!file || (file->flags & TASK_FILE_FLAG_PATH)) return -LINUX_EBADF; if (!user_range_ok(pointer, sizeof(struct native_flock))) return -LINUX_EFAULT; struct native_flock user; __builtin_memcpy(&user, (const void *)(uintptr_t)pointer, sizeof(user)); + bool ofd = command == LINUX_F_OFD_GETLK || command == LINUX_F_OFD_SETLK || + command == LINUX_F_OFD_SETLKW; + bool query = command == LINUX_F_GETLK || command == LINUX_F_OFD_GETLK; if (user.type < LINUX_F_RDLCK || user.type > LINUX_F_UNLCK || - (command == LINUX_F_GETLK && user.type == LINUX_F_UNLCK)) return -LINUX_EINVAL; + (query && user.type == LINUX_F_UNLCK) || (ofd && user.pid)) return -LINUX_EINVAL; int64_t start; if (user.whence == 0) start = 0; else if (user.whence == 1) start = file->offset; @@ -227,14 +271,18 @@ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer) if (__builtin_add_overflow(start, user.length, &start) || start < 0) return -LINUX_EINVAL; } if (file->node.type != RELIEFOS_FS_TYPE_FILE) return -LINUX_EBADF; - if (command != LINUX_F_GETLK && ((user.type == LINUX_F_RDLCK && !file_can_read(file)) || + if (!query && ((user.type == LINUX_F_RDLCK && !file_can_read(file)) || (user.type == LINUX_F_WRLCK && !file_can_write(file)))) return -LINUX_EBADF; - struct record_lock request = {.owner = syscall_record_lock_owner(task), .pid = sched_task_tgid(task), + if (ofd && !file->record_lock_owner) + file->record_lock_owner = __atomic_add_fetch(&next_lock_owner, 1, __ATOMIC_RELAXED); + struct record_lock request = { + .owner = ofd ? file->record_lock_owner : syscall_record_lock_owner(task), + .pid = ofd ? -1 : (int32_t)sched_task_tgid(task), .node = file->node, .type = user.type, .start = start, .end = end}; for (unsigned i = 0; i < RECORD_LOCK_MAX && user.type != LINUX_F_UNLCK; ++i) { const struct record_lock *held = &records[i]; if (!conflicts(held, &request)) continue; - if (command == LINUX_F_GETLK) { + if (query) { user.type = held->type; user.whence = 0; user.start = held->start; @@ -242,8 +290,8 @@ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer) user.pid = held->pid; goto copy_result; } - if (command == LINUX_F_SETLK) return -LINUX_EAGAIN; - if (waits_for(held->owner, request.owner, 10)) return -LINUX_EDEADLK; + if (command == LINUX_F_SETLK || command == LINUX_F_OFD_SETLK) return -LINUX_EAGAIN; + if (!ofd && waits_for(held->owner, request.owner, 10)) return -LINUX_EDEADLK; int reserve = pending_reserve_one(); if (reserve < 0) return reserve; pending[pending_count++] = (struct record_lock_waiter){ @@ -253,7 +301,7 @@ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer) kernel_wait_queue_block_current(&record_waiters); return KERNEL_SYSCALL_BLOCKED; } - if (command != LINUX_F_GETLK) return replace_range(&request); + if (!query) return replace_range(&request); user.type = LINUX_F_UNLCK; copy_result: if (!user_range_writable(pointer, sizeof(user))) return -LINUX_EFAULT; diff --git a/tools/test_linux_descriptors.py b/tools/test_linux_descriptors.py index 72eaa441..2a66afac 100644 --- a/tools/test_linux_descriptors.py +++ b/tools/test_linux_descriptors.py @@ -13,7 +13,8 @@ "clang", "-std=c11", "-g", "-O1", "-ffunction-sections", "-fdata-sections", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", "-Wl,--gc-sections", - "tools/tests/descriptor_table_test.c", "tools/tests/task8_host_stubs/writable_alias_model.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", *kernel_sources("scheduler"), + "tools/tests/descriptor_table_test.c", "tools/tests/task8_host_stubs/writable_alias_model.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", + "tools/tests/task8_host_stubs/descriptor_unreached.c", *kernel_sources("scheduler"), "kernel/sync/wait.c", "kernel/syscall/ipc/sysv_msg.c", "kernel/syscall/ipc/sysv_sem.c", "kernel/syscall/fs/locks.c", "sound/core/core.c", *kernel_sources("pcm"), @@ -23,7 +24,8 @@ "sound/core/timer.c", "sound/core/mapping.c", "sound/core/services.c", "sound/core/work.c", "sound/core/storage_audio.c", "kernel/device/service.c", "kernel/device/graphics_service.c", "kernel/device/sound_service.c", "kernel/device/driver_manager_phase.c", "fs/devfs/identity.c", - "fs/vfs/object.c", "fs/vfs/write_access.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/attributes.c", "fs/vfs/initial.c", "fs/security/access.c", "kernel/syscall/ipc/unix_name.c", + "fs/vfs/object.c", "fs/vfs/write_access.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", + "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/attributes.c", "fs/vfs/initial.c", "fs/security/access.c", "kernel/syscall/ipc/unix_name.c", "-o", binary, ], cwd=ROOT, check=True) subprocess.run([binary], cwd=ROOT, check=True, timeout=20) diff --git a/tools/tests/descriptor_table_test.c b/tools/tests/descriptor_table_test.c index 08c68328..b3d62a1b 100644 --- a/tools/tests/descriptor_table_test.c +++ b/tools/tests/descriptor_table_test.c @@ -71,6 +71,7 @@ static int64_t descriptor_dispatch_vfork(const struct trap_frame *frame); #define sched_fork_current descriptor_dispatch_fork #define sched_vfork_current descriptor_dispatch_vfork #define RELIEFOS_SYSCALL_FRAME_DISPATCH descriptor_dispatch_regs +#include "../../block/core/storage_wait.c" #include "modules/syscall_dispatch.h" #undef RELIEFOS_SYSCALL_FRAME_DISPATCH #undef sched_vfork_current @@ -85,6 +86,10 @@ static int64_t descriptor_dispatch_vfork(const struct trap_frame *frame); void drm_file_close(struct task_file *file) { if (file) file->drm_file = NULL; } void drm_prime_file_close(struct task_file *file) { (void)file; } +/** @brief Require the descriptor fixture to close only card/PRIME files. + * @param file Borrowed closing description, with no modeled sync fences. */ +void drm_sync_close(struct task_file *file) +{ assert(file->kind != TASK_FILE_KIND_DRM_SYNC); } /* This fixture models only file operations, not device discovery/publication. * Real service admission/DRM publication is linked by drm_core_test and covered * by the native DRM coordinator; no broker implementation is stubbed here. */ @@ -181,6 +186,8 @@ static int64_t descriptor_dispatch_regs(struct task *task, uint64_t number, } if (number == LINUX_SYS_INIT_MODULE || number == LINUX_SYS_FINIT_MODULE) return -RELIEFOS_EAGAIN; /* The initializer's final Linux errno. */ + if (number == LINUX_SYS_FCNTL) + return syscall_legacy_descriptors(number, a0, a1, a2, a3, a4, a5); assert((number == LINUX_SYS_READ || number == LINUX_SYS_READV) && task == descriptor_dispatch_task); struct task_file *file = task_file_for_io(task, (int)a0); @@ -520,6 +527,9 @@ uint32_t pty_vt_id(uint32_t number) { return number >= 1 && number <= 6 ? number int pty_is_active(uint32_t id) { return id == 7 || id == 65536u || id == 0x7fffffffu; } int pty_slave_open_allowed(uint32_t id) { return id == 7; } +/** @brief Identify the fixture's legacy PTY endpoints. + * @param id Unused endpoint ID. @return Zero for the modeled legacy endpoints. */ +int pty_is_devpts(uint32_t id) { (void)id; return 0; } int pty_transfer_get(uint32_t id, uint32_t endpoint) { assert(endpoint == TASK_PTY_ENDPOINT_SLAVE); @@ -595,12 +605,16 @@ static int descriptor_control_write(void *opaque, uint32_t control, return 0; } +/** @brief Allocate a fixture task with descriptor capacity and unlimited file size. + * @param pid Fixture task identifier. + * @return Owned zero-initialized task with the modeled resource limits set. */ static struct task *descriptor_audio_task(uint32_t pid) { struct task *task = calloc(1, sizeof(*task)); assert(task); task->pid = pid; task->limits.nofile.rlim_cur = 64; + task->limits.fsize.rlim_cur = LINUX_RLIM_INFINITY; return task; } @@ -1220,10 +1234,10 @@ static void test_materialized_console_permissions(void) assert(!console_references && !task_console_materialize_stdio(task)); struct task_file *file=task_file_for_fd(task,0);assert(file && !file->path_ref.mount); struct linux_stat_abi original,changed; - assert(!metadata_fd_stat(task,0,&original)); + assert(!linux_stat_from_fd(task,0,false,&original)); assert(!syscall_permissions(NULL,task,LINUX_SYS_FCHMOD,0,0600,0,0,0)); assert(!syscall_permissions(NULL,task,LINUX_SYS_FCHOWN,0,123,456,0,0)); - assert(!metadata_fd_stat(task,0,&changed) && (changed.st_mode&07777)==0600 && + assert(!linux_stat_from_fd(task,0,false,&changed) && (changed.st_mode&07777)==0600 && changed.st_uid==123 && changed.st_gid==456); task->cap_effective=0;task->fsuid=789; assert(syscall_permissions(NULL,task,LINUX_SYS_FCHMOD,0,0666,0,0,0)==-RELIEFOS_EPERM); @@ -1233,7 +1247,7 @@ static void test_materialized_console_permissions(void) file->flags&=~TASK_FILE_FLAG_PATH; assert(!syscall_permissions(NULL,task,LINUX_SYS_FCHOWN,0,original.st_uid,original.st_gid,0,0)); assert(!syscall_permissions(NULL,task,LINUX_SYS_FCHMOD,0,original.st_mode&07777,0,0,0)); - assert(!metadata_fd_stat(task,0,&changed) && changed.st_mode==original.st_mode && + assert(!linux_stat_from_fd(task,0,false,&changed) && changed.st_mode==original.st_mode && changed.st_uid==original.st_uid && changed.st_gid==original.st_gid); for(int fd=0;fd<3;++fd)task_discard_file_fd(task,fd); assert(!console_references);free(task); @@ -1593,6 +1607,143 @@ static void test_flock_promotion(void) puts("PASS flock owner promotion: exclusive/shared, ENOMEM rollback and final close"); } +struct descriptor_record_lock { + int16_t type, whence; + int32_t padding; + int64_t start, length; + int32_t pid, trailing_padding; +}; + +/** @brief Exercise OFD locks through actual fcntl, dup/fork and final cleanup. */ +static void test_ofd_record_lock_lifetime(void) +{ + extern struct task *current_task[]; + struct task *parent = calloc(1, sizeof(*parent)), *child = calloc(1, sizeof(*child)); + assert(parent && child); + parent->pid = parent->tgid = 1388; + child->pid = child->tgid = 1389; + parent->limits.nofile.rlim_cur = child->limits.nofile.rlim_cur = 32; + descriptor_dispatch_task = parent; + current_task[0] = parent; + struct task_file *source, *observer; + int fd = task_allocate_fd(parent, 3, &source); + int other = task_allocate_fd(parent, 3, &observer); + assert(fd == 3 && other == 4); + source->flags = observer->flags = RELIEFOS_O_RDWR; + source->node = observer->node = (struct storage_node){ + .type = RELIEFOS_FS_TYPE_FILE, .volume_id = 1, .first_cluster = 8801}; + struct descriptor_record_lock lock = {.type = LINUX_F_WRLCK, .start = 10, .length = 20}; + assert(!syscall_legacy_descriptors(LINUX_SYS_FCNTL, fd, LINUX_F_OFD_SETLK, + (uintptr_t)&lock, 0, 0, 0)); + fail_allocation = 1; + assert(task_duplicate_file_fd(parent, fd, 5, 0) == -RELIEFOS_ENOMEM); + fail_allocation = 0; + assert(!source->description && source->record_lock_owner); + int alias = task_duplicate_file_fd(parent, fd, 5, 0); + assert(alias == 5 && source->description); + struct task_file *held = task_file_get(source); + assert(held && held->record_lock_owner); + child->fd_table = parent->fd_table; + assert(!syscall_clone_task_files(parent, child)); + assert(!syscall_legacy_descriptors(LINUX_SYS_CLOSE, fd, 0, 0, 0, 0, 0)); + assert(task_allocate_fd(parent, 3, &source) == fd); + source->flags = RELIEFOS_O_RDWR; + source->node = observer->node; + ++source->node.first_cluster; + assert(!syscall_legacy_descriptors(LINUX_SYS_CLOSE, fd, 0, 0, 0, 0, 0)); + assert(!syscall_legacy_descriptors(LINUX_SYS_FCNTL, alias, LINUX_F_OFD_SETLK, + (uintptr_t)&lock, 0, 0, 0)); + + descriptor_dispatch_sleep_count = 0; + struct trap_frame frame = {.rax = LINUX_SYS_FCNTL, .rdi = other, + .rsi = (1ULL << 32) | LINUX_F_OFD_SETLK, .rdx = (uintptr_t)&lock, + .rip = 0x7002, .rsp = 0x8000}; + syscall_dispatch_frame(&frame); + assert((int64_t)frame.rax == -RELIEFOS_EAGAIN && frame.rip == 0x7002); + assert(!parent->syscall_file && !parent->restart_syscall && !descriptor_dispatch_sleep_count); + assert(!syscall_legacy_descriptors(LINUX_SYS_CLOSE, alias, 0, 0, 0, 0, 0)); + clear_task_files(child); + assert(!syscall_legacy_descriptors(LINUX_SYS_FCNTL, other, LINUX_F_OFD_GETLK, + (uintptr_t)&lock, 0, 0, 0)); + assert(lock.type == LINUX_F_WRLCK && lock.pid == -1); + task_file_put(held); + lock.pid = 0; + assert(!syscall_legacy_descriptors(LINUX_SYS_FCNTL, other, LINUX_F_OFD_GETLK, + (uintptr_t)&lock, 0, 0, 0)); + assert(lock.type == LINUX_F_UNLCK); + clear_task_files(parent); + sched_task_file_release(parent); + sched_task_file_release(child); + current_task[0] = descriptor_dispatch_task = NULL; + free(parent); + free(child); + puts("PASS OFD lock lifetime: inline promotion, dup/fork, unrelated close, FD reuse, retained reference, final release and nonblocking fcntl frame"); +} + +/** @brief Keep a blocked lock operation on its original OFD across fd reuse. */ +static void test_record_lock_retry_description(void) +{ + extern struct task *current_task[]; + struct task *owner = calloc(1, sizeof(*owner)), *waiter = calloc(1, sizeof(*waiter)); + assert(owner && waiter); + owner->pid = owner->tgid = 1386; + waiter->pid = waiter->tgid = 1387; + owner->limits.nofile.rlim_cur = waiter->limits.nofile.rlim_cur = 32; + struct task_file *source, *waiting; + assert(task_allocate_fd(owner, 3, &source) == 3); + assert(task_allocate_fd(waiter, 3, &waiting) == 3); + source->flags = waiting->flags = RELIEFOS_O_RDWR; + source->node = waiting->node = (struct storage_node){ + .type = RELIEFOS_FS_TYPE_FILE, .volume_id = 1, .first_cluster = 8802}; + fail_allocation = 1; + assert(!task_begin_syscall_io(waiter, LINUX_SYS_FCNTL, 3, LINUX_F_GETFD)); + assert(!waiter->syscall_file); + assert(task_begin_syscall_io(waiter, LINUX_SYS_FCNTL, 3, LINUX_F_OFD_SETLKW) == -RELIEFOS_ENOMEM); + assert(!waiter->syscall_file && !waiting->description); + fail_allocation = 0; + const unsigned commands[] = {LINUX_F_GETLK, LINUX_F_SETLK, LINUX_F_SETLKW, + LINUX_F_OFD_GETLK, LINUX_F_OFD_SETLK, LINUX_F_OFD_SETLKW}; + for (unsigned i = 0; i < sizeof(commands) / sizeof(commands[0]); ++i) { + assert(!task_begin_syscall_io(waiter, LINUX_SYS_FCNTL, 3, commands[i])); + assert(waiter->syscall_file == task_file_for_fd(waiter, 3)); + task_release_syscall_file(waiter); + } + struct descriptor_record_lock lock = {.type = LINUX_F_WRLCK, .length = 1}; + current_task[0] = descriptor_dispatch_task = owner; + assert(!syscall_record_lock(3, LINUX_F_OFD_SETLK, (uintptr_t)&lock)); + current_task[0] = descriptor_dispatch_task = waiter; + assert(!task_begin_syscall_io(waiter, LINUX_SYS_FCNTL, 3, LINUX_F_OFD_SETLKW)); + assert(syscall_record_lock(3, LINUX_F_OFD_SETLKW, (uintptr_t)&lock) == KERNEL_SYSCALL_BLOCKED); + struct task_file *held = waiter->syscall_file; + assert(waiter->waiting_queue); + assert(!syscall_legacy_descriptors(LINUX_SYS_CLOSE, 3, 0, 0, 0, 0, 0)); + assert(task_allocate_fd(waiter, 3, &waiting) == 3); + waiting->flags = RELIEFOS_O_RDWR; + waiting->node = source->node; + ++waiting->node.first_cluster; + current_task[0] = descriptor_dispatch_task = owner; + lock.type = LINUX_F_UNLCK; + assert(!syscall_record_lock(3, LINUX_F_OFD_SETLK, (uintptr_t)&lock)); + current_task[0] = descriptor_dispatch_task = waiter; + lock.type = LINUX_F_WRLCK; + assert(!task_begin_syscall_io(waiter, LINUX_SYS_FCNTL, 3, LINUX_F_OFD_SETLKW)); + assert(task_file_for_io(waiter, 3) == held && held->node.first_cluster == 8802); + assert(!syscall_record_lock(3, LINUX_F_OFD_SETLKW, (uintptr_t)&lock)); + assert(!waiter->waiting_queue && !waiting->record_lock_owner); + current_task[0] = descriptor_dispatch_task = owner; + assert(syscall_record_lock(3, LINUX_F_OFD_SETLK, (uintptr_t)&lock) == -RELIEFOS_EAGAIN); + task_release_syscall_file(waiter); + assert(!syscall_record_lock(3, LINUX_F_OFD_SETLK, (uintptr_t)&lock)); + clear_task_files(owner); + clear_task_files(waiter); + sched_task_file_release(owner); + sched_task_file_release(waiter); + current_task[0] = descriptor_dispatch_task = NULL; + free(owner); + free(waiter); + puts("PASS record-lock admission: six commands, OOM rollback, GETFD, blocked close/reuse and final pinned release"); +} + static void test_pty_descriptions(void) { struct task *parent = calloc(1, sizeof(*parent)), *child = calloc(1, sizeof(*child)); @@ -2977,6 +3128,8 @@ static void test_proc_ofd_lifetime(void) int main(void) { + test_ofd_record_lock_lifetime(); + test_record_lock_retry_description(); test_proc_ofd_lifetime(); assert(!audio_character_init()); assert(!drm_character_init()); diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index aa8a9729..1905835d 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -248,6 +248,9 @@ void syscall_flock_release_owner(struct task_file *owner) { (void)owner; } * @param task Borrowed actor. @param descriptor Borrowed descriptor. */ void syscall_record_locks_close(struct task *task, struct task_file *descriptor) { (void)task; (void)descriptor; } +/** @brief Observe final close against the empty OFD lock registry. + * @param file Borrowed retiring description. */ +void syscall_record_locks_release(struct task_file *file) { (void)file; } /** @brief Retire an unwatched description in this fixture. * @param description Borrowed open description. */ void task_epoll_remove_file_description(struct task_file *description) { (void)description; } diff --git a/tools/tests/record_locks_test.c b/tools/tests/record_locks_test.c index ce0ba376..df97760a 100644 --- a/tools/tests/record_locks_test.c +++ b/tools/tests/record_locks_test.c @@ -10,10 +10,13 @@ static struct task wait_owner; static struct task lock_waiters[RECORD_LOCK_WAITERS_TEST]; static struct task_file file = {.used = 1, .flags = LINUX_O_RDWR, .node = {.type = RELIEFOS_FS_TYPE_FILE, .volume_id = 1, .first_cluster = 50}}; +static struct task_file other_file; static int allocation_fails; struct task *sched_current_task(void) { return current; } struct task_file *task_file_for_fd(struct task *task, int fd) -{ assert(task); return fd == 5 ? &file : NULL; } +{ assert(task); return fd == 5 ? &file : fd == 6 ? &other_file : NULL; } +struct task_file *task_file_for_io(struct task *task, int fd) +{ return task_file_for_fd(task, fd); } bool user_range_ok(uint64_t pointer, uint64_t size) { return pointer > 4096 && size == 32; } bool user_range_writable(uint64_t pointer, uint64_t size) { return user_range_ok(pointer, size); } void *kernel_malloc(size_t size) { return allocation_fails ? NULL : malloc(size); } @@ -25,10 +28,65 @@ uint32_t kernel_wait_queue_wake_all(struct kernel_wait_queue *queue) { (void)que void kernel_wait_queue_remove(struct kernel_wait_queue *queue, struct task *task) { assert(task->waiting_queue == queue); task->waiting_queue = NULL; } void kernel_wait_queue_block_current(struct kernel_wait_queue *queue) { current->waiting_queue = queue; } -static int request(unsigned command, short type, long start, long size) +static int request_fd(int fd, unsigned command, short type, long start, long size) { struct native_flock lock = {.type = type, .start = start, .length = size}; - return syscall_record_lock(5, command, (uintptr_t)&lock); + return syscall_record_lock(fd, command, (uintptr_t)&lock); +} +static int request(unsigned command, short type, long start, long size) +{ + return request_fd(5, command, type, start, size); +} + +static void test_ofd_record_locks(void) +{ + file.flags = LINUX_O_RDWR; + other_file = file; + current = &first; + assert(request(LINUX_F_OFD_SETLK, LINUX_F_WRLCK, 10, 20) == 0); + assert(request(LINUX_F_SETLK, LINUX_F_WRLCK, 10, 1) == -LINUX_EAGAIN); + struct native_flock result = {.type = LINUX_F_WRLCK, .start = 10, .length = 1}; + assert(syscall_record_lock(5, LINUX_F_OFD_GETLK, (uintptr_t)&result) == 0); + assert(result.type == LINUX_F_UNLCK && result.start == 10 && result.length == 1 && !result.pid); + result.type = LINUX_F_WRLCK; + assert(syscall_record_lock(6, LINUX_F_OFD_GETLK, (uintptr_t)&result) == 0); + assert(result.type == LINUX_F_WRLCK && result.start == 10 && result.length == 20 && result.pid == -1); + result = (struct native_flock){.type = LINUX_F_WRLCK, .start = 10, .length = 1}; + assert(syscall_record_lock(5, LINUX_F_GETLK, (uintptr_t)&result) == 0 && result.pid == -1); + const unsigned commands[] = {LINUX_F_OFD_GETLK, LINUX_F_OFD_SETLK, LINUX_F_OFD_SETLKW}; + for (unsigned i = 0; i < sizeof(commands) / sizeof(commands[0]); ++i) { + result = (struct native_flock){.type = LINUX_F_WRLCK, .start = 50, .length = 1, .pid = 41}; + assert(syscall_record_lock(5, commands[i], (uintptr_t)&result) == -LINUX_EINVAL); + } + assert(request(LINUX_F_OFD_SETLK, LINUX_F_RDLCK, 15, 5) == 0); + assert(request_fd(6, LINUX_F_OFD_SETLK, LINUX_F_RDLCK, 15, 5) == 0); + assert(request_fd(6, LINUX_F_OFD_SETLK, LINUX_F_WRLCK, 10, 5) == -LINUX_EAGAIN); + allocation_fails = 1; + assert(request(LINUX_F_OFD_SETLK, LINUX_F_UNLCK, 10, 5) == -LINUX_ENOLCK); + allocation_fails = 0; + syscall_record_locks_close(&first, &file); + assert(request_fd(6, LINUX_F_OFD_SETLK, LINUX_F_WRLCK, 10, 5) == -LINUX_EAGAIN); + current = &second; + assert(request_fd(6, LINUX_F_OFD_SETLKW, LINUX_F_WRLCK, 10, 5) == KERNEL_SYSCALL_BLOCKED); + current = &first; + assert(request(LINUX_F_OFD_SETLK, LINUX_F_UNLCK, 0, 0) == 0); + current = &second; + assert(request_fd(6, LINUX_F_OFD_SETLKW, LINUX_F_WRLCK, 10, 5) == 0 && !second.waiting_queue); + assert(request_fd(6, LINUX_F_OFD_SETLK, LINUX_F_UNLCK, 0, 0) == 0); + + current = &first; + assert(request(LINUX_F_OFD_SETLK, LINUX_F_WRLCK, 0, 1) == 0); + current = &second; + assert(request_fd(6, LINUX_F_OFD_SETLK, LINUX_F_WRLCK, 1, 1) == 0); + current = &first; + assert(request(LINUX_F_OFD_SETLKW, LINUX_F_WRLCK, 1, 1) == KERNEL_SYSCALL_BLOCKED); + current = &second; + assert(request_fd(6, LINUX_F_OFD_SETLKW, LINUX_F_WRLCK, 0, 1) == KERNEL_SYSCALL_BLOCKED); + assert(request_fd(6, LINUX_F_OFD_SETLK, LINUX_F_UNLCK, 0, 0) == 0); + current = &first; + assert(request(LINUX_F_OFD_SETLK, LINUX_F_UNLCK, 0, 0) == 0); + assert(!pending_count && !first.waiting_queue && !second.waiting_queue); + puts("PASS OFD ranges: independent owners, POSIX conflicts, PID checks, queries, conversion, OOM and blocking without deadlock detection"); } static int test_more_than_64_record_lock_waiters(void) @@ -109,5 +167,6 @@ int main(void) file.flags = TASK_FILE_FLAG_PATH; assert(request(LINUX_F_GETLK, LINUX_F_RDLCK, 100, 0) == -LINUX_EBADF); syscall_record_locks_close(&first, &file); + test_ofd_record_locks(); puts("PASS production record locks: 65 pending requests, conflict, split/merge, stable owner, deadlock, close, ENOLCK rollback and unaligned ABI"); } diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 4db2cdc6..4cc7d33f 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -5272,6 +5272,7 @@ "tools/tests/task8_host_stubs/writable_alias_model.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", + "tools/tests/task8_host_stubs/descriptor_unreached.c", "kernel/sched/exec.c", "kernel/sched/task.c", "kernel/sched/core.c", @@ -5315,6 +5316,8 @@ "fs/devfs/identity.c", "fs/vfs/object.c", "fs/vfs/write_access.c", + "fs/vfs/lookup_cache.c", + "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", diff --git a/tools/tests/task8_host_stubs/descriptor_unreached.c b/tools/tests/task8_host_stubs/descriptor_unreached.c new file mode 100644 index 00000000..4358cb2c --- /dev/null +++ b/tools/tests/task8_host_stubs/descriptor_unreached.c @@ -0,0 +1,41 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +/* Descriptor fixtures model UNIX sockets, legacy PTYs and card event I/O. + * Trap unmodeled routing and hardware branches if a test reaches them. + * Real lock, descriptor, wait and VFS operations remain linked to production. */ +#define UNREACHED(name) \ + /** @brief Reject a branch outside the descriptor fixture's model. */ \ + __attribute__((noreturn)) void name(void) { __builtin_trap(); } + +UNREACHED(task_netlink_release) +UNREACHED(task_netlink_recv) +UNREACHED(task_netlink_send) +UNREACHED(task_netlink_poll) +UNREACHED(task_netlink_passcred) +UNREACHED(task_netlink_recv_staged) +UNREACHED(syscall_netlink) +UNREACHED(task_packet_address_size) +UNREACHED(task_udp_address_size) +UNREACHED(task_packet_recv_ex) +UNREACHED(task_udp_recv_ex) +UNREACHED(net_socket_family) +UNREACHED(net_socket_connect6_fd) +UNREACHED(net_socket_address6) +UNREACHED(net_socket_listen_fd) +UNREACHED(net_socket_accept_peek) +UNREACHED(net_socket_bind6_fd) +UNREACHED(net_socket_accept_commit) +UNREACHED(net_socket_bound_device) +UNREACHED(net_interface_device_option) +UNREACHED(net_socket_nodelay) +UNREACHED(net_socket_ipv6_option) +UNREACHED(net_socket_is_listening) +UNREACHED(net_socket_wait_readable) +UNREACHED(net_socket_reuse) +UNREACHED(drm_sync_ioctl) +UNREACHED(drm_sync_poll) +UNREACHED(devpts_slave_pty) +UNREACHED(devpts_resolve_ptmx) +UNREACHED(devpts_new_pty) +UNREACHED(task_pidfd_poll) +UNREACHED(address_space_user_page_copyable) +UNREACHED(task_pipe_try_io) From a46b562c45c30ab2f864e3aa13dc32e5ce0461b8 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 18:24:19 +0800 Subject: [PATCH 36/97] fix(exec): clear native ELF entry finalizer register Do not pass the initial environment vector as a glibc loader finalizer. Preserve the private interpreter startup ABI and cover both entry paths. --- .../locale/en/LC_MESSAGES/userspace-api/exec.po | 3 +++ .../locale/ja/LC_MESSAGES/userspace-api/exec.po | 3 +++ Documentation/userspace-api/exec.rst | 4 ++++ kernel/exec/userland.c | 11 +++++++++-- tools/tests/vdso_auxv_test.c | 16 ++++++++++++++-- 5 files changed, 33 insertions(+), 4 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/exec.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/exec.po index f1b4952d..05c0e0ae 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/exec.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/exec.po @@ -89,3 +89,6 @@ msgstr "" msgstr "" + +msgid "原生 x86-64 ELF 入口从初始栈读取 ``argc``、``argv`` 和 ``envp``。内核在入口将 ``RDX`` 置零,不提供动态加载器退出回调。仅采用旧 ReliefOS 私有解释器 ABI 的 程序仍在 ``RDX`` 接收 ``envp``,并在 ``R8`` 接收启动记录。" +msgstr "A native x86-64 ELF entry point reads ``argc``, ``argv`` and ``envp`` from the initial stack. The kernel clears ``RDX`` on entry; it does not supply a dynamic loader exit callback. Programs using the historical private ReliefOS interpreter ABI still receive ``envp`` in ``RDX`` and the launch record in ``R8``." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/exec.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/exec.po index 3aa5fe48..f09eb399 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/exec.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/exec.po @@ -77,3 +77,6 @@ msgstr "" msgstr "" + +msgid "原生 x86-64 ELF 入口从初始栈读取 ``argc``、``argv`` 和 ``envp``。内核在入口将 ``RDX`` 置零,不提供动态加载器退出回调。仅采用旧 ReliefOS 私有解释器 ABI 的 程序仍在 ``RDX`` 接收 ``envp``,并在 ``R8`` 接收启动记录。" +msgstr "ネイティブ x86-64 ELF のエントリーポイントは初期スタックから ``argc``、``argv``、``envp`` を読み取る。カーネルはエントリー時に ``RDX`` をゼロにし、動的ローダーの終了コールバックを渡さない。旧 ReliefOS 独自のインタープリター ABI を使うプログラムでは、引き続き ``RDX`` で ``envp``、``R8`` で起動レコードを受け取る。" diff --git a/Documentation/userspace-api/exec.rst b/Documentation/userspace-api/exec.rst index b71e20ab..4de5b257 100644 --- a/Documentation/userspace-api/exec.rst +++ b/Documentation/userspace-api/exec.rst @@ -24,6 +24,10 @@ exec 参数与初始栈 exec;失败保留旧映像、描述符和信号状态。内部 boot/service launch 请求仍 使用原有的小型固定请求结构,该结构不限制 Linux exec 系统调用。 +原生 x86-64 ELF 入口从初始栈读取 ``argc``、``argv`` 和 ``envp``。内核在入口将 +``RDX`` 置零,不提供动态加载器退出回调。仅采用旧 ReliefOS 私有解释器 ABI 的 +程序仍在 ``RDX`` 接收 ``envp``,并在 ``R8`` 接收启动记录。 + 本仓 ``tools/test_exec_script.py`` 对生产参数复制和 shebang 重写运行 ASan/UBSan 测试;``tools/test_exec_limits.py`` 在 Linux 上运行边界 参照。对应的 ``tools/tests/exec_limits_runtime_probe.c`` 可以在 ReliefOS 内用 diff --git a/kernel/exec/userland.c b/kernel/exec/userland.c index dc6d1126..a2f5b36e 100644 --- a/kernel/exec/userland.c +++ b/kernel/exec/userland.c @@ -318,7 +318,12 @@ static int write_user_u64(const struct address_space *as, uint64_t vaddr, uint64 } /** - * @brief Lay out argv/envp (and the dynamic-launch record) on the task's user stack and point the initial frame at them. + * @brief Build the initial ELF stack and entry registers for a staged image. + * @param task Unpublished task receiving stack pages and the initial frame. + * @param execfn Original name for AT_EXECFN, or NULL to use the task path. + * @param vdso_ehdr Mapped vDSO ELF header address, or zero when absent. + * @return Zero or negative stack budget/mapping errno. Native ELF starts with + * no loader finalizer in RDX; the private interpreter still receives envp. */ static int prepare_user_exec_stack(struct task *task, const char *execfn, uint64_t vdso_ehdr) { @@ -490,7 +495,9 @@ static int prepare_user_exec_stack(struct task *task, const char *execfn, uint64 task->frame.rsp = argc_base; task->frame.rdi = argc; task->frame.rsi = argv_base; - task->frame.rdx = envp_base; + /* A native CRT registers a nonzero RDX as the loader's exit callback. + * Only the private interpreter ABI expects an environment pointer here. */ + task->frame.rdx = launch_base ? envp_base : 0; task->frame.r8 = launch_base; return 0; } diff --git a/tools/tests/vdso_auxv_test.c b/tools/tests/vdso_auxv_test.c index c370dd9b..960b189b 100644 --- a/tools/tests/vdso_auxv_test.c +++ b/tools/tests/vdso_auxv_test.c @@ -1,4 +1,4 @@ -/* Detect wrong auxv capacity/layout and advertising an absent vDSO image. */ +/* Check the initial ELF stack and the native/private entry register contracts. */ #include #include #include @@ -40,8 +40,11 @@ int main(void) task->exec_phnum = 3; for (unsigned i = 0; i < 16; ++i) task->dynamic_launch.random[i] = (unsigned char)(i + 1); const uint64_t vdso = 0x28000000; + task->frame.rdx = UINT64_C(0xdeadbeef); assert(prepare_user_exec_stack(task, task->path, vdso) == 0); assert(!(task->frame.rsp & 15)); + /* glibc _start interprets %rdx as a destructor, not an environment pointer. */ + assert(task->frame.rdx == 0 && task->frame.r8 == 0); uint64_t *words = (void *)(stack + (task->frame.rsp - (top - sizeof(stack)))); assert(words[0] == 1 && words[1] && words[2] == 0 && words[3] == 0); uint64_t *aux = words + 4; @@ -56,7 +59,16 @@ int main(void) } } assert(count == 16 && aux[1] == 0 && seen_vdso == 1 && seen_random == 1); + + task->dynamic_launch.abi_major = RELIEFOS_ELF_ABI_MAJOR; + assert(prepare_user_exec_stack(task, task->path, vdso) == 0); + assert(task->frame.rdi == 1 && task->frame.rsi == task->frame.rsp + 8); + assert(task->frame.rdx == task->frame.rsp + 24); + assert(task->frame.r8 > task->frame.rdx && task->frame.r8 < top); + struct reliefos_dynamic_launch launch; + memcpy(&launch, stack + (task->frame.r8 - (top - sizeof(stack))), sizeof(launch)); + assert(launch.abi_major == RELIEFOS_ELF_ABI_MAJOR && launch.main_entry == 0x400100); free(task); - puts("PASS initial stack: vDSO auxv, terminator, random data and SysV alignment"); + puts("PASS ELF entry: vDSO auxv, SysV stack, null native destructor and private launch ABI"); return 0; } From 2c68750afbd1e8e84f1d28cd6b50bf6c6d7e0883 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 18:31:45 +0800 Subject: [PATCH 37/97] feat(procfs): expose a stable boot ID --- .../en/LC_MESSAGES/userspace-api/procfs.po | 3 + .../ja/LC_MESSAGES/userspace-api/procfs.po | 3 + Documentation/userspace-api/procfs.rst | 3 + fs/proc/procfs.c | 69 +++++++++++- tools/tests/procfs_directories_test.c | 104 ++++++++++++++++++ 5 files changed, 177 insertions(+), 5 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po index 35c84dd1..942d5c98 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po @@ -304,6 +304,9 @@ msgstr "" msgid "``/proc/sys/kernel/pid_max``:非零 32 位 PID 命名空间上限。" msgstr "``/proc/sys/kernel/pid_max``: upper bound of the nonzero 32-bit PID namespace." +msgid "``/proc/sys/kernel/random/boot_id``:本次启动的 UUID v4。格式为带连字符的小写十六进制字符串, 末尾带换行,同一次启动中的所有 proc 挂载读取相同值。首次有效读取由内核随机源生成; 随机源报错时返回原错误,后续读取可重试。" +msgstr "``/proc/sys/kernel/random/boot_id``: this boot's UUID v4, printed in lowercase hexadecimal with hyphens and a final newline. All proc mounts return the same value during a boot. The kernel random source supplies the ID on the first successful read. An entropy error is returned unchanged and later reads can retry." + msgid "``/proc/sys/fs/nr_open``:描述符实现上限。" msgstr "``/proc/sys/fs/nr_open``: descriptor implementation limit." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po index 116ede41..5ad20dcc 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po @@ -265,6 +265,9 @@ msgstr "次のノードは現行カーネル方針の読み取り専用スナッ msgid "``/proc/sys/kernel/pid_max``:非零 32 位 PID 命名空间上限。" msgstr "``/proc/sys/kernel/pid_max``:非ゼロの 32 ビット PID 名前空間の上限。" +msgid "``/proc/sys/kernel/random/boot_id``:本次启动的 UUID v4。格式为带连字符的小写十六进制字符串, 末尾带换行,同一次启动中的所有 proc 挂载读取相同值。首次有效读取由内核随机源生成; 随机源报错时返回原错误,后续读取可重试。" +msgstr "``/proc/sys/kernel/random/boot_id``:今回の起動を表す UUID v4 です。ハイフン付きの小文字の十六進数で、末尾に改行があります。同じ起動中はすべての proc マウントから同じ値を読み取れます。最初の読み取りが成功した時点でカーネルの乱数源から生成します。乱数源のエラーはそのまま返され、後続の読み取りで再試行できます。" + msgid "``/proc/sys/fs/nr_open``:描述符实现上限。" msgstr "``/proc/sys/fs/nr_open``:記述子の実装上の上限。" diff --git a/Documentation/userspace-api/procfs.rst b/Documentation/userspace-api/procfs.rst index 7713233d..6ff808f3 100644 --- a/Documentation/userspace-api/procfs.rst +++ b/Documentation/userspace-api/procfs.rst @@ -147,6 +147,9 @@ dup 共享已打开的视图,重新打开会生成新视图。快照不采用 以下节点是现行内核策略的只读快照,不支持通过写文件调整: * ``/proc/sys/kernel/pid_max``:非零 32 位 PID 命名空间上限。 +* ``/proc/sys/kernel/random/boot_id``:本次启动的 UUID v4。格式为带连字符的小写十六进制字符串, + 末尾带换行,同一次启动中的所有 proc 挂载读取相同值。首次有效读取由内核随机源生成; + 随机源报错时返回原错误,后续读取可重试。 * ``/proc/sys/fs/nr_open``:描述符实现上限。 * ``/proc/sys/fs/file-nr``:实际已分配 OFD、零个闲置预分配 OFD、全局上限。 dup/fork 别名不重复计数,排队、映射或进行中 I/O 保留的 OFD 直到最终释放才减计数。 diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 3846a5ab..033a5ebc 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -16,7 +16,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -30,6 +32,8 @@ #define PROCFS_PATH_MAX RELIEFOS_FS_PATH_LEN #define PROCFS_CONTENT_MAX 1024u +#define PROCFS_RANDOM_DIR "/proc/sys/kernel/random" +#define PROCFS_BOOT_ID PROCFS_RANDOM_DIR "/boot_id" static int proc_text_eq(const char *a, const char *b) { @@ -331,6 +335,50 @@ static int proc_fill_content(const char *path, char *buffer, uint32_t capacity) return -2; } +/** + * @brief Read one slice of the boot-wide UUID v4, shared by all proc mounts. + * @param offset Byte position including the final newline. + * @param buffer Kernel destination; may be NULL only if length is zero. + * @param length Writable byte capacity. + * @param out_read Optional byte count, already cleared by proc_read. + * @return Zero or a negative entropy-source error. The first successful + * nonempty read publishes the ID under an IRQ-safe lock for the rest of the boot. + */ +static int proc_boot_id_read(uint64_t offset, void *buffer, uint32_t length, + uint32_t *out_read) +{ + enum { boot_id_text_length = sizeof("00000000-0000-0000-0000-000000000000\n") - 1 }; + static struct kernel_spinlock lock = KERNEL_SPINLOCK_INIT; + static uint8_t boot_id[16]; + static bool ready; + uint8_t bytes[sizeof(boot_id)]; + uint64_t flags; + int rc = 0; + + if (!length || offset >= boot_id_text_length) return 0; + kernel_spin_lock_irqsave(&lock, &flags); + if (!ready) { + rc = kernel_random_fill(boot_id, sizeof(boot_id)); + if (!rc) { + boot_id[6] = (boot_id[6] & 0x0f) | 0x40; /* Version 4. */ + boot_id[8] = (boot_id[8] & 0x3f) | 0x80; /* RFC UUID variant. */ + ready = true; + } + } + if (!rc) __builtin_memcpy(bytes, boot_id, sizeof(bytes)); + kernel_spin_unlock_irqrestore(&lock, flags); + if (rc) return rc; + + struct text_stream stream = {.offset = offset, .buffer = buffer, .capacity = length}; + for (unsigned i = 0; i < sizeof(bytes); ++i) { + if (i == 4 || i == 6 || i == 8 || i == 10) text_string(&stream, "-"); + text_hex(&stream, bytes[i], 2); + } + text_string(&stream, "\n"); + if (out_read) *out_read = stream.written; + return 0; +} + /** * @brief Parse a proc fd link without accepting overflow or trailing text. * @param file Task-relative pathname, nullable. @@ -901,7 +949,7 @@ int proc_lookup(const char *path, struct storage_node *out) } #endif if (proc_text_eq(path, "/proc") || proc_text_eq(path, "/proc/sys") || - proc_text_eq(path, "/proc/sys/kernel") || + proc_text_eq(path, "/proc/sys/kernel") || proc_text_eq(path, PROCFS_RANDOM_DIR) || proc_text_eq(path, "/proc/asound") #ifdef CONFIG_LOCK_STAT || proc_text_eq(path, "/proc/reliefnt") @@ -938,7 +986,9 @@ int proc_lookup(const char *path, struct storage_node *out) return 0; } #endif - if (proc_memory_is_file(path) || proc_mount_view(path,NULL) || proc_text_eq(path,"/proc/cpuinfo") || proc_text_eq(path,"/proc/leonos-drivers")) { + if (proc_memory_is_file(path) || proc_mount_view(path,NULL) || + proc_text_eq(path, PROCFS_BOOT_ID) || proc_text_eq(path,"/proc/cpuinfo") || + proc_text_eq(path,"/proc/leonos-drivers")) { if (out) *out = (struct storage_node){ .type = RELIEFOS_FS_TYPE_FILE, .flags = STORAGE_NODE_FLAG_PROC, .first_cluster = 0x50524f43u, .size = 0, @@ -1051,7 +1101,8 @@ int proc_lookup(const char *path, struct storage_node *out) * @param out_read Optional caller-owned writable actual byte count. * @return Zero or negative errno, preserving backend failures. Execution-owned; * retains no caller memory and live generated views can change between reads. - * A cgroup membership record reflects a single locked ancestry snapshot. */ + * A cgroup membership record reflects a single locked ancestry snapshot; + * boot_id remains fixed throughout the boot. */ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, uint32_t *out_read) { @@ -1059,6 +1110,8 @@ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, *out_read = 0; if (!path || (!buffer && length)) return -RELIEFOS_EINVAL; + if (proc_text_eq(path, PROCFS_BOOT_ID)) + return proc_boot_id_read(offset, buffer, length, out_read); if (proc_extra_kind(path) == 1) { struct text_stream stream = {.offset = offset, .buffer = buffer, .capacity = length}; int rc = proc_extra_emit(path, &stream); @@ -1298,9 +1351,15 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * return 1; } #endif + if (proc_text_eq(path, PROCFS_RANDOM_DIR)) { + if (*offset) return 0; + *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_FILE, .name = "boot_id"}; + *offset = 1; + return 1; + } if (proc_text_eq(path, "/proc/sys") || proc_text_eq(path, "/proc/sys/kernel")) { static const char *values[] = {"hostname", "domainname", "ostype", "osrelease", - "version", "overflowuid", "overflowgid", "pid_max" + "version", "overflowuid", "overflowgid", "pid_max", "random" #ifdef CONFIG_SECCOMP_FILTER , "seccomp" #endif @@ -1309,7 +1368,7 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * if (*offset >= (parent ? 2 : sizeof(values) / sizeof(values[0]))) return 0; const char *name = parent ? (*offset ? "fs" : "kernel") : values[*offset]; - entry->type = parent || proc_text_eq(name, "seccomp") + entry->type = parent || proc_text_eq(name, "seccomp") || proc_text_eq(name, "random") ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_FILE; proc_copy(entry->name, sizeof(entry->name), name); ++*offset; diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index 679afaa9..c4a838d9 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -5,10 +5,49 @@ #include #include #include "../../include/reliefnt/audio.h" +#include +#include int sound_service_card_snapshot(uint32_t index, uint32_t *out_id, struct audio_card_identity *identity) { (void)index; (void)out_id; (void)identity; return -2; } #include "../../fs/proc/procfs.c" + +static unsigned proc_entropy_calls; +static bool proc_entropy_fails = true; + +/** @brief Model the bounded hardware entropy source used by proc boot_id. + * @param buffer Writable byte array. @param length Must be 16 bytes. + * @return Zero on success or negative EIO for the injected failure. + */ +int kernel_random_fill(void *buffer, size_t length) +{ + static const uint8_t sample[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, + 0x35, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc}; + assert(length == sizeof(sample)); + ++proc_entropy_calls; + if (proc_entropy_fails) return -EIO; + memcpy(buffer, sample, length); + return 0; +} + +/** @brief Model IRQ-safe spinlock acquisition in this single-threaded fixture. + * @param lock Unheld lock. @param flags Saved IRQ-state output. + */ +void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) +{ + assert(!lock->state); + lock->state = 1; + *flags = 0; +} + +/** @brief Release a held fixture lock. + * @param lock Held lock. @param flags Previously saved IRQ state. + */ +void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) +{ + assert(lock->state == 1 && !flags); + lock->state = 0; +} #ifndef MEMORY_REPORTING_REAL_PRODUCERS /* Other proc tests model the separately linked memory reporting provider. */ bool proc_memory_is_file(const char *name) @@ -832,8 +871,73 @@ static void test_proc_mount_namespace_handles(void) puts("PASS proc namespace aliases, permissions, stable identity and PID reuse"); } +/** @brief Verify stable, read-only boot identity through independent proc mounts. */ +static void test_proc_boot_id(void) +{ + struct vfs_namespace ns[2] = {0}; + struct vfs_path root[2] = {0}, boot_id[2] = {0}; + unsigned before = proc_allocations; + for (unsigned i = 0; i < 2; ++i) { + struct vfs_mount *mount = NULL; + assert(!proc_create_vfs_mount(&mount)); + assert(!vfs_namespace_init(&ns[i], mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns[i], &root[i])); + assert(!vfs_path_lookup(&ns[i], &root[i], &root[i], "sys/kernel/random/boot_id", 0, + &boot_id[i])); + } + + struct vfs_path kernel = {0}, random = {0}; + assert(!vfs_path_lookup(&ns[0], &root[0], &root[0], "sys/kernel", 0, &kernel)); + assert(!vfs_path_lookup(&ns[0], &root[0], &kernel, "random", 0, &random)); + struct reliefos_dir_entry entry; + bool found_random = false; + uint64_t cursor = 0; + int rc; + while ((rc = vfs_path_readdir(&kernel, &cursor, &entry)) > 0) + if (!strcmp(entry.name, "random")) + found_random = entry.type == RELIEFOS_FS_TYPE_DIR; + assert(!rc && found_random); + cursor = 0; + assert(vfs_path_readdir(&random, &cursor, &entry) == 1 && + !strcmp(entry.name, "boot_id") && entry.type == RELIEFOS_FS_TYPE_FILE); + assert(!vfs_path_readdir(&random, &cursor, &entry)); + + struct linux_stat_abi st; + assert(!vfs_path_stat(&random, &st) && st.st_mode == (LINUX_S_IFDIR | 0555)); + assert(!vfs_path_stat(&boot_id[0], &st) && st.st_mode == (LINUX_S_IFREG | 0444) && + st.st_size == 0 && !st.st_uid && !st.st_gid); + assert(vfs_path_truncate(&boot_id[0], 0) == -EROFS); + const char expected[] = "01234567-89ab-4def-b510-32547698badc\n"; + char text[sizeof(expected)] = {0}; + uint32_t got = 0; + assert(!vfs_path_read(&boot_id[0], sizeof(expected) - 1, text, sizeof(text), &got) && !got); + assert(!proc_entropy_calls); + assert(vfs_path_read(&boot_id[0], 0, text, sizeof(text), &got) == -EIO && !got && !text[0]); + proc_entropy_fails = false; + assert(!vfs_path_read(&boot_id[0], 0, text, 7, &got) && got == 7); + assert(!vfs_path_read(&boot_id[0], 7, text + 7, sizeof(text) - 7, &got) && + got == sizeof(expected) - 1 - 7); + assert(!memcmp(text, expected, sizeof(expected))); + proc_entropy_fails = true; + memset(text, 0, sizeof(text)); + assert(!vfs_path_read(&boot_id[1], 0, text, sizeof(text), &got) && got == sizeof(expected) - 1); + assert(!memcmp(text, expected, sizeof(expected)) && proc_entropy_calls == 2); + + vfs_path_put(&random); + vfs_path_put(&kernel); + for (unsigned i = 0; i < 2; ++i) { + vfs_path_put(&boot_id[i]); + vfs_path_put(&root[i]); + assert(!vfs_namespace_destroy(&ns[i])); + } + assert(proc_allocations == before); + puts("PASS proc boot_id lookups, UUID format, stable partial reads and entropy retry"); +} + int main(void) { + test_proc_boot_id(); test_proc_fd_metadata(); test_proc_fd_object_link(); test_proc_mount_objects(); From f5d1ef9717e08ba070bacda457ecc49e5d0811e0 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 18:47:54 +0800 Subject: [PATCH 38/97] fix(tmpfs): decouple memory mounts from disk volume slots --- .../en/LC_MESSAGES/userspace-api/abi.po | 3 + .../ja/LC_MESSAGES/userspace-api/abi.po | 3 + Documentation/userspace-api/abi.rst | 5 + block/core/device_number.c | 21 ++-- block/core/storage_core_api.h | 27 ++++- block/core/storage_state.c | 7 +- block/core/storage_state_data.c | 79 ++++++++++++- block/core/storage_sync.c | 21 ++-- block/core/storage_types.h | 8 +- block/partition/partition_mount.c | 2 +- fs/tmpfs/core.c | 7 +- fs/vfs/mounts.c | 18 +-- fs/vfs/storage_backend.h | 5 + fs/vfs/storage_initial.c | 44 ++----- fs/vfs/storage_mount.c | 51 +++++---- include/reliefnt/storage.h | 23 ++-- include/reliefnt/tmpfs.h | 10 ++ tools/tests/mount_backend_test.c | 108 +++++++++++++++--- 18 files changed, 309 insertions(+), 133 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 8f066f57..2018af27 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -354,6 +354,9 @@ msgstr "" msgid "文件系统上下文和游离挂载" msgstr "Filesystem Contexts and Detached Mounts" +msgid "由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 ``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 mountinfo 报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 inode 引用释放且相关缓存回收后,设备号才能重用。" +msgstr "Tmpfs instances created by ``mount(2)`` or a filesystem context, and the initial ``/dev/shm``, do not occupy disk volume slots. Each instance has a distinct anonymous device number; ``stat`` and mountinfo report the same device number, and bind mounts share the original instance's number. The number may be reused only after the last mount and inode references are released and their caches are retired." + msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` creates a filesystem context. The caller needs effective ``CAP_SYS_ADMIN``. ``FSCONFIG_SET_STRING`` in ``fsconfig`` accepts the existing tmpfs options, including ``size``, ``nr_blocks``, ``nr_inodes``, ``mode``, ``uid`` and ``gid``. ``FSCONFIG_SET_FLAG`` accepts ``ro`` and ``rw``. ``FSCONFIG_CMD_CREATE`` creates the filesystem using the configured options and may be retried after failure. The context belongs to the open-file description, is shared after dup or fork, and is released with the final reference." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index d68908c3..51d84cb8 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -309,6 +309,9 @@ msgstr "" msgid "文件系统上下文和游离挂载" msgstr "ファイルシステムコンテキストと未接続マウント" +msgid "由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 ``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 mountinfo 报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 inode 引用释放且相关缓存回收后,设备号才能重用。" +msgstr "``mount(2)`` またはファイルシステムコンテキストで作成した tmpfs インスタンスと、起動時の ``/dev/shm`` は、ディスクのボリュームスロットを消費しません。各インスタンスは個別の匿名デバイス番号を持ち、``stat`` と mountinfo は同じ番号を報告します。バインドマウントは元のインスタンスの番号を共有します。最後のマウント参照と inode 参照が解放され、関連するキャッシュが破棄された後にのみ、番号を再利用できます。" + msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` はファイルシステムコンテキストを作成します。呼び出し元には有効な ``CAP_SYS_ADMIN`` が必要です。``fsconfig`` の ``FSCONFIG_SET_STRING`` は ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid``、``gid`` などの既存の tmpfs オプションを受け付けます。``FSCONFIG_SET_FLAG`` は ``ro`` と ``rw`` を受け付けます。``FSCONFIG_CMD_CREATE`` は設定済みオプションでファイルシステムを作成し、失敗後に再試行できます。コンテキストはオープンファイル記述に属し、dup または fork 後に共有され、最後の参照が解放されると破棄されます。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 387ad5b8..0d5aa0a0 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -110,6 +110,11 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。 +由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 +``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 +mountinfo 报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 +inode 引用释放且相关缓存回收后,设备号才能重用。 + ``fsopen("proc", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 diff --git a/block/core/device_number.c b/block/core/device_number.c index 2fc118d8..7f94667e 100644 --- a/block/core/device_number.c +++ b/block/core/device_number.c @@ -2,13 +2,10 @@ #include "storage_internal.h" #include -/** @brief Compute the same block or anonymous device identity for stat/mountinfo. - * @param volume Required stable native instance, borrowed under execution ownership. - * @return Registered block dev_t when known, otherwise volume_id+1 anonymous - * identity. Pure geometry/state query, no I/O, allocation or reference transfer. - */ +/** @copydoc storage_volume_device_number */ uint64_t storage_volume_device_number(const struct storage_volume *volume) { + if (volume->tmpfs) return tmpfs_device_number(volume->volume_id); uint64_t device = 0; /* ISO may live on a registered memory/loop-style block device as well as * an optical drive. Its held whole-device identity is authoritative. */ @@ -19,14 +16,12 @@ uint64_t storage_volume_device_number(const struct storage_volume *volume) if(volume->filesystem==STORAGE_FILESYSTEM_ISO9660 && (volume->source_disk_id&STORAGE_BLOCK_OPTICAL_BIT)) return storage_block_rdev(STORAGE_BLOCK_VOLUME_ID(volume->source_disk_id,-1)); - if (!volume->tmpfs) { - if (volume->data_partition_mount) - device = storage_block_rdev(STORAGE_BLOCK_VOLUME_ID( - volume->source_disk_id, volume->source_partition_index)); - else if (volume->filesystem == STORAGE_FILESYSTEM_FAT32) device = volume->esp_device; - else if (storage_filesystem_is_ext(volume)) device = volume->ext_device; - else if (volume->filesystem == STORAGE_FILESYSTEM_EXFAT) device = volume->exfat_device; - } + if (volume->data_partition_mount) + device = storage_block_rdev(STORAGE_BLOCK_VOLUME_ID( + volume->source_disk_id, volume->source_partition_index)); + else if (volume->filesystem == STORAGE_FILESYSTEM_FAT32) device = volume->esp_device; + else if (storage_filesystem_is_ext(volume)) device = volume->ext_device; + else if (volume->filesystem == STORAGE_FILESYSTEM_EXFAT) device = volume->exfat_device; return device ? device : (uint64_t)volume->volume_id + 1; } diff --git a/block/core/storage_core_api.h b/block/core/storage_core_api.h index 9e654c81..467702e2 100644 --- a/block/core/storage_core_api.h +++ b/block/core/storage_core_api.h @@ -161,6 +161,29 @@ int storage_read_iso_blocks(uint64_t lba, uint32_t block_count, void *buffer); * Caller holds storage execution ownership; shared volume/cache state must remain selected and live throughout the call. Uses the registered device and transport exclusion; no raw RAM backing or ownership transfer. */ int storage_read_sectors(uint64_t lba, uint32_t sector_count, void *buffer); +/** @brief Borrow a ready disk-table or runtime tmpfs instance by native ID. + * @param id Native volume ID, not an encoded device number. + * @return Ready instance or NULL. Caller holds execution ownership; no I/O. + */ +struct storage_volume *storage_mounted_volume(uint32_t id); +/** @brief Borrow the ready instance named by an already held storage node. + * @param node Borrowed node, nullable. Only tmpfs nodes select RAM-only IDs. + * @return Ready instance, including private shmem when applicable, or NULL. + * Caller holds execution ownership. No I/O admission or selection change. + */ +struct storage_volume *storage_node_volume(const struct storage_node *node); +/** @brief Reserve a runtime tmpfs ID by linking the caller's private volume. + * @param volume New heap context whose readiness is still false. + * @return Zero or -ENOSPC. Requires execution ownership. Does not allocate, + * take ownership or expose the instance to lookup before it is marked ready. + */ +int storage_register_runtime_tmpfs(struct storage_volume *volume); +/** @brief Unlink a runtime tmpfs and let later creations reuse its ID. + * @param volume Owned linked context whose mounts, inodes and caches retired, + * or whose construction failed before acquiring them. + * Execution ownership required; this does not free the context. + */ +void storage_unregister_runtime_tmpfs(struct storage_volume *volume); /** * @brief Select a live native volume while preserving the previous selection for restoration. * @param node Required borrowed identity whose volume and mount generation remain live. @@ -245,8 +268,8 @@ uint64_t fat_sector_for_cluster(uint32_t cluster); uint64_t min_u64(uint64_t a, uint64_t b); /** @brief Compute the same block or anonymous device identity for stat/mountinfo. * @param volume Required stable native instance, borrowed under execution ownership. - * @return Registered block dev_t when known, otherwise volume_id+1 anonymous - * identity. Pure geometry/state query, no I/O, allocation or reference transfer. + * @return Registered block dev_t when known, otherwise an encoded anonymous + * dev_t. Pure geometry/state query, no I/O, allocation or reference transfer. */ uint64_t storage_volume_device_number(const struct storage_volume *volume); /** diff --git a/block/core/storage_state.c b/block/core/storage_state.c index e000ebd7..ecc724e0 100644 --- a/block/core/storage_state.c +++ b/block/core/storage_state.c @@ -501,12 +501,7 @@ uint64_t min_u64(uint64_t a, uint64_t b) int storage_select_node_volume(const struct storage_node *node, struct storage_volume **old_volume) { - struct storage_volume *volume = NULL; - if (node && node->volume_id == STORAGE_SHMEM_VOLUME && - (node->flags & STORAGE_NODE_FLAG_TMPFS) && g_shmem_volume.ready) - volume = &g_shmem_volume; - else if (node && node->volume_id < STORAGE_MAX_VOLUMES && g_volumes[node->volume_id].ready) - volume = &g_volumes[node->volume_id]; + struct storage_volume *volume = storage_node_volume(node); if (!volume) { return -2; } diff --git a/block/core/storage_state_data.c b/block/core/storage_state_data.c index bf49282d..0bd2579e 100644 --- a/block/core/storage_state_data.c +++ b/block/core/storage_state_data.c @@ -1,15 +1,86 @@ /* Shared storage state, defined exactly once. block/core/storage_types.h * declares these extern so every storage module can be an independent - * translation unit instead of sharing one copy per file. This file carries - * no functions: host fixtures link it to get the shared state without also - * pulling in the block-core primitives they replace with fakes. */ + * translation unit instead of sharing one copy per file. The in-memory + * volume index has no dependency on block I/O, which host fixtures can fake. */ #include -#include "storage_types.h" +#include +#include "storage_core_api.h" struct storage_volume g_volumes[STORAGE_MAX_VOLUMES]; struct storage_volume g_shmem_volume; struct storage_volume *g_active_volume = &g_volumes[0]; +#define STORAGE_RUNTIME_TMPFS_BUCKETS 256u +static struct storage_volume *runtime_tmpfs[STORAGE_RUNTIME_TMPFS_BUCKETS]; +/* All access is execution-owned. No ID below this hint is available. */ +static uint32_t runtime_tmpfs_hint = STORAGE_RUNTIME_TMPFS_FIRST; +static uint32_t runtime_tmpfs_count; + +/** @brief Locate the registry link for a valid runtime tmpfs ID. + * @param id ID in the runtime tmpfs range. + * @return Borrowed link containing the instance or the empty insertion point. + * Execution ownership required, no I/O or allocation. + */ +static struct storage_volume **storage_runtime_tmpfs_link(uint32_t id) +{ + struct storage_volume **link = &runtime_tmpfs[id % STORAGE_RUNTIME_TMPFS_BUCKETS]; + while (*link && (*link)->volume_id != id) + link = &(*link)->runtime_next; + return link; +} + +/** @copydoc storage_register_runtime_tmpfs */ +int storage_register_runtime_tmpfs(struct storage_volume *volume) +{ + if (runtime_tmpfs_count == STORAGE_RUNTIME_TMPFS_LAST - STORAGE_RUNTIME_TMPFS_FIRST + 1) + return -ENOSPC; + for (uint32_t id = runtime_tmpfs_hint; id <= STORAGE_RUNTIME_TMPFS_LAST; ++id) { + struct storage_volume **link = storage_runtime_tmpfs_link(id); + if (*link) continue; + volume->volume_id = id; + volume->runtime_next = NULL; + *link = volume; + runtime_tmpfs_hint = id + 1; + ++runtime_tmpfs_count; + return 0; + } + return -ENOSPC; +} + +/** @copydoc storage_unregister_runtime_tmpfs */ +void storage_unregister_runtime_tmpfs(struct storage_volume *volume) +{ + uint32_t id = volume->volume_id; + struct storage_volume **link = storage_runtime_tmpfs_link(id); + if (*link != volume) return; + *link = volume->runtime_next; + --runtime_tmpfs_count; + if (id < runtime_tmpfs_hint) runtime_tmpfs_hint = id; +} + +/** @copydoc storage_mounted_volume */ +struct storage_volume *storage_mounted_volume(uint32_t id) +{ + struct storage_volume *volume = NULL; + if (id < STORAGE_MAX_VOLUMES) + volume = &g_volumes[id]; + else if (id >= STORAGE_RUNTIME_TMPFS_FIRST && id <= STORAGE_RUNTIME_TMPFS_LAST) + volume = *storage_runtime_tmpfs_link(id); + return volume && volume->ready ? volume : NULL; +} + +/** @copydoc storage_node_volume */ +struct storage_volume *storage_node_volume(const struct storage_node *node) +{ + if (!node) return NULL; + uint32_t id = node->volume_id; + if (id >= STORAGE_MAX_VOLUMES && !(node->flags & STORAGE_NODE_FLAG_TMPFS)) + return NULL; + if (id == STORAGE_SHMEM_VOLUME) + return g_shmem_volume.ready ? &g_shmem_volume : NULL; + return storage_mounted_volume(id); +} + bool storage_io_async_context; bool storage_io_write_started; uint32_t storage_task_io_owner; diff --git a/block/core/storage_sync.c b/block/core/storage_sync.c index 9560c12d..7f509a7c 100644 --- a/block/core/storage_sync.c +++ b/block/core/storage_sync.c @@ -37,23 +37,21 @@ int storage_ext4_device_flush(const struct storage_volume *volume) return ret; } -/** @brief Settle one selected native filesystem before its device cache. - * @param volume_id Existing volume slot; this is not a disk/path identity. - * @return First writeback/transport error or zero; absent/not-ready is ENODEV. - * Execution exclusion spans the operation, restoring the prior async admission - * state. Provider callbacks run outside registry locks; no mutation is replayed. - */ +/** @copydoc storage_sync_volume */ int storage_sync_volume(uint32_t volume_id) { - if (volume_id >= STORAGE_MAX_VOLUMES) return -19; - struct storage_volume *volume = &g_volumes[volume_id]; uint64_t flags; kernel_execution_lock_irqsave(&flags); + struct storage_volume *volume = storage_mounted_volume(volume_id); + if (!volume) { + kernel_execution_unlock_irqrestore(flags); + return -19; + } bool saved_async = storage_io_async_context; storage_io_async_context = false; /* Native writeback precedes the transport lock and physical cache flush. */ const struct storage_filesystem_ops *ops=volume->fs_ops; - int ret=volume->ready && ops && ops->sync ? ops->sync(volume) : 0; + int ret=ops && ops->sync ? ops->sync(volume) : 0; int transport_ret; if (volume->tmpfs && !volume->device_ref.device) transport_ret = storage_flush_volume(volume); else { @@ -67,10 +65,7 @@ int storage_sync_volume(uint32_t volume_id) return ret; } -/** @brief Sync every ready native instance, retaining the first observed error. - * @return Zero or first filesystem/transport errno. Holds execution exclusion, - * delegates per-instance ordering and never stops after an earlier failure. - */ +/** @copydoc storage_sync_all */ int storage_sync_all(void) { int result = 0; diff --git a/block/core/storage_types.h b/block/core/storage_types.h index d3800219..00fa07c6 100644 --- a/block/core/storage_types.h +++ b/block/core/storage_types.h @@ -36,6 +36,11 @@ #define STORAGE_VOLUME_TARGET_ROOT 1u #define STORAGE_VOLUME_BOOT 2u #define STORAGE_VOLUME_DYNAMIC_FIRST 3u +/* Runtime tmpfs uses major 0, minors 0x101..0x10000. Leave the low IDs to + * the disk table, pseudo filesystems and internal shmem, and higher minors + * to devpts instances. The native volume ID is one less than the minor. */ +#define STORAGE_RUNTIME_TMPFS_FIRST 0x100u +#define STORAGE_RUNTIME_TMPFS_LAST 0xffffu #define STORAGE_INSTALL_DISK_INITIAL_CAPACITY RELIEFOS_INSTALL_MAX_DISKS #define STORAGE_DIR_INDEX_ENTRIES 512u #define INSTALL_ESP_FIRST_LBA 2048ULL @@ -98,8 +103,9 @@ struct storage_volume { struct fat_mount_options fat_options; struct storage_read_cursor fat_read_cursor; uint64_t vfs_mounts; + struct storage_volume *runtime_next; /* Runtime tmpfs registry linkage. */ + uint32_t volume_id; bool vfs_managed; /* Last graph attachment owns backend/cache teardown. */ - uint8_t volume_id; uint8_t kind; uint8_t filesystem; uint8_t bus; diff --git a/block/partition/partition_mount.c b/block/partition/partition_mount.c index 77664528..a251e33d 100644 --- a/block/partition/partition_mount.c +++ b/block/partition/partition_mount.c @@ -295,7 +295,7 @@ static int storage_open_block_partition_owned(uint32_t disk_id, uint32_t partiti old_volume = g_active_volume; storage_cache_invalidate(); storage_memzero(volume, sizeof(*volume)); - volume->volume_id = (uint8_t)volume_id; + volume->volume_id = volume_id; ret=storage_volume_from_install_disk(volume,disk); if(ret)return ret; volume->mount_flags = flags; diff --git a/fs/tmpfs/core.c b/fs/tmpfs/core.c index 69a8d73e..b0dca798 100644 --- a/fs/tmpfs/core.c +++ b/fs/tmpfs/core.c @@ -124,6 +124,11 @@ void tmpfs_destroy(struct tmpfs_super *fs) tmpfs_free_inode(fs, fs->inodes[i]); kernel_free(fs); } +/** @brief Allocate one inode with the superblock's encoded anonymous device. + * @param fs Live filesystem under tmpfs serialization. @param mode Linux mode. + * @param out Receives the inode owned by fs on success. + * @return Zero or negative capacity/allocation errno; no inode published on failure. + */ static int tmpfs_alloc_inode(struct tmpfs_super *fs, uint32_t mode, struct tmpfs_inode **out) { if ((fs->max_inodes && fs->used_inodes >= fs->max_inodes) || !fs->next_ino) @@ -134,7 +139,7 @@ static int tmpfs_alloc_inode(struct tmpfs_super *fs, uint32_t mode, struct tmpfs __builtin_memset(n, 0, sizeof(*n)); n->owner=fs; n->stat = (struct linux_stat_abi){.st_ino = fs->next_ino++, - .st_dev = fs->volume + 1, + .st_dev = tmpfs_device_number(fs->volume), .st_mode = mode, .st_nlink = (mode & LINUX_S_IFMT) == LINUX_S_IFDIR ? 2 : 1, .st_blksize = TMPFS_PAGE, diff --git a/fs/vfs/mounts.c b/fs/vfs/mounts.c index cd66e2e8..c87e66fc 100644 --- a/fs/vfs/mounts.c +++ b/fs/vfs/mounts.c @@ -1,5 +1,5 @@ #include "../../block/core/storage_internal.h" -/* Read-only mount listing for /proc/mounts and /etc/mtab. */ +/** @copydoc storage_node_mount_flags */ int storage_node_mount_flags(const struct storage_node *node, uint64_t *mount_flags) { if (!node || !mount_flags) return -22; @@ -7,26 +7,20 @@ int storage_node_mount_flags(const struct storage_node *node, uint64_t *mount_fl kernel_execution_lock_irqsave(&flags); /* Reading mount policy must not acquire the unrelated asynchronous disk * transaction; mmap needs only the already pinned volume metadata. */ - const struct storage_volume *volume = node->volume_id == STORAGE_SHMEM_VOLUME && - (node->flags & STORAGE_NODE_FLAG_TMPFS) ? &g_shmem_volume : - node->volume_id < STORAGE_MAX_VOLUMES ? &g_volumes[node->volume_id] : NULL; - int ret = volume && volume->ready ? 0 : -19; + const struct storage_volume *volume = storage_node_volume(node); + int ret = volume ? 0 : -19; if (!ret) *mount_flags = volume->mount_flags; kernel_execution_unlock_irqrestore(flags); return ret; } -/** - * @brief Read a mounted filesystem's Linux stat device number under the mount lock. - * @param volume_id Mounted-volume slot, distinct from an encoded block device ID. - * @return Linux dev_t matching mountinfo and stat, or zero for an unavailable slot. - */ +/** @copydoc storage_volume_device */ uint64_t storage_volume_device(uint32_t volume_id) { uint64_t flags; kernel_execution_lock_irqsave(&flags); - uint64_t device = volume_id < STORAGE_MAX_VOLUMES && g_volumes[volume_id].ready ? - storage_volume_device_number(&g_volumes[volume_id]) : 0; + const struct storage_volume *volume = storage_mounted_volume(volume_id); + uint64_t device = volume ? storage_volume_device_number(volume) : 0; kernel_execution_unlock_irqrestore(flags); return device; } diff --git a/fs/vfs/storage_backend.h b/fs/vfs/storage_backend.h index 69301e8e..efe2ac07 100644 --- a/fs/vfs/storage_backend.h +++ b/fs/vfs/storage_backend.h @@ -12,6 +12,11 @@ bool storage_inode_volume_writers(uint32_t volume); * Caller owns the execution transaction. */ bool storage_inode_volume_swap_active(uint32_t volume); +/** @brief Drop a native mount membership after its VFS finish succeeds. + * @param volume Borrowed live context, nullable. The last managed membership + * can retire the context; the caller must not use it after the put. + * Caller holds execution ownership; no graph/module lock spans cleanup. + */ void storage_volume_mount_put(struct storage_volume *volume); /** @brief Look up one component in an already selected filesystem directory. * @param context Borrowed storage volume, pinned by its VFS mount. diff --git a/fs/vfs/storage_initial.c b/fs/vfs/storage_initial.c index fb3e6a6d..fdfdd931 100644 --- a/fs/vfs/storage_initial.c +++ b/fs/vfs/storage_initial.c @@ -47,27 +47,17 @@ static int storage_initial_procfs(void *context,struct vfs_mount **out) static int storage_initial_sysfs(void *context,struct vfs_mount **out) {(void)context;return sysfs_create_vfs_mount(out);} -/** @brief Allocate one fresh builtin boot-shm filesystem without a mount label. - * @param created Required empty output receiving the owned ready volume slot. - * @return Zero or negative allocation/quota/slot errno. Caller attaches this - * exact context at /dev/shm or destroys it after failed assembly; it never - * guesses identity by scanning legacy path labels. Exclusive boot execution - * required, no graph/module lock spans allocation; no ownership on failure. +/** @brief Create the initial sticky /dev/shm as an owned memory mount. + * @param context Unused factory context. + * @param out Receives one detached mount, empty on failure. + * @return Zero or negative constructor errno. Exclusive boot execution; + * graph rollback or final retirement releases the instance independently of + * disk slots, just as for later tmpfs mounts. */ -static int storage_initial_shm(struct storage_volume **created) +static int storage_initial_shm(void *context,struct vfs_mount **out) { - *created=NULL; - uint32_t slot=STORAGE_VOLUME_DYNAMIC_FIRST; - while(slottmpfs_source,sizeof(volume->tmpfs_source),"tmpfs"); - *created=volume;return 0; + (void)context; + return storage_new_tmpfs_mount("tmpfs",MS_NOSUID|MS_NODEV,"size=0,nr_inodes=0,mode=1777",0,0,out); } /** @brief Assemble the one initial shared namespace before kernel path users. @@ -84,7 +74,6 @@ int storage_namespace_bootstrap(void) { if(vfs_system_namespace())return -EBUSY; if(!g_volumes[0].ready)return -ENODEV; - struct storage_volume *created=NULL;int rc=storage_initial_shm(&created);if(rc)return rc; struct vfs_boot_mount mounts[STORAGE_MAX_VOLUMES+3]={ {.target="/dev",.create=storage_initial_devfs}, {.target="/proc",.create=storage_initial_procfs}, @@ -103,17 +92,6 @@ int storage_namespace_bootstrap(void) .create_directory=true,.skip_missing_target=true}; ++optical_count; } - mounts[count++]=(struct vfs_boot_mount){.target="/dev/shm",.create=storage_initial_volume,.context=created}; - rc=vfs_system_bootstrap(storage_initial_root,&g_volumes[0],mounts,count); - if(rc && created) { - /* Assembly retired every owned path before returning an error. Refuse - * destructive cleanup if a provider violated that lifetime contract. */ - if(storage_inode_volume_busy(created->volume_id)) - console_error("[vfs] retained boot shm volume=%u after failed assembly\n",created->volume_id); - else { - tmpfs_destroy(created->tmpfs);*created=(struct storage_volume){0}; - storage_cache_invalidate(); - } - } - return rc; + mounts[count++]=(struct vfs_boot_mount){.target="/dev/shm",.create=storage_initial_shm}; + return vfs_system_bootstrap(storage_initial_root,&g_volumes[0],mounts,count); } diff --git a/fs/vfs/storage_mount.c b/fs/vfs/storage_mount.c index 01151e17..1f9e3a89 100644 --- a/fs/vfs/storage_mount.c +++ b/fs/vfs/storage_mount.c @@ -3,6 +3,7 @@ #include "../../block/core/storage_internal.h" #include #include +#include #include "mount_internal.h" /** @brief Commit explicit ownership/masks before exposing a FAT attachment. @@ -29,10 +30,11 @@ int storage_mount_fat_options(struct vfs_mount *mount,const char *options) return 0; } -/** @brief Destroy an unowned initialized instance after native inode retirement. +/** @brief Destroy an unowned instance and retire its native registry identity. * @param volume Exclusive context without mount memberships; nullable. * @return Zero or negative busy/purge errno. Caller completed synchronous - * flush before final mount destruction; failed purge retains context/code. + * flush before final mount destruction (unpublished instances need none). + * Failed purge retains context/code and prevents ID reuse. * Execution ownership required, no graph/module lock spans provider cleanup. */ static int storage_volume_discard(struct storage_volume *volume) @@ -42,9 +44,18 @@ static int storage_volume_discard(struct storage_volume *volume) int rc=storage_inode_purge_volume(volume->volume_id);if(rc)return rc; if(g_active_volume==volume)g_active_volume=&g_volumes[STORAGE_VOLUME_ROOT]; storage_destroy_volume(volume); - *volume=(struct storage_volume){0};storage_cache_invalidate();return 0; + if (volume->volume_id >= STORAGE_RUNTIME_TMPFS_FIRST) { + /* The RAM backend's page and inode caches are already purged. It + * owns no disk metadata cache entries or asynchronous I/O slot. */ + storage_unregister_runtime_tmpfs(volume); + kernel_free(volume); + } else { + *volume=(struct storage_volume){0};storage_cache_invalidate(); + } + return 0; } +/** @copydoc storage_volume_mount_put */ void storage_volume_mount_put(struct storage_volume *volume) { if(!volume || !volume->vfs_mounts)return; @@ -53,15 +64,7 @@ void storage_volume_mount_put(struct storage_volume *volume) if(rc)console_error("[vfs] final backend cleanup retained volume=%u error=%d\n",volume->volume_id,rc); } -/** @brief Construct a fresh owned builtin memory filesystem and attachment. - * @param source Borrowed optional diagnostic label. @param flags Mount policy. - * @param options Borrowed optional tmpfs limits/mode options. - * @param uid New root owner UID. @param gid New root owner GID. - * @param out Required owned detached mount output, empty on failure. - * @return Zero or negative option/capacity/allocation/provider errno. Execution - * ownership required; all failed construction/description state is retired. - * The builtin memory implementation remains permanent for memfd/SysV/rootfs. - */ +/** @copydoc storage_new_tmpfs_mount */ int storage_new_tmpfs_mount(const char *source,uint64_t flags,const char *options, uint32_t uid,uint32_t gid,struct vfs_mount **out) { @@ -69,19 +72,25 @@ int storage_new_tmpfs_mount(const char *source,uint64_t flags,const char *option const uint64_t supported=MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_SYNCHRONOUS|MS_DIRSYNC| MS_NOATIME|MS_NODIRATIME|MS_RELATIME|MS_STRICTATIME|MS_LAZYTIME; if(flags&~supported)return -EOPNOTSUPP; - uint32_t slot=STORAGE_VOLUME_DYNAMIC_FIRST; - while(slotvolume_id,flags,options,uid,gid,&volume->tmpfs); + if(rc)storage_unregister_runtime_tmpfs(volume); + } + if(rc){kernel_free(volume);return rc;} + volume->ready=true; + /* The constructor owns the context until both the mount and its source + * description exist. Error puts drop pins but cannot free it underneath us. */ rc=storage_create_vfs_mount(volume,NULL,out); - if(!rc)rc=vfs_mount_describe(*out,source && source[0] ? source : "none","tmpfs",storage_volume_device_number(volume)); + if(!rc)rc=vfs_mount_set_source(*out,source && source[0] ? source : "none"); if(rc) { vfs_mount_put(*out);*out=NULL; int cleanup=storage_volume_discard(volume);if(cleanup)return cleanup; - } + } else volume->vfs_managed=true; return rc; } diff --git a/include/reliefnt/storage.h b/include/reliefnt/storage.h index 27925c2b..36e91068 100644 --- a/include/reliefnt/storage.h +++ b/include/reliefnt/storage.h @@ -107,9 +107,10 @@ struct vfs_mount; * @param uid Root inode owner filesystem UID. * @param gid Root inode owner filesystem GID. * @param out Receives one owned detached mount; empty on every failure. - * @return Zero or negative option/quota/allocation/capacity errno. No target - * pathname is stored. Final path/mount put destroys the owned backend after - * all inode pins retire. Caller holds execution ownership, no graph locks. + * @return Zero or negative option/quota/allocation/capacity errno. Runtime + * tmpfs uses a separate RAM-only ID registry, not a disk slot. No target + * pathname is stored. Final retirement destroys the backend and releases its + * ID once all mount/inode pins retire. Caller holds execution, no graph locks. */ int storage_new_tmpfs_mount(const char *source,uint64_t flags,const char *options, uint32_t uid,uint32_t gid,struct vfs_mount **out); @@ -194,7 +195,12 @@ struct storage_ext4_fiemap_extent { uint64_t logical,physical,length; uint32_t f int storage_fallocate_node(struct storage_node *node,uint32_t mode,uint64_t offset,uint64_t length); int storage_fiemap_node(const struct storage_node *,uint64_t,uint64_t, struct storage_ext4_fiemap_extent *,uint32_t,uint32_t *); -int storage_node_mount_flags(const struct storage_node *node, uint64_t *flags); +/** @brief Read native mount flags without acquiring disk I/O ownership. + * @param node Required live native node. @param mount_flags Output flags. + * @return Zero or negative input/absent-volume errno. Takes execution exclusion + * and supports both disk-table instances and private/public tmpfs. + */ +int storage_node_mount_flags(const struct storage_node *node, uint64_t *mount_flags); int storage_tmpfs_get_page(const struct storage_node *node, uint64_t offset, uint64_t *phys); /** @brief Query tmpfs inode page residency without allocating it. * @param node Borrowed backing identity. @param offset Page-aligned byte offset. @@ -224,15 +230,16 @@ int storage_tmpfs_fallocate(struct storage_node *node,uint32_t mode,uint64_t off int storage_shmem_create(uint32_t uid, uint32_t gid, struct storage_node *node, struct storage_inode_ref **reference); /** @brief Settle native filesystem writeback before its registered device flush. - * @param volume_id Existing native volume slot. + * @param volume_id Existing disk-table or runtime tmpfs volume ID. * @return Zero or first writeback/transport errno; absent/not-ready is ENODEV. * Acquires execution exclusion, saves/restores async state and pins provider * code through callbacks without holding any filesystem/device registry lock. */ int storage_sync_volume(uint32_t volume_id); -/** @brief Sync every ready volume while retaining the first observed error. +/** @brief Sync the ready disk-table volumes, retaining the first error. * @return Zero or first native writeback/transport errno; later instances are * still attempted. Acquires execution exclusion, delegates per-volume ordering. + * Runtime tmpfs has no persistent writeback; namespace sync uses actual mounts. */ int storage_sync_all(void); int storage_sync_disk(uint32_t disk_id); @@ -307,8 +314,8 @@ struct storage_read_cursor { /** * @brief Read the Linux device identity of a mounted filesystem under the mount lock. - * @param volume_id Mounted-volume slot, distinct from a block device's encoded ID. - * @return Linux dev_t matching mountinfo and stat, or zero for an unavailable slot. + * @param volume_id Disk-table or runtime tmpfs volume ID, not a block dev_t. + * @return Linux dev_t matching mountinfo and stat, or zero for an unavailable ID. */ uint64_t storage_volume_device(uint32_t volume_id); diff --git a/include/reliefnt/tmpfs.h b/include/reliefnt/tmpfs.h index 3d990ddc..e0645032 100644 --- a/include/reliefnt/tmpfs.h +++ b/include/reliefnt/tmpfs.h @@ -1,7 +1,17 @@ #ifndef RELIEFNT_TMPFS_H #define RELIEFNT_TMPFS_H +#include #include +/** @brief Encode the major-zero device identity shared by tmpfs stat and VFS. + * @param volume Native tmpfs volume ID; its anonymous minor is volume plus 1. + * @return Linux dev_t, or zero for an unrepresentable volume ID. No I/O or locking. + */ +static inline uint64_t tmpfs_device_number(uint32_t volume) +{ + return volume < 0xfffffu ? block_device_make_number(0, volume + 1) : 0; +} + /* Callers serialize these operations with the storage execution lock. */ struct tmpfs_super; /** @brief Observe this instance's name/metadata epoch, including direct users. diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 1905835d..52f0182f 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -1662,8 +1662,7 @@ static void initial_root_access_policy(void) } } vfs_path_put(&file);vfs_path_put(&root);assert(!vfs_namespace_destroy(ns)); - assert(g_volumes[3].ready && g_volumes[3].tmpfs && !storage_inode_volume_busy(3)); - tmpfs_destroy(g_volumes[3].tmpfs);g_volumes[3]=(struct storage_volume){0}; + assert(!storage_mounted_volume(STORAGE_RUNTIME_TMPFS_FIRST)); } g_volumes[0].mount_flags=saved_flags;g_volumes[0].fs_ops=saved_ops; g_volumes[0].read_only_reason=saved_readonly;test_wall_seconds=saved_clock; @@ -1671,6 +1670,9 @@ static void initial_root_access_policy(void) puts("PASS boot root default relatime, explicit noatime/strictatime, statfs, cross-second reads and unchanged volume flags"); } +/** @brief Verify boot assembly can mount and roll back shm with every disk slot occupied. + * @param rootfs Borrowed base tmpfs for the boot mountpoints. + */ static void production_initial_namespace(struct tmpfs_super *rootfs) { assert(!tmpfs_create(rootfs,"/boot",LINUX_S_IFDIR|0755,NULL,NULL)); @@ -1682,10 +1684,14 @@ static void production_initial_namespace(struct tmpfs_super *rootfs) struct tmpfs_super *fs=NULL;assert(!tmpfs_new(slot,0,"size=0,nr_inodes=0",0,0,&fs)); g_volumes[slot]=(struct storage_volume){.volume_id=slot,.kind=STORAGE_VOLUME_ANONYMOUS,.ready=true,.filesystem=STORAGE_FILESYSTEM_TMPFS,.fs_ops=&storage_tmpfs_ops,.tmpfs=fs}; } + /* Occupied non-optical disk slots are not themselves boot attachments. */ + for(unsigned slot=STORAGE_VOLUME_DYNAMIC_FIRST;slotvolume_id==2);vfs_path_put(&node); assert(!vfs_path_lookup(ns,&root,&root,"/dev/shm",0,&node)); assert(vfs_path_node(&node)->flags&STORAGE_NODE_FLAG_TMPFS); - assert(vfs_path_context(&node)==&g_volumes[3]); + uint32_t shm_id=vfs_path_node(&node)->volume_id; + assert(shm_id>=STORAGE_RUNTIME_TMPFS_FIRST && + vfs_path_context(&node)==storage_mounted_volume(shm_id)); struct reliefos_permissions mode;assert(!vfs_path_permissions(&node,&mode,false)); assert(mode.mode==01777 && !mode.uid && !mode.gid); create_held_file(&node,true);vfs_path_put(&node); @@ -1727,15 +1735,18 @@ static void production_initial_namespace(struct tmpfs_super *rootfs) g_volumes[2].data_partition_mount=false;g_volumes[2].source_disk_id=0;g_volumes[2].source_partition_index=0; vfs_path_put(&mounted);vfs_path_put(&destination);vfs_path_put(&root); assert(!vfs_namespace_destroy(ns)); - assert(g_volumes[3].ready && g_volumes[3].tmpfs && !storage_inode_volume_busy(3)); - tmpfs_destroy(g_volumes[3].tmpfs);g_volumes[3]=(struct storage_volume){0};success=true; + assert(!storage_mounted_volume(shm_id));success=true; } - assert(!g_volumes[3].ready && !g_volumes[3].tmpfs); + assert(!storage_mounted_volume(STORAGE_RUNTIME_TMPFS_FIRST)); + for(unsigned slot=STORAGE_VOLUME_DYNAMIC_FIRST;slotmount_flags==original_flags); assert(vfs_path_mount_flags(&existing_root)==existing_policy);vfs_path_put(&existing_root); vfs_path_put(&file);vfs_path_put(&root);assert(!vfs_namespace_destroy(ns)); - for(unsigned slot=3;slot<=5;++slot) { + assert(!storage_mounted_volume(STORAGE_RUNTIME_TMPFS_FIRST)); + for(unsigned slot=4;slot<=5;++slot) { assert(g_volumes[slot].ready && g_volumes[slot].tmpfs && !storage_inode_volume_busy(slot)); tmpfs_destroy(g_volumes[slot].tmpfs);g_volumes[slot]=(struct storage_volume){0}; } @@ -2310,6 +2322,59 @@ static void device_mount_objects(struct vfs_namespace *ns,const struct vfs_path puts("PASS real devfs mount: independent attachment/flag, null/input/shm nodes, directory iteration and MS_MOVE"); } +/** @brief Keep many isolated tmpfs backends alive without borrowing disk slots. */ +static void runtime_tmpfs_capacity(void) +{ + enum { count = STORAGE_MAX_VOLUMES + 12 }; + struct vfs_path roots[count] = {0}, files[count] = {0}; + uint64_t devices[count] = {0}; + unsigned disk_slots = 0; + for (unsigned i = STORAGE_VOLUME_DYNAMIC_FIRST; i < STORAGE_MAX_VOLUMES; ++i) + disk_slots += g_volumes[i].ready; + for (unsigned i = 0; i < count; ++i) { + struct vfs_mount *mount = NULL; + assert(!storage_new_tmpfs_mount("private", MS_NOSUID, NULL, 0, 0, &mount)); + assert(!vfs_mount_detached_root(mount, &roots[i])); + struct linux_stat_abi st; + assert(!vfs_path_stat(&roots[i], &st)); + assert(st.st_dev && st.st_dev == mount->device && !(st.st_dev & 0xfff00u)); + devices[i] = st.st_dev; + for (unsigned j = 0; j < i; ++j) + assert(devices[i] != devices[j]); + vfs_mount_put(mount); + + struct reliefos_permissions mode = {0600, 0, 0}; + assert(!vfs_path_new_file(&roots[i], "same-name", &mode, &files[i])); + uint32_t bytes = 0; unsigned char value = i; + assert(!vfs_path_write(&files[i], 0, &value, 1, &bytes) && bytes == 1); + } + unsigned used = 0; + for (unsigned i = STORAGE_VOLUME_DYNAMIC_FIRST; i < STORAGE_MAX_VOLUMES; ++i) + used += g_volumes[i].ready; + assert(disk_slots == used); + for (unsigned i = 0; i < count; ++i) { + const struct storage_node *node = vfs_path_node(&files[i]); + uint64_t flags = 0; + assert(!storage_node_mount_flags(node, &flags) && (flags & MS_NOSUID)); + assert(storage_volume_device(node->volume_id) == devices[i]); + assert(!vfs_path_sync(&files[i], true, false)); + + unsigned char value = 0; uint32_t bytes = 0; + assert(!vfs_path_read(&files[i], 0, &value, 1, &bytes) && bytes == 1 && value == i); + struct linux_stat_abi st; + assert(!vfs_path_stat(&files[i], &st) && st.st_dev == devices[i]); + uint32_t id = node->volume_id; + vfs_path_put(&files[i]); + vfs_path_put(&roots[i]); + assert(!storage_volume_device(id) && storage_sync_volume(id) == -ENODEV); + } + struct vfs_mount *replacement = NULL; + assert(!storage_new_tmpfs_mount("replacement", 0, NULL, 0, 0, &replacement)); + assert(replacement->device == devices[0]); /* the now-retired ID is reusable */ + vfs_mount_put(replacement); + puts("PASS runtime tmpfs capacity: independent identities and data, disk slots untouched, final release"); +} + /* Runtime backends belong to graph attachments. No target pathname is stored * in the volume, and a bare inode writer/root pin must also prevent teardown. */ static void runtime_mount_objects(struct vfs_namespace *ns,const struct vfs_path *root,struct tmpfs_super *fs) @@ -2332,7 +2397,7 @@ static void runtime_mount_objects(struct vfs_namespace *ns,const struct vfs_path if(rc)assert(rc==-ENOMEM && !mount); else {assert(mount);vfs_mount_put(mount);mount=NULL;} unsigned after=0;for(unsigned i=0;ivolume_id; assert(volume->ready); /* final held path still owns the detached backend */ - vfs_path_put(&mounted);assert(!volume->ready); + vfs_path_put(&mounted);assert(!storage_mounted_volume(id)); vfs_path_put(&point);vfs_path_put(&destination); puts("PASS owned runtime tmpfs mounts: allocation rollback, root credentials, held writer/raw-inode busy checks, remount, MS_MOVE and final backend release"); } @@ -2389,6 +2455,7 @@ static void runtime_mount_objects(struct vfs_namespace *ns,const struct vfs_path /* Test the real storage finish/discard path, not only a synthetic backend's * callback. A detached final mount must not abandon a retained raw inode or * lose the backing context after a controller flush failure. */ +/** @brief Keep a runtime ID reserved until VFS finish and the final put succeed. */ static void runtime_failed_teardown(void) { for(unsigned mode=0;mode<3;++mode) { @@ -2421,7 +2488,7 @@ static void runtime_failed_teardown(void) assert(vfs_reclaim_mounts(8)==1); if(mode==1)assert(retirement_flush_calls==3); } - assert(!volume->ready && !volume->vfs_mounts && !vfs_reclaim_mounts(8)); + assert(!storage_mounted_volume(slot) && !vfs_reclaim_mounts(8)); if(mode==1)assert(!unregister_block_device(&retirement_registration)); } puts("PASS actual backend deferred teardown: raw-inode wait, failed device flush, no allocation, slot retention, revived membership and final retry"); @@ -2434,7 +2501,7 @@ static void runtime_detached_mount(struct vfs_namespace *ns,const struct vfs_pat struct vfs_path detached={0},file={0},found={0},point={0},mounted={0}; assert(!storage_new_tmpfs_mount("detached",MS_NOSUID, "size=8192,nr_inodes=16,mode=0700",1000,1000,&mount)); - struct storage_volume *volume=mount->context; + uint32_t id=mount->root->node.volume_id; struct vfs_path private_root={mount,mount->root}; assert(vfs_path_lookup(ns,root,&private_root,".",0,&found)==-EXDEV); assert(!vfs_mount_detached_root(mount,&detached)); @@ -2474,7 +2541,7 @@ static void runtime_detached_mount(struct vfs_namespace *ns,const struct vfs_pat vfs_path_put(&file);vfs_path_put(&detached); assert(!vfs_mount_unmount(ns,&mounted)); vfs_path_put(&mounted);vfs_path_put(&point); - assert(!volume->ready); + assert(!storage_mounted_volume(id)); puts("PASS detached tmpfs access: reconfigure rollback, failed attachment, publication and final release"); } @@ -2489,6 +2556,7 @@ static void runtime_attachment_policies(struct vfs_namespace *ns,const struct vf struct vfs_mount *first=NULL,*second=NULL; assert(!storage_new_tmpfs_mount("policy",MS_NOSUID|MS_NODEV|MS_RELATIME,NULL,1700,2700,&first)); struct storage_volume *volume=first->context; + uint32_t id=volume->volume_id; assert(!storage_create_vfs_mount(volume,NULL,&second)); assert(!vfs_mount_set_flags(second,MS_NOEXEC|MS_NOATIME)); assert(!vfs_mount_attach(ns,first,&a) && !vfs_mount_attach(ns,second,&b)); @@ -2539,7 +2607,7 @@ static void runtime_attachment_policies(struct vfs_namespace *ns,const struct vf assert(!vfs_path_read(&alias,0,bytes,sizeof(bytes),&done) && done==4 && !memcmp(bytes,"kept",4)); assert(vfs_path_mount_flags(&two)==(MS_NOEXEC|MS_NOATIME)); vfs_path_put(&alias);assert(!vfs_mount_unmount(ns,&two));vfs_path_put(&two); - assert(!volume->ready);vfs_path_put(&a);vfs_path_put(&b); + assert(!storage_mounted_volume(id));vfs_path_put(&a);vfs_path_put(&b); puts("PASS independent attachment policy/statfs/atime with shared readonly backing and last-mount lifetime"); } @@ -3270,6 +3338,7 @@ static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pat assert(!scoped_mount_call(ns,&actor,LINUX_SYS_MOUNT,source,target,type,MS_NOSUID|MS_NODEV|MS_SILENT|MS_MGC_VAL,options)); struct vfs_path mounted={0};assert(!vfs_path_lookup(ns,root,root,user.target,0,&mounted)); struct storage_volume *volume=vfs_path_context(&mounted); + uint32_t id=volume->volume_id; assert(volume->tmpfs); assert((vfs_path_mount_flags(&mounted)&(MS_RELATIME|MS_NOSUID|MS_NODEV))==(MS_RELATIME|MS_NOSUID|MS_NODEV)); strcpy(user.options,"data=ordered"); @@ -3308,7 +3377,7 @@ static void runtime_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pat strcpy(user.source,"/syscall-link"); assert(scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,source,UMOUNT_NOFOLLOW,0,0,0)==-EINVAL); assert(!scoped_mount_call(ns,&actor,LINUX_SYS_UMOUNT2,source,0,0,0,0)); - assert(!volume->ready && !actor.lookup_scope.armed); + assert(!storage_mounted_volume(id) && !actor.lookup_scope.armed); strcpy(user.source,"/syscall-source"); strcpy(user.type,"ext3"); strcpy(user.options,"data=ordered"); @@ -4175,12 +4244,14 @@ static void runtime_lazy_unmount(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_mount_attach(ns,mount,&cover));vfs_mount_put(mount); assert(!vfs_path_lookup(ns,root,root,"/lazy-root",0,&top)); struct storage_volume *outer=vfs_path_context(&top); + uint32_t outer_id=outer->volume_id; assert(!vfs_path_create_node(&top,"child",LINUX_S_IFDIR,&mode,NULL,&point)); assert(!storage_new_tmpfs_mount("lazy-child",0,NULL,1000,1000,&mount)); assert(!vfs_mount_attach(ns,mount,&point));vfs_mount_put(mount); vfs_path_put(&point); assert(!vfs_path_lookup(ns,root,&top,"child",0,&child)); struct storage_volume *inner=vfs_path_context(&child); + uint32_t inner_id=inner->volume_id; struct vfs_path source={0}; assert(!vfs_path_create_node(&child,"view",LINUX_S_IFDIR,&mode,NULL,&source)); assert(!vfs_path_create_node(&child,"alias",LINUX_S_IFDIR,&mode,NULL,&point)); @@ -4238,7 +4309,7 @@ static void runtime_lazy_unmount(struct vfs_namespace *ns,const struct vfs_path for(unsigned attempt=0;attempt<3 && vfs_reclaim_pending();++attempt) assert(vfs_reclaim_mounts(8)); assert(!vfs_reclaim_pending()); - assert(!outer->ready && !inner->ready); + assert(!storage_mounted_volume(outer_id) && !storage_mounted_volume(inner_id)); lookup_user_base=lookup_user_bytes=0; puts("PASS lazy unmount: immediate subtree removal, held paths, mount-root boundary and deferred cleanup"); } @@ -4545,6 +4616,7 @@ int main(int argc,char **argv) assert(!tmpfs_unlink(fs,"/dynamic-codec",false));g_volumes[0].fs_ops=audited; assert(root.mount->ops->lookup_generation(root.mount->context)); runtime_boot_objects(&ns,&root,fs); + runtime_tmpfs_capacity(); runtime_mount_objects(&ns,&root,fs); runtime_failed_teardown(); runtime_detached_mount(&ns,&root); @@ -4629,7 +4701,7 @@ int main(int argc,char **argv) if(argc==2)iso_filesystem(argv[1]); if(argc==4)cluster_filesystem(argv[1],argv[2],!strcmp(argv[3],"exfat")); /* devtmpfs retains a private backing reference for the kernel lifetime. - * Exercise it after fixtures which deliberately recycle all dynamic slots. */ + * Run it after the tests which assert full runtime tmpfs retirement. */ assert(!tmpfs_new(0,0,"size=0,nr_inodes=0",0,0,&fs)); g_volumes[0]=(struct storage_volume){.volume_id=0,.kind=STORAGE_VOLUME_ANONYMOUS, .ready=true,.filesystem=STORAGE_FILESYSTEM_TMPFS,.fs_ops=&storage_tmpfs_ops,.tmpfs=fs}; From cedfb06bcd72a272cd9a7b18e18c6f0226c65d75 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 18:53:04 +0800 Subject: [PATCH 39/97] fix(fd): expose O_PATH status through F_GETFL --- .../LC_MESSAGES/userspace-api/descriptors.po | 3 ++ .../LC_MESSAGES/userspace-api/descriptors.po | 3 ++ Documentation/userspace-api/descriptors.rst | 4 +++ kernel/syscall/fd/legacy_descriptors.c | 8 +++++ tools/tests/descriptor_table_test.c | 33 +++++++++++++++++++ 5 files changed, 51 insertions(+) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index ffecb996..395e9143 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -65,6 +65,9 @@ msgstr "" msgid "授权与身份" msgstr "Authorization and Identity" +msgid "``fcntl(F_GETFL)`` 返回 ``O_PATH`` 以及打开时保留的 ``O_DIRECTORY`` 和 ``O_NOFOLLOW``,不包含由 ``F_GETFD`` 查询的 close-on-exec 标志。复制描述符 保留同一打开状态;``F_SETFL`` 和 ``ioctl`` 对 ``O_PATH`` 描述符返回 ``EBADF``。" +msgstr "``fcntl(F_GETFL)`` returns ``O_PATH`` and any ``O_DIRECTORY`` and ``O_NOFOLLOW`` flags retained at open time. It does not include close-on-exec, which is reported by ``F_GETFD``. A duplicate descriptor preserves the same open status; ``F_SETFL`` and ``ioctl`` return ``EBADF`` on an ``O_PATH`` descriptor." + msgid "" "打开时执行 DAC,读写检查描述符访问模式,O_PATH 不能进行普通读写。 重读分区表 BLKRRPART 要求 " "CAP_SYS_ADMIN,不依赖旧桌面角色。 utimensat(fd, NULL, times, 0) 更新该 fd 持有的 " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index 6c4e8098..1cca2a2f 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -59,6 +59,9 @@ msgstr "" msgid "授权与身份" msgstr "認可と同一性" +msgid "``fcntl(F_GETFL)`` 返回 ``O_PATH`` 以及打开时保留的 ``O_DIRECTORY`` 和 ``O_NOFOLLOW``,不包含由 ``F_GETFD`` 查询的 close-on-exec 标志。复制描述符 保留同一打开状态;``F_SETFL`` 和 ``ioctl`` 对 ``O_PATH`` 描述符返回 ``EBADF``。" +msgstr "``fcntl(F_GETFL)`` は ``O_PATH`` と、オープン時に保持された ``O_DIRECTORY`` および ``O_NOFOLLOW`` を返します。``F_GETFD`` で照会する close-on-exec フラグは含みません。複製したディスクリプターは同じオープン状態を維持し、``O_PATH`` ディスクリプターに対する ``F_SETFL`` と ``ioctl`` は ``EBADF`` を返します。" + msgid "" "打开时执行 DAC,读写检查描述符访问模式,O_PATH 不能进行普通读写。 重读分区表 BLKRRPART 要求 " "CAP_SYS_ADMIN,不依赖旧桌面角色。 utimensat(fd, NULL, times, 0) 更新该 fd 持有的 " diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index de992611..a9f9b749 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -29,6 +29,10 @@ POSIX 元数据。共享实例已有挂载时,不同选项返回 ``EBUSY``。 utimensat(fd, NULL, times, 0) 更新该 fd 持有的 inode,改名或 unlink 不把它 重定向到另一个同名文件;O_PATH 应拒绝。 +``fcntl(F_GETFL)`` 返回 ``O_PATH`` 以及打开时保留的 ``O_DIRECTORY`` 和 +``O_NOFOLLOW``,不包含由 ``F_GETFD`` 查询的 close-on-exec 标志。复制描述符 +保留同一打开状态;``F_SETFL`` 和 ``ioctl`` 对 ``O_PATH`` 描述符返回 ``EBADF``。 + Linux 请求值 ============ diff --git a/kernel/syscall/fd/legacy_descriptors.c b/kernel/syscall/fd/legacy_descriptors.c index 0e0df577..72359ff1 100644 --- a/kernel/syscall/fd/legacy_descriptors.c +++ b/kernel/syscall/fd/legacy_descriptors.c @@ -16,6 +16,9 @@ * @param a5 Sixth native ABI argument. * @return Original result, negative errno, or internal blocking/retry status. * @note The caller retains the kernel execution transaction and descriptor pins. + * F_GETFL on a path-only descriptor translates the private kind to O_PATH. + * Duplication and descriptor flag operations still work; status changes and + * other commands requiring an open file description reject O_PATH with EBADF. */ int64_t syscall_legacy_descriptors(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) { @@ -136,6 +139,11 @@ int64_t syscall_legacy_descriptors(uint64_t number, uint64_t a0, uint64_t a1, ui int ret = task_fd_set_descriptor_flags(task, (int)a0, (uint32_t)a2); return ret < 0 ? ret : 0; } + if (file_fd && (file_fd->flags & TASK_FILE_FLAG_PATH)) { + if (a1 == RELIEFOS_F_GETFL) + return LINUX_O_PATH | (file_fd->flags & (LINUX_O_DIRECTORY | LINUX_O_NOFOLLOW)); + return -RELIEFOS_EBADF; + } if (!file_fd && !pty_fd && task_pty_stream_for_fd(task, (int)a0) < 0) { return -RELIEFOS_EBADF; } diff --git a/tools/tests/descriptor_table_test.c b/tools/tests/descriptor_table_test.c index b3d62a1b..914a16bf 100644 --- a/tools/tests/descriptor_table_test.c +++ b/tools/tests/descriptor_table_test.c @@ -1329,6 +1329,37 @@ static void writer_namespace_close(struct vfs_namespace *ns,struct task *task,st vfs_path_put(&task->fs_paths.root);vfs_path_put(&task->fs_paths.cwd);vfs_path_put(root); assert(!vfs_namespace_destroy(ns) && !writer_path_pins); } + +/** @brief Let a caller detect O_PATH via F_GETFL without admitting I/O. */ +static void test_path_status_flags(void) +{ + struct task *task=calloc(1,sizeof(*task));assert(task); + task->limits.nofile.rlim_cur=64;descriptor_dispatch_task=task; + struct vfs_namespace ns={0};struct vfs_path root={0}; + writer_namespace_open(&ns,task,&root); + const uint32_t status=LINUX_O_PATH|LINUX_O_DIRECTORY|LINUX_O_NOFOLLOW; + const uint32_t input=status|LINUX_O_CLOEXEC|LINUX_O_RDWR|LINUX_O_TRUNC|LINUX_O_NONBLOCK; + int fd=syscall_open_object(&ns,task,LINUX_AT_FDCWD,(uintptr_t)"/",input,0); + assert(fd>=0 && (task_file_for_fd(task,fd)->flags&TASK_FILE_FLAG_PATH)); + assert(syscall_legacy_descriptors(LINUX_SYS_FCNTL,fd,LINUX_F_GETFL,0,0,0,0)==status); + assert(syscall_legacy_descriptors(LINUX_SYS_FCNTL,fd,LINUX_F_GETFD,0,0,0,0)==LINUX_FD_CLOEXEC); + int alias=syscall_legacy_descriptors(LINUX_SYS_FCNTL,fd,LINUX_F_DUPFD,0,0,0,0); + assert(alias>=0 && alias!=fd && !task_fd_descriptor_flags(task,alias)); + task_discard_file_fd(task,fd); + assert(syscall_legacy_descriptors(LINUX_SYS_FCNTL,alias,LINUX_F_GETFL,0,0,0,0)==status); + assert(syscall_legacy_descriptors(LINUX_SYS_FCNTL,alias,LINUX_F_SETFL,LINUX_O_NONBLOCK,0,0,0)==-EBADF); + assert(syscall_ioctl_resolve_fd(task,alias)==-EBADF); + task_discard_file_fd(task,alias); + + fd=syscall_open_object(&ns,task,LINUX_AT_FDCWD,(uintptr_t)"/",LINUX_O_PATH,0); + assert(fd>=0 && !task_fd_descriptor_flags(task,fd)); + assert(syscall_legacy_descriptors(LINUX_SYS_FCNTL,fd,LINUX_F_GETFL,0,0,0,0)==LINUX_O_PATH); + task_discard_file_fd(task,fd); + writer_namespace_close(&ns,task,&root); + sched_task_file_release(task);descriptor_dispatch_task=NULL;free(task); + puts("PASS O_PATH status is observable via F_GETFL, survives dup, and denies F_SETFL/ioctl"); +} + static void test_regular_inode_writer_ofd_lifetime(void) { struct task *task=calloc(1,sizeof(*task));assert(task); @@ -1956,6 +1987,7 @@ static void test_epoll_open_file_description_lifetime(void) assert(epfd == 4); target->flags = TASK_FILE_FLAG_EPOLL | RELIEFOS_O_RDWR; target->aux = (uint64_t)(uintptr_t)epoll; + assert(syscall_legacy_descriptors(LINUX_SYS_FCNTL,epfd,LINUX_F_GETFL,0,0,0,0)==LINUX_O_RDWR); int duplicate = task_duplicate_file_fd(task, original, 5, 0); assert(duplicate == 5 && task_file_for_fd(task, duplicate) == task_file_for_fd(task, original)); @@ -3153,6 +3185,7 @@ int main(void) test_finit_preflight_before_allocation(); test_finit_preflight_retires_other_io(); test_regular_inode_writer_ofd_lifetime(); + test_path_status_flags(); test_nonblocking_drm_read_dispatch(); test_audio_write_batch(); kernel_objects_init(); From 9e6558cf1cf69749ed99375d27f8bef0abdfd4ae Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 19:01:45 +0800 Subject: [PATCH 40/97] feat(netlink): deliver userspace udev notifications --- .../userspace-api/device-filesystems.po | 9 + .../userspace-api/device-filesystems.po | 9 + .../userspace-api/device-filesystems.rst | 14 ++ include/reliefnt/netlink.h | 13 +- kernel/syscall/ipc/socket.c | 21 ++- net/socket/netlink.c | 174 +++++++++++++----- tools/tests/ipv6_control_test.c | 116 +++++++++++- tools/tests/socket_batch_unix_test.c | 4 +- 8 files changed, 294 insertions(+), 66 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 2c5bb45d..8cd3b59e 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -94,6 +94,15 @@ msgstr "" "retroactively acquire a limit, and existing contents must fit under any " "new limit, matching Linux shmem reconfiguration constraints." +msgid "设备事件" +msgstr "Device events" + +msgid "``AF_NETLINK`` 的 ``NETLINK_KOBJECT_UEVENT`` 使用组 1 发送内核设备通知, 使用组 2 接收 udev 处理后的通知。绑定组掩码或增减组成员资格不需要额外权限。 组 2 的发送和指定非零端口的单播需要有效的 ``CAP_NET_ADMIN``;用户态不能 写入组 1,亦不能通过端口 0 注入内核事件。发送侧需要显式指定目标。" +msgstr "``NETLINK_KOBJECT_UEVENT`` on ``AF_NETLINK`` uses group 1 for kernel device notifications and group 2 for notifications processed by udev. Binding a group mask or joining and leaving groups requires no additional privilege. Sending to group 2 or unicasting to a nonzero port requires effective ``CAP_NET_ADMIN``. Userspace cannot send to group 1 or inject kernel events through port 0. The sender must specify an explicit destination." + +msgid "接收方的 ``sockaddr_nl`` 报告发送端口和多播组掩码,单播的组掩码为 0。 开启 ``SO_PASSCRED`` 后,``recvmsg`` 返回入队时的发送进程 ID、真实 UID 和 GID;内核事件的端口及凭据均为 0。经典 BPF 过滤在入队前执行。数据报最多 8192 字节;多播接收方超出队列容量时报告 ``ENOBUFS``,单播发送方遇到满 队列时收到 ``EAGAIN``。" +msgstr "The receiver's ``sockaddr_nl`` reports the sender's port and the multicast group mask, which is zero for unicast. With ``SO_PASSCRED`` enabled, ``recvmsg`` returns the sender's process ID, real UID, and real GID captured at enqueue time. Kernel events carry zero for the port and all credentials. Classic BPF filtering runs before enqueue. Datagrams are limited to 8192 bytes. Multicast receivers report ``ENOBUFS`` when their queue overflows, and unicast senders receive ``EAGAIN`` when the destination queue is full." + msgid "devpts" msgstr "devpts" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index c443c2e3..5dda2ebc 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -86,6 +86,15 @@ msgstr "" "の初回作成時のみです。既存の無制限インスタンスに後から上限を設けることはできず、既存の内容は新しい上限内に収まる必要があります。これは Linux" " shmem の再設定時の制約と同じです。" +msgid "设备事件" +msgstr "デバイスイベント" + +msgid "``AF_NETLINK`` 的 ``NETLINK_KOBJECT_UEVENT`` 使用组 1 发送内核设备通知, 使用组 2 接收 udev 处理后的通知。绑定组掩码或增减组成员资格不需要额外权限。 组 2 的发送和指定非零端口的单播需要有效的 ``CAP_NET_ADMIN``;用户态不能 写入组 1,亦不能通过端口 0 注入内核事件。发送侧需要显式指定目标。" +msgstr "``AF_NETLINK`` の ``NETLINK_KOBJECT_UEVENT`` は、カーネルのデバイス通知にグループ 1、udev が処理した通知にグループ 2 を使用します。グループマスクを指定したバインドやグループへの参加・脱退に追加権限は不要です。グループ 2 への送信や 0 以外のポートへのユニキャストには有効な ``CAP_NET_ADMIN`` が必要です。ユーザー空間からグループ 1 への送信や、ポート 0 を介したカーネルイベントの注入はできません。送信先は明示的に指定します。" + +msgid "接收方的 ``sockaddr_nl`` 报告发送端口和多播组掩码,单播的组掩码为 0。 开启 ``SO_PASSCRED`` 后,``recvmsg`` 返回入队时的发送进程 ID、真实 UID 和 GID;内核事件的端口及凭据均为 0。经典 BPF 过滤在入队前执行。数据报最多 8192 字节;多播接收方超出队列容量时报告 ``ENOBUFS``,单播发送方遇到满 队列时收到 ``EAGAIN``。" +msgstr "受信側の ``sockaddr_nl`` は送信元ポートとマルチキャストのグループマスクを返します。ユニキャストではマスクは 0 です。``SO_PASSCRED`` を有効にすると、``recvmsg`` はキュー投入時の送信プロセス ID、実 UID、実 GID を返します。カーネルイベントのポートと資格情報はすべて 0 です。クラシック BPF のフィルターはキュー投入前に適用されます。データグラムの上限は 8192 バイトです。マルチキャストで受信キューがあふれると受信側に ``ENOBUFS`` が、ユニキャストで宛先キューが満杯の場合は送信側に ``EAGAIN`` が返ります。" + msgid "devpts" msgstr "devpts" diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index c51ade9c..175f2eeb 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -42,6 +42,20 @@ devtmpfs 挂载选项 ``gid`` 只在首次创建 tmpfs 时设置根 inode。已有无限容量的实例拒绝追溯增加 容量上限,已有内容也必须容纳在新上限内,与 Linux shmem 的重新配置约束一致。 +设备事件 +======== + +``AF_NETLINK`` 的 ``NETLINK_KOBJECT_UEVENT`` 使用组 1 发送内核设备通知, +使用组 2 接收 udev 处理后的通知。绑定组掩码或增减组成员资格不需要额外权限。 +组 2 的发送和指定非零端口的单播需要有效的 ``CAP_NET_ADMIN``;用户态不能 +写入组 1,亦不能通过端口 0 注入内核事件。发送侧需要显式指定目标。 + +接收方的 ``sockaddr_nl`` 报告发送端口和多播组掩码,单播的组掩码为 0。 +开启 ``SO_PASSCRED`` 后,``recvmsg`` 返回入队时的发送进程 ID、真实 UID 和 +GID;内核事件的端口及凭据均为 0。经典 BPF 过滤在入队前执行。数据报最多 +8192 字节;多播接收方超出队列容量时报告 ``ENOBUFS``,单播发送方遇到满 +队列时收到 ``EAGAIN``。 + devpts ====== diff --git a/include/reliefnt/netlink.h b/include/reliefnt/netlink.h index 70e3e629..f520cbf8 100644 --- a/include/reliefnt/netlink.h +++ b/include/reliefnt/netlink.h @@ -6,13 +6,13 @@ struct task; struct task_file; #define TASK_FILE_KIND_NETLINK 4u -/** @brief Handle a route-netlink socket operation under execution ownership. +/** @brief Handle a netlink socket operation under execution ownership. * @param number Native syscall number. @param a0 First argument. @param a1 Second argument. * @param a2 Third argument. @param a3 Fourth argument. @param a4 Fifth argument. * @param a5 Sixth argument. @return Syscall result or negative errno. */ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, uint64_t a3,uint64_t a4,uint64_t a5); -/** @brief Process a kernel-bound netlink datagram from a pinned OFD. +/** @brief Send a route request or privileged userspace uevent from a pinned OFD. * @param file Retained OFD. @param data Validated bytes. @param length Byte count. * @param flags Linux flags. @param address Optional user destination. @param address_length * Destination size. @return Bytes accepted or negative errno. */ @@ -27,10 +27,13 @@ int task_netlink_recv(struct task_file *file,void *data,uint32_t length,uint32_t /** @brief Receive into caller-owned staging storage without retaining user pointers. * @param file Retained OFD. @param data Kernel output. @param length Capacity. * @param flags Linux flags. @param source Optional kernel source output. - * @param source_length Output source length. @return Bytes, errno or blocked marker. */ + * @param source_length Output source length when source is requested. + * @param credentials Optional output for the datagram's sender credentials. + * @return Bytes, negative errno or blocked marker. */ int task_netlink_recv_staged(struct task_file *file,void *data,uint32_t length,uint32_t flags, - void *source,uint32_t *source_length); -/* Kernel-originated datagrams carry pid, uid and gid zero with SO_PASSCRED. */ + void *source,uint32_t *source_length,struct ucred *credentials); +/** @brief Check whether the recipient requested SCM_CREDENTIALS. + * @param file Retained socket description. @return True when SO_PASSCRED is enabled. */ bool task_netlink_passcred(const struct task_file *file); /* Publish KOBJ_CHANGE to group 1. All input is kernel-owned and is copied * before return. properties contains NUL-terminated environment entries. */ diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 8b95560a..b1782075 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -1154,7 +1154,7 @@ static int inet_receive_probe(struct task_file *file,uint32_t capacity, unsigned char byte=0; int result; if(file->kind==TASK_FILE_KIND_NETLINK) - result=task_netlink_recv_staged(file,&byte,0,flags|MSG_PEEK|MSG_TRUNC,NULL,NULL); + result=task_netlink_recv_staged(file,&byte,0,flags|MSG_PEEK|MSG_TRUNC,NULL,NULL,NULL); else if(file->kind==TASK_FILE_KIND_PACKET) result=task_packet_recv_staged(file,&byte,0,flags|MSG_PEEK|MSG_TRUNC,NULL,NULL); else if(file->kind==TASK_FILE_KIND_UDP) @@ -2462,6 +2462,8 @@ complete_message: ; * @param total Validated aggregate vector capacity. * @param output Captured input length and output flags. * @return Bytes processed, negative errno, or the internal blocking sentinel. + * @note Netlink SO_PASSCRED reflects the sender metadata of the dequeued + * datagram rather than the receiver, for both kernel and userspace events. */ static int64_t inet_message(struct task_file *file, uint64_t user_header, struct msghdr message, uint32_t flags, bool receiving, @@ -2566,17 +2568,17 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, struct sockaddr_storage source = {0}; uint32_t source_length = 0; struct net_udp_rx_info udp_info = {0}; + struct ucred netlink_credentials = {0}; + if (netlink) ret = task_netlink_recv_staged(file, payload, output_size, + (flags & ~MSG_CMSG_CLOEXEC) | MSG_TRUNC, message.msg_name ? &source : NULL, + &source_length, netlink_passcred ? &netlink_credentials : NULL); #ifdef CONFIG_SWAP - if(netlink)ret=task_netlink_recv_staged(file,payload,output_size,(flags & ~MSG_CMSG_CLOEXEC)|MSG_TRUNC, - message.msg_name ? &source : NULL,&source_length); else if(packet)ret=task_packet_recv_ex(file,payload,output_size,(flags & ~MSG_CMSG_CLOEXEC)|MSG_TRUNC, message.msg_name ? &source : NULL,&source_length,&udp_info); else if(udp) ret=task_udp_recv_ex(file,payload,output_size,(flags & ~MSG_CMSG_CLOEXEC)|MSG_TRUNC, message.msg_name ? &source : NULL,&source_length,&udp_info); else ret=task_inet_recv(file,payload,output_size,flags); #else - if (netlink) ret = task_netlink_recv_staged(file, payload, size, (flags & ~MSG_CMSG_CLOEXEC) | MSG_TRUNC, - message.msg_name ? &source : NULL, &source_length); else if (packet) ret = task_packet_recv_ex(file, payload, size, (flags & ~MSG_CMSG_CLOEXEC) | MSG_TRUNC, message.msg_name ? &source : NULL,&source_length,&udp_info); else if (udp) ret = task_udp_recv_ex(file, payload, size, (flags & ~MSG_CMSG_CLOEXEC) | MSG_TRUNC, @@ -2599,19 +2601,18 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, output->flags = datagram && (uint64_t)ret > size ? MSG_TRUNC : 0; uint64_t used = 0; if (netlink_passcred) { - const struct ucred credentials = {0}; const uint64_t available = message.msg_control ? message.msg_controllen : 0; - if (available < CMSG_LEN(sizeof(credentials))) + if (available < CMSG_LEN(sizeof(netlink_credentials))) output->flags |= MSG_CTRUNC; if (available >= CMSG_LEN(0)) { uint64_t copy = available - CMSG_LEN(0); - if (copy > sizeof(credentials)) - copy = sizeof(credentials); + if (copy > sizeof(netlink_credentials)) + copy = sizeof(netlink_credentials); const struct cmsghdr header = { .cmsg_len = CMSG_LEN(copy), .cmsg_level = SOL_SOCKET, .cmsg_type = SCM_CREDENTIALS, }; __builtin_memcpy(message.msg_control, &header, sizeof(header)); - __builtin_memcpy((uint8_t *)message.msg_control + CMSG_LEN(0), &credentials, copy); + __builtin_memcpy((uint8_t *)message.msg_control + CMSG_LEN(0), &netlink_credentials, copy); used = CMSG_SPACE(copy) < available ? CMSG_SPACE(copy) : available; } } diff --git a/net/socket/netlink.c b/net/socket/netlink.c index 506ee1b6..02d50de1 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -29,7 +29,15 @@ * A linked registry has no artificial process/socket count limit. */ #define NL_MESSAGE_MAX 8192u #define NL_QUEUE_BUDGET (8u * NL_MESSAGE_MAX) -struct netlink_message { struct netlink_message *next; uint32_t length, groups; uint8_t data[]; }; +#define NL_UEVENT_KERNEL_GROUP 1u +#define NL_UEVENT_UDEV_GROUP 2u +#define NL_UEVENT_GROUPS (NL_UEVENT_KERNEL_GROUP | NL_UEVENT_UDEV_GROUP) +struct netlink_message { + struct netlink_message *next; + uint32_t length, groups, port; + struct ucred credentials; + uint8_t data[]; +}; struct netlink_socket { struct netlink_socket *next; struct netlink_message *head, *tail; @@ -61,14 +69,14 @@ static uint32_t nl_previous_link_count; static bool nl_snapshot_ready; #define NL_SUPPORTED_GROUPS (RTMGRP_LINK|RTMGRP_IPV6_IFADDR|RTMGRP_IPV6_ROUTE) -/** @brief Resolve the route socket attached to an open description. +/** @brief Resolve the netlink socket attached to an open description. * @param file Borrowed OFD. @return State or NULL for another kind. */ static struct netlink_socket *nl_socket(const struct task_file *file) { return file && file->kind == TASK_FILE_KIND_NETLINK ? (void *)(uintptr_t)file->aux : NULL; } /** @brief Test a nonzero port against every bound endpoint. * @param port Proposed ID. @param except Socket excluded from the comparison. - * @return True when another live route socket already owns it. */ + * @return True when another socket in the protocol already owns it. */ static bool nl_port_used(uint32_t port, const struct netlink_socket *except) { for (struct netlink_socket *s = netlink_sockets; s; s = s->next) @@ -396,7 +404,7 @@ static int nl_initial_snapshot(void) static int nl_set_groups(struct netlink_socket *s, uint32_t groups) { if (s->protocol == NETLINK_KOBJECT_UEVENT) { - if (groups & ~1u) + if (groups & ~NL_UEVENT_GROUPS) return -LINUX_EOPNOTSUPP; s->groups = groups; return 0; @@ -421,35 +429,54 @@ static void nl_overrun(uint32_t group) kernel_poll_readiness_notify(); } -/** @brief Filter and queue one multicast datagram for each matching subscriber. +/** @brief Filter and queue one datagram with its source metadata. + * @param s Recipient. @param port Source netlink port (zero for kernel). + * @param group Destination group bit, or zero for unicast. + * @param data Validated datagram. @param length Original length. + * @param credentials Sender's credential snapshot, or NULL for kernel. + * @return Queued length, zero if filtered, or negative errno. + */ +static int nl_queue_datagram(struct netlink_socket *s, uint32_t port, uint32_t group, + const void *data, uint32_t length, const struct ucred *credentials) +{ + uint32_t admitted = socket_filter_run(s->filter, data, length); + if (!admitted) + return 0; + if (s->queued_bytes > NL_QUEUE_BUDGET - NL_MESSAGE_MAX) + return -LINUX_EAGAIN; + struct netlink_message *message = kernel_malloc(sizeof(*message) + admitted); + if (!message) + return -LINUX_ENOBUFS; + *message = (struct netlink_message){.length = admitted, .groups = group, .port = port}; + if (credentials) + message->credentials = *credentials; + __builtin_memcpy(message->data, data, admitted); + if (s->tail) + s->tail->next = message; + else + s->head = message; + s->tail = message; + s->queued_bytes += NL_MESSAGE_MAX; + return (int)admitted; +} + +/** @brief Fan out to subscribed sockets, reporting per-recipient queue overruns. * @param protocol Netlink protocol. @param group Linux group bit. - * @param data Kernel-owned datagram. @param length Datagram length. + * @param data Validated datagram. @param length Datagram length. + * @param sender Sending socket, excluded from fanout, or NULL for kernel. + * @param credentials Sender's credential snapshot, or NULL for kernel. */ -static void nl_multicast(int protocol, uint32_t group, const void *data, uint32_t length) +static void nl_multicast(int protocol, uint32_t group, const void *data, uint32_t length, + const struct netlink_socket *sender, const struct ucred *credentials) { bool notified = false; for (struct netlink_socket *s = netlink_sockets; s; s = s->next) { - if (s->protocol != protocol || !(s->groups & group)) + if (s == sender || s->protocol != protocol || !(s->groups & group)) continue; - uint32_t admitted = socket_filter_run(s->filter, data, length); - if (!admitted) - continue; - notified = true; - struct netlink_message *message = NULL; - if (s->queued_bytes <= NL_QUEUE_BUDGET - NL_MESSAGE_MAX) - message = kernel_malloc(sizeof(*message) + admitted); - if (!message) { + int result = nl_queue_datagram(s, sender ? sender->port : 0, group, data, length, credentials); + if (result < 0) s->overrun = true; - continue; - } - *message = (struct netlink_message){.length = admitted, .groups = group}; - __builtin_memcpy(message->data, data, admitted); - if (s->tail) - s->tail->next = message; - else - s->head = message; - s->tail = message; - s->queued_bytes += NL_MESSAGE_MAX; + notified |= result != 0; } if (notified) kernel_poll_readiness_notify(); @@ -475,7 +502,7 @@ void netlink_uevent_change(const char *devpath, const char *subsystem, text_unsigned(&stream, ++uevent_seqnum); text_bytes(&stream, "", 1); if (stream.position <= sizeof(payload)) - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, stream.written); + nl_multicast(NETLINK_KOBJECT_UEVENT, NL_UEVENT_KERNEL_GROUP, payload, stream.written, NULL, NULL); } EXPORT_SYMBOL(netlink_uevent_change); @@ -523,7 +550,7 @@ static void nl_publish(uint32_t group,uint16_t type,const void *value,bool up) group==RTMGRP_IPV6_ROUTE ? nl_route6(&b,0,value,type,false) : nl_link_snapshot(&b,0,false,type,value); if (rc) { kernel_free(message); nl_overrun(group); return; } - nl_multicast(NETLINK_ROUTE, group, message->data, b.used); + nl_multicast(NETLINK_ROUTE, group, message->data, b.used, NULL, NULL); kernel_free(message); } @@ -973,7 +1000,60 @@ static int nl_request(struct nl_builder *b, const struct nlmsghdr *h) return 0; } -/** @brief Process one complete kernel-bound datagram and filter bounded replies. +/** @brief Deliver a udev datagram to the userspace multicast group or a worker port. + * @param sender Sending socket under execution ownership. @param data Validated bytes. + * @param length Nonzero bounded payload size. @param address Explicit user destination. + * @param address_length User address size. @return Bytes accepted or negative errno. + * @note The caller needs CAP_NET_ADMIN. Kernel-originated group 1 is not writable. + */ +static int nl_uevent_send(struct netlink_socket *sender, const void *data, uint32_t length, + uint64_t address, uint32_t address_length) +{ + struct task *task = sched_current_task(); + if (!task || !(task->cap_effective & (1ULL << CAP_NET_ADMIN)) || !address) + return -LINUX_EPERM; + struct sockaddr_nl dst; + if ((int32_t)address_length < (int32_t)sizeof(dst)) + return -LINUX_EINVAL; + int rc = socket_user_import(task, address, &dst, sizeof(dst)); + if (rc) + return rc; + if (dst.nl_family != AF_NETLINK) + return -LINUX_EAFNOSUPPORT; + if ((dst.nl_groups & NL_UEVENT_KERNEL_GROUP) || (!dst.nl_groups && !dst.nl_pid)) + return -LINUX_EPERM; + if (dst.nl_groups && (dst.nl_groups != NL_UEVENT_UDEV_GROUP || dst.nl_pid)) + return -LINUX_EOPNOTSUPP; + + rc = nl_autobind(sender, task); + if (rc) + return rc; + const struct ucred credentials = {(int32_t)sched_task_tgid(task), task->uid, task->gid}; + void *payload = kernel_malloc(length); + if (!payload) + return -LINUX_ENOBUFS; + __builtin_memcpy(payload, data, length); + if (dst.nl_groups) { + nl_multicast(NETLINK_KOBJECT_UEVENT, dst.nl_groups, payload, length, sender, &credentials); + rc = (int)length; + } else { + rc = -LINUX_ECONNREFUSED; + for (struct netlink_socket *s = netlink_sockets; s; s = s->next) { + if (s->protocol != sender->protocol || !s->bound || s->port != dst.nl_pid) + continue; + rc = nl_queue_datagram(s, sender->port, 0, payload, length, &credentials); + if (rc > 0) + kernel_poll_readiness_notify(); + if (rc >= 0) + rc = (int)length; + break; + } + } + kernel_free(payload); + return rc; +} + +/** @brief Process a route request or deliver a privileged userspace uevent. * @param file Pinned OFD. @param data Validated bytes. @param length Input length. * @param flags Linux send flags. @param address Optional user destination. * @param address_length Address length. @return Bytes accepted or errno. */ @@ -982,9 +1062,12 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui { struct netlink_socket *s=nl_socket(file); if (!s) return -LINUX_EBADF; - if (s->protocol == NETLINK_KOBJECT_UEVENT) - return -LINUX_EPERM; if (flags & ~(MSG_DONTWAIT|MSG_NOSIGNAL)) return -LINUX_EOPNOTSUPP; + if (s->protocol == NETLINK_KOBJECT_UEVENT) { + if (!length) return -LINUX_ENODATA; + if (length > NL_MESSAGE_MAX) return -LINUX_EMSGSIZE; + return nl_uevent_send(s, data, length, address, address_length); + } if (!length || length > NL_MESSAGE_MAX) return -LINUX_EMSGSIZE; if (address) { if (address_length < sizeof(struct sockaddr_nl)) return -LINUX_EINVAL; @@ -1042,7 +1125,7 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui pos+=NLMSG_ALIGN(h->nlmsg_len); } kernel_free(bytes); - message->next=NULL; message->length=builder.used; message->groups=0; + *message = (struct netlink_message){.length = builder.used}; struct netlink_message *replies[2]={message,completion}; bool published = false; for (unsigned i=0;i<2;++i) { @@ -1064,9 +1147,11 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui * @param file Retained OFD. @param data Writable destination. @param length Capacity. * @param flags Native flags. @param address Optional user source. @param address_length * User length pointer. @param source Optional staged source. @param source_length Optional - * staged length. @return Byte count, errno, or blocked marker. */ + * staged length. @param credentials Optional staged sender credentials. + * @return Byte count, errno, or blocked marker. */ static int nl_receive(struct task_file *file,void *data,uint32_t length,uint32_t flags, - uint64_t address,uint64_t address_length,void *source,uint32_t *source_length) + uint64_t address,uint64_t address_length,void *source,uint32_t *source_length, + struct ucred *credentials) { struct netlink_socket *s=nl_socket(file); if (!s) return -LINUX_EBADF; @@ -1077,7 +1162,8 @@ static int nl_receive(struct task_file *file,void *data,uint32_t length,uint32_t sched_sleep_current_until(time_ticks()+1); return KERNEL_SYSCALL_BLOCKED; } - struct sockaddr_nl from={.nl_family=AF_NETLINK,.nl_groups=s->head->groups}; + struct netlink_message *m=s->head; + struct sockaddr_nl from={.nl_family=AF_NETLINK,.nl_pid=m->port,.nl_groups=m->groups}; if (address) { uint32_t cap; int rc=socket_user_length(sched_current_task(),address_length,&cap); if (rc) return rc; if ((int32_t)cap<0) return -LINUX_EINVAL; @@ -1088,7 +1174,7 @@ static int nl_receive(struct task_file *file,void *data,uint32_t length,uint32_t *(uint32_t *)(uintptr_t)address_length=sizeof(from); } if (source && source_length) { __builtin_memcpy(source,&from,sizeof(from)); *source_length=sizeof(from); } - struct netlink_message *m=s->head; + if (credentials) *credentials=m->credentials; uint32_t copied=lengthlength ? length : m->length; if (copied) __builtin_memcpy(data,m->data,copied); int result=(flags & MSG_TRUNC) ? (int)m->length : (int)copied; @@ -1099,20 +1185,24 @@ static int nl_receive(struct task_file *file,void *data,uint32_t length,uint32_t return result; } -/** @brief Receive one route-netlink datagram with optional user source address. +/** @brief Receive one netlink datagram with optional user source address. * @param file Retained OFD. @param data Output. @param length Capacity. @param flags Flags. * @param address User source. @param address_length User socklen. @return Bytes or errno. */ int task_netlink_recv(struct task_file *file,void *data,uint32_t length,uint32_t flags, uint64_t address,uint64_t address_length) -{ return nl_receive(file,data,length,flags,address,address_length,NULL,NULL); } +{ return nl_receive(file,data,length,flags,address,address_length,NULL,NULL,NULL); } /** @brief Receive into kernel-owned buffers for atomic staged user output. * @param file Retained OFD. @param data Kernel output. @param length Capacity. @param flags Flags. - * @param source Optional source buffer. @param source_length Output size. @return Bytes or errno. */ + * @param source Optional source buffer. @param source_length Output size. + * @param credentials Optional output for the datagram's sender credentials. + * @return Bytes, negative errno or blocked marker. */ int task_netlink_recv_staged(struct task_file *file,void *data,uint32_t length,uint32_t flags, - void *source,uint32_t *source_length) -{ return nl_receive(file,data,length,flags,0,0,source,source_length); } + void *source,uint32_t *source_length,struct ucred *credentials) +{ return nl_receive(file,data,length,flags,0,0,source,source_length,credentials); } +/** @brief Check the recipient's SO_PASSCRED setting. + * @param file Retained socket description. @return True when enabled. */ bool task_netlink_passcred(const struct task_file *file) { const struct netlink_socket *s = nl_socket(file); @@ -1245,7 +1335,7 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, uint32_t group; int rc=socket_user_import(task,a3,&group,sizeof(group)); if (rc) return rc; if (!group || group>32) return -LINUX_EINVAL; uint32_t mask=1u<<(group-1); - if (!(mask & (s->protocol == NETLINK_ROUTE ? NL_SUPPORTED_GROUPS : 1u))) + if (!(mask & (s->protocol == NETLINK_ROUTE ? NL_SUPPORTED_GROUPS : NL_UEVENT_GROUPS))) return -LINUX_EOPNOTSUPP; return nl_set_groups(s,a2==NETLINK_ADD_MEMBERSHIP ? s->groups|mask : s->groups&~mask); } diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index a75951e9..6ff5a58f 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -215,6 +215,107 @@ static void check_netlink_reuseaddr(void) puts("PASS route and kobject netlink SO_REUSEADDR: state and exclusive port binding"); } +/** @brief Route processed device notifications without exposing the kernel group. */ +static void check_uevent_userspace_delivery(void) +{ + int sender = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT, 0, 0); + int kernel = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT, 0, 0); + int monitor = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT, 0, 0); + int worker = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT, 0, 0); + assert(sender >= 0 && kernel >= 0 && monitor >= 0 && worker >= 0); + + current.pid = 651; + current.tgid = 650; + current.uid = 1000; + current.gid = 1001; + current.cap_effective = 0; + const struct sockaddr_nl sender_address = {.nl_family = AF_NETLINK, .nl_pid = 42, .nl_groups = 2}; + const struct sockaddr_nl kernel_address = {.nl_family = AF_NETLINK, .nl_groups = 1}; + const struct sockaddr_nl udev_address = {.nl_family = AF_NETLINK, .nl_groups = 2}; + const struct sockaddr_nl worker_address = {.nl_family = AF_NETLINK, .nl_pid = 77}; + const struct sockaddr_nl unknown_address = {.nl_family = AF_NETLINK, .nl_pid = 78}; + const struct sockaddr_nl no_target = {.nl_family = AF_NETLINK}; + assert(!call(__NR_bind, monitor, (uintptr_t)&udev_address, sizeof(udev_address), 0, 0)); + assert(!call(__NR_bind, kernel, (uintptr_t)&kernel_address, sizeof(kernel_address), 0, 0)); + assert(!call(__NR_bind, sender, (uintptr_t)&sender_address, sizeof(sender_address), 0, 0)); + assert(!call(__NR_bind, worker, (uintptr_t)&worker_address, sizeof(worker_address), 0, 0)); + + const char payload[] = "processed-device"; + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&udev_address, sizeof(udev_address)) == -LINUX_EPERM); + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&worker_address, sizeof(worker_address)) == -LINUX_EPERM); + current.cap_effective = 1ULL << CAP_NET_ADMIN; + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&kernel_address, sizeof(kernel_address)) == -LINUX_EPERM); + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&no_target, sizeof(no_target)) == -LINUX_EPERM); + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&unknown_address, sizeof(unknown_address)) == -LINUX_ECONNREFUSED); + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&udev_address, sizeof(udev_address)) == sizeof(payload)); + current.uid = 2000; + current.gid = 2001; + char output[64]; + assert(receive(kernel, output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(sender, output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(worker, output, sizeof(output)) == -LINUX_EAGAIN); + + struct sockaddr_nl from = {0}; + struct ucred credentials = {0}; + uint32_t from_size = 0; + assert(task_netlink_recv_staged(&files[monitor], output, sizeof(output), MSG_PEEK, + &from, &from_size, &credentials) == sizeof(payload)); + assert(from_size == sizeof(from) && from.nl_family == AF_NETLINK && + from.nl_pid == sender_address.nl_pid && from.nl_groups == 2); + assert(credentials.pid == 650 && credentials.uid == 1000 && credentials.gid == 1001); + assert(receive(monitor, output, sizeof(output)) == sizeof(payload)); + assert(!memcmp(output, payload, sizeof(payload))); + assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); + + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&worker_address, sizeof(worker_address)) == sizeof(payload)); + assert(task_netlink_recv_staged(&files[worker], output, sizeof(output), MSG_DONTWAIT, + &from, &from_size, &credentials) == sizeof(payload)); + assert(from.nl_pid == sender_address.nl_pid && !from.nl_groups); + assert(credentials.pid == 650 && credentials.uid == 2000 && credentials.gid == 2001); + assert(!memcmp(output, payload, sizeof(payload))); + assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(kernel, output, sizeof(output)) == -LINUX_EAGAIN); + + const uint32_t userspace_group = 2; + assert(!call(__NR_setsockopt, monitor, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, + (uintptr_t)&userspace_group, sizeof(userspace_group))); + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&udev_address, sizeof(udev_address)) == sizeof(payload)); + assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); + assert(!call(__NR_setsockopt, monitor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, + (uintptr_t)&userspace_group, sizeof(userspace_group))); + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&udev_address, sizeof(udev_address)) == sizeof(payload)); + assert(receive(monitor, output, sizeof(output)) == sizeof(payload)); + + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + assert(task_netlink_recv_staged(&files[kernel], output, sizeof(output), MSG_DONTWAIT, + &from, &from_size, &credentials) == sizeof(payload)); + assert(!from.nl_pid && from.nl_groups == 1 && + !credentials.pid && !credentials.uid && !credentials.gid); + assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); + + allocation_fail_after = 1; /* The snapshot succeeds but the unicast queue allocation fails. */ + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&worker_address, sizeof(worker_address)) == -LINUX_ENOBUFS); + allocation_fail_after = -1; + assert(receive(worker, output, sizeof(output)) == -LINUX_EAGAIN); + for (int fd = 0; fd < 4; ++fd) { + task_netlink_release(&files[fd]); + files[fd] = (struct task_file){0}; + } + current = (struct task){0}; + assert(!allocations); + puts("PASS kobject uevent: userspace group isolation, privileged delivery and sender metadata"); +} + /** @brief Exercise filter installation and message delivery on both netlink protocols. */ static void check_netlink_filter(void) { @@ -243,13 +344,13 @@ static void check_netlink_filter(void) uint8_t payload[] = {0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0xaa, 0xbb, 0xcc, 0xdd}; uint8_t output[64]; - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == 9); assert(!memcmp(output, payload, 9)); - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, 7); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, 7, NULL, NULL); assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); payload[4] = 0x21; - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); payload[4] = 0x12; @@ -266,7 +367,7 @@ static void check_netlink_filter(void) }; struct sock_fprog expression = {.len = sizeof(arithmetic) / sizeof(arithmetic[0]), .filter = arithmetic}; assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&expression, sizeof(expression))); - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == 9); struct sock_filter invalid_path[] = { BPF_STMT(BPF_LD | BPF_W | BPF_IMM, 0), @@ -291,7 +392,7 @@ static void check_netlink_filter(void) }; struct sock_fprog zero_divisor = {.len = 4, .filter = divide}; assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&zero_divisor, sizeof(zero_divisor))); - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program))); @@ -303,10 +404,10 @@ static void check_netlink_filter(void) assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program)) == -LINUX_ENOMEM); allocation_fail_after = -1; } - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == 9); assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_DETACH_FILTER, (uintptr_t)&value, sizeof(value))); - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload)); + nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == (int)sizeof(payload)); struct sock_filter reject[] = {BPF_STMT(BPF_RET | BPF_K, 0)}; @@ -347,6 +448,7 @@ static void check_netlink_filter(void) int main(void) { check_netlink_reuseaddr(); + check_uevent_userspace_delivery(); assert(!net_interface_register(2)); check_netlink_filter(); net_config.local_ip=0x0a00020f; net_config.subnet_mask=0xffffff00; diff --git a/tools/tests/socket_batch_unix_test.c b/tools/tests/socket_batch_unix_test.c index 0ada6ef6..8d269189 100644 --- a/tools/tests/socket_batch_unix_test.c +++ b/tools/tests/socket_batch_unix_test.c @@ -55,8 +55,8 @@ int task_netlink_recv(struct task_file *file, void *data, uint32_t length, { (void)file; (void)data; (void)length; (void)flags; (void)address; (void)address_length; abort(); } /** @brief Fail if this UNIX fixture stages a netlink message. */ int task_netlink_recv_staged(struct task_file *file, void *data, uint32_t length, uint32_t flags, - void *source, uint32_t *source_length) -{ (void)file; (void)data; (void)length; (void)flags; (void)source; (void)source_length; abort(); } + void *source, uint32_t *source_length, struct ucred *credentials) +{ (void)file; (void)data; (void)length; (void)flags; (void)source; (void)source_length; (void)credentials; abort(); } /** @brief Fail if this UNIX fixture reads netlink credential configuration. */ bool task_netlink_passcred(const struct task_file *file) { (void)file; abort(); } From 804fdfadb7dd59e9349dbe2b3245e040a0c3710d Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 19:08:41 +0800 Subject: [PATCH 41/97] fix(sysfs): expose the subsystem for block devices --- .../LC_MESSAGES/userspace-api/descriptors.po | 3 + .../LC_MESSAGES/userspace-api/descriptors.po | 3 + Documentation/userspace-api/descriptors.rst | 4 ++ fs/sysfs/sysfs.c | 11 +++- tools/tests/linux_inventory_test.c | 56 +++++++++++++++++-- 5 files changed, 72 insertions(+), 5 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index 395e9143..da252fbb 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -38,6 +38,9 @@ msgstr "" "return the actually registered read-only flag and logical sector size " "respectively." +msgid "整盘和分区的 sysfs 设备目录都有指向 ``/sys/class/block`` 的相对 ``subsystem`` 链接。``/sys/dev/block/:`` 和 ``/sys/class/block/`` 指向同一设备目录,用户态可凭设备节点的 ``st_rdev`` 验证块设备身份。" +msgstr "The sysfs directories of both whole disks and partitions have a relative ``subsystem`` link to ``/sys/class/block``. ``/sys/dev/block/:`` and ``/sys/class/block/`` point to the same device directory, allowing userspace to verify a block device's identity using the device node's ``st_rdev``." + msgid "" "FAT32/exFAT 的显式挂载支持 Linux ``uid``、``gid``、``umask``、``fmask`` 和 ``dmask``" " 选项。UID/GID 使用十进制,掩码使用八进制。完整解析成功后才提交。 显式选项决定该文件系统实例的合成所有权和模式,ext " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index 1cca2a2f..66aa466d 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -34,6 +34,9 @@ msgstr "" "は開いた記述子が保持するディスク全体の番号を返し、パーティション記述子は所属するディスクの番号を返します。取り外し後も古い記述子は元の番号を保持し、再登録ではより大きい番号を割り当てます。``BLKROGET``" " と ``BLKSSZGET`` はそれぞれ実際に登録された読み取り専用フラグと論理セクターサイズを返します。" +msgid "整盘和分区的 sysfs 设备目录都有指向 ``/sys/class/block`` 的相对 ``subsystem`` 链接。``/sys/dev/block/:`` 和 ``/sys/class/block/`` 指向同一设备目录,用户态可凭设备节点的 ``st_rdev`` 验证块设备身份。" +msgstr "ディスク全体とパーティションの sysfs デバイスディレクトリには、``/sys/class/block`` を指す相対 ``subsystem`` リンクがあります。``/sys/dev/block/:`` と ``/sys/class/block/`` は同じデバイスディレクトリを指すため、ユーザー空間はデバイスノードの ``st_rdev`` を使ってブロックデバイスを識別できます。" + msgid "" "FAT32/exFAT 的显式挂载支持 Linux ``uid``、``gid``、``umask``、``fmask`` 和 ``dmask``" " 选项。UID/GID 使用十进制,掩码使用八进制。完整解析成功后才提交。 显式选项决定该文件系统实例的合成所有权和模式,ext " diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index a9f9b749..558fcccd 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -11,6 +11,10 @@ 拔出后旧描述符保留原序号。重新注册分配更大的序号。``BLKROGET`` 与 ``BLKSSZGET`` 分别返回真实注册的只读标志和逻辑扇区大小。 +整盘和分区的 sysfs 设备目录都有指向 ``/sys/class/block`` 的相对 ``subsystem`` +链接。``/sys/dev/block/:`` 和 ``/sys/class/block/`` +指向同一设备目录,用户态可凭设备节点的 ``st_rdev`` 验证块设备身份。 + FAT32/exFAT 的显式挂载支持 Linux ``uid``、``gid``、``umask``、``fmask`` 和 ``dmask`` 选项。UID/GID 使用十进制,掩码使用八进制。完整解析成功后才提交。 显式选项决定该文件系统实例的合成所有权和模式,ext 文件系统继续使用介质上的 diff --git a/fs/sysfs/sysfs.c b/fs/sysfs/sysfs.c index 803fcfe0..b692e47f 100644 --- a/fs/sysfs/sysfs.c +++ b/fs/sysfs/sysfs.c @@ -253,7 +253,7 @@ static int sys_block_pci_parent(uint32_t disk) return -1; } -/** @brief Visit registered block geometry using the same identity as devfs. +/** @brief Visit block geometry, class membership and the same identity as devfs. * @param visit Borrowed synchronous attribute consumer. @param ctx Consumer context. * @return Zero or enumeration/consumer errno. Execution ownership stabilizes * inventory and native reads; memory images remain visible despite installer @@ -341,6 +341,15 @@ static int sys_blocks(sys_visit visit, void *ctx) j == 7 ? (uint32_t)part + 1 : info.block_size}; if ((ret = visit(&n, ctx))) return ret; } + /* Resolve relative to the actual disk directory. PCI paths and + * partitions can be deeper than the platform disk fallback. */ + s = (struct text_stream){.buffer=target, .capacity=sizeof(target)-1}; + for (const char *p=base+sizeof("/sys")-1; *p; ++p) + if (*p=='/') text_string(&s, "../"); + text_string(&s, "class/block"); + target[s.written] = 0; + sys_path(path, base, -1, "/subsystem"); + if ((ret=sys_emit(visit,ctx,path,A_LINK,0,target))) return ret; sys_path(target, "../../", -1, base + 5); sys_path(path, "/sys/dev/block/", -1, number); if ((ret=sys_emit(visit,ctx,path,A_LINK,0,target))) return ret; diff --git a/tools/tests/linux_inventory_test.c b/tools/tests/linux_inventory_test.c index bb41235f..c46ce61f 100644 --- a/tools/tests/linux_inventory_test.c +++ b/tools/tests/linux_inventory_test.c @@ -25,16 +25,23 @@ static uint8_t fixture_slot=3; static unsigned fixture_refs; int storage_disk_block_get(uint32_t disk,struct block_device_ref *out) { - if (!fixture_block_pci || (disk && !(disk==1 && fixture_second_pci))) return -LINUX_ENODEV; - out->device=(void *)(uintptr_t)1;++fixture_refs;return 0; + if (disk && !(disk == 1 && fixture_second_pci) && !(disk == 7 && fixture_ram)) + return -LINUX_ENODEV; + out->device=(void *)(uintptr_t)(disk + 1);++fixture_refs;return 0; } int block_device_info(const struct block_device_ref *ref,struct block_device_info *out) { assert(ref && ref->device); - *out=(struct block_device_info){.transport=fixture_transport,.bus=0,.slot=fixture_slot,.function=0, + *out=(struct block_device_info){.transport=fixture_block_pci && + (uintptr_t)ref->device != 8 ? fixture_transport : 0, + .bus=0,.slot=fixture_slot,.function=0, + .blocks=(uintptr_t)ref->device == 1 ? 131072 : 65536,.block_size=512, .flags=BLOCK_DEVICE_SWAP_SAFE}; return 0; } +/** @brief Supply a nonzero registration sequence for each fixture disk. */ +uint64_t block_device_sequence(const struct block_device_ref *ref) +{ assert(ref && ref->device); return (uintptr_t)ref->device + 15; } void block_device_put(struct block_device_ref *ref) { assert(ref && ref->device && fixture_refs);ref->device=NULL;--fixture_refs; } int storage_list_block_disks(struct reliefos_install_disk *disks, uint32_t capacity, uint32_t *count) @@ -137,6 +144,17 @@ bool graphics_service_kms_scanout_active(void) { return fixture_kms_enabled; } +/** @brief Provide one virtual connector while the fixture GPU is registered. */ +int graphics_service_connector_info(uint32_t index, struct graphics_connector_info *out) +{ + if (index || !fixture_drm_present) + return -LINUX_ENODEV; + *out = (struct graphics_connector_info){ + .connected = true, .enabled = fixture_kms_enabled, .mode_count = 1, + .widths = {fixture_fb.width}, .heights = {fixture_fb.height}, + }; + return 0; +} static void read_value(const char *path, char *out, size_t capacity) { uint32_t total = 0, got; @@ -172,6 +190,31 @@ static void walk(const char *path, unsigned depth) } assert(ret == 0); } + +/** @brief Resolve a block identity from its rdev and classify its subsystem. */ +static void check_block_subsystem(const char *device, const char *expected) +{ + struct vfs_mount *mount = NULL; + struct vfs_namespace ns = {0}; + struct vfs_path root = {0}, block = {0}, actual = {0}, class = {0}; + assert(!sysfs_create_vfs_mount(&mount)); + assert(!vfs_namespace_init(&ns, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns, &root)); + assert(!vfs_path_lookup(&ns, &root, &root, device, VFS_LOOKUP_FOLLOW, &block)); + char canonical[RELIEFOS_FS_PATH_LEN]; + assert(!vfs_path_backend_name(&block, canonical, sizeof(canonical))); + assert(!strcmp(canonical, expected)); + assert(!vfs_path_lookup(&ns, &root, &block, "subsystem", VFS_LOOKUP_FOLLOW, &actual)); + assert(!vfs_path_lookup(&ns, &root, &root, "class/block", VFS_LOOKUP_FOLLOW, &class)); + assert(vfs_path_same_inode(&actual, &class)); + vfs_path_put(&class); + vfs_path_put(&actual); + vfs_path_put(&block); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns)); +} + int main(void) { cpu_inventory_capture(0); @@ -185,8 +228,10 @@ int main(void) read_value("/sys/devices/platform/leonos-block/sda/sda1/size", value, sizeof(value)); assert(!strcmp(value, "32768\n")); read_value("/sys/devices/platform/leonos-block/sda/uevent", value, sizeof(value)); - assert(!strcmp(value, "MAJOR=259\nMINOR=0\nDEVNAME=sda\nDEVTYPE=disk\n")); + assert(!strcmp(value, "MAJOR=259\nMINOR=0\nDEVNAME=sda\nDEVTYPE=disk\nDISKSEQ=16\n")); assert(proc_readlink("/sys/dev/block/259:1", value, sizeof(value)) > 0); + check_block_subsystem("dev/block/259:0", "/devices/platform/leonos-block/sda"); + check_block_subsystem("dev/block/259:1", "/devices/platform/leonos-block/sda/sda1"); fixture_block_pci=true; read_value("/sys/devices/pci0000:00/0000:00:03.0/block/sda/dev",value,sizeof(value)); assert(!strcmp(value,"259:0\n")); @@ -199,6 +244,9 @@ int main(void) block_len=proc_readlink("/sys/dev/block/259:0",value,sizeof(value)); assert(block_len==(int)strlen(block_target));value[block_len]=0; assert(!strcmp(value,block_target)); + check_block_subsystem("dev/block/259:0", "/devices/pci0000:00/0000:00:03.0/block/sda"); + check_block_subsystem("dev/block/259:1", "/devices/pci0000:00/0000:00:03.0/block/sda/sda1"); + puts("PASS block sysfs subsystem: rdev lookup and device-relative class resolution"); fixture_second_pci=true; read_value("/sys/devices/pci0000:00/0000:00:03.0/block/sdb/dev",value,sizeof(value)); assert(!strcmp(value,"259:128\n") && !fixture_refs); From 3086b0d207e92dc5aa4d2bfd7ca14af12fb64740 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 19:22:27 +0800 Subject: [PATCH 42/97] fix(process): report unavailable resource limits as EINVAL --- Documentation/admin-guide/limitations.rst | 4 +++ .../en/LC_MESSAGES/admin-guide/limitations.po | 3 ++ .../ja/LC_MESSAGES/admin-guide/limitations.po | 3 ++ kernel/syscall/process/process.c | 4 ++- tools/tests/resource_limits_test.c | 31 +++++++++++++++++++ 5 files changed, 44 insertions(+), 1 deletion(-) diff --git a/Documentation/admin-guide/limitations.rst b/Documentation/admin-guide/limitations.rst index 5417cad7..d797cde5 100644 --- a/Documentation/admin-guide/limitations.rst +++ b/Documentation/admin-guide/limitations.rst @@ -24,3 +24,7 @@ GPU 支持限于已实现的设备与能力,不等于通用 Linux DRM 驱动 不修改音频支持清单掩盖失败。部分旧 fixture 与总测试存在 独立失败,定向测试通过不能称为完整 ABI 或 POSIX 认证。 CPU 统计精度仍为 10 ms,不包含独立 IRQ、softirq、iowait 和完整子进程统计。 + +资源限制接口对尚未实现的 ``RLIMIT_CPU``、``RLIMIT_RSS``、``RLIMIT_LOCKS``、 +``RLIMIT_MSGQUEUE``、``RLIMIT_NICE`` 和 ``RLIMIT_RTTIME`` 返回 ``EINVAL``。 +用户态可以跳过这些项目;内核不接受或执行这些限制。 diff --git a/Documentation/locale/en/LC_MESSAGES/admin-guide/limitations.po b/Documentation/locale/en/LC_MESSAGES/admin-guide/limitations.po index f2572854..a0bc19b4 100644 --- a/Documentation/locale/en/LC_MESSAGES/admin-guide/limitations.po +++ b/Documentation/locale/en/LC_MESSAGES/admin-guide/limitations.po @@ -56,3 +56,6 @@ msgstr "" "independent failures; passing targeted tests cannot be called full ABI or POSIX certification. CPU" " statistics still have 10 ms precision and do not include separate IRQ, softirq, iowait, or " "complete child-process statistics." + +msgid "资源限制接口对尚未实现的 ``RLIMIT_CPU``、``RLIMIT_RSS``、``RLIMIT_LOCKS``、 ``RLIMIT_MSGQUEUE``、``RLIMIT_NICE`` 和 ``RLIMIT_RTTIME`` 返回 ``EINVAL``。 用户态可以跳过这些项目;内核不接受或执行这些限制。" +msgstr "The resource-limit interfaces return ``EINVAL`` for the unimplemented ``RLIMIT_CPU``, ``RLIMIT_RSS``, ``RLIMIT_LOCKS``, ``RLIMIT_MSGQUEUE``, ``RLIMIT_NICE`` and ``RLIMIT_RTTIME``. Userspace can skip these resources; the kernel does not accept or enforce their limits." diff --git a/Documentation/locale/ja/LC_MESSAGES/admin-guide/limitations.po b/Documentation/locale/ja/LC_MESSAGES/admin-guide/limitations.po index 1cc9f61a..5a7190cd 100644 --- a/Documentation/locale/ja/LC_MESSAGES/admin-guide/limitations.po +++ b/Documentation/locale/ja/LC_MESSAGES/admin-guide/limitations.po @@ -47,3 +47,6 @@ msgstr "" "バイトです。追加フィールドは独立したフィクスチャで検査し、旧バージョンの記述子は初期化前に拒否します。元の golden " "データは再生成せず、失敗を隠すために音声対応一覧を変更することもありません。一部の旧フィクスチャと総合テストには独立した失敗があり、対象を絞ったテストの合格を完全な ABI 認証や POSIX " "認証とは呼べません。CPU 統計の精度は依然として 10 ms で、独立した IRQ、softirq、iowait、完全な子プロセス統計は含みません。" + +msgid "资源限制接口对尚未实现的 ``RLIMIT_CPU``、``RLIMIT_RSS``、``RLIMIT_LOCKS``、 ``RLIMIT_MSGQUEUE``、``RLIMIT_NICE`` 和 ``RLIMIT_RTTIME`` 返回 ``EINVAL``。 用户态可以跳过这些项目;内核不接受或执行这些限制。" +msgstr "リソース制限インターフェースは、未実装の ``RLIMIT_CPU``、``RLIMIT_RSS``、``RLIMIT_LOCKS``、``RLIMIT_MSGQUEUE``、``RLIMIT_NICE``、``RLIMIT_RTTIME`` に対して ``EINVAL`` を返します。ユーザー空間はこれらの項目をスキップでき、カーネルはこれらの制限を受け付けず、適用もしません。" diff --git a/kernel/syscall/process/process.c b/kernel/syscall/process/process.c index b10a710f..427cc814 100644 --- a/kernel/syscall/process/process.c +++ b/kernel/syscall/process/process.c @@ -60,6 +60,8 @@ static int process_prepare_user(struct task *task, uint64_t address, uint64_t si * Input is captured before an overlapping old-limit output is written. Linux * commits the update before reporting an old-limit copy fault; preserve that. * RTPRIO is stored and inherited even while realtime scheduling is unavailable. + * Limit identifiers not implemented by this kernel return EINVAL so userspace + * can distinguish them from an unavailable syscall. * @param number Resource-limit syscall number. * @param a0 First syscall argument. @param a1 Second syscall argument. * @param a2 Third syscall argument. @param a3 Fourth syscall argument. @@ -130,7 +132,7 @@ static int64_t process_resource_limit(uint64_t number, uint64_t a0, uint64_t a1, else if (resource == LINUX_RLIMIT_MEMLOCK) stored = &limits->memlock; else if (resource == LINUX_RLIMIT_FSIZE) stored = &limits->fsize; else if (resource == LINUX_RLIMIT_RTPRIO) stored = &limits->rtprio; - else return -LINUX_ENOSYS; + else return -LINUX_EINVAL; if (setting && next.rlim_max > stored->rlim_max && !(caller->cap_effective & (1ULL << CAP_SYS_RESOURCE))) return -LINUX_EPERM; if ((old_pointer || number == LINUX_SYS_GETRLIMIT) && diff --git a/tools/tests/resource_limits_test.c b/tools/tests/resource_limits_test.c index e302367f..f40be5cd 100644 --- a/tools/tests/resource_limits_test.c +++ b/tools/tests/resource_limits_test.c @@ -19,8 +19,39 @@ bool user_range_ok(uint64_t address, uint64_t length) bool user_range_writable(uint64_t address, uint64_t length) { return user_range_ok(address, length) && address != readonly; } +/** + * @brief Exercise the complete getrlimit probe used by the stock PAM stack. + * @note Unavailable limits are skipped on EINVAL; they must not appear + * supported or make an otherwise usable prlimit64 syscall look unavailable. + */ +static void test_limit_discovery(void) +{ + const uint32_t unavailable = (1u << LINUX_RLIMIT_CPU) | (1u << LINUX_RLIMIT_RSS) | + (1u << LINUX_RLIMIT_LOCKS) | (1u << LINUX_RLIMIT_MSGQUEUE) | + (1u << LINUX_RLIMIT_NICE) | (1u << LINUX_RLIMIT_RTTIME); + for (uint32_t resource = 0; resource < LINUX_RLIM_NLIMITS; ++resource) { + const bool missing = (unavailable & (1u << resource)) != 0; + const struct linux_rlimit64 finite = {1, 2}; + struct linux_rlimit64 out = {UINT64_MAX, UINT64_MAX}; + int expected = missing ? -LINUX_EINVAL : 0; + assert(process_resource_limit(LINUX_SYS_PRLIMIT64, 0, resource, 0, + (uintptr_t)&out) == expected); + assert(process_resource_limit(LINUX_SYS_GETRLIMIT, resource, + (uintptr_t)&out, 0, 0) == expected); + if (missing) { + assert(out.rlim_cur == UINT64_MAX && out.rlim_max == UINT64_MAX); + assert(process_resource_limit(LINUX_SYS_SETRLIMIT, resource, + (uintptr_t)&finite, 0, 0) == -LINUX_EINVAL); + } else { + assert(out.rlim_cur == 0 && out.rlim_max == 0); + } + } + puts("PASS PAM resource discovery: implemented values and distinct unavailable limits"); +} + int main(void) { + test_limit_discovery(); struct task_address_space_state shared = {0}; caller.shared_mm = &shared; caller.euid = caller.fsuid = 1000; From 1becc6cd63dff2ef55cff94d181fbf9c8d0fb941 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 19:36:11 +0800 Subject: [PATCH 43/97] feat(sysfs): expose the active virtual terminal to logind --- .../userspace-api/device-filesystems.po | 9 ++ .../userspace-api/device-filesystems.po | 9 ++ .../userspace-api/device-filesystems.rst | 14 +++ drivers/tty/pty/vt.c | 15 +++- fs/sysfs/internal.h | 3 + fs/sysfs/mount.c | 87 ++++++++++++++++++- fs/sysfs/sysfs.c | 16 ++++ include/reliefnt/pty.h | 5 ++ kernel/syscall/event/epoll.c | 34 ++++---- tools/test_linux_inventory.py | 2 +- tools/tests/epoll_capacity_test.c | 32 ++++++- tools/tests/linux_inventory_test.c | 79 +++++++++++++++++ tools/tests/linux_pty_test.c | 13 ++- 13 files changed, 296 insertions(+), 22 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 8cd3b59e..27fa5fa1 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -206,6 +206,15 @@ msgstr "" "node. If no valid devpts multiplexer is found, the kernel uses its early-" "boot PTY allocation path. Other lookup errors are returned to the caller." +msgid "前台虚拟终端" +msgstr "Foreground virtual terminal" + +msgid "有虚拟终端时,只读的 ``/sys/class/tty/tty0/active`` 通过类链接访问 ``/sys/devices/virtual/tty/tty0/active``,读取返回当前前台终端的名称,如 ``tty1`` 加换行。前台实际切换时唤醒等待者;仅修改图形模式、仅请求切换 或拒绝交接不会通知。" +msgstr "When virtual terminals are available, the read-only class link exposes ``/sys/devices/virtual/tty/tty0/active`` at ``/sys/class/tty/tty0/active``. Reading the attribute returns the current foreground terminal name, such as ``tty1``, followed by a newline. A committed switch wakes waiters. Changing the graphics mode, merely requesting a switch, or refusing the handoff does not notify." + +msgid "每次打开独立记录读取进度,复制的描述符共享该记录。首次读取前及未读取的 切换后,poll/epoll 即使兴趣掩码为零也报告 ``POLLERR``/``EPOLLERR``;订阅 优先事件时也报告 ``POLLPRI``/``EPOLLPRI``。通知不会被 poll 消耗;从文件 开头再次读取会获取当前终端并确认通知。分段读取可读完现有快照;多次切换 可以合并,即使切回原终端也会通知。" +msgstr "Each open tracks its own read progress; duplicated descriptors share that state. Before the first read and after an unread switch, poll/epoll reports ``POLLERR``/``EPOLLERR`` even with an empty interest mask, as well as ``POLLPRI``/``EPOLLPRI`` when priority events are requested. Polling does not consume the notification. Reading again from offset zero obtains the current terminal and acknowledges the change. Partial reads can finish the previous snapshot. Multiple switches can coalesce, but a round trip to the same terminal still notifies." + msgid "cgroup v2" msgstr "Unified cgroup hierarchy (v2)" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index 5dda2ebc..2564a5d8 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -181,6 +181,15 @@ msgstr "" "が見つかれば新しいセッションとマスターのディスクリプタはそのインスタンスに属し、アクセス可否は従来のデバイスノードの権限で決まります。有効な " "devpts マルチプレクサが見つからない場合は起動初期の PTY 割り当てを使用し、それ以外の検索エラーは呼び出し元に返します。" +msgid "前台虚拟终端" +msgstr "フォアグラウンド仮想端末" + +msgid "有虚拟终端时,只读的 ``/sys/class/tty/tty0/active`` 通过类链接访问 ``/sys/devices/virtual/tty/tty0/active``,读取返回当前前台终端的名称,如 ``tty1`` 加换行。前台实际切换时唤醒等待者;仅修改图形模式、仅请求切换 或拒绝交接不会通知。" +msgstr "仮想端末がある場合、読み取り専用の ``/sys/class/tty/tty0/active`` はクラスのリンク経由で ``/sys/devices/virtual/tty/tty0/active`` を参照します。読み取ると、現在のフォアグラウンド端末名(例: ``tty1``)と改行を返します。実際に端末を切り替えると待機中の処理を起こします。グラフィックスモードの変更、切り替えの要求だけの場合、引き渡しの拒否では通知しません。" + +msgid "每次打开独立记录读取进度,复制的描述符共享该记录。首次读取前及未读取的 切换后,poll/epoll 即使兴趣掩码为零也报告 ``POLLERR``/``EPOLLERR``;订阅 优先事件时也报告 ``POLLPRI``/``EPOLLPRI``。通知不会被 poll 消耗;从文件 开头再次读取会获取当前终端并确认通知。分段读取可读完现有快照;多次切换 可以合并,即使切回原终端也会通知。" +msgstr "オープンごとに読み取りの進捗を記録し、複製したディスクリプタはその状態を共有します。初回の読み取り前および未確認の切り替え後は、監視マスクが空でも poll/epoll が ``POLLERR``/``EPOLLERR`` を返し、優先イベントの監視時には ``POLLPRI``/``EPOLLPRI`` も返します。ポーリングで通知は消費されません。ファイルの先頭から読み直すと、現在の端末を取得して通知を確認します。分割読み取りでは既存のスナップショットの続きを読めます。複数回の切り替えは一つの通知にまとまる場合がありますが、元の端末に戻っても通知します。" + msgid "cgroup v2" msgstr "統合 cgroup 階層(v2)" diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 175f2eeb..1208fd5f 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -100,6 +100,20 @@ devpts 挂载选项 权限决定是否可打开。找不到有效的 devpts 多路复用器时沿用启动阶段的旧 PTY 分配;其他查找错误则返回调用方。 +前台虚拟终端 +============ + +有虚拟终端时,只读的 ``/sys/class/tty/tty0/active`` 通过类链接访问 +``/sys/devices/virtual/tty/tty0/active``,读取返回当前前台终端的名称,如 +``tty1`` 加换行。前台实际切换时唤醒等待者;仅修改图形模式、仅请求切换 +或拒绝交接不会通知。 + +每次打开独立记录读取进度,复制的描述符共享该记录。首次读取前及未读取的 +切换后,poll/epoll 即使兴趣掩码为零也报告 ``POLLERR``/``EPOLLERR``;订阅 +优先事件时也报告 ``POLLPRI``/``EPOLLPRI``。通知不会被 poll 消耗;从文件 +开头再次读取会获取当前终端并确认通知。分段读取可读完现有快照;多次切换 +可以合并,即使切回原终端也会通知。 + cgroup v2 ========= diff --git a/drivers/tty/pty/vt.c b/drivers/tty/pty/vt.c index 24b67b5a..17062323 100644 --- a/drivers/tty/pty/vt.c +++ b/drivers/tty/pty/vt.c @@ -1,6 +1,8 @@ #include #include "internal.h" +static uint64_t vt_foreground_generation; + /** * @brief Deliver one process-directed VT controller signal, not a group broadcast. * @param signal_number Registered signal; zero is an existence probe. @@ -46,6 +48,7 @@ int pty_vt_init(void) } vt_switch_target = 0; vt_display_generation = 1; + vt_foreground_generation = 1; active_vt = 1; vt_ready = 1; return 0; @@ -214,6 +217,7 @@ int pty_vt_open_query(void) * * Runs only once the outgoing VT_PROCESS controller has granted the release * with VT_RELDISP(1), or immediately when the outgoing console is VT_AUTO. + * Publishes poll readiness after the new foreground console is selected. */ static int pty_vt_commit_switch(uint32_t number) { @@ -225,8 +229,10 @@ static int pty_vt_commit_switch(uint32_t number) if (active_vt && active_vt <= VT_COUNT) vt_release_pending[active_vt - 1u] = 0; vt_switch_target = 0; ++vt_display_generation; - if (active_vt && active_vt != number) graphics_service_kms_vt_release(); + bool foreground_changed = active_vt != number; + if (active_vt && foreground_changed) graphics_service_kms_vt_release(); active_vt = number; + if (foreground_changed) ++vt_foreground_generation; /* A grabbed graphical client can consume modifier releases while the * display is away. Do not carry stale Ctrl/Alt state into the next VT; * evdev consumers receive their independent modifier snapshot below. */ @@ -238,6 +244,7 @@ static int pty_vt_commit_switch(uint32_t number) vt_graphical[number - 1u] != 0); input_set_graphical_vt(vt_graphical[number - 1u] ? number : 0); console_vt_activate(number, vt_graphical[number - 1u] != 0); + if (foreground_changed) kernel_poll_readiness_notify(); (void)kernel_wait_queue_wake_all(&vt_waiters); if (vt_modes[number - 1u].mode == VT_PROCESS) { /* The new controller keeps VT_PROCESS; the pending flag is cleared by @@ -322,6 +329,12 @@ uint64_t pty_vt_generation(void) return vt_display_generation; } +/** @copydoc pty_vt_foreground_generation */ +uint64_t pty_vt_foreground_generation(void) +{ + return vt_foreground_generation; +} + /** * @brief Request a display switch to a fixed virtual console. * @param number Destination virtual console number, one through six. diff --git a/fs/sysfs/internal.h b/fs/sysfs/internal.h index 26f04098..c64f5406 100644 --- a/fs/sysfs/internal.h +++ b/fs/sysfs/internal.h @@ -3,6 +3,9 @@ #define RELIEFNT_SYSFS_INTERNAL_H #include #include + +#define SYSFS_TTY0_ACTIVE "/sys/devices/virtual/tty/tty0/active" + /** @brief Decode an intrinsic sysfs module parameter key. * @param path Borrowed provider-internal path, never a global routing input. * @param module Required MODULE_NAME_LEN-byte module output. diff --git a/fs/sysfs/mount.c b/fs/sysfs/mount.c index 1a75629f..2655cbc2 100644 --- a/fs/sysfs/mount.c +++ b/fs/sysfs/mount.c @@ -1,5 +1,8 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include +#include +#include +#include #include #include #include @@ -57,7 +60,85 @@ static void sysfs_key_put(void *identity) #endif } -/** @brief Construct a detached sysfs mount with descriptor-authorized stores. +struct sysfs_foreground_view { + uint64_t generation; + uint32_t length; + char value[sizeof("tty4294967295\n") - 1]; +}; + +/** @brief Allocate a per-description notification cursor for tty0/active. + * @param name Intrinsic sysfs key. @param flags Already authorized open flags. + * @param state Receives the owned cursor or NULL for ordinary sysfs files. + * @return Zero or negative ENOMEM without publishing a partial cursor. + */ +static int sysfs_foreground_open(const char *name, uint32_t flags, void **state) +{ + (void)flags; + *state = NULL; + if (__builtin_strcmp(name, SYSFS_TTY0_ACTIVE)) return 0; + struct sysfs_foreground_view *view = kernel_malloc(sizeof(*view)); + if (!view) return -ENOMEM; + *view = (struct sysfs_foreground_view){0}; + *state = view; + return 0; +} + +/** @brief Render and acknowledge the current foreground VT on a fresh read. + * @param state Borrowed cursor, serialized by the kernel execution transaction. + * @param offset Byte position. @param buffer Destination for up to capacity bytes. + * @param capacity Available bytes. @param read Receives the number copied. + * @return Zero or a negative sysfs error; zero-length reads do not acknowledge. + * Nonzero continuation offsets read the existing snapshot if it has been filled. + */ +static int sysfs_foreground_read(void *state, uint64_t offset, void *buffer, + uint32_t capacity, uint32_t *read) +{ + struct sysfs_foreground_view *view = state; + *read = 0; + if (!capacity) return 0; + if (!offset || !view->length) { + int rc = sysfs_read(SYSFS_TTY0_ACTIVE, 0, view->value, sizeof(view->value), &view->length); + if (rc) return rc; + view->generation = pty_vt_foreground_generation(); + } + if (offset < view->length) { + uint32_t count = view->length - (uint32_t)offset; + if (count > capacity) count = capacity; + __builtin_memcpy(buffer, view->value + offset, count); + *read = count; + } + return 0; +} + +/** @brief Report normal file readiness and unacknowledged foreground changes. + * @param state Borrowed per-description cursor. @param events Requested bits. + * @param consume Delivery hint; only a fresh read acknowledges this attribute. + * @param generation Optional output for the live change generation. + * @param ready Receives readiness, including unconditional POLLERR on change. + * @return True when the retained sysfs cursor handled the readiness query. + */ +static bool sysfs_foreground_poll(void *state, short events, bool consume, + uint64_t *generation, short *ready) +{ + (void)consume; + const struct sysfs_foreground_view *view = state; + uint64_t current = pty_vt_foreground_generation(); + if (generation) *generation = current; + *ready = events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM); + if (!view->length || view->generation != current) + *ready |= POLLERR | (events & POLLPRI); + return true; +} + +/** @brief Release the final reference's foreground notification cursor. + * @param state Owned capture, consumed once. + */ +static void sysfs_foreground_close(void *state) +{ + kernel_free(state); +} + +/** @brief Construct a detached sysfs mount with descriptor-authorized stores and VT events. * @param out Required empty output, receiving one owned mount on success. * @return Zero or negative errno with balanced generated inode identities. * Execution-owned task context; inventory stays immutable, while parameter @@ -68,7 +149,9 @@ int sysfs_create_vfs_mount(struct vfs_mount **out) static const struct vfs_pseudo_provider provider={.root="/sys",.filesystem="sysfs",.lookup=sysfs_lookup, .read=sysfs_read,.write=sysfs_parameter_write,.truncate=sysfs_parameter_truncate, .readdir=sysfs_readdir,.readlink=sysfs_readlink,.permissions=sysfs_parameter_permissions, - .get_identity=sysfs_key_identity,.identity_alive=sysfs_key_alive,.put_identity=sysfs_key_put + .get_identity=sysfs_key_identity,.identity_alive=sysfs_key_alive,.put_identity=sysfs_key_put, + .open=sysfs_foreground_open,.read_open=sysfs_foreground_read, + .poll_open=sysfs_foreground_poll,.close=sysfs_foreground_close }; return vfs_pseudo_mount_new(&provider,out); } diff --git a/fs/sysfs/sysfs.c b/fs/sysfs/sysfs.c index b692e47f..613959c4 100644 --- a/fs/sysfs/sysfs.c +++ b/fs/sysfs/sysfs.c @@ -6,12 +6,14 @@ #include #include #include +#include #include #include #include #include #include #include "../ext_common/storage_ext4_types.h" +#include "internal.h" #define SYSFS_PCI_MAX 256u static struct pci_device pci_devices[SYSFS_PCI_MAX]; @@ -28,6 +30,7 @@ enum attribute { A_DMI, A_CPUSET, A_CPU_ONLINE, + A_TTY_ACTIVE, A_PACKAGE, A_CORE, A_SIBLINGS, @@ -489,6 +492,15 @@ static int sys_walk(sys_visit visit, void *ctx) return ret; if ((ret = sys_emit(visit, ctx, "/sys/class/dmi/id", A_LINK, 0, "../../devices/virtual/dmi/id"))) return ret; + uint32_t foreground = pty_vt_active(); + if (foreground && + ((ret = sys_emit(visit, ctx, "/sys/class/tty", A_DIR, 0, NULL)) || + (ret = sys_emit(visit, ctx, "/sys/devices/virtual/tty", A_DIR, 0, NULL)) || + (ret = sys_emit(visit, ctx, "/sys/devices/virtual/tty/tty0", A_DIR, 0, NULL)) || + (ret = sys_emit(visit, ctx, "/sys/class/tty/tty0", A_LINK, 0, + "../../devices/virtual/tty/tty0")) || + (ret = sys_emit(visit, ctx, SYSFS_TTY0_ACTIVE, A_TTY_ACTIVE, foreground, NULL)))) + return ret; if((ret=sys_modules_walk(visit,ctx))) return ret; const struct platform_dmi_info *dmi = platform_dmi(); char path[RELIEFOS_FS_PATH_LEN], target[RELIEFOS_FS_PATH_LEN]; @@ -700,6 +712,10 @@ static void sys_value(const struct sys_node *n, struct text_stream *s) case A_MODULE_NUMBER: text_unsigned(s,n->value); break; + case A_TTY_ACTIVE: + text_string(s, "tty"); + text_unsigned(s, n->index); + break; case A_DMI: text_string(s, platform_dmi()->values[n->index]); break; diff --git a/include/reliefnt/pty.h b/include/reliefnt/pty.h index 831f28a4..1cfdd356 100644 --- a/include/reliefnt/pty.h +++ b/include/reliefnt/pty.h @@ -64,6 +64,11 @@ uint32_t pty_vt_active(void); * @return Generation incremented by visible VT switches and mode activations. */ uint64_t pty_vt_generation(void); +/** @brief Read the committed foreground VT notification generation. + * @return Generation unchanged by graphics mode changes or ungranted switches. + * Sample with pty_vt_active() in the same kernel execution transaction. + */ +uint64_t pty_vt_foreground_generation(void); /** @brief Request activation of a VT under the execution transaction. * @param number Virtual console number. * @return Zero on success or negative EINVAL. diff --git a/kernel/syscall/event/epoll.c b/kernel/syscall/event/epoll.c index 7e134257..73339fa3 100644 --- a/kernel/syscall/event/epoll.c +++ b/kernel/syscall/event/epoll.c @@ -4,16 +4,21 @@ /** * @brief Snapshot input progress for providers with edge-triggered readiness. * @param file Pinned watched description, or NULL for a PTY watch. + * @param progress_events Receives the ready bits refreshed by a new generation. * @return Provider, visible evdev or socket receive generation. * Execution-owned context. Evdev filtering matches read/poll and does not * expose other VTs, devices or exclusive grabs. No UAPI state is modified. */ -static uint64_t epoll_event_generation(const struct task_file *file) +static uint64_t epoll_event_generation(const struct task_file *file, uint32_t *progress_events) { uint64_t generation; short ready; - if (file && vfs_file_poll(file->provider_file, 0, false, &generation, &ready)) + *progress_events = EPOLLIN | EPOLLPRI | EPOLLRDNORM | EPOLLRDBAND | EPOLLMSG | EPOLLRDHUP; + if (file && vfs_file_poll(file->provider_file, 0, false, &generation, &ready)) { + /* Generated notifications may use only EPOLLERR (no interest bits). */ + *progress_events |= EPOLLERR; return generation; + } if (file && (file->flags & TASK_FILE_FLAG_DEV_NODE) && (file->node.first_cluster == STORAGE_DEV_KIND_MOUSE || file->node.first_cluster == STORAGE_DEV_KIND_KEYBOARD)) @@ -355,12 +360,11 @@ bool task_epoll_poll_ready(struct task *task, struct task_file *file) ready = poll_to_epoll(pollfd.revents); if (!ready) continue; - generation = epoll_event_generation(watch->file); if (entry->events & EPOLLET) { + uint32_t progress_events; + generation = epoll_event_generation(watch->file, &progress_events); uint32_t edge = ready & ~entry->ready; - uint32_t input = ready & (EPOLLIN | EPOLLPRI | EPOLLRDNORM | - EPOLLRDBAND | EPOLLMSG | EPOLLRDHUP); - if (input && generation != entry->generation) edge |= input; + if (generation != entry->generation) edge |= ready & progress_events; if (!edge) continue; } return true; @@ -584,7 +588,7 @@ static int64_t syscall_epoll_wait_common(struct task *task, struct task_epoll *e struct task_epoll_entry *entry = &epoll->item[i]; struct pollfd pollfd; uint32_t ready; - uint64_t generation; + uint64_t generation = 0; uint64_t deadline = task->poll_deadline_ticks; struct task_file *saved_file; struct task_pty_fd saved_pty; @@ -606,10 +610,9 @@ static int64_t syscall_epoll_wait_common(struct task *task, struct task_epoll *e if (timeout_ms != 0 && deadline) task->poll_deadline_ticks = deadline; ready = poll_to_epoll(pollfd.revents); - generation = ready ? epoll_event_generation(entry->watch ? entry->watch->file : NULL) : 0; if (!ready) { entry->ready = 0; - entry->generation = generation; + entry->generation = 0; continue; } uint32_t observed_ready=ready; @@ -620,13 +623,14 @@ static int64_t syscall_epoll_wait_common(struct task *task, struct task_epoll *e * readiness as a blanket suppression loses a later EPOLLIN edge * whenever Xorg registers EPOLLIN|EPOLLOUT together. */ + uint32_t progress_events; + generation = epoll_event_generation(entry->watch ? entry->watch->file : NULL, + &progress_events); uint32_t edge = ready & ~entry->ready; - uint32_t input = ready & (EPOLLIN | EPOLLPRI | EPOLLRDNORM | - EPOLLRDBAND | EPOLLMSG | EPOLLRDHUP); - /* A stream or evdev queue can drain and refill before the next - * probe. The readiness bit then never passes through zero, but - * the provider generation still records new visible input. */ - if (input && generation != entry->generation) edge |= input; + /* A provider or queue can drain and refill before the next probe. + * Its generation preserves the new edge even if the bit never + * appeared clear to this watch. */ + if (generation != entry->generation) edge |= ready & progress_events; if (!edge) { entry->ready = ready; entry->generation = generation; diff --git a/tools/test_linux_inventory.py b/tools/test_linux_inventory.py index f4f6af76..298ed366 100644 --- a/tools/test_linux_inventory.py +++ b/tools/test_linux_inventory.py @@ -11,7 +11,7 @@ def host(): run(['cc','-std=c11','-O1','-g','-fsanitize=address,undefined','-ffunction-sections','-fdata-sections','-Wl,--gc-sections', '-Iinclude','-Iinclude','-Iinclude/uapi', '-Iinclude','tools/tests/linux_inventory_test.c','fs/vfs/mount_tree.c', 'fs/vfs/lookup_cache.c', - 'fs/vfs/path.c','fs/vfs/mount_table.c','fs/vfs/file.c','fs/vfs/pseudo.c', 'fs/vfs/attributes.c','fs/proc/mount.c','fs/nsfs/namespace.c','fs/proc/views.c','kernel/syscall/fd/proc.c','fs/vfs/exec_file.c', + 'fs/vfs/path.c','fs/vfs/mount_table.c','fs/vfs/file.c','fs/vfs/open.c','fs/vfs/pseudo.c', 'fs/vfs/attributes.c','fs/proc/mount.c','fs/nsfs/namespace.c','fs/proc/views.c','kernel/syscall/fd/proc.c','fs/vfs/exec_file.c', 'fs/sysfs/mount.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','fs/security/access.c','-o',executable]) run([executable]) diff --git a/tools/tests/epoll_capacity_test.c b/tools/tests/epoll_capacity_test.c index 08eeafdb..8768259e 100644 --- a/tools/tests/epoll_capacity_test.c +++ b/tools/tests/epoll_capacity_test.c @@ -123,6 +123,7 @@ int64_t syscall_poll_park(struct task *task, int64_t timeout_ms, struct fixture_mount_view { uint64_t generation; uint64_t seen; + bool acknowledge_on_read; }; /** @brief Model a retained mount view with independent observation state. */ @@ -135,7 +136,7 @@ bool vfs_file_poll(struct vfs_open_file *file,short events,bool consume, *ready=events&(POLLIN|POLLRDNORM); if(view->seen!=view->generation) { *ready|=POLLERR|(events&POLLPRI); - if(consume)view->seen=view->generation; + if(consume && !view->acknowledge_on_read)view->seen=view->generation; } return true; } @@ -344,6 +345,34 @@ static void test_nested_mount_view(void) puts("PASS nested epoll mount view: retained event, repeated changes and no duplicate edge"); } +/** @brief Deliver new EPOLLERR edges for a read-acknowledged provider. */ +static void test_provider_error_edges(void) +{ + struct fixture_mount_view view={.generation=1,.seen=1,.acknowledge_on_read=true}; + struct task_epoll *epoll=calloc(1,sizeof(*epoll)); + struct task_file epoll_fd={.used=1,.flags=TASK_FILE_FLAG_EPOLL,.aux=(uintptr_t)epoll}; + struct task_file source={.used=1,.provider_file=(struct vfs_open_file *)&view}; + struct epoll_event event={.events=EPOLLET,.data=39},output; + assert(epoll); + current.limits.nofile.rlim_cur=TEST_FD_MAX; + descriptors[30]=&epoll_fd;descriptors[31]=&source; + assert(!syscall_epoll_ctl(30,EPOLL_CTL_ADD,31,(uintptr_t)&event)); + assert(!syscall_epoll_wait(30,(uintptr_t)&output,1,0)); + ++view.generation; + assert(syscall_epoll_wait(30,(uintptr_t)&output,1,0)==1 && output.events==EPOLLERR); + assert(!syscall_epoll_wait(30,(uintptr_t)&output,1,0)); + view.seen=view.generation; + /* The next event may arrive before epoll observes that read's drain. */ + ++view.generation; + assert(task_epoll_poll_ready(¤t,&epoll_fd)); + assert(syscall_epoll_wait(30,(uintptr_t)&output,1,0)==1 && output.events==EPOLLERR); + assert(!task_epoll_poll_ready(¤t,&epoll_fd)); + task_epoll_destroy(epoll); + descriptors[30]=descriptors[31]=NULL; + current=(struct task){0};kernel_free_calls=0; + puts("PASS epoll provider errors: zero interest mask and repeated generation edges"); +} + int main(void) { struct task_epoll *epoll; @@ -352,6 +381,7 @@ int main(void) test_nested_epoll(); test_nested_mount_view(); + test_provider_error_edges(); test_evdev_edges(); memset(¤t, 0, sizeof(current)); current.pid = 1; diff --git a/tools/tests/linux_inventory_test.c b/tools/tests/linux_inventory_test.c index c46ce61f..5577fc75 100644 --- a/tools/tests/linux_inventory_test.c +++ b/tools/tests/linux_inventory_test.c @@ -14,6 +14,20 @@ #include static unsigned fixture_cpus=1; +static uint32_t fixture_foreground; +static uint64_t fixture_foreground_generation; + +/** @brief Supply the foreground VT exposed by the fixture's display driver. */ +uint32_t pty_vt_active(void) +{ + return fixture_foreground; +} + +/** @brief Supply the fixture display driver's committed-switch generation. */ +uint64_t pty_vt_foreground_generation(void) +{ + return fixture_foreground_generation; +} static bool fixture_drm_present; static bool fixture_render_present; static bool fixture_kms_enabled; @@ -191,6 +205,70 @@ static void walk(const char *path, unsigned depth) assert(ret == 0); } +/** @brief Exercise the actual sysfs VFS provider with logind-style polls. */ +static void check_foreground_sysfs(void) +{ + struct storage_node node; + assert(sysfs_lookup("/sys/devices/virtual/tty/tty0/active", &node) == -ENOENT); + fixture_foreground = 1; + fixture_foreground_generation = 1; + + struct vfs_mount *mount = NULL; + struct vfs_namespace ns = {0}; + struct vfs_path root = {0}, active = {0}, canonical = {0}; + assert(!sysfs_create_vfs_mount(&mount)); + assert(!vfs_namespace_init(&ns, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns, &root)); + assert(!vfs_path_lookup(&ns, &root, &root, "class/tty/tty0/active", + VFS_LOOKUP_FOLLOW, &active)); + assert(!vfs_path_lookup(&ns, &root, &root, "devices/virtual/tty/tty0/active", + VFS_LOOKUP_FOLLOW, &canonical)); + assert(vfs_path_same_inode(&active, &canonical)); + struct reliefos_permissions mode; + assert(!vfs_path_permissions(&active, &mode, false) && mode.mode == 0444); + + struct vfs_open_file *first = NULL, *second = NULL; + assert(!vfs_file_open(&active, 0, &first) && first); + assert(!vfs_file_open(&canonical, 0, &second) && second); + char buf[8]; + uint32_t got; + short ready; + assert(vfs_file_poll(first, POLLPRI, true, NULL, &ready) && ready == (POLLERR | POLLPRI)); + assert(!vfs_file_read(first, 0, buf, 0, &got) && !got); + assert(vfs_file_poll(first, 0, false, NULL, &ready) && ready == POLLERR); + assert(!vfs_file_read(first, 0, buf, 3, &got) && got == 3 && !memcmp(buf, "tty", 3)); + assert(vfs_file_poll(first, POLLIN, false, NULL, &ready) && ready == POLLIN); + assert(vfs_file_poll(second, 0, false, NULL, &ready) && ready == POLLERR); + + fixture_foreground = 2; + ++fixture_foreground_generation; + assert(vfs_file_poll(first, 0, true, NULL, &ready) && ready == POLLERR); + assert(!vfs_file_read(first, 3, buf, sizeof(buf), &got) && got == 2 && !memcmp(buf, "1\n", 2)); + assert(vfs_file_poll(first, 0, false, NULL, &ready) && ready == POLLERR); + assert(!vfs_file_read(first, 0, buf, sizeof(buf), &got) && got == 5 && !memcmp(buf, "tty2\n", 5)); + assert(vfs_file_poll(first, 0, false, NULL, &ready) && !ready); + assert(vfs_file_poll(second, POLLPRI, false, NULL, &ready) && ready == (POLLERR | POLLPRI)); + + /* Switching away and back without a poll must not hide the update. */ + fixture_foreground = 3; + ++fixture_foreground_generation; + fixture_foreground = 2; + ++fixture_foreground_generation; + assert(vfs_file_poll(first, 0, false, NULL, &ready) && ready == POLLERR); + assert(!vfs_file_read(first, 0, buf, sizeof(buf), &got) && got == 5 && !memcmp(buf, "tty2\n", 5)); + assert(vfs_file_poll(first, 0, false, NULL, &ready) && !ready); + assert(vfs_file_poll(second, 0, false, NULL, &ready) && ready == POLLERR); + + vfs_file_close(second); + vfs_file_close(first); + vfs_path_put(&canonical); + vfs_path_put(&active); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns)); + puts("PASS sysfs foreground VT: class alias, per-open reads and zero-mask notifications"); +} + /** @brief Resolve a block identity from its rdev and classify its subsystem. */ static void check_block_subsystem(const char *device, const char *expected) { @@ -218,6 +296,7 @@ static void check_block_subsystem(const char *device, const char *expected) int main(void) { cpu_inventory_capture(0); + check_foreground_sysfs(); char value[16384]; struct storage_node node; assert(proc_lookup("/sys/dev/block", &node) == 0 && node.type == RELIEFOS_FS_TYPE_DIR); diff --git a/tools/tests/linux_pty_test.c b/tools/tests/linux_pty_test.c index 6df90ca2..d9da4e56 100644 --- a/tools/tests/linux_pty_test.c +++ b/tools/tests/linux_pty_test.c @@ -12,7 +12,7 @@ int console_prepare_vt(bool graphics) { (void)graphics; return 0; } static struct task owner; static unsigned signals; -static unsigned blocked, awakened; +static unsigned blocked, awakened, poll_wakes; void *kernel_malloc(size_t size) { return malloc(size); } void kernel_free(void *memory) { free(memory); } void kernel_spin_init(struct kernel_spinlock *lock) { lock->state = 0; } @@ -25,7 +25,8 @@ void kernel_wait_queue_init(struct kernel_wait_queue *q) { memset(q, 0, sizeof(* void kernel_wait_queue_remove(struct kernel_wait_queue *q, struct task *t) { (void)q; (void)t; } void kernel_wait_queue_block_current(struct kernel_wait_queue *q) { (void)q; ++blocked; } uint32_t kernel_wait_queue_wake_all(struct kernel_wait_queue *q) { (void)q; ++awakened; return 1; } -void kernel_poll_readiness_notify(void) { } +/** @brief Count readiness wakeups sent by the real PTY implementation. */ +void kernel_poll_readiness_notify(void) { ++poll_wakes; } static unsigned descriptor_refs = 1; static uint8_t keyboard_caps, keyboard_num; uint8_t input_caps_lock_active(void) { return keyboard_caps; } @@ -479,8 +480,12 @@ int main(void) assert(pty_vt_wait_active(2) == KERNEL_SYSCALL_BLOCKED && blocked == 1); unsigned before_wake = awakened; uint64_t generation = pty_vt_generation(); + uint64_t foreground = pty_vt_foreground_generation(); + unsigned before_poll_wake = poll_wakes; assert(pty_vt_switch(2) == 0 && awakened == before_wake + 1); + assert(poll_wakes == before_poll_wake + 1); assert(pty_vt_generation() == generation + 1); + assert(pty_vt_foreground_generation() == foreground + 1); assert(pty_vt_wait_active(2) == 0); assert(pty_vt_switch(1) == 0); assert(pty_vt_switch(0) == -22 && pty_vt_active() == 1); @@ -495,16 +500,20 @@ int main(void) owner.process_group = owner.pid; owner.controlling_pty_id = 1; assert(pty_vt_set_mode(1, &controller) == 0); + foreground = pty_vt_foreground_generation(); assert(pty_vt_set_graphics(1, 1) == 0); signals = 0; assert(pty_vt_switch(2) == 0); assert(pty_vt_active() == 1 && pty_vt_graphical_active()); /* held */ assert(signals == 1); /* relsig */ + assert(pty_vt_foreground_generation() == foreground); assert(pty_vt_release_display(1, 0) == 0); /* refuse */ assert(pty_vt_active() == 1 && pty_vt_graphical_active()); assert(pty_vt_switch(2) == 0); assert(signals == 2); + assert(pty_vt_foreground_generation() == foreground); assert(pty_vt_release_display(1, 1) == 0); /* grant */ + assert(pty_vt_foreground_generation() == foreground + 1); assert(pty_vt_active() == 2 && !pty_vt_graphical_active()); assert(pty_vt_get_mode(2, &probe) == 0 && probe.mode == VT_AUTO); signals = 0; From dad94f0c72c80919e404f0eaf1b3e5f1ac80098a Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 19:43:21 +0800 Subject: [PATCH 44/97] fix(cgroup): preserve independent control inode permissions --- .../userspace-api/device-filesystems.po | 3 + .../userspace-api/device-filesystems.po | 3 + .../userspace-api/device-filesystems.rst | 5 + fs/cgroup/filesystem.c | 130 +++++++++++++++--- fs/cgroup/hierarchy.c | 11 +- fs/cgroup/internal.h | 14 +- tools/tests/mount_backend_test.c | 43 ++++++ 7 files changed, 184 insertions(+), 25 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 27fa5fa1..3c5d3a3a 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -232,6 +232,9 @@ msgstr "" "An administrator can create a group with ``mkdir`` and remove a non-root " "group with no live tasks or children using ``rmdir``." +msgid "控制组目录与每个控制文件分别保存所有者、组和权限位。通过标准 ``chmod``/``chown`` 变更某个 inode 不会影响同组的其他 inode;只读挂载 拒绝变更。控制器停用并重新启用时生成新的控制文件,旧文件的权限不会继承。 可写操作仍须有内核实现,且修改层级或控制值仍要求 ``CAP_SYS_ADMIN``。" +msgstr "A cgroup directory and each control file keep independent ownership and mode bits. Standard ``chmod`` and ``chown`` affect only the selected inode; read-only mounts reject changes. Disabling and re-enabling a controller creates new control files without inheriting old permissions. A write operation must still be implemented by the kernel, and hierarchy or control-value changes still require ``CAP_SYS_ADMIN``." + msgid "成员与事件" msgstr "Membership and events" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index 2564a5d8..10d5197c 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -205,6 +205,9 @@ msgstr "" "の識別情報を共有し、最後のマウントを解除しても再マウント時に同じ階層が見えます。読み取り専用などのポリシーはマウントごとに独立しています。管理者は" " ``mkdir`` でグループを作成し、稼働中のタスクや子グループのない非ルートグループを ``rmdir`` で削除できます。" +msgid "控制组目录与每个控制文件分别保存所有者、组和权限位。通过标准 ``chmod``/``chown`` 变更某个 inode 不会影响同组的其他 inode;只读挂载 拒绝变更。控制器停用并重新启用时生成新的控制文件,旧文件的权限不会继承。 可写操作仍须有内核实现,且修改层级或控制值仍要求 ``CAP_SYS_ADMIN``。" +msgstr "コントロールグループのディレクトリと各制御ファイルは、所有者・グループ・モードビットを個別に保持します。標準の ``chmod`` と ``chown`` が変更するのは指定した inode だけです。読み取り専用マウントでは変更できません。コントローラーを無効化して再び有効にすると、古い権限を引き継がない新しい制御ファイルが作成されます。書き込み操作にはカーネルの実装が必要で、階層や制御値の変更には引き続き ``CAP_SYS_ADMIN`` が必要です。" + msgid "成员与事件" msgstr "所属とイベント" diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 1208fd5f..9d228a50 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -123,6 +123,11 @@ cgroup v2 策略独立。管理员可以用 ``mkdir`` 创建控制组,用 ``rmdir`` 删除没有活任务和 子组的非根组。 +控制组目录与每个控制文件分别保存所有者、组和权限位。通过标准 +``chmod``/``chown`` 变更某个 inode 不会影响同组的其他 inode;只读挂载 +拒绝变更。控制器停用并重新启用时生成新的控制文件,旧文件的权限不会继承。 +可写操作仍须有内核实现,且修改层级或控制值仍要求 ``CAP_SYS_ADMIN``。 + 成员与事件 ---------- diff --git a/fs/cgroup/filesystem.c b/fs/cgroup/filesystem.c index 488c3cf3..5c0573cf 100644 --- a/fs/cgroup/filesystem.c +++ b/fs/cgroup/filesystem.c @@ -12,6 +12,17 @@ #define CGROUP_COMMAND_MAX 4095u _Static_assert(CG_FILE_COUNT <= (1u << CGROUP_FILE_SHIFT), "cgroup inode file bits"); +/* Exact control-inode metadata survives dentry churn and controller retirement + * while pinned. Unmodified, unpinned controls can use their creation defaults. */ +struct cgroup_control_metadata { + struct cgroup_control_metadata *next; + struct cgroup *group; + uint64_t key; + uint32_t pins; + bool changed; + struct reliefos_permissions mode; +}; + static const struct vfs_backend_ops cgroup_ops; static const struct cgroup_control { const char *name; @@ -82,28 +93,84 @@ static int cgroup_lookup(void *context, const struct storage_node *parent, const return -ENOENT; } -/** @brief Pin the actual group for one dentry or control file. */ +/** @brief Find the shared metadata slot of an exact control incarnation. + * @param group Live group under execution ownership. + * @param key Immutable cgroup inode key. @return Borrowed list slot. + */ +static struct cgroup_control_metadata **cgroup_metadata_slot(struct cgroup *group, uint64_t key) +{ + struct cgroup_control_metadata **slot = &group->metadata; + while (*slot && (*slot)->key != key) slot = &(*slot)->next; + return slot; +} + +/** @brief Compute an unmodified control's original metadata. + * @param group Borrowed live group. @param file Live control selector. + * @return Default mode and publication-time owner, not directory ownership. + */ +static struct reliefos_permissions cgroup_control_default(const struct cgroup *group, + enum cgroup_file file) +{ + return (struct reliefos_permissions){controls[file].writable ? 0644u : 0444u, + file < CG_PIDS_MAX ? group->control_uid : group->pids_uid, + file < CG_PIDS_MAX ? group->control_gid : group->pids_gid}; +} + +/** @brief Pin the group and, for controls, shared exact-inode metadata. */ static int cgroup_retain(void *context, const struct storage_node *node, void **pin) { (void)context; *pin = NULL; struct cgroup *g = cgroup_find(node->first_cluster); if (!node_live(g, node)) return -ENOENT; + enum cgroup_file file = node_file(node); + if (file == CG_DIR) *pin = g; + else { + struct cgroup_control_metadata **slot = cgroup_metadata_slot(g, node->entry_id); + if (!*slot) { + struct cgroup_control_metadata *meta = kernel_malloc(sizeof(*meta)); + if (!meta) return -ENOMEM; + *meta = (struct cgroup_control_metadata){.group=g,.key=node->entry_id, + .mode=cgroup_control_default(g, file)}; + *slot = meta; + } + ++(*slot)->pins; + *pin = *slot; + } uint64_t flags; kernel_spin_lock_irqsave(&scheduler_lock, &flags); cgroup_get_locked(g); kernel_spin_unlock_irqrestore(&scheduler_lock, flags); - *pin = g; return 0; } -/** @brief Release the inode pin independently of its current name and visibility. */ +/** @brief Free metadata once neither a live override nor an inode pin needs it. + * @param group Owning group under execution ownership. @param node Exact key. + * @param meta Borrowed record, whose storage may be freed before return. + */ +static void cgroup_metadata_drop(struct cgroup *group, const struct storage_node *node, + struct cgroup_control_metadata *meta) +{ + if (meta->pins || (meta->changed && node_live(group, node))) return; + struct cgroup_control_metadata **slot = cgroup_metadata_slot(group, meta->key); + *slot = meta->next; + kernel_free(meta); +} + +/** @brief Release the inode and metadata pins independent of the live name. */ static void cgroup_release(void *context, const struct storage_node *node, void *pin) { - (void)context; (void)node; + (void)context; + struct cgroup *group = pin; + if (node_file(node) != CG_DIR) { + struct cgroup_control_metadata *meta = pin; + group = meta->group; + --meta->pins; + cgroup_metadata_drop(group, node, meta); + } uint64_t flags; kernel_spin_lock_irqsave(&scheduler_lock, &flags); - cgroup_put_locked(pin); + cgroup_put_locked(group); kernel_spin_unlock_irqrestore(&scheduler_lock, flags); cgroup2_kick(); } @@ -120,13 +187,21 @@ static bool cgroup_admin(void) } /** @brief Return directory or control metadata for a retained inode key. */ -static struct reliefos_permissions cgroup_mode(const struct cgroup *g, enum cgroup_file file) +static struct reliefos_permissions cgroup_mode(struct cgroup *group, const struct storage_node *node) { - if (file == CG_DIR) return g->mode; - return (struct reliefos_permissions){controls[file].writable ? 0644u : 0444u, g->mode.uid, g->mode.gid}; + enum cgroup_file file = node_file(node); + if (file == CG_DIR) return group->mode; + struct cgroup_control_metadata *meta = *cgroup_metadata_slot(group, node->entry_id); + return meta ? meta->mode : cgroup_control_default(group, file); } -/** @brief Expose DAC metadata and allow only privileged directory attribute changes. */ +/** @brief Read or persist the exact live inode's VFS-authorized DAC metadata. + * @param context Shared hierarchy context. @param path Pinned directory or control. + * @param value Receives metadata, or supplies the already authorized change. + * @param write True to update metadata. @return Zero, ENODEV or EROFS. + * Directory updates never affect control inodes, and changing a control's + * attributes does not change its supported operations. + */ static int cgroup_permissions(void *context, const struct vfs_path *path, struct reliefos_permissions *value, bool write) { @@ -135,10 +210,17 @@ static int cgroup_permissions(void *context, const struct vfs_path *path, struct cgroup *g = cgroup_find(node->first_cluster); if (!node_live(g, node)) return -ENODEV; enum cgroup_file file = node_file(node); - if (!write) { *value = cgroup_mode(g, file); return 0; } + if (!write) { *value = cgroup_mode(g, node); return 0; } if (vfs_path_mount_flags(path) & MS_RDONLY) return -EROFS; - if (file != CG_DIR || !cgroup_admin()) return -EPERM; - g->mode = (struct reliefos_permissions){value->mode & 0777u, value->uid, value->gid}; + struct reliefos_permissions mode = {value->mode & 07777u, value->uid, value->gid}; + if (file == CG_DIR) g->mode = mode; + else { + /* A retained path has already materialized the exact inode record. */ + struct cgroup_control_metadata *meta = *cgroup_metadata_slot(g, node->entry_id); + if (!meta) return -ENODEV; + meta->mode = mode; + meta->changed = true; + } return 0; } @@ -147,10 +229,10 @@ static int cgroup_stat(void *context, const struct vfs_path *path, struct linux_ { (void)context; const struct storage_node *node = vfs_path_node(path); - const struct cgroup *g = cgroup_find(node->first_cluster); + struct cgroup *g = cgroup_find(node->first_cluster); enum cgroup_file file = node_file(node); if (!g || file >= CG_FILE_COUNT) return -ENOENT; - struct reliefos_permissions mode = cgroup_mode(g, file); + struct reliefos_permissions mode = cgroup_mode(g, node); uint64_t links = 0; if (node_live(g, node)) { links = file == CG_DIR ? 2 : 1; @@ -187,13 +269,18 @@ static int cgroup_create(void *context, const struct storage_node *parent, const return pin ? cgroup_retain(context, out, pin) : 0; } -/** @brief Retire the weak watches of every file in a removed controller incarnation. */ -static void cgroup_remove_files(const struct cgroup *g, enum cgroup_file first, uint32_t epoch) +/** @brief Retire watches and unpinned metadata for removed control incarnations. + * @param g Owning group. @param first First retired selector. + * @param epoch Controller generation at removal, before re-publication. + */ +static void cgroup_remove_files(struct cgroup *g, enum cgroup_file first, uint32_t epoch) { - if (!fsnotify_has_watches()) return; + bool watches = fsnotify_has_watches(); for (enum cgroup_file file = first; file < CG_FILE_COUNT; ++file) { struct storage_node key = cgroup_node(g, file, epoch); - cgroup_notify(&key, true); + struct cgroup_control_metadata *meta = *cgroup_metadata_slot(g, key.entry_id); + if (meta) cgroup_metadata_drop(g, &key, meta); + if (watches) cgroup_notify(&key, true); } } @@ -437,13 +524,16 @@ static int cgroup_write(void *context, struct storage_node *node, uint64_t offse uint64_t flags; kernel_spin_lock_irqsave(&scheduler_lock, &flags); uint32_t retired_epoch = !enable && g->subtree_pids ? g->pids_epoch : 0; - if (file == CG_SUBTREE && enable >= 0) rc = cgroup_set_subtree_locked(g, enable); + if (file == CG_SUBTREE && enable >= 0) { + const struct task *caller = sched_current_task(); + rc = cgroup_set_subtree_locked(g, enable, caller ? caller->fsuid : 0, caller ? caller->fsgid : 0); + } else if (file == CG_PROCS) rc = cgroup_move_locked(g, value); else if (file == CG_PIDS_MAX) g->limit = limit; kernel_spin_unlock_irqrestore(&scheduler_lock, flags); if (rc) return rc; if (retired_epoch) - for (const struct cgroup *child = g->children; child; child = child->sibling) + for (struct cgroup *child = g->children; child; child = child->sibling) cgroup_remove_files(child, CG_PIDS_MAX, retired_epoch); cgroup2_kick(); *written = length; diff --git a/fs/cgroup/hierarchy.c b/fs/cgroup/hierarchy.c index ae51c5b4..e2de9e1d 100644 --- a/fs/cgroup/hierarchy.c +++ b/fs/cgroup/hierarchy.c @@ -67,7 +67,8 @@ int cgroup_mkdir(struct cgroup *parent, const char *name, const struct reliefos_ struct cgroup *g = kernel_malloc(sizeof(*g) + n + 1); if (!g) return -ENOMEM; *g = (struct cgroup){.parent=parent,.refs=1,.linked=true,.limit=CGROUP_PIDS_UNLIMITED, - .mode={mode->mode & 0777u,mode->uid,mode->gid},.id=++last_id, + .mode={mode->mode & 07777u,mode->uid,mode->gid},.id=++last_id, + .control_uid=mode->uid,.control_gid=mode->gid,.pids_uid=mode->uid,.pids_gid=mode->gid, .path_length=(uint16_t)(parent->path_length+1+n),.depth=(uint16_t)(parent->depth+1)}; __builtin_memcpy(g->name, name, n+1); uint64_t flags; @@ -108,8 +109,8 @@ int cgroup_rmdir(struct cgroup *g) bool cgroup_pids_enabled(const struct cgroup *g) { return g->parent && g->parent->subtree_pids; } -/** @brief Change the state of all direct pids children in one locked transaction. */ -int cgroup_set_subtree_locked(struct cgroup *g, bool enabled) +/** @copydoc cgroup_set_subtree_locked */ +int cgroup_set_subtree_locked(struct cgroup *g, bool enabled, uint32_t uid, uint32_t gid) { if (g->subtree_pids == enabled) return 0; if (enabled && g->parent && !cgroup_pids_enabled(g)) return -ENOENT; @@ -122,6 +123,10 @@ int cgroup_set_subtree_locked(struct cgroup *g, bool enabled) child->limit = CGROUP_PIDS_UNLIMITED; child->events = child->local_events = 0; child->peak = child->charged; + if (enabled) { + child->pids_uid = uid; + child->pids_gid = gid; + } } if (enabled) ++g->pids_epoch; g->subtree_pids = enabled; diff --git a/fs/cgroup/internal.h b/fs/cgroup/internal.h index 8d9e6fb7..26f13920 100644 --- a/fs/cgroup/internal.h +++ b/fs/cgroup/internal.h @@ -16,6 +16,8 @@ enum cgroup_file { CG_PIDS_MAX, CG_PIDS_CURRENT, CG_PIDS_PEAK, CG_PIDS_EVENTS, CG_PIDS_LOCAL, CG_FILE_COUNT, }; +struct cgroup_control_metadata; + /* Topology/index and VFS operations require the execution writer. All task * membership, counters, controller state, refs and pending bits are also * serialized by scheduler_lock, including updates from remote task exit. */ @@ -26,6 +28,8 @@ struct cgroup { uint16_t path_length, depth, pending; bool linked, subtree_pids, queued; struct reliefos_permissions mode; + struct cgroup_control_metadata *metadata; + uint32_t control_uid, control_gid, pids_uid, pids_gid; char name[]; }; @@ -45,8 +49,14 @@ void cgroup_get_locked(struct cgroup *group); void cgroup_put_locked(struct cgroup *group); /** @brief Test controller availability while holding scheduler_lock. */ bool cgroup_pids_enabled(const struct cgroup *group); -/** @brief Switch child controller visibility atomically with fork admission. */ -int cgroup_set_subtree_locked(struct cgroup *group, bool enabled); +/** @brief Switch child controller visibility atomically with fork admission. + * @param group Borrowed live group under scheduler_lock. + * @param enabled Whether to enable pids in its children. + * @param uid Filesystem UID assigned to newly published pids controls. + * @param gid Filesystem GID assigned to newly published pids controls. + * @return Zero or negative errno without a partial controller change. + */ +int cgroup_set_subtree_locked(struct cgroup *group, bool enabled, uint32_t uid, uint32_t gid); /** @brief Move the live thread group identified by PID or TID under scheduler_lock. */ int cgroup_move_locked(struct cgroup *destination, uint32_t pid); /** @brief Identify a live, published user thread in the locked task table. */ diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 52f0182f..91d9e035 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2905,6 +2905,47 @@ static void cgroup_expect_event(struct fsnotify_instance *instance,int wd,uint32 fsnotify_pop(instance); } +/** @brief Change a delegated directory and its controls through normal DAC. */ +static void cgroup_control_metadata(struct task *actor,const struct vfs_path *group, + const struct vfs_path *alias) +{ + struct task delegate={.kind=TASK_KIND_USER,.fsuid=1500,.fsgid=1500}; + struct task outsider={.kind=TASK_KIND_USER,.fsuid=1501,.fsgid=1501}; + struct vfs_path procs={0},procs_ro={0},events={0},subtree={0},pids={0}; + struct linux_stat_abi stat; + assert(!vfs_path_lookup_child(group,"cgroup.procs",&procs)); + assert(!vfs_path_lookup_child(alias,"cgroup.procs",&procs_ro)); + assert(!vfs_path_lookup_child(group,"cgroup.events",&events)); + assert(!vfs_path_lookup_child(group,"cgroup.subtree_control",&subtree)); + assert(!vfs_path_lookup_child(group,"pids.max",&pids)); + + actor->cap_effective|=(1ULL<cap_effective=1ULL< Date: Sun, 29 Nov 2026 20:04:45 +0800 Subject: [PATCH 45/97] fix(epoll): refresh unix stream write edges on peer drain --- .../LC_MESSAGES/userspace-api/descriptors.po | 10 +++ .../LC_MESSAGES/userspace-api/descriptors.po | 9 +++ Documentation/userspace-api/descriptors.rst | 4 + include/reliefnt/syscall_internal.h | 6 ++ kernel/syscall/event/epoll.c | 60 +++++++++------ kernel/syscall/internal.h | 1 + kernel/syscall/ipc/socket.c | 27 +++++++ tools/tests/epoll_capacity_test.c | 2 + tools/tests/poll_wakeup_test.c | 73 ++++++++++++++++++- tools/tests/task8_epoll_user_test.c | 2 + 10 files changed, 166 insertions(+), 28 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index da252fbb..50d22da8 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -205,6 +205,16 @@ msgstr "" "removed when the last reference to the target open file description is " "closed." +msgid "" +"对 ``AF_UNIX`` 流套接字,对端读空接收队列或让满队列腾出空间时,边沿触发的 监听会重新收到 " +"``EPOLLOUT``,即使两次等待之间没有观察到不可写状态。 预读不产生发送通知;只有新输入时不会额外返回 ``EPOLLOUT``。" +msgstr "" +"When the peer of an ``AF_UNIX`` stream socket empties its receive " +"queue or frees space in a full queue, an edge-triggered watch receives" +" ``EPOLLOUT`` again, even if neither wait observed it as non-writable." +" Peeking does not generate a transmit notification, and incoming data " +"alone does not report ``EPOLLOUT`` again." + msgid "ppoll 与信号掩码" msgstr "ppoll and Signal Masks" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index 66aa466d..a59ed7a9 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -178,6 +178,15 @@ msgstr "" "を返します。直接または ``dup`` で複製した記述子を介して自分自身を監視しようとすると ``EINVAL`` " "を返します。監視対象のオープンファイル記述に対する最後の参照が閉じられると、監視項目は削除されます。" +msgid "" +"对 ``AF_UNIX`` 流套接字,对端读空接收队列或让满队列腾出空间时,边沿触发的 监听会重新收到 " +"``EPOLLOUT``,即使两次等待之间没有观察到不可写状态。 预读不产生发送通知;只有新输入时不会额外返回 ``EPOLLOUT``。" +msgstr "" +"``AF_UNIX`` " +"ストリームソケットの対向側が受信キューを空にするか、満杯だったキューに空きができると、二度の待機で書き込み不可を観測していなくても、エッジトリガーの監視に再び" +" ``EPOLLOUT`` が通知されます。先読みでは送信通知は発生せず、新しい入力だけでは ``EPOLLOUT`` " +"が再通知されることもありません。" + msgid "ppoll 与信号掩码" msgstr "ppoll とシグナルマスク" diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index 558fcccd..429b1be1 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -94,6 +94,10 @@ evdev 进度只取对应设备、VT 和 OFD grab 可见的事件;另一终端 监视关系;形成环或超出深度时返回 ``ELOOP``。直接或经 ``dup`` 别名监视 自身返回 ``EINVAL``;目标的最后一个打开文件描述引用关闭后移除监视项。 +对 ``AF_UNIX`` 流套接字,对端读空接收队列或让满队列腾出空间时,边沿触发的 +监听会重新收到 ``EPOLLOUT``,即使两次等待之间没有观察到不可写状态。 +预读不产生发送通知;只有新输入时不会额外返回 ``EPOLLOUT``。 + ppoll 与信号掩码 ================ diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index 3faeb203..ed1bb7b8 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -609,6 +609,12 @@ short task_socket_poll(const struct task_file *file, short events); * @return Monotonic receive generation, or zero for non-UNIX sockets. */ uint64_t task_socket_event_generation(const struct task_file *file); +/** + * @brief Snapshot peer drain progress for write edges on AF_UNIX streams. + * @param file Retained socket open file description, or NULL. + * @return Monotonic transmit wake generation, or zero for other sockets. + */ +uint64_t task_socket_write_generation(const struct task_file *file); /** * @brief Handle Unix socket ioctls with native usercopy and error semantics. * @param file Retained Unix socket open file description. diff --git a/kernel/syscall/event/epoll.c b/kernel/syscall/event/epoll.c index 73339fa3..419a6c31 100644 --- a/kernel/syscall/event/epoll.c +++ b/kernel/syscall/event/epoll.c @@ -27,6 +27,28 @@ static uint64_t epoll_event_generation(const struct task_file *file, uint32_t *p return task_socket_event_generation(file); } +/** + * @brief Determine which ready bits are new for an edge-triggered registration. + * @param entry Watched registration; does not consume or mutate it. + * @param file Pinned watched description, or NULL for a PTY. + * @param ready Current epoll readiness bits. + * @param generation Receives the current input/provider generation. + * @param write_generation Receives the current socket write-wake generation. + * @return Ready bits not previously delivered or refreshed by provider progress. + */ +static uint32_t epoll_new_edges(const struct task_epoll_entry *entry, + const struct task_file *file, uint32_t ready, + uint64_t *generation, uint64_t *write_generation) +{ + uint32_t progress_events; + *generation = epoll_event_generation(file, &progress_events); + *write_generation = task_socket_write_generation(file); + uint32_t edge = ready & ~entry->ready; + if (*generation != entry->generation) edge |= ready & progress_events; + if (*write_generation != entry->write_generation) edge |= ready & EPOLLOUT; + return edge; +} + /** @brief Prepare exactly one bounded epoll operand at the outer syscall gate. * @param task Current task. @param address User operand. @param size Bytes. * @param writing Output access when true. @return Zero, EFAULT, or private @@ -337,7 +359,7 @@ bool task_epoll_poll_ready(struct task *task, struct task_file *file) struct task_pty_fd saved_pty; int saved_fd; uint32_t ready; - uint64_t generation; + uint64_t generation, write_generation; if (!entry->active || entry->disabled || !watch || (!watch->file && !watch->pty)) @@ -360,13 +382,9 @@ bool task_epoll_poll_ready(struct task *task, struct task_file *file) ready = poll_to_epoll(pollfd.revents); if (!ready) continue; - if (entry->events & EPOLLET) { - uint32_t progress_events; - generation = epoll_event_generation(watch->file, &progress_events); - uint32_t edge = ready & ~entry->ready; - if (generation != entry->generation) edge |= ready & progress_events; - if (!edge) continue; - } + if ((entry->events & EPOLLET) && + !epoll_new_edges(entry, watch->file, ready, &generation, &write_generation)) + continue; return true; } task->poll_deadline_ticks = saved_deadline; @@ -539,6 +557,7 @@ int64_t syscall_epoll_ctl(uint64_t epfd_arg, uint64_t op_arg, epoll->item[found].ready = 0; epoll->item[found].disabled = 0; epoll->item[found].generation = 0; + epoll->item[found].write_generation = 0; kernel_poll_readiness_notify(); goto out; } @@ -588,7 +607,7 @@ static int64_t syscall_epoll_wait_common(struct task *task, struct task_epoll *e struct task_epoll_entry *entry = &epoll->item[i]; struct pollfd pollfd; uint32_t ready; - uint64_t generation = 0; + uint64_t generation = 0, write_generation = 0; uint64_t deadline = task->poll_deadline_ticks; struct task_file *saved_file; struct task_pty_fd saved_pty; @@ -612,28 +631,20 @@ static int64_t syscall_epoll_wait_common(struct task *task, struct task_epoll *e ready = poll_to_epoll(pollfd.revents); if (!ready) { entry->ready = 0; - entry->generation = 0; + entry->generation = entry->write_generation = 0; continue; } uint32_t observed_ready=ready; if (entry->events & EPOLLET) { - /* - * Edge-triggered readiness is tracked per event bit. A UNIX - * stream socket is normally writable, so treating any previous - * readiness as a blanket suppression loses a later EPOLLIN edge - * whenever Xorg registers EPOLLIN|EPOLLOUT together. - */ - uint32_t progress_events; - generation = epoll_event_generation(entry->watch ? entry->watch->file : NULL, - &progress_events); - uint32_t edge = ready & ~entry->ready; - /* A provider or queue can drain and refill before the next probe. - * Its generation preserves the new edge even if the bit never - * appeared clear to this watch. */ - if (generation != entry->generation) edge |= ready & progress_events; + /* Per-direction progress also catches a transition that began + * and ended between two probes. Input never refreshes output. */ + uint32_t edge = epoll_new_edges(entry, + entry->watch ? entry->watch->file : NULL, ready, + &generation, &write_generation); if (!edge) { entry->ready = ready; entry->generation = generation; + entry->write_generation = write_generation; continue; } ready = edge; @@ -654,6 +665,7 @@ static int64_t syscall_epoll_wait_common(struct task *task, struct task_epoll *e if (entry->events & EPOLLET) { entry->ready = observed_ready; entry->generation = generation; + entry->write_generation = write_generation; } else entry->ready = ready; if (entry->events & EPOLLONESHOT) entry->disabled = 1; } diff --git a/kernel/syscall/internal.h b/kernel/syscall/internal.h index a22a2a3a..299bc0f9 100644 --- a/kernel/syscall/internal.h +++ b/kernel/syscall/internal.h @@ -125,6 +125,7 @@ struct task_epoll_entry { uint64_t data; uint32_t ready; uint64_t generation; + uint64_t write_generation; uint32_t active; uint32_t disabled; struct task_epoll_watch *watch; diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index b1782075..d22d57a6 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -149,6 +149,7 @@ struct unix_socket { uint32_t *pending; uint64_t rx_read; uint64_t rx_written; + uint64_t tx_generation; struct unix_rights *rights; struct unix_stream_credentials *cred_head, *cred_tail; struct unix_packet *packets; @@ -657,6 +658,17 @@ void task_socket_collect(void) collecting = false; } +/** @brief Compare two positions in a stream ring before committing a read. + * @param socket Receiving socket whose head is stable under execution ownership. + * @param tail Original read position. + * @return True if a full receive ring became writable or was completely drained. + */ +static bool unix_stream_write_edge(const struct unix_socket *socket, uint32_t tail) +{ + return (socket->rx_head + 1u) % UNIX_SOCKET_RX_CAP == tail || + socket->rx_tail == socket->rx_head; +} + /** @brief Consume or peek UNIX data and retain packet metadata for recvmsg. * @param file Borrowed socket description. @param buffer Kernel data output. * @param length Available output bytes. @param flags Linux receive flags. @@ -770,6 +782,10 @@ static int unix_read_data(struct task_file *file, void *buffer, uint32_t length, kernel_free(expired); } if (!socket->cred_head) socket->cred_tail = NULL; + if (unix_stream_write_edge(socket, tail)) { + struct unix_socket *peer = unix_from_handle(socket->peer_handle); + if (peer) ++peer->tx_generation; + } } unix_wake_peer(socket); return (int)count; @@ -1062,6 +1078,17 @@ uint64_t task_socket_event_generation(const struct task_file *file) return socket ? socket->rx_written : 0; } +/** + * @brief Snapshot peer drain progress for write edges on AF_UNIX streams. + * @param file Retained socket open file description, or NULL. + * @return Monotonic transmit wake generation, or zero for other sockets. + */ +uint64_t task_socket_write_generation(const struct task_file *file) +{ + struct unix_socket *socket = unix_from_file(file); + return socket && socket->type == SOCK_STREAM ? socket->tx_generation : 0; +} + /** * @brief Query queued receive bytes or update a socket OFD's nonblocking flag. * @param file Retained socket open file description. diff --git a/tools/tests/epoll_capacity_test.c b/tools/tests/epoll_capacity_test.c index 8768259e..c8669dfe 100644 --- a/tools/tests/epoll_capacity_test.c +++ b/tools/tests/epoll_capacity_test.c @@ -104,6 +104,8 @@ void kernel_poll_readiness_notify(void) { } void kernel_poll_wait_remove(struct task *task) { (void)task; } uint64_t task_socket_event_generation(const struct task_file *file) { (void)file; return 0; } +uint64_t task_socket_write_generation(const struct task_file *file) +{ (void)file; return 0; } uint64_t time_ticks(void) { return 0; } uint64_t time_uptime_us(void) { static uint64_t now; return ++now; } void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) diff --git a/tools/tests/poll_wakeup_test.c b/tools/tests/poll_wakeup_test.c index 277e7860..99f1ab93 100644 --- a/tools/tests/poll_wakeup_test.c +++ b/tools/tests/poll_wakeup_test.c @@ -15,6 +15,8 @@ #include #include #include +#include +#include "../../kernel/syscall/internal.h" /* Exercise the real AF_UNIX readiness publisher and real poll implementation. */ #include "../../kernel/syscall/ipc/socket.c" @@ -64,6 +66,9 @@ uint64_t time_ticks(void) return fake_ticks; } +int time_clock_get(int32_t id, struct linux_timespec *out) +{ assert(id == LINUX_CLOCK_REALTIME); *out = (struct linux_timespec){0}; return 0; } + void sched_sleep_current_until(uint64_t wake_tick) { current.wake_tick = wake_tick; @@ -159,6 +164,12 @@ short task_netlink_poll(const struct task_file *file, short events) { (void)file; (void)events; abort(); } void task_netlink_release(struct task_file *file) { (void)file; abort(); } +int pty_transfer_get(uint32_t pty_id, uint32_t endpoint) +{ (void)pty_id; (void)endpoint; abort(); } +int sched_task_pty_alloc(struct task *task, struct task_pty_fd **out) +{ (void)task; (void)out; abort(); } +void syscall_record_locks_release(struct task_file *file) +{ assert((file->flags & (TASK_FILE_FLAG_SOCKET_UNIX | TASK_FILE_FLAG_EPOLL)) != 0); } void pty_transfer_put(uint32_t pty_id, uint32_t endpoint) { (void)pty_id; (void)endpoint; } void pty_reap_hungup(uint32_t pty_id) { (void)pty_id; } @@ -172,9 +183,12 @@ bool user_range_ok(uint64_t pointer, uint64_t size) return user_range_writable(pointer, size); } +int user_range_readable(uint64_t pointer, uint64_t size) +{ return user_range_ok(pointer, size) ? 0 : -LINUX_EFAULT; } + struct task_file *task_descriptor_for_fd(struct task *task, int fd) { - return task && fd == 3 ? &task->files[0] : NULL; + return task && (fd == 3 || fd == 4) ? &task->files[fd - 3] : NULL; } @@ -203,9 +217,9 @@ short task_packet_poll(struct task_file *file, short events) { (void)file; (void)events; return 0; } short task_udp_poll(struct task_file *file, short events) { (void)file; (void)events; return 0; } -short input_evdev_available_vt(uint32_t kind, uint32_t index, uint64_t cursor, - uint32_t vt) -{ (void)kind; (void)index; (void)cursor; (void)vt; return 0; } +int input_evdev_available_vt(uint32_t kind, uint64_t cursor, uint64_t grab_token, + uint32_t vt) +{ (void)kind; (void)cursor; (void)grab_token; (void)vt; return 0; } short audio_mixer_poll(const struct task_file *file, short events) { (void)file; (void)events; return 0; } short audio_device_poll(const struct task_file *file, short events) @@ -236,6 +250,54 @@ static void setup_socketpair(struct unix_socket **reader_out, *writer_out = writer; } +/** @brief Reproduce a broker's cached EPOLLOUT after a short write is drained. */ +static void check_unix_write_edge(struct task_file *writer) +{ + struct task_epoll *epoll = kernel_malloc(sizeof(*epoll)); + assert(epoll); + *epoll = (struct task_epoll){0}; + current.files[1] = (struct task_file){.used = 1, .flags = TASK_FILE_FLAG_EPOLL, + .aux = (uintptr_t)epoll}; + + /* Watch the writer on fd 3; use the other socket as a local read endpoint. */ + struct task_file receiver = current.files[0]; + current.files[0] = *writer; + struct epoll_event interest = {.events = EPOLLIN | EPOLLOUT | EPOLLET, .data = 17}; + struct epoll_event event = {0}; + assert(!syscall_epoll_ctl(4, EPOLL_CTL_ADD, 3, (uintptr_t)&interest)); + assert(syscall_epoll_wait(4, (uintptr_t)&event, 1, 0) == 1 && event.events == EPOLLOUT); + assert(!syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + + /* The send fits and no observer ever sees a full queue. A peer peek or a + * partial read of one segment doesn't release its send capacity. */ + unsigned char bytes[2] = {0}; + assert(task_socket_write(writer, "ab", 2) == 2); + assert(!syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + assert(unix_read_data(&receiver, bytes, 1, MSG_PEEK, NULL, NULL) == 1); + assert(bytes[0] == 'a' && !syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + assert(task_socket_read(&receiver, bytes, 1) == 1 && bytes[0] == 'a'); + assert(!syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + assert(task_socket_read(&receiver, bytes, 1) == 1 && bytes[0] == 'b'); + assert(task_epoll_poll_ready(¤t, ¤t.files[1])); + assert(task_epoll_poll_ready(¤t, ¤t.files[1])); + assert(syscall_epoll_wait(4, (uintptr_t)&event, 1, 0) == 1 && event.events == EPOLLOUT); + assert(!syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + + /* Incoming data refreshes only input. Sending nothing cannot refresh output. */ + assert(task_socket_write(&receiver, "x", 1) == 1); + assert(syscall_epoll_wait(4, (uintptr_t)&event, 1, 0) == 1 && event.events == EPOLLIN); + assert(task_socket_write(writer, "", 0) == 0); + assert(task_socket_read(writer, bytes, 1) == 1 && bytes[0] == 'x'); + assert(!syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + + assert(!syscall_epoll_ctl(4, EPOLL_CTL_DEL, 3, 0)); + clear_task_file(¤t.files[1]); + /* Transfer the writer descriptor back to its caller without closing it. */ + *writer = current.files[0]; + current.files[0] = receiver; + puts("PASS AF_UNIX stream EPOLLOUT after peer drain, independent of EPOLLIN"); +} + int main(void) { struct unix_socket *reader, *writer; @@ -326,6 +388,9 @@ int main(void) assert(syscall_poll((uint64_t)(uintptr_t)&request, 1, 20) == 0); assert(!current.poll_deadline_ticks && !current.waiting_queue); assert(!kernel_poll_wait_registered(¤t)); + check_unix_write_edge(&writer_file); + clear_task_file(¤t.files[0]); + clear_task_file(&writer_file); puts("PASS poll readiness wake, stopped/exited cleanup, finite timeout, and nfds=0 fallback"); return 0; } diff --git a/tools/tests/task8_epoll_user_test.c b/tools/tests/task8_epoll_user_test.c index fc9c137b..37463d6d 100644 --- a/tools/tests/task8_epoll_user_test.c +++ b/tools/tests/task8_epoll_user_test.c @@ -28,6 +28,8 @@ bool user_range_writable(uint64_t address,uint64_t length) } uint64_t kernel_poll_readiness_generation(void) { return 0; } uint64_t task_socket_event_generation(const struct task_file *file) { (void)file;return 0; } +uint64_t task_socket_write_generation(const struct task_file *file) +{ (void)file; return 0; } uint64_t input_evdev_event_generation_vt(uint32_t kind,uint64_t token,uint32_t vt) { (void)kind;(void)token;(void)vt;return 0; } uint64_t time_ticks(void) { return 100; } From f98fc4e33ff52a9257969fb65bf123fcccf1cdbc Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 20:11:39 +0800 Subject: [PATCH 46/97] fix(socket): account unix stream send buffers for SIOCOUTQ --- .../LC_MESSAGES/userspace-api/descriptors.po | 28 ++++-- .../LC_MESSAGES/userspace-api/descriptors.po | 18 +++- Documentation/userspace-api/descriptors.rst | 7 +- include/reliefnt/syscall_internal.h | 8 +- kernel/syscall/ipc/socket.c | 94 +++++++++++++++---- tools/tests/poll_wakeup_test.c | 6 ++ tools/tests/socket_batch_unix_test.c | 55 ++++++++++- 7 files changed, 181 insertions(+), 35 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index 50d22da8..ae0d37a8 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -206,14 +206,15 @@ msgstr "" "closed." msgid "" -"对 ``AF_UNIX`` 流套接字,对端读空接收队列或让满队列腾出空间时,边沿触发的 监听会重新收到 " -"``EPOLLOUT``,即使两次等待之间没有观察到不可写状态。 预读不产生发送通知;只有新输入时不会额外返回 ``EPOLLOUT``。" +"对 ``AF_UNIX`` 流套接字,对端读完一个发送片段或让满队列腾出空间时,边沿触发的 监听会重新收到 " +"``EPOLLOUT``,即使两次等待之间没有观察到不可写状态。 预读不产生发送通知;只有新输入时不会额外返回 " +"``EPOLLOUT``。" msgstr "" -"When the peer of an ``AF_UNIX`` stream socket empties its receive " -"queue or frees space in a full queue, an edge-triggered watch receives" -" ``EPOLLOUT`` again, even if neither wait observed it as non-writable." -" Peeking does not generate a transmit notification, and incoming data " -"alone does not report ``EPOLLOUT`` again." +"When the peer of an ``AF_UNIX`` stream socket finishes reading a " +"send segment or frees space in a full queue, an edge-triggered watch" +" receives ``EPOLLOUT`` again, even if neither wait observed it as " +"non-writable. Peeking does not generate a transmit notification, and" +" incoming data alone does not report ``EPOLLOUT`` again." msgid "ppoll 与信号掩码" msgstr "ppoll and Signal Masks" @@ -381,6 +382,19 @@ msgstr "" "underlying forced read-only and other existing flags; it does not change " "policies for shared volumes, ESPs, optical media, or other mount roles." +msgid "" +"``AF_UNIX`` 流套接字的 ``SIOCOUTQ``(与 ``TIOCOUTQ`` 同号)向原生 32 位整数 " +"写入仍由对端队列持有的发送缓冲区计量。每个片段按本内核的分配单位计量, 不是精确的未读有效载荷大小或 Linux " +"的缓冲区字节数。片段读完时才释放其计量, 预读不释放;没有排队片段时返回 0。数据报和有序数据包暂不支持此操作。" +msgstr "" +"For ``AF_UNIX`` stream sockets, ``SIOCOUTQ`` (the same request " +"number as ``TIOCOUTQ``) writes the send-buffer charge still held in " +"the peer queue to a native 32-bit integer. Segments are charged in " +"this kernel’s allocation units, not the exact unread payload size or" +" Linux buffer byte count. A charge is released when its segment is " +"fully read, but not on peek. An empty queue returns 0. Datagram and " +"sequenced-packet sockets do not yet support this request." + msgid "" "查看根之外的挂载根不出现在 chroot 视图中;可见记录保留实际 ID,因此其 parent ID " "可能位于查看范围之外。路径字段转义空格、制表符、换行和反斜线。 分段读取使用同一图顺序和字节偏移,不依赖反向插入的内部链表布局。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index a59ed7a9..2a853642 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -179,11 +179,12 @@ msgstr "" "を返します。監視対象のオープンファイル記述に対する最後の参照が閉じられると、監視項目は削除されます。" msgid "" -"对 ``AF_UNIX`` 流套接字,对端读空接收队列或让满队列腾出空间时,边沿触发的 监听会重新收到 " -"``EPOLLOUT``,即使两次等待之间没有观察到不可写状态。 预读不产生发送通知;只有新输入时不会额外返回 ``EPOLLOUT``。" +"对 ``AF_UNIX`` 流套接字,对端读完一个发送片段或让满队列腾出空间时,边沿触发的 监听会重新收到 " +"``EPOLLOUT``,即使两次等待之间没有观察到不可写状态。 预读不产生发送通知;只有新输入时不会额外返回 " +"``EPOLLOUT``。" msgstr "" "``AF_UNIX`` " -"ストリームソケットの対向側が受信キューを空にするか、満杯だったキューに空きができると、二度の待機で書き込み不可を観測していなくても、エッジトリガーの監視に再び" +"ストリームソケットの対向側が送信セグメントを読み終えるか、満杯だったキューに空きができると、二度の待機で書き込み不可を観測していなくても、エッジトリガーの監視に再び" " ``EPOLLOUT`` が通知されます。先読みでは送信通知は発生せず、新しい入力だけでは ``EPOLLOUT`` " "が再通知されることもありません。" @@ -329,6 +330,17 @@ msgstr "" "``MS_STRICTATIME`` " "を優先します。このデフォルトはルートのマウントインスタンスだけに作用し、下位の強制読み取り専用と既存の他のフラグを保持します。共有ボリューム、ESP、光学メディアなど他のマウント役割の方針は変更しません。" +msgid "" +"``AF_UNIX`` 流套接字的 ``SIOCOUTQ``(与 ``TIOCOUTQ`` 同号)向原生 32 位整数 " +"写入仍由对端队列持有的发送缓冲区计量。每个片段按本内核的分配单位计量, 不是精确的未读有效载荷大小或 Linux " +"的缓冲区字节数。片段读完时才释放其计量, 预读不释放;没有排队片段时返回 0。数据报和有序数据包暂不支持此操作。" +msgstr "" +"``AF_UNIX`` ストリームソケットの ``SIOCOUTQ``(``TIOCOUTQ`` " +"と同じ要求番号)は、対向側のキューに残る送信バッファの計上量をネイティブの 32 " +"ビット整数に書き込みます。各セグメントの計上には当カーネルの割り当て単位を使うため、正確な未読ペイロードのサイズや Linux " +"のバッファのバイト数ではありません。計上量はセグメントの読み取り完了時に解放され、先読みでは解放されません。キューが空なら 0 " +"を返します。データグラムと順序付きパケットのソケットでは未対応です。" + msgid "" "查看根之外的挂载根不出现在 chroot 视图中;可见记录保留实际 ID,因此其 parent ID " "可能位于查看范围之外。路径字段转义空格、制表符、换行和反斜线。 分段读取使用同一图顺序和字节偏移,不依赖反向插入的内部链表布局。" diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index 429b1be1..ee6269e7 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -94,7 +94,7 @@ evdev 进度只取对应设备、VT 和 OFD grab 可见的事件;另一终端 监视关系;形成环或超出深度时返回 ``ELOOP``。直接或经 ``dup`` 别名监视 自身返回 ``EINVAL``;目标的最后一个打开文件描述引用关闭后移除监视项。 -对 ``AF_UNIX`` 流套接字,对端读空接收队列或让满队列腾出空间时,边沿触发的 +对 ``AF_UNIX`` 流套接字,对端读完一个发送片段或让满队列腾出空间时,边沿触发的 监听会重新收到 ``EPOLLOUT``,即使两次等待之间没有观察到不可写状态。 预读不产生发送通知;只有新输入时不会额外返回 ``EPOLLOUT``。 @@ -126,6 +126,11 @@ TCP 的 ``recvfrom/recvmsg`` 支持 ``MSG_PEEK``:重复预读保留相同的 UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。 +``AF_UNIX`` 流套接字的 ``SIOCOUTQ``(与 ``TIOCOUTQ`` 同号)向原生 32 位整数 +写入仍由对端队列持有的发送缓冲区计量。每个片段按本内核的分配单位计量, +不是精确的未读有效载荷大小或 Linux 的缓冲区字节数。片段读完时才释放其计量, +预读不释放;没有排队片段时返回 0。数据报和有序数据包暂不支持此操作。 + ``AF_UNIX`` 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 使用原生整数 控制接收时间戳,默认关闭。启用任一选项会选定对应的控制消息类型,查询时仅 选中的选项返回 1,通过任一选项设置 0 均关闭。监听套接字的设置不由 diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index ed1bb7b8..5b4d3634 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -610,7 +610,7 @@ short task_socket_poll(const struct task_file *file, short events); */ uint64_t task_socket_event_generation(const struct task_file *file); /** - * @brief Snapshot peer drain progress for write edges on AF_UNIX streams. + * @brief Snapshot peer send-buffer retirement or space recovery for UNIX stream edges. * @param file Retained socket open file description, or NULL. * @return Monotonic transmit wake generation, or zero for other sockets. */ @@ -618,9 +618,9 @@ uint64_t task_socket_write_generation(const struct task_file *file); /** * @brief Handle Unix socket ioctls with native usercopy and error semantics. * @param file Retained Unix socket open file description. - * @param request Linux ioctl number. - * @param address User result pointer. - * @return Zero or a negative Linux errno. + * @param request FIONREAD, stream SIOCOUTQ (TIOCOUTQ), or FIONBIO. + * @param address User pointer to the 32-bit output or input flag. + * @return Zero, a negative Linux errno, or a private usercopy retry status. */ int task_socket_ioctl(struct task_file *file, uint64_t request, uint64_t address); int64_t syscall_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index d22d57a6..8284e8cb 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -50,6 +50,8 @@ extern void page_cache_note_write(uint64_t) __attribute__((weak)); #define UNIX_SOCKET_RX_CAP 16384u #define UNIX_SOCKET_FD_TRANSFER_MAX 253u #define UNIX_SOCKET_CMSG_CAP 65536u +/* Logical send-buffer accounting units for the ring-backed stream. */ +#define UNIX_STREAM_TX_QUANTUM 256u #ifdef CONFIG_SWAP /** @brief Retire this TCP socket's readiness wait before a prerequisite wait. @@ -115,6 +117,15 @@ struct unix_stream_credentials { struct ucred credentials; }; +/* One record per accepted stream write, owned by the receiver until the last + * byte of that segment is consumed. The kernel execution transaction protects + * both the ledger and the byte ring. */ +struct unix_stream_tx { + struct unix_stream_tx *next; + uint64_t end; + uint32_t charge; +}; + enum unix_socket_state { UNIX_SOCKET_OPEN = 0, UNIX_SOCKET_LISTEN = 1, UNIX_SOCKET_CONNECTED = 2 }; @@ -150,6 +161,8 @@ struct unix_socket { uint64_t rx_read; uint64_t rx_written; uint64_t tx_generation; + struct unix_stream_tx *stream_tx_head, *stream_tx_tail; + uint32_t stream_tx_charge; struct unix_rights *rights; struct unix_stream_credentials *cred_head, *cred_tail; struct unix_packet *packets; @@ -493,6 +506,27 @@ static void unix_wake_peer(struct unix_socket *socket) kernel_poll_readiness_notify(); } +/** + * @brief Retire receive-ring accounting records through a committed position. + * @param socket Receiver that owns the queued stream records. + * @param limit Inclusive end position; rx_written retires all on close. + * @return True if at least one completed send-buffer charge was released. + * Caller owns the execution transaction; no user pointers are touched. + */ +static bool unix_stream_retire_tx(struct unix_socket *socket, uint64_t limit) +{ + bool released = false; + while (socket->stream_tx_head && socket->stream_tx_head->end <= limit) { + struct unix_stream_tx *entry = socket->stream_tx_head; + socket->stream_tx_head = entry->next; + socket->stream_tx_charge -= entry->charge; + kernel_free(entry); + released = true; + } + if (!socket->stream_tx_head) socket->stream_tx_tail = NULL; + return released; +} + /** * @brief Drop one AF_UNIX socket reference and remove its final object safely. * @param handle Stable kernel object handle, ignored when already retired. @@ -507,6 +541,7 @@ static void unix_release_handle(uint32_t handle) if (socket->refs) --socket->refs; if (socket->refs) return; bool unread = socket->rx_head != socket->rx_tail || socket->packets || socket->unaccepted; + (void)unix_stream_retire_tx(socket, socket->rx_written); while (socket->cred_head) { struct unix_stream_credentials *credentials = socket->cred_head; socket->cred_head = credentials->next; @@ -658,17 +693,6 @@ void task_socket_collect(void) collecting = false; } -/** @brief Compare two positions in a stream ring before committing a read. - * @param socket Receiving socket whose head is stable under execution ownership. - * @param tail Original read position. - * @return True if a full receive ring became writable or was completely drained. - */ -static bool unix_stream_write_edge(const struct unix_socket *socket, uint32_t tail) -{ - return (socket->rx_head + 1u) % UNIX_SOCKET_RX_CAP == tail || - socket->rx_tail == socket->rx_head; -} - /** @brief Consume or peek UNIX data and retain packet metadata for recvmsg. * @param file Borrowed socket description. @param buffer Kernel data output. * @param length Available output bytes. @param flags Linux receive flags. @@ -782,7 +806,9 @@ static int unix_read_data(struct task_file *file, void *buffer, uint32_t length, kernel_free(expired); } if (!socket->cred_head) socket->cred_tail = NULL; - if (unix_stream_write_edge(socket, tail)) { + bool released = unix_stream_retire_tx(socket, socket->rx_read); + bool was_full = (socket->rx_head + 1u) % UNIX_SOCKET_RX_CAP == tail; + if (released || was_full) { struct unix_socket *peer = unix_from_handle(socket->peer_handle); if (peer) ++peer->tx_generation; } @@ -939,6 +965,15 @@ static int unix_send_packet(struct task_file *file, struct unix_socket *peer, return (int)length; } +/** + * @brief Queue stream data and its logical send-buffer charge atomically. + * @param file Borrowed sending description under execution ownership. + * @param buffer Kernel-owned payload, NULL only for a zero-length write. + * @param length Available bytes, capped by the peer's ring capacity. + * @param credentials Optional explicit SCM credentials. + * @return Accepted bytes, a negative errno or a private wait status. + * A sequenced packet or datagram is passed to its separate packet backend. + */ static int unix_write_data(struct task_file *file, const void *buffer, uint32_t length, const struct ucred *credentials) { @@ -963,13 +998,24 @@ static int unix_write_data(struct task_file *file, const void *buffer, uint32_t return unix_block(socket, file, &socket->wait_tx, false, 0); } if (length > free_space) length = free_space; + struct unix_stream_tx *tx = kernel_malloc(sizeof(*tx)); + if (!tx) return -RELIEFOS_ENOMEM; + /* A nonempty record accounts for payload plus bookkeeping, rounded + * to a fixed allocation unit. The ring retains payload in place and + * does not allocate Linux sk_buffs. */ + uint32_t charge = (length + (uint32_t)sizeof(*tx) + UNIX_STREAM_TX_QUANTUM - 1u) & + ~(UNIX_STREAM_TX_QUANTUM - 1u); + *tx = (struct unix_stream_tx){.end = peer->rx_written + length, .charge = charge}; struct ucred sent = unix_send_credentials(socket, peer, credentials); if (sent.pid) { struct unix_stream_credentials *segment = peer->cred_tail; if (!segment || segment->end != peer->rx_written || !unix_credentials_equal(segment->credentials, sent)) { segment = kernel_malloc(sizeof(*segment)); - if (!segment) return -RELIEFOS_ENOMEM; + if (!segment) { + kernel_free(tx); + return -RELIEFOS_ENOMEM; + } *segment = (struct unix_stream_credentials){.start = peer->rx_written, .end = peer->rx_written, .credentials = sent}; if (peer->cred_tail) peer->cred_tail->next = segment; @@ -984,6 +1030,10 @@ static int unix_write_data(struct task_file *file, const void *buffer, uint32_t peer->rx_head = next; } peer->rx_written += count; + if (peer->stream_tx_tail) peer->stream_tx_tail->next = tx; + else peer->stream_tx_head = tx; + peer->stream_tx_tail = tx; + peer->stream_tx_charge += charge; (void)kernel_wait_queue_wake_all(&peer->wait_rx); kernel_poll_readiness_notify(); return (int)count; @@ -1079,7 +1129,7 @@ uint64_t task_socket_event_generation(const struct task_file *file) } /** - * @brief Snapshot peer drain progress for write edges on AF_UNIX streams. + * @brief Snapshot peer send-buffer retirement or space recovery for UNIX stream edges. * @param file Retained socket open file description, or NULL. * @return Monotonic transmit wake generation, or zero for other sockets. */ @@ -1090,11 +1140,11 @@ uint64_t task_socket_write_generation(const struct task_file *file) } /** - * @brief Query queued receive bytes or update a socket OFD's nonblocking flag. + * @brief Query queued input bytes or stream send-buffer charge, or set nonblocking mode. * @param file Retained socket open file description. - * @param request Native FIONREAD or FIONBIO request. + * @param request Native FIONREAD, stream SIOCOUTQ (TIOCOUTQ), or FIONBIO. * @param address User pointer to one 32-bit result or input flag. - * @return Zero, or negative EBADF/ENOTTY/EINVAL/EFAULT. + * @return Zero, a negative Linux errno, or a private output retry status. */ int task_socket_ioctl(struct task_file *file, uint64_t request, uint64_t address) { @@ -1108,11 +1158,17 @@ int task_socket_ioctl(struct task_file *file, uint64_t request, uint64_t address else file->flags &= ~RELIEFOS_O_NONBLOCK; return 0; } - if (request != FIONREAD) return -RELIEFOS_ENOTTY; - if (socket->state == UNIX_SOCKET_LISTEN) return -RELIEFOS_EINVAL; + if (request != FIONREAD && (request != TIOCOUTQ || socket->type != SOCK_STREAM)) + return -LINUX_ENOTTY; + if (request == FIONREAD && socket->state == UNIX_SOCKET_LISTEN) return -RELIEFOS_EINVAL; int prep=socket_user_prepare(sched_current_task(),address,sizeof(int32_t),true); if(prep)return prep; if (!user_range_writable(address, sizeof(int32_t))) return -RELIEFOS_EFAULT; + if (request == TIOCOUTQ) { + const struct unix_socket *peer = unix_from_handle(socket->peer_handle); + *(int32_t *)(uintptr_t)address = peer ? (int32_t)peer->stream_tx_charge : 0; + return 0; + } uint32_t bytes = socket->type == SOCK_STREAM ? (socket->rx_head + UNIX_SOCKET_RX_CAP - socket->rx_tail) % UNIX_SOCKET_RX_CAP : socket->type == SOCK_SEQPACKET ? socket->packet_bytes diff --git a/tools/tests/poll_wakeup_test.c b/tools/tests/poll_wakeup_test.c index 99f1ab93..2fbfab7b 100644 --- a/tools/tests/poll_wakeup_test.c +++ b/tools/tests/poll_wakeup_test.c @@ -277,12 +277,17 @@ static void check_unix_write_edge(struct task_file *writer) assert(bytes[0] == 'a' && !syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); assert(task_socket_read(&receiver, bytes, 1) == 1 && bytes[0] == 'a'); assert(!syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + assert(task_socket_write(writer, "c", 1) == 1); assert(task_socket_read(&receiver, bytes, 1) == 1 && bytes[0] == 'b'); assert(task_epoll_poll_ready(¤t, ¤t.files[1])); assert(task_epoll_poll_ready(¤t, ¤t.files[1])); assert(syscall_epoll_wait(4, (uintptr_t)&event, 1, 0) == 1 && event.events == EPOLLOUT); assert(!syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + assert(task_socket_read(&receiver, bytes, 1) == 1 && bytes[0] == 'c'); + assert(syscall_epoll_wait(4, (uintptr_t)&event, 1, 0) == 1 && event.events == EPOLLOUT); + assert(!syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + /* Incoming data refreshes only input. Sending nothing cannot refresh output. */ assert(task_socket_write(&receiver, "x", 1) == 1); assert(syscall_epoll_wait(4, (uintptr_t)&event, 1, 0) == 1 && event.events == EPOLLIN); @@ -290,6 +295,7 @@ static void check_unix_write_edge(struct task_file *writer) assert(task_socket_read(writer, bytes, 1) == 1 && bytes[0] == 'x'); assert(!syscall_epoll_wait(4, (uintptr_t)&event, 1, 0)); + assert(task_socket_write(writer, "close", 5) == 5); assert(!syscall_epoll_ctl(4, EPOLL_CTL_DEL, 3, 0)); clear_task_file(¤t.files[1]); /* Transfer the writer descriptor back to its caller without closing it. */ diff --git a/tools/tests/socket_batch_unix_test.c b/tools/tests/socket_batch_unix_test.c index 8d269189..17471471 100644 --- a/tools/tests/socket_batch_unix_test.c +++ b/tools/tests/socket_batch_unix_test.c @@ -14,6 +14,7 @@ static bool swap_replace_passed; #endif static uint64_t readonly; static unsigned allocations; +static long allocation_budget = -1; static unsigned pty_holds; static struct linux_timespec fixture_realtime = {100, 123456789}; /* AF_UNIX cases must not cross into another socket family's backend. */ @@ -84,7 +85,14 @@ int task_pty_import_fd(struct task *task, const struct task_pty_fd *source, uint assert(source->pty_id == 7 && pty_holds); return 7; } -void *kernel_malloc(size_t size) { void *p = malloc(size); if (p) ++allocations; return p; } +void *kernel_malloc(size_t size) +{ + if (allocation_budget == 0) return NULL; + if (allocation_budget > 0) --allocation_budget; + void *p = malloc(size); + if (p) ++allocations; + return p; +} void kernel_free(void *p) { if (p) { assert(allocations); --allocations; free(p); } } struct task *sched_current_task(void) { return ¤t; } uint32_t sched_current_pid(void) { return current.pid; } @@ -269,6 +277,50 @@ static void check_unix_timestamps(void) puts("PASS AF_UNIX timestamps: old/new, PEEK, queued enable, ordering and truncation"); } +/** @brief Check native-sized stream TX accounting, peek and partial consumption. */ +static void check_unix_stream_outq(void) +{ + int32_t count = -1; + uintptr_t result = (uintptr_t)&count; + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count == 0); + /* Fail the accounting allocation and then the separate credential + * allocation. Neither failure may publish bytes or charge the sender. */ + uint32_t passcred = peers[1].passcred; + peers[1].passcred = 1; + for (long budget = 0; budget <= 1; ++budget) { + allocation_budget = budget; + assert(task_socket_write(&endpoints[0], "ab", 2) == -LINUX_ENOMEM); + allocation_budget = -1; + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count == 0); + assert(!task_socket_poll(&endpoints[1], POLLIN) && !allocations); + } + peers[1].passcred = passcred; + assert(task_socket_write(&endpoints[0], "ab", 2) == 2); + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count > 128); + int32_t charged = count; + assert(!task_socket_ioctl(&endpoints[1], TIOCOUTQ, result) && count == 0); + count = -1; + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count == charged); + + char data; + assert(unix_read_data(&endpoints[1], &data, 1, MSG_PEEK, NULL, NULL) == 1 && data == 'a'); + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count == charged); + assert(task_socket_read(&endpoints[1], &data, 1) == 1 && data == 'a'); + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count == charged); + assert(task_socket_write(&endpoints[0], "c", 1) == 1); + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count > charged + 128); + int32_t second = count - charged; + assert(task_socket_read(&endpoints[1], &data, 1) == 1 && data == 'b'); + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count == second); + assert(task_socket_read(&endpoints[1], &data, 1) == 1 && data == 'c'); + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count == 0); + assert(task_socket_ioctl(&endpoints[0], TIOCOUTQ, 0) == -LINUX_EFAULT); + assert(task_socket_write(&endpoints[0], "", 0) == 0); + assert(!task_socket_ioctl(&endpoints[0], TIOCOUTQ, result) && count == 0); + assert(!allocations); + puts("PASS AF_UNIX stream SIOCOUTQ: pending charge, peek, drain, EFAULT"); +} + int main(void) { current.kind = TASK_KIND_USER; @@ -454,6 +506,7 @@ int main(void) assert(unix_message_rights(¤t, &m, &held, &credential, &explicit) == credential_cases[i].error); assert(!held && !allocations); } + check_unix_stream_outq(); puts("PASS actual Unix mmsg: packet boundaries, WAITFORONE, blocking resume, length faults, SCM_RIGHTS references/CLOEXEC"); return 0; } From 3307f124d0b1c3e90215b82d935e7c01fd1b4965 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 20:25:46 +0800 Subject: [PATCH 47/97] feat(cgroup): delegate contained v2 subtrees to users --- .../userspace-api/device-filesystems.po | 52 ++---- .../userspace-api/device-filesystems.po | 47 ++--- .../userspace-api/device-filesystems.rst | 25 ++- fs/cgroup/filesystem.c | 167 +++++++++++++++--- fs/cgroup/hierarchy.c | 30 +++- fs/cgroup/internal.h | 17 +- fs/security/access.c | 66 +++++-- fs/vfs/attributes.c | 33 +++- fs/vfs/mount_internal.h | 3 + fs/vfs/open.c | 8 +- include/reliefnt/mount.h | 24 ++- include/reliefnt/permissions.h | 29 +++ kernel/syscall/io/file_io.c | 6 +- kernel/syscall/io/transfer.c | 6 +- tools/test_cgroup_scheduler.py | 2 +- tools/tests/cgroup_scheduler_test.c | 3 +- tools/tests/mount_backend_io_boundaries.c | 25 ++- tools/tests/mount_backend_test.c | 129 +++++++++++++- ...candidate-4-inet-signal-candidate-4.stub.c | 2 + tools/tests/task8_transfer_user_test.c | 4 + tools/tests/task_exit_logging_test.c | 2 + 21 files changed, 531 insertions(+), 149 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 3c5d3a3a..30680b5a 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -218,39 +218,26 @@ msgstr "Each open tracks its own read progress; duplicated descriptors share tha msgid "cgroup v2" msgstr "Unified cgroup hierarchy (v2)" -msgid "" -"``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` " -"挂载统一控制组层级。 ``/proc/filesystems`` 将其列为 ``nodev``,``statfs`` 返回 " -"``0x63677270``。 所有挂载共享同一层级和 inode 身份,包括最后一次卸载后的重新挂载;只读等挂载点 策略独立。管理员可以用 " -"``mkdir`` 创建控制组,用 ``rmdir`` 删除没有活任务和 子组的非根组。" -msgstr "" -"``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` mounts " -"the unified control group hierarchy. ``/proc/filesystems`` lists it as " -"``nodev`` and ``statfs`` reports ``0x63677270``. Mounts share a hierarchy" -" and inode identities, even after the last attachment is unmounted and " -"mounted again. Each attachment has its own policy, including read-only. " -"An administrator can create a group with ``mkdir`` and remove a non-root " -"group with no live tasks or children using ``rmdir``." +msgid "``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` 挂载统一控制组层级。 ``/proc/filesystems`` 将其列为 ``nodev``,``statfs`` 返回 ``0x63677270``。 所有挂载共享同一层级和 inode 身份,包括最后一次卸载后的重新挂载;只读等挂载点 策略独立。" +msgstr "``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` mounts the unified control group hierarchy. ``/proc/filesystems`` lists it as ``nodev`` and ``statfs`` reports ``0x63677270``. Mounts share the hierarchy and inode identities, even after the last attachment is unmounted and mounted again. Each attachment has its own policy, including read-only." + +msgid "控制组目录与每个控制文件分别保存所有者、组和权限位。通过标准 ``chmod``/``chown`` 变更某个 inode 不会影响同组的其他 inode;只读挂载 拒绝变更。控制器停用并重新启用时生成新的控制文件,旧文件的权限不会继承。" +msgstr "A cgroup directory and each control file keep independent ownership and mode bits. Standard ``chmod`` and ``chown`` affect only the selected inode; read-only mounts reject changes. Disabling and re-enabling a controller creates new control files without inheriting old permissions." + +msgid "权限委派" +msgstr "Permission-based delegation" -msgid "控制组目录与每个控制文件分别保存所有者、组和权限位。通过标准 ``chmod``/``chown`` 变更某个 inode 不会影响同组的其他 inode;只读挂载 拒绝变更。控制器停用并重新启用时生成新的控制文件,旧文件的权限不会继承。 可写操作仍须有内核实现,且修改层级或控制值仍要求 ``CAP_SYS_ADMIN``。" -msgstr "A cgroup directory and each control file keep independent ownership and mode bits. Standard ``chmod`` and ``chown`` affect only the selected inode; read-only mounts reject changes. Disabling and re-enabling a controller creates new control files without inheriting old permissions. A write operation must still be implemented by the kernel, and hierarchy or control-value changes still require ``CAP_SYS_ADMIN``." +msgid "管理者可通过目录权限委派子树。对实际父目录有写入和搜索权限的调用者可以 创建子组,或删除没有活任务和子组的非根组;删除还受目录 sticky 位约束。 授予 ``cgroup.subtree_control`` 写权限只允许调整本组向下启用的控制器, 不改变本组由父级管理的配额。``pids.max`` 的写入仍要求 ``CAP_SYS_ADMIN``, 不会因为更改文件所有权或权限而开放给普通用户。" +msgstr "An administrator can delegate a subtree through directory permissions. Callers with write and search permission on the actual parent can create child groups and remove non-root groups with no live tasks or children. Removing a child also honors the parent directory’s sticky bit. Write access to ``cgroup.subtree_control`` only allows adjusting controller availability below that group, not the group’s own parent-imposed limits. Writing ``pids.max`` still requires ``CAP_SYS_ADMIN``, regardless of its owner or mode." + +msgid "迁移进程需要对目的组的 ``cgroup.procs`` 有写权限,也需要对源组与目的组最近 共同祖先的 ``cgroup.procs`` 有写权限。共同祖先可以是源组或目的组自身。 祖先检查在迁移前执行,使用打开文件时保存的文件系统凭据(包括附加组), 不因复制、传递描述符或写入者的凭据变化而扩大权限。未获授权时返回 ``EACCES``,不修改任何线程的归属。" +msgstr "Moving a process requires write access to both the destination group’s ``cgroup.procs`` and the nearest common ancestor’s ``cgroup.procs``. The ancestor can be the source or destination itself. Its permissions are checked using the filesystem credentials saved at open time, including supplementary groups, before moving any thread. Duplicating or passing the descriptor and changing the writer’s credentials do not expand that authority. Denial returns ``EACCES`` without changing membership." msgid "成员与事件" msgstr "Membership and events" -msgid "" -"向 ``cgroup.procs`` 写入 PID 或 TID 会迁移该进程的所有活线程,不迁移子进程; 写入 0 " -"选择调用者。读取该文件列出本组的进程 ID;只读的 ``cgroup.threads`` 列出本组的线程 " -"ID。``/proc//cgroup`` 以 ``0::/路径`` 报告成员身份, 不依赖控制组层级挂载在何处。只有拥有 " -"``CAP_SYS_ADMIN`` 的用户任务能修改层级和控制值。" -msgstr "" -"Writing a PID or TID to ``cgroup.procs`` moves every live thread in that " -"process, but not its child processes. Writing 0 selects the caller. " -"Reading that file lists process IDs in the group; the read-only " -"``cgroup.threads`` lists thread IDs. ``/proc//cgroup`` reports " -"membership as ``0::/path`` regardless of where the hierarchy is mounted. " -"Only user tasks with ``CAP_SYS_ADMIN`` can modify the hierarchy and its " -"controls." +msgid "向 ``cgroup.procs`` 写入 PID 或 TID 会迁移该进程的所有活线程,不迁移子进程; 写入 0 选择调用者。读取该文件列出本组的进程 ID;只读的 ``cgroup.threads`` 列出本组的线程 ID。``/proc//cgroup`` 以 ``0::/路径`` 报告成员身份, 不依赖控制组层级挂载在何处。" +msgstr "Writing a PID or TID to ``cgroup.procs`` moves every live thread in that process, but not its child processes. Writing 0 selects the caller. Reading that file lists process IDs in the group; the read-only ``cgroup.threads`` lists thread IDs. ``/proc//cgroup`` reports membership as ``0::/path`` regardless of where the hierarchy is mounted." msgid "" "非根组的 ``cgroup.events`` 中,``populated`` 表示本组或后代是否仍有活线程, 不包含僵尸。其变化与 " @@ -298,11 +285,11 @@ msgstr "" " descendants." msgid "" -"不支持 cgroup v1、threaded 模式、cgroup namespace、非特权委托或其他控制器。 " +"不支持 cgroup v1、threaded 模式、cgroup namespace 或其他控制器。 " "``nsdelegate``、``memory_recursiveprot`` 只接受为兼容性挂载参数,不启用相应功能。 通知仅支持 " "inotify,不支持通过 ``POLLPRI`` 订阅状态变化。" msgstr "" -"cgroup v1, threaded mode, cgroup namespaces, unprivileged delegation and " +"cgroup v1, threaded mode, cgroup namespaces and " "other controllers are not supported. ``nsdelegate`` and " "``memory_recursiveprot`` are accepted only as compatibility mount " "options; they do not enable those features. Notifications use inotify; " @@ -315,7 +302,7 @@ msgid "" "``tools/test_mount_backend.py`` 覆盖 devtmpfs 共享挂载、元数据、设备号、符号 " "链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 " "选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` 覆盖 PTY " -"ABI、会话与主端挂断行为。控制组挂载、文件语义及 inotify 也由 ``tools/test_mount_backend.py`` " +"ABI、会话与主端挂断行为。控制组挂载、委派边界及 inotify 也由 ``tools/test_mount_backend.py`` " "覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 调度器的配额拒绝、创建回滚、退出及回收。来宾启动、udev " "和 systemd 集成需要 另行验证。" msgstr "" @@ -324,7 +311,6 @@ msgstr "" "policy and retry after allocation failure. It also checks devpts " "isolation, options, bind mounts, endpoint lifetime, number reuse and " "rollback. ``tools/test_linux_pty.py`` checks the PTY ABI, sessions and " -"master hangup. The mount backend suite covers cgroup mounts, control " -"files and inotify. ``tools/test_cgroup_scheduler.py`` exercises quota " +"master hangup. The mount backend suite covers cgroup mounts, delegation boundaries, and inotify. ``tools/test_cgroup_scheduler.py`` exercises quota " "denials, creation rollback, exit and reap through the real scheduler. " "Guest boot, udev and systemd integration require separate validation." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index 10d5197c..61825056 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -193,35 +193,26 @@ msgstr "オープンごとに読み取りの進捗を記録し、複製したデ msgid "cgroup v2" msgstr "統合 cgroup 階層(v2)" -msgid "" -"``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` " -"挂载统一控制组层级。 ``/proc/filesystems`` 将其列为 ``nodev``,``statfs`` 返回 " -"``0x63677270``。 所有挂载共享同一层级和 inode 身份,包括最后一次卸载后的重新挂载;只读等挂载点 策略独立。管理员可以用 " -"``mkdir`` 创建控制组,用 ``rmdir`` 删除没有活任务和 子组的非根组。" -msgstr "" -"``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` " -"は統合コントロールグループ階層をマウントします。``/proc/filesystems`` には ``nodev`` " -"と表示され、``statfs`` は ``0x63677270`` を返します。すべてのマウントは階層と inode " -"の識別情報を共有し、最後のマウントを解除しても再マウント時に同じ階層が見えます。読み取り専用などのポリシーはマウントごとに独立しています。管理者は" -" ``mkdir`` でグループを作成し、稼働中のタスクや子グループのない非ルートグループを ``rmdir`` で削除できます。" +msgid "``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` 挂载统一控制组层级。 ``/proc/filesystems`` 将其列为 ``nodev``,``statfs`` 返回 ``0x63677270``。 所有挂载共享同一层级和 inode 身份,包括最后一次卸载后的重新挂载;只读等挂载点 策略独立。" +msgstr "``mount(\"none\", \"/sys/fs/cgroup\", \"cgroup2\", flags, data)`` は統合コントロールグループ階層をマウントします。``/proc/filesystems`` には ``nodev`` と表示され、``statfs`` は ``0x63677270`` を返します。すべてのマウントは階層と inode の識別情報を共有し、最後のマウントを解除しても再マウント時に同じ階層が見えます。読み取り専用などのポリシーはマウントごとに独立しています。" + +msgid "控制组目录与每个控制文件分别保存所有者、组和权限位。通过标准 ``chmod``/``chown`` 变更某个 inode 不会影响同组的其他 inode;只读挂载 拒绝变更。控制器停用并重新启用时生成新的控制文件,旧文件的权限不会继承。" +msgstr "コントロールグループのディレクトリと各制御ファイルは、所有者・グループ・モードビットを個別に保持します。標準の ``chmod`` と ``chown`` が変更するのは指定した inode だけです。読み取り専用マウントでは変更できません。コントローラーを無効化して再び有効にすると、古い権限を引き継がない新しい制御ファイルが作成されます。" + +msgid "权限委派" +msgstr "権限の委譲" -msgid "控制组目录与每个控制文件分别保存所有者、组和权限位。通过标准 ``chmod``/``chown`` 变更某个 inode 不会影响同组的其他 inode;只读挂载 拒绝变更。控制器停用并重新启用时生成新的控制文件,旧文件的权限不会继承。 可写操作仍须有内核实现,且修改层级或控制值仍要求 ``CAP_SYS_ADMIN``。" -msgstr "コントロールグループのディレクトリと各制御ファイルは、所有者・グループ・モードビットを個別に保持します。標準の ``chmod`` と ``chown`` が変更するのは指定した inode だけです。読み取り専用マウントでは変更できません。コントローラーを無効化して再び有効にすると、古い権限を引き継がない新しい制御ファイルが作成されます。書き込み操作にはカーネルの実装が必要で、階層や制御値の変更には引き続き ``CAP_SYS_ADMIN`` が必要です。" +msgid "管理者可通过目录权限委派子树。对实际父目录有写入和搜索权限的调用者可以 创建子组,或删除没有活任务和子组的非根组;删除还受目录 sticky 位约束。 授予 ``cgroup.subtree_control`` 写权限只允许调整本组向下启用的控制器, 不改变本组由父级管理的配额。``pids.max`` 的写入仍要求 ``CAP_SYS_ADMIN``, 不会因为更改文件所有权或权限而开放给普通用户。" +msgstr "管理者はディレクトリの権限を使ってサブツリーを委譲できます。実際の親ディレクトリに書き込み権限と検索権限があれば、子グループを作成し、稼働中のタスクも子グループもない非ルートグループを削除できます。削除には親ディレクトリの sticky ビットも適用されます。``cgroup.subtree_control`` の書き込み権限で変更できるのは配下のコントローラーの有効化だけで、そのグループ自体に親が設定した上限は変わりません。``pids.max`` の書き込みには、所有者やモードにかかわらず ``CAP_SYS_ADMIN`` が必要です。" + +msgid "迁移进程需要对目的组的 ``cgroup.procs`` 有写权限,也需要对源组与目的组最近 共同祖先的 ``cgroup.procs`` 有写权限。共同祖先可以是源组或目的组自身。 祖先检查在迁移前执行,使用打开文件时保存的文件系统凭据(包括附加组), 不因复制、传递描述符或写入者的凭据变化而扩大权限。未获授权时返回 ``EACCES``,不修改任何线程的归属。" +msgstr "プロセスの移動には、移動先と、移動元・移動先の最も近い共通の祖先の両方で ``cgroup.procs`` への書き込み権限が必要です。移動元または移動先そのものが共通の祖先になる場合もあります。祖先の権限は、追加グループも含めてファイルを開いた時点のファイルシステム資格情報で、スレッドの移動前に確認します。記述子の複製や受け渡し、書き込み時の資格情報の変更によって権限が拡大することはありません。拒否時には所属を変更せず ``EACCES`` を返します。" msgid "成员与事件" msgstr "所属とイベント" -msgid "" -"向 ``cgroup.procs`` 写入 PID 或 TID 会迁移该进程的所有活线程,不迁移子进程; 写入 0 " -"选择调用者。读取该文件列出本组的进程 ID;只读的 ``cgroup.threads`` 列出本组的线程 " -"ID。``/proc//cgroup`` 以 ``0::/路径`` 报告成员身份, 不依赖控制组层级挂载在何处。只有拥有 " -"``CAP_SYS_ADMIN`` 的用户任务能修改层级和控制值。" -msgstr "" -"``cgroup.procs`` に PID または TID " -"を書き込むと、そのプロセスの稼働中の全スレッドが移動します。子プロセスは移動しません。0 " -"を書き込むと呼び出し元を選択します。このファイルを読むとグループ内の PID が、読み取り専用の ``cgroup.threads`` を読むと " -"TID が列挙されます。``/proc//cgroup`` はマウント位置にかかわらず ``0::/パス`` " -"形式で所属を示します。階層と制御値を変更できるユーザータスクには ``CAP_SYS_ADMIN`` が必要です。" +msgid "向 ``cgroup.procs`` 写入 PID 或 TID 会迁移该进程的所有活线程,不迁移子进程; 写入 0 选择调用者。读取该文件列出本组的进程 ID;只读的 ``cgroup.threads`` 列出本组的线程 ID。``/proc//cgroup`` 以 ``0::/路径`` 报告成员身份, 不依赖控制组层级挂载在何处。" +msgstr "``cgroup.procs`` に PID または TID を書き込むと、そのプロセスの稼働中の全スレッドが移動します。子プロセスは移動しません。0 を書き込むと呼び出し元を選択します。このファイルを読むとグループ内の PID が、読み取り専用の ``cgroup.threads`` を読むと TID が列挙されます。``/proc//cgroup`` はマウント位置にかかわらず ``0::/パス`` 形式で所属を示します。" msgid "" "非根组的 ``cgroup.events`` 中,``populated`` 表示本组或后代是否仍有活线程, 不包含僵尸。其变化与 " @@ -262,12 +253,12 @@ msgstr "" "はそのグループの上限による拒否を記録し、``pids.events`` は子孫の上限による拒否も集計します。" msgid "" -"不支持 cgroup v1、threaded 模式、cgroup namespace、非特权委托或其他控制器。 " +"不支持 cgroup v1、threaded 模式、cgroup namespace 或其他控制器。 " "``nsdelegate``、``memory_recursiveprot`` 只接受为兼容性挂载参数,不启用相应功能。 通知仅支持 " "inotify,不支持通过 ``POLLPRI`` 订阅状态变化。" msgstr "" "cgroup v1、スレッドモード、cgroup " -"名前空間、非特権ユーザーへの委譲、および他のコントローラーには対応していません。``nsdelegate`` と " +"名前空間、および他のコントローラーには対応していません。``nsdelegate`` と " "``memory_recursiveprot`` は互換性のためにマウントオプションとして受理されますが、機能は有効になりません。状態変更は " "inotify で通知されます。``POLLPRI`` による通知には対応していません。" @@ -278,14 +269,14 @@ msgid "" "``tools/test_mount_backend.py`` 覆盖 devtmpfs 共享挂载、元数据、设备号、符号 " "链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 " "选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` 覆盖 PTY " -"ABI、会话与主端挂断行为。控制组挂载、文件语义及 inotify 也由 ``tools/test_mount_backend.py`` " +"ABI、会话与主端挂断行为。控制组挂载、委派边界及 inotify 也由 ``tools/test_mount_backend.py`` " "覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 调度器的配额拒绝、创建回滚、退出及回收。来宾启动、udev " "和 systemd 集成需要 另行验证。" msgstr "" "``tools/test_mount_backend.py`` は devtmpfs " "の共有マウント、メタデータ、デバイス番号、シンボリックリンク、デバイスの追加と削除、ユーザーによる置き換え、マウントポリシー、割り当て失敗後の再試行を確認します。また、devpts" " の分離、オプション、バインド、端点の寿命、番号の再利用とロールバックも確認します。``tools/test_linux_pty.py`` は " -"PTY ABI、セッションとマスターの切断を確認します。マウントのテストは cgroup の制御ファイルと inotify " +"PTY ABI、セッションとマスターの切断を確認します。マウントのテストは cgroup の委譲範囲と inotify " "も対象とします。``tools/test_cgroup_scheduler.py`` " "は実際のスケジューラーで上限による拒否、作成失敗時のロールバック、終了と回収を確認します。ゲストの起動、udev、systemd " "の統合は別途検証が必要です。" diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 9d228a50..37ff5b9f 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -120,13 +120,26 @@ cgroup v2 ``mount("none", "/sys/fs/cgroup", "cgroup2", flags, data)`` 挂载统一控制组层级。 ``/proc/filesystems`` 将其列为 ``nodev``,``statfs`` 返回 ``0x63677270``。 所有挂载共享同一层级和 inode 身份,包括最后一次卸载后的重新挂载;只读等挂载点 -策略独立。管理员可以用 ``mkdir`` 创建控制组,用 ``rmdir`` 删除没有活任务和 -子组的非根组。 +策略独立。 控制组目录与每个控制文件分别保存所有者、组和权限位。通过标准 ``chmod``/``chown`` 变更某个 inode 不会影响同组的其他 inode;只读挂载 拒绝变更。控制器停用并重新启用时生成新的控制文件,旧文件的权限不会继承。 -可写操作仍须有内核实现,且修改层级或控制值仍要求 ``CAP_SYS_ADMIN``。 + +权限委派 +-------- + +管理者可通过目录权限委派子树。对实际父目录有写入和搜索权限的调用者可以 +创建子组,或删除没有活任务和子组的非根组;删除还受目录 sticky 位约束。 +授予 ``cgroup.subtree_control`` 写权限只允许调整本组向下启用的控制器, +不改变本组由父级管理的配额。``pids.max`` 的写入仍要求 ``CAP_SYS_ADMIN``, +不会因为更改文件所有权或权限而开放给普通用户。 + +迁移进程需要对目的组的 ``cgroup.procs`` 有写权限,也需要对源组与目的组最近 +共同祖先的 ``cgroup.procs`` 有写权限。共同祖先可以是源组或目的组自身。 +祖先检查在迁移前执行,使用打开文件时保存的文件系统凭据(包括附加组), +不因复制、传递描述符或写入者的凭据变化而扩大权限。未获授权时返回 +``EACCES``,不修改任何线程的归属。 成员与事件 ---------- @@ -134,7 +147,7 @@ cgroup v2 向 ``cgroup.procs`` 写入 PID 或 TID 会迁移该进程的所有活线程,不迁移子进程; 写入 0 选择调用者。读取该文件列出本组的进程 ID;只读的 ``cgroup.threads`` 列出本组的线程 ID。``/proc//cgroup`` 以 ``0::/路径`` 报告成员身份, -不依赖控制组层级挂载在何处。只有拥有 ``CAP_SYS_ADMIN`` 的用户任务能修改层级和控制值。 +不依赖控制组层级挂载在何处。 非根组的 ``cgroup.events`` 中,``populated`` 表示本组或后代是否仍有活线程, 不包含僵尸。其变化与 ``pids.events``、``pids.events.local`` 的变化由 VFS worker @@ -155,7 +168,7 @@ PID 配额 僵尸仍计入 ``pids.current``,直至实际回收。带 ``WNOWAIT`` 的等待不回收配额。 ``pids.events.local`` 记录本组触发的拒绝,``pids.events`` 还累计后代的拒绝。 -不支持 cgroup v1、threaded 模式、cgroup namespace、非特权委托或其他控制器。 +不支持 cgroup v1、threaded 模式、cgroup namespace 或其他控制器。 ``nsdelegate``、``memory_recursiveprot`` 只接受为兼容性挂载参数,不启用相应功能。 通知仅支持 inotify,不支持通过 ``POLLPRI`` 订阅状态变化。 @@ -165,7 +178,7 @@ PID 配额 ``tools/test_mount_backend.py`` 覆盖 devtmpfs 共享挂载、元数据、设备号、符号 链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` -覆盖 PTY ABI、会话与主端挂断行为。控制组挂载、文件语义及 inotify 也由 +覆盖 PTY ABI、会话与主端挂断行为。控制组挂载、委派边界及 inotify 也由 ``tools/test_mount_backend.py`` 覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 调度器的配额拒绝、创建回滚、退出及回收。来宾启动、udev 和 systemd 集成需要 另行验证。 diff --git a/fs/cgroup/filesystem.c b/fs/cgroup/filesystem.c index 5c0573cf..ab32421b 100644 --- a/fs/cgroup/filesystem.c +++ b/fs/cgroup/filesystem.c @@ -3,9 +3,11 @@ #include #include #include +#include #include #include #include +#include #include #define CGROUP_FILE_SHIFT 4u @@ -179,11 +181,13 @@ static void cgroup_release(void *context, const struct storage_node *node, void static bool cgroup_same(void *context, const struct storage_node *a, const struct storage_node *b) { (void)context; return a->entry_id == b->entry_id; } -/** @brief Restrict hierarchy changes to a system administrator (no delegation). */ -static bool cgroup_admin(void) +/** @brief Borrow current filesystem credentials, treating kernel I/O as trusted. + * @return A snapshot valid under current execution ownership, with borrowed groups. + */ +static struct fs_access_cred cgroup_caller_cred(void) { const struct task *task = sched_current_task(); - return !task || task->kind == TASK_KIND_KERNEL || (task->cap_effective & (1ULL << CAP_SYS_ADMIN)); + return fs_access_credentials(task && task->kind != TASK_KIND_KERNEL ? task : NULL, false); } /** @brief Return directory or control metadata for a retained inode key. */ @@ -195,6 +199,29 @@ static struct reliefos_permissions cgroup_mode(struct cgroup *group, const struc return meta ? meta->mode : cgroup_control_default(group, file); } +/** @copydoc cgroup_procs_may_write */ +int cgroup_procs_may_write(struct cgroup *group, const struct fs_access_cred *cred) +{ + struct storage_node procs = cgroup_node(group, CG_PROCS, 0); + struct reliefos_permissions mode = cgroup_mode(group, &procs); + return fs_permissions_check_mode(cred, false, &mode, FS_ACCESS_WRITE); +} + +/** @brief Authorize a control mutation with exact metadata and supported policy. + * @param group Live inode owner. @param node Its live inode key. + * @param cred Borrowed credentials from the opening or path operation. + * @return Zero or negative DAC/unsupported-operation errno. + */ +static int cgroup_control_access(struct cgroup *group, const struct storage_node *node, + const struct fs_access_cred *cred) +{ + enum cgroup_file file = node_file(node); + if (!controls[file].writable || (file == CG_PIDS_MAX && !(cred->caps & (1ULL << CAP_SYS_ADMIN)))) + return -EPERM; + struct reliefos_permissions mode = cgroup_mode(group, node); + return fs_permissions_check_mode(cred, false, &mode, FS_ACCESS_WRITE); +} + /** @brief Read or persist the exact live inode's VFS-authorized DAC metadata. * @param context Shared hierarchy context. @param path Pinned directory or control. * @param value Receives metadata, or supplies the already authorized change. @@ -253,17 +280,26 @@ static int cgroup_statfs(void *context, const struct storage_node *node, struct return 0; } -/** @brief Publish only directories, reserving the control names even when disabled. */ +/** @brief Publish a child only with write/search DAC on the actual parent. + * The backend enforces parent DAC even for internal callers without a + * pathname permission walk, and reserves disabled control names. + */ static int cgroup_create(void *context, const struct storage_node *parent, const char *name, uint32_t type, const struct reliefos_permissions *mode, const char *target, struct storage_node *out, void **pin) { (void)context; (void)target; - if (type != LINUX_S_IFDIR || !cgroup_admin()) return -EPERM; + if (type != LINUX_S_IFDIR) return -EPERM; + struct cgroup *group = cgroup_find(parent->first_cluster); + if (!node_live(group, parent)) return -ENOENT; + if (node_file(parent) != CG_DIR) return -ENOTDIR; + struct fs_access_cred cred = cgroup_caller_cred(); + int rc = fs_permissions_check_mode(&cred, true, &group->mode, FS_ACCESS_WRITE | FS_ACCESS_EXEC); + if (rc) return rc; for (enum cgroup_file file = CG_PROCS; file < CG_FILE_COUNT; ++file) if (!__builtin_strcmp(controls[file].name, name)) return -EEXIST; struct cgroup *g = NULL; - int rc = cgroup_mkdir(cgroup_find(parent->first_cluster), name, mode, &g); + rc = cgroup_mkdir(group, name, mode, &g); if (rc) return rc; *out = cgroup_node(g, CG_DIR, 0); return pin ? cgroup_retain(context, out, pin) : 0; @@ -284,14 +320,25 @@ static void cgroup_remove_files(struct cgroup *g, enum cgroup_file first, uint32 } } -/** @brief Remove an empty group and retire its control and directory watch keys. */ +/** @brief Remove an empty child after actual parent DAC and sticky checks. + * A retained child or mount alias is not by itself permission to unlink it. + */ static int cgroup_remove(void *context, const struct vfs_path *path, bool directory) { (void)context; - if (!directory || !cgroup_admin()) return -EPERM; - struct cgroup *g = cgroup_find(vfs_path_node(path)->first_cluster); - if (!g) return -ENOENT; - int rc = cgroup_rmdir(g); + if (!directory) return -EPERM; + const struct storage_node *node = vfs_path_node(path); + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENOENT; + if (node_file(node) != CG_DIR) return -ENOTDIR; + if (!g->parent) return -EBUSY; + struct fs_access_cred cred = cgroup_caller_cred(); + const struct reliefos_permissions *parent = &g->parent->mode; + int rc = fs_permissions_check_mode(&cred, true, parent, FS_ACCESS_WRITE | FS_ACCESS_EXEC); + if (rc) return rc; + if ((parent->mode & 01000u) && cred.uid != parent->uid && cred.uid != g->mode.uid && + !(cred.caps & (1ULL << CAP_FOWNER))) return -EPERM; + rc = cgroup_rmdir(g); if (!rc) cgroup_remove_files(g, CG_DIR, g->parent->pids_epoch); return rc; } @@ -495,16 +542,18 @@ static int command_subtree(const char *text, size_t length, int *enable) return 0; } -/** @brief Apply one fully validated cgroup control write in a scheduler transaction. */ -static int cgroup_write(void *context, struct storage_node *node, uint64_t offset, - const void *bytes, uint32_t length, uint32_t *written) +/** @brief Parse and apply a command without moving a task before its final DAC check. + * @param g Live group under execution ownership. + * @param file Already authorized writable selector. + * @param cred Borrowed credentials for cgroup.procs containment. + * @param bytes Command data. @param length Byte count. + * @param written Output, changed only when a command commits. + * @return Zero or negative errno. Task membership and pids state changes hold + * scheduler_lock; notifications run only after it is released. + */ +static int cgroup_write_command(struct cgroup *g, enum cgroup_file file, const struct fs_access_cred *cred, + const void *bytes, uint32_t length, uint32_t *written) { - (void)context; (void)offset; - *written = 0; - struct cgroup *g = cgroup_find(node->first_cluster); - if (!node_live(g, node)) return -ENODEV; - enum cgroup_file file = node_file(node); - if (file == CG_DIR || !controls[file].writable || !cgroup_admin()) return -EPERM; if (!length) return 0; if (length > CGROUP_COMMAND_MAX) return -E2BIG; const char *text = bytes; @@ -528,7 +577,7 @@ static int cgroup_write(void *context, struct storage_node *node, uint64_t offse const struct task *caller = sched_current_task(); rc = cgroup_set_subtree_locked(g, enable, caller ? caller->fsuid : 0, caller ? caller->fsgid : 0); } - else if (file == CG_PROCS) rc = cgroup_move_locked(g, value); + else if (file == CG_PROCS) rc = cgroup_move_locked(g, value, cred); else if (file == CG_PIDS_MAX) g->limit = limit; kernel_spin_unlock_irqrestore(&scheduler_lock, flags); if (rc) return rc; @@ -540,16 +589,83 @@ static int cgroup_write(void *context, struct storage_node *node, uint64_t offse return 0; } -/** @brief Accept harmless O_TRUNC on writable live controls, without changing policy. */ +/** @brief Write without an OFD using the current credentials on the exact inode. */ +static int cgroup_write(void *context, struct storage_node *node, uint64_t offset, + const void *bytes, uint32_t length, uint32_t *written) +{ + (void)context; (void)offset; + *written = 0; + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENODEV; + struct fs_access_cred cred = cgroup_caller_cred(); + int rc = cgroup_control_access(g, node, &cred); + return rc ? rc : cgroup_write_command(g, node_file(node), &cred, bytes, length, written); +} + +/** @brief Capture write authority for a delegatable control's canonical OFD. + * @param context Borrowed hierarchy context. @param node Authorized live inode. + * @param flags Native open flags. @param state Receives an owned snapshot or NULL. + * @return Zero or negative errno; a writable open must not proceed without its snapshot. + */ +static int cgroup_file_open(void *context, const struct storage_node *node, uint32_t flags, void **state) +{ + (void)context; + *state = NULL; + enum cgroup_file file = node_file(node); + uint32_t access = flags & LINUX_O_ACCMODE; + if ((file != CG_PROCS && file != CG_SUBTREE) || + (access != LINUX_O_WRONLY && access != LINUX_O_RDWR)) return 0; + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENODEV; + struct fs_access_cred cred = cgroup_caller_cred(); + int rc = cgroup_control_access(g, node, &cred); + if (rc) return rc; + struct fs_access_cred *snapshot = kernel_malloc(sizeof(*snapshot)); + if (!snapshot) return -ENOMEM; + task_groups_retain(cred.groups); + *snapshot = cred; + *state = snapshot; + return 0; +} + +/** @brief Use an opened control's original authority for the live inode. + * Destination access was established at open; cgroup.procs rechecks current + * ancestor metadata with the captured credentials during the actual move. + */ +static int cgroup_file_write(void *context, struct storage_node *node, void *state, uint64_t offset, + const void *bytes, uint32_t length, uint32_t *written) +{ + (void)context; (void)offset; + *written = 0; + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENODEV; + enum cgroup_file file = node_file(node); + if (file != CG_PROCS && file != CG_SUBTREE) return -EPERM; + return cgroup_write_command(g, file, state, bytes, length, written); +} + +/** @brief Release the opener's snapshot and its optional supplementary groups. */ +static void cgroup_file_close(void *context, const struct storage_node *node, void *state) +{ + (void)context; (void)node; + struct fs_access_cred *cred = state; + task_groups_put(cred->groups); + kernel_free(cred); +} + +/** @brief Accept zero-length truncation on authorized writable controls as a no-op. */ static int cgroup_truncate(void *context, struct storage_node *node, uint64_t length) { (void)context; - if (!node_live(cgroup_find(node->first_cluster), node)) return -ENODEV; - if (!controls[node_file(node)].writable || !cgroup_admin()) return -EPERM; + struct cgroup *g = cgroup_find(node->first_cluster); + if (!node_live(g, node)) return -ENODEV; + struct fs_access_cred cred = cgroup_caller_cred(); + int rc = cgroup_control_access(g, node, &cred); + if (rc) return rc; return length ? -EINVAL : 0; } -/** @brief Validate attachment options without claiming the unimplemented controllers or delegation. */ +/** @brief Validate attachment options without claiming controller or namespace delegation support. */ static int cgroup_remount(void *context, uint64_t flags, const char *options) { (void)context; @@ -578,6 +694,7 @@ static const struct vfs_backend_ops cgroup_ops = { .remount_options = cgroup_remount, .read = cgroup_read, .readdir = cgroup_readdir, .readdir_name = cgroup_readdir_name, .permissions = cgroup_permissions, .create_node = cgroup_create, .getattr = cgroup_stat, .statfs = cgroup_statfs, .write = cgroup_write, .truncate = cgroup_truncate, + .file_open = cgroup_file_open, .file_write = cgroup_file_write, .file_close = cgroup_file_close, .sync = cgroup_sync, .remove_node = cgroup_remove, }; diff --git a/fs/cgroup/hierarchy.c b/fs/cgroup/hierarchy.c index e2de9e1d..9e387b2c 100644 --- a/fs/cgroup/hierarchy.c +++ b/fs/cgroup/hierarchy.c @@ -53,15 +53,17 @@ void cgroup_put_locked(struct cgroup *g) if (!--g->refs) queue_locked(g, 0); } -/** @brief Construct a fully initialized empty child before publishing it. */ +/** @brief Construct and publish an empty child with a name safe for procfs records. */ int cgroup_mkdir(struct cgroup *parent, const char *name, const struct reliefos_permissions *mode, struct cgroup **out) { if (!parent->linked) return -ENOENT; if (!__builtin_strncmp(name, "cgroup.", 7)) return -EINVAL; + size_t n = 0; + for (; name[n]; ++n) + if (name[n] == '\n') return -EINVAL; for (struct cgroup *child = parent->children; child; child = child->sibling) if (!__builtin_strcmp(child->name, name)) return -EEXIST; - size_t n = __builtin_strlen(name); if (parent->path_length + 1 + n >= VFS_PATH_MAX) return -ENAMETOOLONG; if (last_id == UINT32_MAX) return -ENOSPC; struct cgroup *g = kernel_malloc(sizeof(*g) + n + 1); @@ -204,31 +206,41 @@ static struct cgroup *common_ancestor(struct cgroup *a, struct cgroup *b) return a; } -/** @brief Migrate the live process, not the selected individual thread. +/** @brief Authorize and migrate the live process, not an individual thread. + * @param destination Live group approved by destination inode DAC. + * @param pid PID or TID; zero selects the current process. + * @param cred Borrowed credentials with which to check the common ancestor. + * @return Zero or negative errno before changing membership; caller holds + * both execution ownership and scheduler_lock. * An exited leader with surviving threads still identifies that process. * Migration may exceed a limit; subsequent fork admission enforces it. */ -int cgroup_move_locked(struct cgroup *destination, uint32_t pid) +int cgroup_move_locked(struct cgroup *destination, uint32_t pid, const struct fs_access_cred *cred) { if (!destination->linked) return -ENODEV; struct task *target = pid ? sched_find(pid) : sched_current_task(); if (!target || !target->pid || target->kind != TASK_KIND_USER) return -ESRCH; uint32_t tgid = sched_task_tgid(target); if (!cgroup_live_task(target) && target->pid != tgid) return -ESRCH; - struct cgroup *old = NULL; + struct cgroup *old = NULL, *ancestor = NULL; int64_t moved = 0; struct task *task; for (uint32_t i = 0; (task = sched_task_at(i)); ++i) { if (!cgroup_live_task(task) || sched_task_tgid(task) != tgid) continue; - struct cgroup *from = task->cgroup ? task->cgroup : &cgroup_root; - if (destination == from) return 0; - old = from; + if (!old) { + /* All live threads of a process share one domain. Inspect a live + * member, not a zombie leader whose reference may be stale. */ + old = task->cgroup ? task->cgroup : &cgroup_root; + ancestor = common_ancestor(old, destination); + int rc = cgroup_procs_may_write(ancestor, cred); + if (rc) return rc; + if (destination == old) return 0; + } if (task->cgroup) cgroup_put_locked(task->cgroup); task->cgroup = destination->parent ? destination : NULL; if (task->cgroup) cgroup_get_locked(task->cgroup); ++moved; } if (!moved) return -ESRCH; - struct cgroup *ancestor = common_ancestor(old, destination); adjust_locked(old, ancestor, -moved, -moved); adjust_locked(destination, ancestor, moved, moved); return 0; diff --git a/fs/cgroup/internal.h b/fs/cgroup/internal.h index 26f13920..2b46273f 100644 --- a/fs/cgroup/internal.h +++ b/fs/cgroup/internal.h @@ -17,6 +17,7 @@ enum cgroup_file { }; struct cgroup_control_metadata; +struct fs_access_cred; /* Topology/index and VFS operations require the execution writer. All task * membership, counters, controller state, refs and pending bits are also @@ -57,8 +58,20 @@ bool cgroup_pids_enabled(const struct cgroup *group); * @return Zero or negative errno without a partial controller change. */ int cgroup_set_subtree_locked(struct cgroup *group, bool enabled, uint32_t uid, uint32_t gid); -/** @brief Move the live thread group identified by PID or TID under scheduler_lock. */ -int cgroup_move_locked(struct cgroup *destination, uint32_t pid); +/** @brief Check write DAC on the common ancestor's actual cgroup.procs inode. + * @param group Live ancestor held by the hierarchy under execution ownership. + * @param cred Borrowed opener credentials (current credentials for path I/O). + * @return Zero or EACCES, without lookup, allocation or I/O under scheduler_lock. + */ +int cgroup_procs_may_write(struct cgroup *group, const struct fs_access_cred *cred); +/** @brief Move the live thread group only within the authorized hierarchy. + * @param destination Live group with destination file write access already admitted. + * @param pid PID or TID; zero selects the calling process. + * @param cred Borrowed credentials for the common-ancestor check. + * @return Zero or negative errno before any move. VFS execution ownership + * and scheduler_lock cover both authorization and the membership update. + */ +int cgroup_move_locked(struct cgroup *destination, uint32_t pid, const struct fs_access_cred *cred); /** @brief Identify a live, published user thread in the locked task table. */ bool cgroup_live_task(const struct task *task); /** @brief Export an inode's globally unique key for a borrowed group and epoch. */ diff --git a/fs/security/access.c b/fs/security/access.c index 1b15e95b..76364756 100644 --- a/fs/security/access.c +++ b/fs/security/access.c @@ -7,6 +7,22 @@ #include #include +/** @brief Find a GID in the sorted immutable supplementary group list. + * @param groups Borrowed optional group list. @param gid Group to find. + * @return True if present. Bounded logarithmic search with no locking or I/O. + */ +static bool group_list_contains(const struct task_groups *groups,uint32_t gid) +{ + uint32_t lo=0,hi=groups ? groups->count : 0; + while(loids[mid]==gid)return true; + if(groups->ids[mid]gid : task->fsgid; - if (gid == primary) return true; - const struct task_groups *groups = task->groups; - if (groups) for (uint32_t i = 0; i < groups->count; ++i) - if (groups->ids[i] == gid) return true; - return false; + return gid==primary || group_list_contains(task->groups,gid); } void task_groups_retain(struct task_groups *groups) @@ -32,11 +44,20 @@ void task_groups_retain(struct task_groups *groups) if (groups) __atomic_add_fetch(&groups->references, 1, __ATOMIC_RELAXED); } +/** @copydoc task_groups_put */ +void task_groups_put(struct task_groups *groups) +{ + if (groups && !__atomic_sub_fetch(&groups->references, 1, __ATOMIC_ACQ_REL)) kernel_free(groups); +} + +/** @brief Clear the task's supplementary group list and drop its reference. + * @param task Borrowed task whose credentials the caller owns. + */ void task_groups_release(struct task *task) { struct task_groups *groups = task->groups; task->groups = NULL; - if (groups && !__atomic_sub_fetch(&groups->references, 1, __ATOMIC_ACQ_REL)) kernel_free(groups); + task_groups_put(groups); } int task_groups_set(struct task *task, const uint32_t *ids, uint32_t count) @@ -156,19 +177,26 @@ int fs_virtual_permissions(const char *intrinsic,const struct storage_node *node *value=(struct reliefos_permissions){mode,0,0};return 0; } -/* Shared DAC policy; the caller selects exactly one inode metadata authority. */ -static int check_mode(const struct task *task,const struct storage_node *node, - const struct reliefos_permissions *value,uint32_t access,bool real_ids) +/** @copydoc fs_access_credentials */ +struct fs_access_cred fs_access_credentials(const struct task *task,bool real_ids) +{ + if(!task)return (struct fs_access_cred){.caps=UINT64_MAX}; + return (struct fs_access_cred){.uid=real_ids ? task->uid : task->fsuid, + .gid=real_ids ? task->gid : task->fsgid,.groups=task->groups, + .caps=real_ids ? (task->uid ? 0 : task->cap_permitted) : task->cap_effective}; +} + +/** @copydoc fs_permissions_check_mode */ +int fs_permissions_check_mode(const struct fs_access_cred *cred,bool directory, + const struct reliefos_permissions *value,uint32_t access) { - uint32_t uid = task ? (real_ids ? task->uid : task->fsuid) : 0; - uint64_t caps = !task ? UINT64_MAX : real_ids ? - (task->uid ? 0 : task->cap_permitted) : task->cap_effective; - uint32_t shift = uid == value->uid ? 6 : task_in_group(task, value->gid, real_ids) ? 3 : 0; + uint32_t shift=cred->uid==value->uid ? 6 : + cred->gid==value->gid || group_list_contains(cred->groups,value->gid) ? 3 : 0; if (((value->mode >> shift) & access) == access) return 0; - if ((caps & (1ULL << CAP_DAC_OVERRIDE)) && - (!(access & FS_ACCESS_EXEC) || node->type == RELIEFOS_FS_TYPE_DIR || (value->mode & 0111u))) return 0; - if ((caps & (1ULL << CAP_DAC_READ_SEARCH)) && - (node->type == RELIEFOS_FS_TYPE_DIR ? !(access & FS_ACCESS_WRITE) : access == FS_ACCESS_READ)) return 0; + if ((cred->caps & (1ULL << CAP_DAC_OVERRIDE)) && + (!(access & FS_ACCESS_EXEC) || directory || (value->mode & 0111u))) return 0; + if ((cred->caps & (1ULL << CAP_DAC_READ_SEARCH)) && + (directory ? !(access & FS_ACCESS_WRITE) : access == FS_ACCESS_READ)) return 0; return -RELIEFOS_EACCES; } @@ -187,7 +215,9 @@ int fs_permissions_check_path(const struct task *task,const struct vfs_path *pat node->type==RELIEFOS_FS_TYPE_SYMLINK))return -RELIEFOS_EROFS; if(node->type==RELIEFOS_FS_TYPE_FILE && (access&FS_ACCESS_EXEC) && (flags&MS_NOEXEC))return -RELIEFOS_EACCES; struct reliefos_permissions value;int ret=vfs_path_permissions(path,&value,false); - return ret<0 ? ret : check_mode(task,node,&value,access,real_ids); + if(ret<0)return ret; + struct fs_access_cred cred=fs_access_credentials(task,real_ids); + return fs_permissions_check_mode(&cred,node->type==RELIEFOS_FS_TYPE_DIR,&value,access); } /** @brief Apply the common chmod policy without performing metadata I/O. diff --git a/fs/vfs/attributes.c b/fs/vfs/attributes.c index ea9e5da2..f002f382 100644 --- a/fs/vfs/attributes.c +++ b/fs/vfs/attributes.c @@ -54,21 +54,44 @@ int vfs_path_statfs(const struct vfs_path *path,struct linux_statfs_abi *out) return rc; } -int vfs_path_write(const struct vfs_path *path,uint64_t offset,const void *bytes, - uint32_t length,uint32_t *written) +/** @brief Enforce common positional write policy for path or captured I/O. + * @param path Borrowed actual inode; equals the capture path when provided. + * @param file Optional borrowed private open state, already write-authorized. + * @param offset Byte position. @param bytes Kernel source, nullable at zero length. + * @param length Byte count. @param written Actual count, cleared on failure before I/O. + * @return Provider status or negative validation/mount errno. + */ +static int vfs_write_path(const struct vfs_path *path,struct vfs_open_file *file,uint64_t offset, + const void *bytes,uint32_t length,uint32_t *written) { if(!written)return -EINVAL;*written=0; if(!vfs_path_valid(path) || (length && !bytes))return -EINVAL; if(path->dentry->node.type==RELIEFOS_FS_TYPE_DIR)return -EISDIR; if(vfs_path_mount_flags(path)&MS_RDONLY)return -EROFS; - if(!path->mount->ops->write)return -EOPNOTSUPP; - char empty;int rc=path->mount->ops->write(path->mount->context,&path->dentry->node,offset, - bytes ? bytes : &empty,length,written); + const struct vfs_backend_ops *ops=path->mount->ops; + char empty;int rc; + if(file && ops->file_write) + rc=ops->file_write(path->mount->context,&path->dentry->node,file->state,offset, + bytes ? bytes : &empty,length,written); + else if(ops->write) + rc=ops->write(path->mount->context,&path->dentry->node,offset, + bytes ? bytes : &empty,length,written); + else return -EOPNOTSUPP; if(*written>length){*written=0;return -EIO;} if(*written && vfs_notify_event)vfs_notify_event(path,IN_MODIFY); return rc; } +/** @copydoc vfs_path_write */ +int vfs_path_write(const struct vfs_path *path,uint64_t offset,const void *bytes, + uint32_t length,uint32_t *written) +{return vfs_write_path(path,NULL,offset,bytes,length,written);} + +/** @copydoc vfs_file_write */ +int vfs_file_write(struct vfs_open_file *file,uint64_t offset,const void *bytes, + uint32_t length,uint32_t *written) +{return vfs_write_path(file ? &file->path : NULL,file,offset,bytes,length,written);} + int vfs_path_truncate(const struct vfs_path *path,uint64_t length) { if(!vfs_path_valid(path))return -EINVAL; diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 87f7276c..3bba58a4 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -10,6 +10,9 @@ struct vfs_lookup_cache_entry; +/** @brief A provider's private capture and the path it owns until final close. */ +struct vfs_open_file {struct vfs_path path;void *state;}; + /** @brief Publish one committed change to a live mount graph. * @param ns Borrowed graph under execution ownership, NULL is ignored. * Advances its mount-view generation and wakes poll waiters without allocation. diff --git a/fs/vfs/open.c b/fs/vfs/open.c index 86b0f2b0..3bd500ef 100644 --- a/fs/vfs/open.c +++ b/fs/vfs/open.c @@ -1,8 +1,6 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "mount_internal.h" -struct vfs_open_file {struct vfs_path path;void *state;}; - /** @brief Capture optional authorized per-open provider state transactionally. * @param path Borrowed actual inode, already authorized for sanitized flags. * @param flags Sanitized open status flags; caller bypasses this for O_PATH. @@ -18,7 +16,7 @@ int vfs_file_open(const struct vfs_path *path,uint32_t flags,struct vfs_open_fil if(!vfs_path_valid(path))return -EINVAL; const struct vfs_backend_ops *ops=path->mount->ops; if(!ops->file_open)return 0; - if(!ops->file_close || !ops->file_read)return -EINVAL; + if(!ops->file_close || (!ops->file_read && !ops->file_write))return -EINVAL; void *state=NULL;int rc=ops->file_open(path->mount->context,&path->dentry->node,flags,&state); if(rc || !state) { if(state)ops->file_close(path->mount->context,&path->dentry->node,state); @@ -37,6 +35,7 @@ int vfs_file_open(const struct vfs_path *path,uint32_t flags,struct vfs_open_fil * @param read Required actual byte output, zero on validation/protocol error. * @return Provider status or negative EINVAL/EIO. The handle pins code and * inode even if an external identity (for example PID) has since retired. + * Captures without a read callback fall back to the retained path. * Execution ownership required; no graph/module lock spans the callback. */ int vfs_file_read(struct vfs_open_file *file,uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read) @@ -44,6 +43,7 @@ int vfs_file_read(struct vfs_open_file *file,uint64_t offset,void *buffer,uint32 if(!read)return -EINVAL;*read=0; if(!file || (!buffer && capacity))return -EINVAL; const struct vfs_path *path=&file->path;char empty; + if(!path->mount->ops->file_read)return vfs_path_read(path,offset,buffer,capacity,read); int rc=path->mount->ops->file_read(path->mount->context,&path->dentry->node,file->state, offset,buffer ? buffer : &empty,capacity,read,vfs_path_mount_flags(path)); if(*read>capacity){*read=0;return -EIO;} @@ -74,7 +74,7 @@ bool vfs_file_poll(struct vfs_open_file *file,short events,bool consume, /** @brief Retire private open state before releasing its provider path/code. * @param file Owned optional handle; NULL does nothing. Caller clears its * stored pointer before entry so nested cleanup cannot release it twice. - * @return None. Runs once per canonical OFD, after in-flight reads complete. + * @return None. Runs once per canonical OFD, after in-flight I/O completes. * Execution ownership required; callbacks may perform I/O without any graph, * scheduler or module-table spinlock held by this function. */ diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index df869098..0cf007ae 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -36,12 +36,25 @@ int vfs_file_open(const struct vfs_path *path,uint32_t flags,struct vfs_open_fil * @param capacity Destination byte count. * @param read Required actual count output, cleared on validation failure. * @return Provider status or negative errno with bounded output count. + * Captures without a read callback use the retained path's normal reader. * Execution ownership required; no graph/module lock spans callbacks. */ int vfs_file_read(struct vfs_open_file *file,uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read); +/** @brief Write through a retained open description's optional provider capture. + * @param file Borrowed live handle, required; caller has checked write access. + * @param offset Positional byte offset. + * @param bytes Kernel-accessible source, nullable only at zero length. + * @param length Source byte count. + * @param written Required actual count output, cleared on validation failure. + * @return Zero or negative errno with bounded output. Uses path-based writing + * if the provider captures only reads. Mount policy and notifications apply + * equally on either path; no graph/module lock spans the callback. + */ +int vfs_file_write(struct vfs_open_file *file,uint64_t offset,const void *bytes, + uint32_t length,uint32_t *written); /** @brief Consume one captured open state before its path/code can retire. * @param file Owned optional handle, NULL is ignored; caller clears its slot. - * @return None. Final OFD cleanup only, after all in-flight reads finish. + * @return None. Final OFD cleanup only, after all in-flight I/O finishes. * Execution ownership required; no graph/module lock spans provider cleanup. */ void vfs_file_close(struct vfs_open_file *file); @@ -125,14 +138,17 @@ struct vfs_backend_ops { int (*read_cursor)(void *context,const struct storage_node *node,uint64_t offset, void *buffer,uint32_t capacity,uint32_t *read, struct storage_read_cursor *cursor,uint64_t mount_flags); - /* Optional OFD-local capture/read/release trio. open is nonblocking and - * returns NULL when this inode needs no private state. Any returned state, + /* Optional OFD-local capture, at least one I/O callback, and release. + * open is nonblocking and returns NULL when this inode needs no private state. Any returned state, * including on error, is owned by the caller and consumed by file_close. * The retained provider path outlives every callback; no graph lock spans - * callbacks. Authorization precedes open, and O_PATH bypasses the trio. */ + * callbacks. Authorization precedes open, and O_PATH bypasses capture. + * Direction without a capture callback uses the corresponding path I/O. */ int (*file_open)(void *context,const struct storage_node *node,uint32_t flags,void **state); int (*file_read)(void *context,const struct storage_node *node,void *state, uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read,uint64_t mount_flags); + int (*file_write)(void *context,struct storage_node *node,void *state, + uint64_t offset,const void *bytes,uint32_t length,uint32_t *written); void (*file_close)(void *context,const struct storage_node *node,void *state); /* Optional readiness and generation for a captured OFD. Probes with * consume=false must preserve pending events for nested epoll watches. */ diff --git a/include/reliefnt/permissions.h b/include/reliefnt/permissions.h index 3deb04f3..72316f42 100644 --- a/include/reliefnt/permissions.h +++ b/include/reliefnt/permissions.h @@ -7,6 +7,31 @@ #define FS_ACCESS_EXEC 1U #define FS_ACCESS_WRITE 2U #define FS_ACCESS_READ 4U + +/** @brief Filesystem identity and effective DAC capabilities, without a task pointer. */ +struct fs_access_cred { + uint32_t uid, gid; + uint64_t caps; + struct task_groups *groups; /**< Immutable list; retain it if the snapshot outlives the task access. */ +}; + +/** @brief Borrow the credentials used by one mode authorization. + * @param task Execution-owned source, NULL for trusted kernel access. + * @param real_ids Select the real IDs and applicable permitted capabilities. + * @return A value snapshot with a borrowed supplementary group list. + */ +struct fs_access_cred fs_access_credentials(const struct task *task,bool real_ids); +/** @brief Check normal DAC using only an inode type, mode and explicit credentials. + * @param cred Borrowed snapshot whose optional group list remains live. + * @param directory Whether directory search, rather than file execute, is requested. + * @param value Borrowed inode ownership and mode. + * @param access FS_ACCESS_* mask. + * @return Zero or negative errno. No mount policy, allocation or I/O; safe + * under a spinlock when callers stabilize metadata and credentials. + */ +int fs_permissions_check_mode(const struct fs_access_cred *cred,bool directory, + const struct reliefos_permissions *value,uint32_t access); + /** @brief Apply DAC and filesystem policy to an already retained object. * @param task Borrowed credentials, NULL for trusted kernel capability access. * @param path Borrowed held path, stable under execution ownership. @@ -79,6 +104,10 @@ int fs_virtual_chown(const struct task *task,const char *intrinsic, */ bool task_in_group(const struct task *task, uint32_t gid, bool real_ids); void task_groups_retain(struct task_groups *groups); +/** @brief Drop an optional owned reference to an immutable supplementary group list. + * @param groups Retained list (freed on its last reference), or NULL. + */ +void task_groups_put(struct task_groups *groups); void task_groups_release(struct task *task); int task_groups_set(struct task *task, const uint32_t *ids, uint32_t count); diff --git a/kernel/syscall/io/file_io.c b/kernel/syscall/io/file_io.c index bb9909ca..68ec3951 100644 --- a/kernel/syscall/io/file_io.c +++ b/kernel/syscall/io/file_io.c @@ -201,7 +201,8 @@ static void regular_stage_copy_read(struct regular_io_stage *s, uint32_t count) * A vector retains the OFD reservation between completed elements until its * common parent completion/cancellation, so another caller cannot interleave. * Execution ownership is required. Ordinary files use their retained provider - * and optional OFD-local provider capture/cursor, never a diagnostic filename; + * and optional OFD-local provider capture/cursor for reads and writes, never + * a diagnostic filename; * genuine block nodes use the block service. No graph/module lock spans * callbacks. O_APPEND stats the actual inode; sync flags flush the retained * provider, except for the immediately committed proc diagnostic control. @@ -307,7 +308,8 @@ int64_t syscall_regular_io(struct task *task, struct task_file *file, uint64_t b io_buffer, length, &transferred); } else if (writing) { file->read_cursor.valid = 0; - ret = vfs_path_write(&file->path_ref,position+done, + ret = file->provider_file ? vfs_file_write(file->provider_file,position+done, + io_buffer,length,&transferred) : vfs_path_write(&file->path_ref,position+done, io_buffer,length,&transferred); } else if(file->provider_file) { file->read_cursor.valid=0; diff --git a/kernel/syscall/io/transfer.c b/kernel/syscall/io/transfer.c index 933a6bac..9b56202b 100644 --- a/kernel/syscall/io/transfer.c +++ b/kernel/syscall/io/transfer.c @@ -296,7 +296,8 @@ static int64_t transfer_complete(struct task *task) /** @brief Copy retained source bytes to the original output description. * @param state Owned transfer metadata with unread buffered bytes, required. * @param written Required output count, cleared before dispatch. - * @return Zero or provider/stream errno, preserving short accepted progress. + * @return Zero or provider/stream errno, preserving short accepted progress + * and the original destination's per-open write authority. * Callbacks run under execution ownership without graph/module locks; the * state owns provider code and stable kernel staging bytes through waits. */ @@ -306,7 +307,8 @@ static int transfer_output(struct task_transfer_state *state,uint32_t *written) const void *bytes=state->bytes+state->consumed; uint32_t count=state->buffered-state->consumed;*written=0; if(output->node.type==RELIEFOS_FS_TYPE_FILE) - return vfs_path_write(&output->path_ref,state->output_position,bytes,count,written); + return output->provider_file ? vfs_file_write(output->provider_file,state->output_position,bytes,count,written) : + vfs_path_write(&output->path_ref,state->output_position,bytes,count,written); int rc=output->flags&TASK_FILE_FLAG_PIPE ? task_pipe_write(output,bytes,count) : output->flags&TASK_FILE_FLAG_SOCKET_UNIX ? task_socket_write(output,bytes,count) : task_inet_write(output,bytes,count); diff --git a/tools/test_cgroup_scheduler.py b/tools/test_cgroup_scheduler.py index 98644fec..b43b9ed7 100644 --- a/tools/test_cgroup_scheduler.py +++ b/tools/test_cgroup_scheduler.py @@ -14,7 +14,7 @@ def main() -> None: "clang", "-std=c11", "-O1", "-g", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/cgroup_scheduler_test.c", - "fs/cgroup/hierarchy.c", "fs/cgroup/filesystem.c", "fs/vfs/lookup_cache.c", + "fs/cgroup/hierarchy.c", "fs/cgroup/filesystem.c", "fs/security/access.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "-o", str(binary), ], cwd=ROOT, check=True) subprocess.run([str(binary)], cwd=ROOT, check=True, timeout=20) diff --git a/tools/tests/cgroup_scheduler_test.c b/tools/tests/cgroup_scheduler_test.c index 08d5660d..4b16147c 100644 --- a/tools/tests/cgroup_scheduler_test.c +++ b/tools/tests/cgroup_scheduler_test.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: Apache-2.0 */ /* Real scheduler, hierarchy and cgroup backend. Model only MM/CPU, empty * descriptors, and the deferred notification boundary in this host fixture. */ +#define RELIEFNT_FIXTURE_REAL_GROUPS #define main exit_logging_fixture_main #include "task_exit_logging_test.c" #undef main @@ -50,8 +51,6 @@ int task_sysv_sem_clone(struct task *parent, struct task *child, uint64_t flags) void storage_inode_retain(struct storage_inode_ref *inode) { assert(!inode); } /** @brief Reject an executable write denial on an empty image. */ int storage_inode_deny_write(struct storage_inode_ref *inode) { assert(!inode); abort(); } -/** @brief The fixture starts from root credentials with no supplementary groups. */ -void task_groups_retain(struct task_groups *groups) { assert(!groups); } /** @brief No mapped file descriptors are owned by the modeled MM. */ struct task_file *task_file_get(struct task_file *file) { assert(!file); return NULL; } /** @brief Reject a device-backed VMA in the empty modeled address space. */ diff --git a/tools/tests/mount_backend_io_boundaries.c b/tools/tests/mount_backend_io_boundaries.c index 2e38bce3..a40fbca9 100644 --- a/tools/tests/mount_backend_io_boundaries.c +++ b/tools/tests/mount_backend_io_boundaries.c @@ -2,11 +2,13 @@ /** @file * @brief Trap unrelated provider calls from the mount backend's FD tests. * The namespace handle has no data plane. Its front ends must answer before - * reaching socket/terminal providers, file page staging or user page aliases. + * reaching socket/terminal providers or user page aliases. The cgroup + * control test is the only caller with a modeled staged-write input page. */ #include "../../kernel/syscall/internal.h" #include #include +#include #include #define UNREACHED(type, name, args) type name args { abort(); } @@ -38,8 +40,6 @@ UNREACHED(int, serial_tx_user, (const void *b, size_t n)) UNREACHED(void, console_serial_write_len, (const char *b, size_t n)) UNREACHED(void, console_write_len, (const char *b, size_t n)) UNREACHED(int, user_copy_to_task, (struct task *t, uint64_t a, const void *b, uint64_t n)) -UNREACHED(uint64_t, address_space_user_page_phys, (const struct address_space *as, uint64_t address)) -UNREACHED(uint64_t, address_space_user_page_flags, (const struct address_space *as, uint64_t address)) UNREACHED(uint32_t, mm_page_refcount, (uint64_t phys)) UNREACHED(void, mm_retain_page, (uint64_t phys)) UNREACHED(int, page_cache_retain, (uint64_t phys)) @@ -49,5 +49,22 @@ UNREACHED(void *, paging_kernel_direct_map, (uint64_t phys)) UNREACHED(void *, paging_ioremap_device_page, (uint64_t phys, uint64_t cache_bits)) #undef UNREACHED -/** @brief Supply a deterministic clock for the regular engine's zero-length path. */ +/* Only the cgroup fixture supplies a resident input page for staged writes. */ +uint64_t mount_backend_write_page; + +/** @brief Resolve the exact modeled host-backed user page, rejecting other I/O. */ +uint64_t address_space_user_page_phys(const struct address_space *as,uint64_t address) +{ + assert(as && mount_backend_write_page && (address & ~4095ULL)==mount_backend_write_page); + return mount_backend_write_page; +} + +/** @brief The supplied writable command source is ordinary memory, not MMIO. */ +uint64_t address_space_user_page_flags(const struct address_space *as,uint64_t address) +{ + (void)address_space_user_page_phys(as,address); + return 0; +} + +/** @brief Supply a deterministic clock for synchronous regular-file I/O. */ uint64_t time_work_counter_us(void) { return 0; } diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 91d9e035..a58e4fa5 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2909,6 +2909,7 @@ static void cgroup_expect_event(struct fsnotify_instance *instance,int wd,uint32 static void cgroup_control_metadata(struct task *actor,const struct vfs_path *group, const struct vfs_path *alias) { + uint64_t saved_caps=actor->cap_effective; struct task delegate={.kind=TASK_KIND_USER,.fsuid=1500,.fsgid=1500}; struct task outsider={.kind=TASK_KIND_USER,.fsuid=1501,.fsgid=1501}; struct vfs_path procs={0},procs_ro={0},events={0},subtree={0},pids={0}; @@ -2939,20 +2940,139 @@ static void cgroup_control_metadata(struct task *actor,const struct vfs_path *gr assert(!vfs_path_stat(&subtree,&stat) && stat.st_mode==(LINUX_S_IFREG|0644)); assert(!fs_permissions_chown_path(actor,&pids,1500,1500)); assert(!vfs_path_stat(&pids,&stat) && stat.st_uid==1500 && stat.st_gid==1500); - actor->cap_effective=1ULL<cap_effective=saved_caps; vfs_path_put(&pids);vfs_path_put(&subtree);vfs_path_put(&events); vfs_path_put(&procs_ro);vfs_path_put(&procs); puts("PASS cgroup control metadata: exact inode ownership and mode, readonly and DAC"); } +/** @brief Write a user command through the original opened description and real staged I/O. */ +static void cgroup_fd_command(struct task *actor,int fd,char *buffer,const char *command,int status) +{ + extern uint64_t mount_backend_write_page; + struct task_file *file=task_file_for_fd(actor,fd); + assert(file && file_can_write(file)); + strcpy(buffer,command); + mount_backend_write_page=(uintptr_t)buffer & ~4095ULL; + int64_t rc=syscall_regular_io(actor,file,(uintptr_t)buffer,strlen(buffer),0,true,false); + mount_backend_write_page=0; + assert(rc==(status ? status : (int64_t)strlen(buffer))); +} + +/** @brief Verify ownership-based delegation, including OFD credential lifetime and containment. */ +static void cgroup_delegation(struct vfs_namespace *ns,struct task *actor, + const struct vfs_path *rw,const struct vfs_path *ro) +{ + const uint64_t admin=actor->cap_effective|(1ULL<cap_effective=admin; + assert(!fs_permissions_chown_path(actor,&owned,1500,1500)); + assert(!fs_permissions_chown_path(actor,&peer,1500,1500)); + assert(!vfs_path_lookup_child(&peer,"cgroup.procs",&control)); + assert(!fs_permissions_chown_path(actor,&control,1500,1500));vfs_path_put(&control); + assert(!vfs_path_lookup_child(&owned,"cgroup.procs",&procs)); + assert(!fs_permissions_chown_path(actor,&procs,0,5010)); + assert(!fs_permissions_chmod_path(actor,&procs,0664)); + assert(!vfs_path_lookup_child(&owned,"cgroup.subtree_control",&control)); + assert(!fs_permissions_chown_path(actor,&control,1500,1500));vfs_path_put(&control); + assert(!vfs_path_lookup_child(&owned,"pids.max",&control)); + assert(!fs_permissions_chown_path(actor,&control,1500,1500));vfs_path_put(&control); + + _Alignas(4096) struct { + char command[16], child[40], outside[40], on_ro[40]; + char child_procs[64], parent_procs[64], peer_procs[64], ro_procs[64]; + char subtree[64], pids_max[64], threads[64]; + } user={.child="/cgroup/managed/init.scope",.outside="/cgroup/forbidden", + .on_ro="/cgroup-ro/managed/forbidden",.child_procs="/cgroup/managed/init.scope/cgroup.procs", + .parent_procs="/cgroup/managed/cgroup.procs",.peer_procs="/cgroup/peer/cgroup.procs", + .ro_procs="/cgroup-ro/managed/cgroup.procs",.subtree="/cgroup/managed/cgroup.subtree_control", + .pids_max="/cgroup/managed/pids.max",.threads="/cgroup/managed/init.scope/cgroup.threads"}; + uintptr_t saved_base=lookup_user_base;size_t saved_bytes=lookup_user_bytes; + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + actor->fsuid=actor->fsgid=1500;actor->cap_effective=0; + assert(!syscall_create_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.child,LINUX_S_IFDIR,0755,NULL)); + assert(syscall_create_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.outside,LINUX_S_IFDIR,0755,NULL)==-EACCES); + assert(syscall_create_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.on_ro,LINUX_S_IFDIR,0755,NULL)==-EROFS); + assert(vfs_path_create_node(rw,"forbidden",LINUX_S_IFDIR,&root_mode,NULL,NULL)==-EACCES); + assert(vfs_path_remove(ns,&peer,true)==-EACCES); + assert(!vfs_path_lookup_child(&owned,"init.scope",&scope)); + struct linux_stat_abi attributes; + assert(!vfs_path_stat(&scope,&attributes) && attributes.st_uid==1500 && attributes.st_gid==1500); + + const uint32_t delegated_gid=5010; + assert(!task_groups_set(actor,&delegated_gid,1)); + int fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.child_procs,LINUX_O_WRONLY|LINUX_O_TRUNC,0); + assert(fd>=0); + int moved_fd=task_duplicate_file_fd(actor,fd,0,0);assert(moved_fd>=0); + task_discard_file_fd(actor,fd); + cgroup_fd_command(actor,moved_fd,user.command,"0",-EACCES); + assert(!actor->cgroup && !cgroup_tasks[1]->cgroup); + + /* A later writer's raised credentials must not widen the existing OFD. */ + actor->fsuid=actor->fsgid=0;actor->cap_effective=admin; + cgroup_fd_command(actor,moved_fd,user.command,"0",-EACCES); + cgroup_write_text(&owned,"cgroup.procs","0",0); + actor->fsuid=actor->fsgid=1500;actor->cap_effective=0; + + /* The original supplementary group authorizes the common ancestor, + * even after the opener replaces its live group list. */ + assert(!task_groups_set(actor,NULL,0)); + assert(syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.parent_procs,LINUX_O_WRONLY,0)==-EACCES); + cgroup_fd_command(actor,moved_fd,user.command,"904\n",0); + cgroup_check_text(&scope,"cgroup.procs","903\n"); + cgroup_check_text(&scope,"cgroup.threads","903\n904\n"); + assert(!task_groups_set(actor,&delegated_gid,1)); + assert(syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.ro_procs,LINUX_O_WRONLY,0)==-EROFS); + fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.peer_procs,LINUX_O_WRONLY,0);assert(fd>=0); + cgroup_fd_command(actor,fd,user.command,"0",-EACCES);task_discard_file_fd(actor,fd); + cgroup_check_text(&scope,"cgroup.procs","903\n"); + cgroup_check_text(&peer,"cgroup.procs",""); + + fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.subtree,LINUX_O_WRONLY|LINUX_O_TRUNC,0);assert(fd>=0); + cgroup_fd_command(actor,fd,user.command,"+pids",0);task_discard_file_fd(actor,fd); + cgroup_check_text(&scope,"pids.current","2\n"); + fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.pids_max,LINUX_O_WRONLY,0);assert(fd>=0); + cgroup_fd_command(actor,fd,user.command,"0",-EPERM);task_discard_file_fd(actor,fd); + cgroup_check_text(&owned,"pids.max","max\n"); + assert(!vfs_path_lookup_child(&scope,"cgroup.threads",&control)); + assert(!fs_permissions_chmod_path(actor,&control,0644));vfs_path_put(&control); + fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.threads,LINUX_O_WRONLY,0);assert(fd>=0); + cgroup_fd_command(actor,fd,user.command,"0",-EPERM);task_discard_file_fd(actor,fd); + + fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.parent_procs,LINUX_O_WRONLY,0);assert(fd>=0); + actor->fsuid=0;assert(!fs_permissions_chmod_path(actor,&procs,0644));actor->fsuid=1500; + cgroup_fd_command(actor,fd,user.command,"0",-EACCES); + actor->fsuid=0;assert(!fs_permissions_chmod_path(actor,&procs,0664));actor->fsuid=1500; + cgroup_fd_command(actor,fd,user.command,"0",0);task_discard_file_fd(actor,fd); + assert(vfs_path_remove(ns,&owned_ro,true)==-EROFS); + assert(!syscall_remove_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.child,true)); + cgroup_fd_command(actor,moved_fd,user.command,"0",-ENODEV); + task_discard_file_fd(actor,moved_fd); + task_groups_release(actor); + + actor->fsuid=actor->fsgid=0;actor->cap_effective=admin; + cgroup_write_text(rw,"cgroup.procs","0",0); + assert(!vfs_path_remove(ns,&owned,true) && !vfs_path_remove(ns,&peer,true)); + vfs_path_put(&procs);vfs_path_put(&scope);vfs_path_put(&owned_ro); + vfs_path_put(&peer);vfs_path_put(&owned); + lookup_user_base=saved_base;lookup_user_bytes=saved_bytes; + puts("PASS cgroup2 delegation: writable child, opener DAC, containment, readonly and protected controls"); +} + /** @brief Exercise cgroup attachments, generated controls, migration and inode lifetime. */ static void cgroup_mount_syscalls(struct vfs_namespace *ns,const struct vfs_path *root) { assert(!vfs_kernel_mkdir(ns,"/cgroup",0755)); assert(!vfs_kernel_mkdir(ns,"/cgroup-ro",0755)); - struct task actor={.pid=903,.kind=TASK_KIND_USER,.state=TASK_RUNNING,.cap_effective=1ULL<nofile.rlim_cur=32; cgroup_tasks[0]=&actor;cgroup_tasks[1]=&thread; vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); struct {char source[16],target[32],type[16],options[40];} user={ @@ -2991,6 +3111,7 @@ static void cgroup_mount_syscalls(struct vfs_namespace *ns,const struct vfs_path assert(!vfs_path_lookup_child(&alias,"pids.max",&old)); assert(!vfs_path_lookup_child(&alias,"cgroup.events",&events)); cgroup_control_metadata(&actor,&group,&alias); + cgroup_delegation(ns,&actor,&rw,&ro); struct fsnotify_instance *watch=NULL; struct fsnotify_key key; assert(!fsnotify_create(0,NULL,NULL,&watch)); @@ -3001,8 +3122,8 @@ static void cgroup_mount_syscalls(struct vfs_namespace *ns,const struct vfs_path cgroup_write_text(&group,"pids.max","0",0); actor.cap_effective=0; - cgroup_write_text(&group,"cgroup.procs","904",-EPERM); - actor.cap_effective=1ULL< Date: Sun, 29 Nov 2026 20:30:21 +0800 Subject: [PATCH 48/97] feat(procfs): expose random UUID reads for Linux userspace --- .../en/LC_MESSAGES/userspace-api/procfs.po | 9 +-- .../ja/LC_MESSAGES/userspace-api/procfs.po | 7 ++- Documentation/userspace-api/procfs.rst | 5 +- fs/proc/procfs.c | 56 +++++++++++-------- tools/tests/procfs_directories_test.c | 39 +++++++++++-- 5 files changed, 80 insertions(+), 36 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po index 942d5c98..d59a8684 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po @@ -296,10 +296,8 @@ msgstr "" msgid "策略节点" msgstr "Policy Nodes" -msgid "以下节点是现行内核策略的只读快照,不支持通过写文件调整:" -msgstr "" -"The following nodes are read-only snapshots of current kernel policies and cannot be adjusted by " -"writing files:" +msgid "以下节点提供只读内核信息,不支持通过写文件调整:" +msgstr "The following nodes expose read-only kernel information and cannot be changed by writing to them:" msgid "``/proc/sys/kernel/pid_max``:非零 32 位 PID 命名空间上限。" msgstr "``/proc/sys/kernel/pid_max``: upper bound of the nonzero 32-bit PID namespace." @@ -307,6 +305,9 @@ msgstr "``/proc/sys/kernel/pid_max``: upper bound of the nonzero 32-bit PID name msgid "``/proc/sys/kernel/random/boot_id``:本次启动的 UUID v4。格式为带连字符的小写十六进制字符串, 末尾带换行,同一次启动中的所有 proc 挂载读取相同值。首次有效读取由内核随机源生成; 随机源报错时返回原错误,后续读取可重试。" msgstr "``/proc/sys/kernel/random/boot_id``: this boot's UUID v4, printed in lowercase hexadecimal with hyphens and a final newline. All proc mounts return the same value during a boot. The kernel random source supplies the ID on the first successful read. An entropy error is returned unchanged and later reads can retry." +msgid "``/proc/sys/kernel/random/uuid``:同样以带换行的 UUID v4 文本输出。每次非空且未到文件末尾的读取 都先从内核随机源生成新值,再按偏移和长度截取;分多次短读可能读到不同 UUID 的片段。 需要完整 UUID 时应从偏移 0 一次读取 37 字节。随机源错误原样返回,后续读取可重试。" +msgstr "``/proc/sys/kernel/random/uuid``: outputs UUID v4 text with a final newline. Each nonempty read before end of file generates a new value from the kernel random source, then returns the requested slice. Separate short reads can return slices of different UUIDs. To obtain a complete UUID, read 37 bytes in one operation at offset zero. Random-source errors are returned unchanged and later reads can retry." + msgid "``/proc/sys/fs/nr_open``:描述符实现上限。" msgstr "``/proc/sys/fs/nr_open``: descriptor implementation limit." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po index 5ad20dcc..f330d709 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po @@ -259,8 +259,8 @@ msgstr "" msgid "策略节点" msgstr "方針ノード" -msgid "以下节点是现行内核策略的只读快照,不支持通过写文件调整:" -msgstr "次のノードは現行カーネル方針の読み取り専用スナップショットで、ファイルへの書き込みでは変更できません。" +msgid "以下节点提供只读内核信息,不支持通过写文件调整:" +msgstr "次のノードはカーネルの情報を読み取り専用で公開し、ファイルへの書き込みでは変更できません。" msgid "``/proc/sys/kernel/pid_max``:非零 32 位 PID 命名空间上限。" msgstr "``/proc/sys/kernel/pid_max``:非ゼロの 32 ビット PID 名前空間の上限。" @@ -268,6 +268,9 @@ msgstr "``/proc/sys/kernel/pid_max``:非ゼロの 32 ビット PID 名前空 msgid "``/proc/sys/kernel/random/boot_id``:本次启动的 UUID v4。格式为带连字符的小写十六进制字符串, 末尾带换行,同一次启动中的所有 proc 挂载读取相同值。首次有效读取由内核随机源生成; 随机源报错时返回原错误,后续读取可重试。" msgstr "``/proc/sys/kernel/random/boot_id``:今回の起動を表す UUID v4 です。ハイフン付きの小文字の十六進数で、末尾に改行があります。同じ起動中はすべての proc マウントから同じ値を読み取れます。最初の読み取りが成功した時点でカーネルの乱数源から生成します。乱数源のエラーはそのまま返され、後続の読み取りで再試行できます。" +msgid "``/proc/sys/kernel/random/uuid``:同样以带换行的 UUID v4 文本输出。每次非空且未到文件末尾的读取 都先从内核随机源生成新值,再按偏移和长度截取;分多次短读可能读到不同 UUID 的片段。 需要完整 UUID 时应从偏移 0 一次读取 37 字节。随机源错误原样返回,后续读取可重试。" +msgstr "``/proc/sys/kernel/random/uuid``:末尾に改行がある UUID v4 のテキストを返します。ファイル末尾に達する前の空でない読み取りごとに、カーネルの乱数源から新しい値を生成し、指定の範囲を返します。短い読み取りを繰り返すと、異なる UUID の断片が返る場合があります。完全な UUID を得るには、オフセット 0 から一度に 37 バイトを読み取ります。乱数源のエラーはそのまま返され、後続の読み取りで再試行できます。" + msgid "``/proc/sys/fs/nr_open``:描述符实现上限。" msgstr "``/proc/sys/fs/nr_open``:記述子の実装上の上限。" diff --git a/Documentation/userspace-api/procfs.rst b/Documentation/userspace-api/procfs.rst index 6ff808f3..6551230a 100644 --- a/Documentation/userspace-api/procfs.rst +++ b/Documentation/userspace-api/procfs.rst @@ -144,12 +144,15 @@ dup 共享已打开的视图,重新打开会生成新视图。快照不采用 策略节点 ======== -以下节点是现行内核策略的只读快照,不支持通过写文件调整: +以下节点提供只读内核信息,不支持通过写文件调整: * ``/proc/sys/kernel/pid_max``:非零 32 位 PID 命名空间上限。 * ``/proc/sys/kernel/random/boot_id``:本次启动的 UUID v4。格式为带连字符的小写十六进制字符串, 末尾带换行,同一次启动中的所有 proc 挂载读取相同值。首次有效读取由内核随机源生成; 随机源报错时返回原错误,后续读取可重试。 +* ``/proc/sys/kernel/random/uuid``:同样以带换行的 UUID v4 文本输出。每次非空且未到文件末尾的读取 + 都先从内核随机源生成新值,再按偏移和长度截取;分多次短读可能读到不同 UUID 的片段。 + 需要完整 UUID 时应从偏移 0 一次读取 37 字节。随机源错误原样返回,后续读取可重试。 * ``/proc/sys/fs/nr_open``:描述符实现上限。 * ``/proc/sys/fs/file-nr``:实际已分配 OFD、零个闲置预分配 OFD、全局上限。 dup/fork 别名不重复计数,排队、映射或进行中 I/O 保留的 OFD 直到最终释放才减计数。 diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 033a5ebc..39950f37 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -34,6 +34,7 @@ #define PROCFS_CONTENT_MAX 1024u #define PROCFS_RANDOM_DIR "/proc/sys/kernel/random" #define PROCFS_BOOT_ID PROCFS_RANDOM_DIR "/boot_id" +#define PROCFS_UUID PROCFS_RANDOM_DIR "/uuid" static int proc_text_eq(const char *a, const char *b) { @@ -336,39 +337,43 @@ static int proc_fill_content(const char *path, char *buffer, uint32_t capacity) } /** - * @brief Read one slice of the boot-wide UUID v4, shared by all proc mounts. + * @brief Read one slice of a UUID v4 from the kernel random source. + * @param boot_scoped Reuse the boot-wide ID instead of generating a new UUID for this read. * @param offset Byte position including the final newline. * @param buffer Kernel destination; may be NULL only if length is zero. * @param length Writable byte capacity. * @param out_read Optional byte count, already cleared by proc_read. - * @return Zero or a negative entropy-source error. The first successful + * @return Zero or a negative entropy-source error. For boot_id the first successful * nonempty read publishes the ID under an IRQ-safe lock for the rest of the boot. */ -static int proc_boot_id_read(uint64_t offset, void *buffer, uint32_t length, - uint32_t *out_read) +static int proc_uuid_read(bool boot_scoped, uint64_t offset, void *buffer, uint32_t length, + uint32_t *out_read) { - enum { boot_id_text_length = sizeof("00000000-0000-0000-0000-000000000000\n") - 1 }; + enum { uuid_text_length = sizeof("00000000-0000-0000-0000-000000000000\n") - 1 }; static struct kernel_spinlock lock = KERNEL_SPINLOCK_INIT; static uint8_t boot_id[16]; static bool ready; uint8_t bytes[sizeof(boot_id)]; - uint64_t flags; - int rc = 0; + int rc; - if (!length || offset >= boot_id_text_length) return 0; - kernel_spin_lock_irqsave(&lock, &flags); - if (!ready) { - rc = kernel_random_fill(boot_id, sizeof(boot_id)); - if (!rc) { - boot_id[6] = (boot_id[6] & 0x0f) | 0x40; /* Version 4. */ - boot_id[8] = (boot_id[8] & 0x3f) | 0x80; /* RFC UUID variant. */ - ready = true; + if (!length || offset >= uuid_text_length) return 0; + if (boot_scoped) { + uint64_t flags; + rc = 0; + kernel_spin_lock_irqsave(&lock, &flags); + if (!ready) { + rc = kernel_random_fill(boot_id, sizeof(boot_id)); + ready = !rc; } + if (!rc) __builtin_memcpy(bytes, boot_id, sizeof(bytes)); + kernel_spin_unlock_irqrestore(&lock, flags); + } else { + rc = kernel_random_fill(bytes, sizeof(bytes)); } - if (!rc) __builtin_memcpy(bytes, boot_id, sizeof(bytes)); - kernel_spin_unlock_irqrestore(&lock, flags); if (rc) return rc; + bytes[6] = (bytes[6] & 0x0f) | 0x40; /* Version 4. */ + bytes[8] = (bytes[8] & 0x3f) | 0x80; /* RFC UUID variant. */ struct text_stream stream = {.offset = offset, .buffer = buffer, .capacity = length}; for (unsigned i = 0; i < sizeof(bytes); ++i) { if (i == 4 || i == 6 || i == 8 || i == 10) text_string(&stream, "-"); @@ -987,7 +992,8 @@ int proc_lookup(const char *path, struct storage_node *out) } #endif if (proc_memory_is_file(path) || proc_mount_view(path,NULL) || - proc_text_eq(path, PROCFS_BOOT_ID) || proc_text_eq(path,"/proc/cpuinfo") || + proc_text_eq(path, PROCFS_BOOT_ID) || proc_text_eq(path, PROCFS_UUID) || + proc_text_eq(path,"/proc/cpuinfo") || proc_text_eq(path,"/proc/leonos-drivers")) { if (out) *out = (struct storage_node){ .type = RELIEFOS_FS_TYPE_FILE, .flags = STORAGE_NODE_FLAG_PROC, @@ -1102,7 +1108,8 @@ int proc_lookup(const char *path, struct storage_node *out) * @return Zero or negative errno, preserving backend failures. Execution-owned; * retains no caller memory and live generated views can change between reads. * A cgroup membership record reflects a single locked ancestry snapshot; - * boot_id remains fixed throughout the boot. */ + * boot_id remains fixed throughout the boot, whereas each in-range nonempty + * random/uuid read generates a new UUID before slicing at the requested offset. */ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, uint32_t *out_read) { @@ -1111,7 +1118,9 @@ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, if (!path || (!buffer && length)) return -RELIEFOS_EINVAL; if (proc_text_eq(path, PROCFS_BOOT_ID)) - return proc_boot_id_read(offset, buffer, length, out_read); + return proc_uuid_read(true, offset, buffer, length, out_read); + if (proc_text_eq(path, PROCFS_UUID)) + return proc_uuid_read(false, offset, buffer, length, out_read); if (proc_extra_kind(path) == 1) { struct text_stream stream = {.offset = offset, .buffer = buffer, .capacity = length}; int rc = proc_extra_emit(path, &stream); @@ -1352,9 +1361,10 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * } #endif if (proc_text_eq(path, PROCFS_RANDOM_DIR)) { - if (*offset) return 0; - *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_FILE, .name = "boot_id"}; - *offset = 1; + if (*offset >= 2) return 0; + *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_FILE}; + proc_copy(entry->name, sizeof(entry->name), *offset ? "uuid" : "boot_id"); + ++*offset; return 1; } if (proc_text_eq(path, "/proc/sys") || proc_text_eq(path, "/proc/sys/kernel")) { diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index c4a838d9..d3654802 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -14,8 +14,9 @@ int sound_service_card_snapshot(uint32_t index, uint32_t *out_id, static unsigned proc_entropy_calls; static bool proc_entropy_fails = true; +static uint8_t proc_entropy_next = 1; -/** @brief Model the bounded hardware entropy source used by proc boot_id. +/** @brief Supply distinguishable samples for the real proc UUID handlers. * @param buffer Writable byte array. @param length Must be 16 bytes. * @return Zero on success or negative EIO for the injected failure. */ @@ -27,6 +28,7 @@ int kernel_random_fill(void *buffer, size_t length) ++proc_entropy_calls; if (proc_entropy_fails) return -EIO; memcpy(buffer, sample, length); + ((uint8_t *)buffer)[0] = proc_entropy_next++; return 0; } @@ -871,8 +873,8 @@ static void test_proc_mount_namespace_handles(void) puts("PASS proc namespace aliases, permissions, stable identity and PID reuse"); } -/** @brief Verify stable, read-only boot identity through independent proc mounts. */ -static void test_proc_boot_id(void) +/** @brief Verify stable boot identity, fresh UUIDs and entropy retry via proc mounts. */ +static void test_proc_random_uuid(void) { struct vfs_namespace ns[2] = {0}; struct vfs_path root[2] = {0}, boot_id[2] = {0}; @@ -901,7 +903,6 @@ static void test_proc_boot_id(void) cursor = 0; assert(vfs_path_readdir(&random, &cursor, &entry) == 1 && !strcmp(entry.name, "boot_id") && entry.type == RELIEFOS_FS_TYPE_FILE); - assert(!vfs_path_readdir(&random, &cursor, &entry)); struct linux_stat_abi st; assert(!vfs_path_stat(&random, &st) && st.st_mode == (LINUX_S_IFDIR | 0555)); @@ -924,6 +925,32 @@ static void test_proc_boot_id(void) assert(!vfs_path_read(&boot_id[1], 0, text, sizeof(text), &got) && got == sizeof(expected) - 1); assert(!memcmp(text, expected, sizeof(expected)) && proc_entropy_calls == 2); + struct vfs_path uuid = {0}; + assert(!vfs_path_lookup(&ns[0], &root[0], &random, "uuid", 0, &uuid)); + assert(vfs_path_readdir(&random, &cursor, &entry) == 1 && + !strcmp(entry.name, "uuid") && entry.type == RELIEFOS_FS_TYPE_FILE); + assert(!vfs_path_readdir(&random, &cursor, &entry)); + assert(!vfs_path_stat(&uuid, &st) && st.st_mode == (LINUX_S_IFREG | 0444) && + st.st_size == 0 && !st.st_uid && !st.st_gid); + assert(vfs_path_truncate(&uuid, 0) == -EROFS); + assert(!vfs_path_read(&uuid, 0, text, 0, &got) && !got); + assert(!vfs_path_read(&uuid, sizeof(expected) - 1, text, sizeof(text), &got) && !got); + assert(!memcmp(text, expected, sizeof(expected)) && proc_entropy_calls == 2); + assert(vfs_path_read(&uuid, 0, text, sizeof(text), &got) == -EIO && !got); + assert(!memcmp(text, expected, sizeof(expected))); + proc_entropy_fails = false; + assert(!vfs_path_read(&uuid, 0, text, sizeof(text), &got) && got == 37 && + !memcmp(text, "02234567-89ab-4def-b510-32547698badc\n", 37)); + assert(!vfs_path_read(&uuid, 0, text, sizeof(text), &got) && got == 37 && + !memcmp(text, "03234567-89ab-4def-b510-32547698badc\n", 37)); + assert(!vfs_path_read(&uuid, 0, text, 2, &got) && got == 2 && !memcmp(text, "04", 2)); + assert(!vfs_path_read(&uuid, 1, text, sizeof(text), &got) && got == 36 && + !memcmp(text, "5234567-89ab-4def-b510-32547698badc\n", 36)); + assert(!vfs_path_read(&uuid, 36, text, sizeof(text), &got) && got == 1 && text[0] == '\n'); + assert(!vfs_path_read(&boot_id[0], 0, text, sizeof(text), &got) && got == 37 && + !memcmp(text, expected, sizeof(expected))); + + vfs_path_put(&uuid); vfs_path_put(&random); vfs_path_put(&kernel); for (unsigned i = 0; i < 2; ++i) { @@ -932,12 +959,12 @@ static void test_proc_boot_id(void) assert(!vfs_namespace_destroy(&ns[i])); } assert(proc_allocations == before); - puts("PASS proc boot_id lookups, UUID format, stable partial reads and entropy retry"); + puts("PASS proc random UUID reads, stable boot ID and entropy retry"); } int main(void) { - test_proc_boot_id(); + test_proc_random_uuid(); test_proc_fd_metadata(); test_proc_fd_object_link(); test_proc_mount_objects(); From 4d03a7cb0671e335de5f7a69e49fc545311da037 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 20:39:40 +0800 Subject: [PATCH 49/97] feat(process): support child subreapers and orphan adoption --- .../en/LC_MESSAGES/userspace-api/abi.po | 9 + .../ja/LC_MESSAGES/userspace-api/abi.po | 9 + Documentation/userspace-api/abi.rst | 13 ++ include/reliefnt/task/types.h | 2 + include/uapi/linux/prctl.h | 4 + kernel/sched/clone.c | 2 + kernel/sched/exec.c | 6 +- kernel/sched/internal.h | 7 + kernel/sched/signal.c | 24 ++- kernel/sched/task.c | 161 ++++++++++-------- kernel/syscall/process/process.c | 18 ++ tools/test_exit_logging.py | 33 ++-- tools/tests/Makefile | 2 +- tools/tests/task_subreaper_test.c | 129 ++++++++++++++ 14 files changed, 325 insertions(+), 94 deletions(-) create mode 100644 tools/tests/task_subreaper_test.c diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 2018af27..ea27b2e6 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -48,6 +48,15 @@ msgstr "" " across the kernel, exported headers, userspace wrappers, consumers, and necessary validation. " "Updating golden data does not replace layout or semantic review." +msgid "孤儿进程接管" +msgstr "Orphan Process Adoption" + +msgid "``PR_SET_CHILD_SUBREAPER`` 的第二个参数为非零时启用,为零时清除。 ``PR_GET_CHILD_SUBREAPER`` 将当前状态(0 或 1)写入第二个参数指向的用户态 ``int``。不需要特权。同一进程内的线程共享该状态;fork 和创建新进程的 clone 不继承该状态,exec 保留。" +msgstr "``PR_SET_CHILD_SUBREAPER`` enables the setting with a nonzero second argument and clears it with zero. ``PR_GET_CHILD_SUBREAPER`` writes the current state (0 or 1) to the user-space ``int`` pointed to by its second argument. No privilege is required. Threads in the process share this state; fork and clone that creates a new process do not inherit it, and exec preserves it." + +msgid "创建子进程的线程退出时,若其进程仍有活动线程,则不改变子进程的可见父进程。 最后一个活动线程退出后,最近的仍存活且已启用接管的祖先进程成为新父进程; 没有这种祖先则回退到 PID 1。新父进程可等待被接管的子进程,并按 SIGCHLD 规则 接收退出通知。当前不提供独立的 PID 命名空间。" +msgstr "When the thread that created a child exits, the child's visible parent process is unchanged if that process has other living threads. Once the last living thread exits, the nearest living ancestor with subreaping enabled becomes the new parent, falling back to PID 1 if none exists. The new parent can wait for adopted children and receives exit notifications according to the SIGCHLD rules. Separate PID namespaces are not implemented." + msgid "创建挂载命名空间" msgstr "Creating a mount namespace" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 51d84cb8..430fd45f 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -43,6 +43,15 @@ msgstr "" "に見せかけてはなりません。利用可能とみなせるのは実装済みのインターフェースだけで、ヘッダーの存在は完全な実行時認証の代わりにはなりません。インターフェース変更はカーネル、公開ヘッダー、ユーザー空間ラッパー、利用側、必要な検証に同期して反映し、golden" " データの更新でレイアウトや意味の審査を代替しません。" +msgid "孤儿进程接管" +msgstr "孤児プロセスの引き取り" + +msgid "``PR_SET_CHILD_SUBREAPER`` 的第二个参数为非零时启用,为零时清除。 ``PR_GET_CHILD_SUBREAPER`` 将当前状态(0 或 1)写入第二个参数指向的用户态 ``int``。不需要特权。同一进程内的线程共享该状态;fork 和创建新进程的 clone 不继承该状态,exec 保留。" +msgstr "``PR_SET_CHILD_SUBREAPER`` は第 2 引数が非ゼロなら設定を有効にし、ゼロなら解除します。``PR_GET_CHILD_SUBREAPER`` は現在の状態(0 または 1)を、第 2 引数が指すユーザー空間の ``int`` に書き込みます。特権は不要です。同じプロセス内のスレッドで状態を共有します。fork や新規プロセスを作成する clone では継承されず、exec では保持されます。" + +msgid "创建子进程的线程退出时,若其进程仍有活动线程,则不改变子进程的可见父进程。 最后一个活动线程退出后,最近的仍存活且已启用接管的祖先进程成为新父进程; 没有这种祖先则回退到 PID 1。新父进程可等待被接管的子进程,并按 SIGCHLD 规则 接收退出通知。当前不提供独立的 PID 命名空间。" +msgstr "子を作成したスレッドが終了しても、そのプロセスに生存しているスレッドがあれば、子から見える親プロセスは変わりません。最後の生存スレッドが終了すると、引き取りを有効にした最も近い生存祖先が新しい親となり、該当する祖先がいなければ PID 1 が引き取ります。新しい親は引き取った子を待機でき、SIGCHLD の規則に従って終了通知を受け取ります。独立した PID 名前空間は未実装です。" + msgid "创建挂载命名空间" msgstr "マウント名前空間の作成" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 0d5aa0a0..90f02234 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -37,6 +37,19 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。 +孤儿进程接管 +============ + +``PR_SET_CHILD_SUBREAPER`` 的第二个参数为非零时启用,为零时清除。 +``PR_GET_CHILD_SUBREAPER`` 将当前状态(0 或 1)写入第二个参数指向的用户态 +``int``。不需要特权。同一进程内的线程共享该状态;fork 和创建新进程的 clone +不继承该状态,exec 保留。 + +创建子进程的线程退出时,若其进程仍有活动线程,则不改变子进程的可见父进程。 +最后一个活动线程退出后,最近的仍存活且已启用接管的祖先进程成为新父进程; +没有这种祖先则回退到 PID 1。新父进程可等待被接管的子进程,并按 SIGCHLD 规则 +接收退出通知。当前不提供独立的 PID 命名空间。 + 创建挂载命名空间 ================ diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index 5abd355b..c0b77ade 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -546,6 +546,8 @@ struct task { bool nproc_exceeded; /* Copied by fork/clone and retained by exec; only uname.sysname changes. */ bool uname_linux; + /* Process property on the thread-group leader; accessed atomically at runtime. */ + bool child_subreaper; #ifdef CONFIG_SECCOMP_FILTER struct seccomp_filter *seccomp_filter; uint32_t seccomp_count; /* Last published count, also visible for zombies. */ diff --git a/include/uapi/linux/prctl.h b/include/uapi/linux/prctl.h index 1a120718..7e8c98e8 100644 --- a/include/uapi/linux/prctl.h +++ b/include/uapi/linux/prctl.h @@ -15,10 +15,14 @@ #define LINUX_PR_SET_SECUREBITS 28 #define PR_GET_SECCOMP 21 #define PR_SET_SECCOMP 22 +#define PR_SET_CHILD_SUBREAPER 36 +#define PR_GET_CHILD_SUBREAPER 37 #define PR_SET_NO_NEW_PRIVS 38 #define PR_GET_NO_NEW_PRIVS 39 #define LINUX_PR_GET_SECCOMP PR_GET_SECCOMP #define LINUX_PR_SET_SECCOMP PR_SET_SECCOMP +#define LINUX_PR_SET_CHILD_SUBREAPER PR_SET_CHILD_SUBREAPER +#define LINUX_PR_GET_CHILD_SUBREAPER PR_GET_CHILD_SUBREAPER #define LINUX_PR_SET_NO_NEW_PRIVS PR_SET_NO_NEW_PRIVS #define LINUX_PR_GET_NO_NEW_PRIVS PR_GET_NO_NEW_PRIVS #define LINUX_PR_CAP_AMBIENT 47 diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index 3055b7d1..104efb35 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -243,6 +243,8 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag *child = *parent; /* Borrowed by the shallow copy; only successful publication takes a charge. */ child->cgroup = NULL; + /* Forked processes start unset and new threads use their existing leader. */ + child->child_subreaper = false; #ifdef CONFIG_SECCOMP_FILTER /* The shallow copy hasn't taken a reference, nor does a new thread * inherit a pending synchronous signal. */ diff --git a/kernel/sched/exec.c b/kernel/sched/exec.c index 7a889857..21e67123 100644 --- a/kernel/sched/exec.c +++ b/kernel/sched/exec.c @@ -128,8 +128,9 @@ int sched_set_task_exec_params(uint32_t pid, uint32_t argc, char *const argv[], * @param task Current task under exclusive execution ownership; required. * @return Zero when ready, negative file-table error, or EAGAIN while a remote * sibling is retiring. Retains the filesystem state shared via CLONE_FS. - * During de-threading, the retired leader's PID charge does not follow its - * PID to the surviving task. Called without scheduler_lock; takes it for signals. + * During de-threading, the child subreaper setting follows the process + * identity; the retired leader's PID charge does not. Called without + * scheduler_lock; takes it for signals and the leader handover. */ int sched_prepare_exec_current(struct task *task) { @@ -187,6 +188,7 @@ int sched_prepare_exec_current(struct task *task) task->parent_pid = leader->parent_pid; task->parent_exit_signal = leader->parent_exit_signal; task->parent_exit_notified = 0; + task->child_subreaper = __atomic_load_n(&leader->child_subreaper, __ATOMIC_RELAXED); task->flags |= leader->flags & TASK_FLAG_WAITABLE_CHILD; leader->flags &= ~TASK_FLAG_WAITABLE_CHILD; if (cgroup2_task_reap) cgroup2_task_reap(leader); diff --git a/kernel/sched/internal.h b/kernel/sched/internal.h index e4d75acb..081ae1db 100644 --- a/kernel/sched/internal.h +++ b/kernel/sched/internal.h @@ -787,6 +787,13 @@ void sched_signalfd_reconfigure(struct task *updater); void sched_wake_process_signal(uint32_t tgid, uint64_t bit); +/** @brief Report a waitable group exit once to its current parent. + * @param leader Group leader, nullable. Caller holds scheduler_lock. + */ +void sched_notify_parent_exit_locked(struct task *leader); +/** @brief Report group exit after a member finishes cleanup. + * @param task Retiring member, retained by caller. Takes scheduler_lock. + */ void sched_notify_parent_exit(struct task *task); void sched_itimer_task(struct task *task, const struct linux_itimerval *value, struct linux_itimerval *old); diff --git a/kernel/sched/signal.c b/kernel/sched/signal.c index 35e988a3..7c2a7c3a 100644 --- a/kernel/sched/signal.c +++ b/kernel/sched/signal.c @@ -52,16 +52,13 @@ void sched_wake_process_signal(uint32_t tgid, uint64_t bit) if (woke) sched_request_reschedule_all_online(); } -void sched_notify_parent_exit(struct task *task) +/** @brief Notify the current parent of a waitable group exit if not yet reported. + * @param leader Group leader, nullable. Caller holds scheduler_lock. + */ +void sched_notify_parent_exit_locked(struct task *leader) { - uint64_t flags; - kernel_spin_lock_irqsave(&scheduler_lock, &flags); - struct task *leader = sched_find(sched_task_tgid(task)); if (!leader || leader->state != TASK_EXITED || leader->running_cpu != SCHED_CPU_NONE || - thread_group_pending(leader->pid, leader) || leader->parent_exit_notified) { - kernel_spin_unlock_irqrestore(&scheduler_lock, flags); - return; - } + thread_group_pending(leader->pid, leader) || leader->parent_exit_notified) return; leader->parent_exit_notified = 1; unsigned sig = leader->parent_exit_signal; if (leader->parent_pid && sig && sig < KERNEL_SIGNAL_ACTION_MAX) { @@ -76,6 +73,17 @@ void sched_notify_parent_exit(struct task *task) break; } } +} + +/** @brief Notify the current parent after a thread finishes exit cleanup. + * @param task Retiring group member, retained by the caller. + * Takes scheduler_lock to resolve the leader and its current parent together. + */ +void sched_notify_parent_exit(struct task *task) +{ + uint64_t flags; + kernel_spin_lock_irqsave(&scheduler_lock, &flags); + sched_notify_parent_exit_locked(sched_find(sched_task_tgid(task))); kernel_spin_unlock_irqrestore(&scheduler_lock, flags); } diff --git a/kernel/sched/task.c b/kernel/sched/task.c index 09e7dd41..ec9cc5d4 100644 --- a/kernel/sched/task.c +++ b/kernel/sched/task.c @@ -576,19 +576,108 @@ int sched_publish_user_task(uint32_t pid) return rc; } +/** @brief Choose a living reaper thread, preferring the process leader. + * @param leader Borrowed process leader, nullable. + * @return Borrowed live member, or NULL. Caller holds scheduler_lock. + * Already exited threads awaiting remote CPU or resource retirement cannot reap. + */ +static const struct task *sched_live_reaper_thread_locked(const struct task *leader) +{ + if (!leader || leader->kind != TASK_KIND_USER || + (leader->flags & TASK_FLAG_LAUNCH_PREPARING)) return NULL; + if (leader->state != TASK_EXITED) return leader; + for (uint32_t i = 0; i < task_count; ++i) { + const struct task *member = tasks[i]; + if (member->pid && member->state != TASK_EXITED && sched_task_tgid(member) == leader->pid) + return member; + } + return NULL; +} + +/** @brief Choose the nearest live ancestor subreaper, otherwise PID 1. + * @param exiting Task in a process that has no living thread. + * @return Borrowed live reaper thread, or NULL before init exists. + * Caller holds scheduler_lock; the current kernel has one PID namespace. + */ +static const struct task *sched_ancestor_reaper_locked(const struct task *exiting) +{ + uint32_t ancestor_pid = exiting->parent_pid; + for (uint32_t depth = 0; ancestor_pid > 1 && depth < task_count; ++depth) { + const struct task *ancestor = sched_find(ancestor_pid); + if (!ancestor) break; + if (__atomic_load_n(&ancestor->child_subreaper, __ATOMIC_RELAXED)) { + const struct task *reaper = sched_live_reaper_thread_locked(ancestor); + if (reaper) return reaper; + } + ancestor_pid = ancestor->parent_pid; + } + return sched_live_reaper_thread_locked(sched_find(1)); +} + +/** @brief Update process and creating-thread parent links after a first exit. + * @param exiting Just-exited task, still retained in the task table. + * Caller holds scheduler_lock. A live sibling retains process parentage. + * A fully adopted zombie is notified under the same lock as its new parent + * assignment, so a later reaper exit cannot redirect a stale signal. + */ +static void sched_reparent_on_exit_locked(const struct task *exiting) +{ + uint32_t tgid = sched_task_tgid(exiting); + const struct task *leader = exiting->pid == tgid ? exiting : sched_find(tgid); + const struct task *sibling = sched_live_reaper_thread_locked(leader); + const struct task *reaper = sibling; + bool resolved = sibling != NULL; + if (!sibling) { + const struct task *old_parent = sched_find(exiting->parent_pid); + if (old_parent && old_parent->process_group != exiting->process_group && + old_parent->process_session == exiting->process_session) + sched_mark_orphaned_group(exiting->process_group); + } + for (uint32_t i = 0; i < task_count; ++i) { + struct task *child = tasks[i]; + if (!child->pid) continue; + bool lost_thread = child->pdeath_parent_pid == exiting->pid; + bool lost_process = !sibling && child->parent_pid == tgid; + if (!lost_thread && !lost_process) continue; + if (!resolved) { + reaper = sched_ancestor_reaper_locked(exiting); + resolved = true; + } + if (lost_thread) { + if (child->pdeath_signal) child->flags |= TASK_FLAG_PDEATH_NOTIFY; + child->pdeath_parent_pid = reaper ? reaper->pid : 0; + } + if (!lost_process) continue; + child->parent_pid = reaper ? sched_task_tgid(reaper) : 0; + if (!reaper) { + child->flags &= ~TASK_FLAG_WAITABLE_CHILD; + if (child->state == TASK_EXITED && cgroup2_task_reap) cgroup2_task_reap(child); + } else if (child->pid == sched_task_tgid(child) && + !(child->flags & TASK_FLAG_LAUNCH_PREPARING)) { + child->parent_exit_signal = 17; /* SIGCHLD */ + child->parent_exit_notified = 0; + child->flags |= TASK_FLAG_WAITABLE_CHILD; + if (child->flags & TASK_FLAG_RESOURCES_RELEASED) sched_notify_parent_exit_locked(child); + } + /* The new parent may still connect a stopped group to its session. */ + if (child->process_session == exiting->process_session && + child->process_group != exiting->process_group) + sched_mark_orphaned_group(child->process_group); + } +} + /** - * @brief Publish terminal task state and log its first exit after releasing the scheduler lock. + * @brief Publish terminal task state, hand over children and log the first exit. * @param pid Task identifier; PID 1 panics and an absent PID has no exit event. * @param code Exit status; repeated calls retain the existing status-update and cleanup semantics. * The caller must not hold scheduler_lock. Capture a bounded diagnostic under - * that lock, update cgroup population once, and defer resource release until - * the CPU reservation is quiescent. + * that lock, update cgroup population and parent links once, and defer resource + * release until the CPU reservation is quiescent. */ void sched_exit(uint32_t pid, uint64_t code) { uint64_t flags; bool gpu_owner_quiescent = false; - bool adopted_zombie = false; bool exit_event = false; uint32_t exit_pid = 0; uint64_t exit_code = 0; @@ -618,65 +707,7 @@ void sched_exit(uint32_t pid, uint64_t code) break; } } - if (exiting && !thread_group_pending(sched_task_tgid(exiting), exiting)) { - const struct task *parent = sched_find(exiting->parent_pid); - if (parent && parent->process_group != exiting->process_group && - parent->process_session == exiting->process_session) - sched_mark_orphaned_group(exiting->process_group); - } - for (uint32_t i = 0; i < task_count; ++i) { - if (exiting && !thread_group_pending(sched_task_tgid(exiting), exiting) && - tasks[i]->parent_pid == sched_task_tgid(exiting)) { - if (tasks[i]->process_session == exiting->process_session && - tasks[i]->process_group != exiting->process_group) - sched_mark_orphaned_group(tasks[i]->process_group); - struct task *reaper = sched_find(1); - if (reaper && reaper != exiting && reaper->state != TASK_EXITED) { - tasks[i]->parent_pid = 1; - /* Thread siblings follow the parent relationship, but only - * process leaders become waitable children of PID 1. */ - if (tasks[i]->pid == sched_task_tgid(tasks[i]) && - !(tasks[i]->flags & TASK_FLAG_LAUNCH_PREPARING)) { - tasks[i]->parent_exit_signal = 17; - tasks[i]->parent_exit_notified = 0; - tasks[i]->flags |= TASK_FLAG_WAITABLE_CHILD; - if (tasks[i]->state == TASK_EXITED && - tasks[i]->running_cpu == SCHED_CPU_NONE && - !thread_group_pending(tasks[i]->pid, tasks[i])) adopted_zombie = true; - } - } else { - tasks[i]->parent_pid = 0; - tasks[i]->flags &= ~TASK_FLAG_WAITABLE_CHILD; - if (tasks[i]->state == TASK_EXITED && cgroup2_task_reap) cgroup2_task_reap(tasks[i]); - } - } - } - if (exiting && exit_event) { - /* Reparent the real-parent link within the surviving thread group - * first. Only a dying group hands children to init. This link also - * determines which thread can wait with __WNOTHREAD. */ - uint32_t reaper_pid = 0; - if (exiting->kind == TASK_KIND_USER) { - uint32_t group = sched_task_tgid(exiting); - for (uint32_t i = 0; i < task_count; ++i) { - const struct task *candidate = tasks[i]; - if (candidate->pid && candidate->state != TASK_EXITED && - sched_task_tgid(candidate) == group) { - reaper_pid = candidate->pid; - break; - } - } - } - if (!reaper_pid) { - const struct task *init = sched_find(1); - if (init && init->state != TASK_EXITED) reaper_pid = 1; - } - for (uint32_t i = 0; i < task_count; ++i) { - if (tasks[i]->pdeath_parent_pid != exit_pid) continue; - if (tasks[i]->pdeath_signal) tasks[i]->flags |= TASK_FLAG_PDEATH_NOTIFY; - tasks[i]->pdeath_parent_pid = reaper_pid; - } - } + if (exit_event) sched_reparent_on_exit_locked(exiting); if (exiting) { /* Detach a dying parent before its task slot can be reused. */ vfork_parent_exit_locked(exiting); @@ -691,10 +722,6 @@ void sched_exit(uint32_t pid, uint64_t code) exit_name, (unsigned long long)exit_code); } - if (adopted_zombie) { - struct task *reaper = sched_find(1); - if (reaper && reaper->state != TASK_EXITED) sched_signal_user_process(1, 17); - } /* Signal delivery takes scheduler locks itself and may terminate a group. */ for (uint32_t i = 0; i < task_count; ++i) { struct task *task = tasks[i]; diff --git a/kernel/syscall/process/process.c b/kernel/syscall/process/process.c index 427cc814..fc3f854c 100644 --- a/kernel/syscall/process/process.c +++ b/kernel/syscall/process/process.c @@ -346,6 +346,7 @@ int64_t syscall_linux_signal(uint64_t number, uint64_t signal_number, * @param arg5 Selector-specific value; reserved for uname selection. * @return Operation result or negative errno. Uname selection needs no * capability and affects only this task and subsequently created descendants. + * Child subreaper selection is unprivileged and shared by the thread group. */ int64_t syscall_process_prctl(uint64_t option, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5) @@ -395,6 +396,23 @@ int64_t syscall_process_prctl(uint64_t option, uint64_t arg2, uint64_t arg3, if (arg2 > 1) return -RELIEFOS_EINVAL; sched_task_mm(task)->nondumpable = !arg2; return 0; + case LINUX_PR_SET_CHILD_SUBREAPER: + case LINUX_PR_GET_CHILD_SUBREAPER: { + /* Execution ownership pins this process's group leader, even if its + * own thread has exited; adoption can sample the flag under scheduler_lock. */ + struct task *leader = sched_find(sched_task_tgid(task)); + if (!leader) return -LINUX_ESRCH; + if ((uint32_t)option == LINUX_PR_SET_CHILD_SUBREAPER) { + __atomic_store_n(&leader->child_subreaper, arg2 != 0, __ATOMIC_RELAXED); + return 0; + } + int prep = process_prepare_user(task, arg2, sizeof(int), true); + if (prep) return prep; + if (!user_range_writable(arg2, sizeof(int))) return -LINUX_EFAULT; + int active = __atomic_load_n(&leader->child_subreaper, __ATOMIC_RELAXED); + __builtin_memcpy((void *)(uintptr_t)arg2, &active, sizeof(active)); + return 0; + } case LINUX_PR_SET_NO_NEW_PRIVS: if (arg2 != 1 || arg3 || arg4 || arg5) return -RELIEFOS_EINVAL; task->no_new_privs = true; diff --git a/tools/test_exit_logging.py b/tools/test_exit_logging.py index 2b355b02..513e0a18 100644 --- a/tools/test_exit_logging.py +++ b/tools/test_exit_logging.py @@ -1,10 +1,8 @@ #!/usr/bin/env python3 -"""Build and run the task-exit logging contract fixture. +"""Build and run the task-exit logging and subreaper contract fixtures. -The fixture compiles the real scheduler exit path and the userland exit stub -against a host harness, so a failure means the kernel no longer emits exactly -one exit event per task, emits it while holding the scheduler lock, or loses the -pid/name/code snapshot it captured under that lock. +The fixtures compile the real scheduler exit path, covering the one-time +unlocked diagnostic and the new owner's SIGCHLD and wait after reparenting. """ from pathlib import Path import subprocess @@ -20,17 +18,20 @@ def main() -> int: with tempfile.TemporaryDirectory(prefix="reliefos-exit-log-") as directory: - binary = Path(directory) / "task-exit-logging" - subprocess.run( - ["clang", "-std=c11", "-g", "-O1", - "-ffunction-sections", "-fdata-sections", - "-fsanitize=address,undefined", "-fno-sanitize-recover=all", - *INCLUDES, "-Wl,--gc-sections", - "tools/tests/task_exit_logging_test.c", "fs/vfs/lookup_cache.c", "-o", str(binary)], - cwd=ROOT, check=True) - result = subprocess.run([str(binary)], cwd=ROOT, timeout=30) - print("task-exit-logging: " + ("PASS" if result.returncode == 0 else "FAIL")) - return result.returncode + for fixture in ("task_exit_logging", "task_subreaper"): + binary = Path(directory) / fixture + subprocess.run( + ["clang", "-std=c11", "-g", "-O1", + "-ffunction-sections", "-fdata-sections", + "-fsanitize=address,undefined", "-fno-sanitize-recover=all", + *INCLUDES, "-Wl,--gc-sections", + f"tools/tests/{fixture}_test.c", "fs/vfs/lookup_cache.c", "-o", str(binary)], + cwd=ROOT, check=True) + result = subprocess.run([str(binary)], cwd=ROOT, timeout=30) + print(f"{fixture}: " + ("PASS" if result.returncode == 0 else "FAIL")) + if result.returncode: + return result.returncode + return 0 if __name__ == "__main__": diff --git a/tools/tests/Makefile b/tools/tests/Makefile index 6006c10d..d717c4c9 100644 --- a/tools/tests/Makefile +++ b/tools/tests/Makefile @@ -12,7 +12,7 @@ test-host: test-host-smoke: $(Q)$(RELIEFNT_HOST_TEST_RUN) --suite boot_policy --suite brand_identity --suite gpu_usercopy --suite drm \ --suite loadavg --suite input --suite input_routing --suite uapi --suite seccomp_bpf \ - --suite acpi_pm_timer --suite apic_timer --suite cpu_accounting \ + --suite acpi_pm_timer --suite apic_timer --suite cpu_accounting --suite exit_logging \ --suite fat_async_read --suite fat_read_split \ --suite squashfs --suite squashfs_boot \ --suite linux_pty --suite linux_resources --suite mount_backend --suite mount_namespace_task --suite cgroup_scheduler \ diff --git a/tools/tests/task_subreaper_test.c b/tools/tests/task_subreaper_test.c new file mode 100644 index 00000000..06156300 --- /dev/null +++ b/tools/tests/task_subreaper_test.c @@ -0,0 +1,129 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +/** @file @brief Exercise prctl and orphan adoption through the real scheduler. */ +#define main exit_logging_fixture_main +#include "task_exit_logging_test.c" +#undef main +#include "../../kernel/syscall/process/process.c" + +/* Linux x86-64 ABI numbers, independent of the kernel's dispatch table. */ +enum { SUBREAPER_SET = 36, SUBREAPER_GET = 37, CHILD_SIGNAL = 17 }; + +/** @brief Check the fixture's user-buffer boundary. + * @param address Host operand. @param length Byte count. + * @return True for ranges admitted by the fixture. + */ +bool user_range_ok(uint64_t address, uint64_t length) +{ + return address >= 4096 && length <= UINT64_MAX - address; +} + +/** @brief Check a writable user operand. + * @param address Host operand. @param length Byte count. + * @return True for ranges admitted by the fixture. + */ +bool user_range_writable(uint64_t address, uint64_t length) +{ + return user_range_ok(address, length); +} + +/** @brief No file tables are shared in the synthetic thread group. + * @param task The caller replacing its image. @return Zero for its empty table. + */ +int syscall_unshare_task_files(struct task *task) +{ + assert(task == sched_current_task() && !task->shared_files); + return 0; +} + +/** @brief There is no shared signal queue to detach in the synthetic group. + * @param task The exec caller, with scheduler lock held. + */ +void kernel_signal_detach_process(struct task *task) +{ + assert(scheduler_lock_depth && task == sched_current_task() && !task->shared_process_signal_queue); +} + +/** @brief Select the simulated current task on the fixture's CPU. @param task New caller. */ +static void select_caller(struct task *task) +{ + current_pid[0] = task->pid; + current_task[0] = task; +} + +/** @brief Link a synthetic process to its creating thread. + * @param child Borrowed child. @param creator Borrowed parent thread. + */ +static void link_child(struct task *child, const struct task *creator) +{ + child->parent_pid = sched_task_tgid(creator); + child->pdeath_parent_pid = creator->pid; +} + +/** @brief Check prctl, subsequent orphan ownership, SIGCHLD and wait. @return Zero on success. */ +int main(void) +{ + struct task *init = fixture_task(1, "init"); + struct task *outer = fixture_task(40, "outer-reaper"); + struct task *near = fixture_task(41, "near-reaper"); + struct task *exec_thread = fixture_task(42, "reaper-exec-thread"); + struct task *parent = fixture_task(43, "dying-parent"); + struct task *child = fixture_task(44, "live-child"); + struct task *zombie = fixture_task(45, "zombie-child"); + struct task *last_thread = fixture_task(46, "last-live-parent-thread"); + struct task *table[] = {init, outer, near, exec_thread, parent, child, zombie, last_thread}; + install_tasks(table, sizeof(table) / sizeof(table[0])); + link_child(outer, init); + link_child(near, outer); + link_child(exec_thread, outer); + exec_thread->tgid = near->pid; + exec_thread->flags = 0; + link_child(parent, exec_thread); + link_child(last_thread, exec_thread); + last_thread->tgid = parent->pid; + last_thread->flags = 0; + link_child(child, parent); + link_child(zombie, parent); + /* The old parent's exit must not itself supply the adopted zombie's SIGCHLD. */ + parent->parent_exit_signal = 0; + parent->running_cpu = 1; /* Already exited, but awaiting remote CPU quiescence. */ + + select_caller(outer); + struct { int flag; unsigned canary; } value = {-1, 0x12345678}; + assert(!syscall_process_prctl(SUBREAPER_GET, (uintptr_t)&value.flag, 1, 2, 3)); + assert(!value.flag && value.canary == 0x12345678); + assert(!syscall_process_prctl(SUBREAPER_SET, 1, 0, 0, 0)); + select_caller(exec_thread); + assert(!syscall_process_prctl(SUBREAPER_SET, UINT64_C(1) << 32, 1, 2, 3)); + select_caller(near); + assert(!syscall_process_prctl(SUBREAPER_GET, (uintptr_t)&value.flag, 0, 0, 0) && + value.flag == 1 && value.canary == 0x12345678); + assert(syscall_process_prctl(SUBREAPER_GET, 1, 0, 0, 0) == -LINUX_EFAULT); + select_caller(exec_thread); + assert(!sched_prepare_exec_current(exec_thread) && exec_thread->pid == 41); + assert(!syscall_process_prctl(SUBREAPER_GET, (uintptr_t)&value.flag, 0, 0, 0) && value.flag == 1); + + sched_exit(zombie->pid, 37); + assert(!*sched_task_process_pending(exec_thread)); + sched_exit(parent->pid, 24); + assert(child->parent_pid == parent->pid && child->pdeath_parent_pid == last_thread->pid); + sched_exit(last_thread->pid, 24); + assert(child->parent_pid == 41 && child->pdeath_parent_pid == 41); + assert(!sched_wait_reap(outer->pid, 45, LINUX_WEXITED, NULL, NULL)); + assert(*sched_task_process_pending(exec_thread) & (UINT64_C(1) << (CHILD_SIGNAL - 1))); + int status = 0; + assert(sched_wait_reap(41, 45, LINUX_WEXITED | LINUX_WNOTHREAD, &status, NULL) == 45 && + status == 37 << 8 && !sched_find(45)); + + assert(!syscall_process_prctl(SUBREAPER_SET, 0, 0, 0, 0)); + assert(!syscall_process_prctl(SUBREAPER_GET, (uintptr_t)&value.flag, 0, 0, 0) && !value.flag); + assert(child->parent_pid == 41); + sched_exit(41, 0); + assert(child->parent_pid == 40 && child->pdeath_parent_pid == 40); + sched_exit(40, 0); + assert(child->parent_pid == 1 && child->pdeath_parent_pid == 1); + + current_task[0] = NULL; + for (unsigned i = 0; i < sizeof(table) / sizeof(table[0]); ++i) free(table[i]); + puts("PASS subreaper prctl, thread-group exec, nearest adoption, SIGCHLD and wait"); + return 0; +} From c687864ffa9b3b9858d1b8a54570e12c926006a1 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 22:19:38 +0800 Subject: [PATCH 50/97] fix(cgroup): honor delegated pids limit write permissions --- .../userspace-api/device-filesystems.po | 7 +++++-- .../userspace-api/device-filesystems.po | 7 +++++-- .../userspace-api/device-filesystems.rst | 8 ++++++-- fs/cgroup/filesystem.c | 12 +++++------ tools/tests/mount_backend_test.c | 20 ++++++++++++++++--- 5 files changed, 39 insertions(+), 15 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 30680b5a..b7575988 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -227,8 +227,8 @@ msgstr "A cgroup directory and each control file keep independent ownership and msgid "权限委派" msgstr "Permission-based delegation" -msgid "管理者可通过目录权限委派子树。对实际父目录有写入和搜索权限的调用者可以 创建子组,或删除没有活任务和子组的非根组;删除还受目录 sticky 位约束。 授予 ``cgroup.subtree_control`` 写权限只允许调整本组向下启用的控制器, 不改变本组由父级管理的配额。``pids.max`` 的写入仍要求 ``CAP_SYS_ADMIN``, 不会因为更改文件所有权或权限而开放给普通用户。" -msgstr "An administrator can delegate a subtree through directory permissions. Callers with write and search permission on the actual parent can create child groups and remove non-root groups with no live tasks or children. Removing a child also honors the parent directory’s sticky bit. Write access to ``cgroup.subtree_control`` only allows adjusting controller availability below that group, not the group’s own parent-imposed limits. Writing ``pids.max`` still requires ``CAP_SYS_ADMIN``, regardless of its owner or mode." +msgid "管理者可通过目录权限委派子树。对实际父目录有写入和搜索权限的调用者可以 创建子组,或删除没有活任务和子组的非根组;删除还受目录 sticky 位约束。 授予 ``cgroup.subtree_control`` 写权限只允许调整本组向下启用的控制器, 不改变本组由父级管理的配额。管理者可另外通过 ``pids.max`` 自身的所有权和 权限位授权普通用户修改该组的配额;创建线程时仍检查本组及所有祖先的上限。" +msgstr "Managers can delegate a subtree through directory permissions. A caller with write and search permission on the actual parent can create child groups or remove non-root groups without live tasks or children; removal also observes the sticky bit. Write access to ``cgroup.subtree_control`` authorizes controller enablement below that group and leaves its parent-managed quota in place. Managers can separately grant ordinary users write access to that group’s ``pids.max`` through its own ownership and mode. Thread creation still checks the limits of the group and every ancestor." msgid "迁移进程需要对目的组的 ``cgroup.procs`` 有写权限,也需要对源组与目的组最近 共同祖先的 ``cgroup.procs`` 有写权限。共同祖先可以是源组或目的组自身。 祖先检查在迁移前执行,使用打开文件时保存的文件系统凭据(包括附加组), 不因复制、传递描述符或写入者的凭据变化而扩大权限。未获授权时返回 ``EACCES``,不修改任何线程的归属。" msgstr "Moving a process requires write access to both the destination group’s ``cgroup.procs`` and the nearest common ancestor’s ``cgroup.procs``. The ancestor can be the source or destination itself. Its permissions are checked using the filesystem credentials saved at open time, including supplementary groups, before moving any thread. Duplicating or passing the descriptor and changing the writer’s credentials do not expand that authority. Denial returns ``EACCES`` without changing membership." @@ -314,3 +314,6 @@ msgstr "" "master hangup. The mount backend suite covers cgroup mounts, delegation boundaries, and inotify. ``tools/test_cgroup_scheduler.py`` exercises quota " "denials, creation rollback, exit and reap through the real scheduler. " "Guest boot, udev and systemd integration require separate validation." + +msgid "可写控制文件在打开时检查其精确 inode 的权限,成功打开的描述符保留写入授权。 随后更改权限或调用者凭据不撤销该描述符的授权;重新打开及直接路径写入检查 当时的权限。非法配额命令返回 ``EINVAL`` 并保留原上限,只读挂载返回 ``EROFS``。" +msgstr "Opening a writable control checks permissions on its exact inode; a successful descriptor retains its write authorization. Later mode or caller credential changes preserve that authorization. New opens and direct path writes check the permissions at the time of the operation. Invalid quota commands return ``EINVAL`` and preserve the existing limit; read-only mounts return ``EROFS``." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index 61825056..8c1980b9 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -202,8 +202,8 @@ msgstr "コントロールグループのディレクトリと各制御ファイ msgid "权限委派" msgstr "権限の委譲" -msgid "管理者可通过目录权限委派子树。对实际父目录有写入和搜索权限的调用者可以 创建子组,或删除没有活任务和子组的非根组;删除还受目录 sticky 位约束。 授予 ``cgroup.subtree_control`` 写权限只允许调整本组向下启用的控制器, 不改变本组由父级管理的配额。``pids.max`` 的写入仍要求 ``CAP_SYS_ADMIN``, 不会因为更改文件所有权或权限而开放给普通用户。" -msgstr "管理者はディレクトリの権限を使ってサブツリーを委譲できます。実際の親ディレクトリに書き込み権限と検索権限があれば、子グループを作成し、稼働中のタスクも子グループもない非ルートグループを削除できます。削除には親ディレクトリの sticky ビットも適用されます。``cgroup.subtree_control`` の書き込み権限で変更できるのは配下のコントローラーの有効化だけで、そのグループ自体に親が設定した上限は変わりません。``pids.max`` の書き込みには、所有者やモードにかかわらず ``CAP_SYS_ADMIN`` が必要です。" +msgid "管理者可通过目录权限委派子树。对实际父目录有写入和搜索权限的调用者可以 创建子组,或删除没有活任务和子组的非根组;删除还受目录 sticky 位约束。 授予 ``cgroup.subtree_control`` 写权限只允许调整本组向下启用的控制器, 不改变本组由父级管理的配额。管理者可另外通过 ``pids.max`` 自身的所有权和 权限位授权普通用户修改该组的配额;创建线程时仍检查本组及所有祖先的上限。" +msgstr "管理者はディレクトリの権限でサブツリーを委譲できます。実際の親に書き込みと検索の権限を持つ呼び出し元は、子グループを作成したり、稼働中のタスクや子がない非ルートグループを削除したりできます。削除には sticky ビットも適用されます。``cgroup.subtree_control`` の書き込み権限は、そのグループより下のコントローラーの有効化を許可し、親が管理する当該グループの上限を維持します。管理者は ``pids.max`` 自体の所有権とモードで一般ユーザーに当該グループの上限変更を許可できます。スレッドの作成時には、当該グループとすべての祖先の上限が確認されます。" msgid "迁移进程需要对目的组的 ``cgroup.procs`` 有写权限,也需要对源组与目的组最近 共同祖先的 ``cgroup.procs`` 有写权限。共同祖先可以是源组或目的组自身。 祖先检查在迁移前执行,使用打开文件时保存的文件系统凭据(包括附加组), 不因复制、传递描述符或写入者的凭据变化而扩大权限。未获授权时返回 ``EACCES``,不修改任何线程的归属。" msgstr "プロセスの移動には、移動先と、移動元・移動先の最も近い共通の祖先の両方で ``cgroup.procs`` への書き込み権限が必要です。移動元または移動先そのものが共通の祖先になる場合もあります。祖先の権限は、追加グループも含めてファイルを開いた時点のファイルシステム資格情報で、スレッドの移動前に確認します。記述子の複製や受け渡し、書き込み時の資格情報の変更によって権限が拡大することはありません。拒否時には所属を変更せず ``EACCES`` を返します。" @@ -280,3 +280,6 @@ msgstr "" "も対象とします。``tools/test_cgroup_scheduler.py`` " "は実際のスケジューラーで上限による拒否、作成失敗時のロールバック、終了と回収を確認します。ゲストの起動、udev、systemd " "の統合は別途検証が必要です。" + +msgid "可写控制文件在打开时检查其精确 inode 的权限,成功打开的描述符保留写入授权。 随后更改权限或调用者凭据不撤销该描述符的授权;重新打开及直接路径写入检查 当时的权限。非法配额命令返回 ``EINVAL`` 并保留原上限,只读挂载返回 ``EROFS``。" +msgstr "書き込み可能な制御ファイルを開くと、対象 inode の権限が確認され、成功した記述子は書き込みの許可を保持します。その後のモードや呼び出し元の資格情報の変更でも、その許可は保持されます。再度開く操作とパスへの直接書き込みでは、その時点の権限を確認します。不正な上限コマンドは既存の上限を保持して ``EINVAL`` を返し、読み取り専用マウントでは ``EROFS`` を返します。" diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 37ff5b9f..128bc7b5 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -132,8 +132,12 @@ cgroup v2 管理者可通过目录权限委派子树。对实际父目录有写入和搜索权限的调用者可以 创建子组,或删除没有活任务和子组的非根组;删除还受目录 sticky 位约束。 授予 ``cgroup.subtree_control`` 写权限只允许调整本组向下启用的控制器, -不改变本组由父级管理的配额。``pids.max`` 的写入仍要求 ``CAP_SYS_ADMIN``, -不会因为更改文件所有权或权限而开放给普通用户。 +不改变本组由父级管理的配额。管理者可另外通过 ``pids.max`` 自身的所有权和 +权限位授权普通用户修改该组的配额;创建线程时仍检查本组及所有祖先的上限。 + +可写控制文件在打开时检查其精确 inode 的权限,成功打开的描述符保留写入授权。 +随后更改权限或调用者凭据不撤销该描述符的授权;重新打开及直接路径写入检查 +当时的权限。非法配额命令返回 ``EINVAL`` 并保留原上限,只读挂载返回 ``EROFS``。 迁移进程需要对目的组的 ``cgroup.procs`` 有写权限,也需要对源组与目的组最近 共同祖先的 ``cgroup.procs`` 有写权限。共同祖先可以是源组或目的组自身。 diff --git a/fs/cgroup/filesystem.c b/fs/cgroup/filesystem.c index ab32421b..be696e18 100644 --- a/fs/cgroup/filesystem.c +++ b/fs/cgroup/filesystem.c @@ -207,7 +207,7 @@ int cgroup_procs_may_write(struct cgroup *group, const struct fs_access_cred *cr return fs_permissions_check_mode(cred, false, &mode, FS_ACCESS_WRITE); } -/** @brief Authorize a control mutation with exact metadata and supported policy. +/** @brief Authorize a supported control mutation using its exact inode DAC. * @param group Live inode owner. @param node Its live inode key. * @param cred Borrowed credentials from the opening or path operation. * @return Zero or negative DAC/unsupported-operation errno. @@ -216,8 +216,7 @@ static int cgroup_control_access(struct cgroup *group, const struct storage_node const struct fs_access_cred *cred) { enum cgroup_file file = node_file(node); - if (!controls[file].writable || (file == CG_PIDS_MAX && !(cred->caps & (1ULL << CAP_SYS_ADMIN)))) - return -EPERM; + if (!controls[file].writable) return -EPERM; struct reliefos_permissions mode = cgroup_mode(group, node); return fs_permissions_check_mode(cred, false, &mode, FS_ACCESS_WRITE); } @@ -602,7 +601,7 @@ static int cgroup_write(void *context, struct storage_node *node, uint64_t offse return rc ? rc : cgroup_write_command(g, node_file(node), &cred, bytes, length, written); } -/** @brief Capture write authority for a delegatable control's canonical OFD. +/** @brief Capture write authority for a writable control's canonical OFD. * @param context Borrowed hierarchy context. @param node Authorized live inode. * @param flags Native open flags. @param state Receives an owned snapshot or NULL. * @return Zero or negative errno; a writable open must not proceed without its snapshot. @@ -613,7 +612,7 @@ static int cgroup_file_open(void *context, const struct storage_node *node, uint *state = NULL; enum cgroup_file file = node_file(node); uint32_t access = flags & LINUX_O_ACCMODE; - if ((file != CG_PROCS && file != CG_SUBTREE) || + if (!controls[file].writable || (access != LINUX_O_WRONLY && access != LINUX_O_RDWR)) return 0; struct cgroup *g = cgroup_find(node->first_cluster); if (!node_live(g, node)) return -ENODEV; @@ -631,6 +630,7 @@ static int cgroup_file_open(void *context, const struct storage_node *node, uint /** @brief Use an opened control's original authority for the live inode. * Destination access was established at open; cgroup.procs rechecks current * ancestor metadata with the captured credentials during the actual move. + * pids.max updates remain constrained by every ancestor's enforced limit. */ static int cgroup_file_write(void *context, struct storage_node *node, void *state, uint64_t offset, const void *bytes, uint32_t length, uint32_t *written) @@ -640,7 +640,7 @@ static int cgroup_file_write(void *context, struct storage_node *node, void *sta struct cgroup *g = cgroup_find(node->first_cluster); if (!node_live(g, node)) return -ENODEV; enum cgroup_file file = node_file(node); - if (file != CG_PROCS && file != CG_SUBTREE) return -EPERM; + if (!controls[file].writable) return -EPERM; return cgroup_write_command(g, file, state, bytes, length, written); } diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index a58e4fa5..63dff33a 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2986,12 +2986,13 @@ static void cgroup_delegation(struct vfs_namespace *ns,struct task *actor, _Alignas(4096) struct { char command[16], child[40], outside[40], on_ro[40]; char child_procs[64], parent_procs[64], peer_procs[64], ro_procs[64]; - char subtree[64], pids_max[64], threads[64]; + char subtree[64], pids_max[64], peer_max[64], ro_max[64], threads[64]; } user={.child="/cgroup/managed/init.scope",.outside="/cgroup/forbidden", .on_ro="/cgroup-ro/managed/forbidden",.child_procs="/cgroup/managed/init.scope/cgroup.procs", .parent_procs="/cgroup/managed/cgroup.procs",.peer_procs="/cgroup/peer/cgroup.procs", .ro_procs="/cgroup-ro/managed/cgroup.procs",.subtree="/cgroup/managed/cgroup.subtree_control", - .pids_max="/cgroup/managed/pids.max",.threads="/cgroup/managed/init.scope/cgroup.threads"}; + .pids_max="/cgroup/managed/pids.max",.peer_max="/cgroup/peer/pids.max", + .ro_max="/cgroup-ro/managed/pids.max",.threads="/cgroup/managed/init.scope/cgroup.threads"}; uintptr_t saved_base=lookup_user_base;size_t saved_bytes=lookup_user_bytes; lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); actor->fsuid=actor->fsgid=1500;actor->cap_effective=0; @@ -3036,9 +3037,22 @@ static void cgroup_delegation(struct vfs_namespace *ns,struct task *actor, fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.subtree,LINUX_O_WRONLY|LINUX_O_TRUNC,0);assert(fd>=0); cgroup_fd_command(actor,fd,user.command,"+pids",0);task_discard_file_fd(actor,fd); cgroup_check_text(&scope,"pids.current","2\n"); + assert(syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.peer_max,LINUX_O_WRONLY,0)==-EACCES); + assert(syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.ro_max,LINUX_O_WRONLY,0)==-EROFS); fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.pids_max,LINUX_O_WRONLY,0);assert(fd>=0); - cgroup_fd_command(actor,fd,user.command,"0",-EPERM);task_discard_file_fd(actor,fd); + cgroup_fd_command(actor,fd,user.command,"0",0); + cgroup_check_text(&owned,"pids.max","0\n"); + cgroup_fd_command(actor,fd,user.command,"invalid",-EINVAL); + cgroup_check_text(&owned,"pids.max","0\n"); + assert(!vfs_path_lookup_child(&owned,"pids.max",&control)); + assert(!fs_permissions_chmod_path(actor,&control,0444)); + actor->fsuid=actor->fsgid=1501; + assert(syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.pids_max,LINUX_O_WRONLY,0)==-EACCES); + cgroup_write_text(&owned,"pids.max","max",-EACCES); + cgroup_fd_command(actor,fd,user.command,"max",0);task_discard_file_fd(actor,fd); cgroup_check_text(&owned,"pids.max","max\n"); + actor->fsuid=actor->fsgid=1500; + assert(!fs_permissions_chmod_path(actor,&control,0644));vfs_path_put(&control); assert(!vfs_path_lookup_child(&scope,"cgroup.threads",&control)); assert(!fs_permissions_chmod_path(actor,&control,0644));vfs_path_put(&control); fd=syscall_open_object(ns,actor,LINUX_AT_FDCWD,(uintptr_t)user.threads,LINUX_O_WRONLY,0);assert(fd>=0); From 04945d2bcfffdc22bafa1a7b0a4afcf618c9b964 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 22:28:34 +0800 Subject: [PATCH 51/97] fix(fd): support inode-owned advisory locks on device nodes --- .../LC_MESSAGES/userspace-api/descriptors.po | 3 + .../LC_MESSAGES/userspace-api/descriptors.po | 3 + Documentation/userspace-api/descriptors.rst | 7 + kernel/syscall/fd/flock.c | 45 +++++- kernel/syscall/internal.h | 10 ++ tools/tests/descriptor_table_test.c | 144 ++++++++++++++++++ 6 files changed, 205 insertions(+), 7 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index ae0d37a8..2cadaf94 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -416,3 +416,6 @@ msgstr "The timestamp precedes ``SCM_CREDENTIALS`` and ``SCM_RIGHTS``. A short c msgid "启动时,探测到的 ISO9660 光盘按 ``/media/cdrom0``、``/media/cdrom1`` 等顺序 尝试挂载。若 ``/media`` 不存在,跳过自动挂载,不创建它;仍可用对应的光盘块设备 显式挂载。若父目录存在,只创建缺少的末级目录,不改变已有目录的元数据。其他 查找、创建或挂载错误不会被忽略。启动挂载图发布前失败时会释放图内挂载点引用并 返回原错误;后端若未能完成回收,将保留到重试。正常卸载的忙检查不变。" msgstr "At startup, detected ISO9660 discs are tried at ``/media/cdrom0``, ``/media/cdrom1`` and so on. If ``/media`` is absent, automount is skipped without creating it; the matching optical block device can still be mounted explicitly. If the parent exists, only missing leaf directories are created, leaving existing directory metadata unchanged. Other lookup, creation or mount failures are not ignored. A failure before the boot mount graph is published drops mountpoint references in that graph and returns the original error. Cleanup that the backend cannot finish is retained for retry. Normal unmount busy checks are unchanged." + +msgid "``flock`` 支持普通文件和实际打开的设备节点,包括 ``/dev/console``。 设备描述符以只读、只写或读写方式打开时,均可取得共享锁或独占锁。锁使用实际 打开的设备 inode 身份,硬链接和 bind 别名共享锁,独立创建的设备节点及独立 文件系统实例各自持锁。``dup`` 共享锁所有权,解锁或最后一个打开文件描述 引用关闭时释放锁。引导期无路径设备保留固有节点身份。``O_PATH`` 和匿名 eventfd 描述符返回 ``EBADF``。" +msgstr "``flock`` supports regular files and opened device nodes, including ``/dev/console``. Read-only, write-only and read/write device descriptors can acquire shared or exclusive locks. Locks use the actual opened device inode identity. Hardlink and bind aliases share locks, while separately created device nodes and independent filesystem instances have independent locks. ``dup`` shares lock ownership. Unlocking or closing the final open-file-description reference releases the lock. Pathless bootstrap devices retain their intrinsic node identity. ``O_PATH`` and anonymous eventfd descriptors return ``EBADF``." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index 2a853642..54758794 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -359,3 +359,6 @@ msgstr "タイムスタンプは ``SCM_CREDENTIALS`` と ``SCM_RIGHTS`` より msgid "启动时,探测到的 ISO9660 光盘按 ``/media/cdrom0``、``/media/cdrom1`` 等顺序 尝试挂载。若 ``/media`` 不存在,跳过自动挂载,不创建它;仍可用对应的光盘块设备 显式挂载。若父目录存在,只创建缺少的末级目录,不改变已有目录的元数据。其他 查找、创建或挂载错误不会被忽略。启动挂载图发布前失败时会释放图内挂载点引用并 返回原错误;后端若未能完成回收,将保留到重试。正常卸载的忙检查不变。" msgstr "起動時、検出された ISO9660 ディスクのマウントを ``/media/cdrom0``、``/media/cdrom1`` などの順に試みる。``/media`` がなければ作成せずに自動マウントを省略するが、対応する光学ブロックデバイスは明示的にマウントできる。親ディレクトリがあれば不足している末端ディレクトリだけを作成し、既存のメタデータは変更しない。他の検索、作成、マウントのエラーは無視しない。起動時のマウントグラフの公開前に失敗すると、そのグラフ内のマウントポイントへの参照を解放して元のエラーを返す。バックエンドが回収を完了できなければ再試行のために保持する。通常のアンマウントでの使用中チェックは変わらない。" + +msgid "``flock`` 支持普通文件和实际打开的设备节点,包括 ``/dev/console``。 设备描述符以只读、只写或读写方式打开时,均可取得共享锁或独占锁。锁使用实际 打开的设备 inode 身份,硬链接和 bind 别名共享锁,独立创建的设备节点及独立 文件系统实例各自持锁。``dup`` 共享锁所有权,解锁或最后一个打开文件描述 引用关闭时释放锁。引导期无路径设备保留固有节点身份。``O_PATH`` 和匿名 eventfd 描述符返回 ``EBADF``。" +msgstr "``flock`` は通常ファイルと、``/dev/console`` を含む開かれたデバイスノードに対応します。読み取り専用、書き込み専用、読み書きのデバイス記述子はいずれも共有ロックと排他ロックを取得できます。ロックは実際に開いたデバイス inode の識別情報を使用します。ハードリンクと bind の別名はロックを共有し、個別に作成したデバイスノードと独立したファイルシステムのインスタンスは独立したロックを持ちます。``dup`` はロックの所有権を共有します。明示的な解除または開いたファイル記述への最後の参照を閉じるとロックを解放します。起動時のパスを持たないデバイスは固有のノード識別情報を保持します。``O_PATH`` と匿名 eventfd 記述子は ``EBADF`` を返します。" diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index ee6269e7..fffd3054 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -37,6 +37,13 @@ utimensat(fd, NULL, times, 0) 更新该 fd 持有的 inode,改名或 unlink ``O_NOFOLLOW``,不包含由 ``F_GETFD`` 查询的 close-on-exec 标志。复制描述符 保留同一打开状态;``F_SETFL`` 和 ``ioctl`` 对 ``O_PATH`` 描述符返回 ``EBADF``。 +``flock`` 支持普通文件和实际打开的设备节点,包括 ``/dev/console``。 +设备描述符以只读、只写或读写方式打开时,均可取得共享锁或独占锁。锁使用实际 +打开的设备 inode 身份,硬链接和 bind 别名共享锁,独立创建的设备节点及独立 +文件系统实例各自持锁。``dup`` 共享锁所有权,解锁或最后一个打开文件描述 +引用关闭时释放锁。引导期无路径设备保留固有节点身份。``O_PATH`` 和匿名 +eventfd 描述符返回 ``EBADF``。 + Linux 请求值 ============ diff --git a/kernel/syscall/fd/flock.c b/kernel/syscall/fd/flock.c index c3de0540..ed58a317 100644 --- a/kernel/syscall/fd/flock.c +++ b/kernel/syscall/fd/flock.c @@ -3,7 +3,7 @@ static bool syscall_flock_node_equal(const struct storage_node *a, const struct storage_node *b); -static struct reliefos_flock_entry *syscall_flock_find(const struct storage_node *node); +static struct reliefos_flock_entry *syscall_flock_find(const struct task_file *file); static struct reliefos_flock_entry *syscall_flock_alloc(const struct storage_node *node); @@ -18,11 +18,28 @@ static bool syscall_flock_node_equal(const struct storage_node *a, a->volume_id == b->volume_id; } -static struct reliefos_flock_entry *syscall_flock_find(const struct storage_node *node) +/** + * @brief Find an advisory lock using the opened device inode when available. + * @param file Borrowed live OFD under caller-held execution ownership. + * @return Matching lock entry or NULL. A live lock owner supplies the retained + * path without an extra reference. Bind and hardlink aliases share identity, + * while separate device inodes and filesystem instances remain independent. + * Pathless bootstrap devices retain their existing intrinsic-node identity. + */ +static struct reliefos_flock_entry *syscall_flock_find(const struct task_file *file) { - for (uint32_t i = 0; i < RELIEFOS_FLOCK_MAX; ++i) - if (reliefos_flocks[i].used && syscall_flock_node_equal(&reliefos_flocks[i].node, node)) - return &reliefos_flocks[i]; + for (uint32_t i = 0; i < RELIEFOS_FLOCK_MAX; ++i) { + struct reliefos_flock_entry *entry = &reliefos_flocks[i]; + if (!entry->used || !syscall_flock_node_equal(&entry->node, &file->node)) + continue; + const struct task_file *owner = entry->owner; + if (!owner && entry->shared_count) owner = entry->shared_owners[0]; + if (file->node.type == RELIEFOS_FS_TYPE_DEVICE && owner && + (vfs_path_node(&file->path_ref) || vfs_path_node(&owner->path_ref)) && + !vfs_path_same_inode(&file->path_ref, &owner->path_ref)) + continue; + return entry; + } return NULL; } @@ -81,6 +98,17 @@ static bool syscall_flock_conflicts(const struct reliefos_flock_entry *entry, return requested == RELIEFOS_FLOCK_EX || entry->type == RELIEFOS_FLOCK_EX; } +/** + * @brief Apply an OFD-owned advisory lock to a regular file or opened device node. + * @param fd_arg Linux descriptor number, interpreted as an unsigned 32-bit value. + * @param operation Shared, exclusive or unlock operation with optional nonblocking mode. + * @return Zero on success, negative errno on failure, or KERNEL_SYSCALL_BLOCKED + * while waiting for a conflicting lock. + * @note Read-only and write-only device descriptions may acquire either lock + * type. Device nodes require TASK_FILE_FLAG_DEV_NODE. O_PATH descriptors return + * EBADF. Retained device inode identity, dup/fork owner sharing and final-close + * release apply under caller-held execution ownership. + */ int64_t syscall_flock(uint64_t fd_arg, uint32_t operation) { struct task *task = sched_current_task(); @@ -94,8 +122,11 @@ int64_t syscall_flock(uint64_t fd_arg, uint32_t operation) (RELIEFOS_FLOCK_SH | RELIEFOS_FLOCK_EX)) return -RELIEFOS_EINVAL; file = task_file_for_fd(task, (int)(uint32_t)fd_arg); if (!file) return -RELIEFOS_EBADF; - if (file->node.type != RELIEFOS_FS_TYPE_FILE) return -RELIEFOS_EBADF; - entry = syscall_flock_find(&file->node); + if ((file->flags & TASK_FILE_FLAG_PATH) || + (file->node.type != RELIEFOS_FS_TYPE_FILE && + (file->node.type != RELIEFOS_FS_TYPE_DEVICE || + !(file->flags & TASK_FILE_FLAG_DEV_NODE)))) return -RELIEFOS_EBADF; + entry = syscall_flock_find(file); if (operation & RELIEFOS_FLOCK_UN) { if (!entry || !file->flock_type) return 0; if (file->flock_type == RELIEFOS_FLOCK_EX && entry->owner == file) { diff --git a/kernel/syscall/internal.h b/kernel/syscall/internal.h index 299bc0f9..d6780f5f 100644 --- a/kernel/syscall/internal.h +++ b/kernel/syscall/internal.h @@ -674,6 +674,16 @@ void copy_text(char *dst, uint32_t cap, const char *src); void syscall_flock_release_owner(struct task_file *owner); +/** + * @brief Apply an OFD-owned advisory lock to a regular file or opened device node. + * @param fd_arg Linux descriptor number, interpreted as an unsigned 32-bit value. + * @param operation Shared, exclusive or unlock operation with optional nonblocking mode. + * @return Zero, negative errno, or KERNEL_SYSCALL_BLOCKED on a lock conflict. + * @note Either device access mode permits either lock type. Device nodes require + * TASK_FILE_FLAG_DEV_NODE. O_PATH returns EBADF. Dup/fork share ownership until + * unlock or final description release. Caller holds execution ownership while + * using the existing lock table and retained device inode identity. + */ int64_t syscall_flock(uint64_t fd_arg, uint32_t operation); /** diff --git a/tools/tests/descriptor_table_test.c b/tools/tests/descriptor_table_test.c index 914a16bf..746c4564 100644 --- a/tools/tests/descriptor_table_test.c +++ b/tools/tests/descriptor_table_test.c @@ -1638,6 +1638,148 @@ static void test_flock_promotion(void) puts("PASS flock owner promotion: exclusive/shared, ENOMEM rollback and final close"); } +/** @brief Exercise device-node flock admission and console OFD lifetime through real descriptors. */ +static void test_console_flock(void) +{ + const uint32_t access_modes[] = {RELIEFOS_O_RDONLY, RELIEFOS_O_WRONLY, RELIEFOS_O_RDWR}; + const struct storage_node console = { + .type = RELIEFOS_FS_TYPE_DEVICE, + .flags = STORAGE_NODE_FLAG_DEV_NODE, + .first_cluster = STORAGE_DEV_KIND_CONSOLE, + .volume_id = STORAGE_VOLUME_ROOT, + }; + struct storage_node null_device = console; + null_device.first_cluster = STORAGE_DEV_KIND_NULL; + + for (unsigned i = 0; i < sizeof(access_modes) / sizeof(access_modes[0]); ++i) { + struct task *task = calloc(1, sizeof(*task)); + assert(task); + task->limits.nofile.rlim_cur = 64; + descriptor_dispatch_task = task; + int owner = alloc_task_fd(task, &console, + TASK_FILE_FLAG_DEV_NODE | access_modes[i] | LINUX_O_NOCTTY, "/dev/console"); + int contender = alloc_task_fd(task, &console, + TASK_FILE_FLAG_DEV_NODE | RELIEFOS_O_RDONLY, "/dev/console"); + int independent = alloc_task_fd(task, &null_device, + TASK_FILE_FLAG_DEV_NODE | TASK_FILE_FLAG_DEV_NULL | RELIEFOS_O_RDONLY, "/dev/null"); + int path_only = alloc_task_fd(task, &console, + TASK_FILE_FLAG_DEV_NODE | TASK_FILE_FLAG_PATH, "/dev/console"); + int anonymous = syscall_eventfd_create(0, 0); + assert(owner >= 0 && contender >= 0 && independent >= 0 && path_only >= 0 && + anonymous >= 0); + assert(syscall_flock(anonymous, RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == -RELIEFOS_EBADF); + + int64_t result = syscall_legacy_descriptors(LINUX_SYS_FLOCK, owner, + RELIEFOS_FLOCK_EX, 0, 0, 0, 0); + if (result != 0) + fprintf(stderr, "FAIL console flock access=%u returned %lld, expected 0\n", + access_modes[i], (long long)result); + assert(result == 0); + assert(syscall_flock(contender, RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == -RELIEFOS_EWOULDBLOCK); + assert(syscall_flock(contender, RELIEFOS_FLOCK_SH | RELIEFOS_FLOCK_NB) == -RELIEFOS_EWOULDBLOCK); + assert(syscall_flock(independent, RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == 0); + assert(syscall_flock(path_only, RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == -RELIEFOS_EBADF); + assert(syscall_flock(path_only, RELIEFOS_FLOCK_SH | RELIEFOS_FLOCK_NB) == -RELIEFOS_EBADF); + assert(syscall_flock(path_only, RELIEFOS_FLOCK_UN) == -RELIEFOS_EBADF); + assert(syscall_flock(UINT32_MAX, RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == -RELIEFOS_EBADF); + + int duplicate = task_duplicate_file_fd(task, owner, 0, 0); + assert(duplicate >= 0); + task_discard_file_fd(task, owner); + assert(syscall_flock(contender, RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == -RELIEFOS_EWOULDBLOCK); + assert(syscall_flock(duplicate, RELIEFOS_FLOCK_UN) == 0); + assert(syscall_flock(contender, RELIEFOS_FLOCK_SH | RELIEFOS_FLOCK_NB) == 0); + assert(syscall_flock(duplicate, RELIEFOS_FLOCK_SH | RELIEFOS_FLOCK_NB) == 0); + task_discard_file_fd(task, duplicate); + assert(syscall_flock(contender, RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == 0); + task_discard_file_fd(task, contender); + int reopened = alloc_task_fd(task, &console, + TASK_FILE_FLAG_DEV_NODE | RELIEFOS_O_RDONLY, "/dev/console"); + assert(reopened >= 0); + assert(syscall_flock(reopened, RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == 0); + + descriptor_dispatch_task = NULL; + syscall_release_task_files(task); + free(task); + assert(console_references == 0); + } + puts("PASS console flock: read/write access, independent opens/devices, shared locks, dup/final close and O_PATH/anonymous EBADF"); +} + +/** @brief Expose two console-device inodes and one alias in a fixture filesystem. */ +static int flock_device_lookup(void *context, const struct storage_node *parent, + const char *name, struct storage_node *out) +{ + (void)context; + assert(parent->type == RELIEFOS_FS_TYPE_DIR); + if (strcmp(name, "console") && strcmp(name, "alias") && strcmp(name, "other")) + return -ENOENT; + *out = (struct storage_node){ + .type = RELIEFOS_FS_TYPE_DEVICE, + .flags = STORAGE_NODE_FLAG_DEV_NODE | STORAGE_NODE_FLAG_RDEV, + .first_cluster = strcmp(name, "other") ? 71 : 72, + }; + return 0; +} + +/** @brief Keep device locks on actual inodes across aliases and distinct mounts. */ +static void test_device_flock_identity(void) +{ + static const struct vfs_backend_ops ops = { + .lookup = flock_device_lookup, .retain = writer_path_retain, + .release = writer_path_release, .same_node = writer_path_same, + }; + struct storage_node root_node = {.type = RELIEFOS_FS_TYPE_DIR, .first_cluster = 1}; + struct storage_node console = { + .type = RELIEFOS_FS_TYPE_DEVICE, .flags = STORAGE_NODE_FLAG_DEV_NODE, + .first_cluster = STORAGE_DEV_KIND_CONSOLE, .volume_id = STORAGE_VOLUME_ROOT, + }; + int contexts[2] = {0}; + struct vfs_mount *mounts[3] = {0}; + struct vfs_path roots[3] = {0}; + assert(!vfs_mount_new(&ops, &contexts[0], NULL, &root_node, &mounts[0])); + assert(!vfs_mount_detached_root(mounts[0], &roots[0])); + assert(!vfs_mount_clone_root(&roots[0], &mounts[1])); + assert(!vfs_mount_detached_root(mounts[1], &roots[1])); + assert(!vfs_mount_new(&ops, &contexts[1], NULL, &root_node, &mounts[2])); + assert(!vfs_mount_detached_root(mounts[2], &roots[2])); + struct task *task = calloc(1, sizeof(*task)); + assert(task); + task->limits.nofile.rlim_cur = 64; + descriptor_dispatch_task = task; + const char *names[] = {"console", "alias", "other", "console", "console"}; + const unsigned mount_indices[] = {0, 0, 0, 1, 2}; + int fds[5]; + for (unsigned i = 0; i < 5; ++i) { + struct vfs_path path = {0}; + assert(!vfs_path_lookup_child(&roots[mount_indices[i]], names[i], &path)); + fds[i] = alloc_task_fd(task, &console, TASK_FILE_FLAG_DEV_NODE | RELIEFOS_O_RDWR, + "/diagnostic-console"); + assert(fds[i] >= 0); + task_file_bind_path(task_file_for_fd(task, fds[i]), &path); + vfs_path_put(&path); + } + assert(!syscall_flock(fds[0], RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB)); + assert(syscall_flock(fds[1], RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == -EWOULDBLOCK); + assert(syscall_flock(fds[3], RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == -EWOULDBLOCK); + assert(!syscall_flock(fds[2], RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB)); + assert(!syscall_flock(fds[4], RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB)); + task_discard_file_fd(task, fds[0]); + assert(!syscall_flock(fds[1], RELIEFOS_FLOCK_SH | RELIEFOS_FLOCK_NB)); + assert(syscall_flock(fds[3], RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB) == -EWOULDBLOCK); + task_discard_file_fd(task, fds[1]); + assert(!syscall_flock(fds[3], RELIEFOS_FLOCK_EX | RELIEFOS_FLOCK_NB)); + syscall_release_task_files(task); + descriptor_dispatch_task = NULL; + free(task); + for (unsigned i = 3; i > 0; --i) { + vfs_path_put(&roots[i - 1]); + vfs_mount_put(mounts[i - 1]); + } + assert(!console_references && !writer_path_pins); + puts("PASS device flock identity: inode aliases, bind identity, separate mknod and filesystem instances"); +} + struct descriptor_record_lock { int16_t type, whence; int32_t padding; @@ -3228,6 +3370,8 @@ int main(void) assert(device_stat.st_mode == 0020660 && device_stat.st_rdev == 1); puts("PASS stat pipe endpoints report FIFO; character devices remain unchanged"); test_flock_promotion(); + test_console_flock(); + test_device_flock_identity(); test_epoll_open_file_description_lifetime(); test_epoll_eventfd_dup_readiness(); test_epoll_clone_description_lifetime(); From 13f97023f12f9f224020bd780685b3b596052e89 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 22:42:58 +0800 Subject: [PATCH 52/97] feat(cgroup): account hierarchical CPU usage from scheduler --- .../userspace-api/device-filesystems.po | 80 +++++++++---- .../userspace-api/device-filesystems.po | 62 +++++++--- .../userspace-api/device-filesystems.rst | 27 ++++- fs/cgroup/filesystem.c | 15 ++- fs/cgroup/hierarchy.c | 21 +++- fs/cgroup/internal.h | 3 +- include/reliefnt/cgroup.h | 14 ++- include/reliefnt/proc_stats.h | 4 + include/reliefnt/sched.h | 1 + kernel/sched/accounting.c | 24 ++-- kernel/sched/core.c | 2 +- kernel/sched/internal.h | 3 +- kernel/sched/task.c | 9 ++ tools/tests/cgroup_scheduler_test.c | 106 +++++++++++++++++- tools/tests/mount_backend_test.c | 2 + tools/tests/task_exit_logging_test.c | 8 +- 16 files changed, 321 insertions(+), 60 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index b7575988..1c32d176 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -254,6 +254,44 @@ msgstr "" "Zombies retaining membership in a removed group show a `` (deleted)`` " "suffix." +msgid "CPU 使用统计" +msgstr "CPU usage accounting" + +msgid "" +"每个组始终提供只读的 ``cpu.stat``,依次输出 ``usage_usec``、``user_usec`` 和 " +"``system_usec`` 三行。总量为用户态与内核态时间之和,每项均以微秒表示, 达到 64 位无符号上限时饱和。当前时钟为 100 " +"Hz,统计分辨率为 10,000 微秒; 多个 CPU 的实际运行时间累加。" +msgstr "" +"Every group always exposes a read-only ``cpu.stat`` with three lines in " +"order, ``usage_usec``, ``user_usec`` and ``system_usec``. Total usage is " +"the sum of user and system time. Values are microseconds and saturate at " +"the unsigned 64-bit maximum. The current clock runs at 100 Hz with a " +"resolution of 10,000 microseconds. Actual runtime on multiple CPUs is " +"added together." + +msgid "" +"每段 CPU 时间计入当时所属的组及其所有祖先;根组同时统计直接归属根组的任务。 读取先在调度器锁下结算所有在线 " +"CPU,重复读取仅累计新增的时间。进程迁移先 结算原组的运行时间,再切换所有活线程的归属,已累计的历史保留在原组和祖先。" +msgstr "" +"Each CPU interval is charged to the group owning the task at that time " +"and every ancestor. The root also accounts for tasks assigned directly to" +" it. Reads settle all online CPUs under the scheduler lock and repeated " +"reads add only newly elapsed time. Process migration settles the old " +"groups before changing all live threads, retaining accumulated history in" +" the old groups and their ancestors." + +msgid "" +"任务进入就绪、阻塞或退出状态后,仍持有 CPU 归属的最后一段执行继续计入原组, 直至 CPU " +"归属退休。删除子组后,祖先保留已累计的历史;同名新组从零开始。 CPU 使用统计作为基础控制文件提供,``cgroup.controllers``" +" 反映实际可用的 调度控制器。" +msgstr "" +"A task that becomes ready, blocked or exited continues to charge its " +"final execution interval to the old group while retaining CPU ownership, " +"until that ownership retires. Ancestors retain accumulated history after " +"a subgroup is deleted. A new group with the same name starts at zero. CPU" +" accounting is provided by a base control file, while " +"``cgroup.controllers`` lists the available scheduling controllers." + msgid "PID 配额" msgstr "PID limits" @@ -273,16 +311,16 @@ msgstr "" "group’s limit or an ancestor’s limit." msgid "" -"配额按照线程计数,且只在创建成功时计入。普通线程退出后释放其配额;可等待的 僵尸仍计入 ``pids.current``,直至实际回收。带 " -"``WNOWAIT`` 的等待不回收配额。 ``pids.events.local`` 记录本组触发的拒绝,``pids.events`` " -"还累计后代的拒绝。" +"配额按照线程计数,且只在创建成功时计入。普通线程退出后,在最后的 CPU 归属 退休时释放其配额;可等待的僵尸仍计入 " +"``pids.current``,直至实际回收且 CPU 归属已退休。带 ``WNOWAIT`` 的等待不回收配额。 " +"``pids.events.local`` 记录本组触发的拒绝,``pids.events`` 还累计后代的拒绝。" msgstr "" -"Each thread is charged only after successful creation. Non-waitable " -"threads release the charge on exit; waitable zombies remain in " -"``pids.current`` until reaped. A wait with ``WNOWAIT`` does not release " -"the charge. ``pids.events.local`` records denials triggered by the " -"group’s own limit, and ``pids.events`` also includes denials triggered in" -" descendants." +"Quotas count threads and are charged only after successful creation. " +"Exited ordinary threads release their charge when final CPU ownership " +"retires. Waitable zombies remain in ``pids.current`` until they are " +"reaped and CPU ownership has retired. Waiting with ``WNOWAIT`` retains " +"the charge. ``pids.events.local`` counts rejections triggered by this " +"group, and ``pids.events`` also accumulates descendant rejections." msgid "" "不支持 cgroup v1、threaded 模式、cgroup namespace 或其他控制器。 " @@ -303,17 +341,21 @@ msgid "" "链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 " "选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` 覆盖 PTY " "ABI、会话与主端挂断行为。控制组挂载、委派边界及 inotify 也由 ``tools/test_mount_backend.py`` " -"覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 调度器的配额拒绝、创建回滚、退出及回收。来宾启动、udev " -"和 systemd 集成需要 另行验证。" +"覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 调度器的配额拒绝、创建回滚、退出及回收,以及双 CPU " +"用户态与内核态统计、 迁移结算、退出尾段、空闲 CPU 和已删除子组的历史。来宾启动、udev 和 systemd 集成需要另行验证。" msgstr "" -"``tools/test_mount_backend.py`` checks shared devtmpfs mounts, metadata, " -"device numbers, symlinks, device lifecycle, user replacements, mount " -"policy and retry after allocation failure. It also checks devpts " -"isolation, options, bind mounts, endpoint lifetime, number reuse and " -"rollback. ``tools/test_linux_pty.py`` checks the PTY ABI, sessions and " -"master hangup. The mount backend suite covers cgroup mounts, delegation boundaries, and inotify. ``tools/test_cgroup_scheduler.py`` exercises quota " -"denials, creation rollback, exit and reap through the real scheduler. " -"Guest boot, udev and systemd integration require separate validation." +"``tools/test_mount_backend.py`` covers devtmpfs shared mounts, metadata, " +"device numbers, symlinks, device addition and removal, user replacements," +" mount policies and allocation retry. It also checks devpts instance " +"isolation, options, binding, endpoint lifetime, number reuse and " +"rollback. ``tools/test_linux_pty.py`` covers PTY ABI, sessions and master" +" hangup. Control-group mounts, delegation boundaries and inotify are also" +" covered by ``tools/test_mount_backend.py``. " +"``tools/test_cgroup_scheduler.py`` checks quota rejection, creation " +"rollback, exit and reap in the real scheduler, as well as dual-CPU user " +"and system accounting, migration settlement, exit tails, idle CPUs and " +"deleted-subgroup history. Guest boot, udev and systemd integration " +"require separate verification." msgid "可写控制文件在打开时检查其精确 inode 的权限,成功打开的描述符保留写入授权。 随后更改权限或调用者凭据不撤销该描述符的授权;重新打开及直接路径写入检查 当时的权限。非法配额命令返回 ``EINVAL`` 并保留原上限,只读挂载返回 ``EROFS``。" msgstr "Opening a writable control checks permissions on its exact inode; a successful descriptor retains its write authorization. Later mode or caller credential changes preserve that authorization. New opens and direct path writes check the permissions at the time of the operation. Invalid quota commands return ``EINVAL`` and preserve the existing limit; read-only mounts return ``EROFS``." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index 8c1980b9..a795006a 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -227,6 +227,37 @@ msgstr "" "inode が同名のグループやファイルを参照することはありません。削除済みのグループへの参照を保持するゾンビには `` (deleted)`` " "が付きます。" +msgid "CPU 使用统计" +msgstr "CPU 使用量の集計" + +msgid "" +"每个组始终提供只读的 ``cpu.stat``,依次输出 ``usage_usec``、``user_usec`` 和 " +"``system_usec`` 三行。总量为用户态与内核态时间之和,每项均以微秒表示, 达到 64 位无符号上限时饱和。当前时钟为 100 " +"Hz,统计分辨率为 10,000 微秒; 多个 CPU 的实际运行时间累加。" +msgstr "" +"各グループは常に読み取り専用の ``cpu.stat`` " +"を公開し、``usage_usec``、``user_usec``、``system_usec`` の順に 3 " +"行を出力します。合計はユーザー時間とシステム時間の和です。値はマイクロ秒単位で、符号なし 64 ビットの最大値で飽和します。現在のクロックは " +"100 Hz で、集計の分解能は 10,000 マイクロ秒です。複数 CPU の実行時間を合算します。" + +msgid "" +"每段 CPU 时间计入当时所属的组及其所有祖先;根组同时统计直接归属根组的任务。 读取先在调度器锁下结算所有在线 " +"CPU,重复读取仅累计新增的时间。进程迁移先 结算原组的运行时间,再切换所有活线程的归属,已累计的历史保留在原组和祖先。" +msgstr "" +"各 CPU " +"区間は、その時点でタスクが所属するグループとすべての祖先に計上します。ルートは直接所属するタスクも集計します。読み取り時にスケジューラーロック下で全オンライン" +" CPU " +"を精算し、繰り返しの読み取りでは新たに経過した時間だけを加算します。プロセスの移動では全生存スレッドの所属を変更する前に旧グループを精算し、累積履歴を旧グループと祖先に保持します。" + +msgid "" +"任务进入就绪、阻塞或退出状态后,仍持有 CPU 归属的最后一段执行继续计入原组, 直至 CPU " +"归属退休。删除子组后,祖先保留已累计的历史;同名新组从零开始。 CPU 使用统计作为基础控制文件提供,``cgroup.controllers``" +" 反映实际可用的 调度控制器。" +msgstr "" +"タスクが実行可能、待機または終了状態になっても、CPU " +"所有権を保持する最後の実行区間は、その所有権の解放まで旧グループに計上します。子グループの削除後も祖先に累積履歴を保持します。同名の新規グループはゼロから開始します。CPU" +" 集計は基本制御ファイルとして提供し、``cgroup.controllers`` には利用可能なスケジューリングコントローラーを表示します。" + msgid "PID 配额" msgstr "PID の上限" @@ -244,13 +275,14 @@ msgstr "" "``EAGAIN`` を返します。" msgid "" -"配额按照线程计数,且只在创建成功时计入。普通线程退出后释放其配额;可等待的 僵尸仍计入 ``pids.current``,直至实际回收。带 " -"``WNOWAIT`` 的等待不回收配额。 ``pids.events.local`` 记录本组触发的拒绝,``pids.events`` " -"还累计后代的拒绝。" +"配额按照线程计数,且只在创建成功时计入。普通线程退出后,在最后的 CPU 归属 退休时释放其配额;可等待的僵尸仍计入 " +"``pids.current``,直至实际回收且 CPU 归属已退休。带 ``WNOWAIT`` 的等待不回收配额。 " +"``pids.events.local`` 记录本组触发的拒绝,``pids.events`` 还累计后代的拒绝。" msgstr "" -"スレッドの作成に成功したときだけ使用数に加算されます。待機対象でないスレッドは終了時に使用数から除かれます。待機対象のゾンビは回収されるまで " -"``pids.current`` に含まれ、``WNOWAIT`` では使用数が減りません。``pids.events.local`` " -"はそのグループの上限による拒否を記録し、``pids.events`` は子孫の上限による拒否も集計します。" +"上限はスレッド単位で数え、作成の成功時に計上します。通常のスレッドは終了後、最後の CPU " +"所有権の解放時に計上を解除します。待機可能なゾンビは実際に回収され、CPU 所有権が解放されるまで ``pids.current`` " +"に含めます。``WNOWAIT`` による待機は計上を保持します。``pids.events.local`` " +"はこのグループで発生した拒否を数え、``pids.events`` は子孫の拒否も累積します。" msgid "" "不支持 cgroup v1、threaded 模式、cgroup namespace 或其他控制器。 " @@ -270,16 +302,18 @@ msgid "" "链接、设备增删、用户替换、挂载策略和内存不足重试,也验证 devpts 实例隔离、 " "选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` 覆盖 PTY " "ABI、会话与主端挂断行为。控制组挂载、委派边界及 inotify 也由 ``tools/test_mount_backend.py`` " -"覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 调度器的配额拒绝、创建回滚、退出及回收。来宾启动、udev " -"和 systemd 集成需要 另行验证。" +"覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 调度器的配额拒绝、创建回滚、退出及回收,以及双 CPU " +"用户态与内核态统计、 迁移结算、退出尾段、空闲 CPU 和已删除子组的历史。来宾启动、udev 和 systemd 集成需要另行验证。" msgstr "" "``tools/test_mount_backend.py`` は devtmpfs " -"の共有マウント、メタデータ、デバイス番号、シンボリックリンク、デバイスの追加と削除、ユーザーによる置き換え、マウントポリシー、割り当て失敗後の再試行を確認します。また、devpts" -" の分離、オプション、バインド、端点の寿命、番号の再利用とロールバックも確認します。``tools/test_linux_pty.py`` は " -"PTY ABI、セッションとマスターの切断を確認します。マウントのテストは cgroup の委譲範囲と inotify " -"も対象とします。``tools/test_cgroup_scheduler.py`` " -"は実際のスケジューラーで上限による拒否、作成失敗時のロールバック、終了と回収を確認します。ゲストの起動、udev、systemd " -"の統合は別途検証が必要です。" +"の共有マウント、メタデータ、デバイス番号、シンボリックリンク、デバイスの追加と削除、ユーザーによる置換、マウント方針、メモリ割り当ての再試行を検証します。devpts" +" " +"のインスタンス分離、オプション、バインド、端点の寿命、番号の再利用、ロールバックも検証します。``tools/test_linux_pty.py``" +" は PTY ABI、セッション、マスターの切断を検証します。制御グループのマウント、委譲境界、inotify も " +"``tools/test_mount_backend.py`` で検証します。``tools/test_cgroup_scheduler.py``" +" は実スケジューラーでの上限超過の拒否、作成のロールバック、終了と回収、および 2 CPU " +"のユーザー時間とシステム時間、移動時の精算、終了時の最後の実行区間、アイドル " +"CPU、削除した子グループの履歴を検証します。ゲスト起動、udev、systemd 統合は別途検証します。" msgid "可写控制文件在打开时检查其精确 inode 的权限,成功打开的描述符保留写入授权。 随后更改权限或调用者凭据不撤销该描述符的授权;重新打开及直接路径写入检查 当时的权限。非法配额命令返回 ``EINVAL`` 并保留原上限,只读挂载返回 ``EROFS``。" msgstr "書き込み可能な制御ファイルを開くと、対象 inode の権限が確認され、成功した記述子は書き込みの許可を保持します。その後のモードや呼び出し元の資格情報の変更でも、その許可は保持されます。再度開く操作とパスへの直接書き込みでは、その時点の権限を確認します。不正な上限コマンドは既存の上限を保持して ``EINVAL`` を返し、読み取り専用マウントでは ``EROFS`` を返します。" diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 128bc7b5..684a0c8c 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -159,6 +159,23 @@ cgroup v2 保留的 inode 不会指向后来创建的同名组或文件。仍保留成员引用的僵尸显示 `` (deleted)`` 后缀。 +CPU 使用统计 +------------ + +每个组始终提供只读的 ``cpu.stat``,依次输出 ``usage_usec``、``user_usec`` +和 ``system_usec`` 三行。总量为用户态与内核态时间之和,每项均以微秒表示, +达到 64 位无符号上限时饱和。当前时钟为 100 Hz,统计分辨率为 10,000 微秒; +多个 CPU 的实际运行时间累加。 + +每段 CPU 时间计入当时所属的组及其所有祖先;根组同时统计直接归属根组的任务。 +读取先在调度器锁下结算所有在线 CPU,重复读取仅累计新增的时间。进程迁移先 +结算原组的运行时间,再切换所有活线程的归属,已累计的历史保留在原组和祖先。 + +任务进入就绪、阻塞或退出状态后,仍持有 CPU 归属的最后一段执行继续计入原组, +直至 CPU 归属退休。删除子组后,祖先保留已累计的历史;同名新组从零开始。 +CPU 使用统计作为基础控制文件提供,``cgroup.controllers`` 反映实际可用的 +调度控制器。 + PID 配额 -------- @@ -168,8 +185,9 @@ PID 配额 ``pids.max`` 默认为 ``max``。降低上限或迁移线程可以使计数超过上限;以后创建的 线程若超过本组或祖先的上限,则返回 ``EAGAIN``。 -配额按照线程计数,且只在创建成功时计入。普通线程退出后释放其配额;可等待的 -僵尸仍计入 ``pids.current``,直至实际回收。带 ``WNOWAIT`` 的等待不回收配额。 +配额按照线程计数,且只在创建成功时计入。普通线程退出后,在最后的 CPU 归属 +退休时释放其配额;可等待的僵尸仍计入 ``pids.current``,直至实际回收且 CPU +归属已退休。带 ``WNOWAIT`` 的等待不回收配额。 ``pids.events.local`` 记录本组触发的拒绝,``pids.events`` 还累计后代的拒绝。 不支持 cgroup v1、threaded 模式、cgroup namespace 或其他控制器。 @@ -184,5 +202,6 @@ PID 配额 选项、绑定、端点生命周期、编号回收及失败回滚。``tools/test_linux_pty.py`` 覆盖 PTY ABI、会话与主端挂断行为。控制组挂载、委派边界及 inotify 也由 ``tools/test_mount_backend.py`` 覆盖;``tools/test_cgroup_scheduler.py`` 检查真实 -调度器的配额拒绝、创建回滚、退出及回收。来宾启动、udev 和 systemd 集成需要 -另行验证。 +调度器的配额拒绝、创建回滚、退出及回收,以及双 CPU 用户态与内核态统计、 +迁移结算、退出尾段、空闲 CPU 和已删除子组的历史。来宾启动、udev 和 systemd +集成需要另行验证。 diff --git a/fs/cgroup/filesystem.c b/fs/cgroup/filesystem.c index be696e18..944283f5 100644 --- a/fs/cgroup/filesystem.c +++ b/fs/cgroup/filesystem.c @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -33,7 +34,8 @@ static const struct cgroup_control { [CG_PROCS] = {"cgroup.procs", true}, [CG_THREADS] = {"cgroup.threads", false}, [CG_CONTROLLERS] = {"cgroup.controllers", false}, [CG_SUBTREE] = {"cgroup.subtree_control", true}, [CG_TYPE] = {"cgroup.type", false}, [CG_EVENTS] = {"cgroup.events", false}, - [CG_STAT] = {"cgroup.stat", false}, [CG_PIDS_MAX] = {"pids.max", true}, + [CG_STAT] = {"cgroup.stat", false}, [CG_CPU_STAT] = {"cpu.stat", false}, + [CG_PIDS_MAX] = {"pids.max", true}, [CG_PIDS_CURRENT] = {"pids.current", false}, [CG_PIDS_PEAK] = {"pids.peak", false}, [CG_PIDS_EVENTS] = {"pids.events", false}, [CG_PIDS_LOCAL] = {"pids.events.local", false}, }; @@ -453,7 +455,8 @@ static int cgroup_read_members(const struct cgroup *g, bool threads, struct text return 0; } -/** @brief Render the stable Linux control names and a locked counter snapshot. */ +/** @brief Render controls under scheduler_lock, settling all CPUs for cpu.stat. + * Supports positional text slices without allocation or counter resets. */ static int cgroup_read(void *context, const struct storage_node *node, uint64_t offset, void *buffer, uint32_t capacity, uint32_t *read, uint64_t mount_flags) { @@ -483,6 +486,14 @@ static int cgroup_read(void *context, const struct storage_node *node, uint64_t text_string(&text, "nr_descendants "); text_unsigned(&text, g->descendants); text_string(&text, "\nnr_dying_descendants "); text_unsigned(&text, g->dying); text_string(&text, "\n"); break; + case CG_CPU_STAT: + sched_cpu_accounting_sync_locked(); + text_string(&text, "usage_usec "); + text_unsigned(&text, g->cpu_system_usec > UINT64_MAX - g->cpu_user_usec ? UINT64_MAX : + g->cpu_user_usec + g->cpu_system_usec); + text_string(&text, "\nuser_usec "); text_unsigned(&text, g->cpu_user_usec); + text_string(&text, "\nsystem_usec "); text_unsigned(&text, g->cpu_system_usec); + text_string(&text, "\n"); break; case CG_PIDS_MAX: if (g->limit == CGROUP_PIDS_UNLIMITED) text_string(&text, "max"); else text_unsigned(&text, g->limit); diff --git a/fs/cgroup/hierarchy.c b/fs/cgroup/hierarchy.c index 9e387b2c..9ce33f19 100644 --- a/fs/cgroup/hierarchy.c +++ b/fs/cgroup/hierarchy.c @@ -3,8 +3,10 @@ #include #include #include +#include #include #include +#include #include #define CGROUP_INDEX_BUCKETS 256u @@ -174,7 +176,18 @@ void cgroup2_fork_commit(struct task *child, const struct task *parent) adjust_locked(g, NULL, 1, 1); } -/** @brief Separate live population from the PID charge of a waitable zombie. */ +/** @copydoc cgroup2_account_cpu */ +void cgroup2_account_cpu(const struct task *task, uint64_t ticks, bool kernel) +{ + const uint64_t usec_per_tick = 1000000ULL / RELIEFNT_TICK_HZ; + uint64_t usec = ticks > UINT64_MAX / usec_per_tick ? UINT64_MAX : ticks * usec_per_tick; + for (struct cgroup *g = task->cgroup ? task->cgroup : &cgroup_root; g; g = g->parent) { + uint64_t *counter = kernel ? &g->cpu_system_usec : &g->cpu_user_usec; + *counter = usec > UINT64_MAX - *counter ? UINT64_MAX : *counter + usec; + } +} + +/** @brief Separate live population from waitable and unretired CPU ownership. */ void cgroup2_task_exit(struct task *task) { if (!task->cgroup) return; @@ -182,11 +195,11 @@ void cgroup2_task_exit(struct task *task) if (!(task->flags & TASK_FLAG_WAITABLE_CHILD) || !task->parent_pid) cgroup2_task_reap(task); } -/** @brief Release an exiting thread's or reaped zombie's charge without VFS I/O. */ +/** @copydoc cgroup2_task_reap */ void cgroup2_task_reap(struct task *task) { struct cgroup *g = task->cgroup; - if (!g) return; + if (!g || task->running_cpu != UINT32_MAX) return; task->cgroup = NULL; adjust_locked(g, NULL, -1, 0); cgroup_put_locked(g); @@ -213,6 +226,7 @@ static struct cgroup *common_ancestor(struct cgroup *a, struct cgroup *b) * @return Zero or negative errno before changing membership; caller holds * both execution ownership and scheduler_lock. * An exited leader with surviving threads still identifies that process. + * Settles all CPUs before changing the first member's accounting ownership. * Migration may exceed a limit; subsequent fork admission enforces it. */ int cgroup_move_locked(struct cgroup *destination, uint32_t pid, const struct fs_access_cred *cred) { @@ -234,6 +248,7 @@ int cgroup_move_locked(struct cgroup *destination, uint32_t pid, const struct fs int rc = cgroup_procs_may_write(ancestor, cred); if (rc) return rc; if (destination == old) return 0; + sched_cpu_accounting_sync_locked(); } if (task->cgroup) cgroup_put_locked(task->cgroup); task->cgroup = destination->parent ? destination : NULL; diff --git a/fs/cgroup/internal.h b/fs/cgroup/internal.h index 2b46273f..c60e4d45 100644 --- a/fs/cgroup/internal.h +++ b/fs/cgroup/internal.h @@ -13,7 +13,7 @@ enum cgroup_file { CG_DIR, CG_PROCS, CG_THREADS, CG_CONTROLLERS, CG_SUBTREE, CG_TYPE, CG_EVENTS, CG_STAT, - CG_PIDS_MAX, CG_PIDS_CURRENT, CG_PIDS_PEAK, CG_PIDS_EVENTS, CG_PIDS_LOCAL, CG_FILE_COUNT, + CG_CPU_STAT, CG_PIDS_MAX, CG_PIDS_CURRENT, CG_PIDS_PEAK, CG_PIDS_EVENTS, CG_PIDS_LOCAL, CG_FILE_COUNT, }; struct cgroup_control_metadata; @@ -25,6 +25,7 @@ struct fs_access_cred; struct cgroup { struct cgroup *parent, *children, *sibling, *index_next, *work_next; uint64_t refs, live, charged, limit, peak, events, local_events; + uint64_t cpu_user_usec, cpu_system_usec; uint32_t id, pids_epoch, descendants, dying; uint16_t path_length, depth, pending; bool linked, subtree_pids, queued; diff --git a/include/reliefnt/cgroup.h b/include/reliefnt/cgroup.h index 1903323b..cf7b91f5 100644 --- a/include/reliefnt/cgroup.h +++ b/include/reliefnt/cgroup.h @@ -28,12 +28,20 @@ bool cgroup2_fork_allowed(const struct task *parent) __attribute__((weak)); * @param child Fresh task with no charge. @param parent Borrowed parent or NULL. * Requires scheduler_lock and a successful admission in the same transaction. */ void cgroup2_fork_commit(struct task *child, const struct task *parent) __attribute__((weak)); -/** @brief Remove a first-time exit from the population, retaining waitable charges. +/** @brief Remove a first-time exit from the population, retaining unretired CPU ownership. * @param task Borrowed task immediately before exit under scheduler_lock. */ void cgroup2_task_exit(struct task *task) __attribute__((weak)); -/** @brief Release a dead task's charge and group pin once, under scheduler_lock. - * @param task Borrowed exited task that is no longer waitable. */ +/** @brief Release a dead task's charge and group pin after CPU retirement. + * @param task Borrowed exited task whose wait is being consumed or is not waitable. + * Caller holds scheduler_lock. An outstanding CPU reservation defers release. */ void cgroup2_task_reap(struct task *task) __attribute__((weak)); +/** @brief Charge actual CPU ticks to a task's current group and all ancestors. + * @param task Borrowed CPU owner whose group pin survives through retirement. + * @param ticks Newly settled user or kernel ticks, never an absolute counter. + * @param kernel True for system time, false for user time. + * Caller holds scheduler_lock. Uses saturating microseconds without allocation, + * additional locks, I/O or reference transfer. Unassigned tasks charge the root. */ +void cgroup2_account_cpu(const struct task *task, uint64_t ticks, bool kernel) __attribute__((weak)); /** @brief Request a worker turn if changes are pending; never under scheduler_lock. */ void cgroup2_kick(void) __attribute__((weak)); /** @brief Write a task's unified membership line, including deleted ancestry. diff --git a/include/reliefnt/proc_stats.h b/include/reliefnt/proc_stats.h index 62a414ba..d81f11a1 100644 --- a/include/reliefnt/proc_stats.h +++ b/include/reliefnt/proc_stats.h @@ -13,6 +13,10 @@ int proc_fd_details(struct task_file *file, struct text_stream *s); /** @brief Settle local runtime before entering/leaving syscall execution. * @param kernel True at entry; false at direct user return. IRQ-safe lock. */ void sched_account_mode(bool kernel); +/** @brief Settle every online CPU to its current owner and cgroup before a snapshot or move. + * Caller holds scheduler_lock. Charges each elapsed interval once, including + * tasks awaiting CPU retirement. No allocation, I/O or reference transfer. */ +void sched_cpu_accounting_sync_locked(void); /** @brief Snapshot user/system/idle ticks in caller-owned per-CPU arrays. * @param user User ticks. @param system Kernel ticks. @param idle Idle ticks. * @param capacity Array length, clamped to CPU maximum; IRQ-safe, no allocation. */ diff --git a/include/reliefnt/sched.h b/include/reliefnt/sched.h index 703d95ca..92fd843a 100644 --- a/include/reliefnt/sched.h +++ b/include/reliefnt/sched.h @@ -126,6 +126,7 @@ void sched_exit(uint32_t pid, uint64_t code); * @brief Release a quiescent user's resources once and invalidate OOM snapshots. * @param task Execution-owned task, nullable. Running or released tasks remain * unchanged; caller must not hold scheduler_lock across resource teardown. + * Drops nonwaitable cgroup ownership after the CPU's final accounting settlement. */ void sched_release_task_resources(struct task *task); /** diff --git a/kernel/sched/accounting.c b/kernel/sched/accounting.c index 64f8e898..8a39588c 100644 --- a/kernel/sched/accounting.c +++ b/kernel/sched/accounting.c @@ -1,4 +1,5 @@ #include "internal.h" +#include #include static uint64_t cpu_accounting_add(uint64_t value, uint64_t delta); @@ -14,6 +15,10 @@ static uint64_t cpu_accounting_add(uint64_t value, uint64_t delta) return delta > UINT64_MAX - value ? UINT64_MAX : value + delta; } +/** @brief Settle elapsed ticks once to the reserved CPU owner and its cgroup. + * @param cpu Online CPU index below SMP_MAX_CPUS. + * Caller holds scheduler_lock. Keeps billing blocked, ready and exited owners + * until reservation retirement, with no allocation or reference transfer. */ void cpu_accounting_settle(uint32_t cpu) { if (!smp_cpu_online(cpu)) { @@ -34,6 +39,8 @@ void cpu_accounting_settle(uint32_t cpu) if (owner && owner->pid && owner->pid == current_pid[cpu] && owner->running_cpu == cpu) { cpu_accounting[cpu].busy_ticks = cpu_accounting_add(cpu_accounting[cpu].busy_ticks, delta); owner->cpu_ticks = cpu_accounting_add(owner->cpu_ticks, delta); + if (delta && cgroup2_account_cpu) + cgroup2_account_cpu(owner, delta, cpu_accounting[cpu].kernel_mode); if (cpu_accounting[cpu].kernel_mode) { cpu_accounting[cpu].system_ticks = cpu_accounting_add(cpu_accounting[cpu].system_ticks, delta); @@ -48,7 +55,8 @@ void cpu_accounting_settle(uint32_t cpu) } } -void cpu_accounting_sync(void) +/** @copydoc sched_cpu_accounting_sync_locked */ +void sched_cpu_accounting_sync_locked(void) { uint32_t count = smp_cpu_count(); if (count > SMP_MAX_CPUS) count = SMP_MAX_CPUS; @@ -83,7 +91,7 @@ void sched_cpu_ticks(uint64_t *busy_ticks, uint64_t *idle_ticks) { uint64_t flags; kernel_spin_lock_irqsave(&scheduler_lock, &flags); - cpu_accounting_sync(); + sched_cpu_accounting_sync_locked(); uint64_t busy = 0, idle = 0; for (uint32_t cpu = 0; cpu < SMP_MAX_CPUS; ++cpu) { busy = cpu_accounting_add(busy, cpu_accounting[cpu].busy_ticks); @@ -104,7 +112,7 @@ void sched_cpu_ticks_per_cpu(uint64_t *busy_ticks, uint64_t *idle_ticks, uint64_t flags; uint32_t count = capacity < SMP_MAX_CPUS ? capacity : SMP_MAX_CPUS; kernel_spin_lock_irqsave(&scheduler_lock, &flags); - cpu_accounting_sync(); + sched_cpu_accounting_sync_locked(); for (uint32_t i = 0; i < count; ++i) { if (busy_ticks) { busy_ticks[i] = cpu_accounting[i].busy_ticks; @@ -123,7 +131,7 @@ void sched_cpu_runtime_snapshot(uint64_t *busy_ticks, uint64_t *idle_ticks, uint64_t flags; uint32_t count = capacity < SMP_MAX_CPUS ? capacity : SMP_MAX_CPUS; kernel_spin_lock_irqsave(&scheduler_lock, &flags); - cpu_accounting_sync(); + sched_cpu_accounting_sync_locked(); for (uint32_t cpu = 0; cpu < count; ++cpu) { if (busy_ticks) { busy_ticks[cpu] = cpu_accounting[cpu].busy_ticks; @@ -151,7 +159,7 @@ uint64_t sched_task_cpu_ticks(const struct task *task, bool process) { uint64_t flags, result = 0; kernel_spin_lock_irqsave(&scheduler_lock, &flags); - cpu_accounting_sync(); + sched_cpu_accounting_sync_locked(); if (task && !process) result = task->cpu_ticks; else if (task) { uint32_t group = sched_task_tgid(task); @@ -224,7 +232,7 @@ uint32_t sched_snapshot(struct task_snapshot_info *out, uint32_t capacity, uint6 uint64_t flags; uint32_t result; kernel_spin_lock_irqsave(&scheduler_lock, &flags); - cpu_accounting_sync(); + sched_cpu_accounting_sync_locked(); if (tick) { *tick = scheduler_ticks; } @@ -303,7 +311,7 @@ void sched_cpu_times(uint64_t *user, uint64_t *system, uint64_t *idle, uint32_t { uint64_t flags; kernel_spin_lock_irqsave(&scheduler_lock, &flags); - cpu_accounting_sync(); + sched_cpu_accounting_sync_locked(); for (uint32_t i = 0; i < capacity && i < SMP_MAX_CPUS; ++i) { user[i] = cpu_accounting[i].user_ticks; system[i] = cpu_accounting[i].system_ticks; @@ -340,7 +348,7 @@ void cpu_accounting_retire_thread(struct task *task) void cpu_accounting_task_times_locked(const struct task *task, bool process, uint64_t *user, uint64_t *system) { - cpu_accounting_sync(); + sched_cpu_accounting_sync_locked(); *user = *system = 0; for (uint32_t i = 0; task && task->pid && i < task_count; ++i) { const struct task *t = tasks[i]; diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 1d7cdd77..eae9541f 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -257,7 +257,7 @@ void sched_on_tick(void) if (tasks[i]->pid && (tasks[i]->state == TASK_RUNNING || tasks[i]->state == TASK_READY)) ++active; sched_load_update(scheduler_loads, active); } - cpu_accounting_sync(); + sched_cpu_accounting_sync_locked(); if (scheduler_ticks >= scheduler_next_wake_tick) { scheduler_next_wake_tick = UINT64_MAX; for (uint32_t i = 0; i < task_count; ++i) { diff --git a/kernel/sched/internal.h b/kernel/sched/internal.h index 081ae1db..a65bbdf4 100644 --- a/kernel/sched/internal.h +++ b/kernel/sched/internal.h @@ -607,7 +607,8 @@ void task_zero(struct task *task); void cpu_accounting_settle(uint32_t cpu); -void cpu_accounting_sync(void); +/** @copydoc sched_cpu_accounting_sync_locked */ +void sched_cpu_accounting_sync_locked(void); /** @brief Transfer a recycled nonleader's CPU time to its published leader. * @param task Borrowed fully retired task, or NULL. Its counters are consumed. diff --git a/kernel/sched/task.c b/kernel/sched/task.c index ec9cc5d4..806492cb 100644 --- a/kernel/sched/task.c +++ b/kernel/sched/task.c @@ -764,6 +764,7 @@ static void sched_release_task_signals(struct task *task) * CLONE_FS paths retire only at the final shared holder. Backend cleanup can * perform I/O, so the caller must not hold scheduler_lock across this call. * Successful release invalidates bounded OOM holder eligibility snapshots. + * Nonwaitable tasks release their cgroup pin only after final CPU settlement. */ void sched_release_task_resources(struct task *task) { @@ -778,6 +779,14 @@ void sched_release_task_resources(struct task *task) if (!kernel_execution_is_outermost()) return; ((struct sched_task_object *)task)->fork_cow_reclaim = (struct fork_cow_reclaim_state){0}; #endif + if (cgroup2_task_reap) { + uint64_t cgroup_flags; + kernel_spin_lock_irqsave(&scheduler_lock, &cgroup_flags); + if (!(task->flags & TASK_FLAG_WAITABLE_CHILD) || !task->parent_pid) + cgroup2_task_reap(task); + kernel_spin_unlock_irqrestore(&scheduler_lock, cgroup_flags); + if (cgroup2_kick) cgroup2_kick(); + } storage_drain_task_io(task->pid); #ifdef CONFIG_SWAP if(memory_headroom_cancel)memory_headroom_cancel(task); diff --git a/tools/tests/cgroup_scheduler_test.c b/tools/tests/cgroup_scheduler_test.c index 4b16147c..de115c09 100644 --- a/tools/tests/cgroup_scheduler_test.c +++ b/tools/tests/cgroup_scheduler_test.c @@ -89,7 +89,7 @@ static struct vfs_path make_group(const struct vfs_path *parent, const char *nam static void control(const struct vfs_path *group, const char *name, const char *text, bool write) { struct vfs_path path; - char bytes[64]; + char bytes[128]; uint32_t count = 0; assert(!vfs_path_lookup_child(group, name, &path)); struct storage_node node = *vfs_path_node(&path); @@ -110,6 +110,104 @@ static void membership(const struct task *task, const char *expected) assert(text.written == strlen(expected) && !memcmp(bytes, expected, text.written)); } +/** @brief Check exact hierarchical CPU microseconds through the real VFS reader. */ +static void cpu_stat(const struct vfs_path *group, uint64_t user, uint64_t system) +{ + char expected[128]; + snprintf(expected, sizeof(expected), "usage_usec %llu\nuser_usec %llu\nsystem_usec %llu\n", + (unsigned long long)(user + system), (unsigned long long)user, + (unsigned long long)system); + control(group, "cpu.stat", expected, false); +} + +/** @brief Exercise SMP settlement, migration, exit tails and retained ancestor history. */ +static void check_cpu_accounting(const struct vfs_path *root, struct task *actor) +{ + fixture_online_cpus = 2; + struct vfs_path parent = make_group(root, "cpu-jobs"); + struct vfs_path left = make_group(&parent, "left"); + struct vfs_path right = make_group(&parent, "right"); + cpu_stat(root, 0, 0); + cpu_stat(&left, 0, 0); + control(&parent, "cgroup.controllers", "pids\n", false); + control(&parent, "cgroup.subtree_control", "+pids", true); + control(&left, "cgroup.procs", "0", true); + int64_t pid = sched_create_user_task("cpu-worker", RELIEFNT_USER_BASE, USER_STACK_TOP, + actor->pid, 0); + assert(pid > 0 && !sched_publish_user_task((uint32_t)pid)); + struct task *child = sched_find((uint32_t)pid); + assert(child && !(child->flags & TASK_FLAG_WAITABLE_CHILD)); + char number[16]; + snprintf(number, sizeof(number), "%u", child->pid); + control(&right, "cgroup.procs", number, true); + + sched_set_running(actor->pid); + sched_account_mode(false); + fixture_current_cpu = 1; + sched_set_running(child->pid); + sched_account_mode(false); + fixture_current_cpu = 0; + assert(actor->running_cpu == 0 && child->running_cpu == 1); + scheduler_ticks += 2; + cpu_stat(&left, 20000, 0); + cpu_stat(&right, 20000, 0); + cpu_stat(&parent, 40000, 0); + cpu_stat(root, 40000, 0); + cpu_stat(root, 40000, 0); + + sched_account_mode(true); + scheduler_ticks += 3; + control(&left, "cgroup.procs", number, true); + cpu_stat(&left, 20000, 30000); + cpu_stat(&right, 50000, 0); + scheduler_ticks += 4; + cpu_stat(&left, 60000, 70000); + cpu_stat(&parent, 110000, 70000); + sched_account_mode(false); + actor->state = TASK_READY; + child->state = TASK_BLOCKED; + scheduler_ticks += 1; + cpu_stat(&left, 80000, 70000); + actor->state = TASK_RUNNING; + control(&right, "cgroup.procs", "0", true); + + sched_exit(child->pid, 0); + assert(child->cgroup && child->running_cpu == 1); + control(&left, "cgroup.events", "populated 0\nfrozen 0\n", false); + control(&parent, "pids.current", "2\n", false); + assert(!left.mount->ops->remove_node(left.mount->context, &left, true)); + scheduler_ticks += 2; + cpu_stat(&parent, 170000, 70000); + cpu_stat(&right, 70000, 0); + fixture_current_cpu = 1; + sched_quiesce_exited_current(); + assert(child->running_cpu == SCHED_CPU_NONE && child->cgroup); + uint64_t flags; + kernel_execution_lock_irqsave(&flags); + sched_release_task_resources(child); + kernel_execution_unlock_irqrestore(flags); + fixture_current_cpu = 0; + assert(!child->cgroup && (child->flags & TASK_FLAG_RESOURCES_RELEASED)); + control(&parent, "pids.current", "1\n", false); + cpu_stat(&parent, 170000, 70000); + + control(root, "cgroup.procs", "0", true); + assert(!right.mount->ops->remove_node(right.mount->context, &right, true)); + assert(!parent.mount->ops->remove_node(parent.mount->context, &parent, true)); + vfs_path_put(&left); + vfs_path_put(&right); + vfs_path_put(&parent); + cgroup2_service(32); + scheduler_ticks += 3; + cpu_stat(root, 200000, 70000); + parent = make_group(root, "cpu-jobs"); + cpu_stat(&parent, 0, 0); + cpu_stat(root, 200000, 70000); + assert(!parent.mount->ops->remove_node(parent.mount->context, &parent, true)); + vfs_path_put(&parent); + puts("PASS cgroup2 CPU: SMP user/system, migration, retirement, idle and deleted history"); +} + /** @brief Check fork, internal publication, exit and reap against a real hierarchy. */ int main(void) { @@ -196,10 +294,16 @@ int main(void) vfs_path_put(&worker); vfs_path_put(&caller); vfs_path_put(&parent); + check_cpu_accounting(&root, actor); vfs_path_put(&root); assert(!vfs_namespace_destroy(&ns)); cgroup2_service(16); sched_exit(actor->pid, 0); + sched_quiesce_exited_current(); + uint64_t flags; + kernel_execution_lock_irqsave(&flags); + sched_release_task_resources(actor); + kernel_execution_unlock_irqrestore(flags); for (uint32_t i = 0; i < task_count; ++i) { sched_task_identity_detach(tasks[i]); free(tasks[i]); diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 63dff33a..da0f4a5c 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -202,6 +202,8 @@ void sched_truncate_file_mappings(const struct storage_node *node,uint64_t size) static struct task *devpts_actor; static struct task *cgroup_tasks[2]; struct kernel_spinlock scheduler_lock; +/** @brief The synchronous VFS fixture has no elapsed CPU time or CPU owners. */ +void sched_cpu_accounting_sync_locked(void) { assert(scheduler_lock.state); } bool console_vga_text_mode; /** @brief Reject an unexpected blocked scheduler actor in the synchronous fixture. * @param task Unexpected waiter. */ diff --git a/tools/tests/task_exit_logging_test.c b/tools/tests/task_exit_logging_test.c index 62c930d4..925b34f3 100644 --- a/tools/tests/task_exit_logging_test.c +++ b/tools/tests/task_exit_logging_test.c @@ -30,9 +30,11 @@ static unsigned console_calls_while_locked; static char console_log_buffer[4096]; static size_t console_log_len; -uint32_t smp_current_cpu(void) { return 0; } -uint32_t smp_cpu_count(void) { return 1; } -bool smp_cpu_online(uint32_t cpu) { return cpu == 0; } +static uint32_t fixture_current_cpu; +static uint32_t fixture_online_cpus = 1; +uint32_t smp_current_cpu(void) { return fixture_current_cpu; } +uint32_t smp_cpu_count(void) { return fixture_online_cpus; } +bool smp_cpu_online(uint32_t cpu) { return cpu < fixture_online_cpus; } uint64_t paging_kernel_cr3(void) { return 0x1000; } void paging_load_cr3(uint64_t cr3) { assert(cr3 == 0x1000); } uint64_t time_uptime_us(void) { return 0; } From d40a177474b94608f7a3181720d8a10e6b962893 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 22:53:33 +0800 Subject: [PATCH 53/97] fix(exec): classify resumable ELF mapping diagnostics --- kernel/exec/userland.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/kernel/exec/userland.c b/kernel/exec/userland.c index a2f5b36e..03c30034 100644 --- a/kernel/exec/userland.c +++ b/kernel/exec/userland.c @@ -568,7 +568,9 @@ static int userland_prepare_exec_credentials(struct task *next, const struct tas * execution transaction and loader serialization; pathname diagnostics never * reopen the image. Pending kernel launches use the ordinary shebang handler * after final credentials are set. Failed staging keeps all arguments, paths - * and MM references cleanup-owned before any started-task publication. + * and MM references cleanup-owned before any started-task publication. Mapping + * EAGAIN in an armed exec retry scope is logged at DEBUG; terminal failures + * include their returned errno at ERROR. */ static int userland_load_task_image_locked(struct task *task, struct task *old, const char *execfn) { @@ -610,7 +612,9 @@ static int userland_load_task_image_locked(struct task *task, struct task *old, if (ret < 0) return ret; ret = elf64_map_task_image(task, old ? old : task, image, &loaded); if (ret < 0) { - console_error("[reliefnt] failed to map executable %s\n", task->name); + console_log(old && old->lookup_scope.armed && ret == -EAGAIN ? + CONSOLE_LOG_DEBUG : CONSOLE_LOG_ERROR, + "[reliefnt] executable mapping path=%s result=%d\n", task->path, ret); return ret; } sched_task_mm(task)->program_break_base = loaded.program_break; From 0137d007646f0d820d8aab35d0cf7ad889c505be Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 23:17:56 +0800 Subject: [PATCH 54/97] feat(cred): scope capabilities to owning user namespaces --- Documentation/core-api/mount-namespaces.rst | 18 ++++ .../LC_MESSAGES/core-api/mount-namespaces.po | 12 +++ .../LC_MESSAGES/core-api/mount-namespaces.po | 12 +++ drivers/tty/pty/session.c | 5 +- drivers/video/drm/drm_file.c | 3 +- drivers/video/drm/drm_ioctl.c | 3 +- drivers/video/drm/svga/kms.h | 6 ++ drivers/video/drm/svga/layout.c | 3 +- fs/ext_common/vfs.c | 8 +- fs/proc/procfs.c | 19 ++-- fs/security/access.c | 14 +-- include/reliefnt/memory_pressure.h | 1 + include/reliefnt/net.h | 4 +- include/reliefnt/permissions.h | 1 + include/reliefnt/pty.h | 1 + include/reliefnt/sched.h | 3 + include/reliefnt/signal.h | 1 + include/reliefnt/syscall.h | 5 ++ include/reliefnt/syscall_internal.h | 12 ++- include/reliefnt/task/accessors.h | 2 + include/reliefnt/task/types.h | 2 + include/reliefnt/user_namespace.h | 76 ++++++++++++++++ kernel/exec/userland.c | 2 + kernel/sched/Kbuild | 2 +- kernel/sched/clone.c | 9 +- kernel/sched/internal.h | 13 ++- kernel/sched/session.c | 9 +- kernel/sched/signal.c | 3 +- kernel/sched/task.c | 7 +- kernel/sched/user_namespace.c | 38 ++++++++ kernel/sched/wait.c | 3 + kernel/signal/signal_queue.c | 3 +- kernel/syscall/device/device.c | 6 +- kernel/syscall/device/legacy_ioctl.c | 13 +-- kernel/syscall/fd/open.c | 3 +- kernel/syscall/fs/create.c | 6 +- kernel/syscall/fs/directory.c | 3 +- kernel/syscall/fs/filesystem.c | 3 +- kernel/syscall/fs/legacy_filesystem.c | 3 +- kernel/syscall/fs/mount.c | 3 +- kernel/syscall/fs/mutation.c | 6 +- kernel/syscall/fs/xattr.c | 3 +- kernel/syscall/internal.h | 1 + kernel/syscall/ipc/ipc.c | 3 +- kernel/syscall/ipc/socket.c | 3 +- kernel/syscall/ipc/sysv_msg.c | 14 +-- kernel/syscall/ipc/sysv_sem.c | 12 ++- kernel/syscall/ipc/sysv_shm.c | 9 +- kernel/syscall/memory/swap.c | 6 +- kernel/syscall/process/clone.c | 3 +- kernel/syscall/process/process.c | 21 +++-- kernel/syscall/process/process_vm.c | 11 ++- kernel/syscall/process/setns.c | 5 +- kernel/syscall/system/modules.c | 6 +- kernel/syscall/time/time.c | 6 +- mm/reclaim/oom.c | 3 +- mm/user/locked.c | 13 +-- mm/user/mapping.c | 6 +- net/interface/config.c | 3 +- net/interface/ioctl.c | 3 +- net/interface/socket.c | 8 +- net/internal.h | 1 + net/socket/control.c | 6 +- net/socket/netlink.c | 9 +- net/socket/packet.c | 3 +- net/socket/udp.c | 3 +- net/tcp/socket.c | 6 +- tools/test_linux_capabilities.py | 2 +- tools/tests/capability_test.c | 87 +++++++++++++++++++ tools/tests/linux_permissions_test.c | 8 ++ tools/tests/memory_pressure_oom_test.c | 4 + tools/tests/modules/scheduler.h | 1 + tools/tests/mount_namespace_task_test.c | 15 ++++ tools/tests/mprotect_vma_growth_test.c | 5 ++ tools/tests/process_vm_test.c | 21 +++++ tools/tests/task_subreaper_test.c | 5 ++ 76 files changed, 552 insertions(+), 109 deletions(-) create mode 100644 include/reliefnt/user_namespace.h create mode 100644 kernel/sched/user_namespace.c diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index b5f340fb..8d2d11c3 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -86,3 +86,21 @@ cwd;已有文件描述符和 umask 不变。准备失败不会部分切换。 ``vfs_namespace_retire()`` 就地摘除整棵树而不传播卸载,随后释放图本身。已持有 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 ``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。 + +凭据权限作用域 +============== + +任务凭据持有引用计数的用户命名空间,空指针表示初始空间。任务 UID/GID 使用 +全局内核 ID。子空间记录创建者的有效 UID,并持有父空间引用,层级上限为 32。 +fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 +释放。清理登录身份继续保留所属空间。 + +文件系统 DAC 特权覆盖、挂载图管理、设备、网络、IPC、时钟、重启、模块、内存锁定 +和 OOM 调整等共享资源使用初始空间能力。信号、进程优先级、跨进程资源限制与 +ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 +后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。 +ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits +及 seccomp 安装使用调用方所属空间的能力集合。 + +内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 +``EINVAL``,UID/GID 映射与用户空间句柄属于后续接入范围。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index ccf696f6..5eef9004 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -191,3 +191,15 @@ msgstr "``vfs_mount_detached_root()`` explicitly exposes the root of a mount tha msgid "``vfs_mount_attach()`` 成功后,挂载和已持有路径转入目标命名空间的正常生命周期。 传播准备失败时保留游离状态、持有路径和原有策略,调用方可继续使用或重试。 路径与挂载引用在最后一次释放后按现有后端清理规则回收。" msgstr "After ``vfs_mount_attach()`` succeeds, the mount and its retained paths enter the normal lifecycle of the target namespace. If propagation preparation fails, the detached state, retained paths and existing policy remain intact so that the caller can continue using the mount or retry. After the last path and mount references are released, cleanup follows the existing backend rules." + +msgid "凭据权限作用域" +msgstr "Credential capability scope" + +msgid "任务凭据持有引用计数的用户命名空间,空指针表示初始空间。任务 UID/GID 使用 全局内核 ID。子空间记录创建者的有效 UID,并持有父空间引用,层级上限为 32。 fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 释放。清理登录身份继续保留所属空间。" +msgstr "Task credentials hold a reference to a user namespace. A null pointer represents the initial namespace. Task UIDs and GIDs are global kernel IDs. A child namespace records its creator’s effective UID and retains its parent, with a nesting limit of 32. Fork and kernel-launched tasks inherit the reference. Exec keeps it, and wait or task-slot reuse releases the reference of a zombie. Clearing a login identity preserves the owning namespace." + +msgid "文件系统 DAC 特权覆盖、挂载图管理、设备、网络、IPC、时钟、重启、模块、内存锁定 和 OOM 调整等共享资源使用初始空间能力。信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。" +msgstr "Filesystem DAC overrides, mount graph management, devices, networking, IPC, the system clock, reboot, modules, memory locking, and OOM adjustments use initial-namespace capabilities for shared resources. Signals, process priorities, cross-process resource limits, and ptrace authorize capability overrides in the target task’s owning namespace. Raising a hard resource limit still requires initial-namespace capability. Capabilities extend to descendant namespaces. A task in the parent namespace whose effective UID matches the child’s owner has capabilities in that child’s subtree. Ptrace’s capability subset check requires both tasks to be in the same user namespace. Capset, identity changes, securebits, and seccomp installation use the caller’s own namespace capabilities." + +msgid "内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``,UID/GID 映射与用户空间句柄属于后续接入范围。" +msgstr "The kernel provides internal namespace allocation and reference APIs. The user-space ``CLONE_NEWUSER`` creation interface currently returns ``EINVAL``. UID/GID mappings and user namespace handles will be added separately." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index ac7621eb..ba177ebc 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -163,3 +163,15 @@ msgstr "``vfs_mount_detached_root()`` はまだ接続されていないマウン msgid "``vfs_mount_attach()`` 成功后,挂载和已持有路径转入目标命名空间的正常生命周期。 传播准备失败时保留游离状态、持有路径和原有策略,调用方可继续使用或重试。 路径与挂载引用在最后一次释放后按现有后端清理规则回收。" msgstr "``vfs_mount_attach()`` が成功すると、マウントと保持中のパスは対象の名前空間の通常のライフサイクルに入る。伝播の準備に失敗しても、切り離された状態、保持中のパス、既存のポリシーはそのままであり、呼び出し元は利用を継続するか再試行できる。パスとマウントの最後の参照が解放されると、既存のバックエンドの規則に従って回収される。" + +msgid "凭据权限作用域" +msgstr "資格情報のケーパビリティの適用範囲" + +msgid "任务凭据持有引用计数的用户命名空间,空指针表示初始空间。任务 UID/GID 使用 全局内核 ID。子空间记录创建者的有效 UID,并持有父空间引用,层级上限为 32。 fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 释放。清理登录身份继续保留所属空间。" +msgstr "タスクの資格情報は参照カウント付きのユーザー名前空間を保持します。NULL ポインターは初期名前空間を表します。タスクの UID と GID はグローバルなカーネル ID です。子名前空間は作成者の実効 UID を記録し、親の参照を保持します。入れ子の上限は 32 です。fork とカーネルによるタスク起動は参照を継承し、exec では参照を維持します。ゾンビタスクの参照は wait による回収時またはタスクスロットの再利用時に解放されます。ログイン ID を消去しても所属名前空間は維持されます。" + +msgid "文件系统 DAC 特权覆盖、挂载图管理、设备、网络、IPC、时钟、重启、模块、内存锁定 和 OOM 调整等共享资源使用初始空间能力。信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。" +msgstr "ファイルシステムの DAC の上書き、マウントグラフの管理、デバイス、ネットワーク、IPC、システムクロック、再起動、モジュール、メモリロック、OOM 調整などの共有資源には、初期名前空間のケーパビリティが必要です。シグナル、プロセス優先度、別プロセスのリソース制限、ptrace のケーパビリティによる認可は、対象タスクが所属する名前空間で行います。ハードリミットの引き上げには引き続き初期名前空間のケーパビリティが必要です。ケーパビリティは子孫の名前空間にも適用されます。子名前空間の所有者と実効 UID が一致する親名前空間のタスクは、その子のサブツリーでケーパビリティを持ちます。ptrace でケーパビリティの部分集合を確認する際は、両タスクが同じユーザー名前空間に属する必要があります。capset、ID の変更、securebits、seccomp の設定には、呼び出し元が所属する名前空間のケーパビリティを使います。" + +msgid "内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``,UID/GID 映射与用户空间句柄属于后续接入范围。" +msgstr "カーネル内部には名前空間の割り当てと参照を管理する API があります。ユーザー空間の ``CLONE_NEWUSER`` による作成は現在 ``EINVAL`` を返します。UID/GID マッピングとユーザー名前空間ハンドルは別途追加します。" diff --git a/drivers/tty/pty/session.c b/drivers/tty/pty/session.c index 5f38cc1c..14506397 100644 --- a/drivers/tty/pty/session.c +++ b/drivers/tty/pty/session.c @@ -47,6 +47,7 @@ int pty_set_foreground_pgid(uint32_t pty_id, uint32_t caller_pid, * @param steal Raw ioctl argument, whose value 1 requests privileged stealing. * @param readable Whether the descriptor was opened for reading. * @return Zero on attachment or a negative Linux errno. + * Stealing or bypassing descriptor read access requires initial user namespace CAP_SYS_ADMIN. */ int pty_acquire_controlling(uint32_t pty_id, uint32_t caller_pid, int steal, int readable) { @@ -59,10 +60,10 @@ int pty_acquire_controlling(uint32_t pty_id, uint32_t caller_pid, int steal, int if (caller->process_session != leader || caller->controlling_pty_id) return -1; if (session->process_session) { - if (steal != 1 || !(caller->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -1; + if (steal != 1 || !(task_initial_capabilities(caller) & (1ULL << CAP_SYS_ADMIN))) return -1; sched_clear_controlling_pty(pty_id); } - if (!readable && !(caller->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -1; + if (!readable && !(task_initial_capabilities(caller) & (1ULL << CAP_SYS_ADMIN))) return -1; session->process_session = caller->process_session; session->foreground_pgid = caller->process_group; struct task *process = sched_find(leader); diff --git a/drivers/video/drm/drm_file.c b/drivers/video/drm/drm_file.c index 8b6e11b8..c22507a8 100644 --- a/drivers/video/drm/drm_file.c +++ b/drivers/video/drm/drm_file.c @@ -7,9 +7,10 @@ #include #include +/** @brief Check initial user namespace authority over the shared DRM device. */ static bool drm_task_admin(const struct task *task) { - return task && (task->cap_effective & (1ULL << CAP_SYS_ADMIN)); + return task && (task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN)); } static void drm_master_release_device(struct drm_file *file) diff --git a/drivers/video/drm/drm_ioctl.c b/drivers/video/drm/drm_ioctl.c index df480d72..118f0939 100644 --- a/drivers/video/drm/drm_ioctl.c +++ b/drivers/video/drm/drm_ioctl.c @@ -236,9 +236,10 @@ static const struct drm_ioctl_desc *drm_ioctl_find(const struct drm_file *file, return NULL; } +/** @brief Require initial user namespace CAP_SYS_ADMIN for privileged DRM ioctls. */ static bool drm_ioctl_is_admin(const struct task *task) { - return task && (task->cap_effective & (1ULL << CAP_SYS_ADMIN)); + return task && (task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN)); } static bool drm_file_is_current_master(const struct drm_file *file) diff --git a/drivers/video/drm/svga/kms.h b/drivers/video/drm/svga/kms.h index 3bb5f36f..979e6a84 100644 --- a/drivers/video/drm/svga/kms.h +++ b/drivers/video/drm/svga/kms.h @@ -140,6 +140,12 @@ int svga_atomic_ioctl(struct task *task, struct drm_file *file, const struct drm void svga_kms_init(void); bool svga_output_connected(unsigned unit); int svga_layout_check(const struct drm_vmw_rect *rects, unsigned count); +/** @brief Set the shared SVGA layout as device master or initial user namespace admin. + * @param task Borrowed caller credentials and user memory context. + * @param file Open DRM file for the caller's device. + * @param arg Validated request with optional user rectangle array. + * @return Zero or negative errno. Publishes the layout after full validation. + */ int svga_update_layout(struct task *task, struct drm_file *file, const struct drm_vmw_update_layout_arg *arg); uint32_t svga_cursor_limit(void); diff --git a/drivers/video/drm/svga/layout.c b/drivers/video/drm/svga/layout.c index a9a80940..22af3565 100644 --- a/drivers/video/drm/svga/layout.c +++ b/drivers/video/drm/svga/layout.c @@ -56,11 +56,12 @@ int svga_layout_check(const struct drm_vmw_rect *rects, unsigned count) return total > limit || (!no_bbox && (uint64_t)right * bottom * 4 > limit) ? -EINVAL : 0; } +/** @copydoc svga_update_layout */ int svga_update_layout(struct task *task, struct drm_file *file, const struct drm_vmw_update_layout_arg *arg) { bool master = file->is_master && file->master && file->device->master == file->master; - if (!master && !(task->cap_effective & (UINT64_C(1) << CAP_SYS_ADMIN))) + if (!master && !(task_initial_capabilities(task) & (UINT64_C(1) << CAP_SYS_ADMIN))) return -EACCES; unsigned count = arg->num_outputs; if (count > SVGA_MAX_OUTPUTS) diff --git a/fs/ext_common/vfs.c b/fs/ext_common/vfs.c index 461dceb7..ecbcbef5 100644 --- a/fs/ext_common/vfs.c +++ b/fs/ext_common/vfs.c @@ -59,10 +59,16 @@ static int ev_read(struct storage_volume *v,const struct storage_node *node,uint struct ext4_inode_view in; int ret=storage_ext4_check_node(v,node,&in); if (ret<0) return ret; return storage_ext4_read_file_range(v,node->first_cluster,&in,offset,data,len,done); } +/** @brief Clear set-ID bits on write unless initial user namespace CAP_FSETID applies. + * @param v Live ext volume under the storage transaction. + * @param ino Target inode number. + * @param in Current inode metadata, updated in place. + * @return Zero or the negative journal or metadata error. + */ static int ev_drop_privileges(struct storage_volume *v,uint64_t ino,struct ext4_inode_view *in) { struct task *task=sched_current_task(); - if (!task || (task->cap_effective&(1ULL<mode&0170000)!=0100000) return 0; + if (!task || (task_initial_capabilities(task)&(1ULL<mode&0170000)!=0100000) return 0; uint16_t remove=04000; if ((in->mode&0010) || !task_in_group(task,in->gid,false)) remove|=02000; if (!(in->mode&remove)) return 0; struct storage_ext4_handle h; int ret=storage_ext4_journal_start(v,EXT4_JOURNAL_CREDITS,&h); if (ret<0) return ret; diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 39950f37..0697b1c2 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -724,20 +724,25 @@ static int proc_mm_strings(struct task *task, struct text_stream *s, bool enviro } return 0; } -/** @brief Linux PTRACE_MODE_READ_FSCREDS gate for stat address fields. */ +/** @brief Apply READ_FSCREDS using the target's owning user namespace. + * @param caller Execution-owned reader. @param target Stable target task. + * @return True for the same thread group, target-scoped PTRACE authority, or + * matching filesystem IDs and same-namespace commoncap subset authorization. + */ bool proc_stat_mm_visible(struct task *caller, struct task *target) { if (!caller) return false; if (sched_task_tgid(caller) == sched_task_tgid(target)) return true; - bool privileged = (caller->cap_effective & (1ULL << CAP_SYS_PTRACE)) != 0; + bool privileged = task_ns_capable(caller, target->user_ns, CAP_SYS_PTRACE); if (!privileged && (caller->fsuid != target->uid || caller->fsuid != target->euid || caller->fsuid != target->suid || caller->fsgid != target->gid || caller->fsgid != target->egid || caller->fsgid != target->sgid || sched_task_mm(target)->nondumpable)) return false; - return privileged || !(target->cap_permitted & ~caller->cap_effective); + return privileged || (caller->user_ns == target->user_ns && + !(target->cap_permitted & ~caller->cap_effective)); } /** @brief Pin the exact file path referenced by an authorized process FD. @@ -1653,12 +1658,12 @@ int proc_lock_stats_permissions(const char *name, const struct storage_node *nod * @param name Required borrowed intrinsic proc key. * @param length Requested file size, only zero is accepted. * @return Zero or negative errno; VFS enforces the live read-only mount. - * Execution-owned task context; current CAP_SYS_ADMIN is required. */ + * The execution-owned caller needs initial user namespace CAP_SYS_ADMIN. */ int proc_lock_stats_truncate(const char *name, uint64_t length) { if (!proc_text_eq(name, "/proc/reliefnt/lock_stats")) return -EROFS; struct task *task = sched_current_task(); - if (!task || !(task->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -EPERM; + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -EPERM; return length ? -EINVAL : 0; } @@ -1669,7 +1674,7 @@ int proc_lock_stats_truncate(const char *name, uint64_t length) * @param length Exact byte length including optional newline, at most six. * @param written Required writable byte count, zero on failure. * @return Zero or negative errno. Execution-owned task context; VFS checks - * the live read-only mount and this callback checks current CAP_SYS_ADMIN. */ + * the live read-only mount and this callback checks initial user namespace CAP_SYS_ADMIN. */ int proc_lock_stats_write(const char *name, uint64_t offset, const void *buffer, uint32_t length, uint32_t *written) { @@ -1677,7 +1682,7 @@ int proc_lock_stats_write(const char *name, uint64_t offset, const void *buffer, *written = 0; if (!proc_text_eq(name, "/proc/reliefnt/lock_stats")) return -EROFS; struct task *task = sched_current_task(); - if (!task || !(task->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -EPERM; + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -EPERM; if (offset || !buffer || !length || length > 6) return -EINVAL; int rc = lock_profile_control(buffer, length); if (!rc) *written = length; diff --git a/fs/security/access.c b/fs/security/access.c index 76364756..b1c22959 100644 --- a/fs/security/access.c +++ b/fs/security/access.c @@ -183,7 +183,7 @@ struct fs_access_cred fs_access_credentials(const struct task *task,bool real_id if(!task)return (struct fs_access_cred){.caps=UINT64_MAX}; return (struct fs_access_cred){.uid=real_ids ? task->uid : task->fsuid, .gid=real_ids ? task->gid : task->fsgid,.groups=task->groups, - .caps=real_ids ? (task->uid ? 0 : task->cap_permitted) : task->cap_effective}; + .caps=real_ids ? ((task->user_ns || task->uid) ? 0 : task->cap_permitted) : task_initial_capabilities(task)}; } /** @copydoc fs_permissions_check_mode */ @@ -226,15 +226,16 @@ int fs_permissions_check_path(const struct task *task,const struct vfs_path *pat * @param value Caller-owned current metadata, updated only after authorization. * @param mode Requested permission and special bits. * @return Zero or negative errno. No locks or references are acquired. + * CAP_FOWNER and CAP_FSETID overrides require initial user namespace authority. */ static int chmod_value(const struct task *task,const struct storage_node *node, struct reliefos_permissions *value,uint32_t mode) { - if (task && task->fsuid != value->uid && !(task->cap_effective & (1ULL << CAP_FOWNER))) + if (task && task->fsuid != value->uid && !(task_initial_capabilities(task) & (1ULL << CAP_FOWNER))) return -RELIEFOS_EPERM; if (node->type == RELIEFOS_FS_TYPE_SYMLINK) return -RELIEFOS_EOPNOTSUPP; value->mode = (value->mode & LINUX_S_IFMT) | (mode & 07777u); - if (task && !(task->cap_effective & (1ULL << CAP_FSETID)) && + if (task && !(task_initial_capabilities(task) & (1ULL << CAP_FSETID)) && !task_in_group(task, value->gid, false)) value->mode &= ~02000u; return 0; } @@ -246,21 +247,22 @@ static int chmod_value(const struct task *task,const struct storage_node *node, * @param uid New user ID, UINT32_MAX to retain the existing ID. * @param gid New group ID, UINT32_MAX to retain the existing ID. * @return Zero or negative errno. No locks or references are acquired. + * A CAP_CHOWN override requires initial user namespace authority. */ static int chown_value(const struct task *task,const struct storage_node *node, struct reliefos_permissions *value,uint32_t uid,uint32_t gid) { bool drop_sgid = (value->mode & 02000u) && - ((value->mode & 0010u) || (task && !(task->cap_effective & (1ULL << CAP_FSETID)) && + ((value->mode & 0010u) || (task && !(task_initial_capabilities(task) & (1ULL << CAP_FSETID)) && !task_in_group(task, value->gid, false))); if (task) { bool owner = task->fsuid == value->uid; - bool chown_cap = (task->cap_effective & (1ULL << CAP_CHOWN)) != 0; + bool chown_cap = (task_initial_capabilities(task) & (1ULL << CAP_CHOWN)) != 0; if (uid != UINT32_MAX && (!owner || uid != value->uid) && !chown_cap) return -RELIEFOS_EPERM; if (gid != UINT32_MAX && (!owner || (gid != value->gid && !task_in_group(task, gid, false))) && !chown_cap) return -RELIEFOS_EPERM; if (node->type != RELIEFOS_FS_TYPE_DIR && ((value->mode & 04000u) || drop_sgid) && - !owner && !(task->cap_effective & (1ULL << CAP_FOWNER))) return -RELIEFOS_EPERM; + !owner && !(task_initial_capabilities(task) & (1ULL << CAP_FOWNER))) return -RELIEFOS_EPERM; } if (uid != UINT32_MAX) value->uid = uid; if (gid != UINT32_MAX) value->gid = gid; diff --git a/include/reliefnt/memory_pressure.h b/include/reliefnt/memory_pressure.h index 66abeb5f..51bd9df3 100644 --- a/include/reliefnt/memory_pressure.h +++ b/include/reliefnt/memory_pressure.h @@ -130,6 +130,7 @@ int oom_adj_get(struct task *task); * @param value Requested adjustment in -1000..1000. * @param caller Live capability-bearing caller, borrowed under the writer. * @return Zero or -EINVAL/-ESRCH/-EDEADLK/-EACCES; no ownership transfers. + * Lowering the minimum requires CAP_SYS_RESOURCE in the initial user namespace. */ int oom_adj_set(struct task *task, int value, struct task *caller); #endif diff --git a/include/reliefnt/net.h b/include/reliefnt/net.h index 6959ec40..f3fde222 100644 --- a/include/reliefnt/net.h +++ b/include/reliefnt/net.h @@ -302,7 +302,9 @@ void net_driver_detached(void); */ void net_device_info(uint32_t *flags, uint64_t *mac_value, uint32_t *local_ip); -/** @brief Execute a native Linux interface/route ioctl with checked user memory. */ +/** @brief Execute a native Linux interface/route ioctl with checked user memory. + * Changes require initial user namespace CAP_NET_ADMIN. + */ int net_interface_ioctl(uint32_t request, uint64_t address); /** @brief Report whether the primary compatibility NIC is administratively up and ready. */ diff --git a/include/reliefnt/permissions.h b/include/reliefnt/permissions.h index 72316f42..0792a611 100644 --- a/include/reliefnt/permissions.h +++ b/include/reliefnt/permissions.h @@ -19,6 +19,7 @@ struct fs_access_cred { * @param task Execution-owned source, NULL for trusted kernel access. * @param real_ids Select the real IDs and applicable permitted capabilities. * @return A value snapshot with a borrowed supplementary group list. + * DAC capability overrides apply only to initial user namespace credentials. */ struct fs_access_cred fs_access_credentials(const struct task *task,bool real_ids); /** @brief Check normal DAC using only an inode type, mode and explicit credentials. diff --git a/include/reliefnt/pty.h b/include/reliefnt/pty.h index 1cfdd356..ad02019c 100644 --- a/include/reliefnt/pty.h +++ b/include/reliefnt/pty.h @@ -244,6 +244,7 @@ int pty_set_foreground_pgid(uint32_t pty_id, uint32_t caller_pid, * @param steal Value 1 requests privileged terminal stealing. * @param readable Nonzero when the descriptor permits reads. * @return Zero on success or a negative Linux errno. + * Privilege overrides use CAP_SYS_ADMIN in the initial user namespace. */ int pty_acquire_controlling(uint32_t pty_id, uint32_t caller_pid, int steal, int readable); int pty_get_session(uint32_t pty_id, uint32_t *session_id); diff --git a/include/reliefnt/sched.h b/include/reliefnt/sched.h index 92fd843a..ec236d4f 100644 --- a/include/reliefnt/sched.h +++ b/include/reliefnt/sched.h @@ -7,6 +7,7 @@ #include #include +#include /** * @brief Initialize the scheduler, its run queue, and the tick bookkeeping. @@ -22,6 +23,7 @@ struct task *sched_create_kernel_task(const char *name,uint64_t entry,uint64_t l /** * @brief Prepare a blocked user task with inherited identity but no cgroup charge. * @return Prepared PID or negative errno. Caller finishes with sched_publish_user_task(). + * A prepared child retains its parent's owning user namespace. */ int64_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack_top, uint32_t parent_pid, uint32_t flags); @@ -454,6 +456,7 @@ int sched_signal_action(uint32_t pid, int signal_number, uint32_t operation, * @param process_group Target process group identifier. * @param signal_number POSIX signal number. * @return Number of signalled tasks, or a negative scheduler error. + * CAP_KILL is checked in each target's owning user namespace. */ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, int signal_number); diff --git a/include/reliefnt/signal.h b/include/reliefnt/signal.h index 8d83d5cb..0111405d 100644 --- a/include/reliefnt/signal.h +++ b/include/reliefnt/signal.h @@ -90,6 +90,7 @@ int kernel_signal_import_info(struct task *caller, uint64_t pointer, int sig, * @param sig Requested signal; SIGCONT permits the same-session exception. * @return True for an authorized sender, false for NULL tasks or denial. * Does not acquire locks, retain references or enqueue a signal. + * Check the CAP_KILL override in the target's owning user namespace. */ bool kernel_signal_may_send(const struct task *caller, const struct task *target, int sig); /** @brief Test Linux's default-ignore signal set. */ diff --git a/include/reliefnt/syscall.h b/include/reliefnt/syscall.h index 2823a128..bd284711 100644 --- a/include/reliefnt/syscall.h +++ b/include/reliefnt/syscall.h @@ -337,6 +337,8 @@ void syscall_init(void); void syscall_trace_configure(const char *cmdline); /** * @brief Dispatches process identity, groups, signals, priority, and limits. + * Global system controls use initial user namespace capabilities. Signal, + * priority and cross-process limit overrides use the target's owning namespace. */ int64_t syscall_process_control(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3); @@ -457,6 +459,7 @@ int64_t syscall_mm_mlock(uint64_t addr, uint64_t len, uint64_t flags); int64_t syscall_mm_munlock(uint64_t addr, uint64_t len); /** @brief Set current and future lock policy for the shared MM. * @param flags Low 32-bit Linux MCL flags. @return Zero or negative errno. + * A memlock quota override requires CAP_IPC_LOCK in the initial user namespace. */ int64_t syscall_mm_mlockall(uint64_t flags); /** @brief Clear current and future lock policy. @return Zero or negative errno. */ @@ -464,10 +467,12 @@ int64_t syscall_mm_munlockall(void); /** @brief Activate a swap area after Linux flag-width and capability checks. * @param user_path User pathname. @param flags Raw syscall-register flags. * @return Zero or negative errno; disabled builds return -ENOSYS. + * The caller must hold CAP_SYS_ADMIN in the initial user namespace. */ int64_t syscall_mm_swapon(uint64_t user_path,uint64_t flags); /** @brief Deactivate a swap area after the Linux capability check. * @param user_path User pathname. @return Zero or negative errno. + * The caller must hold CAP_SYS_ADMIN in the initial user namespace. */ int64_t syscall_mm_swapoff(uint64_t user_path); int64_t syscall_mm_brk(uint64_t requested); diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index 5b4d3634..86ea06ac 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -18,6 +18,7 @@ struct storage_inode_ref; * @param flags Full native unsigned long flag word, without truncation. * @return Zero, EINVAL for unsupported flags, EPERM without effective * CAP_SYS_ADMIN for CLONE_NEWNS, or the original snapshot error. + * Mount graph creation requires authority in the initial user namespace. */ int64_t syscall_unshare(struct task *task, uint64_t flags); @@ -27,6 +28,7 @@ int64_t syscall_unshare(struct task *task, uint64_t flags); * @param type Zero or CLONE_NEWNS, already reduced to 32 bits. * @return Zero, EBADF for an invalid/O_PATH FD, EINVAL for an unsupported * type, FD or shared filesystem state, or EPERM for missing capabilities. + * Mount graph entry checks capabilities in the initial user namespace. */ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type); @@ -792,10 +794,14 @@ void syscall_record_locks_release(struct task_file *file); * @param task Execution-owned task, nullable. Does not release held locks. */ void syscall_record_lock_cancel(struct task *task); -/** @brief Execute a native realtime clock discipline request. */ +/** @brief Execute a native realtime clock discipline request. + * Clock adjustments require initial user namespace CAP_SYS_TIME. + */ int64_t syscall_adjtimex(int32_t clock, uint64_t address); -/** @brief Check CAP_SYS_MODULE and execute a native driver control request. */ +/** @brief Check CAP_SYS_MODULE and execute a native driver control request. + * Check CAP_SYS_MODULE in the initial user namespace. + */ int64_t syscall_driver_control(uint32_t request, uint64_t address); /** @brief Execute authorized module operations with copied userspace inputs. @@ -804,6 +810,7 @@ int64_t syscall_driver_control(uint32_t request, uint64_t address); * @param a1 Image length, delete flags or parameters user address. * @param a2 Parameters user address or finit flags. * @return Linux result/negative errno; execution transaction held by caller. + * Uses CAP_SYS_MODULE in the initial user namespace. */ int64_t syscall_modules(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2); @@ -812,6 +819,7 @@ int64_t syscall_modules(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2); * @param flags Linux finit flags in the low 32 bits. * @return Zero or Linux errno, including ENOSYS before task lookup when disabled. * Task context under execution ownership; no usercopy, I/O or ref transfer. + * Uses CAP_SYS_MODULE in the initial user namespace. */ int syscall_module_file_prepare(uint64_t fd,uint64_t flags); diff --git a/include/reliefnt/task/accessors.h b/include/reliefnt/task/accessors.h index bbe9df4d..d50c3af0 100644 --- a/include/reliefnt/task/accessors.h +++ b/include/reliefnt/task/accessors.h @@ -299,6 +299,7 @@ static inline struct kernel_sigqueue *sched_task_process_signal_queue(struct tas /** @brief Validate clone flags, namespace privilege and TLS before TID access. * @param flags Linux clone flags and optional exit signal. @param tls TLS base. * @return Zero or the scheduler's original validation errno; no locks or I/O. + * Mount namespace creation requires initial user namespace CAP_SYS_ADMIN. */ int sched_clone_validate_flags(uint64_t flags,uint64_t tls); /** @brief Clone or share a user's resources and owned filesystem paths. @@ -312,6 +313,7 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls); * Execution transaction required; takes scheduler_lock. CLONE_FS shares the * actual root/cwd owner; ordinary fork retains independent path references. * CLONE_NEWNS prepares a distinct graph before reserving a task ID. + * The child retains the caller's user namespace through publication or rollback. */ int64_t sched_clone_current(const struct trap_frame *frame, uint64_t flags, uint64_t stack, uint64_t parent_tid, diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index c0b77ade..5482fca8 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -400,6 +400,7 @@ struct task_groups { }; struct task_credentials_state { + struct user_namespace *user_ns; /**< Owning user namespace; NULL is the initial namespace. */ uint32_t uid; uint32_t gid; uint32_t euid; @@ -731,6 +732,7 @@ struct task { union { struct task_credentials_state credentials; struct { + struct user_namespace *user_ns; uint32_t uid; uint32_t gid; uint32_t euid; diff --git a/include/reliefnt/user_namespace.h b/include/reliefnt/user_namespace.h new file mode 100644 index 00000000..112a3720 --- /dev/null +++ b/include/reliefnt/user_namespace.h @@ -0,0 +1,76 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_USER_NAMESPACE_H +#define RELIEFNT_USER_NAMESPACE_H + +#include +#include + +/** @brief Reference-counted credential scope with immutable parent and owner. + * NULL represents the initial namespace. IDs in task credentials remain global + * kernel IDs. Each child retains its parent until its own final release. + */ +struct user_namespace { + uint64_t references; + struct user_namespace *parent; + uint32_t owner; + uint32_t level; +}; + +/** @brief Allocate a child credential scope without changing its creator. + * @param creator Execution-owned source credentials, required. + * @param out Empty output receiving one owned reference, NULL on failure. + * @return Zero, -EINVAL, -ENOSPC at 32 levels, or -ENOMEM. No user access or + * publication occurs. Caller holds execution ownership outside scheduler_lock. + */ +int user_namespace_create(const struct task *creator, struct user_namespace **out); + +/** @brief Retain an existing namespace or the permanent initial scope. + * @param ns Borrowed live namespace, nullable for the initial namespace. + * @return The same pointer with one additional owned reference when non-NULL. + * Atomic and allocation-free, including under scheduler_lock. + */ +struct user_namespace *user_namespace_get(struct user_namespace *ns); + +/** @brief Release a namespace reference and any unreferenced ancestors. + * @param ns Owned reference, nullable for the initial namespace. + * Atomic reference retirement may free heap objects, with no provider I/O, + * user access or scheduler lock acquisition. + */ +void user_namespace_put(struct user_namespace *ns); + +/** @brief Read effective authority over initial-namespace resources. + * @param task Borrowed stable credentials, NULL has no user capability. + * @return Effective capabilities for the initial namespace, otherwise zero. + * Local capabilities never grant authority over an ancestor. No references, + * locks, allocation or user access. Trusted kernel callers handle NULL at + * their own authorization boundary. + */ +static inline uint64_t task_initial_capabilities(const struct task *task) +{ + return task && !task->user_ns ? task->cap_effective : 0; +} + +/** @brief Authorize a capability in the exact owning user namespace. + * @param task Borrowed execution-owned caller, nullable. + * @param ns Borrowed target scope, NULL selects the initial namespace. + * @param capability Linux capability index. + * @return True for a scoped effective capability or ownership of a child + * scope. Effective capabilities extend to descendants. Neither descendants + * nor siblings gain authority over an ancestor or each other. The caller + * stabilizes both ancestry and credentials. No locks or references are taken. + */ +static inline bool task_ns_capable(const struct task *task, + const struct user_namespace *ns, + unsigned capability) +{ + if (!task || capability > CAP_LAST_CAP) return false; + for (;;) { + if (task->user_ns == ns) + return (task->cap_effective & (UINT64_C(1) << capability)) != 0; + if (!ns) return false; + if (ns->parent == task->user_ns && ns->owner == task->euid) return true; + ns = ns->parent; + } +} + +#endif diff --git a/kernel/exec/userland.c b/kernel/exec/userland.c index 03c30034..0b9f0c40 100644 --- a/kernel/exec/userland.c +++ b/kernel/exec/userland.c @@ -1178,6 +1178,7 @@ static void userland_discard_prepared(struct task *prepared) /** @brief Publish a completely loaded image after all old-MM cleanup finishes. * @param task Current task. @param prepared Detached owned image. * @return Zero; all resources move exactly once or retire after publication. + * The user namespace reference remains owned by the live task across the credential copy. */ static int userland_commit_prepared(struct task *task, struct task *prepared) { @@ -1296,6 +1297,7 @@ int userland_exec_current_path(const struct vfs_path *image,const char *execfn, prepared = kernel_malloc(sizeof(*prepared)); if (!prepared) return -12; __builtin_memset(prepared, 0, sizeof(*prepared)); + /* The live task keeps ownership of the namespace until commit or discard. */ prepared->credentials = task->credentials; sched_task_fs_inherit(prepared,task); vfs_path_get(image,&prepared->address_space.executable_path); diff --git a/kernel/sched/Kbuild b/kernel/sched/Kbuild index 683cf62b..ee908b03 100644 --- a/kernel/sched/Kbuild +++ b/kernel/sched/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := accounting.o clone.o core.o exec.o fair.o fs.o identity.o kthread.o lookup.o oom.o rseq.o session.o signal.o tables.o task.o timers.o wait.o +obj-y := accounting.o clone.o core.o exec.o fair.o fs.o identity.o kthread.o lookup.o oom.o rseq.o session.o signal.o tables.o task.o timers.o user_namespace.o wait.o include $(srctree)/scripts/Makefile.module diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index 104efb35..86b3e4ea 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -131,6 +131,7 @@ void sched_vfork_child_done(struct task *child) * @param flags Linux clone flags and exit signal. @param tls Requested TLS base. * @return Zero or the original clone validation errno; no allocation, locks, * user access or state changes occur. + * Privilege checks for the existing mount graph use initial user namespace capabilities. */ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) { @@ -151,13 +152,13 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) * reaching the unavailable PID/network namespace backend. */ if ((flags & CLONE_NEWPID) && (flags & CLONE_THREAD)) return -LINUX_EINVAL; const struct task *parent = sched_current_task(); - return parent && (parent->cap_effective & (1ULL << CAP_SYS_ADMIN)) + return parent && (task_initial_capabilities(parent) & (1ULL << CAP_SYS_ADMIN)) ? -LINUX_EINVAL : -LINUX_EPERM; } if (flags & ~supported) return -RELIEFOS_ENOSYS; if (flags & CLONE_NEWNS) { const struct task *parent = sched_current_task(); - if (!parent || !(parent->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; + if (!parent || !(task_initial_capabilities(parent) & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; } if ((flags & CLONE_SETTLS) && tls >= RELIEFNT_USER_TLS_LIMIT) return -RELIEFOS_EPERM; return 0; @@ -181,6 +182,7 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) * The child never borrows the parent's retained PID-identity object or pending * syscall lookup names/root/dirfd references or imported vector/transfer state, * including on early allocation failure. + * The child owns its inherited user namespace reference. Rollback releases it. */ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flags, uint64_t stack, uint64_t parent_tid, @@ -241,6 +243,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag } task_zero(child); *child = *parent; + child->user_ns = user_namespace_get(parent->user_ns); /* Borrowed by the shallow copy; only successful publication takes a charge. */ child->cgroup = NULL; /* Forked processes start unset and new threads use their existing leader. */ @@ -590,6 +593,8 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag if (child->shared_files) --child->shared_files->references; kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_fs_release(child); + user_namespace_put(child->user_ns); + child->user_ns = NULL; if (!child->shared_mm) { address_space_destroy(sched_task_as(child)); sched_task_vma_release(child); diff --git a/kernel/sched/internal.h b/kernel/sched/internal.h index a65bbdf4..c5ea3418 100644 --- a/kernel/sched/internal.h +++ b/kernel/sched/internal.h @@ -505,6 +505,10 @@ bool sched_current_cpu_needs_resched(void); uint64_t sched_user_task_count(uint32_t uid); +/** @brief Check a task against the global per-UID process quota. + * @param task Borrowed task under scheduler_lock, nullable. + * @return True at the soft limit unless the global root UID or an initial namespace capability exempts it. + */ bool task_nproc_denied_locked(const struct task *task); uint64_t sched_all_cpu_mask(void); @@ -579,7 +583,8 @@ void task_copy_path(struct task *task, const char *path); void task_copy_identity_text(char *dst, size_t cap, const char *src); /** - * @brief Strip admin flag, uid, role, session, username, and home, leaving an anonymous task. + * @brief Clear task identity and capabilities while retaining its owning user namespace. + * @param task Execution-owned task, nullable. Releases supplemental groups. */ void task_clear_identity(struct task *task); @@ -587,7 +592,8 @@ void task_clear_identity(struct task *task); * @brief Inherit identity and independent held root/cwd paths from a parent. * @param task New task with private filesystem state under execution ownership. * @param parent Stable source task; NULL leaves the destination unchanged. - * Retains group and path references; caller serializes task publication. + * Retains groups, the owning user namespace and path references. The destination + * initially has no owned credential references. Caller serializes publication. */ void task_copy_identity_from_parent(struct task *task, const struct task *parent); @@ -641,6 +647,7 @@ uint32_t task_allocate_pid(void); * @return Borrowed unpublished task slot, or NULL on allocation/size failure. * Caller holds scheduler_lock. Invalidates old PID identities before reuse; * does not perform filesystem/device resource teardown or backend I/O. + * Recycling releases the retired task's owning user namespace reference. */ struct task *alloc_task_slot(void); @@ -653,6 +660,7 @@ struct task *sched_create_kernel_task(const char *name,uint64_t entry,uint64_t l /** * @brief Prepare an unpublished user task and its address space; return PID or negative errno. + * A prepared child retains its parent's owning user namespace. */ int64_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack_top, uint32_t parent_pid, uint32_t flags); @@ -1031,6 +1039,7 @@ int64_t sched_process_group_session(uint32_t process_group); int sched_process_group_orphaned(uint32_t process_group); +/** @brief Send to a process group after checking CAP_KILL in each target's namespace. */ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, int signal_number); diff --git a/kernel/sched/session.c b/kernel/sched/session.c index ebfd6287..b7fe124a 100644 --- a/kernel/sched/session.c +++ b/kernel/sched/session.c @@ -19,7 +19,8 @@ void task_copy_identity_text(char *dst, size_t cap, const char *src) } /** - * @brief Strip admin flag, uid, role, session, username, and home, leaving an anonymous task. + * @brief Clear task identity and capabilities while retaining its owning user namespace. + * @param task Execution-owned task, nullable. Releases supplemental groups. */ void task_clear_identity(struct task *task) { @@ -52,14 +53,16 @@ void task_clear_identity(struct task *task) * @brief Inherit identity and independent filesystem references from a parent. * @param task New task with private filesystem state under execution ownership. * @param parent Stable source task; NULL leaves the destination unchanged. - * Retains group, namespace and mount/dentry references without allocating or resolving - * cached path strings. Caller serializes task publication with scheduler_lock. + * Retains supplemental groups, the owning user namespace and mount/dentry references + * without allocating or resolving cached path strings. The destination initially + * has no owned credential references. Caller serializes publication with scheduler_lock. */ void task_copy_identity_from_parent(struct task *task, const struct task *parent) { if (!task || !parent) { return; } + task->user_ns = user_namespace_get(parent->user_ns); task->uid = parent->uid; task->gid = parent->gid; task->euid = parent->euid; diff --git a/kernel/sched/signal.c b/kernel/sched/signal.c index 7c2a7c3a..54c5b4ef 100644 --- a/kernel/sched/signal.c +++ b/kernel/sched/signal.c @@ -314,6 +314,7 @@ int sched_signal_kernel_group(uint32_t process_group, int signal_number) return count ? count : -LINUX_ESRCH; } +/** @copydoc sched_signal_process_group */ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, int signal_number) { @@ -329,7 +330,7 @@ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, task->process_group != process_group || task->pid != sched_task_tgid(task) || (task->state == TASK_EXITED && !(task->flags & TASK_FLAG_WAITABLE_CHILD))) continue; if (sched_task_tgid(sender) != sched_task_tgid(task) && - !(sender->cap_effective & (1ULL << CAP_KILL)) && + !task_ns_capable(sender, task->user_ns, CAP_KILL) && sender->uid != task->uid && sender->uid != task->suid && sender->euid != task->uid && sender->euid != task->suid && !(signal_number == 18 && sender->process_session == task->process_session)) { diff --git a/kernel/sched/task.c b/kernel/sched/task.c index 806492cb..98d26854 100644 --- a/kernel/sched/task.c +++ b/kernel/sched/task.c @@ -102,10 +102,11 @@ uint64_t sched_user_task_count(uint32_t uid) return count; } +/** @copydoc task_nproc_denied_locked */ bool task_nproc_denied_locked(const struct task *task) { return task && task->uid && - !(task->cap_effective & ((1ULL << CAP_SYS_RESOURCE) | (1ULL << CAP_SYS_ADMIN))) && + !(task_initial_capabilities(task) & ((1ULL << CAP_SYS_RESOURCE) | (1ULL << CAP_SYS_ADMIN))) && user_task_count_locked(task->uid) >= sched_task_limits(task)->nproc.rlim_cur; } @@ -194,6 +195,7 @@ uint32_t task_allocate_pid(void) * Caller holds scheduler_lock. Retires old PID identities before reuse so held * proc inodes cannot retarget. Preserves recycled thread CPU time on its still * published group leader; releases no filesystem or device resources here. + * Recycling releases the old task's owning user namespace reference. */ struct task *alloc_task_slot(void) { @@ -207,6 +209,8 @@ struct task *alloc_task_slot(void) task_release_limits(tasks[i]); fair_forget(tasks[i]); sched_task_identity_detach(tasks[i]); + user_namespace_put(tasks[i]->user_ns); + tasks[i]->user_ns = NULL; struct sched_task_object *object = (struct sched_task_object *)tasks[i]; object->futex_exit = (struct futex_exit_cursor){0}; object->exec_prepared = NULL; @@ -426,6 +430,7 @@ struct task *sched_create_kernel_task(const char *name,uint64_t entry,uint64_t l * @param flags Initial task flags. @return Prepared PID or negative errno. * Prepares the address space and PID identity but neither charges cgroups nor * makes the task runnable. Execution ownership required through final publication. + * The prepared child retains the parent's owning user namespace. */ int64_t sched_create_user_task(const char *name, uint64_t entry, uint64_t stack_top, uint32_t parent_pid, uint32_t flags) diff --git a/kernel/sched/user_namespace.c b/kernel/sched/user_namespace.c new file mode 100644 index 00000000..2afe961f --- /dev/null +++ b/kernel/sched/user_namespace.c @@ -0,0 +1,38 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include +#include +#include + +/** @copydoc user_namespace_get */ +struct user_namespace *user_namespace_get(struct user_namespace *ns) +{ + if (ns) __atomic_add_fetch(&ns->references, 1, __ATOMIC_RELAXED); + return ns; +} + +/** @copydoc user_namespace_put */ +void user_namespace_put(struct user_namespace *ns) +{ + while (ns && !__atomic_sub_fetch(&ns->references, 1, __ATOMIC_ACQ_REL)) { + struct user_namespace *parent = ns->parent; + kernel_free(ns); + ns = parent; + } +} + +/** @copydoc user_namespace_create */ +int user_namespace_create(const struct task *creator, struct user_namespace **out) +{ + if (!out) return -LINUX_EINVAL; + *out = NULL; + if (!creator) return -LINUX_EINVAL; + uint32_t level = creator->user_ns ? creator->user_ns->level + 1 : 1; + if (level > 32) return -LINUX_ENOSPC; + struct user_namespace *ns = kernel_malloc(sizeof(*ns)); + if (!ns) return -LINUX_ENOMEM; + *ns = (struct user_namespace){.references = 1, + .parent = user_namespace_get(creator->user_ns), + .owner = creator->euid, .level = level}; + *out = ns; + return 0; +} diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index dc39999d..8a7462ed 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -170,6 +170,7 @@ static void sched_wait_usage(struct linux_rusage *out, const struct task *task) * execute outside it. WNOWAIT observes without consuming or logging a reap. * Consuming a zombie releases its cgroup charge and invalidates its retained * PID identity before PID unpublish. + * A consuming reap also releases the zombie's owning user namespace reference. */ static int64_t sched_wait_child(uint32_t waiter_pid, int32_t wanted_pid, const struct task_identity *identity, @@ -292,6 +293,8 @@ static int64_t sched_wait_child(uint32_t waiter_pid, int32_t wanted_pid, reap_task->parent_pid = 0; notify_pidfd = sched_task_pidfd_watched(reap_task); sched_task_identity_detach(reap_task); + user_namespace_put(reap_task->user_ns); + reap_task->user_ns = NULL; task_release_limits(reap_task); reap_task->flags &= ~(TASK_FLAG_WAITABLE_CHILD | TASK_FLAG_REAP_IN_PROGRESS); task_copy_name(reap_task, "reaped"); diff --git a/kernel/signal/signal_queue.c b/kernel/signal/signal_queue.c index d4ff16ca..41cdc598 100644 --- a/kernel/signal/signal_queue.c +++ b/kernel/signal/signal_queue.c @@ -332,11 +332,12 @@ int kernel_signal_import_info(struct task *caller, uint64_t pointer, int sig, * @param sig Requested signal; SIGCONT also admits the same-session exception. * @return True when the sender is authorized, false for NULL tasks or denial. * Takes no locks or references and does not queue a signal. + * The CAP_KILL override is scoped to the target's owning user namespace. */ bool kernel_signal_may_send(const struct task *caller, const struct task *target, int sig) { return caller && target && (sched_task_tgid(caller) == sched_task_tgid(target) || - (caller->cap_effective & (1ULL << CAP_KILL)) || + task_ns_capable(caller, target->user_ns, CAP_KILL) || caller->uid == target->uid || caller->uid == target->suid || caller->euid == target->uid || caller->euid == target->suid || (sig == 18 && caller->process_session == target->process_session)); diff --git a/kernel/syscall/device/device.c b/kernel/syscall/device/device.c index 3d5651e1..637d1983 100644 --- a/kernel/syscall/device/device.c +++ b/kernel/syscall/device/device.c @@ -19,12 +19,14 @@ int64_t syscall_device_dispatch(uint64_t number, uint64_t a0, uint64_t a1, return syscall_dispatch_regs_legacy(number, a0, a1, a2, a3, a4, a5); } -/** @brief Authorize and execute one fixed-size driver request on /dev/driverctl. */ +/** @brief Authorize and execute one fixed-size driver request on /dev/driverctl. + * The caller must hold CAP_SYS_MODULE in the initial user namespace. + */ int64_t syscall_driver_control(uint32_t request_number, uint64_t address) { struct task *task = sched_current_task(); if (request_number != RELIEFOS_DRIVER_CONTROL_IOCTL) return -LINUX_ENOTTY; - if (!task || !(task->cap_effective & (1ULL << CAP_SYS_MODULE))) return -LINUX_EPERM; + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_SYS_MODULE))) return -LINUX_EPERM; struct reliefos_driver_control request; int prep=swap_prepare_user_range(task,address,sizeof(request),false); if(prep==SWAP_STORAGE_CONTENDED)return KERNEL_SYSCALL_SWAP_CONTENDED; diff --git a/kernel/syscall/device/legacy_ioctl.c b/kernel/syscall/device/legacy_ioctl.c index 62eeb6b1..1401913e 100644 --- a/kernel/syscall/device/legacy_ioctl.c +++ b/kernel/syscall/device/legacy_ioctl.c @@ -319,6 +319,7 @@ static int64_t fb_user_blit(struct task *task,const struct framebuffer *fb,uint6 * @return Original result, negative errno, or internal blocking/retry status. * @note The caller retains the kernel execution transaction and descriptor pins. * TIOCGPTN returns the master session's instance-local devpts index. + * Privileged device and console controls require capabilities in the initial user namespace. */ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) { @@ -423,7 +424,7 @@ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t } if (a1 == BLKRRPART) { /* Linux requires CAP_SYS_ADMIN for partition-table rescans. */ - if (!task || !(task->cap_effective & (1ULL << CAP_SYS_ADMIN))) { + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) { return -RELIEFOS_EACCES; } if (partition_index >= 0) return -RELIEFOS_EINVAL; @@ -634,19 +635,19 @@ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t } if (a1 == VT_SETMODE) { if (task->controlling_pty_id != id && - !(task->cap_effective & (1ULL << CAP_SYS_TTY_CONFIG))) return -RELIEFOS_EPERM; + !(task_initial_capabilities(task) & (1ULL << CAP_SYS_TTY_CONFIG))) return -RELIEFOS_EPERM; IOCTL_PREPARE(a2, sizeof(struct vt_mode), false, -RELIEFOS_EFAULT); if (!user_range_ok(a2, sizeof(struct vt_mode))) return -RELIEFOS_EFAULT; return pty_vt_set_mode(id, (const struct vt_mode *)(uintptr_t)a2); } if (a1 == VT_RELDISP) { if (task->controlling_pty_id != id && - !(task->cap_effective & (1ULL << CAP_SYS_TTY_CONFIG))) return -RELIEFOS_EPERM; + !(task_initial_capabilities(task) & (1ULL << CAP_SYS_TTY_CONFIG))) return -RELIEFOS_EPERM; return pty_vt_release_display(id, (int)a2); } if (a1 == VT_ACTIVATE || a1 == VT_WAITACTIVE) { if (task->controlling_pty_id != id && - !(task->cap_effective & (1ULL << CAP_SYS_TTY_CONFIG))) return -RELIEFOS_EPERM; + !(task_initial_capabilities(task) & (1ULL << CAP_SYS_TTY_CONFIG))) return -RELIEFOS_EPERM; if (a2 < 1 || a2 > 6) return -RELIEFOS_EINVAL; return a1 == VT_ACTIVATE ? pty_vt_switch((uint32_t)a2) : pty_vt_wait_active((uint32_t)a2); @@ -664,14 +665,14 @@ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t } if (a1 == KDSKBMODE) { if (task->controlling_pty_id != id && - !(task->cap_effective & (1ULL << CAP_SYS_TTY_CONFIG))) return -RELIEFOS_EPERM; + !(task_initial_capabilities(task) & (1ULL << CAP_SYS_TTY_CONFIG))) return -RELIEFOS_EPERM; return pty_vt_set_keyboard_mode(id, (int)a2); } /* KDSETMODE changes who owns the display, so it follows the same rule * as the other VT ioctls: the controlling terminal or the * CAP_SYS_TTY_CONFIG capability. */ if (task->controlling_pty_id != id && - !(task->cap_effective & (1ULL << CAP_SYS_TTY_CONFIG))) + !(task_initial_capabilities(task) & (1ULL << CAP_SYS_TTY_CONFIG))) return -RELIEFOS_EPERM; if (a2 != KD_TEXT && a2 != KD_GRAPHICS) return -RELIEFOS_EINVAL; return pty_vt_set_graphics(id, a2 == KD_GRAPHICS); diff --git a/kernel/syscall/fd/open.c b/kernel/syscall/fd/open.c index f657cc80..6e9e7d95 100644 --- a/kernel/syscall/fd/open.c +++ b/kernel/syscall/fd/open.c @@ -84,6 +84,7 @@ static int open_inode_path(struct task *task,const struct vfs_path *path,uint32_ * open side effects. Namespace handles reject write access and truncation * before DAC. A writable regular OFD holds a writer charge on its * selected attachment until the last reference retires. + * Preserving set-ID bits on truncate requires initial user namespace CAP_FSETID. */ int64_t syscall_open_object(struct vfs_namespace *ns,struct task *task,int32_t dirfd, uint64_t pathname,uint32_t flags,uint32_t mode) @@ -135,7 +136,7 @@ int64_t syscall_open_object(struct vfs_namespace *ns,struct task *task,int32_t d struct reliefos_permissions value; if(!rc)rc=vfs_path_permissions(&found.path,&value,false); if(!rc && (flags&LINUX_O_NOATIME) && task->fsuid!=value.uid && - !(task->cap_effective&(1ULL<type==RELIEFOS_FS_TYPE_SOCKET || (value.mode&LINUX_S_IFMT)==LINUX_S_IFSOCK))rc=-LINUX_ENXIO; } char diagnostic[SCHED_TASK_FILE_PATH_LEN]={0}; diff --git a/kernel/syscall/fs/create.c b/kernel/syscall/fs/create.c index f859ded9..7d66403e 100644 --- a/kernel/syscall/fs/create.c +++ b/kernel/syscall/fs/create.c @@ -9,6 +9,7 @@ * @param out Receives final mode, fsuid and inherited/default group. * @return Zero or negative errno. Applies umask, directory SGID inheritance, * non-directory CAP_FSETID/group rules and symlink0777. No locks span I/O. + * An override of setgid clearing requires initial user namespace CAP_FSETID. */ int syscall_creation_mode(struct task *task,const struct vfs_path *parent,uint32_t type, uint32_t mode,struct reliefos_permissions *out) @@ -24,7 +25,7 @@ int syscall_creation_mode(struct task *task,const struct vfs_path *parent,uint32 out->gid=inherited.gid; if(type==LINUX_S_IFDIR)out->mode|=02000; } - if(type!=LINUX_S_IFDIR && !(task->cap_effective&(1ULL<gid,false))out->mode&=~02000u; return 0; } @@ -41,6 +42,7 @@ int syscall_creation_mode(struct task *task,const struct vfs_path *parent,uint32 * @return Zero or negative errno. Existing entries return EEXIST before parent * write checks. A successful create has no following VFS allocation/open step; * retained operands survive retries without text replay or locks across I/O. + * Creating character and block devices requires initial user namespace CAP_MKNOD. */ static int64_t syscall_create_member(struct vfs_namespace *ns,struct task *task,int32_t dirfd, uint64_t pathname,uint32_t type,uint32_t mode,const char *target,uint32_t device) @@ -65,7 +67,7 @@ static int64_t syscall_create_member(struct vfs_namespace *ns,struct task *task, struct reliefos_permissions value; if(!rc)rc=syscall_creation_mode(task,&parent.path,type,mode,&value); if(!rc && special && !(type==LINUX_S_IFCHR && !device) && - !(task->cap_effective&(1ULL<type!=RELIEFOS_FS_TYPE_DIR)rc=-RELIEFOS_ENOTDIR; if(!rc)rc=fs_permissions_check_path(task,&found.path,FS_ACCESS_EXEC,false); - if(!rc && number==LINUX_SYS_CHROOT && !(task->cap_effective&(1ULL<root : &paths->cwd; diff --git a/kernel/syscall/fs/filesystem.c b/kernel/syscall/fs/filesystem.c index 2286c5cb..3dcd07cf 100644 --- a/kernel/syscall/fs/filesystem.c +++ b/kernel/syscall/fs/filesystem.c @@ -68,6 +68,7 @@ int64_t syscall_openat2(uint64_t dirfd, uint64_t pathname, * across metadata waits, including a directory renamed while the call waits. * No diagnostic name replay or graph/module lock spans provider I/O; times * are rounded to the existing backend's whole-second timestamp resolution. + * CAP_FOWNER is checked in the initial user namespace. */ int64_t syscall_update_path_times(struct task *task, int32_t dirfd, uint64_t path_ptr, const struct linux_timespec times[2], uint32_t flags, @@ -90,7 +91,7 @@ int64_t syscall_update_path_times(struct task *task, int32_t dirfd, uint64_t pat if (ret < 0) return ret; struct reliefos_permissions perms; ret = vfs_path_permissions(&found.path,&perms,false); - if (!ret && task && task->fsuid != perms.uid && !(task->cap_effective&(1ULL<fsuid != perms.uid && !(task_initial_capabilities(task)&(1ULL<cap_effective & (1ULL << CAP_SETGID))) return -RELIEFOS_EPERM; + if (!(task_initial_capabilities(task) & (1ULL << CAP_SETGID))) return -RELIEFOS_EPERM; if (size < 0 || size > 65536) return -RELIEFOS_EINVAL; if (size && !user_range_ok(a1, (uint64_t)size * 4)) return -RELIEFOS_EFAULT; return task_groups_set(task, (const uint32_t *)(uintptr_t)a1, (uint32_t)size); diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 346a3275..6989b9ab 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -217,11 +217,12 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * * @return Zero or negative Linux errno/internal EAGAIN. Text and lookup state * remain scope-owned across waits; temporary unscoped allocations are always * freed. The resulting graph owns backend lifetime, without target prefixes. + * The mounted graph is owned by the initial user namespace. */ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_t number, uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4) { - if(!task || !(task->cap_effective&(1ULL<cap_effective&(1ULL<fsuid==directory.uid)return rc; @@ -100,6 +101,7 @@ int64_t syscall_rename_object(struct vfs_namespace *ns,struct task *task,int32_t * Linux CAP_DAC_READ_SEARCH capability; ordinary sources do not need read DAC. * Directories and zero-link inodes cannot be relinked. No name replay, creation * metadata duplication, post-publication allocation or lock across I/O occurs. + * Linking an FD via AT_EMPTY_PATH requires initial user namespace CAP_DAC_READ_SEARCH. */ int64_t syscall_link_object(struct vfs_namespace *ns,struct task *task,int32_t oldfd,uint64_t oldname, int32_t newfd,uint64_t newname,uint32_t flags) @@ -108,7 +110,7 @@ int64_t syscall_link_object(struct vfs_namespace *ns,struct task *task,int32_t o if(!task)return -RELIEFOS_ESRCH; struct task_user_text text={0}; int rc=task_lookup_user_text(task,oldname,VFS_PATH_MAX,false,&text);if(rc)return rc; - if(!text.text[0] && (flags&LINUX_AT_EMPTY_PATH) && !(task->cap_effective&(1ULL<XATTR_BUFFER_MAX ? XATTR_BUFFER_MAX : (uint32_t)size; uint32_t length=0; void *buffer=NULL; - bool privileged=(task->cap_effective&(1ull<cap_effective & ((1ULL << CAP_SYS_RESOURCE) | (1ULL << CAP_SYS_ADMIN))); + return task && (task_initial_capabilities(task) & ((1ULL << CAP_SYS_RESOURCE) | (1ULL << CAP_SYS_ADMIN))); } /** @brief Allocate a stable pipe object, ring and per-UID accounting entry. diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 8284e8cb..fa7e8efe 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -1699,6 +1699,7 @@ static int unix_message_vectors(struct msghdr *message, uint64_t *total) * Receives owned rights. @param credentials Receives supplied credentials. * @param explicit_credentials Reports a credentials record. @param kernel_control * Selects an already owned kernel snapshot. @return Zero or a negative errno. + * Overriding global sender IDs or the PID requires initial user namespace capabilities. */ static int unix_message_rights_common(struct task *task, const struct msghdr *message, struct unix_rights **out, struct ucred *credentials, @@ -1732,7 +1733,7 @@ static int unix_message_rights_common(struct task *task, const struct msghdr *me } /* Linux v6.12 net/core/scm.c: each forged field requires its * own effective capability, including for an euid-zero sender. */ - uint64_t capabilities = task->cap_effective; + uint64_t capabilities = task_initial_capabilities(task); if ((credentials->pid != (int32_t)sched_task_tgid(task) && !(capabilities & (1ULL << CAP_SYS_ADMIN))) || (credentials->uid != task->uid && credentials->uid != task->euid && diff --git a/kernel/syscall/ipc/sysv_msg.c b/kernel/syscall/ipc/sysv_msg.c index 3a492ffe..496f9530 100644 --- a/kernel/syscall/ipc/sysv_msg.c +++ b/kernel/syscall/ipc/sysv_msg.c @@ -96,7 +96,9 @@ static bool msg_in_group(const struct task *task, uint32_t group) return false; } -/** @brief Check ipcperms owner/creator, group and CAP_IPC_OWNER access. */ +/** @brief Check ipcperms owner/creator, group and CAP_IPC_OWNER access. + * The CAP_IPC_OWNER override is checked in the initial user namespace. + */ static bool msg_permitted(struct task *task, struct sysv_msg_queue *queue, uint32_t requested) { struct linux_ipc64_perm *p = &queue->stat.msg_perm; @@ -104,7 +106,7 @@ static bool msg_permitted(struct task *task, struct sysv_msg_queue *queue, uint3 requested = (requested | (requested >> 3) | (requested >> 6)) & 7; if (task->euid == p->uid || task->euid == p->cuid) granted >>= 6; else if (msg_in_group(task, p->gid) || msg_in_group(task, p->cgid)) granted >>= 3; - return !(requested & ~granted) || (task->cap_effective & (1ULL << CAP_IPC_OWNER)); + return !(requested & ~granted) || (task_initial_capabilities(task) & (1ULL << CAP_IPC_OWNER)); } /** @brief Resolve an IPC ID with optional sequence validation for STAT index commands. */ @@ -443,7 +445,9 @@ static void msg_remove(struct sysv_msg_queue *q) msg_put_queue(q); } -/** @brief Implement native msgctl layouts, permissions, configuration and live accounting. */ +/** @brief Implement native msgctl layouts, permissions, configuration and live accounting. + * The global queue's owner and capacity overrides use initial user namespace capabilities. + */ static int64_t msg_control(struct task *task, int32_t id, int32_t command, uint64_t buffer) { if (id < 0 || command < 0) return -LINUX_EINVAL; @@ -484,11 +488,11 @@ static int64_t msg_control(struct task *task, int32_t id, int32_t command, uint6 } struct linux_ipc64_perm *p = &q->stat.msg_perm; if (task->euid != p->uid && task->euid != p->cuid && - !(task->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; + !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; if (command == LINUX_IPC_RMID) { msg_remove(q); return 0; } /* msgctl_down takes int even though the native input field is unsigned long. */ int32_t bytes = (int32_t)input.msg_qbytes; - if ((uint32_t)bytes > LINUX_MSGMNB && !(task->cap_effective & (1ULL << CAP_SYS_RESOURCE))) return -LINUX_EPERM; + if ((uint32_t)bytes > LINUX_MSGMNB && !(task_initial_capabilities(task) & (1ULL << CAP_SYS_RESOURCE))) return -LINUX_EPERM; if (input.msg_perm.uid == UINT32_MAX || input.msg_perm.gid == UINT32_MAX) return -LINUX_EINVAL; p->uid = input.msg_perm.uid; p->gid = input.msg_perm.gid; p->mode = input.msg_perm.mode & 0777; q->stat.msg_qbytes = (uint64_t)(int64_t)bytes; q->stat.msg_ctime = msg_now(); diff --git a/kernel/syscall/ipc/sysv_sem.c b/kernel/syscall/ipc/sysv_sem.c index a5b094f9..fd9c32c0 100644 --- a/kernel/syscall/ipc/sysv_sem.c +++ b/kernel/syscall/ipc/sysv_sem.c @@ -112,7 +112,9 @@ static int sem_prepare_output(struct task *task, uint64_t pointer, uint64_t leng } #endif -/** @brief Apply ipcperms using effective UID, fsgid and supplementary groups. */ +/** @brief Apply ipcperms using effective UID, fsgid and supplementary groups. + * The CAP_IPC_OWNER override is checked in the initial user namespace. + */ static bool sem_permitted(const struct task *task, const struct sysv_sem_array *a, uint32_t flags) { const struct linux_ipc64_perm *p = &a->stat.sem_perm; @@ -122,7 +124,7 @@ static bool sem_permitted(const struct task *task, const struct sysv_sem_array * if (task->groups->ids[i] == p->gid || task->groups->ids[i] == p->cgid) group = true; if (task->euid == p->uid || task->euid == p->cuid) mode >>= 6; else if (group) mode >>= 3; - return !(requested & ~mode) || (task->cap_effective & (1ULL << CAP_IPC_OWNER)); + return !(requested & ~mode) || (task_initial_capabilities(task) & (1ULL << CAP_IPC_OWNER)); } /** @brief Look up a native ID, optionally ignoring its generation for SEM_STAT. */ @@ -598,7 +600,9 @@ static int sem_all(struct task *task, struct sysv_sem_array *a, uint64_t pointer return error; } -/** @brief Implement native semctl command, width, permission and copy ordering. */ +/** @brief Implement native semctl command, width, permission and copy ordering. + * Administrative changes to the shared registry require initial user namespace CAP_SYS_ADMIN. + */ static int64_t sem_control(struct task *task, int32_t id, int32_t index, int32_t cmd, uint64_t arg) { if (id < 0) return -LINUX_EINVAL; @@ -633,7 +637,7 @@ static int64_t sem_control(struct task *task, int32_t id, int32_t index, int32_t struct linux_ipc64_perm *p = &a->stat.sem_perm; if (owner) { if (task->euid != p->uid && task->euid != p->cuid && - !(task->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; + !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; if (cmd == LINUX_IPC_RMID) { sem_remove(a); return 0; } if (input.sem_perm.uid == UINT32_MAX || input.sem_perm.gid == UINT32_MAX) return -LINUX_EINVAL; p->uid = input.sem_perm.uid; p->gid = input.sem_perm.gid; p->mode = input.sem_perm.mode & 0777; diff --git a/kernel/syscall/ipc/sysv_shm.c b/kernel/syscall/ipc/sysv_shm.c index f6f6ce11..98d2a5a7 100644 --- a/kernel/syscall/ipc/sysv_shm.c +++ b/kernel/syscall/ipc/sysv_shm.c @@ -74,6 +74,7 @@ static bool sysv_shm_group(const struct task *task, uint32_t gid) * @param task Caller credentials. @param segment Live registry entry. * @param requested Linux permission bits, collapsed into read/write/execute. * @return True when DAC or the effective capability permits access. + * The CAP_IPC_OWNER override is checked in the initial user namespace. */ static bool sysv_shm_access(const struct task *task, const struct sysv_shm_segment *segment, uint32_t requested) @@ -83,16 +84,17 @@ static bool sysv_shm_access(const struct task *task, requested = (requested | (requested >> 3) | (requested >> 6)) & 7; if (task->euid == perm->uid || task->euid == perm->cuid) mode >>= 6; else if (sysv_shm_group(task, perm->gid) || sysv_shm_group(task, perm->cgid)) mode >>= 3; - return !(requested & ~mode) || (task->cap_effective & (1ULL << CAP_IPC_OWNER)); + return !(requested & ~mode) || (task_initial_capabilities(task) & (1ULL << CAP_IPC_OWNER)); } /** @brief Check IPC_SET/RMID ownership. * @param task Caller credentials. @param segment Live registry entry. * @return True for its owner, creator, or CAP_SYS_ADMIN. + * The shared registry's CAP_SYS_ADMIN override is checked in the initial user namespace. */ static bool sysv_shm_owner(const struct task *task, const struct sysv_shm_segment *segment) { return task->euid == segment->stat.shm_perm.uid || task->euid == segment->stat.shm_perm.cuid || - (task->cap_effective & (1ULL << CAP_SYS_ADMIN)); + (task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN)); } /** @brief Resolve a generation ID or SHM_STAT slot. * @param id Nonnegative native ID or slot. @param index Select a slot lookup. @@ -346,10 +348,11 @@ static int64_t sysv_shm_detach(struct task *task, uint64_t address) * @param task Caller credentials and shared resource limits. * @param s Live segment. @param lock True for SHM_LOCK, false for SHM_UNLOCK. * @return Zero or negative errno, without changing a denied segment's mode. + * The memlock override is checked in the initial user namespace. */ static int sysv_shm_lock(struct task *task, struct sysv_shm_segment *s, bool lock) { - bool privileged = task->cap_effective & (1ULL << CAP_IPC_LOCK); + bool privileged = task_initial_capabilities(task) & (1ULL << CAP_IPC_LOCK); if (!privileged && task->euid != s->stat.shm_perm.uid && task->euid != s->stat.shm_perm.cuid) return -LINUX_EPERM; uint64_t limit = sched_task_limits(task)->memlock.rlim_cur; diff --git a/kernel/syscall/memory/swap.c b/kernel/syscall/memory/swap.c index 44003006..ca18bfe3 100644 --- a/kernel/syscall/memory/swap.c +++ b/kernel/syscall/memory/swap.c @@ -20,6 +20,7 @@ int swap_deactivate_user(uint64_t path); * @param user_path User pathname, validated after flags and capability. * @param flags Raw ABI register; Linux defines the argument as a 32-bit int. * @return Zero or terminal negative errno; disabled builds return -ENOSYS. + * The caller must hold CAP_SYS_ADMIN in the initial user namespace. */ int64_t syscall_mm_swapon(uint64_t user_path,uint64_t flags) { @@ -27,7 +28,7 @@ int64_t syscall_mm_swapon(uint64_t user_path,uint64_t flags) uint32_t value=(uint32_t)flags; if (value & ~0x7ffffu) return -EINVAL; struct task *task=sched_current_task(); - if (!task || !(task->cap_effective&(1ULL<cap_effective&(1ULL<cap_effective & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; + if (new_namespace && !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; return sched_task_fs_unshare(task, new_namespace); } diff --git a/kernel/syscall/process/process.c b/kernel/syscall/process/process.c index fc3f854c..1bc25912 100644 --- a/kernel/syscall/process/process.c +++ b/kernel/syscall/process/process.c @@ -66,6 +66,8 @@ static int process_prepare_user(struct task *task, uint64_t address, uint64_t si * @param a0 First syscall argument. @param a1 Second syscall argument. * @param a2 Third syscall argument. @param a3 Fourth syscall argument. * @return Zero on success, or a negative Linux errno or retry sentinel. + * Cross-process overrides use the target's owning user namespace. + * Increasing a hard limit requires CAP_SYS_RESOURCE in the initial user namespace. */ static int64_t process_resource_limit(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3) @@ -110,7 +112,7 @@ static int64_t process_resource_limit(uint64_t number, uint64_t a0, uint64_t a1, #endif target=combined && (uint32_t)a0 ? sched_find((uint32_t)a0) : caller; if (!target) return -LINUX_ESRCH; - if (combined && caller != target && !(caller->cap_effective & (1ULL << CAP_SYS_RESOURCE)) && + if (combined && caller != target && !task_ns_capable(caller, target->user_ns, CAP_SYS_RESOURCE) && (caller->uid != target->uid || caller->uid != target->euid || caller->uid != target->suid || caller->gid != target->gid || caller->gid != target->egid || caller->gid != target->sgid)) return -LINUX_EPERM; @@ -134,7 +136,7 @@ static int64_t process_resource_limit(uint64_t number, uint64_t a0, uint64_t a1, else if (resource == LINUX_RLIMIT_RTPRIO) stored = &limits->rtprio; else return -LINUX_EINVAL; if (setting && next.rlim_max > stored->rlim_max && - !(caller->cap_effective & (1ULL << CAP_SYS_RESOURCE))) return -LINUX_EPERM; + !(task_initial_capabilities(caller) & (1ULL << CAP_SYS_RESOURCE))) return -LINUX_EPERM; if ((old_pointer || number == LINUX_SYS_GETRLIMIT) && process_prepare_user(caller, old_pointer, sizeof(previous), true) == KERNEL_SYSCALL_SWAP_CONTENDED) { @@ -474,6 +476,7 @@ int64_t syscall_process_prctl(uint64_t option, uint64_t arg2, uint64_t arg3, } } +/** @copydoc syscall_process_control */ int64_t syscall_process_control(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3) { @@ -903,7 +906,7 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, struct task *task = sched_current_task(); char captured[RELIEFOS_UTSNAME_LEN] = {0}; int32_t length = (int32_t)a1; /* native syscall takes int, not size_t */ - if (!task || !(task->cap_effective & (1ULL << CAP_SYS_ADMIN))) return -RELIEFOS_EPERM; + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -RELIEFOS_EPERM; if (length < 0 || length >= (int32_t)RELIEFOS_UTSNAME_LEN) return -RELIEFOS_EINVAL; if (length) { int prep=process_prepare_user(task,a0,(uint32_t)length,false);if(prep)return prep; } if (length && !user_range_ok(a0, (uint32_t)length)) return -RELIEFOS_EFAULT; @@ -977,7 +980,7 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, } if (number == LINUX_SYS_SETTIMEOFDAY) { struct task *task = sched_current_task(); - if (!task || !(task->cap_effective & (1ULL << CAP_SYS_TIME))) return -RELIEFOS_EPERM; + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_SYS_TIME))) return -RELIEFOS_EPERM; if (a0) { int prep=process_prepare_user(task,a0,16,false);if(prep)return prep; } if (!a0 || !user_range_ok(a0, 16u)) return -RELIEFOS_EFAULT; int64_t sec = ((const int64_t *)(uintptr_t)a0)[0], usec = ((const int64_t *)(uintptr_t)a0)[1]; @@ -989,7 +992,7 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, if (number == LINUX_SYS_CLOCK_SETTIME) { struct task *task = sched_current_task(); struct linux_timespec value; - if (!task || !(task->cap_effective & (1ULL << CAP_SYS_TIME))) return -RELIEFOS_EPERM; + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_SYS_TIME))) return -RELIEFOS_EPERM; if ((int32_t)a0 != LINUX_CLOCK_REALTIME) return -RELIEFOS_EINVAL; if (a1) { int prep=process_prepare_user(task,a1,sizeof(value),false);if(prep)return prep; } if (!a1 || !user_range_ok(a1, sizeof(value))) return -RELIEFOS_EFAULT; @@ -1101,7 +1104,7 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, } if (number == LINUX_SYS_REBOOT) { struct task *task = sched_current_task(); - if (!task || !(task->cap_effective & (1ULL << CAP_SYS_BOOT))) return -RELIEFOS_EPERM; + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_SYS_BOOT))) return -RELIEFOS_EPERM; /* Linux reboot(int magic1, int magic2, unsigned int cmd, void *arg). */ uint32_t magic1 = (uint32_t)a0; uint32_t magic2 = (uint32_t)a1; @@ -1158,7 +1161,7 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, (number == LINUX_SYS_TGKILL && sched_task_tgid(target) != (uint32_t)a0)) return -LINUX_ESRCH; if (!sender || (sched_task_tgid(sender) != sched_task_tgid(target) && - !(sender->cap_effective & (1ULL << CAP_KILL)) && sender->uid != target->uid && + !task_ns_capable(sender, target->user_ns, CAP_KILL) && sender->uid != target->uid && sender->uid != target->suid && sender->euid != target->uid && sender->euid != target->suid && !(sig == 18 && sender->process_session == target->process_session))) return -RELIEFOS_EPERM; @@ -1187,7 +1190,7 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, if (!target || target->kind != TASK_KIND_USER || sched_task_tgid(target) != (uint32_t)requested_pid) return -LINUX_ESRCH; if (sched_task_tgid(current) != sched_task_tgid(target) && - !(current->cap_effective & (1ULL << CAP_KILL)) && + !task_ns_capable(current, target->user_ns, CAP_KILL) && current->uid != target->uid && current->uid != target->suid && current->euid != target->uid && current->euid != target->suid && !(signal_number == 18 && current->process_session == target->process_session)) return -RELIEFOS_EPERM; @@ -1228,7 +1231,7 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, * a renice child to lower its same-owner parent's priority; PID * inequality alone is not a privilege boundary. RLIMIT_NICE is * currently unsupported, so raising requires CAP_SYS_NICE. */ - bool privileged = (current->cap_effective & (1ULL << CAP_SYS_NICE)) != 0; + bool privileged = task_ns_capable(current, selected->user_ns, CAP_SYS_NICE); if (!privileged && current->euid != selected->uid && current->euid != selected->euid) return -LINUX_EPERM; if (!privileged && requested < selected->priority) return -LINUX_EACCES; diff --git a/kernel/syscall/process/process_vm.c b/kernel/syscall/process/process_vm.c index 287461bd..b1737517 100644 --- a/kernel/syscall/process/process_vm.c +++ b/kernel/syscall/process/process_vm.c @@ -337,16 +337,21 @@ int64_t syscall_process_vm(int32_t pid,uint64_t local_pointer,uint64_t local_cou } #endif -/** @brief Apply mm_access(ATTACH_REALCREDS) and commoncap for the current user namespace. */ +/** @brief Apply ATTACH_REALCREDS and commoncap in the target's owning user namespace. + * @param caller Execution-owned source credentials. @param target Stable target task. + * @return True for shared MM/thread-group access, target-scoped PTRACE authority, + * or matching IDs and a permitted-set subset within the same user namespace. + */ static bool process_vm_may_access(struct task *caller, struct task *target) { if (sched_task_mm(caller) == sched_task_mm(target) || sched_task_tgid(caller) == sched_task_tgid(target)) return true; - bool privileged = (caller->cap_effective & (1ULL << CAP_SYS_PTRACE)) != 0; + bool privileged = task_ns_capable(caller, target->user_ns, CAP_SYS_PTRACE); if (!privileged && (caller->uid != target->uid || caller->uid != target->euid || caller->uid != target->suid || caller->gid != target->gid || caller->gid != target->egid || caller->gid != target->sgid || sched_task_mm(target)->nondumpable)) return false; - return privileged || !(target->cap_permitted & ~caller->cap_permitted); + return privileged || (caller->user_ns == target->user_ns && + !(target->cap_permitted & ~caller->cap_permitted)); } /** @brief Resolve a page in either address space; remote GUP cannot access MMIO or grow stacks. */ diff --git a/kernel/syscall/process/setns.c b/kernel/syscall/process/setns.c index c94d0644..886a419b 100644 --- a/kernel/syscall/process/setns.c +++ b/kernel/syscall/process/setns.c @@ -10,6 +10,7 @@ * @param fd Descriptor number (not O_PATH or a pidfd). * @param type Zero or CLONE_NEWNS. * @return Zero or a negative descriptor, capability or graph error. + * Mount graph entry requires CAP_SYS_ADMIN and CAP_SYS_CHROOT in the initial user namespace. */ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) { @@ -21,7 +22,7 @@ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) struct vfs_namespace *ns = nsfs_path_namespace(&file->path_ref); if (!ns) return -LINUX_EINVAL; const uint64_t required = (1ULL << CAP_SYS_ADMIN) | (1ULL << CAP_SYS_CHROOT); - /* Only the initial user namespace exists, shared by caller and target. */ - if ((task->cap_effective & required) != required) return -LINUX_EPERM; + /* Existing mount graphs are owned by the initial user namespace. */ + if ((task_initial_capabilities(task) & required) != required) return -LINUX_EPERM; return sched_task_fs_join_namespace(task, ns); } diff --git a/kernel/syscall/system/modules.c b/kernel/syscall/system/modules.c index bf48b232..6d3988a3 100644 --- a/kernel/syscall/system/modules.c +++ b/kernel/syscall/system/modules.c @@ -188,6 +188,7 @@ static int module_copy_arguments(struct task *task,uint64_t address,char **out,v * @param flags Linux finit_module flags, consumed as unsigned 32 bits. * @return Zero or Linux errno. Task/execution context, no usercopy, I/O or * reference transfer. The caller retains the transaction through OFD pinning. + * The caller must hold CAP_SYS_MODULE in the initial user namespace. */ int syscall_module_file_prepare(uint64_t fd,uint64_t flags) { @@ -195,7 +196,7 @@ int syscall_module_file_prepare(uint64_t fd,uint64_t flags) (void)fd;(void)flags;return -ENOSYS; #else struct task *task=sched_current_task(); - if(!task || !(task->cap_effective&(1ULL<cap_effective&(1ULL<cap_effective & (1ULL << CAP_SYS_TIME))); + int result = time_adjust(&value, task && (task_initial_capabilities(task) & (1ULL << CAP_SYS_TIME))); if (result < 0) return result; /* Like Linux, mutation precedes the output copy; a late EFAULT does not undo it. */ if (!user_range_writable(address, sizeof(value))) return -LINUX_EFAULT; diff --git a/mm/reclaim/oom.c b/mm/reclaim/oom.c index 3340ba51..4a6b5fd0 100644 --- a/mm/reclaim/oom.c +++ b/mm/reclaim/oom.c @@ -146,6 +146,7 @@ int oom_adj_get(struct task *task) * @param caller Capability-bearing task; both tasks remain execution-pinned. * @return Zero or -EINVAL/-ESRCH/-EDEADLK/-EACCES. Sole outer writer required; * no task reference transfers and no memory is allocated. + * Lowering the minimum requires initial user namespace CAP_SYS_RESOURCE. */ int oom_adj_set(struct task *task, int value, struct task *caller) { @@ -153,7 +154,7 @@ int oom_adj_set(struct task *task, int value, struct task *caller) if (!task || !task->pid || task->kind != TASK_KIND_USER || !caller) return -ESRCH; if (!kernel_execution_is_outermost()) return -EDEADLK; int minimum; sched_oom_policy_get(task, NULL, &minimum); - bool privileged = (caller->cap_effective & (1ULL << CAP_SYS_RESOURCE)) != 0; + bool privileged = (task_initial_capabilities(caller) & (1ULL << CAP_SYS_RESOURCE)) != 0; if (value < minimum && !privileged) return -EACCES; uint32_t group = sched_task_tgid(task); uint64_t cr3 = sched_task_as(task)->cr3; diff --git a/mm/user/locked.c b/mm/user/locked.c index 00b3304d..96b12d03 100644 --- a/mm/user/locked.c +++ b/mm/user/locked.c @@ -169,12 +169,12 @@ uint64_t mm_locked_bytes(struct task *task) return total; } -/** @brief Admit Linux lock operations by effective capability and memlock limit. +/** @brief Admit Linux lock operations by initial-scope capability and memlock limit. * @param task Borrowed current user task. @return True when locking is permitted. */ static bool mm_can_lock(const struct task *task) { - return task && ((task->cap_effective & (1ULL << CAP_IPC_LOCK)) || + return task && ((task_initial_capabilities(task) & (1ULL << CAP_IPC_LOCK)) || sched_task_limits(task)->memlock.rlim_cur != 0); } @@ -257,11 +257,12 @@ static int mm_lock_prepare_slices(struct task *task, uint64_t start, uint64_t en * @param task Execution-owned user task. @param low Faulting new low page. * @param old_low Previously admitted low page. @param mode Future policy bits. * @return Zero or negative ENOMEM; new metadata and pages roll back on failure. + * A memlock quota override requires initial user namespace CAP_IPC_LOCK. */ int mm_lock_future_stack(struct task *task, uint64_t low, uint64_t old_low, uint32_t mode) { uint64_t length = old_low - low; - if (!(task->cap_effective & (1ULL << CAP_IPC_LOCK))) { + if (!(task_initial_capabilities(task) & (1ULL << CAP_IPC_LOCK))) { uint64_t limit = sched_task_limits(task)->memlock.rlim_cur & ~(PAGE_SIZE - 1ULL); uint64_t held = mm_locked_bytes(task); if (held > limit || length > limit - held) return -RELIEFOS_ENOMEM; @@ -294,6 +295,7 @@ int mm_lock_future_stack(struct task *task, uint64_t low, uint64_t old_low, uint * @param populate Perform checked eager population for an ordinary mlock. * @return Zero or a negative Linux errno. Capacity and quota are checked before * VMA mutation; checked eager population precedes policy publication. + * A memlock quota override requires initial user namespace CAP_IPC_LOCK. */ static int mm_lock_range(struct task *task, uint64_t addr, uint64_t len, bool lock, bool onfault, bool check_quota, bool populate) @@ -353,7 +355,7 @@ static int mm_lock_range(struct task *task, uint64_t addr, uint64_t len, if (piece_end < vma->end) ++splits; cursor = piece_end; } - if (lock && check_quota && !(task->cap_effective & (1ULL << CAP_IPC_LOCK))) { + if (lock && check_quota && !(task_initial_capabilities(task) & (1ULL << CAP_IPC_LOCK))) { uint64_t limit = sched_task_limits(task)->memlock.rlim_cur & ~(PAGE_SIZE - 1ULL); if (current > limit || length - already > limit - current) return -RELIEFOS_ENOMEM; } @@ -484,6 +486,7 @@ int64_t syscall_mm_munlock(uint64_t addr, uint64_t len) /** @brief Set current and future lock policy for the current task. * @param flags Linux mlockall mode. @return Zero or a negative errno. + * A memlock quota override requires initial user namespace CAP_IPC_LOCK. */ int64_t syscall_mm_mlockall(uint64_t flags) { @@ -492,7 +495,7 @@ int64_t syscall_mm_mlockall(uint64_t flags) if ((mode & ~(LINUX_MCL_CURRENT | LINUX_MCL_FUTURE | LINUX_MCL_ONFAULT)) || !(mode & (LINUX_MCL_CURRENT | LINUX_MCL_FUTURE))) return -RELIEFOS_EINVAL; if (!mm_can_lock(task)) return -RELIEFOS_EPERM; - if ((mode & LINUX_MCL_CURRENT) && !(task->cap_effective & (1ULL << CAP_IPC_LOCK)) && + if ((mode & LINUX_MCL_CURRENT) && !(task_initial_capabilities(task) & (1ULL << CAP_IPC_LOCK)) && task_vma_total_bytes(task) > (sched_task_limits(task)->memlock.rlim_cur & ~(PAGE_SIZE - 1ULL))) return -RELIEFOS_ENOMEM; if (mm_context_ensure(sched_task_as(task)) < 0) return -RELIEFOS_ENOMEM; diff --git a/mm/user/mapping.c b/mm/user/mapping.c index 71c56cfd..1d16f7a1 100644 --- a/mm/user/mapping.c +++ b/mm/user/mapping.c @@ -202,13 +202,14 @@ static uint64_t task_find_file_mmap_region(struct task *task, uint64_t len) * @param task Execution-owned user MM. @param start First page. @param end Exclusive end. * @param vma_flags Mapping flags updated with lock policy on success. * @return Zero or negative EAGAIN before any existing mapping is removed. + * A memlock quota override requires initial user namespace CAP_IPC_LOCK. */ static int task_future_lock_mapping(struct task *task, uint64_t start, uint64_t end, uint32_t *vma_flags) { uint32_t mode = mm_lock_flags(sched_task_as(task)); if (!(mode & LINUX_MCL_FUTURE)) return 0; - if (!(task->cap_effective & (1ULL << CAP_IPC_LOCK))) { + if (!(task_initial_capabilities(task) & (1ULL << CAP_IPC_LOCK))) { uint64_t held = mm_locked_bytes(task), replaced = 0; uint64_t limit = sched_task_limits(task)->memlock.rlim_cur & ~(PAGE_SIZE - 1ULL); for (uint32_t i = 0; i < sched_task_vma_capacity(task); ++i) { @@ -644,11 +645,12 @@ int64_t syscall_mm_brk(uint64_t requested) * @param task Execution-owned MM. @param old_len Locked bytes removed at source. * @param new_len Locked bytes installed at destination. @param target Optional fixed target. * @return True when capability or memlock quota admits the final intervals. + * A memlock quota override requires initial user namespace CAP_IPC_LOCK. */ static bool task_remap_lock_allowed(struct task *task, uint64_t old_len, uint64_t new_len, uint64_t target) { - if (task->cap_effective & (1ULL << CAP_IPC_LOCK)) return true; + if (task_initial_capabilities(task) & (1ULL << CAP_IPC_LOCK)) return true; uint64_t held = mm_locked_bytes(task), replaced = 0; if (target) { uint64_t target_end = target + new_len; diff --git a/net/interface/config.c b/net/interface/config.c index eb1966db..2e85e4b4 100644 --- a/net/interface/config.c +++ b/net/interface/config.c @@ -454,6 +454,7 @@ void net_device_info(uint32_t *flags, uint64_t *mac_value, uint32_t *local_ip) * @param address User pointer to a native in6_ifreq or in6_rtmsg. * @return Zero or negative errno. The current task must hold CAP_NET_ADMIN; * imported bytes are owned locally and no user reference crosses a wait. + * The shared network namespace is owned by the initial user namespace. */ int net_ipv6_interface_ioctl(uint32_t request, uint64_t address) { @@ -461,7 +462,7 @@ int net_ipv6_interface_ioctl(uint32_t request, uint64_t address) if (request != SIOCSIFADDR && request != SIOCDIFADDR && request != SIOCADDRT && request != SIOCDELRT) return net_interface_ioctl(request, address); - if (!task || !(task->cap_effective & (1ULL << CAP_NET_ADMIN))) return -LINUX_EPERM; + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_NET_ADMIN))) return -LINUX_EPERM; if (request == SIOCSIFADDR || request == SIOCDIFADDR) { struct in6_ifreq input; int rc = socket_user_import(task, address, &input, sizeof(input)); diff --git a/net/interface/ioctl.c b/net/interface/ioctl.c index fbeb48b8..5bd0f0f8 100644 --- a/net/interface/ioctl.c +++ b/net/interface/ioctl.c @@ -141,13 +141,14 @@ int net_interface_configure_ipv4(uint32_t index, uint32_t address, return 0; } +/** @copydoc net_interface_ioctl */ int net_interface_ioctl(uint32_t request, uint64_t address) { bool change = request == SIOCSIFFLAGS || request == SIOCSIFADDR || request == SIOCSIFNETMASK || request == SIOCSIFBRDADDR || request == SIOCSIFMTU || request == SIOCADDRT || request == SIOCDELRT; struct task *task = sched_current_task(); - if (change && (!task || !(task->cap_effective & (1ULL << CAP_NET_ADMIN)))) + if (change && (!task || !(task_initial_capabilities(task) & (1ULL << CAP_NET_ADMIN)))) return -LINUX_EPERM; if (request == SIOCADDRT || request == SIOCDELRT) return interface_route(task, request, address); diff --git a/net/interface/socket.c b/net/interface/socket.c index 44dc427c..4cc50c64 100644 --- a/net/interface/socket.c +++ b/net/interface/socket.c @@ -10,8 +10,10 @@ * @param set Update when true, query otherwise. @param address User name buffer. * @param length Input byte count for updates, user socklen_t pointer for queries. * @param index Current bound device; changed only after a successful update. - * @return Zero or negative errno. Execution-owned, user memory copied with the - * socket helpers, CAP_NET_RAW required when changing an existing binding. No provider pointer escapes. */ + * @return Zero or negative errno. User memory is copied with the socket helpers + * under execution ownership. Updating a bound socket requires CAP_NET_RAW in + * the initial user namespace. No provider pointer escapes. + */ int net_interface_device_option(bool set, uint64_t address, uint64_t length, uint32_t *index) { if (!index) return -LINUX_EINVAL; @@ -28,7 +30,7 @@ int net_interface_device_option(bool set, uint64_t address, uint64_t length, uin } uint32_t selected = name[0] ? net_interface_index(name) : 0; if (name[0] && !selected) return -LINUX_ENODEV; - if (*index && !(task->cap_effective & (1ULL << CAP_NET_RAW))) return -LINUX_EPERM; + if (*index && !(task_initial_capabilities(task) & (1ULL << CAP_NET_RAW))) return -LINUX_EPERM; *index = selected; return 0; } diff --git a/net/internal.h b/net/internal.h index 6a3ec5bc..deefe18a 100644 --- a/net/internal.h +++ b/net/internal.h @@ -1102,6 +1102,7 @@ void net_device_info(uint32_t *flags, uint64_t *mac_value, uint32_t *local_ip); /** @brief Apply/query eth0 through the Linux native interface ioctl ABI. * Only the real Ethernet interface and the supported default route are exposed. * Unsupported routing/features return an error rather than retaining inert state. + * Changes require initial user namespace CAP_NET_ADMIN. */ int net_interface_ioctl(uint32_t request, uint64_t address); diff --git a/net/socket/control.c b/net/socket/control.c index 363e76ed..8655649f 100644 --- a/net/socket/control.c +++ b/net/socket/control.c @@ -15,7 +15,9 @@ /** @brief Dispatch network socket ioctls against the pinned open description. * @param file Borrowed socket OFD under execution ownership. * @param request Native ioctl number. @param address User argument address. - * @return Zero, negative errno, or a user-memory prerequisite wait marker. */ + * @return Zero, negative errno, or a user-memory prerequisite wait marker. + * Interface changes use initial user namespace CAP_NET_ADMIN. + */ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) { if (!file || !(file->flags & TASK_FILE_FLAG_SOCKET_INET)) return -LINUX_ENOTTY; @@ -49,7 +51,7 @@ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) bool change = control.operation == RELIEFOS_NET_CONTROL_DHCP || (control.operation == RELIEFOS_NET_CONTROL_DNS_POLICY && control.data.dns_policy.mode != RELIEFOS_NET_DNS_MODE_QUERY); - if (change && !(task->cap_effective & (1ULL << CAP_NET_ADMIN))) return -LINUX_EPERM; + if (change && !(task_initial_capabilities(task) & (1ULL << CAP_NET_ADMIN))) return -LINUX_EPERM; switch (control.operation) { case RELIEFOS_NET_CONTROL_CONFIG: control.result = net_get_config(&control.data.config); diff --git a/net/socket/netlink.c b/net/socket/netlink.c index 02d50de1..df757396 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -973,7 +973,9 @@ static int nl_change_route(const struct nlmsghdr *h, bool remove) } /** @brief Process one checked request and append its response or error. - * @param b Output builder. @param h Complete native request. @return Zero or staging error. */ + * @param b Output builder. @param h Complete native request. @return Zero or staging error. + * Routing changes require CAP_NET_ADMIN in the initial user namespace. + */ static int nl_request(struct nl_builder *b, const struct nlmsghdr *h) { uint32_t original=b->used; @@ -985,7 +987,7 @@ static int nl_request(struct nl_builder *b, const struct nlmsghdr *h) h->nlmsg_type==RTM_NEWADDR || h->nlmsg_type==RTM_DELADDR || h->nlmsg_type==RTM_NEWROUTE || h->nlmsg_type==RTM_DELROUTE) { struct task *task=sched_current_task(); - if (!task || !(task->cap_effective & (1ULL<nlmsg_flags & (NLM_F_ECHO|NLM_F_APPEND)) rc=-LINUX_EOPNOTSUPP; else if (h->nlmsg_type==RTM_NEWLINK || h->nlmsg_type==RTM_SETLINK) rc=nl_change_link(h); @@ -1005,12 +1007,13 @@ static int nl_request(struct nl_builder *b, const struct nlmsghdr *h) * @param length Nonzero bounded payload size. @param address Explicit user destination. * @param address_length User address size. @return Bytes accepted or negative errno. * @note The caller needs CAP_NET_ADMIN. Kernel-originated group 1 is not writable. + * Userspace delivery requires initial user namespace CAP_NET_ADMIN. */ static int nl_uevent_send(struct netlink_socket *sender, const void *data, uint32_t length, uint64_t address, uint32_t address_length) { struct task *task = sched_current_task(); - if (!task || !(task->cap_effective & (1ULL << CAP_NET_ADMIN)) || !address) + if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_NET_ADMIN)) || !address) return -LINUX_EPERM; struct sockaddr_nl dst; if ((int32_t)address_length < (int32_t)sizeof(dst)) diff --git a/net/socket/packet.c b/net/socket/packet.c index 87aa87a6..be09da00 100644 --- a/net/socket/packet.c +++ b/net/socket/packet.c @@ -526,6 +526,7 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin * @param a4 Fifth native argument. * @param a5 Sixth native argument. * @return Native result or negative errno; unsupported options are not accepted. + * Packet socket creation requires CAP_NET_RAW in the initial user namespace. */ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) @@ -539,7 +540,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (type != SOCK_RAW && !((int)a0 == AF_PACKET && type == SOCK_DGRAM) && !((int)a0 == AF_INET6 && type == SOCK_DGRAM && (int)a2 == IPPROTO_ICMPV6)) return -LINUX_ESOCKTNOSUPPORT; if (((int)a0 == AF_INET || (int)a0 == AF_INET6) && ((int)a2 <= 0 || (int)a2 > 255)) return -LINUX_EPROTONOSUPPORT; - if (!(task->cap_effective & (1ULL << CAP_NET_RAW))) return -LINUX_EPERM; + if (!(task_initial_capabilities(task) & (1ULL << CAP_NET_RAW))) return -LINUX_EPERM; unsigned index = 0; while (index < PACKET_LIMIT && sockets[index]) ++index; if (index == PACKET_LIMIT) return -LINUX_ENFILE; diff --git a/net/socket/udp.c b/net/socket/udp.c index 043a4f2e..6dc6e89c 100644 --- a/net/socket/udp.c +++ b/net/socket/udp.c @@ -120,6 +120,7 @@ static bool udp_ipv4_overlap(const struct udp_socket *s, uint32_t ip, * @param ip Requested local IPv4 address, or zero for any address. * @param port Requested local port, or zero for automatic allocation. * @return Zero on success or a negative errno. + * Binding a privileged port requires initial user namespace CAP_NET_BIND_SERVICE. */ static int bind_port(struct udp_socket *s, uint32_t ip, uint16_t port) { @@ -128,7 +129,7 @@ static int bind_port(struct udp_socket *s, uint32_t ip, uint16_t port) net_get_config(&config); if (ip && !net_interface_for_ipv4(ip)) return -LINUX_EADDRNOTAVAIL; struct task *task = sched_current_task(); - if (port && port < 1024 && !(task->cap_effective & (1ULL << CAP_NET_BIND_SERVICE))) + if (port && port < 1024 && !(task_initial_capabilities(task) & (1ULL << CAP_NET_BIND_SERVICE))) return -LINUX_EACCES; for (unsigned attempt = 0; attempt < 16384; ++attempt) { uint16_t candidate = port ? port : next_port++; diff --git a/net/tcp/socket.c b/net/tcp/socket.c index 703a2476..689fabd9 100644 --- a/net/tcp/socket.c +++ b/net/tcp/socket.c @@ -383,13 +383,15 @@ static bool tcp_uses_ipv4(const struct net_socket *socket) /** @brief Reserve one TCP port across native and mapped families. * @param socket Unbound endpoint. @param ip Host-order IPv4 address when applicable. - * @param port Requested host-order port or zero. @return Zero or negative errno. */ + * @param port Requested host-order port or zero. @return Zero or negative errno. + * Binding a privileged port requires initial user namespace CAP_NET_BIND_SERVICE. + */ static int tcp_bind_port(struct net_socket *socket, uint32_t ip, uint16_t port) { static uint16_t next_port = 49152; struct task *task = sched_current_task(); if (socket->bound) return -LINUX_EINVAL; - if (port && port < 1024 && (!task || !(task->cap_effective & (1ULL << CAP_NET_BIND_SERVICE)))) return -LINUX_EACCES; + if (port && port < 1024 && (!task || !(task_initial_capabilities(task) & (1ULL << CAP_NET_BIND_SERVICE)))) return -LINUX_EACCES; for (unsigned attempt = 0; attempt < 16384; ++attempt) { uint16_t candidate = port ? port : next_port++; if (next_port < 49152) next_port = 49152; diff --git a/tools/test_linux_capabilities.py b/tools/test_linux_capabilities.py index 178eec4f..f03117b3 100644 --- a/tools/test_linux_capabilities.py +++ b/tools/test_linux_capabilities.py @@ -12,6 +12,6 @@ "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", - "tools/tests/capability_test.c", "-o", binary, + "tools/tests/capability_test.c", "kernel/sched/user_namespace.c", "-o", binary, ], cwd=ROOT, check=True) subprocess.run([binary], cwd=ROOT, check=True, timeout=30) diff --git a/tools/tests/capability_test.c b/tools/tests/capability_test.c index b0b9221e..d385bf76 100644 --- a/tools/tests/capability_test.c +++ b/tools/tests/capability_test.c @@ -1,10 +1,27 @@ #include #include #include +#include #include "../../kernel/syscall/process/process.c" static struct task caller, target; static uint64_t readonly; +static unsigned namespace_allocations; +static bool fail_namespace_allocation; + +void *kernel_malloc(size_t size) +{ + if (fail_namespace_allocation) return NULL; + void *memory = malloc(size); + if (memory) ++namespace_allocations; + return memory; +} + +void kernel_free(void *memory) +{ + if (memory) --namespace_allocations; + free(memory); +} struct task *sched_current_task(void) { return &caller; } struct task *sched_find(uint32_t pid) { return pid == 17 ? &target : NULL; } uint64_t sched_user_task_count(uint32_t uid) { (void)uid; return 0; } @@ -26,8 +43,69 @@ void console_log(enum console_log_level level, const char *format, ...) (void)level; (void)format; } +/** @brief Exercise real namespace ancestry, ownership and reference retirement. */ +static void test_namespace_authority(void) +{ + struct task creator = {.euid = 1000}; + struct user_namespace *child, *sibling, *grandchild; + assert(!user_namespace_create(&creator, &child)); + assert(!user_namespace_create(&creator, &sibling)); + assert(!task_ns_capable(&creator, NULL, CAP_SYS_ADMIN)); + assert(task_ns_capable(&creator, child, CAP_SYS_ADMIN)); + struct task member = {.euid = 2000, .user_ns = child, + .cap_effective = UINT64_C(1) << CAP_KILL}; + assert(!user_namespace_create(&member, &grandchild)); + assert(task_ns_capable(&creator, grandchild, CAP_SYS_ADMIN)); + for (unsigned cap = 0; cap <= CAP_LAST_CAP; ++cap) { + assert(task_ns_capable(&member, child, cap) == (cap == CAP_KILL)); + assert(task_ns_capable(&member, grandchild, cap)); + assert(!task_ns_capable(&member, NULL, cap)); + assert(!task_ns_capable(&member, sibling, cap)); + } + member.euid = 3000; + assert(!task_ns_capable(&member, grandchild, CAP_SYS_ADMIN)); + assert(task_ns_capable(&member, grandchild, CAP_KILL)); + assert(!task_initial_capabilities(&member)); + creator.euid = 3000; + assert(!task_ns_capable(&creator, child, CAP_SYS_ADMIN)); + creator.cap_effective = UINT64_C(1) << CAP_SYS_ADMIN; + assert(task_ns_capable(&creator, grandchild, CAP_SYS_ADMIN)); + assert(task_initial_capabilities(&creator) == (UINT64_C(1) << CAP_SYS_ADMIN)); + assert(!task_ns_capable(NULL, child, CAP_KILL)); + assert(!task_ns_capable(&member, child, CAP_LAST_CAP + 1)); + assert(!task_initial_capabilities(NULL)); + + struct user_namespace *output = child; + fail_namespace_allocation = true; + assert(user_namespace_create(&member, &output) == -LINUX_ENOMEM && !output); + fail_namespace_allocation = false; + assert(child->references == 2); + assert(user_namespace_create(NULL, &output) == -LINUX_EINVAL && !output); + assert(user_namespace_create(&creator, NULL) == -LINUX_EINVAL); + user_namespace_put(child); + assert(task_ns_capable(&creator, grandchild, CAP_SYS_ADMIN)); + user_namespace_put(grandchild); + user_namespace_put(sibling); + assert(!namespace_allocations); + + creator.user_ns = NULL; + for (unsigned i = 1; i <= 32; ++i) { + assert(!user_namespace_create(&creator, &output)); + user_namespace_put(creator.user_ns); + creator.user_ns = output; + assert(output->level == i); + } + assert(user_namespace_create(&creator, &output) == -LINUX_ENOSPC && !output); + user_namespace_put(creator.user_ns); + assert(!namespace_allocations); + assert(!user_namespace_get(NULL)); + user_namespace_put(NULL); + puts("PASS user namespace capability ancestry, ownership, lifetime, OOM and depth"); +} + int main(void) { + test_namespace_authority(); caller = (struct task){.uid = 0, .euid = 0, .cap_effective = 0}; assert(syscall_process_control(LINUX_SYS_REBOOT, 0, 0, 0, 0) == -LINUX_EPERM); caller = (struct task){.uid = 1000, .euid = 1000, .cap_effective = 1ULL << CAP_SYS_BOOT}; @@ -131,5 +209,14 @@ int main(void) (uintptr_t)(unaligned_data + 1), 0, 0) == 0); assert(syscall_process_control(LINUX_SYS_CAPSET, (uintptr_t)(unaligned_header + 1), (uintptr_t)(unaligned_data + 1), 0, 0) == 0); + /* Namespace-local privilege must not authorize a global reboot. */ + struct user_namespace local_scope = {.references = 1, .owner = 1000, .level = 1}; + caller = (struct task){.uid = 1000, .euid = 1000, + .user_ns = &local_scope, + .cap_effective = (1ULL << CAP_SYS_BOOT) | (1ULL << CAP_SETUID)}; + assert(syscall_process_control(LINUX_SYS_REBOOT, 0, 0, 0, 0) == -LINUX_EPERM); + assert(syscall_process_control(LINUX_SYS_SETUID, 2000, 0, 0, 0) == 0); + assert(caller.uid == 2000 && caller.euid == 2000); + puts("PASS namespace-local credentials cannot authorize global reboot"); puts("PASS production capget/capset: root drop, subsets, read-only input, thread ID, version query, target lookup"); } diff --git a/tools/tests/linux_permissions_test.c b/tools/tests/linux_permissions_test.c index 6bff2093..9f461f4b 100644 --- a/tools/tests/linux_permissions_test.c +++ b/tools/tests/linux_permissions_test.c @@ -85,6 +85,14 @@ int main(void) assert(file_check(&dropped_root, file, 4, false) == -13); assert(file_chmod(&dropped_root, file, VFS_LOOKUP_FOLLOW, 0600) == -1); assert(file_chown(&dropped_root, file, VFS_LOOKUP_FOLLOW, 0, 0) == -1); + struct task namespace_root = root; + struct user_namespace local_scope = {.references = 1, .level = 1}; + namespace_root.user_ns = &local_scope; + assert(file_check(&namespace_root, file, 4, false) == -RELIEFOS_EACCES); + assert(file_check(&namespace_root, file, 4, true) == -RELIEFOS_EACCES); + assert(file_chmod(&namespace_root, file, VFS_LOOKUP_FOLLOW, 0600) == -RELIEFOS_EPERM); + assert(file_chown(&namespace_root, file, VFS_LOOKUP_FOLLOW, 0, 0) == -RELIEFOS_EPERM); + puts("PASS namespace-local capabilities cannot override initial-filesystem DAC"); struct task delegated = other; delegated.cap_effective = 1ULL << CAP_DAC_READ_SEARCH; assert(file_check(&delegated, file, 4, false) == 0); diff --git a/tools/tests/memory_pressure_oom_test.c b/tools/tests/memory_pressure_oom_test.c index 88411103..547267e3 100644 --- a/tools/tests/memory_pressure_oom_test.c +++ b/tools/tests/memory_pressure_oom_test.c @@ -91,6 +91,10 @@ static void policy(void) assert(oom_adj_get(a)==500 && oom_adj_get(b)==500); assert(oom_adj_get(init)==0 && oom_adj_get(vf)==0 && oom_adj_get(other)==0); assert(oom_adj_set(a,-1,a)==-EACCES); + struct user_namespace local_scope = {.references = 1, .level = 1}; + priv->user_ns = &local_scope; + assert(oom_adj_set(a,-500,priv)==-EACCES); + priv->user_ns = NULL; assert(!oom_adj_set(a,-500,priv)); int adjustment, minimum; sched_oom_policy_get(b,&adjustment,&minimum); assert(adjustment==-500 && minimum==-500); diff --git a/tools/tests/modules/scheduler.h b/tools/tests/modules/scheduler.h index fc8627b1..7b757041 100644 --- a/tools/tests/modules/scheduler.h +++ b/tools/tests/modules/scheduler.h @@ -25,6 +25,7 @@ static void fixture_exec_other_exit(uint32_t pid, uint64_t code); #include "../../../kernel/sched/fair.c" #include "../../../kernel/sched/fs.c" #include "../../../kernel/sched/identity.c" +#include "../../../kernel/sched/user_namespace.c" #include "../../../kernel/sched/tables.c" #include "../../../kernel/sched/lookup.c" #include "../../../kernel/sched/session.c" diff --git a/tools/tests/mount_namespace_task_test.c b/tools/tests/mount_namespace_task_test.c index d87e1c9b..7f3a0e5e 100644 --- a/tools/tests/mount_namespace_task_test.c +++ b/tools/tests/mount_namespace_task_test.c @@ -88,6 +88,7 @@ static void retire_child(struct task *child) kernel_free(child->exec_envp); kernel_free(child->exec_data); sched_task_identity_detach(child); + user_namespace_put(child->user_ns); task_zero(child); child->state = TASK_EXITED; child->running_cpu = SCHED_CPU_NONE; @@ -304,6 +305,20 @@ int main(void) retire_child(child); assert(ns.references == 1 && root->references == root_refs && volume->references == refs); } + struct user_namespace *user_scope; + assert(!user_namespace_create(parent, &user_scope)); + parent->user_ns = user_scope; + for (unsigned versioned = 0; versioned < 2; ++versioned) { + assert(clone_namespace(parent, user, versioned, CLONE_NEWNS) == -LINUX_EPERM); + assert(clone_namespace(parent, user, versioned, 0) > 0); + assert(child->user_ns == user_scope && user_scope->references == 2); + task_clear_identity(child); + assert(child->user_ns == user_scope); + retire_child(child); + assert(user_scope->references == 1); + } + parent->user_ns = NULL; + user_namespace_put(user_scope); check_unshare(parent, child); check_setns(parent); sched_task_fs_release(parent); diff --git a/tools/tests/mprotect_vma_growth_test.c b/tools/tests/mprotect_vma_growth_test.c index 2770c30f..71ca8632 100644 --- a/tools/tests/mprotect_vma_growth_test.c +++ b/tools/tests/mprotect_vma_growth_test.c @@ -2419,6 +2419,11 @@ static void test_mlock_permission_and_flags(void) assert(syscall_mm_mlockall(LINUX_MCL_FUTURE) == -RELIEFOS_EPERM); assert(!syscall_mm_munlock(base, 0)); current->cap_effective = 1ULL << CAP_IPC_LOCK; + struct user_namespace local_scope = {.references = 1, .level = 1}; + current->user_ns = &local_scope; + assert(syscall_mm_mlock(base, 0, 0) == -RELIEFOS_EPERM); + assert(syscall_mm_mlockall(LINUX_MCL_FUTURE) == -RELIEFOS_EPERM); + current->user_ns = NULL; assert(!syscall_mm_mlock(base, 0, 1ULL << 32)); assert(!syscall_mm_mlockall((1ULL << 32) | LINUX_MCL_FUTURE)); assert(!syscall_mm_munlockall()); diff --git a/tools/tests/process_vm_test.c b/tools/tests/process_vm_test.c index 724d799e..57113bc0 100644 --- a/tools/tests/process_vm_test.c +++ b/tools/tests/process_vm_test.c @@ -17,6 +17,17 @@ static unsigned allocations, faults; static int fail_allocations; static uint64_t inaccessible_physical; static struct { uint64_t address; unsigned refs; } pages[2048]; +/** @brief Report the free capacity of the fixture's physical page pool. + * @return Free capacity in KiB for the paging allocation diagnostics. + */ +uint64_t mm_free_memory_kib(void) +{ + uint64_t free_pages = 0; + for (size_t i = 0; i < sizeof(pages) / sizeof(pages[0]); ++i) + if (!pages[i].refs) ++free_pages; + return free_pages * 4; +} + void *kernel_malloc(size_t n) { if (fail_allocations) return NULL; void *p = malloc(n); if (p) ++allocations; return p; } void kernel_free(void *p) { if (p) { assert(allocations); --allocations; free(p); } } @@ -135,6 +146,16 @@ int main(void) assert(transfer(20, local, 2, remote, 2, 0, false) == -LINUX_EPERM); caller.cap_effective = 1ULL << CAP_SYS_PTRACE; assert(transfer(20, local, 2, remote, 2, 0, false) == 16); + struct user_namespace local_scope = {.references = 1, .owner = 1000, .level = 1}; + caller.user_ns = &local_scope; + assert(transfer(20, local, 2, remote, 2, 0, false) == -LINUX_EPERM); + target.user_ns = &local_scope; + assert(transfer(20, local, 2, remote, 2, 0, false) == 16); + caller.cap_effective = 0; + target.address_space.nondumpable = false; + target.user_ns = NULL; + assert(transfer(20, local, 2, remote, 2, 0, false) == -LINUX_EPERM); + caller.user_ns = NULL; caller.cap_effective = 0; target.address_space.nondumpable = false; caller.address_space.nondumpable = true; assert(transfer(10, local, 2, remote, 2, 0, false) == 16); diff --git a/tools/tests/task_subreaper_test.c b/tools/tests/task_subreaper_test.c index 06156300..8b326de1 100644 --- a/tools/tests/task_subreaper_test.c +++ b/tools/tests/task_subreaper_test.c @@ -102,7 +102,10 @@ int main(void) assert(!sched_prepare_exec_current(exec_thread) && exec_thread->pid == 41); assert(!syscall_process_prctl(SUBREAPER_GET, (uintptr_t)&value.flag, 0, 0, 0) && value.flag == 1); + assert(!user_namespace_create(init, &zombie->user_ns)); + struct user_namespace *zombie_scope = user_namespace_get(zombie->user_ns); sched_exit(zombie->pid, 37); + assert(zombie->user_ns == zombie_scope && zombie_scope->references == 2); assert(!*sched_task_process_pending(exec_thread)); sched_exit(parent->pid, 24); assert(child->parent_pid == parent->pid && child->pdeath_parent_pid == last_thread->pid); @@ -113,6 +116,8 @@ int main(void) int status = 0; assert(sched_wait_reap(41, 45, LINUX_WEXITED | LINUX_WNOTHREAD, &status, NULL) == 45 && status == 37 << 8 && !sched_find(45)); + assert(!zombie->user_ns && zombie_scope->references == 1); + user_namespace_put(zombie_scope); assert(!syscall_process_prctl(SUBREAPER_SET, 0, 0, 0, 0)); assert(!syscall_process_prctl(SUBREAPER_GET, (uintptr_t)&value.flag, 0, 0, 0) && !value.flag); From 4fd5d041aab122020a8d076900c49558d7ea105f Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 23:39:35 +0800 Subject: [PATCH 55/97] feat(userns): publish ID maps through captured proc controls --- Documentation/core-api/mount-namespaces.rst | 12 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 36 +- .../en/LC_MESSAGES/userspace-api/procfs.po | 70 ++++ .../LC_MESSAGES/core-api/mount-namespaces.po | 29 +- .../ja/LC_MESSAGES/userspace-api/procfs.po | 57 ++++ Documentation/userspace-api/procfs.rst | 31 ++ fs/proc/internal.h | 16 +- fs/proc/mount.c | 2 +- fs/proc/procfs.c | 98 +++++- fs/vfs/pseudo.c | 31 +- include/reliefnt/pseudo_fs.h | 4 +- include/reliefnt/user_namespace.h | 124 ++++++- kernel/sched/user_namespace.c | 320 +++++++++++++++++- tools/test_linux_inventory.py | 2 +- tools/test_lock_profile.py | 4 +- tools/test_memory_reporting.py | 4 +- tools/test_procfs.py | 3 +- tools/test_rootfs.py | 2 +- tools/test_user_namespace.py | 17 + tools/tests/Makefile | 1 + tools/tests/host-suites.list | 1 + tools/tests/procfs_directories_test.c | 125 +++++++ tools/tests/rootfs_uts_test.c | 17 +- tools/tests/test-version.sh | 2 +- tools/tests/user_namespace_test.c | 242 +++++++++++++ 25 files changed, 1204 insertions(+), 46 deletions(-) create mode 100644 tools/test_user_namespace.py create mode 100644 tools/tests/user_namespace_test.c diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 8d2d11c3..a3e0e0ed 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -102,5 +102,15 @@ ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。 +空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID +转换为全局内核 ID;转换接口通过 acquire 读取完整映射,无分配和调度器锁。 +初始空间使用恒等映射,``UINT32_MAX`` 为无效 ID。每个父空间范围必须完整落在 +同一映射段内,本地与父范围均不能重叠或包含无效 ID。 + +proc 控制文件在打开时保留目标空间、打开者空间及其标量凭据。写入使用捕获权限 +和当前调用者权限,目标退出或 PID 重用后仍操作原空间。所有映射与 setgroups +策略提交由现有独占执行权串行化,候选解析、权限和分配失败均不发布状态;最后 +一个空间引用释放映射并逐级释放父空间。用户接口见 :doc:`../userspace-api/procfs`。 + 内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 -``EINVAL``,UID/GID 映射与用户空间句柄属于后续接入范围。 +``EINVAL``;用户态 ID 边界转换、创建入口和用户空间句柄仍待接入。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 5eef9004..f95feaac 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -201,5 +201,37 @@ msgstr "Task credentials hold a reference to a user namespace. A null pointer re msgid "文件系统 DAC 特权覆盖、挂载图管理、设备、网络、IPC、时钟、重启、模块、内存锁定 和 OOM 调整等共享资源使用初始空间能力。信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。" msgstr "Filesystem DAC overrides, mount graph management, devices, networking, IPC, the system clock, reboot, modules, memory locking, and OOM adjustments use initial-namespace capabilities for shared resources. Signals, process priorities, cross-process resource limits, and ptrace authorize capability overrides in the target task’s owning namespace. Raising a hard resource limit still requires initial-namespace capability. Capabilities extend to descendant namespaces. A task in the parent namespace whose effective UID matches the child’s owner has capabilities in that child’s subtree. Ptrace’s capability subset check requires both tasks to be in the same user namespace. Capset, identity changes, securebits, and seccomp installation use the caller’s own namespace capabilities." -msgid "内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``,UID/GID 映射与用户空间句柄属于后续接入范围。" -msgstr "The kernel provides internal namespace allocation and reference APIs. The user-space ``CLONE_NEWUSER`` creation interface currently returns ``EINVAL``. UID/GID mappings and user namespace handles will be added separately." +msgid "" +"空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID 转换为全局内核 ID;转换接口通过 acquire " +"读取完整映射,无分配和调度器锁。 初始空间使用恒等映射,``UINT32_MAX`` 为无效 ID。每个父空间范围必须完整落在 " +"同一映射段内,本地与父范围均不能重叠或包含无效 ID。" +msgstr "" +"Each scope owns UID/GID range maps published once and immutable " +"thereafter. Parent-space IDs are converted to global kernel IDs before " +"publication. Conversion acquires the complete map using allocation-free, " +"lock-free reads. The initial namespace uses identity mapping, with " +"``UINT32_MAX`` as the invalid ID. Each parent range must fit in one " +"extent, and local and parent ranges must be disjoint and exclude the " +"invalid ID." + +msgid "" +"proc 控制文件在打开时保留目标空间、打开者空间及其标量凭据。写入使用捕获权限 和当前调用者权限,目标退出或 PID " +"重用后仍操作原空间。所有映射与 setgroups 策略提交由现有独占执行权串行化,候选解析、权限和分配失败均不发布状态;最后 " +"一个空间引用释放映射并逐级释放父空间。用户接口见 :doc:`../userspace-api/procfs`。" +msgstr "" +"Opening a proc control retains the target scope, opener scope and scalar " +"opener credentials. Writes check captured and current authority and keep " +"operating on the retained scope after task exit or PID reuse. Existing " +"exclusive execution ownership serializes all map and setgroups policy " +"commits. Parse, authorization and allocation failures preserve state. The" +" last scope reference frees its maps and releases parent references " +"recursively. See :doc:`../userspace-api/procfs` for the user interface." + +msgid "" +"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``;用户态 ID " +"边界转换、创建入口和用户空间句柄仍待接入。" +msgstr "" +"Internal allocation and reference interfaces are available. Userspace " +"``CLONE_NEWUSER`` currently returns ``EINVAL``. Userspace ID boundary " +"conversion, creation entry points and user-namespace handles remain " +"pending." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po index d59a8684..957e5656 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po @@ -380,3 +380,73 @@ msgstr "With ``invisible``, process and thread directories are visible to caller msgid "绑定和克隆挂载共享原实例的策略,单独创建的 proc 实例互不影响。重挂载及文件 系统上下文重配置只更新显式提供的选项,全部解析成功后才应用。失败时原策略与 挂载标志保持不变。已经打开并捕获的文件视图继续遵守原有的读取生命周期,重新 打开和后续路径操作检查当前策略。" msgstr "Bind and cloned mounts share the original instance policy. Separately created proc instances are independent. Remount and filesystem-context reconfiguration update only explicitly supplied options and apply them after complete parsing succeeds. Failure preserves the previous policy and mount flags. Already opened and captured file views retain their existing read lifecycle. Reopening and later path operations check the current policy." + +msgid "用户命名空间映射" +msgstr "User namespace mappings" + +msgid "" +"``/proc/PID/uid_map``、``gid_map`` 和 ``setgroups`` 也适用于线程路径。 映射文件模式为 " +"0644,setgroups 为 0600;按目标任务的有效 UID/GID 确定所有者, 不可 dump 的任务使用现有 root " +"所有权规则。路径访问遵守 proc 可见性、普通 DAC 和挂载只读策略。当前 ``CLONE_NEWUSER`` 返回 " +"``EINVAL``;这些控制文件先提供 内核已建立空间的映射与策略接口。" +msgstr "" +"``/proc/PID/uid_map``, ``gid_map`` and ``setgroups`` also apply to thread" +" paths. Map files use mode 0644 and setgroups uses 0600. Ownership " +"follows the target effective UID/GID, with existing root ownership rules " +"for nondumpable tasks. Path access follows proc visibility, ordinary DAC " +"and read-only mount policy. ``CLONE_NEWUSER`` currently returns " +"``EINVAL``. These controls provide maps and policy for scopes already " +"established inside the kernel." + +msgid "" +"打开时保留目标和打开者的用户空间及打开者有效 UID/GID、能力集合。后续读取和 写入使用所持空间,目标退出或 PID 被复用后仍访问原空间;旧" +" inode 不能重新打开 为新进程的控制文件。dup 共享捕获状态。读取反映该空间当前映射或策略,并支持 偏移与短读,文件关闭时释放空间引用。" +msgstr "" +"Opening retains the target and opener user namespaces and the opener " +"effective UID/GID and capability set. Subsequent reads and writes use " +"those retained scopes after target exit or PID reuse. Reopening an old " +"inode cannot reach the replacement process. dup shares the capture. Reads" +" reflect current maps or policy with offsets and short reads. Final close" +" releases the namespace references." + +msgid "" +"映射每行包含十进制的本空间首 ID、父空间首 ID 和非零数量。最多 340 行,单次 写入须小于 4096 " +"字节且偏移为零;每种映射只能成功写入一次。范围不能溢出、 重叠或包含 4294967295,父范围须在父空间中完整映射。映射显示的第二列相对于 " +"打开者空间;打开者与目标相同时相对于父空间。初始空间显示恒等映射。格式、 权限或内存分配失败保留原状态,调用者可重新尝试。" +msgstr "" +"Each map row contains a decimal first local ID, first parent ID and " +"nonzero count. Up to 340 rows fit in one write of fewer than 4096 bytes " +"at offset zero. Each map permits one successful write. Ranges must fit, " +"be disjoint and exclude 4294967295, and parent ranges must be completely " +"mapped. The second output column is relative to the opener namespace, or " +"its parent when the opener and target match. The initial namespace shows " +"an identity map. Format, permission and allocation failures preserve " +"state for retry." + +msgid "" +"打开者必须位于目标或其直接父空间,并对目标具有 ``CAP_SYS_ADMIN``。一般映射 还要求打开者与当前写入者均在父空间具备 " +"``CAP_SETUID`` 或 ``CAP_SETGID``。 创建者有效 UID 的单 ID 映射使用 owner 例外;有效 GID 的单 " +"ID 映射还要求先永久 禁止 setgroups。映射父空间 UID 0 需要相应 ``CAP_SETFCAP`` 权限;从目标空间 " +"写入时检查创建时记录的父空间能力。" +msgstr "" +"The opener must be in the target or its direct parent and have " +"``CAP_SYS_ADMIN`` over the target. General maps additionally require both" +" opener and current writer to hold parent ``CAP_SETUID`` or " +"``CAP_SETGID``. The owner exception allows a single-ID map of the creator" +" effective UID. A single-ID effective GID map also requires permanent " +"setgroups denial first. Mapping parent UID 0 requires the applicable " +"``CAP_SETFCAP`` authority. Writes from the target check the parent " +"capability recorded at creation." + +msgid "" +"setgroups 输出 ``allow`` 或 ``deny`` 并带换行。写打开需要目标空间的 " +"``CAP_SYS_ADMIN``;写入偏移为零,长度小于 8 字节,可在关键字后添加空白。 deny 只能在 GID " +"映射发布前设置,设置后不可恢复,子空间继承 deny;allow 不能 撤销禁令。映射文件和 setgroups 均接受零长度 " +"truncate,拒绝非零长度。" +msgstr "" +"setgroups renders ``allow`` or ``deny`` followed by a newline. Write-open" +" requires target ``CAP_SYS_ADMIN``. Writes use offset zero and fewer than" +" 8 bytes, with optional whitespace after the keyword. deny can be set " +"only before the GID map is published and is irreversible and inherited by" +" child scopes. allow cannot reverse denial. Map and setgroups files " +"accept zero-length truncation and reject nonzero lengths." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index ba177ebc..e5b60d3b 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -173,5 +173,30 @@ msgstr "タスクの資格情報は参照カウント付きのユーザー名前 msgid "文件系统 DAC 特权覆盖、挂载图管理、设备、网络、IPC、时钟、重启、模块、内存锁定 和 OOM 调整等共享资源使用初始空间能力。信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。" msgstr "ファイルシステムの DAC の上書き、マウントグラフの管理、デバイス、ネットワーク、IPC、システムクロック、再起動、モジュール、メモリロック、OOM 調整などの共有資源には、初期名前空間のケーパビリティが必要です。シグナル、プロセス優先度、別プロセスのリソース制限、ptrace のケーパビリティによる認可は、対象タスクが所属する名前空間で行います。ハードリミットの引き上げには引き続き初期名前空間のケーパビリティが必要です。ケーパビリティは子孫の名前空間にも適用されます。子名前空間の所有者と実効 UID が一致する親名前空間のタスクは、その子のサブツリーでケーパビリティを持ちます。ptrace でケーパビリティの部分集合を確認する際は、両タスクが同じユーザー名前空間に属する必要があります。capset、ID の変更、securebits、seccomp の設定には、呼び出し元が所属する名前空間のケーパビリティを使います。" -msgid "内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``,UID/GID 映射与用户空间句柄属于后续接入范围。" -msgstr "カーネル内部には名前空間の割り当てと参照を管理する API があります。ユーザー空間の ``CLONE_NEWUSER`` による作成は現在 ``EINVAL`` を返します。UID/GID マッピングとユーザー名前空間ハンドルは別途追加します。" +msgid "" +"空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID 转换为全局内核 ID;转换接口通过 acquire " +"读取完整映射,无分配和调度器锁。 初始空间使用恒等映射,``UINT32_MAX`` 为无效 ID。每个父空间范围必须完整落在 " +"同一映射段内,本地与父范围均不能重叠或包含无效 ID。" +msgstr "" +"各空間は、一度だけ公開され、その後は不変となる UID/GID 範囲マップを保持します。公開前に親空間の ID をグローバルなカーネル ID " +"に変換します。変換は acquire " +"読み取りで完全なマップを取得し、割り当てとスケジューラロックを使用しません。初期空間は恒等マッピングを使用し、``UINT32_MAX`` " +"は無効な ID を表します。親空間の各範囲は単一の区間内に収まり、ローカル範囲と親範囲はそれぞれ重複せず、無効な ID を含められません。" + +msgid "" +"proc 控制文件在打开时保留目标空间、打开者空间及其标量凭据。写入使用捕获权限 和当前调用者权限,目标退出或 PID " +"重用后仍操作原空间。所有映射与 setgroups 策略提交由现有独占执行权串行化,候选解析、权限和分配失败均不发布状态;最后 " +"一个空间引用释放映射并逐级释放父空间。用户接口见 :doc:`../userspace-api/procfs`。" +msgstr "" +"proc " +"制御ファイルを開くと、対象空間、オープンした側の空間とスカラー資格情報を保持します。書き込みは保持した権限と現在の呼び出し元の権限を検査し、対象の終了や" +" PID の再利用後も元の空間を操作します。既存の排他的実行所有権がマップと setgroups " +"方針の公開を直列化します。解析、権限検査、割り当ての失敗時は状態を保持します。空間の最後の参照を解放するとマップと親空間の参照を順次解放します。ユーザーインターフェースは" +" :doc:`../userspace-api/procfs` を参照してください。" + +msgid "" +"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``;用户态 ID " +"边界转换、创建入口和用户空间句柄仍待接入。" +msgstr "" +"カーネル内部の空間割り当てと参照インターフェースを提供します。現在、ユーザー空間の ``CLONE_NEWUSER`` は ``EINVAL`` " +"を返します。ユーザー向け ID 境界変換、作成入口、ユーザー名前空間ハンドルは今後の対応です。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po index f330d709..b8cd4335 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po @@ -336,3 +336,60 @@ msgstr "``invisible`` では、既存の FSCREDS、dumpable、``CAP_SYS_PTRACE`` msgid "绑定和克隆挂载共享原实例的策略,单独创建的 proc 实例互不影响。重挂载及文件 系统上下文重配置只更新显式提供的选项,全部解析成功后才应用。失败时原策略与 挂载标志保持不变。已经打开并捕获的文件视图继续遵守原有的读取生命周期,重新 打开和后续路径操作检查当前策略。" msgstr "bind マウントとクローンされたマウントは元のインスタンスのポリシーを共有します。別々に作成した proc インスタンスは互いに独立しています。再マウントとファイルシステムコンテキストの再設定は明示されたオプションだけを更新し、すべての解析が成功してから適用します。失敗時は以前のポリシーとマウントフラグを保持します。すでに開いて取得したファイルビューは既存の読み取りライフサイクルに従い、再オープンと後続のパス操作は現在のポリシーを検査します。" + +msgid "用户命名空间映射" +msgstr "ユーザー名前空間のマッピング" + +msgid "" +"``/proc/PID/uid_map``、``gid_map`` 和 ``setgroups`` 也适用于线程路径。 映射文件模式为 " +"0644,setgroups 为 0600;按目标任务的有效 UID/GID 确定所有者, 不可 dump 的任务使用现有 root " +"所有权规则。路径访问遵守 proc 可见性、普通 DAC 和挂载只读策略。当前 ``CLONE_NEWUSER`` 返回 " +"``EINVAL``;这些控制文件先提供 内核已建立空间的映射与策略接口。" +msgstr "" +"``/proc/PID/uid_map``、``gid_map``、``setgroups`` はスレッドのパスにも適用します。マップのモードは " +"0644、setgroups は 0600 です。所有者は対象タスクの実効 UID/GID に従い、dump 不可のタスクには既存の root " +"所有権規則を使用します。パスへのアクセスは proc の可視性、通常の DAC、読み取り専用マウント方針に従います。現在 " +"``CLONE_NEWUSER`` は ``EINVAL`` " +"を返します。これらの制御ファイルはカーネル内部で作成済みの空間にマップと方針を提供します。" + +msgid "" +"打开时保留目标和打开者的用户空间及打开者有效 UID/GID、能力集合。后续读取和 写入使用所持空间,目标退出或 PID 被复用后仍访问原空间;旧" +" inode 不能重新打开 为新进程的控制文件。dup 共享捕获状态。读取反映该空间当前映射或策略,并支持 偏移与短读,文件关闭时释放空间引用。" +msgstr "" +"オープン時に対象と呼び出し元のユーザー空間、呼び出し元の実効 UID/GID " +"と能力集合を保持します。その後の読み書きは保持した空間を使用し、対象の終了や PID 再利用後も元の空間にアクセスします。古い inode " +"の再オープンで新しいプロセスの制御ファイルにはアクセスできません。dup " +"は保持状態を共有します。読み取りは現在のマップや方針を反映し、オフセットと短い読み取りを扱います。最後のクローズで空間の参照を解放します。" + +msgid "" +"映射每行包含十进制的本空间首 ID、父空间首 ID 和非零数量。最多 340 行,单次 写入须小于 4096 " +"字节且偏移为零;每种映射只能成功写入一次。范围不能溢出、 重叠或包含 4294967295,父范围须在父空间中完整映射。映射显示的第二列相对于 " +"打开者空间;打开者与目标相同时相对于父空间。初始空间显示恒等映射。格式、 权限或内存分配失败保留原状态,调用者可重新尝试。" +msgstr "" +"マップの各行は、この空間の開始 ID、親空間の開始 ID、ゼロ以外の個数を十進数で指定します。最大 340 行、オフセットはゼロ、一度の書き込みは" +" 4096 バイト未満です。各マップは一度だけ正常に書き込めます。範囲はオーバーフロー、重複、4294967295 " +"の包含を禁止し、親範囲全体が親空間でマップ済みである必要があります。表示の第 2 " +"列はオープンした側の空間を基準とし、対象と同じ空間の場合は親を基準とします。初期空間は恒等マップを表示します。形式、権限、割り当ての失敗時は状態を保持して再試行できます。" + +msgid "" +"打开者必须位于目标或其直接父空间,并对目标具有 ``CAP_SYS_ADMIN``。一般映射 还要求打开者与当前写入者均在父空间具备 " +"``CAP_SETUID`` 或 ``CAP_SETGID``。 创建者有效 UID 的单 ID 映射使用 owner 例外;有效 GID 的单 " +"ID 映射还要求先永久 禁止 setgroups。映射父空间 UID 0 需要相应 ``CAP_SETFCAP`` 权限;从目标空间 " +"写入时检查创建时记录的父空间能力。" +msgstr "" +"オープンする側は対象または直接の親空間に属し、対象に対する ``CAP_SYS_ADMIN`` " +"が必要です。通常のマップでは、オープンした側と現在の書き込み元の両方に親空間の ``CAP_SETUID`` または ``CAP_SETGID``" +" が必要です。所有者例外は作成者の実効 UID の単一 ID マップを許可します。実効 GID の単一 ID マップには先に setgroups " +"の永久禁止も必要です。親空間の UID 0 のマップには該当する ``CAP_SETFCAP`` " +"権限を要求し、対象空間内からの書き込みでは作成時に記録した親の能力を検査します。" + +msgid "" +"setgroups 输出 ``allow`` 或 ``deny`` 并带换行。写打开需要目标空间的 " +"``CAP_SYS_ADMIN``;写入偏移为零,长度小于 8 字节,可在关键字后添加空白。 deny 只能在 GID " +"映射发布前设置,设置后不可恢复,子空间继承 deny;allow 不能 撤销禁令。映射文件和 setgroups 均接受零长度 " +"truncate,拒绝非零长度。" +msgstr "" +"setgroups は ``allow`` または ``deny`` と改行を出力します。書き込みオープンには対象空間の " +"``CAP_SYS_ADMIN`` が必要です。書き込みはオフセットゼロ、8 バイト未満で、キーワード後に空白を付けられます。deny は GID" +" マップ公開前にのみ設定でき、不可逆で子空間に継承されます。allow は禁止を解除できません。マップと setgroups は長さゼロの " +"truncate を受け付け、ゼロ以外を拒否します。" diff --git a/Documentation/userspace-api/procfs.rst b/Documentation/userspace-api/procfs.rst index 6551230a..e81842b7 100644 --- a/Documentation/userspace-api/procfs.rst +++ b/Documentation/userspace-api/procfs.rst @@ -141,6 +141,37 @@ dup 共享已打开的视图,重新打开会生成新视图。快照不采用 原有 ``cmdline``、``environ``、mount view 和诊断文件仍遵守各自既有读取规则。 ``/proc/sys/fs/inotify`` 下的控制值在读取时取当前策略,不使用打开时快照。 +用户命名空间映射 +================ + +``/proc/PID/uid_map``、``gid_map`` 和 ``setgroups`` 也适用于线程路径。 +映射文件模式为 0644,setgroups 为 0600;按目标任务的有效 UID/GID 确定所有者, +不可 dump 的任务使用现有 root 所有权规则。路径访问遵守 proc 可见性、普通 DAC +和挂载只读策略。当前 ``CLONE_NEWUSER`` 返回 ``EINVAL``;这些控制文件先提供 +内核已建立空间的映射与策略接口。 + +打开时保留目标和打开者的用户空间及打开者有效 UID/GID、能力集合。后续读取和 +写入使用所持空间,目标退出或 PID 被复用后仍访问原空间;旧 inode 不能重新打开 +为新进程的控制文件。dup 共享捕获状态。读取反映该空间当前映射或策略,并支持 +偏移与短读,文件关闭时释放空间引用。 + +映射每行包含十进制的本空间首 ID、父空间首 ID 和非零数量。最多 340 行,单次 +写入须小于 4096 字节且偏移为零;每种映射只能成功写入一次。范围不能溢出、 +重叠或包含 4294967295,父范围须在父空间中完整映射。映射显示的第二列相对于 +打开者空间;打开者与目标相同时相对于父空间。初始空间显示恒等映射。格式、 +权限或内存分配失败保留原状态,调用者可重新尝试。 + +打开者必须位于目标或其直接父空间,并对目标具有 ``CAP_SYS_ADMIN``。一般映射 +还要求打开者与当前写入者均在父空间具备 ``CAP_SETUID`` 或 ``CAP_SETGID``。 +创建者有效 UID 的单 ID 映射使用 owner 例外;有效 GID 的单 ID 映射还要求先永久 +禁止 setgroups。映射父空间 UID 0 需要相应 ``CAP_SETFCAP`` 权限;从目标空间 +写入时检查创建时记录的父空间能力。 + +setgroups 输出 ``allow`` 或 ``deny`` 并带换行。写打开需要目标空间的 +``CAP_SYS_ADMIN``;写入偏移为零,长度小于 8 字节,可在关键字后添加空白。 +deny 只能在 GID 映射发布前设置,设置后不可恢复,子空间继承 deny;allow 不能 +撤销禁令。映射文件和 setgroups 均接受零长度 truncate,拒绝非零长度。 + 策略节点 ======== diff --git a/fs/proc/internal.h b/fs/proc/internal.h index 6862ce85..02a9bfc8 100644 --- a/fs/proc/internal.h +++ b/fs/proc/internal.h @@ -21,7 +21,7 @@ int proc_memory_open(const char *name, void **out); int proc_memory_read(void *view, uint64_t offset, void *buffer, uint32_t capacity, uint32_t *read); /** @brief Release an owned memory snapshot; NULL is ignored. */ void proc_memory_close(void *view); -/** @brief Obtain immutable proc permissions, including per-task OOM ownership. +/** @brief Obtain immutable proc permissions, including per-task control ownership. * @param name Intrinsic key. @param node Retained node. @param value Metadata * output or proposal. @param write True for unsupported metadata mutation. * @return Zero or negative errno. Task identity remains execution-owned. @@ -114,11 +114,11 @@ int proc_extra_readdir(const char *path, uint64_t *offset, struct reliefos_dir_e /** @brief Capture a mount view, generated leaf or diagnostic snapshot at open. * @param name Required borrowed NUL-terminated intrinsic inode key. - * @param flags Sanitized open status flags; write-only controls need no view. + * @param flags Sanitized open status flags; namespace controls capture authority. * @param out Required writable output; owned state or NULL on stateless success. * @return Zero or negative errno with no partial ownership on failure. * Execution-owned task context; mount roots retain providers across target - * exit, and generated byte snapshots remain fixed until close. Partition + * exit, namespace controls retain credentials, and byte snapshots remain fixed. Partition * metadata can perform I/O; no graph lock spans renderer callbacks. */ int proc_file_open(const char *name,uint32_t flags,void **out); /** @brief Read a captured mount graph or fixed diagnostic snapshot. @@ -130,6 +130,14 @@ int proc_file_open(const char *name,uint32_t flags,void **out); * @return Renderer status or negative errno; ownership is unchanged. * Execution-owned context; no graph/module lock spans renderer callbacks. */ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read); +/** @brief Write a retained namespace control without replaying its PID path. + * @param value Borrowed open capture. @param offset Required zero position. + * @param buffer Validated bytes. @param length Byte count. + * @param written Required actual output, cleared before validation. + * @return Namespace status or EOPNOTSUPP for live stateless write fallback. + * Execution ownership serializes publication and preserves both credentials. + */ +int proc_file_write(void *value,uint64_t offset,const void *buffer,uint32_t length,uint32_t *written); /** @brief Poll a captured mount view without retargeting its namespace. * @param value Borrowed open capture. @param events Requested poll bits. * @param consume Acknowledge a pending graph change when true. @@ -139,7 +147,7 @@ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,ui * Execution ownership serializes observation with mount transactions. */ bool proc_file_poll(void *value,short events,bool consume,uint64_t *generation,short *ready); -/** @brief Consume an open capture and release its root or diagnostic data. +/** @brief Consume an open capture and release namespace, root or diagnostic data. * @param value Owned optional capture; NULL is ignored. * @return None. Execution-owned final close, no graph/scheduler/module lock * across path release, which can perform provider I/O. */ diff --git a/fs/proc/mount.c b/fs/proc/mount.c index a5b75894..f8609369 100644 --- a/fs/proc/mount.c +++ b/fs/proc/mount.c @@ -147,7 +147,7 @@ int proc_create_vfs_mount_options(const char *options,struct vfs_mount **out) .get_identity=proc_key_identity,.identity_alive=proc_key_alive,.put_identity=proc_key_put, .follow=proc_mount_magic_target,.stat_link=proc_mount_magic_stat, .permissions=proc_control_permissions,.getattr=proc_getattr, - .open=proc_file_open,.read_open=proc_file_read,.close=proc_file_close, + .open=proc_file_open,.read_open=proc_file_read,.write_open=proc_file_write,.close=proc_file_close, .poll_open=proc_file_poll,.authorize=proc_key_authorize, .entry_visible=proc_entry_visible,.reconfigure=proc_reconfigure}; if(!out)return -EINVAL; diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 0697b1c2..318661e9 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -207,6 +208,24 @@ struct task *proc_view_task(const char *path, const char **leaf) return proc_path_kind(path, leaf, &pid) ? sched_find(pid) : NULL; } +/** @brief Classify a namespace control on an intrinsic proc inode key. + * @param name Borrowed provider key. @param target Optional live task output. + * @return Kind plus one, or zero for other leaves. With a target output, + * validate the task path while execution ownership prevents reaping. Without + * it, classify the retained leaf after PID retirement for immediate commit. + */ +static int proc_userns_key(const char *name, struct task **target) +{ + const char *leaf = name; + for (const char *p = name; *p; ++p) + if (*p == '/') leaf = p + 1; + int kind = proc_text_eq(leaf, "uid_map") ? USER_NAMESPACE_UID_MAP + 1 : + proc_text_eq(leaf, "gid_map") ? USER_NAMESPACE_GID_MAP + 1 : + proc_text_eq(leaf, "setgroups") ? USER_NAMESPACE_SETGROUPS + 1 : 0; + if (kind && target) *target = proc_view_task(name, &leaf); + return kind; +} + /** @brief Preserve the established private status fields alongside Linux fields. * @param task Borrowed live task. @param stream Required output stream. * Execution-owned metadata only; no allocation or retained references. @@ -488,6 +507,8 @@ struct proc_open_view { uint64_t mount_generation; void *memory; const char *inotify_control; + bool namespace_control; + struct user_namespace_file namespace_file; bool score_valid; int score; char *text; uint64_t text_size; @@ -501,7 +522,8 @@ struct proc_open_view { * @param flags Sanitized status flags, borrowed and unchanged. * @param out Required owned output; legacy stateless files return NULL. * @return Zero or negative errno with empty output on failure. Mount views - * retain the target's graph and root; generated leaves and diagnostics capture bytes, + * retain the target's graph and root; namespace controls retain the credential + * scope and opener authority; generated leaves and diagnostics capture bytes, * while inotify controls retain a static key and read the current policy. * Namespace ownership outlives its retained paths; final release drops this * path even after task exit. Execution-owned, without graph locks across @@ -510,6 +532,20 @@ struct proc_open_view { int proc_file_open(const char *name,uint32_t flags,void **out) { (void)flags;if(!out)return -RELIEFOS_EINVAL;*out=NULL; + struct task *namespace_task = NULL; + int namespace_kind = proc_userns_key(name, &namespace_task); + if (namespace_kind) { + if (!namespace_task || (namespace_task->flags & TASK_FLAG_RESOURCES_RELEASED)) return -ESRCH; + struct proc_open_view *state = kernel_malloc(sizeof(*state)); + if (!state) return -ENOMEM; + *state = (struct proc_open_view){.namespace_control = true}; + int rc = user_namespace_file_open(namespace_task->user_ns, sched_current_task(), + namespace_kind - 1, (flags & LINUX_O_ACCMODE) != LINUX_O_RDONLY, + &state->namespace_file); + if (rc) { kernel_free(state); return rc; } + *out = state; + return 0; + } if (proc_memory_is_file(name)) { if ((flags & LINUX_O_ACCMODE) != LINUX_O_RDONLY || (flags & LINUX_O_TRUNC)) return -RELIEFOS_EROFS; @@ -609,6 +645,8 @@ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,ui { if(!read)return -RELIEFOS_EINVAL;*read=0; struct proc_open_view *state=value;if(!state)return -RELIEFOS_EINVAL; + if (state->namespace_control) + return user_namespace_file_read(&state->namespace_file, offset, buffer, capacity, read); if (state->inotify_control) { if (!buffer && capacity) return -RELIEFOS_EINVAL; struct text_stream stream = {.offset=offset,.buffer=buffer,.capacity=capacity}; @@ -640,6 +678,23 @@ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,ui return vfs_read_mount_table(state->ns,&state->root,state->mountinfo,offset,buffer,capacity,read); } +/** @brief Commit a namespace control against its captured scope and authority. + * @param value Borrowed open capture, independent of subsequent PID reuse. + * @param offset Byte position. @param buffer Validated input bytes. + * @param length Byte count. @param written Required count output, cleared. + * @return Namespace status, or EOPNOTSUPP to request the live stateless + * control provider. Execution ownership serializes map/policy publication. + */ +int proc_file_write(void *value,uint64_t offset,const void *buffer,uint32_t length,uint32_t *written) +{ + if (!written) return -EINVAL; + *written = 0; + struct proc_open_view *state = value; + if (!state || !state->namespace_control) return -EOPNOTSUPP; + return user_namespace_file_write(&state->namespace_file, sched_current_task(), + offset, buffer, length, written); +} + /** @brief Report mount graph readiness for one captured open description. * @param value Borrowed capture, including non-mount generated files. * @param events Requested poll bits. @param consume Acknowledge graph changes. @@ -664,12 +719,18 @@ bool proc_file_poll(void *value,short events,bool consume,uint64_t *generation,s /** @brief Release an open view after the final shared OFD reference. * @param value Owned optional captured state; NULL is ignored. - * Drops the retained viewing root and graph, even if the target already exited. + * Drops the retained namespace credentials, viewing root and graph, even if + * the target already exited. * Caller holds execution ownership without a graph, scheduler or module lock. */ void proc_file_close(void *value) { struct proc_open_view *state=value;if(!state)return; + if (state->namespace_control) { + user_namespace_file_close(&state->namespace_file); + kernel_free(state); + return; + } if (state->memory) { proc_memory_close(state->memory); kernel_free(state); return; } if (state->score_valid) { kernel_free(state); return; } #ifdef CONFIG_LOCK_STAT @@ -1087,6 +1148,7 @@ int proc_lookup(const char *path, struct storage_node *out) if ((kind == 2 || kind == 3) && file && (proc_text_eq(file, "stat") || proc_text_eq(file, "comm") || proc_text_eq(file, "cmdline") || proc_text_eq(file, "environ") || proc_text_eq(file, "status") || proc_text_eq(file, "oom_score") || proc_text_eq(file, "oom_score_adj") || + proc_text_eq(file, "uid_map") || proc_text_eq(file, "gid_map") || proc_text_eq(file, "setgroups") || proc_text_eq(file, "cgroup"))) { if (kind == 2 && !sched_find(pid)) return -2; if (out) { @@ -1122,6 +1184,19 @@ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, *out_read = 0; if (!path || (!buffer && length)) return -RELIEFOS_EINVAL; + struct task *namespace_task = NULL; + int namespace_kind = proc_userns_key(path, &namespace_task); + if (namespace_kind) { + if (!namespace_task || (namespace_task->flags & TASK_FLAG_RESOURCES_RELEASED)) return -ESRCH; + struct user_namespace_file file; + uint32_t ignored; + int rc = user_namespace_file_open(namespace_task->user_ns, sched_current_task(), + namespace_kind - 1, false, &file); + if (!rc) rc = user_namespace_file_read(&file, offset, buffer, length, + out_read ? out_read : &ignored); + user_namespace_file_close(&file); + return rc; + } if (proc_text_eq(path, PROCFS_BOOT_ID)) return proc_uuid_read(true, offset, buffer, length, out_read); if (proc_text_eq(path, PROCFS_UUID)) @@ -1451,7 +1526,8 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * "exe", "cwd", "root", "comm", "environ", "fd", "task", "fdinfo", "limits", "statm", "maps", "smaps", "smaps_rollup", "auxv", "io", - "oom_score", "oom_score_adj", "cgroup", "ns"}; + "oom_score", "oom_score_adj", "cgroup", "ns", + "uid_map", "gid_map", "setgroups"}; if (*offset == 11 && (proc_thread_path(path) || sched_task_tgid(sched_find(pid)) != pid || !__builtin_strncmp(path, "/proc/thread-self", 17))) ++*offset; @@ -1502,7 +1578,7 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * return 0; } -/** @brief Report synthetic proc metadata with ordinary per-task OOM ownership. +/** @brief Report synthetic proc metadata with per-task control ownership. * @param name Intrinsic key. @param node Retained generated inode. * @param value Required metadata output/proposal. @param write True for an * unsupported metadata mutation. @return Zero or negative errno. Execution @@ -1517,6 +1593,16 @@ int proc_control_permissions(const char *name, const struct storage_node *node, int rc = fs_virtual_permissions(name, node, value, write); #endif if (rc || write) return rc; + struct task *namespace_task = NULL; + int namespace_kind = proc_userns_key(name, &namespace_task); + if (namespace_kind) { + if (!namespace_task || (namespace_task->flags & TASK_FLAG_RESOURCES_RELEASED)) return -ESRCH; + value->mode = namespace_kind == USER_NAMESPACE_SETGROUPS + 1 ? 0600 : 0644; + if (!sched_task_mm(namespace_task)->nondumpable) { + value->uid = namespace_task->euid; + value->gid = namespace_task->egid; + } + } if (proc_inotify_key && proc_inotify_key(name)) value->mode = 0644; if (node->type == RELIEFOS_FS_TYPE_DIR || node->type == RELIEFOS_FS_TYPE_SYMLINK) { const char *leaf = NULL; @@ -1580,10 +1666,11 @@ static int proc_oom_parse(const void *buffer, uint32_t length, int *out) } /** @brief Recognize a live generated control committed by its write callback. - * @param name Intrinsic key. @return True for the OOM or configured lock control. + * @param name Intrinsic key. @return True for namespace, OOM, inotify or lock controls. */ bool proc_control_immediate(const char *name) { + if (proc_userns_key(name, NULL)) return true; if (proc_inotify_key && proc_inotify_key(name)) return true; if (proc_oom_key(name, NULL) == 1) return true; #ifdef CONFIG_LOCK_STAT @@ -1598,6 +1685,7 @@ bool proc_control_immediate(const char *name) */ int proc_control_truncate(const char *name, uint64_t length) { + if (proc_userns_key(name, NULL)) return length ? -EINVAL : 0; if (proc_inotify_key && proc_inotify_key(name)) return length ? -EINVAL : 0; if (proc_oom_key(name, NULL) == 1) return length ? -EINVAL : 0; #ifdef CONFIG_LOCK_STAT diff --git a/fs/vfs/pseudo.c b/fs/vfs/pseudo.c index 7c1eed3d..d2a18ffe 100644 --- a/fs/vfs/pseudo.c +++ b/fs/vfs/pseudo.c @@ -175,16 +175,38 @@ static int pseudo_node_write(void *value,struct storage_node *node,uint64_t offs if(!pseudo_key_live(context,key))return -ENOENT; return context->provider->write ? context->provider->write(key->name,offset,buffer,length,written) : -EROFS; } + +/** @brief Write captured controls independently of a retired external identity. + * @param value Pinned pseudo context. @param node Retained intrinsic key. + * @param state Borrowed capture. @param offset Byte position. + * @param buffer Validated input bytes. @param length Byte count. + * @param written Required output, cleared before dispatch. + * @return Provider status; absent or unsupported captured writes fall back to + * the live stateless provider. Execution-owned, without graph/module locks. + */ +static int pseudo_file_write(void *value,struct storage_node *node,void *state, + uint64_t offset,const void *buffer,uint32_t length,uint32_t *written) +{ + *written = 0; + struct pseudo_mount *context = value; + if (state && context->provider->write_open) { + if (!pseudo_key_find(context, node->entry_id)) return -EINVAL; + int rc = context->provider->write_open(state, offset, buffer, length, written); + if (rc != -EOPNOTSUPP) return rc; + } + return pseudo_node_write(value, node, offset, buffer, length, written); +} /** @brief Identify an immediate-commit control through its held provider. * @param path Borrowed valid path with a retained inode and provider context. - * @return True only for a live provider key admitting immediate commit. + * @return True for a retained provider key admitting immediate commit, + * including successful captured writes after its external identity retires. * Execution-owned; no lookup, allocation, or I/O. */ bool vfs_pseudo_immediate_control(const struct vfs_path *path) { if (!vfs_path_valid(path) || path->mount->ops->write != pseudo_node_write) return false; struct pseudo_mount *context = path->mount->context; struct pseudo_key *key = pseudo_key_find(context, path->dentry->node.entry_id); - return pseudo_key_live(context, key) && context->provider->immediate_write && + return key && context->provider->immediate_write && context->provider->immediate_write(key->name); } @@ -386,7 +408,7 @@ int vfs_pseudo_mount_new_with_state(const struct vfs_pseudo_provider *provider, if(!provider || !provider->root || provider->root[0]!='/' || !provider->lookup || (size && !initial) || size>SIZE_MAX-sizeof(struct pseudo_mount) || (provider->get_identity && (!provider->identity_alive || !provider->put_identity)) || - ((provider->open || provider->read_open || provider->close) && + ((provider->open || provider->read_open || provider->write_open || provider->close) && (!provider->open || !provider->read_open || !provider->close)))return -EINVAL; if(!try_module_get(provider->owner))return -ENODEV; static const struct vfs_backend_ops ops={.lookup=pseudo_node_lookup,.retain=pseudo_node_retain, @@ -394,7 +416,8 @@ int vfs_pseudo_mount_new_with_state(const struct vfs_pseudo_provider *provider, .follow_link=pseudo_node_follow,.stat_link=pseudo_node_stat_link,.destroy=pseudo_context_destroy, .read=pseudo_node_read,.write=pseudo_node_write,.truncate=pseudo_node_truncate, .readdir=pseudo_node_readdir,.permissions=pseudo_node_permissions, - .file_open=pseudo_file_open,.file_read=pseudo_file_read,.file_close=pseudo_file_close, + .file_open=pseudo_file_open,.file_read=pseudo_file_read,.file_write=pseudo_file_write, + .file_close=pseudo_file_close, .file_poll=pseudo_file_poll, .mount_flags=pseudo_mount_flags,.remount=pseudo_remount,.remount_options=pseudo_remount_options, .getattr=pseudo_node_getattr,.statfs=pseudo_node_statfs}; diff --git a/include/reliefnt/pseudo_fs.h b/include/reliefnt/pseudo_fs.h index 20419d99..d0535ae5 100644 --- a/include/reliefnt/pseudo_fs.h +++ b/include/reliefnt/pseudo_fs.h @@ -35,9 +35,11 @@ struct vfs_pseudo_provider { struct reliefos_permissions *value,bool write); /* Optional nonblocking per-open capture. An owned state is consumed by * close even on failed open; NULL means ordinary stateless reads. Reads - * through captured state remain valid after the inode identity retires. */ + * through captured state remain valid after the inode identity retires. + * write_open is optional; EOPNOTSUPP selects the live stateless write. */ int (*open)(const char *intrinsic,uint32_t flags,void **state); int (*read_open)(void *state,uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read); + int (*write_open)(void *state,uint64_t offset,const void *buffer,uint32_t length,uint32_t *written); void (*close)(void *state); /* Optional per-open poll state, valid after the inode identity retires. */ bool (*poll_open)(void *state,short events,bool consume,uint64_t *generation,short *ready); diff --git a/include/reliefnt/user_namespace.h b/include/reliefnt/user_namespace.h index 112a3720..0c7ff74e 100644 --- a/include/reliefnt/user_namespace.h +++ b/include/reliefnt/user_namespace.h @@ -5,6 +5,8 @@ #include #include +struct user_namespace_id_map; + /** @brief Reference-counted credential scope with immutable parent and owner. * NULL represents the initial namespace. IDs in task credentials remain global * kernel IDs. Each child retains its parent until its own final release. @@ -14,8 +16,97 @@ struct user_namespace { struct user_namespace *parent; uint32_t owner; uint32_t level; + struct user_namespace_id_map *uid_map; + struct user_namespace_id_map *gid_map; + bool setgroups_denied; + bool parent_could_setfcap; +}; + +enum user_namespace_file_kind { + USER_NAMESPACE_UID_MAP, + USER_NAMESPACE_GID_MAP, + USER_NAMESPACE_SETGROUPS, }; +/** @brief Owned proc control capture with immutable opener authority. + * Both namespace pointers hold references, including when they are equal. + * IDs use kernel-global values. No task or supplementary group pointer escapes. + */ +struct user_namespace_file { + struct user_namespace *target; + struct user_namespace *opener_ns; + uint32_t euid; + uint32_t egid; + uint64_t capabilities; + enum user_namespace_file_kind kind; +}; + +/** @brief Convert one namespace-local UID or GID to a global kernel ID. + * @param ns Borrowed live namespace, NULL for the initial identity mapping. + * @param group Select the GID mapping. @param id Local ID. + * @return Global ID, or UINT32_MAX for an unmapped or invalid ID. + * Allocation-free acquire of the immutable map, safe under scheduler_lock. + */ +uint32_t user_namespace_id_to_kernel(const struct user_namespace *ns, bool group, uint32_t id); + +/** @brief Convert one global kernel UID or GID into a namespace-local ID. + * @param ns Borrowed live namespace, NULL for the initial identity mapping. + * @param group Select the GID mapping. @param id Global kernel ID. + * @return Local ID, or UINT32_MAX for an unmapped or invalid ID. + * Allocation-free acquire of the immutable map, safe under scheduler_lock. + */ +uint32_t user_namespace_id_from_kernel(const struct user_namespace *ns, bool group, uint32_t id); + +/** @brief Test whether setgroups can run in a live namespace. + * @param ns Borrowed namespace, NULL for the initial namespace. + * @return True when a GID map exists and setgroups has not been denied. + * Allocation-free acquire loads only. The caller checks CAP_SETGID separately. + */ +bool user_namespace_may_setgroups(const struct user_namespace *ns); + +/** @brief Capture references and credentials for a proc namespace control. + * @param target Borrowed namespace to retain, NULL for the initial namespace. + * @param opener Borrowed execution-owned task, required. + * @param kind Control selector. @param write Whether opened with write access. + * @param out Required empty capture, cleared on failure. + * @return Zero, -EINVAL, or -EACCES when setgroups lacks target CAP_SYS_ADMIN. + * Execution ownership required. No task pointer or user memory is retained. + */ +int user_namespace_file_open(struct user_namespace *target, const struct task *opener, + enum user_namespace_file_kind kind, bool write, + struct user_namespace_file *out); + +/** @brief Render a live control through its retained namespace and viewer. + * @param file Borrowed successful capture. @param offset Byte position. + * @param buffer Writable kernel buffer, nullable at zero capacity. + * @param capacity Maximum bytes. @param read Required actual count output. + * @return Zero or -EINVAL. Execution ownership serializes control publication. + * Reads survive target exit and never resolve a PID or transfer ownership. + */ +int user_namespace_file_read(const struct user_namespace_file *file, uint64_t offset, + void *buffer, uint32_t capacity, uint32_t *read); + +/** @brief Commit a one-shot UID/GID map or irreversible setgroups policy. + * @param file Borrowed successful writable control capture. + * @param writer Borrowed current execution-owned task, required. + * @param offset Required zero position. @param buffer Validated input bytes. + * @param length Input size, below one page for maps and eight for setgroups. + * @param written Required actual count output, zero on failure. + * @return Zero or negative errno. Parent authority requires both current and + * opener credentials, with the Linux single-ID owner exception. Invalid, denied + * and OOM writes leave all maps and policy unchanged. The sole execution writer + * serializes commits without holding scheduler_lock or a provider spinlock. + */ +int user_namespace_file_write(const struct user_namespace_file *file, const struct task *writer, + uint64_t offset, const void *buffer, uint32_t length, + uint32_t *written); + +/** @brief Release both namespace references held by an initialized capture. + * @param file Owned capture, nullable. Clears it after release. + * Execution-owned final close, with no user access, I/O or scheduler lock. + */ +void user_namespace_file_close(struct user_namespace_file *file); + /** @brief Allocate a child credential scope without changing its creator. * @param creator Execution-owned source credentials, required. * @param out Empty output receiving one owned reference, NULL on failure. @@ -51,7 +142,9 @@ static inline uint64_t task_initial_capabilities(const struct task *task) } /** @brief Authorize a capability in the exact owning user namespace. - * @param task Borrowed execution-owned caller, nullable. + * @param caller_ns Retained caller scope, NULL for the initial namespace. + * @param euid Global effective UID of the stable caller credentials. + * @param capabilities Effective capability mask from those credentials. * @param ns Borrowed target scope, NULL selects the initial namespace. * @param capability Linux capability index. * @return True for a scoped effective capability or ownership of a child @@ -59,18 +152,33 @@ static inline uint64_t task_initial_capabilities(const struct task *task) * nor siblings gain authority over an ancestor or each other. The caller * stabilizes both ancestry and credentials. No locks or references are taken. */ -static inline bool task_ns_capable(const struct task *task, - const struct user_namespace *ns, - unsigned capability) +static inline bool user_namespace_capable(const struct user_namespace *caller_ns, + uint32_t euid, uint64_t capabilities, + const struct user_namespace *ns, + unsigned capability) { - if (!task || capability > CAP_LAST_CAP) return false; + if (capability > CAP_LAST_CAP) return false; for (;;) { - if (task->user_ns == ns) - return (task->cap_effective & (UINT64_C(1) << capability)) != 0; + if (caller_ns == ns) + return (capabilities & (UINT64_C(1) << capability)) != 0; if (!ns) return false; - if (ns->parent == task->user_ns && ns->owner == task->euid) return true; + if (ns->parent == caller_ns && ns->owner == euid) return true; ns = ns->parent; } } +/** @brief Check live task authority through the same scoped credential rule. + * @param task Borrowed execution-owned credentials, nullable. + * @param ns Borrowed target scope, NULL for the initial namespace. + * @param capability Linux capability index. + * @return Scoped authorization, false for NULL credentials. No side effects. + */ +static inline bool task_ns_capable(const struct task *task, + const struct user_namespace *ns, + unsigned capability) +{ + return task && user_namespace_capable(task->user_ns, task->euid, + task->cap_effective, ns, capability); +} + #endif diff --git a/kernel/sched/user_namespace.c b/kernel/sched/user_namespace.c index 2afe961f..ae4689e1 100644 --- a/kernel/sched/user_namespace.c +++ b/kernel/sched/user_namespace.c @@ -1,8 +1,78 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include #include +#include #include +struct user_namespace_id_extent { + uint32_t first; + uint32_t lower_first; + uint32_t count; +}; + +/** @brief One-shot map whose lower IDs are always global after publication. */ +struct user_namespace_id_map { + uint32_t count; + struct user_namespace_id_extent extents[]; +}; + +/** @brief Acquire an immutable map while its owning namespace is retained. + * @param ns Borrowed noninitial namespace. @param group Select GID map. + * @return Borrowed complete map or NULL before its single publication. + */ +static const struct user_namespace_id_map *namespace_map(const struct user_namespace *ns, bool group) +{ + return __atomic_load_n(group ? &ns->gid_map : &ns->uid_map, __ATOMIC_ACQUIRE); +} + +/** @brief Translate a complete contiguous local range in a retained namespace. + * @param ns Borrowed namespace, nullable for initial identity. + * @param group Select GID map. @param first First local ID. @param count Range size. + * @return First global ID or UINT32_MAX for a hole, boundary or invalid range. + * No allocation or locks. A range must fit in a single parent extent. + */ +static uint32_t namespace_range_to_kernel(const struct user_namespace *ns, bool group, + uint32_t first, uint32_t count) +{ + if (!count || (uint64_t)first + count > UINT32_MAX) return UINT32_MAX; + if (!ns) return first; + const struct user_namespace_id_map *map = namespace_map(ns, group); + if (!map) return UINT32_MAX; + for (uint32_t i = 0; i < map->count; ++i) { + const struct user_namespace_id_extent *extent = &map->extents[i]; + if (first >= extent->first && (uint64_t)first + count <= (uint64_t)extent->first + extent->count) + return extent->lower_first + first - extent->first; + } + return UINT32_MAX; +} + +/** @copydoc user_namespace_id_to_kernel */ +uint32_t user_namespace_id_to_kernel(const struct user_namespace *ns, bool group, uint32_t id) +{ + return namespace_range_to_kernel(ns, group, id, 1); +} + +/** @copydoc user_namespace_id_from_kernel */ +uint32_t user_namespace_id_from_kernel(const struct user_namespace *ns, bool group, uint32_t id) +{ + if (!ns || id == UINT32_MAX) return id; + const struct user_namespace_id_map *map = namespace_map(ns, group); + if (!map) return UINT32_MAX; + for (uint32_t i = 0; i < map->count; ++i) { + const struct user_namespace_id_extent *extent = &map->extents[i]; + if (id >= extent->lower_first && id - extent->lower_first < extent->count) + return extent->first + id - extent->lower_first; + } + return UINT32_MAX; +} + +/** @copydoc user_namespace_may_setgroups */ +bool user_namespace_may_setgroups(const struct user_namespace *ns) +{ + return !ns || (namespace_map(ns, true) && + !__atomic_load_n(&ns->setgroups_denied, __ATOMIC_ACQUIRE)); +} + /** @copydoc user_namespace_get */ struct user_namespace *user_namespace_get(struct user_namespace *ns) { @@ -15,6 +85,8 @@ void user_namespace_put(struct user_namespace *ns) { while (ns && !__atomic_sub_fetch(&ns->references, 1, __ATOMIC_ACQ_REL)) { struct user_namespace *parent = ns->parent; + kernel_free(ns->uid_map); + kernel_free(ns->gid_map); kernel_free(ns); ns = parent; } @@ -32,7 +104,253 @@ int user_namespace_create(const struct task *creator, struct user_namespace **ou if (!ns) return -LINUX_ENOMEM; *ns = (struct user_namespace){.references = 1, .parent = user_namespace_get(creator->user_ns), - .owner = creator->euid, .level = level}; + .owner = creator->euid, .level = level, + .setgroups_denied = creator->user_ns && + __atomic_load_n(&creator->user_ns->setgroups_denied, __ATOMIC_ACQUIRE), + .parent_could_setfcap = task_ns_capable(creator, creator->user_ns, CAP_SETFCAP)}; *out = ns; return 0; } + +/** @copydoc user_namespace_file_open */ +int user_namespace_file_open(struct user_namespace *target, const struct task *opener, + enum user_namespace_file_kind kind, bool write, + struct user_namespace_file *out) +{ + if (!out) return -LINUX_EINVAL; + *out = (struct user_namespace_file){0}; + if (!opener || kind < USER_NAMESPACE_UID_MAP || kind > USER_NAMESPACE_SETGROUPS) + return -LINUX_EINVAL; + if (write && kind == USER_NAMESPACE_SETGROUPS && !task_ns_capable(opener, target, CAP_SYS_ADMIN)) + return -LINUX_EACCES; + *out = (struct user_namespace_file){.target = user_namespace_get(target), + .opener_ns = user_namespace_get(opener->user_ns), .euid = opener->euid, + .egid = opener->egid, .capabilities = opener->cap_effective, .kind = kind}; + return 0; +} + +/** @brief Emit the Linux ten-column decimal field without allocation. + * @param stream Borrowed byte-slice emitter. @param value Unsigned ID or count. + * @return None. Caller serializes map observation under execution ownership. + */ +static void namespace_emit_id(struct text_stream *stream, uint32_t value) +{ + unsigned width = 1; + for (uint32_t n = value; n >= 10; n /= 10) ++width; + for (; width < 10; ++width) text_string(stream, " "); + text_unsigned(stream, value); +} + +/** @copydoc user_namespace_file_read */ +int user_namespace_file_read(const struct user_namespace_file *file, uint64_t offset, + void *buffer, uint32_t capacity, uint32_t *read) +{ + if (!read) return -LINUX_EINVAL; + *read = 0; + if (!file || (!buffer && capacity)) return -LINUX_EINVAL; + struct text_stream stream = {.offset = offset, .buffer = buffer, .capacity = capacity}; + if (file->kind == USER_NAMESPACE_SETGROUPS) { + bool denied = file->target && __atomic_load_n(&file->target->setgroups_denied, __ATOMIC_ACQUIRE); + text_string(&stream, denied ? "deny\n" : "allow\n"); + } else { + bool group = file->kind == USER_NAMESPACE_GID_MAP; + const struct user_namespace_id_map *map = file->target ? namespace_map(file->target, group) : NULL; + const struct user_namespace *viewer = file->opener_ns; + if (viewer == file->target && viewer) viewer = viewer->parent; + uint32_t count = file->target ? (map ? map->count : 0) : 1; + for (uint32_t i = 0; i < count; ++i) { + struct user_namespace_id_extent extent = map ? map->extents[i] : + (struct user_namespace_id_extent){0, 0, UINT32_MAX}; + namespace_emit_id(&stream, extent.first); + text_string(&stream, " "); + namespace_emit_id(&stream, user_namespace_id_from_kernel(viewer, group, extent.lower_first)); + text_string(&stream, " "); + namespace_emit_id(&stream, extent.count); + text_string(&stream, "\n"); + } + } + *read = stream.written; + return 0; +} + +/** @brief Recognize ASCII whitespace in one map row or policy value. + * @param c Input byte. @return True for the six standard whitespace bytes. + */ +static bool namespace_space(unsigned char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; +} + +/** @brief Parse one unsigned decimal field inside a single bounded row. + * @param cursor In/out borrowed position. @param end Exclusive row end. + * @param out Required value output. @return Zero or -EINVAL on syntax/overflow. + */ +static int namespace_parse_id(const unsigned char **cursor, const unsigned char *end, uint32_t *out) +{ + const unsigned char *p = *cursor; + while (p < end && namespace_space(*p)) ++p; + if (p == end || *p < '0' || *p > '9') return -LINUX_EINVAL; + uint32_t value = 0; + do { + uint32_t digit = *p++ - '0'; + if (value > (UINT32_MAX - digit) / 10) return -LINUX_EINVAL; + value = value * 10 + digit; + } while (p < end && *p >= '0' && *p <= '9'); + *out = value; + *cursor = p; + return 0; +} + +/** @brief Parse independent local and parent ranges without publishing a map. + * @param bytes Borrowed validated bytes, possibly NUL terminated within length. + * @param length Exact write size. @param out Required owned candidate output. + * @return Zero, -EINVAL or -ENOMEM. Failed candidates are freed. No user access. + */ +static int namespace_parse_map(const void *bytes, uint32_t length, struct user_namespace_id_map **out) +{ + *out = NULL; + if (!length || length >= 4096) return -LINUX_EINVAL; + uint32_t capacity = length / 6 + 1; + if (capacity > 340) capacity = 340; + struct user_namespace_id_map *map = kernel_malloc(sizeof(*map) + capacity * sizeof(map->extents[0])); + if (!map) return -LINUX_ENOMEM; + map->count = 0; + const unsigned char *p = bytes, *end = p + length; + for (const unsigned char *q = p; q < end; ++q) { + if (!*q) { end = q; break; } + } + int rc = -LINUX_EINVAL; + while (p < end) { + if (map->count == capacity) goto fail; + const unsigned char *line_end = p; + while (line_end < end && *line_end != '\n') ++line_end; + struct user_namespace_id_extent extent; + if (namespace_parse_id(&p, line_end, &extent.first) || p == line_end || !namespace_space(*p) || + namespace_parse_id(&p, line_end, &extent.lower_first) || p == line_end || !namespace_space(*p) || + namespace_parse_id(&p, line_end, &extent.count)) goto fail; + while (p < line_end && namespace_space(*p)) ++p; + if (p != line_end || !extent.count || (uint64_t)extent.first + extent.count > UINT32_MAX || + (uint64_t)extent.lower_first + extent.count > UINT32_MAX) goto fail; + for (uint32_t i = 0; i < map->count; ++i) { + const struct user_namespace_id_extent *other = &map->extents[i]; + if (((uint64_t)extent.first < (uint64_t)other->first + other->count && + (uint64_t)other->first < (uint64_t)extent.first + extent.count) || + ((uint64_t)extent.lower_first < (uint64_t)other->lower_first + other->count && + (uint64_t)other->lower_first < (uint64_t)extent.lower_first + extent.count)) goto fail; + } + map->extents[map->count++] = extent; + p = line_end < end ? line_end + 1 : end; + } + if (!map->count) goto fail; + *out = map; + return 0; +fail: + kernel_free(map); + return rc; +} + +/** @brief Check captured opener authority over a retained namespace. + * @param file Borrowed successful capture. @param ns Borrowed target scope. + * @param capability Linux capability number. @return Scoped authorization. + */ +static bool namespace_file_capable(const struct user_namespace_file *file, + const struct user_namespace *ns, unsigned capability) +{ + return user_namespace_capable(file->opener_ns, file->euid, file->capabilities, ns, capability); +} + +/** @brief Authorize unconverted parent ranges against current and open credentials. + * @param file Borrowed capture. @param writer Execution-owned current task. + * @param map Parsed candidate with parent-local lower IDs. + * @return True for a safe map, false without changing any namespace state. + */ +static bool namespace_map_permitted(const struct user_namespace_file *file, const struct task *writer, + const struct user_namespace_id_map *map) +{ + const struct user_namespace *ns = file->target; + bool group = file->kind == USER_NAMESPACE_GID_MAP; + if (!group) { + for (uint32_t i = 0; i < map->count; ++i) { + if (!map->extents[i].lower_first && + !(file->opener_ns == ns ? ns->parent_could_setfcap : + namespace_file_capable(file, ns->parent, CAP_SETFCAP))) return false; + } + } + if (map->count == 1 && map->extents[0].count == 1 && ns->owner == file->euid) { + uint32_t id = user_namespace_id_to_kernel(ns->parent, group, map->extents[0].lower_first); + if (id != UINT32_MAX && (group ? + (__atomic_load_n(&ns->setgroups_denied, __ATOMIC_ACQUIRE) && id == file->egid) : + id == file->euid)) return true; + } + unsigned capability = group ? CAP_SETGID : CAP_SETUID; + return task_ns_capable(writer, ns->parent, capability) && + namespace_file_capable(file, ns->parent, capability); +} + +/** @brief Validate and commit a setgroups policy using opener-authorized state. + * @param file Borrowed capture. @param buffer Validated bounded input bytes. + * @param length Exact write count below eight. @return Zero or negative errno. + * The sole execution writer serializes this with GID map publication. + */ +static int namespace_write_setgroups(const struct user_namespace_file *file, const void *buffer, + uint32_t length) +{ + if (!length || length >= 8) return -LINUX_EINVAL; + const unsigned char *p = buffer; + uint32_t size = 0; + while (size < length && p[size]) ++size; + bool allow = size >= 5 && !__builtin_memcmp(p, "allow", 5); + uint32_t token = allow ? 5 : 4; + if (!allow && (size < 4 || __builtin_memcmp(p, "deny", 4))) return -LINUX_EINVAL; + for (uint32_t i = token; i < size; ++i) if (!namespace_space(p[i])) return -LINUX_EINVAL; + struct user_namespace *ns = file->target; + if (allow) return ns && __atomic_load_n(&ns->setgroups_denied, __ATOMIC_ACQUIRE) ? -LINUX_EPERM : 0; + if (!ns || namespace_map(ns, true)) return -LINUX_EPERM; + __atomic_store_n(&ns->setgroups_denied, true, __ATOMIC_RELEASE); + return 0; +} + +/** @copydoc user_namespace_file_write */ +int user_namespace_file_write(const struct user_namespace_file *file, const struct task *writer, + uint64_t offset, const void *buffer, uint32_t length, uint32_t *written) +{ + if (!written) return -LINUX_EINVAL; + *written = 0; + if (!file || !writer || (!buffer && length) || offset) return -LINUX_EINVAL; + if (file->kind == USER_NAMESPACE_SETGROUPS) { + int rc = namespace_write_setgroups(file, buffer, length); + if (!rc) *written = length; + return rc; + } + struct user_namespace *ns = file->target; + bool group = file->kind == USER_NAMESPACE_GID_MAP; + if (!ns || (file->opener_ns != ns && file->opener_ns != ns->parent)) return -LINUX_EPERM; + if (length >= 4096) return -LINUX_EINVAL; + if (namespace_map(ns, group) || !namespace_file_capable(file, ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; + struct user_namespace_id_map *map; + int rc = namespace_parse_map(buffer, length, &map); + if (rc) return rc; + rc = -LINUX_EPERM; + if (!namespace_map_permitted(file, writer, map)) goto fail; + for (uint32_t i = 0; i < map->count; ++i) { + struct user_namespace_id_extent *extent = &map->extents[i]; + uint32_t lower = namespace_range_to_kernel(ns->parent, group, extent->lower_first, extent->count); + if (lower == UINT32_MAX) goto fail; + extent->lower_first = lower; + } + __atomic_store_n(group ? &ns->gid_map : &ns->uid_map, map, __ATOMIC_RELEASE); + *written = length; + return 0; +fail: + kernel_free(map); + return rc; +} + +/** @copydoc user_namespace_file_close */ +void user_namespace_file_close(struct user_namespace_file *file) +{ + if (!file) return; + user_namespace_put(file->target); + user_namespace_put(file->opener_ns); + *file = (struct user_namespace_file){0}; +} diff --git a/tools/test_linux_inventory.py b/tools/test_linux_inventory.py index 298ed366..d9385b4f 100644 --- a/tools/test_linux_inventory.py +++ b/tools/test_linux_inventory.py @@ -12,7 +12,7 @@ def host(): '-Iinclude','-Iinclude','-Iinclude/uapi', '-Iinclude','tools/tests/linux_inventory_test.c','fs/vfs/mount_tree.c', 'fs/vfs/lookup_cache.c', 'fs/vfs/path.c','fs/vfs/mount_table.c','fs/vfs/file.c','fs/vfs/open.c','fs/vfs/pseudo.c', 'fs/vfs/attributes.c','fs/proc/mount.c','fs/nsfs/namespace.c','fs/proc/views.c','kernel/syscall/fd/proc.c','fs/vfs/exec_file.c', - 'fs/sysfs/mount.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','fs/security/access.c','-o',executable]) + 'fs/sysfs/mount.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','kernel/sched/user_namespace.c','fs/security/access.c','-o',executable]) run([executable]) if __name__ == "__main__": diff --git a/tools/test_lock_profile.py b/tools/test_lock_profile.py index 4b573a6a..57cfc689 100644 --- a/tools/test_lock_profile.py +++ b/tools/test_lock_profile.py @@ -23,7 +23,7 @@ binary = str(Path(directory) / "proc") sources = ["tools/tests/lock_profile_proc_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", - "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "fs/security/access.c"] + "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "fs/security/access.c"] if (ROOT / "kernel/sync/profile.c").exists(): sources.append("kernel/sync/profile.c") subprocess.run(["cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", @@ -51,6 +51,6 @@ "-Iinclude", "-Iinclude/uapi", "tools/tests/lock_profile_sync_io_test.c", "tools/tests/task8_host_stubs/writable_alias_model.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "tools/tests/task8_host_stubs/user_ram_unreached.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", - "kernel/sched/identity.c", "fs/security/access.c", "kernel/sync/profile.c", + "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "fs/security/access.c", "kernel/sync/profile.c", "-o", binary], cwd=ROOT, check=True) subprocess.run([binary], cwd=ROOT, check=True, timeout=10) diff --git a/tools/test_memory_reporting.py b/tools/test_memory_reporting.py index dc1ff647..2e6e90b8 100644 --- a/tools/test_memory_reporting.py +++ b/tools/test_memory_reporting.py @@ -38,7 +38,7 @@ def run_cases(output, cases): command = [clang, "-std=c11", "-O1", "-g", "-DCONFIG_SWAP=1", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude/uapi", - "tools/tests/memory_pressure_oom_test.c", "kernel/sched/identity.c", + "tools/tests/memory_pressure_oom_test.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/sched/oom.c", "mm/reclaim/oom.c", "mm/reclaim/stats.c", "-o", binary] if run(command): return 1 @@ -74,7 +74,7 @@ def run_cases(output, cases): "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", - "kernel/sched/identity.c", "kernel/sched/oom.c", "fs/security/access.c", + "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/sched/oom.c", "fs/security/access.c", "fs/proc/memory.c", "mm/reclaim/stats.c", "mm/reclaim/oom.c"] proc_command = [clang, "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", diff --git a/tools/test_procfs.py b/tools/test_procfs.py index 10c6ab3e..8f165fd8 100644 --- a/tools/test_procfs.py +++ b/tools/test_procfs.py @@ -20,7 +20,8 @@ def test_real_procfs_directory_lookup_and_enumeration(self): "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", - "kernel/sched/identity.c", "fs/security/access.c", "-o", executable], + "kernel/sched/identity.c", "kernel/sched/user_namespace.c", + "fs/security/access.c", "-o", executable], cwd=ROOT, check=True) subprocess.run([executable], check=True, timeout=10) diff --git a/tools/test_rootfs.py b/tools/test_rootfs.py index 12aeb635..7a1cdf17 100644 --- a/tools/test_rootfs.py +++ b/tools/test_rootfs.py @@ -18,7 +18,7 @@ def test_kernel_modules(self): # mounts as well as its original directory contract. extra = (["fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", - "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", + "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "fs/security/access.c"] if name in ("procfs_directories", "rootfs_paths") else []) if name in ("linux_permissions", "chroot_paths"): extra = ['fs/vfs/mount_tree.c', 'fs/vfs/lookup_cache.c', 'fs/vfs/mount_table.c', 'fs/vfs/path.c', 'fs/vfs/dentry.c', 'fs/vfs/file.c', 'fs/vfs/open.c', 'fs/vfs/attributes.c', 'fs/vfs/mutation.c', 'fs/security/access.c', 'kernel/syscall/fs/create.c', 'kernel/syscall/fs/mutation.c'] diff --git a/tools/test_user_namespace.py b/tools/test_user_namespace.py new file mode 100644 index 00000000..102cbc8d --- /dev/null +++ b/tools/test_user_namespace.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +"""Exercise real namespace ID maps and captured proc-control authority.""" +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +with tempfile.TemporaryDirectory(prefix="reliefnt-user-namespace-") as directory: + executable = str(Path(directory) / "user-namespace") + subprocess.run([ + "cc", "-std=c11", "-O1", "-g", "-Wall", "-Wextra", "-Werror", + "-fsanitize=address,undefined", "-fno-sanitize-recover=all", + "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", + "tools/tests/user_namespace_test.c", "kernel/sched/user_namespace.c", + "-o", executable, + ], cwd=ROOT, check=True) + subprocess.run([executable], cwd=ROOT, check=True, timeout=30) diff --git a/tools/tests/Makefile b/tools/tests/Makefile index d717c4c9..70b5dd74 100644 --- a/tools/tests/Makefile +++ b/tools/tests/Makefile @@ -16,6 +16,7 @@ test-host-smoke: --suite fat_async_read --suite fat_read_split \ --suite squashfs --suite squashfs_boot \ --suite linux_pty --suite linux_resources --suite mount_backend --suite mount_namespace_task --suite cgroup_scheduler \ + --suite user_namespace \ --suite linux_socket_batches --suite ipv6_control \ --suite vdso_mapping --suite vdso_time diff --git a/tools/tests/host-suites.list b/tools/tests/host-suites.list index b06ceab5..8877603a 100644 --- a/tools/tests/host-suites.list +++ b/tools/tests/host-suites.list @@ -60,6 +60,7 @@ kthread tools/test_kthread.py linux_abi_contract tools/test_linux_abi_contract.py linux_audio tools/test_linux_audio.py abi pcm vma device params ioctl mmap control oss mixer linux_capabilities tools/test_linux_capabilities.py +user_namespace tools/test_user_namespace.py linux_descriptors tools/test_linux_descriptors.py linux_inventory tools/test_linux_inventory.py linux_ioctl_cloexec tools/test_linux_ioctl_cloexec.py diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index d3654802..83eb0b7c 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -7,6 +7,7 @@ #include "../../include/reliefnt/audio.h" #include #include +#include int sound_service_card_snapshot(uint32_t index, uint32_t *out_id, struct audio_card_identity *identity) { (void)index; (void)out_id; (void)identity; return -2; } @@ -962,6 +963,125 @@ static void test_proc_random_uuid(void) puts("PASS proc random UUID reads, stable boot ID and entropy retry"); } +/** @brief Exercise namespace controls through captured production proc/VFS handles. */ +static void test_proc_user_namespace_controls(void) +{ + unsigned before = proc_allocations; + uint32_t old_euid = current.euid, old_egid = current.egid; + uint32_t target_euid = foreign.euid, target_egid = foreign.egid; + uint64_t old_caps = current.cap_effective; + bool target_nondumpable = sched_task_mm(&foreign)->nondumpable; + current.euid = current.egid = 1000; + current.cap_effective = UINT64_MAX; + foreign.euid = foreign.egid = 2000; + sched_task_mm(&foreign)->nondumpable = false; + expose_foreign = true; + assert(!current.user_ns && !foreign.user_ns); + assert(!user_namespace_create(¤t, &foreign.user_ns)); + struct user_namespace *original = foreign.user_ns; + + struct vfs_mount *mount = NULL; + struct vfs_namespace ns = {0}; + struct vfs_path root = {0}, paths[3] = {0}, fresh = {0}; + struct vfs_open_file *opened[3] = {0}, *denied = NULL; + assert(!proc_create_vfs_mount(&mount) && !vfs_namespace_init(&ns, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns, &root)); + const char *names[] = {"43/uid_map", "43/gid_map", "43/task/43/setgroups"}; + struct linux_stat_abi st; + uint32_t got, written; + char text[160] = {0}; + for (unsigned i = 0; i < 3; ++i) { + assert(!vfs_path_lookup(&ns, &root, &root, names[i], 0, &paths[i])); + assert(!vfs_path_stat(&paths[i], &st)); + assert(st.st_mode == (LINUX_S_IFREG | (i == 2 ? 0600 : 0644))); + assert(st.st_uid == 2000 && st.st_gid == 2000); + assert(!vfs_path_truncate(&paths[i], 0)); + assert(vfs_path_truncate(&paths[i], 1) == -EINVAL); + unsigned allocations = proc_allocations; + uint32_t references = original->references; + for (int budget = 0; budget < 2; ++budget) { + proc_allocation_budget = budget; + assert(vfs_file_open(&paths[i], LINUX_O_RDWR, &opened[i]) == -ENOMEM); + proc_allocation_budget = -1; + assert(!opened[i] && original->references == references); + assert(proc_allocations == allocations); + } + assert(!vfs_file_open(&paths[i], LINUX_O_RDWR, &opened[i]) && opened[i]); + } + sched_task_mm(&foreign)->nondumpable = true; + assert(!vfs_path_stat(&paths[0], &st) && !st.st_uid && !st.st_gid); + sched_task_mm(&foreign)->nondumpable = false; + assert(!vfs_file_read(opened[0], 0, text, sizeof(text), &got) && !got); + assert(!vfs_file_read(opened[2], 0, text, sizeof(text), &got) && got == 6 && + !memcmp(text, "allow\n", 6)); + assert(vfs_path_write(&paths[0], 0, "0 1000 2\n", 9, &written) == -EROFS && !written); + + /* A descriptor opened without authority cannot borrow later privilege. */ + current.euid = 1001; + current.cap_effective = 0; + assert(vfs_file_open(&paths[2], LINUX_O_WRONLY, &denied) == -EACCES && !denied); + assert(!vfs_file_open(&paths[0], LINUX_O_RDWR, &denied) && denied); + current.cap_effective = UINT64_MAX; + assert(vfs_file_write(denied, 0, "0 1000 2\n", 9, &written) == -EPERM && !written); + vfs_file_close(denied); + current.euid = 1000; + current.cap_effective = 0; + assert(vfs_file_write(opened[0], 0, "0 1000 2\n", 9, &written) == -EPERM && !written); + + /* Retire PID identity and replace its credentials before using old OFDs. */ + sched_task_identity_detach(&foreign); + foreign.user_ns = NULL; + user_namespace_put(original); + assert(original->references == 3); + assert(!user_namespace_create(¤t, &foreign.user_ns)); + assert(vfs_file_open(&paths[0], LINUX_O_RDONLY, &denied) == -ENOENT && !denied); + assert(!vfs_path_lookup(&ns, &root, &root, names[0], 0, &fresh)); + assert(!vfs_path_equal(&paths[0], &fresh)); + assert(!vfs_path_read(&fresh, 0, text, sizeof(text), &got) && !got); + assert(!vfs_file_write(opened[2], 0, "deny\n", 5, &written) && written == 5); + assert(!vfs_file_read(opened[2], 0, text, sizeof(text), &got) && got == 5 && + !memcmp(text, "deny\n", 5)); + assert(!vfs_path_sync_after_write(&paths[2], false)); + assert(!foreign.user_ns->setgroups_denied); + current.cap_effective = UINT64_MAX; + assert(!vfs_path_bind_remount(&root, MS_RDONLY)); + assert(vfs_file_write(opened[0], 0, "0 1000 2\n", 9, &written) == -EROFS && !written); + assert(!vfs_path_bind_remount(&root, 0)); + assert(!vfs_file_write(opened[0], 0, "0 1000 2\n", 9, &written) && written == 9); + assert(!vfs_file_write(opened[1], 0, "0 1000 2\n", 9, &written) && written == 9); + assert(!vfs_path_sync_after_write(&paths[0], false)); + assert(user_namespace_id_to_kernel(original, false, 1) == 1001); + assert(user_namespace_id_to_kernel(original, true, 1) == 1001); + assert(user_namespace_id_to_kernel(foreign.user_ns, false, 0) == UINT32_MAX); + assert(!vfs_file_read(opened[0], 0, text, sizeof(text), &got) && got == 33 && + !memcmp(text, " 0 1000 2\n", 33)); + assert(!vfs_file_read(opened[0], 11, text, 10, &got) && got == 10 && + !memcmp(text, " 1000", 10)); + assert(vfs_file_write(opened[0], 0, "5 1005 1\n", 9, &written) == -EPERM && !written); + assert(vfs_file_write(opened[2], 0, "allow\n", 6, &written) == -EPERM && !written); + + for (unsigned i = 0; i < 3; ++i) { + vfs_file_close(opened[i]); + vfs_path_put(&paths[i]); + } + vfs_path_put(&fresh); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns)); + user_namespace_put(foreign.user_ns); + foreign.user_ns = NULL; + sched_task_identity_detach(&foreign); + foreign.euid = target_euid; + foreign.egid = target_egid; + sched_task_mm(&foreign)->nondumpable = target_nondumpable; + expose_foreign = false; + current.euid = old_euid; + current.egid = old_egid; + current.cap_effective = old_caps; + assert(proc_allocations == before); + puts("PASS proc user namespace controls: captures, permissions, PID reuse, readonly and OOM"); +} + int main(void) { test_proc_random_uuid(); @@ -970,6 +1090,7 @@ int main(void) test_proc_mount_objects(); test_proc_mount_failures(); test_proc_mount_namespace_handles(); + test_proc_user_namespace_controls(); test_proc_mount_hidepid(); strcpy(current.path, "/usr/lib/reliefos/apps/procsys/procsys.elf"); struct storage_node node; @@ -1081,6 +1202,10 @@ int main(void) assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "oom_score_adj") && entry.type == RELIEFOS_FS_TYPE_FILE); assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "cgroup") && entry.type == RELIEFOS_FS_TYPE_FILE); assert(proc_readdir("/proc/42", &offset, &entry) == 1 && !strcmp(entry.name, "ns") && entry.type == RELIEFOS_FS_TYPE_DIR); + const char *namespace_controls[] = {"uid_map", "gid_map", "setgroups"}; + for (unsigned i = 0; i < 3; ++i) + assert(proc_readdir("/proc/42", &offset, &entry) == 1 && + !strcmp(entry.name, namespace_controls[i]) && entry.type == RELIEFOS_FS_TYPE_FILE); assert(proc_readdir("/proc/42", &offset, &entry) == 0); offset = 0; /* Anonymous descriptors must survive proc inode lookup during getdents. diff --git a/tools/tests/rootfs_uts_test.c b/tools/tests/rootfs_uts_test.c index 05a92ab2..92e9de4a 100644 --- a/tools/tests/rootfs_uts_test.c +++ b/tools/tests/rootfs_uts_test.c @@ -2,26 +2,25 @@ #include #include #include "../../kernel/init/uts.c" -static const char *config="test-host\n"; static unsigned locked; -static int read_error, lookup_error; void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) { (void)lock; assert(!locked); locked=1; *flags=0; } void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) { (void)lock; (void)flags; assert(locked); locked=0; } -int storage_read_node(const struct storage_node *node,uint64_t offset,void *out,uint32_t cap,uint32_t *got) -{ assert(!locked && !offset && node->size<=cap); memcpy(out,config,node->size); *got=node->size; return read_error; } int main(void) { char host[65],domain[65],full[64]; memset(full,'x',sizeof(full)); - assert(linux_uts_load_hostname()==0); linux_uts_names(host,domain); + linux_uts_names(host,domain); + assert(!strcmp(host,"reliefos") && !strcmp(domain,"(none)")); + assert(linux_uts_set("test-host",9,0)==0); linux_uts_names(host,domain); assert(!strcmp(host,"test-host") && !strcmp(domain,"(none)")); assert(linux_uts_set(full,64,0)==0); linux_uts_names(host,domain); assert(!memcmp(host,full,64) && !host[64]); assert(linux_uts_set(full,65,0)==-22); + assert(linux_uts_set(NULL,1,0)==-22); + linux_uts_names(host,domain); assert(!memcmp(host,full,64) && !host[64]); assert(linux_uts_set("abc",3,1)==0); linux_uts_names(host,domain); assert(!strcmp(domain,"abc")); assert(linux_uts_set(NULL,0,0)==0); linux_uts_names(host,domain); assert(!host[0]); - config="host\nsecond"; assert(linux_uts_load_hostname()==-22); - config="host\n"; read_error=-5; assert(linux_uts_load_hostname()==-5); - lookup_error=-2; assert(linux_uts_load_hostname()==0); - puts("PASS hostname initialization, shared UTS names, truncation, invalid configuration and I/O failure"); + assert(linux_uts_set(NULL,1,1)==-22); + linux_uts_names(host,domain); assert(!host[0] && !strcmp(domain,"abc")); + puts("PASS initial and shared UTS names, length boundaries and atomic invalid-input rejection"); } diff --git a/tools/tests/test-version.sh b/tools/tests/test-version.sh index 12955f33..b0c49f6e 100644 --- a/tools/tests/test-version.sh +++ b/tools/tests/test-version.sh @@ -45,6 +45,6 @@ ${HOSTCC:-cc} -std=c11 -O1 -g -fsanitize=address,undefined \ "$kernel/fs/vfs/file.c" "$kernel/fs/vfs/open.c" "$kernel/fs/vfs/pseudo.c" \ "$kernel/fs/vfs/attributes.c" "$kernel/fs/proc/mount.c" "$kernel/fs/nsfs/namespace.c" "$kernel/fs/proc/views.c" \ "$kernel/kernel/syscall/fd/proc.c" "$kernel/fs/vfs/exec_file.c" \ - "$kernel/kernel/sched/identity.c" "$kernel/fs/security/access.c" -o "$work/procfs" + "$kernel/kernel/sched/identity.c" "$kernel/kernel/sched/user_namespace.c" "$kernel/fs/security/access.c" -o "$work/procfs" "$work/procfs" printf 'kernel version renderer: base, suffixes, ABI, no-op, reset, validation and procfs passed\n' diff --git a/tools/tests/user_namespace_test.c b/tools/tests/user_namespace_test.c new file mode 100644 index 00000000..f6a8d6ae --- /dev/null +++ b/tools/tests/user_namespace_test.c @@ -0,0 +1,242 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include +#include +#include +#include +#include +#include + +#define ALL_CAPS ((UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1) + +static unsigned allocations; +static bool fail_allocation; + +void *kernel_malloc(size_t size) +{ + if (fail_allocation) return NULL; + void *memory = malloc(size); + if (memory) ++allocations; + return memory; +} + +void kernel_free(void *memory) +{ + if (memory) { assert(allocations); --allocations; } + free(memory); +} + +static struct task root = {.cap_effective = ALL_CAPS}; + +static struct user_namespace *create(const struct task *creator) +{ + struct user_namespace *ns = NULL; + assert(!user_namespace_create(creator, &ns) && ns); + return ns; +} + +static struct user_namespace_file open_control(struct user_namespace *ns, + const struct task *opener, + enum user_namespace_file_kind kind) +{ + struct user_namespace_file file; + assert(!user_namespace_file_open(ns, opener, kind, true, &file)); + return file; +} + +static int write_text(const struct user_namespace_file *file, const struct task *writer, + const char *text) +{ + uint32_t length = strlen(text), written = 99; + int rc = user_namespace_file_write(file, writer, 0, text, length, &written); + assert(written == (rc ? 0 : length)); + return rc; +} + +static void expect_text(const struct user_namespace_file *file, const char *expected) +{ + char text[128] = {0}; uint32_t count; + assert(!user_namespace_file_read(file, 0, text, sizeof(text) - 1, &count)); + assert(count == strlen(expected) && !strcmp(text, expected)); + for (uint32_t i = 0; i < count; ++i) { + char byte; + uint32_t n; + assert(!user_namespace_file_read(file, i, &byte, 1, &n) && n == 1); + assert(byte == expected[i]); + } + assert(!user_namespace_file_read(file, count, text, sizeof(text), &count) && !count); +} + +/* Missing publication, inverse translation or preserved open references fail here. */ +static void test_maps_and_lifetime(void) +{ + struct user_namespace_file initial = open_control(NULL, &root, USER_NAMESPACE_UID_MAP); + expect_text(&initial, " 0 0 4294967295\n"); + assert(write_text(&initial, &root, "0 0 1\n") == -LINUX_EPERM); + user_namespace_file_close(&initial); + assert(user_namespace_id_to_kernel(NULL, false, 1234) == 1234); + assert(user_namespace_id_from_kernel(NULL, true, UINT32_MAX) == UINT32_MAX); + assert(user_namespace_may_setgroups(NULL)); + + struct user_namespace *ns = create(&root); + assert(user_namespace_id_to_kernel(ns, false, 0) == UINT32_MAX); + assert(!user_namespace_may_setgroups(ns)); + struct user_namespace_file uid = open_control(ns, &root, USER_NAMESPACE_UID_MAP); + struct user_namespace_file gid = open_control(ns, &root, USER_NAMESPACE_GID_MAP); + expect_text(&uid, ""); + assert(!write_text(&uid, &root, "10 1000 3\n0 500 2\n")); + assert(user_namespace_id_to_kernel(ns, false, 0) == 500); + assert(user_namespace_id_to_kernel(ns, false, 1) == 501); + assert(user_namespace_id_to_kernel(ns, false, 2) == UINT32_MAX); + assert(user_namespace_id_to_kernel(ns, false, 12) == 1002); + assert(user_namespace_id_from_kernel(ns, false, 1001) == 11); + assert(user_namespace_id_from_kernel(ns, false, 502) == UINT32_MAX); + expect_text(&uid, " 10 1000 3\n 0 500 2\n"); + assert(write_text(&uid, &root, "0 42 1\n") == -LINUX_EPERM); + assert(!write_text(&gid, &root, "0 900 100\n")); + assert(user_namespace_may_setgroups(ns)); + assert(user_namespace_id_to_kernel(ns, true, 12) == 912); + struct user_namespace_file policy = open_control(ns, &root, USER_NAMESPACE_SETGROUPS); + assert(write_text(&policy, &root, "deny\n") == -LINUX_EPERM); + expect_text(&policy, "allow\n"); + user_namespace_put(ns); + expect_text(&uid, " 10 1000 3\n 0 500 2\n"); + user_namespace_file_close(&uid); + user_namespace_file_close(&gid); + user_namespace_file_close(&policy); + assert(!allocations); +} + +/* Invalid or OOM writes must neither consume the one-shot map nor publish IDs. */ +static void test_validation_and_rollback(void) +{ + static const char *invalid[] = { + "", "\n", "0 0 0", "0 0", "0 0 1x", "0 0 1\nx", "-1 0 1", "+0 0 1", + "4294967295 0 1", "0 4294967295 1", "4294967294 0 2", "0 4294967294 2", + "0 0 4294967296", "0 0 1\n0 5 1", "0 0 2\n3 1 1", "0 0 1\n\n", + "0 0 1\n ", "0 0 1 2", "0x1 0 1", "0 0 1\rjunk", "0 0 1\n1 1 0", + }; + struct user_namespace *ns = create(&root); + struct user_namespace_file file = open_control(ns, &root, USER_NAMESPACE_UID_MAP); + for (unsigned i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { + assert(write_text(&file, &root, invalid[i]) == -LINUX_EINVAL); + assert(user_namespace_id_to_kernel(ns, false, 0) == UINT32_MAX); + } + const char embedded[] = {0,'0',' ','0',' ','1'}; + uint32_t n = 9; + assert(user_namespace_file_write(&file, &root, 0, embedded, sizeof(embedded), &n) == -LINUX_EINVAL && !n); + char page[4096]; memset(page, ' ', sizeof(page)); + assert(user_namespace_file_write(&file, &root, 0, page, sizeof(page), &n) == -LINUX_EINVAL && !n); + assert(user_namespace_file_write(&file, &root, 1, "0 0 1", 5, &n) == -LINUX_EINVAL && !n); + fail_allocation = true; + assert(write_text(&file, &root, "0 0 1") == -LINUX_ENOMEM); + fail_allocation = false; + assert(!write_text(&file, &root, "\t0 0 4294967295 \r\n")); + assert(user_namespace_id_to_kernel(ns, false, 4294967294u) == 4294967294u); + assert(user_namespace_id_to_kernel(ns, false, UINT32_MAX) == UINT32_MAX); + user_namespace_file_close(&file); user_namespace_put(ns); + + ns = create(&root); + file = open_control(ns, &root, USER_NAMESPACE_GID_MAP); + char lines[4096]; size_t length = 0; + for (unsigned i = 0; i <= 340; ++i) length += sprintf(lines + length, "%u %u 1\n", i, i); + assert(write_text(&file, &root, lines) == -LINUX_EINVAL); + char *last = strrchr(lines, '\n'); + *last = 0; last = strrchr(lines, '\n'); last[1] = 0; + assert(!write_text(&file, &root, lines)); + assert(user_namespace_id_from_kernel(ns, true, 339) == 339); + assert(user_namespace_id_from_kernel(ns, true, 340) == UINT32_MAX); + user_namespace_file_close(&file); user_namespace_put(ns); + assert(!allocations); +} + +/* Opener credentials, parent authority and irreversible deny prevent ID escalation. */ +static void test_owner_authority(void) +{ + struct task owner = {.euid = 1000, .egid = 2000}; + struct user_namespace *ns = create(&owner); + struct user_namespace_file uid = open_control(ns, &owner, USER_NAMESPACE_UID_MAP); + struct user_namespace_file gid = open_control(ns, &owner, USER_NAMESPACE_GID_MAP); + struct user_namespace_file policy = open_control(ns, &owner, USER_NAMESPACE_SETGROUPS); + assert(write_text(&uid, &root, "0 0 1\n") == -LINUX_EPERM); + assert(write_text(&uid, &root, "0 1000 2\n") == -LINUX_EPERM); + assert(write_text(&gid, &owner, "0 2000 1\n") == -LINUX_EPERM); + assert(write_text(&policy, &owner, " deny\n") == -LINUX_EINVAL); + assert(write_text(&policy, &owner, "denyxxx") == -LINUX_EINVAL); + assert(write_text(&policy, &owner, "deny\nxxx") == -LINUX_EINVAL); + assert(!write_text(&policy, &owner, "deny\n")); + assert(write_text(&policy, &root, "allow") == -LINUX_EPERM); + owner.euid = 3000; owner.egid = 4000; + assert(!write_text(&uid, &owner, "0 1000 1\n")); + assert(!write_text(&gid, &owner, "0 2000 1\n")); + assert(!user_namespace_may_setgroups(ns)); + expect_text(&policy, "deny\n"); + struct task member = {.user_ns = ns, .euid = 1000, .egid = 2000, .cap_effective = ALL_CAPS}; + struct user_namespace_file own = open_control(ns, &member, USER_NAMESPACE_UID_MAP); + expect_text(&own, " 0 1000 1\n"); + struct user_namespace *nested = create(&member); + struct user_namespace_file inherited = open_control(nested, &member, USER_NAMESPACE_SETGROUPS); + expect_text(&inherited, "deny\n"); + assert(write_text(&inherited, &member, "allow\n") == -LINUX_EPERM); + user_namespace_file_close(&inherited); user_namespace_put(nested); + user_namespace_file_close(&own); user_namespace_file_close(&policy); + user_namespace_file_close(&uid); user_namespace_file_close(&gid); user_namespace_put(ns); + assert(!allocations); + + owner = (struct task){.euid = 1000, .egid = 1000}; + ns = create(&owner); + struct task unprivileged = {.euid = 2000}; + assert(user_namespace_file_open(ns, &unprivileged, USER_NAMESPACE_SETGROUPS, true, &policy) == -LINUX_EACCES); + uid = open_control(ns, &root, USER_NAMESPACE_UID_MAP); + assert(write_text(&uid, &unprivileged, "0 1234 2\n") == -LINUX_EPERM); + assert(!write_text(&uid, &root, "0 1234 2\n")); + user_namespace_file_close(&uid); user_namespace_put(ns); + assert(!allocations); +} + +/* Parent holes, namespace mismatch and loss of CAP_SETFCAP must reject publication. */ +static void test_nested_maps_and_root_guard(void) +{ + struct user_namespace *parent = create(&root); + struct user_namespace_file file = open_control(parent, &root, USER_NAMESPACE_UID_MAP); + assert(!write_text(&file, &root, "0 1000 2\n5 2000 3\n")); + user_namespace_file_close(&file); + struct task member = {.user_ns = parent, .euid = 1000, .egid = 2000, .cap_effective = ALL_CAPS}; + struct user_namespace *child = create(&member); + file = open_control(child, &member, USER_NAMESPACE_UID_MAP); + assert(write_text(&file, &member, "0 1 2\n") == -LINUX_EPERM); + struct user_namespace_file ancestor = open_control(child, &root, USER_NAMESPACE_UID_MAP); + assert(write_text(&ancestor, &root, "0 0 1\n") == -LINUX_EPERM); + user_namespace_file_close(&ancestor); + assert(!write_text(&file, &member, "0 5 3\n10 0 1\n")); + assert(user_namespace_id_to_kernel(child, false, 2) == 2002); + assert(user_namespace_id_from_kernel(child, false, 1000) == 10); + expect_text(&file, " 0 5 3\n 10 0 1\n"); + struct task own_member = {.user_ns = child, .euid = 2000, .cap_effective = ALL_CAPS}; + struct user_namespace_file own = open_control(child, &own_member, USER_NAMESPACE_UID_MAP); + expect_text(&own, " 0 5 3\n 10 0 1\n"); + user_namespace_file_close(&own); user_namespace_file_close(&file); + user_namespace_put(child); user_namespace_put(parent); + + struct task limited = {.cap_effective = ALL_CAPS & ~(UINT64_C(1) << CAP_SETFCAP)}; + child = create(&limited); + member = (struct task){.user_ns = child, .cap_effective = ALL_CAPS}; + file = open_control(child, &member, USER_NAMESPACE_UID_MAP); + assert(write_text(&file, &member, "0 0 1\n") == -LINUX_EPERM); + assert(write_text(&file, &member, "0 1 1\n") == -LINUX_EPERM); + user_namespace_file_close(&file); + file = open_control(child, &limited, USER_NAMESPACE_UID_MAP); + assert(write_text(&file, &root, "0 0 1\n") == -LINUX_EPERM); + assert(!write_text(&file, &limited, "0 42 1\n")); + user_namespace_file_close(&file); user_namespace_put(child); + assert(!allocations); +} + +int main(void) +{ + test_maps_and_lifetime(); + test_validation_and_rollback(); + test_owner_authority(); + test_nested_maps_and_root_guard(); + puts("PASS user namespace ID maps, owner/captured authority, deny, nesting, bounds and OOM"); + return 0; +} From d32fcbf2678adddcebc35d78ab728d9ed0372969 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Sun, 29 Nov 2026 23:55:48 +0800 Subject: [PATCH 56/97] feat(userns): translate identity syscalls and supplementary groups --- Documentation/core-api/mount-namespaces.rst | 18 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 43 +++- .../LC_MESSAGES/core-api/mount-namespaces.po | 35 ++- fs/security/access.c | 15 +- include/reliefnt/permissions.h | 18 ++ include/reliefnt/syscall.h | 9 + include/reliefnt/user_namespace.h | 9 + kernel/sched/user_namespace.c | 8 + kernel/syscall/fs/legacy_filesystem.c | 29 ++- kernel/syscall/process/process.c | 60 +++-- tools/storage_graph_test_sources.py | 1 + tools/test_linux_capabilities.py | 3 +- tools/test_linux_permissions.py | 2 +- tools/test_mount_backend.py | 2 +- tools/tests/capability_test.c | 243 +++++++++++++++++- tools/tests/storage_mkdir_mount_test.c | 4 + 16 files changed, 454 insertions(+), 45 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index a3e0e0ed..569cfea9 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -112,5 +112,21 @@ proc 控制文件在打开时保留目标空间、打开者空间及其标量凭 策略提交由现有独占执行权串行化,候选解析、权限和分配失败均不发布状态;最后 一个空间引用释放映射并逐级释放父空间。用户接口见 :doc:`../userspace-api/procfs`。 +身份与附加组 +============ + +``getuid/geteuid/getgid/getegid``、``getresuid/getresgid`` 和 ``getgroups`` +使用调用方用户空间的映射输出 ID,未映射的结果为 65534。``setuid/setgid``、 +``setreuid/setregid`` 与 ``setresuid/setresgid`` 先将所有输入转换为全局 ID, +任一输入未映射时返回 ``EINVAL``。可选输入的 ``UINT32_MAX`` 保留不修改语义。 +``setfsuid/setfsgid`` 始终返回修改前的本地文件系统 ID,拒绝未映射的请求。 + +身份切换按当前空间的 UID 0 执行能力与 securebits 规则。任务身份、文件系统 +权限比较及进程数量统计继续使用全局 ID。``setgroups`` 要求调用方在所属空间 +具有 ``CAP_SETGID``,已经发布 GID 映射且没有禁止该操作。输入全部转换成功后, +一次发布按全局 GID 排序的不可变列表,保留重复项。映射、用户内存或分配错误 +保留旧列表。内部 ``task_groups_set()`` 继续接收全局 ID。 + 内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 -``EINVAL``;用户态 ID 边界转换、创建入口和用户空间句柄仍待接入。 +``EINVAL``。exec、文件元数据等其余用户态 ID 边界、创建入口和用户空间句柄 +仍待接入。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index f95feaac..bd26c7af 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -227,11 +227,44 @@ msgstr "" " last scope reference frees its maps and releases parent references " "recursively. See :doc:`../userspace-api/procfs` for the user interface." +msgid "身份与附加组" +msgstr "Identity and supplementary groups" + +msgid "" +"``getuid/geteuid/getgid/getegid``、``getresuid/getresgid`` 和 ``getgroups``" +" 使用调用方用户空间的映射输出 ID,未映射的结果为 65534。``setuid/setgid``、 ``setreuid/setregid``" +" 与 ``setresuid/setresgid`` 先将所有输入转换为全局 ID, 任一输入未映射时返回 ``EINVAL``。可选输入的 " +"``UINT32_MAX`` 保留不修改语义。 ``setfsuid/setfsgid`` 始终返回修改前的本地文件系统 ID,拒绝未映射的请求。" +msgstr "" +"``getuid/geteuid/getgid/getegid``, ``getresuid/getresgid`` and " +"``getgroups`` map output IDs into the caller’s user namespace, using " +"65534 for unmapped results. ``setuid/setgid``, ``setreuid/setregid`` and " +"``setresuid/setresgid`` convert every input to a global ID before " +"applying the change. Any unmapped input returns ``EINVAL``. Optional " +"``UINT32_MAX`` operands retain their no-change meaning. " +"``setfsuid/setfsgid`` always return the previous local filesystem ID and " +"reject unmapped requests." + +msgid "" +"身份切换按当前空间的 UID 0 执行能力与 securebits 规则。任务身份、文件系统 权限比较及进程数量统计继续使用全局 " +"ID。``setgroups`` 要求调用方在所属空间 具有 ``CAP_SETGID``,已经发布 GID " +"映射且没有禁止该操作。输入全部转换成功后, 一次发布按全局 GID 排序的不可变列表,保留重复项。映射、用户内存或分配错误 保留旧列表。内部 " +"``task_groups_set()`` 继续接收全局 ID。" +msgstr "" +"Identity changes apply capability and securebits rules using UID 0 in the" +" current namespace. Task credentials, filesystem permission comparisons " +"and process-count accounting use global IDs. ``setgroups`` requires " +"``CAP_SETGID`` in the caller’s own namespace, a published GID map and an " +"allowed setgroups policy. After every input is mapped successfully, a " +"single immutable list sorted by global GID is published with duplicates " +"retained. Mapping, user-memory and allocation errors preserve the old " +"list. The internal ``task_groups_set()`` interface accepts global IDs." + msgid "" -"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``;用户态 ID " -"边界转换、创建入口和用户空间句柄仍待接入。" +"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 " +"``EINVAL``。exec、文件元数据等其余用户态 ID 边界、创建入口和用户空间句柄 仍待接入。" msgstr "" "Internal allocation and reference interfaces are available. Userspace " -"``CLONE_NEWUSER`` currently returns ``EINVAL``. Userspace ID boundary " -"conversion, creation entry points and user-namespace handles remain " -"pending." +"``CLONE_NEWUSER`` currently returns ``EINVAL``. Remaining userspace ID " +"boundaries, including exec and file metadata, creation entry points and " +"user-namespace handles still await integration." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index e5b60d3b..7211cd9a 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -194,9 +194,38 @@ msgstr "" "方針の公開を直列化します。解析、権限検査、割り当ての失敗時は状態を保持します。空間の最後の参照を解放するとマップと親空間の参照を順次解放します。ユーザーインターフェースは" " :doc:`../userspace-api/procfs` を参照してください。" +msgid "身份与附加组" +msgstr "識別情報と補助グループ" + +msgid "" +"``getuid/geteuid/getgid/getegid``、``getresuid/getresgid`` 和 ``getgroups``" +" 使用调用方用户空间的映射输出 ID,未映射的结果为 65534。``setuid/setgid``、 ``setreuid/setregid``" +" 与 ``setresuid/setresgid`` 先将所有输入转换为全局 ID, 任一输入未映射时返回 ``EINVAL``。可选输入的 " +"``UINT32_MAX`` 保留不修改语义。 ``setfsuid/setfsgid`` 始终返回修改前的本地文件系统 ID,拒绝未映射的请求。" +msgstr "" +"``getuid/geteuid/getgid/getegid``、``getresuid/getresgid``、``getgroups`` " +"は呼び出し元のユーザー名前空間へ ID を変換して返し、未マッピングの結果には 65534 " +"を使います。``setuid/setgid``、``setreuid/setregid``、``setresuid/setresgid`` " +"は変更を適用する前にすべての入力をグローバル ID へ変換します。未マッピングの入力があれば ``EINVAL`` を返します。省略可能な入力の " +"``UINT32_MAX`` は変更しない指定です。``setfsuid/setfsgid`` は常に変更前のローカルなファイルシステム ID " +"を返し、未マッピングの要求を拒否します。" + +msgid "" +"身份切换按当前空间的 UID 0 执行能力与 securebits 规则。任务身份、文件系统 权限比较及进程数量统计继续使用全局 " +"ID。``setgroups`` 要求调用方在所属空间 具有 ``CAP_SETGID``,已经发布 GID " +"映射且没有禁止该操作。输入全部转换成功后, 一次发布按全局 GID 排序的不可变列表,保留重复项。映射、用户内存或分配错误 保留旧列表。内部 " +"``task_groups_set()`` 继续接收全局 ID。" +msgstr "" +"識別情報の変更では、現在の名前空間の UID 0 を基準に能力と securebits " +"の規則を適用します。タスクの資格情報、ファイルシステム権限の比較、プロセス数の集計にはグローバル ID を使います。``setgroups`` " +"には呼び出し元の名前空間の ``CAP_SETGID``、公開済みの GID マップ、操作を許可する setgroups " +"ポリシーが必要です。すべての入力の変換が成功してから、グローバル GID " +"順に並べた不変リストを一度に公開し、重複は保持します。マッピング、ユーザーメモリ、割り当てのエラー時には古いリストを保持します。内部の " +"``task_groups_set()`` はグローバル ID を受け取ります。" + msgid "" -"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``;用户态 ID " -"边界转换、创建入口和用户空间句柄仍待接入。" +"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 " +"``EINVAL``。exec、文件元数据等其余用户态 ID 边界、创建入口和用户空间句柄 仍待接入。" msgstr "" "カーネル内部の空間割り当てと参照インターフェースを提供します。現在、ユーザー空間の ``CLONE_NEWUSER`` は ``EINVAL`` " -"を返します。ユーザー向け ID 境界変換、作成入口、ユーザー名前空間ハンドルは今後の対応です。" +"を返します。exec やファイルメタデータなどの残りのユーザー空間 ID 境界、作成入口、ユーザー名前空間ハンドルの接続は今後の作業です。" diff --git a/fs/security/access.c b/fs/security/access.c index b1c22959..855dfe51 100644 --- a/fs/security/access.c +++ b/fs/security/access.c @@ -60,7 +60,15 @@ void task_groups_release(struct task *task) task_groups_put(groups); } +/** @copydoc task_groups_set */ int task_groups_set(struct task *task, const uint32_t *ids, uint32_t count) +{ + return task_groups_set_mapped(task, NULL, ids, count); +} + +/** @copydoc task_groups_set_mapped */ +int task_groups_set_mapped(struct task *task, const struct user_namespace *ns, + const uint32_t *ids, uint32_t count) { if (!task || count > 65536u) return -RELIEFOS_EINVAL; struct task_groups *groups = NULL; @@ -70,8 +78,11 @@ int task_groups_set(struct task *task, const uint32_t *ids, uint32_t count) groups->references = 1; groups->count = count; for (uint32_t i = 0; i < count; ++i) { - if (ids[i] == UINT32_MAX) { kernel_free(groups); return -RELIEFOS_EINVAL; } - groups->ids[i] = ids[i]; + uint32_t id; + __builtin_memcpy(&id, (const char *)ids + (size_t)i * sizeof(id), sizeof(id)); + id = user_namespace_id_to_kernel(ns, true, id); + if (id == UINT32_MAX) { kernel_free(groups); return -RELIEFOS_EINVAL; } + groups->ids[i] = id; } /* Linux exposes the sorted supplementary list, retaining duplicates. * Heapsort bounds work for the full NGROUPS_MAX input. */ diff --git a/include/reliefnt/permissions.h b/include/reliefnt/permissions.h index 0792a611..01f62894 100644 --- a/include/reliefnt/permissions.h +++ b/include/reliefnt/permissions.h @@ -110,6 +110,24 @@ void task_groups_retain(struct task_groups *groups); */ void task_groups_put(struct task_groups *groups); void task_groups_release(struct task *task); +/** @brief Atomically replace supplementary groups using global kernel GIDs. + * @param task Execution-owned credentials whose old list remains live on error. + * @param ids Resident input array, possibly unaligned; NULL when count is zero. + * @param count Number of GIDs, at most 65536. + * @return Zero or negative EINVAL/ENOMEM. Sorts global IDs, retaining duplicates. + * Allocates one immutable list and releases the old reference only on success. + */ int task_groups_set(struct task *task, const uint32_t *ids, uint32_t count); +/** @brief Map and atomically replace a task's supplementary groups. + * @param task Execution-owned credentials whose old list remains live on error. + * @param ns Borrowed input namespace, NULL for global kernel IDs. + * @param ids Resident local GID array, possibly unaligned; NULL for zero count. + * @param count Number of GIDs, at most 65536. + * @return Zero or negative EINVAL/ENOMEM. Rejects any unmapped or invalid GID + * before publication, then sorts global IDs and retains duplicates. + * Caller validates user memory and authorizes the operation before calling. + */ +int task_groups_set_mapped(struct task *task, const struct user_namespace *ns, + const uint32_t *ids, uint32_t count); #endif diff --git a/include/reliefnt/syscall.h b/include/reliefnt/syscall.h index bd284711..0f517e3c 100644 --- a/include/reliefnt/syscall.h +++ b/include/reliefnt/syscall.h @@ -339,6 +339,15 @@ void syscall_trace_configure(const char *cmdline); * @brief Dispatches process identity, groups, signals, priority, and limits. * Global system controls use initial user namespace capabilities. Signal, * priority and cross-process limit overrides use the target's owning namespace. + * UID/GID arguments and identity results use the caller's user namespace. + * Unmapped input IDs fail with EINVAL, preserving optional UINT32_MAX operands. + * Unmapped output IDs use 65534. setfsuid/setfsgid always return the prior local + * filesystem identity, including when the requested change is rejected. + * @param number Normalized syscall selector. @param a0 First ABI argument. + * @param a1 Second ABI argument. @param a2 Third ABI argument. + * @param a3 Fourth ABI argument. + * @return Syscall value, negative errno, or internal retry status. + * The caller retains execution ownership and validates user buffers on access. */ int64_t syscall_process_control(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3); diff --git a/include/reliefnt/user_namespace.h b/include/reliefnt/user_namespace.h index 0c7ff74e..e59162a1 100644 --- a/include/reliefnt/user_namespace.h +++ b/include/reliefnt/user_namespace.h @@ -57,6 +57,15 @@ uint32_t user_namespace_id_to_kernel(const struct user_namespace *ns, bool group */ uint32_t user_namespace_id_from_kernel(const struct user_namespace *ns, bool group, uint32_t id); +/** @brief Convert a global UID or GID for a userspace identity result. + * @param ns Borrowed live namespace, NULL for the initial identity mapping. + * @param group Select the GID mapping. @param id Global kernel ID. + * @return Local ID, or the overflow identity 65534 when no mapping exists. + * Allocation-free acquire of the immutable map, safe under scheduler_lock. + */ +uint32_t user_namespace_id_from_kernel_munged(const struct user_namespace *ns, bool group, + uint32_t id); + /** @brief Test whether setgroups can run in a live namespace. * @param ns Borrowed namespace, NULL for the initial namespace. * @return True when a GID map exists and setgroups has not been denied. diff --git a/kernel/sched/user_namespace.c b/kernel/sched/user_namespace.c index ae4689e1..e69c5ab7 100644 --- a/kernel/sched/user_namespace.c +++ b/kernel/sched/user_namespace.c @@ -66,6 +66,14 @@ uint32_t user_namespace_id_from_kernel(const struct user_namespace *ns, bool gro return UINT32_MAX; } +/** @copydoc user_namespace_id_from_kernel_munged */ +uint32_t user_namespace_id_from_kernel_munged(const struct user_namespace *ns, bool group, + uint32_t id) +{ + uint32_t local = user_namespace_id_from_kernel(ns, group, id); + return local == UINT32_MAX ? 65534 : local; +} + /** @copydoc user_namespace_may_setgroups */ bool user_namespace_may_setgroups(const struct user_namespace *ns) { diff --git a/kernel/syscall/fs/legacy_filesystem.c b/kernel/syscall/fs/legacy_filesystem.c index d8fd7c9b..3fd42ba6 100644 --- a/kernel/syscall/fs/legacy_filesystem.c +++ b/kernel/syscall/fs/legacy_filesystem.c @@ -1,4 +1,5 @@ #include "../internal.h" +#include @@ -16,6 +17,8 @@ * @return Original result, negative errno, or internal blocking/retry status. * @note The caller retains the kernel execution transaction and descriptor pins. * Trim authorization requires CAP_SYS_ADMIN in the initial user namespace. + * Supplementary groups use the caller's user namespace and CAP_SETGID there, + * with its setgroups policy. User memory is prepared before list publication. */ int64_t syscall_legacy_filesystem(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) { @@ -69,17 +72,33 @@ int64_t syscall_legacy_filesystem(uint64_t number, uint64_t a0, uint64_t a1, uin int32_t size = (int32_t)a0; if (!task) return -RELIEFOS_EPERM; if (number == LINUX_SYS_SETGROUPS) { - if (!(task_initial_capabilities(task) & (1ULL << CAP_SETGID))) return -RELIEFOS_EPERM; + if (!task_ns_capable(task, task->user_ns, CAP_SETGID) || + !user_namespace_may_setgroups(task->user_ns)) return -RELIEFOS_EPERM; if (size < 0 || size > 65536) return -RELIEFOS_EINVAL; - if (size && !user_range_ok(a1, (uint64_t)size * 4)) return -RELIEFOS_EFAULT; - return task_groups_set(task, (const uint32_t *)(uintptr_t)a1, (uint32_t)size); + if (size) { + uint64_t bytes = (uint64_t)size * sizeof(uint32_t); + int prep = swap_prepare_user_range(task, a1, bytes, false); + if (prep == SWAP_STORAGE_CONTENDED) return KERNEL_SYSCALL_SWAP_CONTENDED; + if (prep < 0 || !user_range_ok(a1, bytes)) return -RELIEFOS_EFAULT; + } + return task_groups_set_mapped(task, task->user_ns, + (const uint32_t *)(uintptr_t)a1, (uint32_t)size); } uint32_t count = task->groups ? task->groups->count : 0; if (size < 0) return -RELIEFOS_EINVAL; if (!size) return count; if ((uint32_t)size < count) return -RELIEFOS_EINVAL; - if (count && !user_range_writable(a1, (uint64_t)count * 4)) return -RELIEFOS_EFAULT; - for (uint32_t i = 0; i < count; ++i) ((uint32_t *)(uintptr_t)a1)[i] = task->groups->ids[i]; + if (count) { + uint64_t bytes = (uint64_t)count * sizeof(uint32_t); + int prep = swap_prepare_user_range(task, a1, bytes, true); + if (prep == SWAP_STORAGE_CONTENDED) return KERNEL_SYSCALL_SWAP_CONTENDED; + if (prep < 0 || !user_range_writable(a1, bytes)) return -RELIEFOS_EFAULT; + } + for (uint32_t i = 0; i < count; ++i) { + uint32_t id = user_namespace_id_from_kernel_munged(task->user_ns, true, + task->groups->ids[i]); + __builtin_memcpy((char *)(uintptr_t)a1 + (size_t)i * sizeof(id), &id, sizeof(id)); + } return count; } diff --git a/kernel/syscall/process/process.c b/kernel/syscall/process/process.c index 1bc25912..64f35806 100644 --- a/kernel/syscall/process/process.c +++ b/kernel/syscall/process/process.c @@ -161,19 +161,27 @@ static int64_t process_resource_limit(uint64_t number, uint64_t a0, uint64_t a1, return 0; } -/* Linux v6.12 security/commoncap.c:cap_emulate_setxuid. */ +/** @brief Commit global UIDs with namespace-root capability transitions. + * @param task Execution-owned caller retaining its user namespace. + * @param real Next global real UID. @param effective Next global effective UID. + * @param saved Next global saved UID. + * Filesystem UID follows the effective UID. securebits govern capability + * changes, while process-count accounting retains global real-UID identity. + */ static void process_commit_uids(struct task *task, uint32_t real, uint32_t effective, uint32_t saved) { uint64_t permitted = task->cap_permitted; uint64_t caps = task->cap_effective; + uint32_t root = user_namespace_id_to_kernel(task->user_ns, false, 0); if (!(task->securebits & SECBIT_NO_SETUID_FIXUP)) { - if ((!task->uid || !task->euid || !task->suid) && real && effective && saved) { + if ((task->uid == root || task->euid == root || task->suid == root) && + real != root && effective != root && saved != root) { if (!(task->securebits & SECBIT_KEEP_CAPS)) permitted = caps = 0; task->cap_ambient = 0; } - if (!task->euid && effective) caps = 0; - if (task->euid && !effective) caps = permitted; + if (task->euid == root && effective != root) caps = 0; + if (task->euid != root && effective == root) caps = permitted; } if (task->uid != real) task->nproc_exceeded = real && sched_user_task_count(real) > sched_task_limits(task)->nproc.rlim_cur; @@ -185,6 +193,11 @@ static void process_commit_uids(struct task *task, uint32_t real, uint32_t effec task->cap_effective = caps; } +/** @brief Commit validated global GIDs and reset filesystem GID. + * @param task Execution-owned caller. @param real Next global real GID. + * @param effective Next global effective GID. @param saved Next global saved GID. + * Credential preparation clears dumpability and parent-death signals as needed. + */ static void process_commit_gids(struct task *task, uint32_t real, uint32_t effective, uint32_t saved) { @@ -603,23 +616,23 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, (void)a3; if (number == LINUX_SYS_GETUID) { struct task *task = sched_current_task(); - return task ? (int64_t)task->uid : 0; + return task ? user_namespace_id_from_kernel_munged(task->user_ns, false, task->uid) : 0; } if (number == LINUX_SYS_GETEUID) { struct task *task = sched_current_task(); - return task ? (int64_t)task->euid : 0; + return task ? user_namespace_id_from_kernel_munged(task->user_ns, false, task->euid) : 0; } if (number == LINUX_SYS_GETGID) { struct task *task = sched_current_task(); - return task ? (int64_t)task->gid : 0; + return task ? user_namespace_id_from_kernel_munged(task->user_ns, true, task->gid) : 0; } if (number == LINUX_SYS_GETEGID) { struct task *task = sched_current_task(); - return task ? (int64_t)task->egid : 0; + return task ? user_namespace_id_from_kernel_munged(task->user_ns, true, task->egid) : 0; } if (number == LINUX_SYS_SETUID) { struct task *task = sched_current_task(); - uint32_t target = (uint32_t)a0; + uint32_t target = user_namespace_id_to_kernel(task ? task->user_ns : NULL, false, (uint32_t)a0); if (target == UINT32_MAX) return -RELIEFOS_EINVAL; if (!task) return -RELIEFOS_EPERM; bool privileged = (task->cap_effective & (1ULL << CAP_SETUID)) != 0; @@ -630,7 +643,7 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, } if (number == LINUX_SYS_SETGID) { struct task *task = sched_current_task(); - uint32_t target = (uint32_t)a0; + uint32_t target = user_namespace_id_to_kernel(task ? task->user_ns : NULL, true, (uint32_t)a0); if (target == UINT32_MAX) return -RELIEFOS_EINVAL; if (!task) return -RELIEFOS_EPERM; bool privileged = (task->cap_effective & (1ULL << CAP_SETGID)) != 0; @@ -658,6 +671,9 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, values[1] = task->egid; values[2] = task->sgid; } + for (unsigned i = 0; i < 3; ++i) + values[i] = user_namespace_id_from_kernel_munged(task->user_ns, + number == LINUX_SYS_GETRESGID, values[i]); __builtin_memcpy((void *)(uintptr_t)a0, &values[0], sizeof(values[0])); __builtin_memcpy((void *)(uintptr_t)a1, &values[1], sizeof(values[1])); __builtin_memcpy((void *)(uintptr_t)a2, &values[2], sizeof(values[2])); @@ -665,10 +681,13 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, } if (number == LINUX_SYS_SETREUID || number == LINUX_SYS_SETREGID) { struct task *task = sched_current_task(); - uint32_t real = (uint32_t)a0; - uint32_t effective = (uint32_t)a1; uint32_t current_real, current_effective, saved; if (!task) return -LINUX_ESRCH; + bool group = number == LINUX_SYS_SETREGID; + uint32_t real = user_namespace_id_to_kernel(task->user_ns, group, (uint32_t)a0); + uint32_t effective = user_namespace_id_to_kernel(task->user_ns, group, (uint32_t)a1); + if (((uint32_t)a0 != UINT32_MAX && real == UINT32_MAX) || + ((uint32_t)a1 != UINT32_MAX && effective == UINT32_MAX)) return -LINUX_EINVAL; if (number == LINUX_SYS_SETREUID) { current_real = task->uid; current_effective = task->euid; @@ -700,6 +719,12 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, uint32_t values[3] = {(uint32_t)a0, (uint32_t)a1, (uint32_t)a2}; uint32_t current[3]; if (!task) return -LINUX_ESRCH; + for (unsigned i = 0; i < 3; ++i) { + uint32_t requested = values[i]; + values[i] = user_namespace_id_to_kernel(task->user_ns, + number == LINUX_SYS_SETRESGID, requested); + if (requested != UINT32_MAX && values[i] == UINT32_MAX) return -LINUX_EINVAL; + } if (number == LINUX_SYS_SETRESUID) { current[0] = task->uid; current[1] = task->euid; current[2] = task->suid; } else { @@ -726,9 +751,10 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, } if (number == LINUX_SYS_SETFSUID || number == LINUX_SYS_SETFSGID) { struct task *task = sched_current_task(); - uint32_t requested = (uint32_t)a0; uint32_t old; if (!task) return -LINUX_ESRCH; + uint32_t requested = user_namespace_id_to_kernel(task->user_ns, + number == LINUX_SYS_SETFSGID, (uint32_t)a0); if (number == LINUX_SYS_SETFSUID) { old = task->fsuid; if (requested != UINT32_MAX && ((task->cap_effective & (1ULL << CAP_SETUID)) || requested == task->uid || @@ -740,8 +766,9 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, (1ULL << CAP_FOWNER) | (1ULL << CAP_FSETID) | (1ULL << CAP_MAC_OVERRIDE) | (1ULL << CAP_LINUX_IMMUTABLE); if (!(task->securebits & SECBIT_NO_SETUID_FIXUP)) { - if (!old && requested) task->cap_effective &= ~fs_caps; - if (old && !requested) task->cap_effective |= task->cap_permitted & fs_caps; + uint32_t root = user_namespace_id_to_kernel(task->user_ns, false, 0); + if (old == root && requested != root) task->cap_effective &= ~fs_caps; + if (old != root && requested == root) task->cap_effective |= task->cap_permitted & fs_caps; } task->fsuid = requested; } @@ -754,7 +781,8 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, task->fsgid = requested; } } - return old; + return user_namespace_id_from_kernel_munged(task->user_ns, + number == LINUX_SYS_SETFSGID, old); } if (number == LINUX_SYS_SCHED_GET_PRIORITY_MAX || number == LINUX_SYS_SCHED_GET_PRIORITY_MIN) { diff --git a/tools/storage_graph_test_sources.py b/tools/storage_graph_test_sources.py index 6b599582..125f03f0 100644 --- a/tools/storage_graph_test_sources.py +++ b/tools/storage_graph_test_sources.py @@ -30,6 +30,7 @@ 'fs/vfs/write_access.c', 'fs/vfs/storage_mount.c', 'fs/security/access.c', + 'kernel/sched/user_namespace.c', 'fs/devfs/mount.c', 'fs/devfs/identity.c', 'fs/devfs/device.c', diff --git a/tools/test_linux_capabilities.py b/tools/test_linux_capabilities.py index f03117b3..7dff4887 100644 --- a/tools/test_linux_capabilities.py +++ b/tools/test_linux_capabilities.py @@ -12,6 +12,7 @@ "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", - "tools/tests/capability_test.c", "kernel/sched/user_namespace.c", "-o", binary, + "tools/tests/capability_test.c", "kernel/sched/user_namespace.c", + "fs/security/access.c", "kernel/syscall/fs/legacy_filesystem.c", "-o", binary, ], cwd=ROOT, check=True) subprocess.run([binary], cwd=ROOT, check=True, timeout=30) diff --git a/tools/test_linux_permissions.py b/tools/test_linux_permissions.py index 7aeb946b..37f24a02 100644 --- a/tools/test_linux_permissions.py +++ b/tools/test_linux_permissions.py @@ -9,7 +9,7 @@ "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/attributes.c", "fs/vfs/mutation.c", "fs/security/access.c", "kernel/syscall/fs/create.c", - "kernel/syscall/fs/mutation.c", + "kernel/syscall/fs/mutation.c", "kernel/sched/user_namespace.c", ] with tempfile.TemporaryDirectory(prefix="reliefnt-permissions-") as directory: for name in ("linux_permissions", "chroot_paths"): diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index 060ccfe0..2b25310e 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -22,7 +22,7 @@ def test_real_tmpfs_without_text_routing(self): "cc", "-std=gnu11", "-O1", "-g", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Wl,--wrap=storage_ext4_read_inode", "-Wl,--wrap=storage_read_device", "-Wl,--wrap=storage_inode_stat", "-Wl,--wrap=storage_backend_commit_rename_metadata", "-Wl,--wrap=storage_cluster_write", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_backend_test.c", "kernel/dma/buffer.c", "drivers/storage/ahci/dma.c", "drivers/storage/ahci/interrupt.c", "drivers/storage/nvme/queue.c", "block/partition/mbr.c", - "fs/cgroup/filesystem.c", "fs/cgroup/hierarchy.c", "fs/vfs/notify.c", "fs/nsfs/namespace.c", + "fs/cgroup/filesystem.c", "fs/cgroup/hierarchy.c", "fs/vfs/notify.c", "fs/nsfs/namespace.c", "kernel/sched/user_namespace.c", "kernel/syscall/dispatch.c", "kernel/syscall/io/legacy_io.c", "kernel/syscall/io/io.c", "kernel/syscall/io/file_io.c", "kernel/syscall/io/seek.c", "kernel/syscall/io/transfer.c", "kernel/syscall/io/directory.c", "kernel/syscall/fs/metadata.c", "tools/tests/mount_backend_io_boundaries.c", diff --git a/tools/tests/capability_test.c b/tools/tests/capability_test.c index d385bf76..e07aa93e 100644 --- a/tools/tests/capability_test.c +++ b/tools/tests/capability_test.c @@ -2,12 +2,16 @@ #include #include #include +#include +#include "../../kernel/syscall/legacy.h" #include "../../kernel/syscall/process/process.c" static struct task caller, target; static uint64_t readonly; static unsigned namespace_allocations; static bool fail_namespace_allocation; +static uint32_t counted_uid; +static uint64_t counted_tasks; void *kernel_malloc(size_t size) { @@ -24,7 +28,7 @@ void kernel_free(void *memory) } struct task *sched_current_task(void) { return &caller; } struct task *sched_find(uint32_t pid) { return pid == 17 ? &target : NULL; } -uint64_t sched_user_task_count(uint32_t uid) { (void)uid; return 0; } +uint64_t sched_user_task_count(uint32_t uid) { counted_uid = uid; return counted_tasks; } bool user_range_ok(uint64_t p, uint64_t n) { return p >= 4096 && n <= UINT64_MAX - p; } bool user_range_writable(uint64_t p, uint64_t n) { return p != readonly && user_range_ok(p, n); } /* Standard ID syscalls must not consult a userspace service or mutate peers. */ @@ -103,9 +107,237 @@ static void test_namespace_authority(void) puts("PASS user namespace capability ancestry, ownership, lifetime, OOM and depth"); } +/** @brief Publish real maps through the same controls used by procfs. */ +static struct user_namespace *mapped_namespace(bool deny_groups) +{ + struct task root = {.cap_effective = (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1}; + struct user_namespace *ns = NULL; + struct user_namespace_file file; + uint32_t written; + assert(!user_namespace_create(&root, &ns)); + if (deny_groups) { + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_SETGROUPS, true, &file)); + assert(!user_namespace_file_write(&file, &root, 0, "deny", 4, &written)); + user_namespace_file_close(&file); + } + const char uid_map[] = "0 1000 8\n20 2000 3\n"; + const char gid_map[] = "0 3000 8\n20 2500 3\n"; + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_UID_MAP, true, &file)); + assert(!user_namespace_file_write(&file, &root, 0, uid_map, sizeof(uid_map) - 1, &written)); + user_namespace_file_close(&file); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_GID_MAP, true, &file)); + assert(!user_namespace_file_write(&file, &root, 0, gid_map, sizeof(gid_map) - 1, &written)); + user_namespace_file_close(&file); + return ns; +} + +/** @brief Check userspace IDs while all stored credentials remain global. */ +static void test_namespace_ids(void) +{ + const uint64_t caps = (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1; + struct user_namespace *ns = mapped_namespace(false); + caller = (struct task){.user_ns = ns, .uid = 1001, .euid = 1002, .suid = 1003, + .fsuid = 1004, .gid = 3001, .egid = 3002, .sgid = 3003, .fsgid = 3004, + .cap_effective = caps, .cap_permitted = caps}; + assert(syscall_process_control(LINUX_SYS_GETUID, 0, 0, 0, 0) == 1); + assert(syscall_process_control(LINUX_SYS_GETEUID, 0, 0, 0, 0) == 2); + assert(syscall_process_control(LINUX_SYS_GETGID, 0, 0, 0, 0) == 1); + assert(syscall_process_control(LINUX_SYS_GETEGID, 0, 0, 0, 0) == 2); + _Alignas(4) unsigned char output[13] = {0}; + uint32_t values[3]; + assert(!syscall_process_control(LINUX_SYS_GETRESUID, (uintptr_t)(output + 1), + (uintptr_t)(output + 5), (uintptr_t)(output + 9), 0)); + __builtin_memcpy(values, output + 1, sizeof(values)); + assert(values[0] == 1 && values[1] == 2 && values[2] == 3); + assert(!syscall_process_control(LINUX_SYS_GETRESGID, (uintptr_t)(output + 1), + (uintptr_t)(output + 5), (uintptr_t)(output + 9), 0)); + __builtin_memcpy(values, output + 1, sizeof(values)); + assert(values[0] == 1 && values[1] == 2 && values[2] == 3); + readonly = (uintptr_t)(output + 5); + assert(syscall_process_control(LINUX_SYS_GETRESUID, (uintptr_t)(output + 1), + readonly, (uintptr_t)(output + 9), 0) == -LINUX_EFAULT); + readonly = 0; + + assert(syscall_process_control(LINUX_SYS_SETUID, 2000, 0, 0, 0) == -LINUX_EINVAL); + assert(syscall_process_control(LINUX_SYS_SETGID, 3000, 0, 0, 0) == -LINUX_EINVAL); + assert(caller.uid == 1001 && caller.gid == 3001); + assert(!syscall_process_control(LINUX_SYS_SETUID, 1, 0, 0, 0)); + assert(caller.uid == 1001 && caller.euid == 1001 && caller.suid == 1001 && caller.fsuid == 1001); + assert(!syscall_process_control(LINUX_SYS_SETGID, 2, 0, 0, 0)); + assert(caller.gid == 3002 && caller.egid == 3002 && caller.sgid == 3002 && caller.fsgid == 3002); + assert(!syscall_process_control(LINUX_SYS_SETREUID, 20, 21, 0, 0)); + assert(caller.uid == 2000 && caller.euid == 2001 && caller.suid == 2001 && caller.fsuid == 2001); + assert(!syscall_process_control(LINUX_SYS_SETREGID, 21, 20, 0, 0)); + assert(caller.gid == 2501 && caller.egid == 2500 && caller.sgid == 2500 && caller.fsgid == 2500); + assert(syscall_process_control(LINUX_SYS_SETREUID, 0, 8, 0, 0) == -LINUX_EINVAL); + assert(syscall_process_control(LINUX_SYS_SETREGID, 8, 0, 0, 0) == -LINUX_EINVAL); + assert(caller.uid == 2000 && caller.gid == 2501); + assert(!syscall_process_control(LINUX_SYS_SETRESUID, 0, UINT32_MAX, 2, 0)); + assert(caller.uid == 1000 && caller.euid == 2001 && caller.suid == 1002); + assert(!syscall_process_control(LINUX_SYS_SETRESGID, 0, UINT32_MAX, 2, 0)); + assert(caller.gid == 3000 && caller.egid == 2500 && caller.sgid == 3002); + assert(syscall_process_control(LINUX_SYS_SETRESUID, 1, 2, 8, 0) == -LINUX_EINVAL); + assert(syscall_process_control(LINUX_SYS_SETRESGID, 1, 8, 2, 0) == -LINUX_EINVAL); + assert(caller.uid == 1000 && caller.euid == 2001 && caller.suid == 1002); + assert(caller.gid == 3000 && caller.egid == 2500 && caller.sgid == 3002); + assert(!syscall_process_control(LINUX_SYS_SETRESUID, UINT32_MAX, UINT32_MAX, UINT32_MAX, 0)); + assert(caller.uid == 1000 && caller.euid == 2001 && caller.suid == 1002); + assert(syscall_process_control(LINUX_SYS_SETFSUID, 3, 0, 0, 0) == 21); + assert(caller.fsuid == 1003); + assert(syscall_process_control(LINUX_SYS_SETFSGID, 3, 0, 0, 0) == 20); + assert(caller.fsgid == 3003); + assert(syscall_process_control(LINUX_SYS_SETFSUID, 8, 0, 0, 0) == 3 && caller.fsuid == 1003); + assert(syscall_process_control(LINUX_SYS_SETFSGID, UINT32_MAX, 0, 0, 0) == 3 && caller.fsgid == 3003); + + caller.uid = caller.euid = caller.suid = caller.fsuid = 9999; + caller.gid = caller.egid = caller.sgid = caller.fsgid = 9999; + assert(syscall_process_control(LINUX_SYS_GETUID, 0, 0, 0, 0) == 65534); + assert(syscall_process_control(LINUX_SYS_GETEUID, 0, 0, 0, 0) == 65534); + assert(syscall_process_control(LINUX_SYS_GETGID, 0, 0, 0, 0) == 65534); + assert(syscall_process_control(LINUX_SYS_GETEGID, 0, 0, 0, 0) == 65534); + assert(!syscall_process_control(LINUX_SYS_GETRESUID, (uintptr_t)&values[0], + (uintptr_t)&values[1], (uintptr_t)&values[2], 0)); + assert(values[0] == 65534 && values[1] == 65534 && values[2] == 65534); + assert(!syscall_process_control(LINUX_SYS_GETRESGID, (uintptr_t)&values[0], + (uintptr_t)&values[1], (uintptr_t)&values[2], 0)); + assert(values[0] == 65534 && values[1] == 65534 && values[2] == 65534); + assert(syscall_process_control(LINUX_SYS_SETFSUID, UINT32_MAX, 0, 0, 0) == 65534); + assert(syscall_process_control(LINUX_SYS_SETFSGID, 8, 0, 0, 0) == 65534); + assert(caller.fsuid == 9999 && caller.fsgid == 9999); + + caller = (struct task){.user_ns = ns, .uid = 1001, .euid = 1002, .suid = 1003, + .fsuid = 1002, .gid = 3001, .egid = 3002, .sgid = 3003, .fsgid = 3002}; + assert(syscall_process_control(LINUX_SYS_SETUID, 0, 0, 0, 0) == -LINUX_EPERM); + assert(!syscall_process_control(LINUX_SYS_SETUID, 3, 0, 0, 0)); + assert(caller.uid == 1001 && caller.euid == 1003 && caller.suid == 1003); + assert(!syscall_process_control(LINUX_SYS_SETRESUID, 3, 1, 3, 0)); + assert(caller.uid == 1003 && caller.euid == 1001 && caller.suid == 1003); + assert(!syscall_process_control(LINUX_SYS_SETGID, 3, 0, 0, 0)); + assert(caller.gid == 3001 && caller.egid == 3003 && caller.sgid == 3003); + assert(!syscall_process_control(LINUX_SYS_SETREGID, 3, 1, 0, 0)); + assert(caller.gid == 3003 && caller.egid == 3001 && caller.sgid == 3001); + user_namespace_put(ns); + caller = (struct task){0}; + assert(!namespace_allocations); + puts("PASS namespace ID syscall mapping, overflow, sentinels and atomic validation"); +} + +/** @brief Root capability transitions use the UID zero of the current scope. */ +static void test_namespace_root_fixup(void) +{ + const uint64_t caps = (1ULL << CAP_SETUID) | (1ULL << CAP_DAC_OVERRIDE) | + (1ULL << CAP_KILL) | (1ULL << CAP_SYS_BOOT); + struct user_namespace *ns = mapped_namespace(false); + caller = (struct task){.user_ns = ns, .uid = 1000, .euid = 1000, .suid = 1000, + .fsuid = 1000, .cap_permitted = caps, .cap_effective = caps, .cap_ambient = 1ULL << CAP_KILL}; + assert(!syscall_process_control(LINUX_SYS_SETUID, 1, 0, 0, 0)); + assert(!caller.cap_permitted && !caller.cap_effective && !caller.cap_ambient); + caller = (struct task){.user_ns = ns, .uid = 1000, .euid = 1001, .suid = 1001, + .fsuid = 1001, .cap_permitted = caps}; + assert(!syscall_process_control(LINUX_SYS_SETRESUID, UINT32_MAX, 0, UINT32_MAX, 0)); + assert(caller.cap_effective == caps && caller.euid == 1000); + assert(!syscall_process_control(LINUX_SYS_SETRESUID, UINT32_MAX, 1, UINT32_MAX, 0)); + assert(!caller.cap_effective && caller.cap_permitted == caps); + caller = (struct task){.user_ns = ns, .uid = 1000, .euid = 1000, .suid = 1000, + .fsuid = 1000, .cap_permitted = caps, .cap_effective = caps}; + assert(syscall_process_control(LINUX_SYS_SETFSUID, 1, 0, 0, 0) == 0); + assert(caller.cap_effective == (caps & ~(1ULL << CAP_DAC_OVERRIDE))); + assert(syscall_process_control(LINUX_SYS_SETFSUID, 0, 0, 0, 0) == 1); + assert(caller.cap_effective == caps); + caller.securebits = SECBIT_KEEP_CAPS; + caller.cap_ambient = 1ULL << CAP_KILL; + assert(!syscall_process_control(LINUX_SYS_SETUID, 2, 0, 0, 0)); + assert(caller.cap_permitted == caps && !caller.cap_effective && !caller.cap_ambient); + caller = (struct task){.user_ns = ns, .uid = 1000, .euid = 1000, .suid = 1000, + .fsuid = 1000, .cap_permitted = caps, .cap_effective = caps, + .securebits = SECBIT_NO_SETUID_FIXUP, .cap_ambient = 1ULL << CAP_KILL}; + counted_tasks = 2; + sched_task_limits(&caller)->nproc.rlim_cur = 1; + assert(!syscall_process_control(LINUX_SYS_SETUID, 2, 0, 0, 0)); + assert(caller.cap_permitted == caps && caller.cap_effective == caps && caller.cap_ambient); + assert(caller.nproc_exceeded && counted_uid == 1002); + assert(!syscall_process_control(LINUX_SYS_SETUID, 0, 0, 0, 0)); + assert(caller.nproc_exceeded && counted_uid == 1000); + counted_tasks = 0; + assert(syscall_process_control(LINUX_SYS_REBOOT, 0, 0, 0, 0) == -LINUX_EPERM); + user_namespace_put(ns); + caller = (struct task){0}; + assert(!namespace_allocations); + puts("PASS namespace root set-ID fixups, securebits and global process counts"); +} + +/** @brief Supplementary groups are mapped before global sorting and publication. */ +static void test_namespace_groups(void) +{ + struct user_namespace *ns = mapped_namespace(false); + caller = (struct task){.user_ns = ns, .cap_effective = 1ULL << CAP_SETGID}; + _Alignas(4) unsigned char input[17]; + const uint32_t ids[] = {1, 20, 1, 0}; + __builtin_memcpy(input + 1, ids, sizeof(ids)); + assert(!syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 4, (uintptr_t)(input + 1), 0, 0, 0, 0)); + assert(caller.groups && caller.groups->count == 4); + const uint32_t kernel_ids[] = {2500, 3000, 3001, 3001}; + assert(!__builtin_memcmp(caller.groups->ids, kernel_ids, sizeof(kernel_ids))); + assert(syscall_legacy_filesystem(LINUX_SYS_GETGROUPS, 0, 0, 0, 0, 0, 0) == 4); + assert(syscall_legacy_filesystem(LINUX_SYS_GETGROUPS, 4, (uintptr_t)(input + 1), 0, 0, 0, 0) == 4); + uint32_t output[4]; + __builtin_memcpy(output, input + 1, sizeof(output)); + assert(output[0] == 20 && output[1] == 0 && output[2] == 1 && output[3] == 1); + struct task_groups *previous = caller.groups; + task_groups_retain(previous); + const uint32_t invalid[] = {0, 8}; + assert(syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 2, (uintptr_t)invalid, 0, 0, 0, 0) == -LINUX_EINVAL); + assert(caller.groups == previous && previous->references == 2); + fail_namespace_allocation = true; + assert(syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 4, (uintptr_t)ids, 0, 0, 0, 0) == -LINUX_ENOMEM); + fail_namespace_allocation = false; + assert(caller.groups == previous && previous->references == 2); + readonly = (uintptr_t)output; + assert(syscall_legacy_filesystem(LINUX_SYS_GETGROUPS, 4, readonly, 0, 0, 0, 0) == -LINUX_EFAULT); + readonly = 0; + assert(syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 1, 0, 0, 0, 0, 0) == -LINUX_EFAULT); + assert(syscall_legacy_filesystem(LINUX_SYS_GETGROUPS, 3, (uintptr_t)output, 0, 0, 0, 0) == -LINUX_EINVAL); + assert(syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, UINT32_MAX, 0, 0, 0, 0, 0) == -LINUX_EINVAL); + assert(syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 65537, 0, 0, 0, 0, 0) == -LINUX_EINVAL); + caller.cap_effective = 0; + assert(syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 0, 0, 0, 0, 0, 0) == -LINUX_EPERM); + caller.cap_effective = 1ULL << CAP_SETGID; + assert(!syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 0, 0, 0, 0, 0, 0)); + assert(!caller.groups && previous->references == 1); + task_groups_put(previous); + const uint32_t global_ids[] = {3000, 77}; + assert(!task_groups_set(&caller, global_ids, 2)); + assert(caller.groups->ids[0] == 77 && caller.groups->ids[1] == 3000); + assert(syscall_legacy_filesystem(LINUX_SYS_GETGROUPS, 2, (uintptr_t)output, 0, 0, 0, 0) == 2); + assert(output[0] == 65534 && output[1] == 0); + task_groups_release(&caller); + user_namespace_put(ns); + + ns = mapped_namespace(true); + caller = (struct task){.user_ns = ns, .cap_effective = 1ULL << CAP_SETGID}; + assert(syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 0, 0, 0, 0, 0, 0) == -LINUX_EPERM); + user_namespace_put(ns); + struct task creator = {0}; + assert(!user_namespace_create(&creator, &ns)); + caller = (struct task){.user_ns = ns, .cap_effective = 1ULL << CAP_SETGID}; + assert(syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 0, 0, 0, 0, 0, 0) == -LINUX_EPERM); + assert(syscall_process_control(LINUX_SYS_SETUID, 0, 0, 0, 0) == -LINUX_EINVAL); + user_namespace_put(ns); + caller = (struct task){.cap_effective = 1ULL << CAP_SETGID}; + assert(!syscall_legacy_filesystem(LINUX_SYS_SETGROUPS, 2, (uintptr_t)global_ids, 0, 0, 0, 0)); + assert(syscall_legacy_filesystem(LINUX_SYS_GETGROUPS, 2, (uintptr_t)output, 0, 0, 0, 0) == 2); + assert(output[0] == 77 && output[1] == 3000); + task_groups_release(&caller); + assert(!namespace_allocations); + puts("PASS mapped supplementary groups, order, duplicate IDs, denial and rollback"); +} + int main(void) { test_namespace_authority(); + test_namespace_ids(); + test_namespace_root_fixup(); + test_namespace_groups(); caller = (struct task){.uid = 0, .euid = 0, .cap_effective = 0}; assert(syscall_process_control(LINUX_SYS_REBOOT, 0, 0, 0, 0) == -LINUX_EPERM); caller = (struct task){.uid = 1000, .euid = 1000, .cap_effective = 1ULL << CAP_SYS_BOOT}; @@ -209,14 +441,5 @@ int main(void) (uintptr_t)(unaligned_data + 1), 0, 0) == 0); assert(syscall_process_control(LINUX_SYS_CAPSET, (uintptr_t)(unaligned_header + 1), (uintptr_t)(unaligned_data + 1), 0, 0) == 0); - /* Namespace-local privilege must not authorize a global reboot. */ - struct user_namespace local_scope = {.references = 1, .owner = 1000, .level = 1}; - caller = (struct task){.uid = 1000, .euid = 1000, - .user_ns = &local_scope, - .cap_effective = (1ULL << CAP_SYS_BOOT) | (1ULL << CAP_SETUID)}; - assert(syscall_process_control(LINUX_SYS_REBOOT, 0, 0, 0, 0) == -LINUX_EPERM); - assert(syscall_process_control(LINUX_SYS_SETUID, 2000, 0, 0, 0) == 0); - assert(caller.uid == 2000 && caller.euid == 2000); - puts("PASS namespace-local credentials cannot authorize global reboot"); puts("PASS production capget/capset: root drop, subsets, read-only input, thread ID, version query, target lookup"); } diff --git a/tools/tests/storage_mkdir_mount_test.c b/tools/tests/storage_mkdir_mount_test.c index 9f1c8e0c..47a417de 100644 --- a/tools/tests/storage_mkdir_mount_test.c +++ b/tools/tests/storage_mkdir_mount_test.c @@ -108,6 +108,10 @@ void pci_unmap_mmio(void *pointer, uint64_t bytes) uint64_t mm_alloc_pages_below(uint32_t pages, uint64_t mask) { (void)pages; (void)mask; abort(); } uint64_t mm_alloc_page(void) { return (uintptr_t)aligned_alloc(4096, 4096); } +/** @brief Provide the fixture's fixed 64 MiB capacity for tmpfs defaults. + * @return Total memory in KiB, independent of transient host allocations. + */ +uint64_t mm_total_memory_kib(void) { return 65536; } void *mm_phys_to_virt(uint64_t physical) { return (void *)(uintptr_t)physical; } void mm_free_page(uint64_t p) { free((void *)(uintptr_t)p); } uint64_t mm_virt_to_phys(const void *address) { return (uintptr_t)address; } From 6c39e588873e06e3f0f9a6f00c4d42db60ee5b69 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 00:03:26 +0800 Subject: [PATCH 57/97] feat(userns): map exec identities and namespace root credentials --- Documentation/core-api/mount-namespaces.rst | 17 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 37 +++- .../LC_MESSAGES/core-api/mount-namespaces.po | 31 ++- kernel/exec/userland.c | 24 ++- tools/test_vdso_mapping.py | 5 +- tools/tests/vdso_auxv_test.c | 201 ++++++++++++++++++ 6 files changed, 296 insertions(+), 19 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 569cfea9..1d309544 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -127,6 +127,19 @@ proc 控制文件在打开时保留目标空间、打开者空间及其标量凭 一次发布按全局 GID 排序的不可变列表,保留重复项。映射、用户内存或分配错误 保留旧列表。内部 ``task_groups_set()`` 继续接收全局 ID。 +exec 身份与权限 +=============== + +ELF 初始栈与保存的 auxv 中,``AT_UID``、``AT_EUID``、``AT_GID`` 和 +``AT_EGID`` 使用新映像所属用户空间的 ID,未映射时输出 65534。 +``AT_SECURE`` 依据全局凭据和 secure-exec 状态生成,两个不同的未映射 ID +即使都输出 65534,也保留原有的身份差异检查。 + +执行文件的 UID 和 GID 都映射到当前空间后,set-ID 位才可改变有效身份。 +``nosuid``、``no_new_privs`` 和外部共享 ``CLONE_FS`` 的权限限制继续生效。 +能力恢复与 secure-exec 的 root 判断使用当前空间 UID 0 对应的全局 ID, +并遵循 securebits、能力边界集、继承与 ambient 集合规则。保存身份与文件系统 +身份继续使用全局 ID;特权执行仍清除父死亡信号并限制可转储状态。 + 内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 -``EINVAL``。exec、文件元数据等其余用户态 ID 边界、创建入口和用户空间句柄 -仍待接入。 +``EINVAL``。文件元数据等其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index bd26c7af..a63f8af4 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -260,11 +260,40 @@ msgstr "" "retained. Mapping, user-memory and allocation errors preserve the old " "list. The internal ``task_groups_set()`` interface accepts global IDs." +msgid "exec 身份与权限" +msgstr "Exec identity and privileges" + +msgid "" +"ELF 初始栈与保存的 auxv 中,``AT_UID``、``AT_EUID``、``AT_GID`` 和 ``AT_EGID`` " +"使用新映像所属用户空间的 ID,未映射时输出 65534。 ``AT_SECURE`` 依据全局凭据和 secure-exec " +"状态生成,两个不同的未映射 ID 即使都输出 65534,也保留原有的身份差异检查。" +msgstr "" +"The initial ELF stack and saved auxv encode ``AT_UID``, ``AT_EUID``, " +"``AT_GID`` and ``AT_EGID`` in the new image’s user namespace, using 65534" +" for unmapped IDs. ``AT_SECURE`` uses global credentials and secure-exec " +"state. Two distinct unmapped IDs retain the identity-difference check " +"even when both are reported as 65534." + +msgid "" +"执行文件的 UID 和 GID 都映射到当前空间后,set-ID 位才可改变有效身份。 ``nosuid``、``no_new_privs`` " +"和外部共享 ``CLONE_FS`` 的权限限制继续生效。 能力恢复与 secure-exec 的 root 判断使用当前空间 UID 0 " +"对应的全局 ID, 并遵循 securebits、能力边界集、继承与 ambient 集合规则。保存身份与文件系统 身份继续使用全局 " +"ID;特权执行仍清除父死亡信号并限制可转储状态。" +msgstr "" +"Set-ID bits can change effective credentials only when both the " +"executable’s UID and GID map into the current namespace. The restrictions" +" from ``nosuid``, ``no_new_privs`` and externally shared ``CLONE_FS`` " +"state still apply. Capability restoration and secure-exec root checks use" +" the global ID corresponding to UID 0 in the current namespace, following" +" securebits, capability bounding, inheritable and ambient set rules. " +"Saved and filesystem credentials use global IDs. Privileged execution " +"clears the parent-death signal and restricts dumpability." + msgid "" -"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 " -"``EINVAL``。exec、文件元数据等其余用户态 ID 边界、创建入口和用户空间句柄 仍待接入。" +"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``。文件元数据等其余用户态 ID " +"边界、创建入口和用户空间句柄仍待接入。" msgstr "" "Internal allocation and reference interfaces are available. Userspace " "``CLONE_NEWUSER`` currently returns ``EINVAL``. Remaining userspace ID " -"boundaries, including exec and file metadata, creation entry points and " -"user-namespace handles still await integration." +"boundaries, including file metadata, creation entry points and user-" +"namespace handles still await integration." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 7211cd9a..904bde91 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -223,9 +223,34 @@ msgstr "" "順に並べた不変リストを一度に公開し、重複は保持します。マッピング、ユーザーメモリ、割り当てのエラー時には古いリストを保持します。内部の " "``task_groups_set()`` はグローバル ID を受け取ります。" +msgid "exec 身份与权限" +msgstr "exec の識別情報と権限" + +msgid "" +"ELF 初始栈与保存的 auxv 中,``AT_UID``、``AT_EUID``、``AT_GID`` 和 ``AT_EGID`` " +"使用新映像所属用户空间的 ID,未映射时输出 65534。 ``AT_SECURE`` 依据全局凭据和 secure-exec " +"状态生成,两个不同的未映射 ID 即使都输出 65534,也保留原有的身份差异检查。" +msgstr "" +"ELF の初期スタックと保存した auxv の ``AT_UID``、``AT_EUID``、``AT_GID``、``AT_EGID`` " +"は、新しい映像が所属するユーザー名前空間の ID を使い、未マッピングの場合は 65534 を返します。``AT_SECURE`` " +"はグローバルな資格情報と secure-exec 状態に基づきます。異なる未マッピング ID が両方とも 65534 " +"と表示されても、元の識別情報の差異を検査します。" + +msgid "" +"执行文件的 UID 和 GID 都映射到当前空间后,set-ID 位才可改变有效身份。 ``nosuid``、``no_new_privs`` " +"和外部共享 ``CLONE_FS`` 的权限限制继续生效。 能力恢复与 secure-exec 的 root 判断使用当前空间 UID 0 " +"对应的全局 ID, 并遵循 securebits、能力边界集、继承与 ambient 集合规则。保存身份与文件系统 身份继续使用全局 " +"ID;特权执行仍清除父死亡信号并限制可转储状态。" +msgstr "" +"実行ファイルの UID と GID の両方が現在の空間にマッピングされている場合にだけ、set-ID " +"ビットで実効資格情報を変更できます。``nosuid``、``no_new_privs``、外部と共有する ``CLONE_FS`` " +"状態による制限を引き続き適用します。能力の復元と secure-exec の root 判定は、現在の空間の UID 0 に対応するグローバル " +"ID を基準にし、securebits、能力の境界集合、継承集合、ambient 集合の規則に従います。保存 ID とファイルシステム ID " +"はグローバル ID を使います。特権実行では親死亡シグナルを消去し、ダンプ可能性を制限します。" + msgid "" -"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 " -"``EINVAL``。exec、文件元数据等其余用户态 ID 边界、创建入口和用户空间句柄 仍待接入。" +"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``。文件元数据等其余用户态 ID " +"边界、创建入口和用户空间句柄仍待接入。" msgstr "" "カーネル内部の空間割り当てと参照インターフェースを提供します。現在、ユーザー空間の ``CLONE_NEWUSER`` は ``EINVAL`` " -"を返します。exec やファイルメタデータなどの残りのユーザー空間 ID 境界、作成入口、ユーザー名前空間ハンドルの接続は今後の作業です。" +"を返します。ファイルメタデータなどの残りのユーザー空間 ID 境界、作成入口、ユーザー名前空間ハンドルの接続は今後の作業です。" diff --git a/kernel/exec/userland.c b/kernel/exec/userland.c index 0b9f0c40..1ffb84f5 100644 --- a/kernel/exec/userland.c +++ b/kernel/exec/userland.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -324,6 +325,8 @@ static int write_user_u64(const struct address_space *as, uint64_t vaddr, uint64 * @param vdso_ehdr Mapped vDSO ELF header address, or zero when absent. * @return Zero or negative stack budget/mapping errno. Native ELF starts with * no loader finalizer in RDX; the private interpreter still receives envp. + * UID/GID auxv entries use the image's user namespace and overflow identity. + * Secure-exec decisions retain the stored global identities. */ static int prepare_user_exec_stack(struct task *task, const char *execfn, uint64_t vdso_ehdr) { @@ -453,10 +456,10 @@ static int prepare_user_exec_stack(struct task *task, const char *execfn, uint64 AT_PAGESZ, 4096, AT_BASE, task->dynamic_launch.interp_base, AT_ENTRY, task->dynamic_launch.main_entry, - AT_UID, task->uid, - AT_EUID, task->euid, - AT_GID, task->gid, - AT_EGID, task->egid, + AT_UID, user_namespace_id_from_kernel_munged(task->user_ns, false, task->uid), + AT_EUID, user_namespace_id_from_kernel_munged(task->user_ns, false, task->euid), + AT_GID, user_namespace_id_from_kernel_munged(task->user_ns, true, task->gid), + AT_EGID, user_namespace_id_from_kernel_munged(task->user_ns, true, task->egid), AT_SECURE, task->secure_exec || task->uid != task->euid || task->gid != task->egid, AT_RANDOM, random_base, AT_RSEQ_FEATURE_SIZE, 32, @@ -508,6 +511,8 @@ static int prepare_user_exec_stack(struct task *task, const char *execfn, uint64 * @return Zero or metadata/unsupported errno; applies set-ID, nosuid, * shared-filesystem, capability, secure-exec and dumpability rules. No * diagnostic pathname lookup or graph/module lock spans metadata callbacks. + * Stored IDs remain global. Set-ID requires both file ownership IDs to be + * mapped in the image's user namespace, whose UID zero defines root. */ static int userland_prepare_exec_credentials(struct task *next, const struct task *old) { @@ -518,16 +523,19 @@ static int userland_prepare_exec_credentials(struct task *next, const struct tas uint64_t mount_flags=vfs_path_mount_flags(image); /* bprm_fill_uid reads the held ELF inode under the execution/storage lock. * An interpreter's set-ID bits never replace the main ELF's authority. */ - if (!old->no_new_privs && !(mount_flags & MS_NOSUID)) { + if (!old->no_new_privs && !(mount_flags & MS_NOSUID) && + user_namespace_id_from_kernel(next->user_ns, false, file.uid) != UINT32_MAX && + user_namespace_id_from_kernel(next->user_ns, true, file.gid) != UINT32_MAX) { if ((file.mode & 06000) && !sched_task_mm(next)->executable_inode) return -95; if (file.mode & 04000) next->euid = file.uid; if ((file.mode & 02010) == 02010) next->egid = file.gid; } /* Linux commoncap.c:cap_bprm_creds_from_file, without file capabilities. */ - bool effective = !(old->securebits & SECBIT_NOROOT) && !next->euid; + uint32_t root = user_namespace_id_to_kernel(next->user_ns, false, 0); + bool effective = !(old->securebits & SECBIT_NOROOT) && next->euid == root; bool setid = next->euid != old->uid || next->egid != old->gid; uint64_t permitted = 0; - if (!(old->securebits & SECBIT_NOROOT) && (!next->uid || !next->euid)) + if (!(old->securebits & SECBIT_NOROOT) && (next->uid == root || next->euid == root)) permitted = old->cap_bset | old->cap_inheritable; /* A separate CLONE_FS holder can modify the new image's cwd/root. The * execution gate serializes this check through the start of sibling @@ -546,7 +554,7 @@ static int userland_prepare_exec_credentials(struct task *next, const struct tas next->cap_permitted = permitted | next->cap_ambient; next->cap_effective = effective ? next->cap_permitted : next->cap_ambient; next->securebits &= ~SECBIT_KEEP_CAPS; - next->secure_exec = setid || (next->uid && + next->secure_exec = setid || (next->uid != root && (effective || (next->cap_permitted & ~next->cap_ambient))); /* Linux fs/exec.c:setup_new_exec clears pdeath_signal on bprm->secureexec * so a parent cannot signal a privileged program. */ diff --git a/tools/test_vdso_mapping.py b/tools/test_vdso_mapping.py index b72efbb1..ab8caf96 100644 --- a/tools/test_vdso_mapping.py +++ b/tools/test_vdso_mapping.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Exercise actual vDSO mapping, physical references and initial auxv layout.""" +"""Exercise vDSO mapping, initial auxv and namespace exec credentials.""" from pathlib import Path import os import subprocess @@ -21,7 +21,8 @@ def main(): "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", - f"tools/tests/{name}_test.c", "-o", str(binary), + f"tools/tests/{name}_test.c", "kernel/sched/user_namespace.c", + "-o", str(binary), ], cwd=ROOT, check=True) subprocess.run([str(binary)], cwd=ROOT, check=True, timeout=30) diff --git a/tools/tests/vdso_auxv_test.c b/tools/tests/vdso_auxv_test.c index 960b189b..222d23f5 100644 --- a/tools/tests/vdso_auxv_test.c +++ b/tools/tests/vdso_auxv_test.c @@ -3,10 +3,194 @@ #include #include #include +#include +#include "../../fs/fs_internal.h" #include "../../kernel/exec/userland.c" static unsigned char stack[16 * 4096] __attribute__((aligned(4096))); static const uint64_t top = 0x2ffff000; +static struct reliefos_permissions image_permissions; +static uint64_t image_mount_flags; +static bool shared_fs; +static int metadata_error; +static unsigned allocations; + +void *kernel_malloc(size_t size) +{ + void *memory = malloc(size); + if (memory) ++allocations; + return memory; +} + +void kernel_free(void *memory) +{ + if (memory) { assert(allocations); --allocations; } + free(memory); +} + +/* Supply retained-inode metadata and external CLONE_FS ownership at the + * credential preparer's boundary. The real namespace and exec logic run. */ +int vfs_path_permissions(const struct vfs_path *path, struct reliefos_permissions *value, bool write) +{ + (void)path; + (void)write; + if (metadata_error) return metadata_error; + *value = image_permissions; + return 0; +} + +uint64_t vfs_path_mount_flags(const struct vfs_path *path) +{ + (void)path; + return image_mount_flags; +} + +bool sched_task_fs_shared_outside_group(const struct task *task) +{ + (void)task; + return shared_fs; +} + +/** @brief Publish a real local root and eight UIDs/GIDs through proc controls. + * @return Owned namespace mapping UIDs 0..7 to 1000..1007 and GIDs to 3000..3007. + */ +static struct user_namespace *mapped_namespace(void) +{ + struct task root = {.cap_effective = (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1}; + struct user_namespace *ns = NULL; + struct user_namespace_file control; + uint32_t written; + assert(!user_namespace_create(&root, &ns)); + const char uid_map[] = "0 1000 8\n"; + const char gid_map[] = "0 3000 8\n"; + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_UID_MAP, true, &control)); + assert(!user_namespace_file_write(&control, &root, 0, uid_map, sizeof(uid_map) - 1, &written)); + user_namespace_file_close(&control); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_GID_MAP, true, &control)); + assert(!user_namespace_file_write(&control, &root, 0, gid_map, sizeof(gid_map) - 1, &written)); + user_namespace_file_close(&control); + return ns; +} + +/** @brief Check actual stack and saved auxv IDs against independently chosen IDs. + * @param task Prepared image and arguments. @param ids Expected UID/EUID/GID/EGID. + * @param secure Expected AT_SECURE independent of overflow output identities. + */ +static void expect_auxv_ids(struct task *task, const uint32_t ids[4], bool secure) +{ + assert(!prepare_user_exec_stack(task, task->path, 0x28000000)); + uint64_t *words = (void *)(stack + task->frame.rsp - (top - sizeof(stack))); + const uint64_t *aux = words + 4; + const struct task_address_space_state *mm = sched_task_mm(task); + assert(mm->saved_auxv_bytes == 34 * sizeof(uint64_t)); + assert(!memcmp(aux, mm->saved_auxv, mm->saved_auxv_bytes)); + unsigned seen = 0; + for (; aux[0]; aux += 2) { + if (aux[0] >= 11 && aux[0] <= 14) { + assert(aux[1] == ids[aux[0] - 11]); + ++seen; + } + if (aux[0] == 23) assert(aux[1] == secure); + } + assert(seen == 4); +} + +/** @brief Detect global-root assumptions and unmapped set-ID file ownership. + * @param ns Borrowed real namespace with nonidentity maps. + */ +static void test_exec_credentials(struct user_namespace *ns) +{ + struct task *old = calloc(1, sizeof(*old)); + struct task *next = calloc(1, sizeof(*next)); + assert(old && next); + struct storage_inode_ref image_inode = {0}; + const uint64_t bset = (1ULL << CAP_SETUID) | (1ULL << CAP_SYS_BOOT); + const uint64_t inheritable = 1ULL << CAP_NET_BIND_SERVICE; + *old = (struct task){.user_ns = ns, .uid = 1000, .euid = 1000, .suid = 1000, + .fsuid = 1000, .gid = 3001, .egid = 3001, .sgid = 3001, .fsgid = 3001, + .cap_bset = bset, .cap_inheritable = inheritable, + .securebits = SECBIT_KEEP_CAPS, .pdeath_signal = 15}; + sched_task_mm(old)->executable_inode = &image_inode; + image_permissions = (struct reliefos_permissions){0755, 1001, 3001}; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(next->cap_permitted == (bset | inheritable)); + assert(next->cap_effective == next->cap_permitted && !next->secure_exec); + assert(next->pdeath_signal == 15 && !(next->securebits & SECBIT_KEEP_CAPS)); + + old->securebits = SECBIT_NOROOT; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(!next->cap_permitted && !next->cap_effective); + old->securebits = 0; + + old->uid = old->euid = old->suid = old->fsuid = 1001; + image_permissions = (struct reliefos_permissions){06755, 1000, 3002}; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(next->uid == 1001 && next->euid == 1000 && next->suid == 1000 && next->fsuid == 1000); + assert(next->gid == 3001 && next->egid == 3002 && next->sgid == 3002 && next->fsgid == 3002); + assert(next->cap_permitted == (bset | inheritable) && next->cap_effective == next->cap_permitted); + assert(next->secure_exec && !next->pdeath_signal && sched_task_mm(next)->nondumpable); + + /* Both file ownership IDs must be mapped even when just one set-ID bit is used. */ + const struct reliefos_permissions unmapped[] = { + {04755, 1000, 9999}, {02755, 9999, 3002}, {06755, 0, 0}, + }; + for (unsigned i = 0; i < sizeof(unmapped) / sizeof(unmapped[0]); ++i) { + image_permissions = unmapped[i]; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(next->euid == 1001 && next->egid == 3001); + assert(!next->cap_permitted && !next->cap_effective && !next->secure_exec); + } + + image_permissions = (struct reliefos_permissions){06755, 1000, 3002}; + old->no_new_privs = true; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(next->euid == 1001 && next->egid == 3001 && !next->cap_permitted); + old->no_new_privs = false; + image_mount_flags = MS_NOSUID; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(next->euid == 1001 && next->egid == 3001 && !next->cap_permitted); + image_mount_flags = 0; + shared_fs = true; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(next->euid == 1001 && next->egid == 3001 && !next->cap_permitted); + shared_fs = false; + + image_permissions = (struct reliefos_permissions){02644, 1000, 3002}; + old->cap_ambient = old->cap_permitted = old->cap_effective = 1ULL << CAP_KILL; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(next->egid == 3001 && next->cap_ambient == (1ULL << CAP_KILL)); + assert(next->cap_permitted == next->cap_ambient && next->cap_effective == next->cap_ambient); + assert(!next->secure_exec); + + old->uid = old->euid = old->suid = old->fsuid = 0; + old->cap_ambient = 0; + image_permissions.mode = 0755; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(!next->cap_permitted && !next->cap_effective && !next->secure_exec); + + /* The initial namespace keeps its ordinary UID-zero behavior. */ + old->user_ns = NULL; + *next = *old; + assert(!userland_prepare_exec_credentials(next, old)); + assert(next->cap_permitted == (bset | inheritable) && next->cap_effective == next->cap_permitted); + metadata_error = -LINUX_EIO; + *next = *old; + assert(userland_prepare_exec_credentials(next, old) == -LINUX_EIO); + assert(next->euid == old->euid && next->cap_permitted == old->cap_permitted); + metadata_error = 0; + free(next); + free(old); + puts("PASS namespace exec credentials: local root, set-ID mapping, restrictions and ambient capabilities"); +} uint64_t address_space_user_page_phys(const struct address_space *as, uint64_t address) { (void)as; @@ -68,6 +252,23 @@ int main(void) struct reliefos_dynamic_launch launch; memcpy(&launch, stack + (task->frame.r8 - (top - sizeof(stack))), sizeof(launch)); assert(launch.abi_major == RELIEFOS_ELF_ABI_MAJOR && launch.main_entry == 0x400100); + + task->uid = 1234; task->euid = 1235; task->gid = 2345; task->egid = 2346; + expect_auxv_ids(task, (const uint32_t[]){1234, 1235, 2345, 2346}, true); + struct user_namespace *ns = mapped_namespace(); + task->user_ns = ns; + task->uid = 1001; task->euid = 1002; task->gid = 3003; task->egid = 3004; + expect_auxv_ids(task, (const uint32_t[]){1, 2, 3, 4}, true); + task->uid = 9998; task->euid = 9999; task->gid = 9998; task->egid = 9999; + expect_auxv_ids(task, (const uint32_t[]){65534, 65534, 65534, 65534}, true); + task->uid = task->euid = 1000; task->gid = task->egid = 3000; + expect_auxv_ids(task, (const uint32_t[]){0, 0, 0, 0}, false); + task->secure_exec = true; + expect_auxv_ids(task, (const uint32_t[]){0, 0, 0, 0}, true); + test_exec_credentials(ns); + user_namespace_put(ns); + task->user_ns = NULL; + assert(!allocations); free(task); puts("PASS ELF entry: vDSO auxv, SysV stack, null native destructor and private launch ABI"); return 0; From 5a6f4bacb97605a9caf9b143f220b72f51370f74 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 00:17:56 +0800 Subject: [PATCH 58/97] feat(userns): map filesystem metadata and ownership identities --- Documentation/core-api/mount-namespaces.rst | 16 ++- .../LC_MESSAGES/core-api/mount-namespaces.po | 38 +++++- .../LC_MESSAGES/core-api/mount-namespaces.po | 39 +++++- kernel/syscall/fs/metadata.c | 11 +- kernel/syscall/fs/permissions.c | 57 ++++++-- tools/tests/descriptor_table_test.c | 128 +++++++++++++++++- tools/tests/task8_host_fixtures.json | 4 + tools/tests/task8_metadata_user_test.c | 118 ++++++++++++++-- 8 files changed, 368 insertions(+), 43 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 1d309544..f367b6e6 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -141,5 +141,19 @@ ELF 初始栈与保存的 auxv 中,``AT_UID``、``AT_EUID``、``AT_GID`` 和 并遵循 securebits、能力边界集、继承与 ambient 集合规则。保存身份与文件系统 身份继续使用全局 ID;特权执行仍清除父死亡信号并限制可转储状态。 +文件元数据与所有权 +================== + +``stat/lstat/fstat/newfstatat/statx`` 在最终复制到用户内存时,将所有者 UID/GID +转换为调用方空间的 ID,未映射时输出 65534。内部元数据查询、权限比较和等待 +输出页期间保存的快照继续使用全局 ID。复制重试保留原快照,并支持未对齐的 +stat/statx 输出地址。 + +``chown/lchown/fchown/fchownat`` 先解析原路径或已保留的描述符,再将指定的 +UID/GID 全部转换为全局 ID。``UINT32_MAX`` 保留不修改语义。任一指定 ID 未映射 +时返回 ``EINVAL``,保留原所有者和权限。路径查找、无效描述符、``O_PATH`` 与 +只读挂载的原有错误优先级保留。实际 VFS 路径、内建设备及隐式终端采用同一 +身份转换规则,现有 DAC 和 set-ID 清除规则继续生效。 + 内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 -``EINVAL``。文件元数据等其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。 +``EINVAL``。其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index a63f8af4..be69a835 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -289,11 +289,41 @@ msgstr "" "Saved and filesystem credentials use global IDs. Privileged execution " "clears the parent-death signal and restricts dumpability." +msgid "文件元数据与所有权" +msgstr "File metadata and ownership" + +msgid "" +"``stat/lstat/fstat/newfstatat/statx`` 在最终复制到用户内存时,将所有者 UID/GID " +"转换为调用方空间的 ID,未映射时输出 65534。内部元数据查询、权限比较和等待 " +"输出页期间保存的快照继续使用全局 ID。复制重试保留原快照,并支持未对齐的 " +"stat/statx 输出地址。" +msgstr "" +"``stat/lstat/fstat/newfstatat/statx`` translate owner UID/GID into the caller's " +"namespace during final userspace copyout, reporting 65534 for unmapped IDs. " +"Internal metadata queries, permission comparisons and snapshots retained " +"while waiting for output pages use global IDs. Copyout retries preserve the " +"original snapshot and support unaligned stat/statx output addresses." + +msgid "" +"``chown/lchown/fchown/fchownat`` 先解析原路径或已保留的描述符,再将指定的 " +"UID/GID 全部转换为全局 ID。``UINT32_MAX`` 保留不修改语义。任一指定 ID 未映射 " +"时返回 ``EINVAL``,保留原所有者和权限。路径查找、无效描述符、``O_PATH`` 与 " +"只读挂载的原有错误优先级保留。实际 VFS 路径、内建设备及隐式终端采用同一 " +"身份转换规则,现有 DAC 和 set-ID 清除规则继续生效。" +msgstr "" +"``chown/lchown/fchown/fchownat`` resolve the original path or retained " +"descriptor before translating every specified UID/GID into a global ID. " +"``UINT32_MAX`` retains its no-change meaning. Any unmapped specified ID " +"returns ``EINVAL`` and preserves ownership and permissions. Existing error " +"precedence for path lookup, invalid descriptors, ``O_PATH`` and read-only " +"mounts is preserved. Actual VFS paths, builtin devices and implicit terminals " +"use the same identity translation rules. Existing DAC and set-ID clearing " +"rules still apply." + msgid "" -"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``。文件元数据等其余用户态 ID " -"边界、创建入口和用户空间句柄仍待接入。" +"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 " +"``EINVAL``。其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。" msgstr "" "Internal allocation and reference interfaces are available. Userspace " "``CLONE_NEWUSER`` currently returns ``EINVAL``. Remaining userspace ID " -"boundaries, including file metadata, creation entry points and user-" -"namespace handles still await integration." +"boundaries, creation entry points and user-namespace handles await integration." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 904bde91..fa40b3b7 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -248,9 +248,40 @@ msgstr "" "ID を基準にし、securebits、能力の境界集合、継承集合、ambient 集合の規則に従います。保存 ID とファイルシステム ID " "はグローバル ID を使います。特権実行では親死亡シグナルを消去し、ダンプ可能性を制限します。" +msgid "文件元数据与所有权" +msgstr "ファイルメタデータと所有権" + +msgid "" +"``stat/lstat/fstat/newfstatat/statx`` 在最终复制到用户内存时,将所有者 UID/GID " +"转换为调用方空间的 ID,未映射时输出 65534。内部元数据查询、权限比较和等待 " +"输出页期间保存的快照继续使用全局 ID。复制重试保留原快照,并支持未对齐的 " +"stat/statx 输出地址。" +msgstr "" +"``stat/lstat/fstat/newfstatat/statx`` はユーザーメモリへの最終コピー時に、所有者の " +"UID/GID を呼び出し元の名前空間の ID に変換し、未マッピングの場合は 65534 を返します。" +"内部のメタデータ照会、権限比較、出力ページの待機中に保持するスナップショットはグローバル " +"ID を使います。コピーの再試行では元のスナップショットを保持し、アラインされていない " +"stat/statx の出力アドレスも扱えます。" + +msgid "" +"``chown/lchown/fchown/fchownat`` 先解析原路径或已保留的描述符,再将指定的 " +"UID/GID 全部转换为全局 ID。``UINT32_MAX`` 保留不修改语义。任一指定 ID 未映射 " +"时返回 ``EINVAL``,保留原所有者和权限。路径查找、无效描述符、``O_PATH`` 与 " +"只读挂载的原有错误优先级保留。实际 VFS 路径、内建设备及隐式终端采用同一 " +"身份转换规则,现有 DAC 和 set-ID 清除规则继续生效。" +msgstr "" +"``chown/lchown/fchown/fchownat`` は元のパスまたは保持した記述子を解決してから、" +"指定されたすべての UID/GID をグローバル ID に変換します。``UINT32_MAX`` " +"は変更しない意味を保持します。指定 ID が未マッピングの場合は ``EINVAL`` " +"を返し、所有者と権限を保持します。パス検索、無効な記述子、``O_PATH``、" +"読み取り専用マウントの既存のエラー優先順位を維持します。実際の VFS " +"パス、組み込みデバイス、暗黙の端末に同じ識別情報の変換規則を適用し、" +"既存の DAC と set-ID ビットの消去規則も引き続き適用します。" + msgid "" -"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``。文件元数据等其余用户态 ID " -"边界、创建入口和用户空间句柄仍待接入。" +"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 " +"``EINVAL``。其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。" msgstr "" -"カーネル内部の空間割り当てと参照インターフェースを提供します。現在、ユーザー空間の ``CLONE_NEWUSER`` は ``EINVAL`` " -"を返します。ファイルメタデータなどの残りのユーザー空間 ID 境界、作成入口、ユーザー名前空間ハンドルの接続は今後の作業です。" +"カーネル内部の空間割り当てと参照インターフェースを提供します。現在、ユーザー空間の " +"``CLONE_NEWUSER`` は ``EINVAL`` を返します。残りのユーザー空間 ID " +"境界、作成入口、ユーザー名前空間ハンドルの接続は今後の作業です。" diff --git a/kernel/syscall/fs/metadata.c b/kernel/syscall/fs/metadata.c index 42cc330d..27fe4157 100644 --- a/kernel/syscall/fs/metadata.c +++ b/kernel/syscall/fs/metadata.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" #include +#include /* Retain attachment metadata alongside the completed inode snapshot while * preparing user output. These values are not collected again on copyout retry. */ @@ -180,7 +181,9 @@ static int metadata_at_stat(struct vfs_namespace *ns,struct task *task,int32_t d * metadata retrieval and writable-range validation. Provider waits retain the * original inode/OFD; no graph/module spinlock spans I/O. Statx advertises * mount-root detection and reports the legacy mount ID when available, - * regardless of the requested mask. + * regardless of the requested mask. Ownership is retained as global IDs across + * output-page waits, then mapped into the caller's user namespace at copyout. + * Unmapped IDs use 65534 and unaligned stat/statx output is supported. */ int64_t syscall_metadata(struct vfs_namespace *ns,struct task *task,uint64_t number, uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4) @@ -250,6 +253,8 @@ int64_t syscall_metadata(struct vfs_namespace *ns,struct task *task,uint64_t num rc=metadata_prepare_result(task,output,output_size,slot,result_kind,&value,sizeof(value),NULL); if(rc)return rc; if(!user_range_writable(output,output_size))return -RELIEFOS_EFAULT; + value.stat.st_uid=user_namespace_id_from_kernel_munged(task->user_ns,false,value.stat.st_uid); + value.stat.st_gid=user_namespace_id_from_kernel_munged(task->user_ns,true,value.stat.st_gid); if(statx) { struct linux_statx extended; linux_statx_from_legacy(&extended,&value.stat,LINUX_STATX_BASIC_STATS); @@ -259,8 +264,8 @@ int64_t syscall_metadata(struct vfs_namespace *ns,struct task *task,uint64_t num } extended.stx_attributes_mask |= LINUX_STATX_ATTR_MOUNT_ROOT; if(value.mount_root)extended.stx_attributes |= LINUX_STATX_ATTR_MOUNT_ROOT; - *(struct linux_statx *)(uintptr_t)output=extended; - } else *(struct linux_stat_abi *)(uintptr_t)output=value.stat; + __builtin_memcpy((void *)(uintptr_t)output,&extended,sizeof(extended)); + } else __builtin_memcpy((void *)(uintptr_t)output,&value.stat,sizeof(value.stat)); return 0; } diff --git a/kernel/syscall/fs/permissions.c b/kernel/syscall/fs/permissions.c index c1bbac9f..2fcf6335 100644 --- a/kernel/syscall/fs/permissions.c +++ b/kernel/syscall/fs/permissions.c @@ -1,16 +1,35 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" +#include + +/** @brief Translate both ownership inputs before any provider mutation. + * @param task Borrowed calling task with stable user namespace credentials. + * @param uid In/out local user ID, replaced by its global ID on success. + * @param gid In/out local group ID, replaced by its global ID on success. + * @return Zero or EINVAL for an unmapped specified ID. UINT32_MAX preserves + * its no-change meaning. Allocation-free and leaves both inputs on failure. + */ +static int permissions_chown_ids(const struct task *task,uint32_t *uid,uint32_t *gid) +{ + uint32_t mapped_uid=user_namespace_id_to_kernel(task->user_ns,false,*uid); + uint32_t mapped_gid=user_namespace_id_to_kernel(task->user_ns,true,*gid); + if((*uid!=UINT32_MAX && mapped_uid==UINT32_MAX) || + (*gid!=UINT32_MAX && mapped_gid==UINT32_MAX))return -RELIEFOS_EINVAL; + *uid=mapped_uid;*gid=mapped_gid;return 0; +} /** @brief Apply chmod/chown to the original descriptor without name replay. * @param task Borrowed calling task with dispatcher-owned OFD/PTY admission. * @param fd Descriptor number, possibly closed/reused since admission. * @param chmod Select mode change instead of ownership change. - * @param value Mode or user ID. - * @param gid Group ID for ownership changes; UINT32_MAX preserves it. + * @param value Mode or namespace-local user ID. + * @param gid Namespace-local group ID; UINT32_MAX preserves it. * @return Zero or negative errno. O_PATH is rejected for descriptor variants. * Builtin implicit terminals and materialized builtin device descriptions use * their admitted inode identity, independent of a displayed pathname; - * all opened path objects retain the provider across metadata I/O. + * all opened path objects retain the provider across metadata I/O. The original + * descriptor is validated before both ownership inputs are mapped to global + * IDs, preserving descriptor/type error precedence. */ static int permissions_fd(struct task *task,int fd,bool chmod,uint32_t value,uint32_t gid) { @@ -23,17 +42,25 @@ static int permissions_fd(struct task *task,int fd,bool chmod,uint32_t value,uin struct task_pty_fd *endpoint=task_pty_for_io(task,fd); if(endpoint && endpoint->description)path=&endpoint->description->path_ref; } - if(path && vfs_path_node(path))return chmod ? fs_permissions_chmod_path(task,path,value) : - fs_permissions_chown_path(task,path,value,gid); - if(file) { - if(!(file->flags&(TASK_FILE_FLAG_DEV_NODE|TASK_FILE_FLAG_DEV_NULL)) || - !(file->node.flags&STORAGE_NODE_FLAG_DEV_NODE))return -RELIEFOS_EOPNOTSUPP; - return chmod ? fs_virtual_chmod(task,"builtin-device",&file->node,value) : - fs_virtual_chown(task,"builtin-device",&file->node,value,gid); + bool held_path=path && vfs_path_node(path); + struct storage_node node;const char *intrinsic="builtin-device"; + if(!held_path) { + if(file) { + if(!(file->flags&(TASK_FILE_FLAG_DEV_NODE|TASK_FILE_FLAG_DEV_NULL)) || + !(file->node.flags&STORAGE_NODE_FLAG_DEV_NODE))return -RELIEFOS_EOPNOTSUPP; + node=file->node; + } else { + int rc=task_pty_node_for_fd(task,fd,&node,&intrinsic); + if(rc)return rc; + } } - struct storage_node node;const char *intrinsic; - int rc=task_pty_node_for_fd(task,fd,&node,&intrinsic); - if(rc)return rc; + if(!chmod) { + if(held_path && (vfs_path_mount_flags(path)&MS_RDONLY))return -RELIEFOS_EROFS; + int rc=permissions_chown_ids(task,&value,&gid); + if(rc)return rc; + } + if(held_path)return chmod ? fs_permissions_chmod_path(task,path,value) : + fs_permissions_chown_path(task,path,value,gid); return chmod ? fs_virtual_chmod(task,intrinsic,&node,value) : fs_virtual_chown(task,intrinsic,&node,value,gid); } @@ -49,6 +76,8 @@ static int permissions_fd(struct task *task,int fd,bool chmod,uint32_t value,uin * @param a4 FCHOWNAT flags. * @return Zero or negative errno. Search checks and final authorization use * actual retained objects; real IDs are used by access unless AT_EACCESS. + * Ownership inputs are namespace-local and both are translated after lookup + * succeeds. Unmapped specified IDs return EINVAL before provider mutation. * Common resolver state retains operands across I/O, with no graph/module * spinlock held by this dispatcher or across provider callbacks. */ @@ -76,6 +105,8 @@ int64_t syscall_permissions(struct vfs_namespace *ns,struct task *task,uint64_t struct vfs_lookup_result found={0}; int rc=resolve_user_object_at_flags(ns,task,at ? (int32_t)a0 : LINUX_AT_FDCWD, at ? a1 : a0,(flags&LINUX_AT_EMPTY_PATH)!=0,real_ids,follow,&found); + if(!rc && !access && !chmod)rc=(vfs_path_mount_flags(&found.path)&MS_RDONLY) ? + -RELIEFOS_EROFS : permissions_chown_ids(task,&value,&gid); if(!rc)rc=access ? fs_permissions_check_path(task,&found.path,value,real_ids) : chmod ? fs_permissions_chmod_path(task,&found.path,value) : fs_permissions_chown_path(task,&found.path,value,gid); diff --git a/tools/tests/descriptor_table_test.c b/tools/tests/descriptor_table_test.c index 746c4564..92298ae9 100644 --- a/tools/tests/descriptor_table_test.c +++ b/tools/tests/descriptor_table_test.c @@ -9,6 +9,7 @@ #include #include #include +#include #include "../../fs/fs_internal.h" #include /** @brief Keep device discovery outside this descriptor-table fixture. @@ -22,6 +23,8 @@ int devfs_lookup_rdev(uint32_t type,uint64_t device,struct storage_node *out) static struct storage_inode_ref descriptor_inode; static unsigned descriptor_truncates; static int descriptor_truncate_error,descriptor_inode_get_error; +static bool descriptor_pty_permissions_enabled; +static struct reliefos_permissions descriptor_pty_permissions; static struct task *descriptor_dispatch_task; static unsigned transfer_pipe_mode,transfer_pipe_calls,transfer_pipe_bytes; @@ -304,14 +307,22 @@ long driver_manager_audio_write_bound(uint32_t generation, const void *data, { (void)generation; (void)data; (void)count; (void)status; abort(); } int driver_manager_audio_state_bound(uint32_t generation, struct reliefos_audio_state *state) { (void)generation; (void)state; abort(); } -/* These newly linked open/stat branches are forbidden in this regular-file - * provider fixture. Real DAC is linked; unrelated hardware/PTY/shmem entry - * points fail loudly instead of standing in for regular namespace behavior. */ +/* Real DAC is linked. PTY metadata is enabled only by the ownership fixture. + * Unrelated hardware/shmem entry points fail loudly at the provider boundary. */ uint64_t storage_volume_device(uint32_t volume){assert(!volume);return 1;} int storage_inode_stat(const struct storage_node *node,struct linux_stat_abi *out){(void)node;(void)out;abort();} -int pty_get_node(uint32_t id,struct storage_node *node){(void)id;(void)node;abort();} +int pty_get_node(uint32_t id,struct storage_node *node) +{ + assert(descriptor_pty_permissions_enabled && id==1); + *node=(struct storage_node){.type=RELIEFOS_FS_TYPE_DEVICE, + .flags=STORAGE_NODE_FLAG_PTY,.first_cluster=1};return 0; +} int pty_inode_permissions(const struct storage_node *node,struct reliefos_permissions *value,bool write) -{(void)node;(void)value;(void)write;abort();} +{ + assert(descriptor_pty_permissions_enabled && node->first_cluster==1); + if(write)descriptor_pty_permissions=*value;else *value=descriptor_pty_permissions; + return 0; +} int32_t pty_create(uint32_t owner){(void)owner;abort();} int pty_destroy(uint32_t owner,uint32_t id){(void)owner;(void)id;abort();} void pty_open_controlling(uint32_t id,uint32_t caller,int readable){(void)id;(void)caller;(void)readable;abort();} @@ -1227,6 +1238,22 @@ static void test_standard_character_stat(void) puts("PASS Linux devfs identities and independent native inode rdev"); } +/** @brief Publish nonidentity maps through the real captured proc controls. */ +static struct user_namespace *descriptor_user_namespace(void) +{ + struct task root={.cap_effective=UINT64_MAX}; + struct user_namespace *ns=NULL;struct user_namespace_file control;uint32_t written; + assert(!user_namespace_create(&root,&ns)); + const char *maps[]={"0 1000 8\n","0 3000 8\n"}; + for(unsigned group=0;group<2;++group) { + assert(!user_namespace_file_open(ns,&root,group ? USER_NAMESPACE_GID_MAP : + USER_NAMESPACE_UID_MAP,true,&control)); + assert(!user_namespace_file_write(&control,&root,0,maps[group],strlen(maps[group]),&written)); + user_namespace_file_close(&control); + } + return ns; +} + static void test_materialized_console_permissions(void) { struct task *task=calloc(1,sizeof(*task));assert(task); @@ -1245,6 +1272,12 @@ static void test_materialized_console_permissions(void) file->flags|=TASK_FILE_FLAG_PATH; assert(syscall_permissions(NULL,task,LINUX_SYS_FCHMOD,0,0666,0,0,0)==-RELIEFOS_EBADF); file->flags&=~TASK_FILE_FLAG_PATH; + assert(!syscall_permissions(NULL,task,LINUX_SYS_FCHOWN,0,1002,3003,0,0)); + task->user_ns=descriptor_user_namespace();task->fsuid=1002;task->fsgid=3003; + assert(!syscall_permissions(NULL,task,LINUX_SYS_FCHOWN,0,2,3,0,0)); + assert(!linux_stat_from_fd(task,0,false,&changed) && changed.st_uid==1002 && changed.st_gid==3003); + assert(syscall_permissions(NULL,task,LINUX_SYS_FCHOWN,0,8,3,0,0)==-RELIEFOS_EINVAL); + user_namespace_put(task->user_ns);task->user_ns=NULL;task->fsuid=task->fsgid=0; assert(!syscall_permissions(NULL,task,LINUX_SYS_FCHOWN,0,original.st_uid,original.st_gid,0,0)); assert(!syscall_permissions(NULL,task,LINUX_SYS_FCHMOD,0,original.st_mode&07777,0,0,0)); assert(!linux_stat_from_fd(task,0,false,&changed) && changed.st_mode==original.st_mode && @@ -1298,6 +1331,7 @@ static void test_finit_preflight_retires_other_io(void) /* One regular inode provider boundary around the actual namespace, DAC, * canonical OFD, open/truncate and stat dispatch implementations. */ static unsigned writer_path_pins; +static struct reliefos_permissions writer_file_permissions={0644,0,0}; static int writer_path_lookup(void *context,const struct storage_node *parent,const char *name,struct storage_node *out) { (void)context;assert(parent->type==RELIEFOS_FS_TYPE_DIR); @@ -1311,7 +1345,11 @@ static bool writer_path_same(void *context,const struct storage_node *one,const {(void)context;return one->first_cluster==two->first_cluster && one->type==two->type;} static int writer_path_permissions(void *context,const struct vfs_path *path,struct reliefos_permissions *value,bool write) { - (void)context;assert(!write);*value=(struct reliefos_permissions){vfs_path_node(path)->type==RELIEFOS_FS_TYPE_DIR ? 0755 : 0644,0,0};return 0; + (void)context; + if(vfs_path_node(path)->type==RELIEFOS_FS_TYPE_DIR) { + assert(!write);*value=(struct reliefos_permissions){0755,0,0}; + } else if(write)writer_file_permissions=*value;else *value=writer_file_permissions; + return 0; } static int writer_path_truncate(void *context,struct storage_node *node,uint64_t size) {(void)context;return storage_truncate_held_node(node,size);} @@ -1330,6 +1368,83 @@ static void writer_namespace_close(struct vfs_namespace *ns,struct task *task,st assert(!vfs_namespace_destroy(ns) && !writer_path_pins); } +/** @brief Catch raw local chown IDs, partial mutation and changed lookup errors. */ +static void test_namespace_chown(void) +{ + struct task *task=calloc(1,sizeof(*task));assert(task); + task->limits.nofile.rlim_cur=64;task->cap_effective=UINT64_MAX; + task->fsuid=1002;task->fsgid=3003;task->user_ns=descriptor_user_namespace(); + const uint32_t group=3004;assert(!task_groups_set(task,&group,1)); + descriptor_inode=(struct storage_inode_ref){.references=1, + .node={.type=RELIEFOS_FS_TYPE_FILE,.flags=STORAGE_NODE_FLAG_TMPFS,.first_cluster=501}}; + writer_file_permissions=(struct reliefos_permissions){06755,1002,3003}; + struct vfs_namespace ns={0};struct vfs_path root={0};writer_namespace_open(&ns,task,&root); + uint64_t name=(uintptr_t)"/module.ko",empty=(uintptr_t)""; + int fd=syscall_open_object(&ns,task,LINUX_AT_FDCWD,name,LINUX_O_RDONLY,0); + int pathfd=syscall_open_object(&ns,task,LINUX_AT_FDCWD,name,LINUX_O_PATH,0); + assert(fd>=0 && pathfd>=0); + struct { + uint64_t number,a0,a1,a2,a3,a4; + } calls[]={ + {LINUX_SYS_CHOWN,name,2,4,0,0}, + {LINUX_SYS_LCHOWN,name,2,4,0,0}, + {LINUX_SYS_FCHOWNAT,LINUX_AT_FDCWD,name,2,4,0}, + {LINUX_SYS_FCHOWN,fd,2,4,0,0}, + {LINUX_SYS_FCHOWNAT,pathfd,empty,2,4,LINUX_AT_EMPTY_PATH}, + }; + for(unsigned i=0;i=0); + assert(syscall_permissions(&ns,task,LINUX_SYS_FCHOWN,anonymous_fd,8,8,0,0)==-RELIEFOS_EOPNOTSUPP); + task_discard_file_fd(task,anonymous_fd);task_discard_file_fd(task,pathfd);task_discard_file_fd(task,fd); + writer_namespace_close(&ns,task,&root);writer_file_permissions=(struct reliefos_permissions){0644,0,0}; + + descriptor_pty_permissions_enabled=true;task->pty_id=1; + descriptor_pty_permissions=(struct reliefos_permissions){0600,1002,3003}; + sched_task_fds(task)->closed_stdio_mask=0; + assert(!syscall_permissions(NULL,task,LINUX_SYS_FCHOWN,0,2,4,0,0)); + assert(descriptor_pty_permissions.uid==1002 && descriptor_pty_permissions.gid==3004); + assert(syscall_permissions(NULL,task,LINUX_SYS_FCHOWN,0,8,4,0,0)==-RELIEFOS_EINVAL); + assert(descriptor_pty_permissions.uid==1002 && descriptor_pty_permissions.gid==3004); + descriptor_pty_permissions_enabled=false;task->pty_id=0; + task_groups_put(task->groups);user_namespace_put(task->user_ns); + sched_task_file_release(task);free(task); + puts("PASS namespace chown: paths, held/O_PATH FDs, terminal ownership, sentinels, atomic rejection and lookup precedence"); +} + /** @brief Let a caller detect O_PATH via F_GETFL without admitting I/O. */ static void test_path_status_flags(void) { @@ -3324,6 +3439,7 @@ int main(void) test_mmap_retry_description(); test_standard_character_stat(); test_materialized_console_permissions(); + test_namespace_chown(); test_finit_preflight_before_allocation(); test_finit_preflight_retires_other_io(); test_regular_inode_writer_ofd_lifetime(); diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 4cc7d33f..7ebb462d 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -1125,6 +1125,8 @@ "-Iinclude", "-Iinclude/uapi", "tools/tests/task8_metadata_user_test.c", + "kernel/syscall/fs/stat.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/metadata-user-green-3" ] @@ -1152,6 +1154,8 @@ "-Iinclude", "-Iinclude/uapi", "tools/tests/task8_metadata_user_test.c", + "kernel/syscall/fs/stat.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/metadata-user-noswap" ] diff --git a/tools/tests/task8_metadata_user_test.c b/tools/tests/task8_metadata_user_test.c index 4a582856..d91b2309 100644 --- a/tools/tests/task8_metadata_user_test.c +++ b/tools/tests/task8_metadata_user_test.c @@ -10,10 +10,12 @@ #include #include "../../kernel/syscall/fs/metadata.c" #include +#include static struct task current; static struct task_file file; static struct storage_node node; static int64_t provider_size=123; +static uint32_t provider_uid,provider_gid; static struct vfs_namespace namespace; static struct task_lookup_path result_slot; static uint64_t swapped; @@ -88,37 +90,128 @@ struct task_pty_fd *task_pty_fd_for_fd(struct task *task,int fd) int task_pty_node_from_endpoint(const struct task_pty_fd *endpoint,uint32_t implicit, struct storage_node *out,const char **path) { (void)endpoint;(void)implicit;(void)out;(void)path;abort(); } -/** @brief Reject a mount-root check in the legacy fstat/readlink fixture. */ +/** @brief Supply a mount-root identity for the pathname stat fixture. */ bool vfs_path_is_mount_root(const struct vfs_path *path) -{ (void)path;abort(); } -/** @brief Reject a mount ID lookup in the legacy fstat/readlink fixture. */ +{ (void)path;return true; } +/** @brief Supply the retained pathname attachment's mount ID. */ uint64_t vfs_path_mount_id(const struct vfs_path *path) -{ (void)path;abort(); } +{ (void)path;return 17; } int task_pty_stream_for_fd(struct task *task,int fd) { (void)task;(void)fd;return -1; } const struct storage_node *vfs_path_node(const struct vfs_path *path) { (void)path;return &node; } -int linux_stat_from_node(struct linux_stat_abi *out,const struct reliefos_stat *st,const struct storage_node *n) -{ (void)out;(void)st;(void)n;assert(0);return 0; } -void linux_stat_fd_type(struct linux_stat_abi *out,const struct task_file *f) -{ (void)out;assert(f==&file); } +/** @brief Reject inode/device metadata outside the held regular-path fixture. */ +int storage_inode_stat(const struct storage_node *n,struct linux_stat_abi *out) +{ (void)n;(void)out;abort(); } +uint64_t storage_volume_device(uint32_t volume) +{ (void)volume;abort(); } +void devfs_stat_identity(struct linux_stat_abi *out,const struct storage_node *n) +{ (void)out;(void)n;abort(); } int fs_virtual_permissions(const char *path,const struct storage_node *n,struct reliefos_permissions *out,bool write) { (void)path;(void)n;(void)out;(void)write;assert(0);return 0; } -int linux_stat_from_path(struct linux_stat_abi *out,const struct vfs_path *path) +int vfs_path_stat(const struct vfs_path *path,struct linux_stat_abi *out) { (void)path;++callbacks;provider_owned=true; if(pending_once){pending_once=false;return -RELIEFOS_EAGAIN;} - provider_completed=true;*out=(struct linux_stat_abi){.st_size=provider_size};return 0; + provider_completed=true;*out=(struct linux_stat_abi){.st_size=provider_size, + .st_mode=LINUX_S_IFREG|0640,.st_ino=73,.st_nlink=2, + .st_uid=provider_uid,.st_gid=provider_gid};return 0; } int vfs_path_statfs(const struct vfs_path *path,struct linux_statfs_abi *out) { (void)path;(void)out;assert(0);return 0; } -void linux_statx_from_legacy(struct linux_statx *out,const struct linux_stat_abi *st,uint32_t mask) -{ (void)out;(void)st;(void)mask;assert(0); } static void reset_fixture(void) { free(result_slot.name);result_slot=(struct task_lookup_path){0}; callbacks=prepares=snapshots=releases=file_prepares=0;swapped=cold_file=0;contended=provider_owned=provider_completed=pending_once=false; strcpy(provider_result,"destination");provider_size=123; + provider_uid=provider_gid=0; +} + +/** @brief Catch global-ID copyout and repeated conversion of cached results. */ +static void test_namespace_stat(void) +{ + struct task root={.cap_effective=UINT64_MAX}; + struct user_namespace *ns=NULL; + struct user_namespace_file control; + uint32_t written; + assert(!user_namespace_create(&root,&ns)); + const char uid_map[]="0 1000 8\n",gid_map[]="0 3000 8\n"; + assert(!user_namespace_file_open(ns,&root,USER_NAMESPACE_UID_MAP,true,&control)); + assert(!user_namespace_file_write(&control,&root,0,uid_map,sizeof(uid_map)-1,&written)); + user_namespace_file_close(&control); + assert(!user_namespace_file_open(ns,&root,USER_NAMESPACE_GID_MAP,true,&control)); + assert(!user_namespace_file_write(&control,&root,0,gid_map,sizeof(gid_map)-1,&written)); + user_namespace_file_close(&control); + current.user_ns=ns; + const uint64_t numbers[]={LINUX_SYS_STAT,LINUX_SYS_LSTAT,LINUX_SYS_FSTAT, + LINUX_SYS_NEWFSTATAT,LINUX_SYS_STATX}; + for(unsigned i=0;i Date: Mon, 30 Nov 2026 00:32:30 +0800 Subject: [PATCH 59/97] feat(userns): translate socket credentials at namespace boundaries --- Documentation/core-api/mount-namespaces.rst | 14 ++ .../LC_MESSAGES/core-api/mount-namespaces.po | 9 ++ .../LC_MESSAGES/core-api/mount-namespaces.po | 9 ++ kernel/syscall/ipc/socket.c | 55 +++++-- tools/test_ipv6_transport.py | 1 + tools/test_linux_socket_batches.py | 2 +- tools/tests/ipv6_vector_stubs.c | 2 + tools/tests/socket_batch_unix_test.c | 146 +++++++++++++++++- tools/tests/task8_host_fixtures.json | 22 +++ tools/tests/task8_socket_receive_test.c | 10 ++ 10 files changed, 255 insertions(+), 15 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index f367b6e6..a1d2d0b9 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -155,5 +155,19 @@ UID/GID 全部转换为全局 ID。``UINT32_MAX`` 保留不修改语义。任一 只读挂载的原有错误优先级保留。实际 VFS 路径、内建设备及隐式终端采用同一 身份转换规则,现有 DAC 和 set-ID 清除规则继续生效。 +socket 凭据 +=========== + +AF_UNIX 的 ``SCM_CREDENTIALS`` 将发送者空间的 UID/GID 输入转换为全局 ID。 +未映射的输入返回 ``EINVAL``。与真实、有效及保存身份均不匹配的 UID/GID, +分别要求当前用户空间的 ``CAP_SETUID`` 和 ``CAP_SETGID``。PID 使用全局编号, +伪造其他 PID 要求初始用户空间的 ``CAP_SYS_ADMIN``。 + +UNIX 消息、流凭据、对端缓存及等待用户页的阶段状态保存全局身份。最终输出 +``SCM_CREDENTIALS``、``SO_PEERCRED`` 和 netlink ``SO_PASSCRED`` 时,按接收者 +用户空间转换 UID/GID,未映射时输出 65534。``MSG_PEEK`` 和输出重试保留原快照, +截断控制消息也使用相同转换。``SO_PEERCRED`` 的无对端结果保留 PID 0 与 +UID/GID ``UINT32_MAX``。 + 内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``。其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index be69a835..263112d6 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -327,3 +327,12 @@ msgstr "" "Internal allocation and reference interfaces are available. Userspace " "``CLONE_NEWUSER`` currently returns ``EINVAL``. Remaining userspace ID " "boundaries, creation entry points and user-namespace handles await integration." + +msgid "socket 凭据" +msgstr "Socket credentials" + +msgid "AF_UNIX 的 ``SCM_CREDENTIALS`` 将发送者空间的 UID/GID 输入转换为全局 ID。 未映射的输入返回 ``EINVAL``。与真实、有效及保存身份均不匹配的 UID/GID, 分别要求当前用户空间的 ``CAP_SETUID`` 和 ``CAP_SETGID``。PID 使用全局编号, 伪造其他 PID 要求初始用户空间的 ``CAP_SYS_ADMIN``。" +msgstr "AF_UNIX ``SCM_CREDENTIALS`` translates UID/GID inputs from the sender namespace to global IDs. Unmapped inputs return ``EINVAL``. A UID/GID that matches none of the real, effective or saved identities requires ``CAP_SETUID`` or ``CAP_SETGID``, respectively, in the current user namespace. PIDs use global numbering. Supplying another PID requires ``CAP_SYS_ADMIN`` in the initial user namespace." + +msgid "UNIX 消息、流凭据、对端缓存及等待用户页的阶段状态保存全局身份。最终输出 ``SCM_CREDENTIALS``、``SO_PEERCRED`` 和 netlink ``SO_PASSCRED`` 时,按接收者 用户空间转换 UID/GID,未映射时输出 65534。``MSG_PEEK`` 和输出重试保留原快照, 截断控制消息也使用相同转换。``SO_PEERCRED`` 的无对端结果保留 PID 0 与 UID/GID ``UINT32_MAX``。" +msgstr "UNIX messages, stream credentials, peer caches and stages waiting for user pages retain global identities. Final ``SCM_CREDENTIALS``, ``SO_PEERCRED`` and netlink ``SO_PASSCRED`` output translates UID/GID into the receiver user namespace, reporting 65534 for unmapped IDs. ``MSG_PEEK`` and output retries preserve the original snapshot. Truncated control messages use the same translation. An absent peer retains PID 0 and UID/GID ``UINT32_MAX`` for ``SO_PEERCRED``." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index fa40b3b7..f7e2fedc 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -285,3 +285,12 @@ msgstr "" "カーネル内部の空間割り当てと参照インターフェースを提供します。現在、ユーザー空間の " "``CLONE_NEWUSER`` は ``EINVAL`` を返します。残りのユーザー空間 ID " "境界、作成入口、ユーザー名前空間ハンドルの接続は今後の作業です。" + +msgid "socket 凭据" +msgstr "ソケットの資格情報" + +msgid "AF_UNIX 的 ``SCM_CREDENTIALS`` 将发送者空间的 UID/GID 输入转换为全局 ID。 未映射的输入返回 ``EINVAL``。与真实、有效及保存身份均不匹配的 UID/GID, 分别要求当前用户空间的 ``CAP_SETUID`` 和 ``CAP_SETGID``。PID 使用全局编号, 伪造其他 PID 要求初始用户空间的 ``CAP_SYS_ADMIN``。" +msgstr "AF_UNIX の ``SCM_CREDENTIALS`` は送信者の名前空間の UID/GID 入力をグローバル ID に変換します。未マッピングの入力は ``EINVAL`` を返します。実、実効、保存のどの識別情報にも一致しない UID/GID には、それぞれ現在のユーザー名前空間の ``CAP_SETUID`` と ``CAP_SETGID`` が必要です。PID はグローバル番号を使い、別の PID の指定には初期ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要です。" + +msgid "UNIX 消息、流凭据、对端缓存及等待用户页的阶段状态保存全局身份。最终输出 ``SCM_CREDENTIALS``、``SO_PEERCRED`` 和 netlink ``SO_PASSCRED`` 时,按接收者 用户空间转换 UID/GID,未映射时输出 65534。``MSG_PEEK`` 和输出重试保留原快照, 截断控制消息也使用相同转换。``SO_PEERCRED`` 的无对端结果保留 PID 0 与 UID/GID ``UINT32_MAX``。" +msgstr "UNIX メッセージ、ストリームの資格情報、対向のキャッシュ、ユーザーページ待機中の段階状態はグローバルな識別情報を保持します。``SCM_CREDENTIALS``、``SO_PEERCRED``、netlink の ``SO_PASSCRED`` の最終出力では UID/GID を受信者のユーザー名前空間に変換し、未マッピングの ID は 65534 を返します。``MSG_PEEK`` と出力の再試行は元のスナップショットを保持します。切り詰められた制御メッセージも同じ変換を使います。``SO_PEERCRED`` の対向がない場合は PID 0 と UID/GID ``UINT32_MAX`` を保持します。" diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index fa7e8efe..08466e23 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -1694,12 +1695,29 @@ static int unix_message_vectors(struct msghdr *message, uint64_t *total) return 0; } +/** @brief Convert a global credential snapshot for one userspace copyout. + * @param task Receiving caller, nullable for the initial user namespace. + * @param credentials Global UID/GID snapshot, passed by value. + * @return Local UID/GID or overflow 65534, preserving the global PID. + * Queued, peer and retry-stage credentials retain their global identities. + */ +static struct ucred socket_user_credentials(const struct task *task, + struct ucred credentials) +{ + const struct user_namespace *ns = task ? task->user_ns : NULL; + credentials.uid = user_namespace_id_from_kernel_munged(ns, false, credentials.uid); + credentials.gid = user_namespace_id_from_kernel_munged(ns, true, credentials.gid); + return credentials; +} + /** @brief Parse one admitted UNIX ancillary buffer and retain each fd entry. * @param task Sender. @param message Original message metadata. @param out - * Receives owned rights. @param credentials Receives supplied credentials. + * Receives owned rights. @param credentials Receives global supplied credentials. * @param explicit_credentials Reports a credentials record. @param kernel_control * Selects an already owned kernel snapshot. @return Zero or a negative errno. - * Overriding global sender IDs or the PID requires initial user namespace capabilities. + * Sender-local UID/GID inputs require mappings and current-namespace authority + * to override real, effective or saved IDs. PID overrides require initial-scope + * CAP_SYS_ADMIN while PIDs use the global namespace. */ static int unix_message_rights_common(struct task *task, const struct msghdr *message, struct unix_rights **out, struct ucred *credentials, @@ -1728,14 +1746,16 @@ static int unix_message_rights_common(struct task *task, const struct msghdr *me if (header.cmsg_len != CMSG_LEN(sizeof(*credentials))) { result = -RELIEFOS_EINVAL; break; } for (unsigned i = 0; i < sizeof(*credentials); ++i) ((uint8_t *)credentials)[i] = bytes[CMSG_LEN(0) + i]; + credentials->uid = user_namespace_id_to_kernel(task->user_ns, false, credentials->uid); + credentials->gid = user_namespace_id_to_kernel(task->user_ns, true, credentials->gid); if (credentials->uid == UINT32_MAX || credentials->gid == UINT32_MAX) { result = -RELIEFOS_EINVAL; break; } /* Linux v6.12 net/core/scm.c: each forged field requires its * own effective capability, including for an euid-zero sender. */ - uint64_t capabilities = task_initial_capabilities(task); + uint64_t capabilities = task->cap_effective; if ((credentials->pid != (int32_t)sched_task_tgid(task) && - !(capabilities & (1ULL << CAP_SYS_ADMIN))) || + !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) || (credentials->uid != task->uid && credentials->uid != task->euid && credentials->uid != task->suid && !(capabilities & (1ULL << CAP_SETUID))) || (credentials->gid != task->gid && credentials->gid != task->egid && @@ -2101,6 +2121,7 @@ static void socket_receive_finish(struct task *task,struct socket_send_stage *st * Accepted packet bytes and ancillary ownership survive contention; each * output data slice is prepared and copied once. Metadata/descriptor outputs * are pinned before descriptor installation so retries cannot duplicate it. + * Credential staging remains global and is mapped only into copyout bytes. */ static int unix_recvmsg_staged(struct task *task,struct task_file *file,uint64_t user_msg, uint64_t name_length_pointer,struct msghdr message,uint32_t flags,uint64_t total, @@ -2223,8 +2244,9 @@ static int unix_recvmsg_staged(struct task *task,struct task_file *file,uint64_t control_bytes=timestamp_end; credential_start=(uint32_t)prepared.msg_controllen; if(stage->passcred) { + struct ucred credentials=socket_user_credentials(task,stage->metadata.credentials); credential_end=(uint32_t)unix_put_control(&prepared,capacity,SCM_CREDENTIALS, - &stage->metadata.credentials,sizeof(stage->metadata.credentials)); + &credentials,sizeof(credentials)); if(credential_end>control_bytes)control_bytes=credential_end; } uint64_t ancillary_used=prepared.msg_controllen; @@ -2396,6 +2418,7 @@ int task_socket_signal_finish(struct task *task) * @param flags Linux receive flags. @param total Total vector capacity. * @param output Message flags output. * @return Bytes, negative errno, or a private wait marker. + * Credential copyout maps global snapshots into the caller's user namespace. */ static int unix_recvmsg(struct task *task, struct task_file *file, const struct msghdr *user_msg, struct msghdr message, @@ -2489,9 +2512,11 @@ complete_message: ; if (socket && socket->timestamp_option && metadata.timestamp_valid) (void)unix_put_control(&message, capacity, socket->timestamp_option, &metadata.timestamp, sizeof(metadata.timestamp)); - if (passcred) + if (passcred) { + struct ucred credentials = socket_user_credentials(task, metadata.credentials); (void)unix_put_control(&message, capacity, SCM_CREDENTIALS, - &metadata.credentials, sizeof(metadata.credentials)); + &credentials, sizeof(credentials)); + } uint8_t *control = (uint8_t *)message.msg_control + message.msg_controllen; capacity -= message.msg_controllen; if (rights) { @@ -2547,7 +2572,8 @@ complete_message: ; * @param output Captured input length and output flags. * @return Bytes processed, negative errno, or the internal blocking sentinel. * @note Netlink SO_PASSCRED reflects the sender metadata of the dequeued - * datagram rather than the receiver, for both kernel and userspace events. + * datagram for both kernel and userspace events, mapping global UID/GID into + * the receiving caller's user namespace at final control-message copyout. */ static int64_t inet_message(struct task_file *file, uint64_t user_header, struct msghdr message, uint32_t flags, bool receiving, @@ -2685,6 +2711,7 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, output->flags = datagram && (uint64_t)ret > size ? MSG_TRUNC : 0; uint64_t used = 0; if (netlink_passcred) { + struct ucred credentials = socket_user_credentials(sched_current_task(), netlink_credentials); const uint64_t available = message.msg_control ? message.msg_controllen : 0; if (available < CMSG_LEN(sizeof(netlink_credentials))) output->flags |= MSG_CTRUNC; @@ -2696,7 +2723,7 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, .cmsg_len = CMSG_LEN(copy), .cmsg_level = SOL_SOCKET, .cmsg_type = SCM_CREDENTIALS, }; __builtin_memcpy(message.msg_control, &header, sizeof(header)); - __builtin_memcpy((uint8_t *)message.msg_control + CMSG_LEN(0), &netlink_credentials, copy); + __builtin_memcpy((uint8_t *)message.msg_control + CMSG_LEN(0), &credentials, copy); used = CMSG_SPACE(copy) < available ? CMSG_SPACE(copy) : available; } } @@ -3149,6 +3176,8 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, * SO_REUSEADDR records a boolean without changing name ownership or being * inherited by accepted sockets. Timestamp old/new options share enablement * and select the emitted control-message ABI. + * SO_PEERCRED maps a retained global snapshot into the caller's user namespace, + * preserving the absent-peer sentinel and the original cached credentials. */ static int unix_socket_option(struct unix_socket *socket, bool setting, int level, int option, uint64_t address, uint64_t length) @@ -3205,6 +3234,7 @@ static int unix_socket_option(struct unix_socket *socket, bool setting, int leve if (level != SOL_SOCKET) return -LINUX_ENOPROTOOPT; int32_t value = 0; struct linux_timeval timeout = {0}; + struct ucred peer_credentials = socket->peer_credentials; const void *data = &value; uint32_t size = sizeof(value); if(option==SO_ERROR) { @@ -3213,7 +3243,12 @@ static int unix_socket_option(struct unix_socket *socket, bool setting, int leve if(prep==KERNEL_SYSCALL_SWAP_CONTENDED)return prep; } switch (option) { - case SO_PEERCRED: data = &socket->peer_credentials; size = sizeof(socket->peer_credentials); break; + case SO_PEERCRED: + if (peer_credentials.pid) + peer_credentials = socket_user_credentials(sched_current_task(), peer_credentials); + data = &peer_credentials; + size = sizeof(peer_credentials); + break; case SO_TYPE: value = (int32_t)socket->type; break; case SO_ERROR: value = socket->error; socket->error = 0; break; case SO_PASSCRED: value = (int32_t)socket->passcred; break; diff --git a/tools/test_ipv6_transport.py b/tools/test_ipv6_transport.py index 240bc244..c759b358 100644 --- a/tools/test_ipv6_transport.py +++ b/tools/test_ipv6_transport.py @@ -20,6 +20,7 @@ "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", "tools/tests/ipv6_vector_test.c", "tools/tests/ipv6_vector_stubs.c", "kernel/syscall/io/vector.c", "kernel/syscall/ipc/socket.c", + "kernel/sched/user_namespace.c", "kernel/syscall/fs/lookup_state.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) binary = out / "ipv6_tcp_test" diff --git a/tools/test_linux_socket_batches.py b/tools/test_linux_socket_batches.py index f5fcda94..49f6f1e3 100644 --- a/tools/test_linux_socket_batches.py +++ b/tools/test_linux_socket_batches.py @@ -17,7 +17,7 @@ subprocess.run(["cc", "-std=c11", "-g", "-O1", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude", "-Iinclude/uapi", - "-Iinclude", "tools/tests/socket_batch_unix_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "-o", output], + "-Iinclude", "tools/tests/socket_batch_unix_test.c", "kernel/sched/user_namespace.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "-o", output], cwd=root, check=True) subprocess.run([output], cwd=root, check=True, timeout=20) output = str(Path(directory) / "socket_batch_abi") diff --git a/tools/tests/ipv6_vector_stubs.c b/tools/tests/ipv6_vector_stubs.c index 9da5c244..68c6cafb 100644 --- a/tools/tests/ipv6_vector_stubs.c +++ b/tools/tests/ipv6_vector_stubs.c @@ -1,4 +1,6 @@ /* Unused fixture dependencies trap if reached. */ +/** @brief Fail if this INET-only fixture enters UNIX timestamp collection. */ +__attribute__((noreturn)) void time_clock_get(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_recv(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_recv_staged(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_send(void) { __builtin_trap(); } diff --git a/tools/tests/socket_batch_unix_test.c b/tools/tests/socket_batch_unix_test.c index 17471471..ad6ee378 100644 --- a/tools/tests/socket_batch_unix_test.c +++ b/tools/tests/socket_batch_unix_test.c @@ -17,6 +17,8 @@ static unsigned allocations; static long allocation_budget = -1; static unsigned pty_holds; static struct linux_timespec fixture_realtime = {100, 123456789}; +static bool netlink_credentials_fixture; +static const struct ucred netlink_sender = {41, 1002, 3003}; /* AF_UNIX cases must not cross into another socket family's backend. */ int task_udp_recv(struct task_file *f, void *b, uint32_t n, uint32_t flags, uint64_t a, uint64_t l) { (void)f; (void)b; (void)n; (void)flags; (void)a; (void)l; abort(); } @@ -54,13 +56,21 @@ int task_netlink_send(struct task_file *file, const void *data, uint32_t length, int task_netlink_recv(struct task_file *file, void *data, uint32_t length, uint32_t flags, uint64_t address, uint64_t address_length) { (void)file; (void)data; (void)length; (void)flags; (void)address; (void)address_length; abort(); } -/** @brief Fail if this UNIX fixture stages a netlink message. */ +/** @brief Supply one global sender snapshot for netlink syscall copyout tests. */ int task_netlink_recv_staged(struct task_file *file, void *data, uint32_t length, uint32_t flags, void *source, uint32_t *source_length, struct ucred *credentials) -{ (void)file; (void)data; (void)length; (void)flags; (void)source; (void)source_length; (void)credentials; abort(); } -/** @brief Fail if this UNIX fixture reads netlink credential configuration. */ +{ + assert(netlink_credentials_fixture && file->kind == TASK_FILE_KIND_NETLINK); + assert(length && flags == (MSG_PEEK | MSG_TRUNC) && !source); + *(char *)data = 'n'; + *source_length = 0; + assert(credentials); + *credentials = netlink_sender; + return 1; +} +/** @brief Enable credentials only for the explicit netlink copyout fixture. */ bool task_netlink_passcred(const struct task_file *file) -{ (void)file; abort(); } +{ assert(netlink_credentials_fixture && file->kind == TASK_FILE_KIND_NETLINK); return true; } int net_socket_error(int32_t h, bool c) { (void)h; (void)c; abort(); } int net_socket_recv(struct reliefos_net_socket_io *r, uint32_t p) { (void)r; (void)p; abort(); } int net_socket_send(struct reliefos_net_socket_io *r, uint32_t p) { (void)r; (void)p; abort(); } @@ -321,6 +331,133 @@ static void check_unix_stream_outq(void) puts("PASS AF_UNIX stream SIOCOUTQ: pending charge, peek, drain, EFAULT"); } +/** @brief Publish nonidentity UID/GID maps through the actual proc controls. */ +static struct user_namespace *socket_test_user_namespace(void) +{ + struct task root = {.cap_effective = UINT64_MAX}; + struct user_namespace *ns = NULL; + struct user_namespace_file control; + uint32_t written; + assert(!user_namespace_create(&root, &ns)); + const char *maps[] = {"0 1000 8\n", "0 3000 8\n"}; + for (unsigned group = 0; group < 2; ++group) { + assert(!user_namespace_file_open(ns, &root, group ? USER_NAMESPACE_GID_MAP : + USER_NAMESPACE_UID_MAP, true, &control)); + assert(!user_namespace_file_write(&control, &root, 0, maps[group], strlen(maps[group]), &written)); + user_namespace_file_close(&control); + } + return ns; +} + +/** @brief Exercise namespace credential inputs, queued snapshots and copyout. */ +static void check_namespace_credentials(void) +{ + assert(!allocations); + struct user_namespace *ns = socket_test_user_namespace(); + current.user_ns = ns; + current.uid = 1000; current.euid = 1001; current.suid = 1002; + current.gid = 3000; current.egid = 3001; current.sgid = 3002; + const struct { + uint64_t caps; + struct ucred sent; + int error; + uint32_t uid, gid; + } cases[] = { + {0, {10, 0, 0}, 0, 1000, 3000}, + {0, {10, 1, 1}, 0, 1001, 3001}, + {0, {10, 2, 2}, 0, 1002, 3002}, + {0, {10, 3, 0}, -LINUX_EPERM}, + {0, {10, 0, 3}, -LINUX_EPERM}, + {1ULL << CAP_SETUID, {10, 3, 0}, 0, 1003, 3000}, + {1ULL << CAP_SETGID, {10, 0, 3}, 0, 1000, 3003}, + {1ULL << CAP_SETUID, {10, 0, 3}, -LINUX_EPERM}, + {1ULL << CAP_SETGID, {10, 3, 0}, -LINUX_EPERM}, + {UINT64_MAX, {11, 0, 0}, -LINUX_EPERM}, + {UINT64_MAX, {10, 8, 0}, -LINUX_EINVAL}, + {UINT64_MAX, {10, 0, 8}, -LINUX_EINVAL}, + {UINT64_MAX, {10, UINT32_MAX, 0}, -LINUX_EINVAL}, + }; + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + unsigned char control[CMSG_SPACE(sizeof(struct ucred))] = {0}; + struct cmsghdr *header = (void *)control; + *header = (struct cmsghdr){CMSG_LEN(sizeof(struct ucred)), SOL_SOCKET, SCM_CREDENTIALS}; + memcpy(CMSG_DATA(header), &cases[i].sent, sizeof(struct ucred)); + struct msghdr message = {.msg_control = control, .msg_controllen = sizeof(control)}; + struct unix_rights *rights = NULL; + struct ucred credentials; + bool explicit; + current.cap_effective = cases[i].caps; + assert(unix_message_rights(¤t, &message, &rights, &credentials, &explicit) == cases[i].error); + assert(!rights && allocations == 3); + if (!cases[i].error) + assert(explicit && credentials.pid == 10 && credentials.uid == cases[i].uid && + credentials.gid == cases[i].gid); + } + peers[0].type = peers[1].type = SOCK_DGRAM; + peers[1].passcred = 1; + current.cap_effective = 0; + const struct ucred sent[] = {{10, 1002, 3003}, {10, 9000, 9001}}; + for (unsigned i = 0; i < 2; ++i) { + assert(unix_send_packet(&endpoints[0], &peers[1], "c", 1, 0, &sent[i]) == 1); + for (unsigned peek = 0; peek < 3; ++peek) { + char byte; + unsigned char control[CMSG_SPACE(sizeof(struct ucred))] = {0}; + struct iovec vector = {&byte, 1}; + struct mmsghdr message = {.msg_hdr = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_control = control, .msg_controllen = sizeof(control)}}; + current.user_ns = peek == 2 ? NULL : ns; + assert(batch(true, &message, 1, peek == 2 ? 0 : MSG_PEEK) == 1 && byte == 'c'); + struct cmsghdr *header = CMSG_FIRSTHDR(&message.msg_hdr); + struct ucred credentials; + assert(header && header->cmsg_type == SCM_CREDENTIALS); + memcpy(&credentials, CMSG_DATA(header), sizeof(credentials)); + assert(credentials.pid == 10); + assert(credentials.uid == (peek == 2 ? sent[i].uid : i ? 65534u : 2u)); + assert(credentials.gid == (peek == 2 ? sent[i].gid : i ? 65534u : 3u)); + } + } + current.user_ns = ns; + peers[0].peer_credentials = sent[0]; + struct ucred peer; + socklen_t size = sizeof(peer); + assert(!unix_socket_option(&peers[0], false, SOL_SOCKET, SO_PEERCRED, + (uintptr_t)&peer, (uintptr_t)&size)); + assert(peer.pid == 10 && peer.uid == 2 && peer.gid == 3); + assert(peers[0].peer_credentials.uid == 1002 && peers[0].peer_credentials.gid == 3003); + peers[0].peer_credentials = sent[1]; + assert(!unix_socket_option(&peers[0], false, SOL_SOCKET, SO_PEERCRED, + (uintptr_t)&peer, (uintptr_t)&size)); + assert(peer.uid == 65534 && peer.gid == 65534); + peers[0].peer_credentials = (struct ucred){0, UINT32_MAX, UINT32_MAX}; + assert(!unix_socket_option(&peers[0], false, SOL_SOCKET, SO_PEERCRED, + (uintptr_t)&peer, (uintptr_t)&size)); + assert(!peer.pid && peer.uid == UINT32_MAX && peer.gid == UINT32_MAX); + + netlink_credentials_fixture = true; + struct task_file netlink = {.kind = TASK_FILE_KIND_NETLINK}; + for (unsigned capacity = 0; capacity <= CMSG_SPACE(sizeof(struct ucred)); capacity += 4) { + char byte; + unsigned char control[CMSG_SPACE(sizeof(struct ucred))] = {0}; + struct iovec vector = {&byte, 1}; + struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_control = control, .msg_controllen = capacity}; + struct socket_message_result result = {0}; + assert(inet_message(&netlink, (uintptr_t)&message, message, MSG_PEEK, true, 1, &result) == 1); + assert(byte == 'n' && !!(result.flags & MSG_CTRUNC) == (capacity < CMSG_LEN(sizeof(struct ucred)))); + if (capacity >= CMSG_LEN(0)) { + struct ucred expected = {41, 2, 3}; + unsigned copied = capacity - CMSG_LEN(0); + if (copied > sizeof(expected)) copied = sizeof(expected); + assert(!memcmp(CMSG_DATA((struct cmsghdr *)(void *)control), &expected, copied)); + } + } + netlink_credentials_fixture = false; + current.user_ns = NULL; + user_namespace_put(ns); + assert(!allocations); + puts("PASS namespace socket credentials: input authority, overflow, PEEK snapshots, peer and netlink copyout"); +} + int main(void) { current.kind = TASK_KIND_USER; @@ -507,6 +644,7 @@ int main(void) assert(!held && !allocations); } check_unix_stream_outq(); + check_namespace_credentials(); puts("PASS actual Unix mmsg: packet boundaries, WAITFORONE, blocking resume, length faults, SCM_RIGHTS references/CLOEXEC"); return 0; } diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 7ebb462d..908d6205 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -351,6 +351,7 @@ "tools/tests/task8_host_stubs/writable_alias_model.c", "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/cleanup-actual-candidate-2" ] @@ -909,6 +910,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/inet-message-user-candidate-3" ] @@ -1016,6 +1018,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/inet-signal-candidate-4" ] @@ -2189,6 +2192,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/socket-front-batch-waitall-green-1" ] @@ -2230,6 +2234,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/socket-receive-collector-green-2" ] @@ -2308,6 +2313,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/socket-scalar-receive-integration-candidate-2" ] @@ -2348,6 +2354,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/socket-send-receive-integration-candidate-2" ] @@ -2997,6 +3004,7 @@ "kernel/exec/usercopy.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-fork-socket-cow" ] @@ -3883,6 +3891,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-inet-from-empty" ] @@ -3968,6 +3977,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-inet-from-short" ] @@ -4053,6 +4063,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-inet-msg-empty" ] @@ -4138,6 +4149,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-inet-msg-short" ] @@ -4289,6 +4301,7 @@ "-Iinclude/uapi", "tools/tests/task8_device_socket_test.c", "fs/vfs/mount_tree.c", + "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", @@ -4302,6 +4315,7 @@ "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "kernel/device/mapping.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-device-socket" ] @@ -4386,6 +4400,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-inet-from-zero" ] @@ -4471,6 +4486,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-inet-msg-zero" ] @@ -4500,6 +4516,7 @@ "-Iinclude/uapi", "tools/tests/task8_inet_tcp_probe_test.c", "tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-inet-tcp-probe" ] @@ -4565,6 +4582,7 @@ "tools/tests/task8_host_stubs/no_prlimit_identity.c", "tools/tests/task8_host_stubs/packet_tcp_unreached.c", "tools/tests/task8_host_stubs/fix1-packet-front-unreached.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-inet-packet-probe" ] @@ -4928,6 +4946,7 @@ "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "tools/tests/task8_host_stubs/socket-send-receive-integration-candidate-2-socket_dispatch_stubs.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-unix-aperture-noswap" ] @@ -5213,12 +5232,14 @@ "-Iinclude/uapi", "tools/tests/socket_batch_unix_test.c", "fs/vfs/mount_tree.c", + "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-existing-unix-batch" ] @@ -5329,6 +5350,7 @@ "fs/vfs/initial.c", "fs/security/access.c", "kernel/syscall/ipc/unix_name.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/fix1-existing-descriptors" ] diff --git a/tools/tests/task8_socket_receive_test.c b/tools/tests/task8_socket_receive_test.c index e7a621d7..cc7b8c37 100644 --- a/tools/tests/task8_socket_receive_test.c +++ b/tools/tests/task8_socket_receive_test.c @@ -136,8 +136,11 @@ int main(void) assert(!unix_socket_option(&peers[1],true,SOL_SOCKET,SO_TIMESTAMP_NEW, (uintptr_t)×tamp_enabled,sizeof(timestamp_enabled))); peers[1].passcred=1; + struct user_namespace *credential_ns=socket_test_user_namespace(); + current.uid=1002;current.gid=3003; fixture_realtime=(struct linux_timespec){200,456789123}; send_one(0x55); + current.user_ns=credential_ns; memset(control,0,sizeof(control)); vector=(struct iovec){output,sizeof(output)}; message=(struct msghdr){.msg_iov=&vector,.msg_iovlen=1, @@ -147,6 +150,8 @@ int main(void) task_lookup_scope_begin(¤t,&frame);readonly=(uintptr_t)control;contended=true; assert(task_socket_message(¤t,&endpoints[1],(uintptr_t)&message,0,true,false,&result)==KERNEL_SYSCALL_SWAP_CONTENDED); assert(!peers[1].packet_count && owned_stage && passed.references==2); + assert(owned_stage->metadata.credentials.uid==1002 && + owned_stage->metadata.credentials.gid==3003); timestamp_enabled=0; assert(!unix_socket_option(&peers[1],true,SOL_SOCKET,SO_TIMESTAMP_OLD, (uintptr_t)×tamp_enabled,sizeof(timestamp_enabled))); @@ -160,9 +165,14 @@ int main(void) assert(stamp.tv_sec==200 && stamp.tv_usec==456789); item=CMSG_NXTHDR(&message,item); assert(item && item->cmsg_type==SCM_CREDENTIALS); + struct ucred credentials; + memcpy(&credentials,CMSG_DATA(item),sizeof(credentials)); + assert(credentials.pid==10 && credentials.uid==2 && credentials.gid==3); item=CMSG_NXTHDR(&message,item); assert(item && item->cmsg_type==SCM_RIGHTS && current.files[0].description==&passed); clear_task_file(¤t.files[0]);task_lookup_scope_cancel(¤t); + current.user_ns=NULL;user_namespace_put(credential_ns); + current.uid=current.gid=100; assert(passed.references==1 && !owned_stage && !allocations && !pins); timestamp_enabled=1; From 9d7610794de7e09e7d5ba36c192b76c18a8dd218 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 00:48:18 +0800 Subject: [PATCH 60/97] feat(userns): translate signal and wait event UIDs --- Documentation/core-api/mount-namespaces.rst | 17 +++ .../LC_MESSAGES/core-api/mount-namespaces.po | 12 ++ .../LC_MESSAGES/core-api/mount-namespaces.po | 12 ++ include/reliefnt/pidfd.h | 4 + include/reliefnt/sched.h | 1 + include/reliefnt/signal.h | 27 +++- include/reliefnt/syscall.h | 2 + kernel/sched/signal.c | 5 +- kernel/sched/wait.c | 1 + kernel/signal/signal_queue.c | 23 ++++ kernel/syscall/process/legacy_process.c | 5 + kernel/syscall/process/pidfd.c | 16 +-- kernel/syscall/process/process.c | 6 +- tools/test_linux_threads.py | 2 + tools/tests/process_signal_queue_test.c | 48 +++++++- tools/tests/signal_info_queue_test.c | 115 +++++++++++++++++- tools/tests/signalfd_test.c | 27 +++- tools/tests/task8_wait_swap_test.c | 38 +++++- 18 files changed, 342 insertions(+), 19 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index a1d2d0b9..2fd0daa2 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -169,5 +169,22 @@ UNIX 消息、流凭据、对端缓存及等待用户页的阶段状态保存全 截断控制消息也使用相同转换。``SO_PEERCRED`` 的无对端结果保留 PID 0 与 UID/GID ``UINT32_MAX``。 +信号与 wait 凭据 +================ + +``kill/tkill/tgkill``、进程组发送和默认 pidfd 信号将发送者真实 UID 转换为各 +接收者用户空间的 ID,未映射时输出 65534。用户提供的 siginfo 在跨空间发送时 +转换 kill、child 和 realtime 布局中的 UID,同空间数字直接保留,包括未映射值。 +timer、poll、fault 和 syscall 布局保留其 union 数据。PID 继续使用全局编号。 + +转换在入队前完成,信号队列、处理函数帧、``sigtimedwait`` 和 ``signalfd`` +使用该接收者空间快照。后续 UID 映射发布保留已入队记录的值。信号权限检查和 +队列配额继续使用全局凭据。 + +数字 PID 和 pidfd 的 ``waitid`` 在内部快照及输出页重试期间保留子进程的全局 +UID,最终复制实际事件时转换为调用方空间的 ID,未映射时输出 65534。 +``WNOHANG`` 无事件结果保持全零,``WNOWAIT`` 保留事件。停止、继续与退出事件 +采用相同转换,最终输出错误沿用已有事件消费规则。 + 内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``。其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 263112d6..c9dbc4b7 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -336,3 +336,15 @@ msgstr "AF_UNIX ``SCM_CREDENTIALS`` translates UID/GID inputs from the sender na msgid "UNIX 消息、流凭据、对端缓存及等待用户页的阶段状态保存全局身份。最终输出 ``SCM_CREDENTIALS``、``SO_PEERCRED`` 和 netlink ``SO_PASSCRED`` 时,按接收者 用户空间转换 UID/GID,未映射时输出 65534。``MSG_PEEK`` 和输出重试保留原快照, 截断控制消息也使用相同转换。``SO_PEERCRED`` 的无对端结果保留 PID 0 与 UID/GID ``UINT32_MAX``。" msgstr "UNIX messages, stream credentials, peer caches and stages waiting for user pages retain global identities. Final ``SCM_CREDENTIALS``, ``SO_PEERCRED`` and netlink ``SO_PASSCRED`` output translates UID/GID into the receiver user namespace, reporting 65534 for unmapped IDs. ``MSG_PEEK`` and output retries preserve the original snapshot. Truncated control messages use the same translation. An absent peer retains PID 0 and UID/GID ``UINT32_MAX`` for ``SO_PEERCRED``." + +msgid "信号与 wait 凭据" +msgstr "Signal and wait credentials" + +msgid "``kill/tkill/tgkill``、进程组发送和默认 pidfd 信号将发送者真实 UID 转换为各 接收者用户空间的 ID,未映射时输出 65534。用户提供的 siginfo 在跨空间发送时 转换 kill、child 和 realtime 布局中的 UID,同空间数字直接保留,包括未映射值。 timer、poll、fault 和 syscall 布局保留其 union 数据。PID 继续使用全局编号。" +msgstr "``kill/tkill/tgkill``, process-group sends and default pidfd signals translate the sender real UID into each receiver user namespace, reporting 65534 for unmapped IDs. Cross-namespace user-supplied siginfo translates the UID in kill, child and realtime layouts. Same-namespace numbers are preserved, including unmapped values. Timer, poll, fault and syscall layouts retain their union data. PIDs use global numbering." + +msgid "转换在入队前完成,信号队列、处理函数帧、``sigtimedwait`` 和 ``signalfd`` 使用该接收者空间快照。后续 UID 映射发布保留已入队记录的值。信号权限检查和 队列配额继续使用全局凭据。" +msgstr "Translation completes before enqueue. Signal queues, handler frames, ``sigtimedwait`` and ``signalfd`` use that receiver-namespace snapshot. Later UID map publication preserves values already queued. Signal permission checks and queue accounting use global credentials." + +msgid "数字 PID 和 pidfd 的 ``waitid`` 在内部快照及输出页重试期间保留子进程的全局 UID,最终复制实际事件时转换为调用方空间的 ID,未映射时输出 65534。 ``WNOHANG`` 无事件结果保持全零,``WNOWAIT`` 保留事件。停止、继续与退出事件 采用相同转换,最终输出错误沿用已有事件消费规则。" +msgstr "Numeric-PID and pidfd ``waitid`` retain the child global UID in internal snapshots and across output-page retries. Final copyout of an actual event maps it into the caller namespace, reporting 65534 for unmapped IDs. ``WNOHANG`` results without an event remain zeroed, and ``WNOWAIT`` preserves the event. Stop, continue and exit events use the same translation. Final output errors follow the existing event-consumption rules." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index f7e2fedc..01d89f47 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -294,3 +294,15 @@ msgstr "AF_UNIX の ``SCM_CREDENTIALS`` は送信者の名前空間の UID/GID msgid "UNIX 消息、流凭据、对端缓存及等待用户页的阶段状态保存全局身份。最终输出 ``SCM_CREDENTIALS``、``SO_PEERCRED`` 和 netlink ``SO_PASSCRED`` 时,按接收者 用户空间转换 UID/GID,未映射时输出 65534。``MSG_PEEK`` 和输出重试保留原快照, 截断控制消息也使用相同转换。``SO_PEERCRED`` 的无对端结果保留 PID 0 与 UID/GID ``UINT32_MAX``。" msgstr "UNIX メッセージ、ストリームの資格情報、対向のキャッシュ、ユーザーページ待機中の段階状態はグローバルな識別情報を保持します。``SCM_CREDENTIALS``、``SO_PEERCRED``、netlink の ``SO_PASSCRED`` の最終出力では UID/GID を受信者のユーザー名前空間に変換し、未マッピングの ID は 65534 を返します。``MSG_PEEK`` と出力の再試行は元のスナップショットを保持します。切り詰められた制御メッセージも同じ変換を使います。``SO_PEERCRED`` の対向がない場合は PID 0 と UID/GID ``UINT32_MAX`` を保持します。" + +msgid "信号与 wait 凭据" +msgstr "シグナルと wait の資格情報" + +msgid "``kill/tkill/tgkill``、进程组发送和默认 pidfd 信号将发送者真实 UID 转换为各 接收者用户空间的 ID,未映射时输出 65534。用户提供的 siginfo 在跨空间发送时 转换 kill、child 和 realtime 布局中的 UID,同空间数字直接保留,包括未映射值。 timer、poll、fault 和 syscall 布局保留其 union 数据。PID 继续使用全局编号。" +msgstr "``kill/tkill/tgkill``、プロセスグループへの送信、既定の pidfd シグナルは、送信者の実 UID を各受信者のユーザー名前空間に変換し、未マッピングの ID は 65534 を返します。空間をまたぐユーザー指定 siginfo は kill、child、realtime レイアウトの UID を変換します。同じ空間の数値は未マッピング値も保持します。timer、poll、fault、syscall レイアウトは union データを保持します。PID はグローバル番号を使います。" + +msgid "转换在入队前完成,信号队列、处理函数帧、``sigtimedwait`` 和 ``signalfd`` 使用该接收者空间快照。后续 UID 映射发布保留已入队记录的值。信号权限检查和 队列配额继续使用全局凭据。" +msgstr "変換はキューへの追加前に完了します。シグナルキュー、ハンドラーフレーム、``sigtimedwait``、``signalfd`` は受信者空間のスナップショットを使います。後から UID マップを公開しても、追加済みレコードの値を保持します。シグナルの権限検査とキューの割り当て量管理はグローバルな資格情報を使います。" + +msgid "数字 PID 和 pidfd 的 ``waitid`` 在内部快照及输出页重试期间保留子进程的全局 UID,最终复制实际事件时转换为调用方空间的 ID,未映射时输出 65534。 ``WNOHANG`` 无事件结果保持全零,``WNOWAIT`` 保留事件。停止、继续与退出事件 采用相同转换,最终输出错误沿用已有事件消费规则。" +msgstr "数値 PID と pidfd の ``waitid`` は、内部スナップショットと出力ページの再試行中に子プロセスのグローバル UID を保持します。実際のイベントを最終コピーするときに呼び出し元の空間へ変換し、未マッピングの ID は 65534 を返します。``WNOHANG`` でイベントがない結果はすべてゼロを保ち、``WNOWAIT`` はイベントを保持します。停止、継続、終了イベントに同じ変換を適用し、最終出力エラーには既存のイベント消費規則を適用します。" diff --git a/include/reliefnt/pidfd.h b/include/reliefnt/pidfd.h index 19615f31..71c571b1 100644 --- a/include/reliefnt/pidfd.h +++ b/include/reliefnt/pidfd.h @@ -18,6 +18,7 @@ int64_t syscall_pidfd_open(struct task *caller, int32_t pid, uint32_t flags); * @param sig Linux signal number or zero for an existence/permission check. * @param pointer Optional user siginfo address. @param flags Linux signal scope. * @return Zero, negative Linux errno, or a private pre-enqueue retry result. + * Sender UIDs are translated into the receiver's user namespace before enqueue. */ int64_t syscall_pidfd_send_signal(struct task *caller, int fd, int sig, uint64_t pointer, uint32_t flags); @@ -26,6 +27,9 @@ int64_t syscall_pidfd_send_signal(struct task *caller, int fd, int sig, * @param infop Optional user siginfo address. @param usage Optional raw ABI rusage address. * @param options Linux waitid event selection and flags. * @return Zero, negative Linux errno, or a private blocking/retry result. + * Internal wait snapshots retain global UIDs until final userspace copyout. + * Actual events map the child UID into the caller's namespace with overflow 65534. + * A no-event result preserves the zeroed UID field. */ int64_t syscall_pidfd_waitid(struct task *caller, int fd, uint64_t infop, uint64_t usage, uint32_t options); diff --git a/include/reliefnt/sched.h b/include/reliefnt/sched.h index ec236d4f..cfc119bc 100644 --- a/include/reliefnt/sched.h +++ b/include/reliefnt/sched.h @@ -457,6 +457,7 @@ int sched_signal_action(uint32_t pid, int signal_number, uint32_t operation, * @param signal_number POSIX signal number. * @return Number of signalled tasks, or a negative scheduler error. * CAP_KILL is checked in each target's owning user namespace. + * Each queued record maps the sender's real UID into that receiver's namespace. */ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, int signal_number); diff --git a/include/reliefnt/signal.h b/include/reliefnt/signal.h index 0111405d..0195b087 100644 --- a/include/reliefnt/signal.h +++ b/include/reliefnt/signal.h @@ -38,9 +38,20 @@ struct kernel_signal_action { * @return 0 on success, or a negative scheduler-style error. */ int kernel_signal_queue_task(struct task *task, int signal_number); -/** @brief Send a thread-directed signal with native Linux siginfo. */ +/** @brief Send a thread-directed signal with native Linux siginfo. + * @param task Execution-owned receiver. + * @param sig Native signal number. + * @param info Optional kernel record with UID already in the receiver namespace. + * @return Zero on success or a negative scheduler-style error. + */ int kernel_signal_queue_task_info(struct task *task, int sig, const struct linux_siginfo *info); -/** @brief Append one pending signal, enforcing the receiver's per-UID queue limit. */ +/** @brief Append one pending signal, enforcing the receiver's per-UID queue limit. + * @param task Execution-owned receiver whose global UID supplies queue accounting. + * @param process Select the shared process queue instead of the private queue. + * @param sig Native signal number. + * @param info Optional kernel record with UID already in the receiver namespace. + * @return Zero on success or a negative Linux errno. + */ int kernel_signal_enqueue(struct task *task, bool process, int sig, const struct linux_siginfo *info); #ifdef CONFIG_SECCOMP_FILTER /** @brief Publish a synchronous, thread-directed SIGSYS without allocating. @@ -70,6 +81,7 @@ void kernel_signal_detach_process(struct task *task); * @param thread Select rt_tgsigqueueinfo rather than rt_sigqueueinfo semantics. * @return Zero, negative Linux errno, or a pre-enqueue swap retry result. * Requires current-task execution ownership without caller-held spinlocks. + * User-supplied UIDs are converted to the receiver namespace before enqueue. * Neither user memory nor target references are retained. */ int64_t kernel_signal_queueinfo(int32_t tgid, int32_t tid, int sig, uint64_t info, bool thread); @@ -84,6 +96,17 @@ int64_t kernel_signal_queueinfo(int32_t tgid, int32_t tid, int sig, uint64_t inf int kernel_signal_import_info(struct task *caller, uint64_t pointer, int sig, struct linux_siginfo *info); +/** @brief Translate a user-supplied siginfo UID before it enters the receiver queue. + * @param sender Borrowed live sender with execution-owned credentials. + * @param target Borrowed live receiver with execution-owned credentials. + * @param info Imported kernel record with its final signal number, updated in place. + * Same-namespace numbers, including unmapped values, are preserved. Cross-namespace + * kill, child and realtime layouts map through global IDs with overflow 65534. + * Other union payloads and PIDs are preserved. No allocation or reference transfer. + */ +void kernel_signal_translate_user_info(const struct task *sender, const struct task *target, + struct linux_siginfo *info); + /** @brief Check native Linux signal permissions for numeric and pidfd sends. * @param caller Borrowed sender under execution ownership, nullable. * @param target Borrowed identity-checked receiver, nullable. diff --git a/include/reliefnt/syscall.h b/include/reliefnt/syscall.h index 0f517e3c..18d09ae7 100644 --- a/include/reliefnt/syscall.h +++ b/include/reliefnt/syscall.h @@ -343,6 +343,8 @@ void syscall_trace_configure(const char *cmdline); * Unmapped input IDs fail with EINVAL, preserving optional UINT32_MAX operands. * Unmapped output IDs use 65534. setfsuid/setfsgid always return the prior local * filesystem identity, including when the requested change is rejected. + * Generated signal records map the sender's real UID into each receiver's + * user namespace before enqueue, using 65534 when unmapped. * @param number Normalized syscall selector. @param a0 First ABI argument. * @param a1 Second ABI argument. @param a2 Third ABI argument. * @param a3 Fourth ABI argument. diff --git a/kernel/sched/signal.c b/kernel/sched/signal.c index 54c5b4ef..ccf6ca91 100644 --- a/kernel/sched/signal.c +++ b/kernel/sched/signal.c @@ -322,8 +322,6 @@ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, int count = 0; int error = -LINUX_ESRCH; if (!sender) return -LINUX_EPERM; - struct linux_siginfo info = {.signo = signal_number, .code = LINUX_SI_USER, - .fields.sender = {.pid = (int32_t)sched_task_tgid(sender), .uid = sender->uid}}; for (uint32_t i = 0; i < task_count; ++i) { struct task *task = tasks[i]; if (!task || !task->pid || task->kind != TASK_KIND_USER || @@ -337,6 +335,9 @@ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, if (error == -LINUX_ESRCH) error = -LINUX_EPERM; continue; } + struct linux_siginfo info = {.signo = signal_number, .code = LINUX_SI_USER, + .fields.sender = {.pid = (int32_t)sched_task_tgid(sender), + .uid = user_namespace_id_from_kernel_munged(task->user_ns, false, sender->uid)}}; int result = sched_signal_user_process_info(task->pid, signal_number, &info); if (result >= 0) ++count; else error = result; diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index 8a7462ed..b6ee988d 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -116,6 +116,7 @@ void sched_sleep_current_until(uint64_t wake_tick) * @param task Borrowed child whose PID and UID identify the event. * @param status Encoded native wait status, including stop/continue events. * Caller holds scheduler_lock; performs no allocation or reference transfer. + * The UID remains kernel-global for conversion at the final userspace boundary. */ static void sched_wait_info(struct linux_siginfo *info, const struct task *task, int status) { diff --git a/kernel/signal/signal_queue.c b/kernel/signal/signal_queue.c index 41cdc598..8f3b61ab 100644 --- a/kernel/signal/signal_queue.c +++ b/kernel/signal/signal_queue.c @@ -343,6 +343,28 @@ bool kernel_signal_may_send(const struct task *caller, const struct task *target (sig == 18 && caller->process_session == target->process_session)); } +/** @copydoc kernel_signal_translate_user_info */ +void kernel_signal_translate_user_info(const struct task *sender, const struct task *target, + struct linux_siginfo *info) +{ + if (sender->user_ns == target->user_ns) return; + int code = info->code; + if (code == LINUX_SI_TIMER || code == -5) return; + if (code > 0 && code < LINUX_SI_KERNEL && !(info->signo == 17 && code <= 6)) { + /* Positive codes through six use fault, syscall or poll payloads. + * Larger defined fault codes still overlap the sender UID field. */ + int limit = 6; + switch (info->signo) { + case 4: limit = 11; break; + case 8: limit = 15; break; + case 11: limit = 10; break; + } + if (code <= limit) return; + } + uint32_t uid = user_namespace_id_to_kernel(sender->user_ns, false, info->fields.sender.uid); + info->fields.sender.uid = user_namespace_id_from_kernel_munged(target->user_ns, false, uid); +} + /** @brief Import and send a user-queued signal through numeric PID/TID lookup. * @param tgid Target PID, or required thread-group ID when thread is true. * @param tid Target TID for thread-directed sends; ignored otherwise. @@ -372,6 +394,7 @@ int64_t kernel_signal_queueinfo(int32_t tgid, int32_t tid, int sig, if (sig < 0 || sig >= LINUX_NSIG) return -LINUX_EINVAL; if (info.code <= 0 && !kernel_signal_may_send(caller, target, sig)) return -LINUX_EPERM; if (!sig) return 0; + kernel_signal_translate_user_info(caller, target, &info); if (thread) return target->state == TASK_EXITED ? 0 : kernel_signal_queue_task_info(target, sig, &info); return sched_signal_user_process_info((uint32_t)tgid, sig, &info); diff --git a/kernel/syscall/process/legacy_process.c b/kernel/syscall/process/legacy_process.c index fa0c3fb5..0d879aa0 100644 --- a/kernel/syscall/process/legacy_process.c +++ b/kernel/syscall/process/legacy_process.c @@ -36,6 +36,8 @@ static int wait_prepare_output(uint64_t address,uint64_t size) * @param a5 Sixth native ABI argument. * @return Original result, negative errno, or internal blocking/retry status. * @note The caller retains the kernel execution transaction and descriptor pins. + * Wait snapshots hold global UIDs through retries. Final waitid copyout maps + * actual event UIDs into the caller's namespace and preserves no-event zeros. */ int64_t syscall_legacy_process(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) { @@ -230,6 +232,9 @@ int64_t syscall_legacy_process(uint64_t number, uint64_t a0, uint64_t a1, uint64 } else if (pid <= 0) pid = -RELIEFOS_ECHILD; if (a2) { if (!user_range_writable(a2, sizeof(info))) return -RELIEFOS_EFAULT; + if (pid > 0) + info.fields.child.uid = user_namespace_id_from_kernel_munged( + sched_current_task()->user_ns, false, info.fields.child.uid); *(struct linux_siginfo *)(uintptr_t)a2 = info; } return pid < 0 ? pid : 0; diff --git a/kernel/syscall/process/pidfd.c b/kernel/syscall/process/pidfd.c index d4244ccb..c10c16a5 100644 --- a/kernel/syscall/process/pidfd.c +++ b/kernel/syscall/process/pidfd.c @@ -52,12 +52,7 @@ int64_t syscall_pidfd_open(struct task *caller, int32_t pid, uint32_t flags) return fd; } -/** @brief Recheck authorization and signal the identity pinned by an OFD. - * @param caller Calling task under execution ownership. @param fd Its pidfd. - * @param sig Linux signal number, or zero for a permission/existence check. - * @param pointer Optional user siginfo address. @param flags Linux signal scope. - * @return Zero, negative Linux errno, or a private pre-enqueue retry result. - */ +/** @copydoc syscall_pidfd_send_signal */ int64_t syscall_pidfd_send_signal(struct task *caller, int fd, int sig, uint64_t pointer, uint32_t flags) { @@ -89,6 +84,9 @@ int64_t syscall_pidfd_send_signal(struct task *caller, int fd, int sig, * legacy numeric kill/power path through this new handle API. */ if (sched_task_tgid(target) == 1 && sched_task_actions(target)[sig].handler <= 1) return 0; + if (pointer) kernel_signal_translate_user_info(caller, target, &info); + else info.fields.sender.uid = user_namespace_id_from_kernel_munged(target->user_ns, false, + caller->uid); if (!thread) return sched_signal_user_process_target(target, sig, &info); return target->state == TASK_EXITED ? 0 : kernel_signal_queue_task_info(target, sig, &info); } @@ -122,6 +120,8 @@ static bool pidfd_wait_output_pending(struct task *caller, uint64_t address, uin * @param infop Optional user siginfo address. @param usage_ptr Optional raw ABI rusage address. * @param options Linux waitid event selection and flags. * @return Zero, negative Linux errno, or a private blocking/retry result. + * Snapshot UIDs remain global until an actual event is copied to userspace, + * when they are mapped to the caller's namespace with overflow 65534. */ int64_t syscall_pidfd_waitid(struct task *caller, int fd, uint64_t infop, uint64_t usage_ptr, uint32_t options) @@ -179,7 +179,9 @@ int64_t syscall_pidfd_waitid(struct task *caller, int fd, uint64_t infop, uint64 out->error = info.error; out->code = info.code; out->fields.child.pid = info.fields.child.pid; - out->fields.child.uid = info.fields.child.uid; + out->fields.child.uid = result > 0 + ? user_namespace_id_from_kernel_munged(caller->user_ns, false, info.fields.child.uid) + : info.fields.child.uid; out->fields.child.status = info.fields.child.status; } return result > 0 ? 0 : result; diff --git a/kernel/syscall/process/process.c b/kernel/syscall/process/process.c index 64f35806..8b98904e 100644 --- a/kernel/syscall/process/process.c +++ b/kernel/syscall/process/process.c @@ -1194,7 +1194,8 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, sender->euid != target->suid && !(sig == 18 && sender->process_session == target->process_session))) return -RELIEFOS_EPERM; struct linux_siginfo info = {.signo = sig, .code = LINUX_SI_TKILL, - .fields.sender = {.pid = (int32_t)sched_task_tgid(sender), .uid = sender->uid}}; + .fields.sender = {.pid = (int32_t)sched_task_tgid(sender), + .uid = user_namespace_id_from_kernel_munged(target->user_ns, false, sender->uid)}}; return kernel_signal_queue_task_info(target, sig, &info); } if (number == LINUX_SYS_KILL) { @@ -1223,7 +1224,8 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, current->euid != target->uid && current->euid != target->suid && !(signal_number == 18 && current->process_session == target->process_session)) return -RELIEFOS_EPERM; struct linux_siginfo info = {.signo = signal_number, .code = LINUX_SI_USER, - .fields.sender = {.pid = (int32_t)sched_task_tgid(current), .uid = current->uid}}; + .fields.sender = {.pid = (int32_t)sched_task_tgid(current), + .uid = user_namespace_id_from_kernel_munged(target->user_ns, false, current->uid)}}; return sched_signal_user_process_info((uint32_t)requested_pid, signal_number, &info); } if (number == RELIEFOS_SYS_NICE) { diff --git a/tools/test_linux_threads.py b/tools/test_linux_threads.py index f9797800..f7827b58 100644 --- a/tools/test_linux_threads.py +++ b/tools/test_linux_threads.py @@ -16,6 +16,8 @@ "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", *(["-D_GNU_SOURCE"] if test == "signal_address_space" else []), f"tools/tests/{test}_test.c", "kernel/syscall/ipc/sysv_sem.c", + *(["kernel/sched/user_namespace.c"] if test in + ("signal_info_queue", "signalfd", "signal_address_space", "user_gp_dispatch") else []), *(["kernel/sched/rseq.c"] if test == "rseq" else []), *(["kernel/ipc/futex_pi.c"] if test in ("futex_queue", "futex_pi") else []), *(["arch/x86_64/cpu/barrier.c"] if test == "membarrier_cpu" else []), diff --git a/tools/tests/process_signal_queue_test.c b/tools/tests/process_signal_queue_test.c index 2d28f433..e872cf99 100644 --- a/tools/tests/process_signal_queue_test.c +++ b/tools/tests/process_signal_queue_test.c @@ -1,6 +1,7 @@ #include #include #include +#include #include "modules/scheduler.h" #include "sysv_shm_fixture_stubs.h" #include "../../kernel/syscall/time/time.c" @@ -41,6 +42,50 @@ void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) { (void)flags; assert(lock->state); lock->state = 0; } +/** @brief Build a distinct receiver mapping using production UID-map controls. */ +static struct user_namespace *group_signal_namespace(const char *map) +{ + struct task root = {.cap_effective = (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1}; + struct user_namespace *ns; + struct user_namespace_file control; + uint32_t written; + assert(!user_namespace_create(&root, &ns)); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_UID_MAP, true, &control)); + assert(!user_namespace_file_write(&control, &root, 0, map, strlen(map), &written)); + user_namespace_file_close(&control); + return ns; +} + +/** @brief Each process-group receiver observes its own namespace's sender UID. */ +static void check_group_signal_namespaces(void) +{ + for (unsigned i = 0; i < 3; ++i) { + kernel_signal_flush(&members[i], false, UINT64_MAX); + kernel_signal_flush(&members[i], true, UINT64_MAX); + } + memset(members, 0, sizeof(members)); + for (unsigned i = 0; i < 3; ++i) { + members[i] = (struct task){.pid = 10 + i, .tgid = 10 + i, + .kind = TASK_KIND_USER, .state = TASK_READY, .process_group = 10, + .uid = 1002, .euid = 1002, .suid = 1002, .blocked_signals = UINT64_MAX}; + } + members[1].user_ns = group_signal_namespace("0 1000 8\n"); + members[2].user_ns = group_signal_namespace("40 1000 8\n"); + const uint32_t expected[] = {1002, 2, 42}; + for (unsigned round = 0; round < 2; ++round) { + assert(sched_signal_process_group(10, 10, 12) == 3); + for (unsigned i = 0; i < 3; ++i) { + struct linux_siginfo info; + assert(kernel_signal_dequeue(&members[i], UINT64_MAX, &info) == 12); + assert(info.fields.sender.uid == expected[i] && info.fields.sender.pid == 10); + } + } + user_namespace_put(members[1].user_ns); + user_namespace_put(members[2].user_ns); + members[1].user_ns = members[2].user_ns = NULL; + assert(!signal_accounts); +} + int main(void) { tasks = table; @@ -250,5 +295,6 @@ int main(void) assert(members[1].state == TASK_READY && !members[1].vfork_child); kernel_signal_flush(&members[1], false, UINT64_MAX); kernel_signal_flush(&members[1], true, UINT64_MAX); - puts("PASS process signals/itimer/exit: shared pending, exited leader, stop/continue, alarm, periodic rearm, final-thread parent notification"); + check_group_signal_namespaces(); + puts("PASS process signals/itimer/exit: shared pending, exited leader, stop/continue, alarm, periodic rearm, final-thread parent notification, namespace UIDs"); } diff --git a/tools/tests/signal_info_queue_test.c b/tools/tests/signal_info_queue_test.c index e14df178..94a555ed 100644 --- a/tools/tests/signal_info_queue_test.c +++ b/tools/tests/signal_info_queue_test.c @@ -6,11 +6,21 @@ #include "../../kernel/signal/signal.c" #include "../../kernel/signal/signal_queue.c" #include "../../kernel/syscall/time/time.c" +#include "../../kernel/syscall/process/pidfd.c" static struct task people[3], *current; static uint64_t ticks = 100, inaccessible; static unsigned allocations, exits; static bool fail_alloc; +static struct task_file signal_pidfd; +struct task_file *task_file_for_io(struct task *task, int fd) +{ assert(task == current && fd == 7); return &signal_pidfd; } +struct task *sched_task_identity_task(const struct task_identity *identity) +{ return (struct task *)identity; } +enum sched_pidfd_state sched_task_pidfd_state(const struct task_identity *identity, bool thread) +{ (void)thread; return identity ? SCHED_PIDFD_LIVE : SCHED_PIDFD_REAPED; } +int sched_signal_user_process_target(struct task *task, int sig, const struct linux_siginfo *info) +{ return kernel_signal_enqueue(task, true, sig, info); } #ifdef CONFIG_SWAP static uint64_t swapped_output,swapped_input; static bool wait_contention,input_contention; @@ -32,7 +42,7 @@ void power_reboot(void) { abort(); } void power_shutdown(void) { abort(); } void *kernel_malloc(size_t size) { if (fail_alloc) return NULL; void *p = malloc(size); if (p) ++allocations; return p; } -void kernel_free(void *p) { assert(allocations); --allocations; free(p); } +void kernel_free(void *p) { if (p) { assert(allocations); --allocations; free(p); } } void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) { assert(!lock->state); lock->state = 1; *flags = 0; } void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) @@ -75,6 +85,108 @@ static int send_info(unsigned target, int sig, uint64_t value, bool thread) sig, (uintptr_t)&info, thread); } +/** @brief Build immutable UID maps through the real proc-control provider. */ +static struct user_namespace *signal_namespace(const char *map) +{ + struct task root = {.cap_effective = (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1}; + struct user_namespace *ns; + struct user_namespace_file control; + uint32_t written; + assert(!user_namespace_create(&root, &ns)); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_UID_MAP, true, &control)); + assert(!user_namespace_file_write(&control, &root, 0, map, strlen(map), &written)); + assert(written == strlen(map)); + user_namespace_file_close(&control); + return ns; +} + +/** @brief Check queueinfo and real pidfd sends at the namespace boundary. */ +static void check_namespace_siginfo(void) +{ + struct user_namespace *sender_ns = signal_namespace("0 1000 8\n20 2000 3\n"); + struct user_namespace *receiver_ns = signal_namespace("40 1000 8\n60 2000 3\n"); + struct task *sender = &people[0], *target = &people[2]; + current = sender; + sender->user_ns = sender_ns; + sender->uid = sender->euid = sender->suid = 1002; + target->user_ns = receiver_ns; + target->uid = target->euid = target->suid = 1002; + target->limits.sigpending.rlim_cur = 8; + target->blocked_signals = UINT64_MAX; + struct linux_siginfo sent = {.signo = 35, .error = 7, .code = LINUX_SI_QUEUE, + .fields.realtime = {.pid = 567, .uid = 2, .value = UINT64_C(0x123456789abcdef0)}}; + struct linux_siginfo received; + for (unsigned thread = 0; thread < 2; ++thread) { + assert(!kernel_signal_queueinfo(12, 12, 35, (uintptr_t)&sent, thread)); + assert(kernel_signal_dequeue(target, UINT64_MAX, &received) == 35); + assert(received.fields.realtime.uid == 42 && received.fields.realtime.pid == 567); + assert(received.fields.realtime.value == sent.fields.realtime.value && received.error == 7); + assert(sent.fields.realtime.uid == 2); + } + sent.fields.realtime.uid = 20; + assert(!kernel_signal_queueinfo(12, 12, 35, (uintptr_t)&sent, true)); + assert(kernel_signal_dequeue(target, UINT64_MAX, &received) == 35); + assert(received.fields.realtime.uid == 60); + sent.fields.realtime.uid = 9000; + assert(!kernel_signal_queueinfo(12, 12, 35, (uintptr_t)&sent, false)); + assert(kernel_signal_dequeue(target, UINT64_MAX, &received) == 35); + assert(received.fields.realtime.uid == 65534); + target->user_ns = sender_ns; + assert(!kernel_signal_queueinfo(12, 12, 35, (uintptr_t)&sent, true)); + assert(kernel_signal_dequeue(target, UINT64_MAX, &received) == 35); + assert(received.fields.realtime.uid == 9000); + target->user_ns = receiver_ns; + sent.fields.realtime.uid = 2; + assert(!kernel_signal_queueinfo(12, 12, 35, (uintptr_t)&sent, true)); + target->user_ns = NULL; + assert(kernel_signal_dequeue(target, UINT64_MAX, &received) == 35); + assert(received.fields.realtime.uid == 42); + target->user_ns = receiver_ns; + const struct { int sig, code; bool uid; } layouts[] = { + {35, LINUX_SI_USER, true}, {35, LINUX_SI_KERNEL, true}, {17, 1, true}, + {4, 11, false}, {8, 15, false}, {11, 10, false}, {7, 5, false}, + {5, 6, false}, {31, 2, false}, {29, 6, false}, {35, 6, false}, + {4, 12, true}, {8, 16, true}, {11, 11, true}, {17, 7, true}, + }; + for (unsigned i = 0; i < sizeof(layouts) / sizeof(layouts[0]); ++i) { + struct linux_siginfo original = {.signo = layouts[i].sig, .code = layouts[i].code, + .fields.realtime = {.pid = 567, .uid = 2, .value = UINT64_C(0x123456789abcdef0)}}; + struct linux_siginfo expected = original; + if (layouts[i].uid) expected.fields.sender.uid = 42; + kernel_signal_translate_user_info(sender, target, &original); + assert(!memcmp(&original, &expected, sizeof(original))); + } + const int payload_codes[] = {LINUX_SI_TIMER, -5}; + for (unsigned i = 0; i < sizeof(payload_codes) / sizeof(payload_codes[0]); ++i) { + sent.code = payload_codes[i]; + assert(!kernel_signal_queueinfo(12, 12, 35, (uintptr_t)&sent, true)); + assert(kernel_signal_dequeue(target, UINT64_MAX, &received) == 35); + assert(!memcmp(&sent, &received, sizeof(sent))); + } + signal_pidfd = (struct task_file){.kind = TASK_FILE_KIND_PIDFD, .aux = (uintptr_t)target}; + for (unsigned thread = 0; thread < 2; ++thread) { + uint32_t flags = thread ? PIDFD_SIGNAL_THREAD : PIDFD_SIGNAL_THREAD_GROUP; + assert(!syscall_pidfd_send_signal(sender, 7, 35, 0, flags)); + assert(kernel_signal_dequeue(target, UINT64_MAX, &received) == 35); + assert(received.fields.sender.uid == 42 && received.fields.sender.pid == 10); + sent.code = LINUX_SI_QUEUE; + assert(!syscall_pidfd_send_signal(sender, 7, 35, (uintptr_t)&sent, flags)); + assert(kernel_signal_dequeue(target, UINT64_MAX, &received) == 35); + assert(received.fields.realtime.uid == 42); + } + assert(!kernel_signal_queueinfo(12, 12, 35, (uintptr_t)&sent, true)); + current = target; + uint64_t mask = UINT64_C(1) << 34; + struct linux_timespec timeout = {0}; + assert(syscall_rt_sigtimedwait((uintptr_t)&mask, (uintptr_t)&received, + (uintptr_t)&timeout, 8) == 35); + assert(received.fields.realtime.uid == 42); + current = sender; + sender->user_ns = target->user_ns = NULL; + user_namespace_put(sender_ns); + user_namespace_put(receiver_ns); +} + int main(void) { for (unsigned i = 0; i < 3; ++i) { @@ -212,6 +324,7 @@ int main(void) current->pending_signals = 1ULL << 11; assert(syscall_rt_sigtimedwait(0, 0, 0, 8) == -LINUX_EINTR && !current->sigwait_active); kernel_signal_flush(current, false, UINT64_MAX); + check_namespace_siginfo(); assert(!allocations && !exits && !signal_accounts); puts("PASS siginfo: FIFO/coalescing, queue priority, per-UID limits, faults/permissions, ignored signals, sigtimedwait lifecycle"); } diff --git a/tools/tests/signalfd_test.c b/tools/tests/signalfd_test.c index 607a4f30..b14eb373 100644 --- a/tools/tests/signalfd_test.c +++ b/tools/tests/signalfd_test.c @@ -22,6 +22,8 @@ void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) { (void)flags; assert(lock->state); lock->state = 0; } struct task *sched_current_task(void) { return current; } struct task *sched_find(uint32_t pid) { return pid == 10 ? &readers[0] : pid == 11 ? &readers[1] : NULL; } +int sched_signal_user_process_info(uint32_t pid, int sig, const struct linux_siginfo *info) +{ return kernel_signal_enqueue(sched_find(pid), true, sig, info); } void sched_alarm_rearm(struct task *task) { (void)task; } void sched_exit_group(uint32_t pid, uint64_t code) { (void)pid; (void)code; assert(0); } void sched_signal_job_control(uint32_t pid, int sig) { (void)pid; (void)sig; assert(0); } @@ -165,5 +167,28 @@ int main(void) output[0] = signalfd_info(&sent); assert(output[0].call_address == 0x12345678 && output[0].syscall == 44 && output[0].arch == 0xc000003e); assert(!allocations); - puts("PASS real signalfd/queues: masks, reader identity, FIFO, readv records, copy faults, blocking wake, siginfo layouts"); + struct task root = {.cap_effective = (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1}; + struct user_namespace *ns; + struct user_namespace_file control; + uint32_t written; + const char map[] = "40 1000 8\n"; + assert(!user_namespace_create(&root, &ns)); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_UID_MAP, true, &control)); + assert(!user_namespace_file_write(&control, &root, 0, map, sizeof(map) - 1, &written)); + user_namespace_file_close(&control); + readers[0].uid = readers[1].uid = 1002; + readers[1].user_ns = ns; + readers[1].blocked_signals = UINT64_MAX; + current = &readers[0]; + sent = (struct linux_siginfo){.signo = 35, .code = LINUX_SI_QUEUE, + .fields.realtime = {.pid = 123, .uid = 1002, .value = 456}}; + assert(!kernel_signal_queueinfo(readers[1].tgid, 11, 35, (uintptr_t)&sent, true)); + current = &readers[1]; + descriptor.aux = UINT64_C(1) << 34; + assert(task_signalfd_read(current, &descriptor, (uintptr_t)output, sizeof(output[0])) == 128); + assert(output[0].uid == 42 && output[0].pid == 123 && output[0].value_ptr == 456); + readers[1].user_ns = NULL; + user_namespace_put(ns); + assert(!allocations); + puts("PASS real signalfd/queues: masks, reader identity, FIFO, readv records, copy faults, blocking wake, siginfo layouts, namespace UIDs"); } diff --git a/tools/tests/task8_wait_swap_test.c b/tools/tests/task8_wait_swap_test.c index 8febdbe4..6807e279 100644 --- a/tools/tests/task8_wait_swap_test.c +++ b/tools/tests/task8_wait_swap_test.c @@ -55,10 +55,24 @@ static struct task *wait_fixture_task(uint32_t pid) object->task=*old;free(old);return &object->task; } +/** @brief Give the parent a nonidentity UID map using the real controls. */ +static void map_wait_namespace(struct task *parent) +{ + struct task root = {.cap_effective = (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1}; + struct user_namespace_file control; + uint32_t written; + const char map[] = "40 1000 8\n"; + assert(!user_namespace_create(&root, &parent->user_ns)); + assert(!user_namespace_file_open(parent->user_ns, &root, USER_NAMESPACE_UID_MAP, true, &control)); + assert(!user_namespace_file_write(&control, &root, 0, map, sizeof(map) - 1, &written)); + user_namespace_file_close(&control); +} + /** @brief Exercise the real pidfd wait front door across both output buffers. */ static void check_pidfd_wait_swap(struct task *child) { child->pid = 51; + child->uid = 1002; child->parent_pid = 50; child->state = TASK_EXITED; child->flags = TASK_FLAG_WAITABLE_CHILD | TASK_FLAG_RESOURCES_RELEASED; @@ -71,6 +85,15 @@ static void check_pidfd_wait_swap(struct task *child) struct linux_siginfo info = {0}; struct linux_rusage usage = {.ru_utime = {-1, -1}}; const uintptr_t siginfo = (uintptr_t)&info, rusage = (uintptr_t)&usage; + assert(!syscall_legacy_process(LINUX_SYS_WAITID, LINUX_P_PIDFD, 7, siginfo, + LINUX_WEXITED | LINUX_WNOWAIT, 0, 0)); + assert(info.fields.child.uid == 42 && child->pid == 51 && child->uid == 1002); + child->uid = 9000; + assert(!syscall_legacy_process(LINUX_SYS_WAITID, LINUX_P_PIDFD, 7, siginfo, + LINUX_WEXITED | LINUX_WNOWAIT, 0, 0)); + assert(info.fields.child.uid == 65534 && child->uid == 9000); + child->uid = 1002; + info = (struct linux_siginfo){0}; contended = true; swapped = rusage; assert(syscall_legacy_process(LINUX_SYS_WAITID, LINUX_P_PIDFD, 7, siginfo, @@ -103,6 +126,8 @@ int main(void) parent->state=TASK_RUNNING;child->parent_pid=50;child->state=TASK_EXITED; child->exit_code=7;child->flags|=TASK_FLAG_RESOURCES_RELEASED; execution_lock_depth=1;interrupts_enabled=false; + map_wait_namespace(parent); + child->uid = 1002; int status=-1;swapped=(uintptr_t)&status;contended=true; assert(syscall_legacy_process(LINUX_SYS_WAIT4,51,(uintptr_t)&status,0,0,0,0)==KERNEL_SYSCALL_SWAP_CONTENDED); assert(child->pid==51 && status==-1); @@ -113,13 +138,14 @@ int main(void) child->pid=51;child->parent_pid=50;child->state=TASK_EXITED; child->flags=TASK_FLAG_WAITABLE_CHILD|TASK_FLAG_RESOURCES_RELEASED; + child->uid = 1002; struct linux_siginfo info={0};swapped=(uintptr_t)&info;contended=true; assert(syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,4|0x01000000u,0,0)==KERNEL_SYSCALL_SWAP_CONTENDED); assert(child->pid==51);contended=false; assert(!syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,4|0x01000000u,0,0)); - assert(child->pid==51 && info.fields.child.pid==51); + assert(child->pid==51 && info.fields.child.pid==51 && info.fields.child.uid==42); assert(!syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,4,0,0)); - assert(child->pid==0 && info.fields.child.status==7); + assert(child->pid==0 && info.fields.child.status==7 && info.fields.child.uid==42); child->pid=51;child->parent_pid=50;child->state=TASK_READY; child->flags=TASK_FLAG_WAITABLE_CHILD;status=123;swapped=(uintptr_t)&status;contended=true; @@ -130,7 +156,7 @@ int main(void) assert(syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,4|1,0,0)==KERNEL_SYSCALL_SWAP_CONTENDED); contended=false; assert(!syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,4|1,0,0)); - assert(!info.signo && !info.fields.child.pid); + assert(!info.signo && !info.fields.child.pid && !info.fields.child.uid); /* A sibling may consume the unreserved event while the first waiter is * parked. Its retry must observe ECHILD, never a fabricated old result. */ @@ -151,20 +177,24 @@ int main(void) child->pid=51;child->parent_pid=50;child->state=TASK_STOPPED; child->flags=TASK_FLAG_WAITABLE_CHILD;child->child_event=TASK_CHILD_EVENT_STOPPED; child->stop_signal=19;memset(&info,0,sizeof(info)); + child->uid = 9000; swapped=(uintptr_t)&info;contended=true; assert(syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,2|0x01000000u,0,0)==KERNEL_SYSCALL_SWAP_CONTENDED); assert(child->child_event==TASK_CHILD_EVENT_STOPPED); contended=false; assert(!syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,2|0x01000000u,0,0)); assert(info.code==5 && info.fields.child.status==19 && child->child_event==TASK_CHILD_EVENT_STOPPED); + assert(info.fields.child.uid == 65534 && child->uid == 9000); assert(!syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,2,0,0)); assert(child->child_event==TASK_CHILD_EVENT_NONE); child->state=TASK_READY;child->child_event=TASK_CHILD_EVENT_CONTINUED; + child->uid = 1002; swapped=(uintptr_t)&info;contended=true; assert(syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,8,0,0)==KERNEL_SYSCALL_SWAP_CONTENDED); assert(child->child_event==TASK_CHILD_EVENT_CONTINUED);contended=false; assert(!syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,8,0,0)); assert(info.code==6 && info.fields.child.status==18 && child->child_event==TASK_CHILD_EVENT_NONE); + assert(info.fields.child.uid == 42); child->state=TASK_READY; @@ -192,6 +222,8 @@ int main(void) assert(syscall_legacy_process(LINUX_SYS_WAITID,1,51,(uintptr_t)&info,4,0,0)==-RELIEFOS_ECHILD); assert(!info.signo && !info.fields.child.pid); check_pidfd_wait_swap(child); + user_namespace_put(parent->user_ns); + parent->user_ns = NULL; execution_lock_depth=0;interrupts_enabled=true;free(parent);free(child);free(peer); puts("PASS wait4/waitid readiness, pidfd and numeric swap retry, cleanup gate and late errors");return 0; } From 15228f2009f2ecc0507cba1d789333414b87b6ea Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 00:58:26 +0800 Subject: [PATCH 61/97] feat(userns): translate SysV IPC owner and creator identities --- Documentation/core-api/mount-namespaces.rst | 14 +++ .../LC_MESSAGES/core-api/mount-namespaces.po | 9 ++ .../LC_MESSAGES/core-api/mount-namespaces.po | 9 ++ kernel/syscall/ipc/sysv_msg.c | 15 +++- kernel/syscall/ipc/sysv_permissions.h | 45 ++++++++++ kernel/syscall/ipc/sysv_sem.c | 12 ++- kernel/syscall/ipc/sysv_shm.c | 15 ++-- tools/test_linux_sysv_msg.py | 3 +- tools/test_linux_sysv_sem.py | 3 +- tools/tests/sysv_msg_test.c | 82 +++++++++++++++++- tools/tests/sysv_sem_test.c | 79 ++++++++++++++++- tools/tests/sysv_shm_test.c | 85 +++++++++++++++++++ tools/tests/task8_host_fixtures.json | 4 + tools/tests/task8_msg_signal_test.c | 10 +++ tools/tests/task8_msg_user_test.c | 14 ++- tools/tests/task8_sem_user_test.c | 14 ++- tools/tests/task8_shm_user_test.c | 17 ++++ 17 files changed, 409 insertions(+), 21 deletions(-) create mode 100644 kernel/syscall/ipc/sysv_permissions.h diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 2fd0daa2..79ff466b 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -186,5 +186,19 @@ UID,最终复制实际事件时转换为调用方空间的 ID,未映射时 ``WNOHANG`` 无事件结果保持全零,``WNOWAIT`` 保留事件。停止、继续与退出事件 采用相同转换,最终输出错误沿用已有事件消费规则。 +SysV IPC 凭据 +============= + +消息队列、信号量和共享内存的注册表、权限判断与配额使用全局 UID/GID。 +``IPC_STAT``、各类 ``STAT`` 和 ``STAT_ANY`` 在输出副本中将所有者及创建者的 +``uid/gid/cuid/cgid`` 转换为调用方用户空间的 ID,未映射时输出 65534。 +用户页等待与复制失败沿用原有重试及错误规则,查询保留注册表的全局身份。 + +``IPC_SET`` 先执行现有对象所有权与资源限制检查,再将输入的 UID/GID 全部 +转换为全局 ID。任一输入未映射或为 ``UINT32_MAX`` 时返回 ``EINVAL``,对象的 +身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 +创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 +用户空间检查。 + 内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 ``EINVAL``。其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index c9dbc4b7..00b9c8bc 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -348,3 +348,12 @@ msgstr "Translation completes before enqueue. Signal queues, handler frames, ``s msgid "数字 PID 和 pidfd 的 ``waitid`` 在内部快照及输出页重试期间保留子进程的全局 UID,最终复制实际事件时转换为调用方空间的 ID,未映射时输出 65534。 ``WNOHANG`` 无事件结果保持全零,``WNOWAIT`` 保留事件。停止、继续与退出事件 采用相同转换,最终输出错误沿用已有事件消费规则。" msgstr "Numeric-PID and pidfd ``waitid`` retain the child global UID in internal snapshots and across output-page retries. Final copyout of an actual event maps it into the caller namespace, reporting 65534 for unmapped IDs. ``WNOHANG`` results without an event remain zeroed, and ``WNOWAIT`` preserves the event. Stop, continue and exit events use the same translation. Final output errors follow the existing event-consumption rules." + +msgid "SysV IPC 凭据" +msgstr "SysV IPC credentials" + +msgid "消息队列、信号量和共享内存的注册表、权限判断与配额使用全局 UID/GID。 ``IPC_STAT``、各类 ``STAT`` 和 ``STAT_ANY`` 在输出副本中将所有者及创建者的 ``uid/gid/cuid/cgid`` 转换为调用方用户空间的 ID,未映射时输出 65534。 用户页等待与复制失败沿用原有重试及错误规则,查询保留注册表的全局身份。" +msgstr "Message queue, semaphore and shared-memory registries, permission checks and quotas use global UID/GID values. ``IPC_STAT``, the ``STAT`` variants and ``STAT_ANY`` translate the owner and creator ``uid/gid/cuid/cgid`` fields in the output copy into the caller user namespace, reporting 65534 for unmapped IDs. Waiting for user pages and copy failures follow the existing retry and error rules. Queries retain the global identities in the registry." + +msgid "``IPC_SET`` 先执行现有对象所有权与资源限制检查,再将输入的 UID/GID 全部 转换为全局 ID。任一输入未映射或为 ``UINT32_MAX`` 时返回 ``EINVAL``,对象的 身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 用户空间检查。" +msgstr "``IPC_SET`` first performs the existing object ownership and resource-limit checks, then translates both input UID/GID values into global IDs. An unmapped input or ``UINT32_MAX`` returns ``EINVAL``, preserving the object identities, permissions, capacity and modification time. Success updates the owner and low 0777 permission bits while preserving creator identities and shared-memory lock and deletion flags. Global IPC administration and resource privileges are still checked in the initial user namespace." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 01d89f47..8c84c98f 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -306,3 +306,12 @@ msgstr "変換はキューへの追加前に完了します。シグナルキュ msgid "数字 PID 和 pidfd 的 ``waitid`` 在内部快照及输出页重试期间保留子进程的全局 UID,最终复制实际事件时转换为调用方空间的 ID,未映射时输出 65534。 ``WNOHANG`` 无事件结果保持全零,``WNOWAIT`` 保留事件。停止、继续与退出事件 采用相同转换,最终输出错误沿用已有事件消费规则。" msgstr "数値 PID と pidfd の ``waitid`` は、内部スナップショットと出力ページの再試行中に子プロセスのグローバル UID を保持します。実際のイベントを最終コピーするときに呼び出し元の空間へ変換し、未マッピングの ID は 65534 を返します。``WNOHANG`` でイベントがない結果はすべてゼロを保ち、``WNOWAIT`` はイベントを保持します。停止、継続、終了イベントに同じ変換を適用し、最終出力エラーには既存のイベント消費規則を適用します。" + +msgid "SysV IPC 凭据" +msgstr "SysV IPC の資格情報" + +msgid "消息队列、信号量和共享内存的注册表、权限判断与配额使用全局 UID/GID。 ``IPC_STAT``、各类 ``STAT`` 和 ``STAT_ANY`` 在输出副本中将所有者及创建者的 ``uid/gid/cuid/cgid`` 转换为调用方用户空间的 ID,未映射时输出 65534。 用户页等待与复制失败沿用原有重试及错误规则,查询保留注册表的全局身份。" +msgstr "メッセージキュー、セマフォ、共有メモリの登録表、権限判定、割り当て制限はグローバル UID/GID を使用します。``IPC_STAT``、各種 ``STAT``、``STAT_ANY`` は出力用コピーの所有者と作成者の ``uid/gid/cuid/cgid`` を呼び出し元のユーザー名前空間の ID に変換し、未マッピングの ID は 65534 として返します。ユーザーページの待機とコピー失敗には既存の再試行とエラー規則を適用します。照会では登録表のグローバル ID を保持します。" + +msgid "``IPC_SET`` 先执行现有对象所有权与资源限制检查,再将输入的 UID/GID 全部 转换为全局 ID。任一输入未映射或为 ``UINT32_MAX`` 时返回 ``EINVAL``,对象的 身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 用户空间检查。" +msgstr "``IPC_SET`` は既存のオブジェクト所有権とリソース制限を確認してから、入力 UID/GID の両方をグローバル ID に変換します。未マッピングの入力または ``UINT32_MAX`` には ``EINVAL`` を返し、オブジェクトの ID、権限、容量、変更時刻を保持します。成功時は所有者と下位 0777 の権限ビットを更新し、作成者の ID と共有メモリのロックおよび削除フラグを保持します。グローバル IPC 管理とリソース特権は引き続き初期ユーザー名前空間で確認します。" diff --git a/kernel/syscall/ipc/sysv_msg.c b/kernel/syscall/ipc/sysv_msg.c index 496f9530..e963847a 100644 --- a/kernel/syscall/ipc/sysv_msg.c +++ b/kernel/syscall/ipc/sysv_msg.c @@ -12,6 +12,7 @@ #include #include #include +#include "sysv_permissions.h" #define MSG_ID_SLOTS 32768u @@ -445,8 +446,12 @@ static void msg_remove(struct sysv_msg_queue *q) msg_put_queue(q); } -/** @brief Implement native msgctl layouts, permissions, configuration and live accounting. +/** @brief Implement native msgctl with namespace-local identity input/output. * The global queue's owner and capacity overrides use initial user namespace capabilities. + * @param task Execution-owned caller credentials and output address space. + * @param id Native ID or MSG_STAT slot. @param command Native command. + * @param buffer User control structure, ignored for IPC_RMID. + * @return Native result, negative errno, or the swapped-page retry marker. */ static int64_t msg_control(struct task *task, int32_t id, int32_t command, uint64_t buffer) { @@ -483,7 +488,9 @@ static int64_t msg_control(struct task *task, int32_t id, int32_t command, uint6 int prep = msg_prepare_output(task, buffer, sizeof(q->stat)); if (prep) return prep; #endif - int error = user_copy_to_task(task, buffer, &q->stat, sizeof(q->stat)); + struct linux_msqid64_ds output = q->stat; + sysv_permissions_to_user(task, &output.msg_perm); + int error = user_copy_to_task(task, buffer, &output, sizeof(output)); return error ? error : command == LINUX_IPC_STAT ? 0 : q->id; } struct linux_ipc64_perm *p = &q->stat.msg_perm; @@ -493,8 +500,8 @@ static int64_t msg_control(struct task *task, int32_t id, int32_t command, uint6 /* msgctl_down takes int even though the native input field is unsigned long. */ int32_t bytes = (int32_t)input.msg_qbytes; if ((uint32_t)bytes > LINUX_MSGMNB && !(task_initial_capabilities(task) & (1ULL << CAP_SYS_RESOURCE))) return -LINUX_EPERM; - if (input.msg_perm.uid == UINT32_MAX || input.msg_perm.gid == UINT32_MAX) return -LINUX_EINVAL; - p->uid = input.msg_perm.uid; p->gid = input.msg_perm.gid; p->mode = input.msg_perm.mode & 0777; + int error = sysv_permissions_update(task, &input.msg_perm, p); + if (error) return error; q->stat.msg_qbytes = (uint64_t)(int64_t)bytes; q->stat.msg_ctime = msg_now(); for (struct task_sysv_msg_state *w = q->receivers; w; w = w->next) msg_wake(w); msg_wake_senders(q); diff --git a/kernel/syscall/ipc/sysv_permissions.h b/kernel/syscall/ipc/sysv_permissions.h new file mode 100644 index 00000000..208a18ba --- /dev/null +++ b/kernel/syscall/ipc/sysv_permissions.h @@ -0,0 +1,45 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_SYSV_PERMISSIONS_H +#define RELIEFNT_SYSV_PERMISSIONS_H + +#include +#include +#include + +/** @brief Translate a temporary IPC status record into the caller namespace. + * @param task Execution-owned caller with a retained user namespace. + * @param permissions Writable output copy containing global IDs on entry. + * Unmapped owner and creator IDs become 65534. Registry state is untouched. + * No allocation, references, locks or user access occur. + */ +static inline void sysv_permissions_to_user(const struct task *task, + struct ipc64_perm *permissions) +{ + permissions->uid = user_namespace_id_from_kernel_munged(task->user_ns, false, permissions->uid); + permissions->gid = user_namespace_id_from_kernel_munged(task->user_ns, true, permissions->gid); + permissions->cuid = user_namespace_id_from_kernel_munged(task->user_ns, false, permissions->cuid); + permissions->cgid = user_namespace_id_from_kernel_munged(task->user_ns, true, permissions->cgid); +} + +/** @brief Apply IPC_SET only after both namespace-local owner IDs are valid. + * @param task Execution-owned caller with a retained user namespace. + * @param input Kernel copy of the caller's requested permissions. + * @param permissions Registry permissions, serialized by execution ownership. + * @return Zero, or -EINVAL without mutation for an unmapped or invalid ID. + * Caller checks object ownership and resource limits first. Creator IDs and + * mode bits outside 0777 are retained. No allocation, locks or user access. + */ +static inline int sysv_permissions_update(const struct task *task, + const struct ipc64_perm *input, + struct ipc64_perm *permissions) +{ + uint32_t uid = user_namespace_id_to_kernel(task->user_ns, false, input->uid); + uint32_t gid = user_namespace_id_to_kernel(task->user_ns, true, input->gid); + if (uid == UINT32_MAX || gid == UINT32_MAX) return -LINUX_EINVAL; + permissions->uid = uid; + permissions->gid = gid; + permissions->mode = (permissions->mode & ~0777u) | (input->mode & 0777); + return 0; +} + +#endif diff --git a/kernel/syscall/ipc/sysv_sem.c b/kernel/syscall/ipc/sysv_sem.c index fd9c32c0..f65f4cae 100644 --- a/kernel/syscall/ipc/sysv_sem.c +++ b/kernel/syscall/ipc/sysv_sem.c @@ -12,6 +12,7 @@ #include #include #include +#include "sysv_permissions.h" #define SEM_ID_SLOTS 32768u #define SEM_FAST_IO 256u @@ -600,8 +601,12 @@ static int sem_all(struct task *task, struct sysv_sem_array *a, uint64_t pointer return error; } -/** @brief Implement native semctl command, width, permission and copy ordering. +/** @brief Implement native semctl with namespace-local identity input/output. * Administrative changes to the shared registry require initial user namespace CAP_SYS_ADMIN. + * @param task Execution-owned caller credentials and output address space. + * @param id Native ID or SEM_STAT slot. @param index Semaphore number. + * @param cmd Native command. @param arg Native value or user structure address. + * @return Native result, negative errno, or the swapped-page retry marker. */ static int64_t sem_control(struct task *task, int32_t id, int32_t index, int32_t cmd, uint64_t arg) { @@ -639,8 +644,8 @@ static int64_t sem_control(struct task *task, int32_t id, int32_t index, int32_t if (task->euid != p->uid && task->euid != p->cuid && !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; if (cmd == LINUX_IPC_RMID) { sem_remove(a); return 0; } - if (input.sem_perm.uid == UINT32_MAX || input.sem_perm.gid == UINT32_MAX) return -LINUX_EINVAL; - p->uid = input.sem_perm.uid; p->gid = input.sem_perm.gid; p->mode = input.sem_perm.mode & 0777; + int error = sysv_permissions_update(task, &input.sem_perm, p); + if (error) return error; a->stat.sem_ctime = sem_wall_time(); return 0; } @@ -648,6 +653,7 @@ static int64_t sem_control(struct task *task, int32_t id, int32_t index, int32_t cmd == LINUX_SETALL || cmd == LINUX_SETVAL ? 0222 : 0444)) return -LINUX_EACCES; if (stat) { struct linux_semid64_ds output = a->stat; + sysv_permissions_to_user(task, &output.sem_perm); output.sem_otime = a->values[0].otime; for (uint32_t i = 1; i < output.sem_nsems; ++i) if (a->values[i].otime > output.sem_otime) output.sem_otime = a->values[i].otime; diff --git a/kernel/syscall/ipc/sysv_shm.c b/kernel/syscall/ipc/sysv_shm.c index 98d2a5a7..5500ead8 100644 --- a/kernel/syscall/ipc/sysv_shm.c +++ b/kernel/syscall/ipc/sysv_shm.c @@ -14,6 +14,7 @@ #include #include #include +#include "sysv_permissions.h" #define SYSV_SHM_SLOTS 4096u #define SYSV_SHM_ID_BITS 12u @@ -370,7 +371,7 @@ static int sysv_shm_lock(struct task *task, struct sysv_shm_segment *s, bool loc } else if (!lock) s->stat.shm_perm.mode &= ~SYSV_SHM_LOCKED; return 0; } -/** @brief Dispatch canonical LP64 shmctl structures and commands. +/** @brief Dispatch LP64 shmctl with namespace-local identity input/output. * @param task Caller credentials and output address space. * @param id Native ID or SHM_STAT slot. @param command Native unmodified command. * @param pointer User structure address, ignored for RMID and LOCK/UNLOCK. @@ -413,12 +414,8 @@ static int64_t sysv_shm_control(struct task *task, int32_t id, int32_t command, s->stat.shm_perm.mode |= SYSV_SHM_DEST; if (!s->stat.shm_nattch && !s->pending_attach) sysv_shm_destroy(s); } else { - if (input.shm_perm.uid == UINT32_MAX || input.shm_perm.gid == UINT32_MAX) - return -LINUX_EINVAL; - s->stat.shm_perm.uid = input.shm_perm.uid; - s->stat.shm_perm.gid = input.shm_perm.gid; - s->stat.shm_perm.mode = (s->stat.shm_perm.mode & ~0777u) | - (input.shm_perm.mode & 0777); + int error = sysv_permissions_update(task, &input.shm_perm, &s->stat.shm_perm); + if (error) return error; s->stat.shm_ctime = sysv_shm_now(); } return 0; @@ -427,7 +424,9 @@ static int64_t sysv_shm_control(struct task *task, int32_t id, int32_t command, return sysv_shm_lock(task, s, command == SHM_LOCK); if (command != SHM_STAT_ANY && !sysv_shm_access(task, s, 4)) return -LINUX_EACCES; int prep=sysv_shm_prepare(task,pointer,sizeof(s->stat),true);if(prep)return prep; - return user_copy_to_task(task, pointer, &s->stat, sizeof(s->stat)) ? + struct shmid64_ds output = s->stat; + sysv_permissions_to_user(task, &output.shm_perm); + return user_copy_to_task(task, pointer, &output, sizeof(output)) ? -LINUX_EFAULT : (command == IPC_STAT ? 0 : s->id); } /** @brief Execute native shmget/shmat/shmdt/shmctl; no private SHM fallback. diff --git a/tools/test_linux_sysv_msg.py b/tools/test_linux_sysv_msg.py index 70710b64..fc33c0d8 100644 --- a/tools/test_linux_sysv_msg.py +++ b/tools/test_linux_sysv_msg.py @@ -10,7 +10,8 @@ subprocess.run(["cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude", "-Iinclude/uapi", - "-Iinclude", "tools/tests/sysv_msg_test.c", "-o", output], + "-Iinclude", "tools/tests/sysv_msg_test.c", + "kernel/sched/user_namespace.c", "-o", output], cwd=root, check=True) subprocess.run([output], cwd=root, check=True, timeout=20) output = str(Path(directory) / "sysv_msg_abi") diff --git a/tools/test_linux_sysv_sem.py b/tools/test_linux_sysv_sem.py index 557db93b..6f4eb820 100644 --- a/tools/test_linux_sysv_sem.py +++ b/tools/test_linux_sysv_sem.py @@ -10,7 +10,8 @@ subprocess.run(["cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude", "-Iinclude/uapi", - "-Iinclude", "tools/tests/sysv_sem_test.c", "-o", output], + "-Iinclude", "tools/tests/sysv_sem_test.c", + "kernel/sched/user_namespace.c", "-o", output], cwd=root, check=True) subprocess.run([output], cwd=root, check=True, timeout=20) output = str(Path(directory) / "sysv_sem_abi") diff --git a/tools/tests/sysv_msg_test.c b/tools/tests/sysv_msg_test.c index a17219c2..244b78c4 100644 --- a/tools/tests/sysv_msg_test.c +++ b/tools/tests/sysv_msg_test.c @@ -45,6 +45,85 @@ static int64_t receive_msg(int q, void *msg, uint64_t size, int64_t type, uint32 static int64_t control(int q, int cmd, void *data) { return syscall_sysv_msg(__NR_msgctl, q, cmd, (uintptr_t)data, 0, 0); } +/** @brief Exercise real UID/GID maps at msgctl input and output boundaries. */ +static void check_namespace_permissions(void) +{ + struct task root = {.cap_effective = UINT64_MAX}; + struct user_namespace *ns; + struct user_namespace_file file; + uint32_t written; + const char uid_map[] = "0 1000 8\n", gid_map[] = "40 100 8\n"; + assert(!user_namespace_create(&root, &ns)); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_UID_MAP, true, &file)); + assert(!user_namespace_file_write(&file, &root, 0, uid_map, sizeof(uid_map) - 1, &written)); + user_namespace_file_close(&file); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_GID_MAP, true, &file)); + assert(!user_namespace_file_write(&file, &root, 0, gid_map, sizeof(gid_map) - 1, &written)); + user_namespace_file_close(&file); + current = &tasks[0]; + current->user_ns = ns; + current->euid = 1000; + current->egid = current->fsgid = 100; + current->cap_effective = UINT64_MAX; + int id = msgget(0, 0600); + assert(id >= 0); + struct linux_msqid64_ds output, input, before; + const int commands[] = {LINUX_IPC_STAT, LINUX_MSG_STAT, LINUX_MSG_STAT_ANY}; + for (unsigned i = 0; i < 3; ++i) { + assert(control(i ? id & 32767 : id, commands[i], &output) == (i ? id : 0)); + assert(output.msg_perm.uid == 0 && output.msg_perm.cuid == 0); + assert(output.msg_perm.gid == 40 && output.msg_perm.cgid == 40); + } + input = output; + input.msg_perm.uid = 2; + input.msg_perm.gid = 42; + input.msg_perm.cuid = input.msg_perm.cgid = UINT32_MAX; + input.msg_perm.mode = 04755; + input.msg_qbytes = 1024; + assert(!control(id, LINUX_IPC_SET, &input)); + assert(!control(id, LINUX_IPC_STAT, &before)); + assert(before.msg_perm.uid == 2 && before.msg_perm.gid == 42); + assert(before.msg_perm.cuid == 0 && before.msg_perm.cgid == 40); + assert(before.msg_perm.mode == 0755 && before.msg_qbytes == 1024); + current->user_ns = NULL; + assert(!control(id, LINUX_IPC_STAT, &output)); + assert(output.msg_perm.uid == 1002 && output.msg_perm.gid == 102); + assert(output.msg_perm.cuid == 1000 && output.msg_perm.cgid == 100); + current->user_ns = ns; + const uint32_t invalid[] = {64, UINT32_MAX}; + for (unsigned i = 0; i < 2; ++i) { + input = before; + input.msg_perm.uid = invalid[i]; + input.msg_perm.gid = 43; + input.msg_perm.mode = 0; + input.msg_qbytes = 8; + assert(control(id, LINUX_IPC_SET, &input) == -LINUX_EINVAL); + assert(!control(id, LINUX_IPC_STAT, &output) && !memcmp(&before, &output, sizeof(output))); + input.msg_perm.uid = 3; + input.msg_perm.gid = invalid[i]; + assert(control(id, LINUX_IPC_SET, &input) == -LINUX_EINVAL); + assert(!control(id, LINUX_IPC_STAT, &output) && !memcmp(&before, &output, sizeof(output))); + } + assert(control(id, LINUX_IPC_STAT, (void *)1) == -LINUX_EFAULT); + current->euid = 9000; + assert(control(id, LINUX_IPC_RMID, NULL) == -LINUX_EPERM); + current->euid = 1000; + assert(!control(id, LINUX_IPC_RMID, NULL)); + current->user_ns = NULL; + current->euid = 5000; + current->egid = current->fsgid = 500; + id = msgget(0, 0600); + assert(id >= 0); + current->user_ns = ns; + assert(control(id & 32767, LINUX_MSG_STAT_ANY, &output) == id); + assert(output.msg_perm.uid == 65534 && output.msg_perm.cuid == 65534); + assert(output.msg_perm.gid == 65534 && output.msg_perm.cgid == 65534); + assert(!control(id, LINUX_IPC_RMID, NULL)); + current->user_ns = NULL; + user_namespace_put(ns); + assert(!allocations); +} + int main(void) { for (unsigned i = 0; i < 4; ++i) { @@ -197,7 +276,8 @@ int main(void) assert(control(q, LINUX_IPC_RMID, NULL) == 0); } assert(reused && !allocations); - puts("PASS kernel SysV queues: data/order, copy faults, permissions, blocked payload, pipeline, RMID and references"); + check_namespace_permissions(); + puts("PASS kernel SysV queues: data/order, copy faults, namespace permissions, blocked payload, pipeline, RMID and references"); return 0; } #endif diff --git a/tools/tests/sysv_sem_test.c b/tools/tests/sysv_sem_test.c index b9ac7e34..bafbc2fb 100644 --- a/tools/tests/sysv_sem_test.c +++ b/tools/tests/sysv_sem_test.c @@ -47,6 +47,82 @@ static int64_t op(int id, struct linux_sembuf *ops, uint64_t n) static int64_t timed(int id, struct linux_sembuf *ops, uint64_t n, struct linux_timespec *t) { return syscall_sysv_sem(__NR_semtimedop, id, (uintptr_t)ops, n, (uintptr_t)t); } +/** @brief Exercise real UID/GID maps at semctl input and output boundaries. */ +static void check_namespace_permissions(void) +{ + struct task root = {.cap_effective = UINT64_MAX}; + struct user_namespace *ns; + struct user_namespace_file file; + uint32_t written; + const char uid_map[] = "0 1000 8\n", gid_map[] = "40 100 8\n"; + assert(!user_namespace_create(&root, &ns)); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_UID_MAP, true, &file)); + assert(!user_namespace_file_write(&file, &root, 0, uid_map, sizeof(uid_map) - 1, &written)); + user_namespace_file_close(&file); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_GID_MAP, true, &file)); + assert(!user_namespace_file_write(&file, &root, 0, gid_map, sizeof(gid_map) - 1, &written)); + user_namespace_file_close(&file); + current = &tasks[0]; + current->user_ns = ns; + current->euid = 1000; + current->egid = current->fsgid = 100; + current->cap_effective = UINT64_MAX; + int id = get(0, 2, 0600); + assert(id >= 0); + struct linux_semid64_ds output, input, before; + const int commands[] = {LINUX_IPC_STAT, LINUX_SEM_STAT, LINUX_SEM_STAT_ANY}; + for (unsigned i = 0; i < 3; ++i) { + assert(ctl(i ? id & 32767 : id, 0, commands[i], (uintptr_t)&output) == (i ? id : 0)); + assert(output.sem_perm.uid == 0 && output.sem_perm.cuid == 0); + assert(output.sem_perm.gid == 40 && output.sem_perm.cgid == 40); + } + input = output; + input.sem_perm.uid = 2; + input.sem_perm.gid = 42; + input.sem_perm.cuid = input.sem_perm.cgid = UINT32_MAX; + input.sem_perm.mode = 04755; + assert(!ctl(id, 0, LINUX_IPC_SET, (uintptr_t)&input)); + assert(!ctl(id, 0, LINUX_IPC_STAT, (uintptr_t)&before)); + assert(before.sem_perm.uid == 2 && before.sem_perm.gid == 42); + assert(before.sem_perm.cuid == 0 && before.sem_perm.cgid == 40 && before.sem_perm.mode == 0755); + current->user_ns = NULL; + assert(!ctl(id, 0, LINUX_IPC_STAT, (uintptr_t)&output)); + assert(output.sem_perm.uid == 1002 && output.sem_perm.gid == 102); + assert(output.sem_perm.cuid == 1000 && output.sem_perm.cgid == 100); + current->user_ns = ns; + const uint32_t invalid[] = {64, UINT32_MAX}; + for (unsigned i = 0; i < 2; ++i) { + input = before; + input.sem_perm.uid = invalid[i]; + input.sem_perm.gid = 43; + input.sem_perm.mode = 0; + assert(ctl(id, 0, LINUX_IPC_SET, (uintptr_t)&input) == -LINUX_EINVAL); + assert(!ctl(id, 0, LINUX_IPC_STAT, (uintptr_t)&output) && !memcmp(&before, &output, sizeof(output))); + input.sem_perm.uid = 3; + input.sem_perm.gid = invalid[i]; + assert(ctl(id, 0, LINUX_IPC_SET, (uintptr_t)&input) == -LINUX_EINVAL); + assert(!ctl(id, 0, LINUX_IPC_STAT, (uintptr_t)&output) && !memcmp(&before, &output, sizeof(output))); + } + assert(ctl(id, 0, LINUX_IPC_STAT, 1) == -LINUX_EFAULT); + current->euid = 9000; + assert(ctl(id, 0, LINUX_IPC_RMID, 0) == -LINUX_EPERM); + current->euid = 1000; + assert(!ctl(id, 0, LINUX_IPC_RMID, 0)); + current->user_ns = NULL; + current->euid = 5000; + current->egid = current->fsgid = 500; + id = get(0, 1, 0600); + assert(id >= 0); + current->user_ns = ns; + assert(ctl(id & 32767, 0, LINUX_SEM_STAT_ANY, (uintptr_t)&output) == id); + assert(output.sem_perm.uid == 65534 && output.sem_perm.cuid == 65534); + assert(output.sem_perm.gid == 65534 && output.sem_perm.cgid == 65534); + assert(!ctl(id, 0, LINUX_IPC_RMID, 0)); + current->user_ns = NULL; + user_namespace_put(ns); + assert(!allocations); +} + int main(void) { for (unsigned i = 0; i < 4; ++i) { @@ -220,7 +296,8 @@ int main(void) assert(ctl(id, 0, LINUX_SETALL, (uintptr_t)large) == -LINUX_EFAULT); fault_at = 0; assert(ctl(id, 0, LINUX_IPC_RMID, 0) == 0 && !allocations); - puts("PASS kernel SysV semaphores: atomic rollback, blocked snapshots, timeouts, commands, undo sharing and removal"); + check_namespace_permissions(); + puts("PASS kernel SysV semaphores: atomic rollback, namespace permissions, blocked snapshots, timeouts, commands, undo sharing and removal"); return 0; } #endif diff --git a/tools/tests/sysv_shm_test.c b/tools/tests/sysv_shm_test.c index 6a46f92b..1470efb5 100644 --- a/tools/tests/sysv_shm_test.c +++ b/tools/tests/sysv_shm_test.c @@ -287,6 +287,90 @@ static void clone_pending_operands(struct task *parent,struct task *child,struct puts("PASS actual fork/CLONE_FS: graph and path ownership, rollback, and no inherited pending operands"); } +/** @brief Exercise real UID/GID maps at shmctl input and output boundaries. + * @param parent Execution-owned fixture task, restored to initial credentials. + */ +static void check_shm_namespace_permissions(struct task *parent) +{ + struct task root = {.cap_effective = UINT64_MAX}; + struct user_namespace *ns; + struct user_namespace_file file; + uint32_t written; + const char uid_map[] = "0 1000 8\n", gid_map[] = "40 100 8\n"; + assert(!user_namespace_create(&root, &ns)); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_UID_MAP, true, &file)); + assert(!user_namespace_file_write(&file, &root, 0, uid_map, sizeof(uid_map) - 1, &written)); + user_namespace_file_close(&file); + assert(!user_namespace_file_open(ns, &root, USER_NAMESPACE_GID_MAP, true, &file)); + assert(!user_namespace_file_write(&file, &root, 0, gid_map, sizeof(gid_map) - 1, &written)); + user_namespace_file_close(&file); + parent->user_ns = ns; + parent->euid = 1000; + parent->egid = parent->fsgid = 100; + parent->cap_effective = UINT64_MAX; + int id = get(IPC_PRIVATE, 4096, 0600); + assert(id >= 0); + assert(!ctl(id, SHM_LOCK, NULL)); + struct shmid64_ds output, input, before; + const int commands[] = {IPC_STAT, SHM_STAT, SHM_STAT_ANY}; + int slot = id & (SYSV_SHM_SLOTS - 1); + for (unsigned i = 0; i < 3; ++i) { + assert(ctl(i ? slot : id, commands[i], &output) == (i ? id : 0)); + assert(output.shm_perm.uid == 0 && output.shm_perm.cuid == 0); + assert(output.shm_perm.gid == 40 && output.shm_perm.cgid == 40); + } + input = output; + input.shm_perm.uid = 2; + input.shm_perm.gid = 42; + input.shm_perm.cuid = input.shm_perm.cgid = UINT32_MAX; + input.shm_perm.mode = 04755; + assert(!ctl(id, IPC_SET, &input)); + assert(!ctl(id, IPC_STAT, &before)); + assert(before.shm_perm.uid == 2 && before.shm_perm.gid == 42); + assert(before.shm_perm.cuid == 0 && before.shm_perm.cgid == 40); + assert(before.shm_perm.mode == (SYSV_SHM_LOCKED | 0755)); + parent->user_ns = NULL; + assert(!ctl(id, IPC_STAT, &output)); + assert(output.shm_perm.uid == 1002 && output.shm_perm.gid == 102); + assert(output.shm_perm.cuid == 1000 && output.shm_perm.cgid == 100); + parent->user_ns = ns; + const uint32_t invalid[] = {64, UINT32_MAX}; + for (unsigned i = 0; i < 2; ++i) { + input = before; + input.shm_perm.uid = invalid[i]; + input.shm_perm.gid = 43; + input.shm_perm.mode = 0; + assert(ctl(id, IPC_SET, &input) == -LINUX_EINVAL); + assert(!ctl(id, IPC_STAT, &output) && !memcmp(&before, &output, sizeof(output))); + input.shm_perm.uid = 3; + input.shm_perm.gid = invalid[i]; + assert(ctl(id, IPC_SET, &input) == -LINUX_EINVAL); + assert(!ctl(id, IPC_STAT, &output) && !memcmp(&before, &output, sizeof(output))); + } + assert(ctl(id, IPC_STAT, (void *)1) == -LINUX_EFAULT); + parent->euid = 9000; + assert(ctl(id, IPC_RMID, NULL) == -LINUX_EPERM); + parent->euid = 1000; + assert(!ctl(id, IPC_RMID, NULL)); + parent->user_ns = NULL; + parent->euid = 5000; + parent->egid = parent->fsgid = 500; + id = get(IPC_PRIVATE, 4096, 0600); + assert(id >= 0); + parent->user_ns = ns; + assert(ctl(id & (SYSV_SHM_SLOTS - 1), SHM_STAT_ANY, &output) == id); + assert(output.shm_perm.uid == 65534 && output.shm_perm.cuid == 65534); + assert(output.shm_perm.gid == 65534 && output.shm_perm.cgid == 65534); + assert(!ctl(id, IPC_RMID, NULL)); + parent->user_ns = NULL; + parent->euid = 1000; + parent->egid = parent->fsgid = 100; + parent->cap_effective = 0; + user_namespace_put(ns); + assert(!shm_heap_live && !live_pages()); +} + + #ifdef TASK8_CLONE_TID_TEST int inherited_task8_sysv_shm_main(void) #else @@ -712,6 +796,7 @@ int main(void) assert(ctl(id, IPC_STAT, &stat) == -LINUX_EINVAL && !shm_heap_live); address_space_destroy(sched_task_as(parent)); assert(!live_pages()); + check_shm_namespace_permissions(parent); tasks = NULL; task_count = 0; current_pid[0] = 0; puts("PASS real SysV SHM registry/PTE/VMA: zero pages, independent MMs, fork sharing,"); puts("readonly max_prot, split nattch, RMID live IDs, shmdt pieces, failure rollback and final page reclamation"); diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 908d6205..cf856f4e 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -1367,6 +1367,7 @@ "kernel/syscall/fs/locks.c", "tools/tests/task8_host_stubs/msg-signal-boundaries.c", "tools/tests/task8_host_stubs/no_prlimit_identity.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/msg-signal-candidate-2" ] @@ -1396,6 +1397,7 @@ "tools/tests/task8_msg_user_test.c", "kernel/syscall/fs/lookup_state.c", "tools/tests/task8_host_stubs/no_prlimit_identity.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/msg-user-rmid-unlinked-candidate-1" ] @@ -1924,6 +1926,7 @@ "tools/tests/task8_sem_user_test.c", "kernel/syscall/fs/lookup_state.c", "tools/tests/task8_host_stubs/no_prlimit_identity.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/sem-user-aperture-candidate-1" ] @@ -1970,6 +1973,7 @@ "-Wl,--gc-sections", "{tmp}/shm-user-candidate-1.o", "tools/tests/task8_host_stubs/shm-user-candidate-1-shm-user-candidate-1.stub.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/shm-user-candidate-1" ] diff --git a/tools/tests/task8_msg_signal_test.c b/tools/tests/task8_msg_signal_test.c index fa041e63..a5f6bba8 100644 --- a/tools/tests/task8_msg_signal_test.c +++ b/tools/tests/task8_msg_signal_test.c @@ -10,6 +10,16 @@ #undef main #include +/** @brief Check readable fixture memory after swap preparation. + * @param address First byte in the fixture's mapped signal address space. + * @param length Number of bytes to validate without accessing user memory. + * @return Zero for readable memory, or -EFAULT outside the mapped range. + */ +int user_range_readable(uint64_t address, uint64_t length) +{ + return user_range_ok(address, length) ? 0 : -LINUX_EFAULT; +} + /** @brief Invoke a message syscall with the real retry scope and task state. */ static int64_t scoped_msg(struct task *task,uint64_t nr,uint64_t a0,uint64_t a1, uint64_t a2,uint64_t a3,uint64_t a4) diff --git a/tools/tests/task8_msg_user_test.c b/tools/tests/task8_msg_user_test.c index 4cea2288..ad648ef6 100644 --- a/tools/tests/task8_msg_user_test.c +++ b/tools/tests/task8_msg_user_test.c @@ -7,6 +7,17 @@ #include "sysv_msg_test.c" #undef main #include + +/** @brief Check readable fixture memory after swap preparation. + * @param address First byte of the requested user range. + * @param length Number of bytes, including the fixture's injected read fault. + * @return Zero for readable memory, or -EFAULT for a rejected range. + */ +int user_range_readable(uint64_t address, uint64_t length) +{ + return user_range_ok(address, length) ? 0 : -LINUX_EFAULT; +} + static uint64_t blocked; static bool contended; static unsigned preparations; @@ -78,6 +89,7 @@ int main(void) current=&tasks[1];contended=false; assert(recv_scoped(q,&output,8,0)==-LINUX_EIDRM); task_lookup_scope_cancel(current);assert(!allocations && preparations); - puts("PASS SysV msg: retained input, queued and pipeline waits, RMID and exact cancellation"); + check_namespace_permissions(); + puts("PASS SysV msg: retained input, queued and pipeline waits, RMID, namespace permissions and exact cancellation"); return 0; } diff --git a/tools/tests/task8_sem_user_test.c b/tools/tests/task8_sem_user_test.c index 53e42d13..c4535cce 100644 --- a/tools/tests/task8_sem_user_test.c +++ b/tools/tests/task8_sem_user_test.c @@ -7,6 +7,17 @@ #include "sysv_sem_test.c" #undef main #include + +/** @brief Check readable fixture memory after swap preparation. + * @param address First byte of the requested user range. + * @param length Number of bytes, including the fixture's injected read fault. + * @return Zero for readable memory, or -EFAULT for a rejected range. + */ +int user_range_readable(uint64_t address, uint64_t length) +{ + return user_range_ok(address, length) ? 0 : -LINUX_EFAULT; +} + static uint64_t blocked; static bool contended; static unsigned preparations; @@ -52,6 +63,7 @@ int main(void) assert(scoped(__NR_semctl,id,0,LINUX_GETALL,across)==-LINUX_EFAULT); assert(preparations==before);task_lookup_scope_cancel(current);fault_at=0;contended=false; assert(!ctl(id,0,LINUX_IPC_RMID,0));free(values);free(output);assert(!allocations && preparations); - puts("PASS SysV sem: retained timeout and SETALL input; bounded GETALL prerequisite"); + check_namespace_permissions(); + puts("PASS SysV sem: retained timeout and SETALL input, namespace permissions and bounded GETALL prerequisite"); return 0; } diff --git a/tools/tests/task8_shm_user_test.c b/tools/tests/task8_shm_user_test.c index 810de206..6f604432 100644 --- a/tools/tests/task8_shm_user_test.c +++ b/tools/tests/task8_shm_user_test.c @@ -36,6 +36,23 @@ int main(void) assert(segment.stat.shm_perm.uid==101 && segment.stat.shm_ctime==42); unsigned before=preparations; assert(sysv_shm_control(¤t,1,-1,1)==-LINUX_EINVAL && preparations==before); + struct user_namespace empty = {.references = 1}; + current.user_ns = ∅ + struct shmid64_ds snapshot = segment.stat, output; + contended = true; + assert(sysv_shm_control(¤t, 1, SHM_STAT_ANY, (uintptr_t)&output) == + KERNEL_SYSCALL_SWAP_CONTENDED); + assert(!memcmp(&snapshot, &segment.stat, sizeof(snapshot))); + contended = false; + assert(sysv_shm_control(¤t, 1, SHM_STAT_ANY, (uintptr_t)&output) == 1); + assert(output.shm_perm.uid == 65534 && output.shm_perm.cuid == 65534); + assert(output.shm_perm.gid == 65534 && output.shm_perm.cgid == 65534); + input.shm_perm.uid = 2; + input.shm_perm.gid = 3; + input.shm_perm.mode = 0; + assert(sysv_shm_control(¤t, 1, IPC_SET, (uintptr_t)&input) == -LINUX_EINVAL); + assert(!memcmp(&snapshot, &segment.stat, sizeof(snapshot))); + current.user_ns = NULL; puts("PASS shmctl: bounded swapped input/output, no early mutation, ignored invalid command"); return 0; } From 643724f748c0242cd2c4f66a437f043ce1bb379b Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 01:04:45 +0800 Subject: [PATCH 62/97] feat(userns): render proc status credentials in the viewer namespace --- .../en/LC_MESSAGES/userspace-api/procfs.po | 3 + .../ja/LC_MESSAGES/userspace-api/procfs.po | 3 + Documentation/userspace-api/procfs.rst | 5 ++ fs/proc/views.c | 13 ++-- tools/tests/procfs_raw_probe.c | 29 ++++++-- tools/tests/procfs_views_test.c | 68 +++++++++++++++++++ 6 files changed, 112 insertions(+), 9 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po index 957e5656..ad13643a 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po @@ -450,3 +450,6 @@ msgstr "" "only before the GID map is published and is irreversible and inherited by" " child scopes. allow cannot reverse denial. Map and setgroups files " "accept zero-length truncation and reject nonzero lengths." + +msgid "``status`` 的四个 ``Uid``、四个 ``Gid`` 和 ``Groups`` 中的补充组按生成视图时 调用者的用户命名空间输出。未映射的 ID 显示为 65534,目标任务的内部凭据保持 全局 ID。成功打开的文件保存已渲染字节,之后切换空间或转交描述符继续读取 原视图,重新打开时使用新调用者的空间。" +msgstr "The four ``Uid`` fields, four ``Gid`` fields and supplementary ``Groups`` in ``status`` use the user namespace of the caller generating the view. Unmapped IDs appear as 65534. The target task retains kernel-global credentials. A successfully opened file retains the rendered bytes across namespace changes or descriptor transfers. Reopening uses the new caller namespace." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po index b8cd4335..b204d9cb 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po @@ -393,3 +393,6 @@ msgstr "" "``CAP_SYS_ADMIN`` が必要です。書き込みはオフセットゼロ、8 バイト未満で、キーワード後に空白を付けられます。deny は GID" " マップ公開前にのみ設定でき、不可逆で子空間に継承されます。allow は禁止を解除できません。マップと setgroups は長さゼロの " "truncate を受け付け、ゼロ以外を拒否します。" + +msgid "``status`` 的四个 ``Uid``、四个 ``Gid`` 和 ``Groups`` 中的补充组按生成视图时 调用者的用户命名空间输出。未映射的 ID 显示为 65534,目标任务的内部凭据保持 全局 ID。成功打开的文件保存已渲染字节,之后切换空间或转交描述符继续读取 原视图,重新打开时使用新调用者的空间。" +msgstr "``status`` の四つの ``Uid``、四つの ``Gid`` と補助 ``Groups`` は、ビューを生成する呼び出し元のユーザー名前空間で表示します。未マップの ID は 65534 となり、対象タスクの内部資格情報はグローバル ID を保持します。正常にオープンしたファイルは描画済みバイト列を保存するため、名前空間の切り替えや記述子の転送後も元のビューを読みます。再オープンでは新しい呼び出し元の空間を使用します。" diff --git a/Documentation/userspace-api/procfs.rst b/Documentation/userspace-api/procfs.rst index e81842b7..6c551638 100644 --- a/Documentation/userspace-api/procfs.rst +++ b/Documentation/userspace-api/procfs.rst @@ -144,6 +144,11 @@ dup 共享已打开的视图,重新打开会生成新视图。快照不采用 用户命名空间映射 ================ +``status`` 的四个 ``Uid``、四个 ``Gid`` 和 ``Groups`` 中的补充组按生成视图时 +调用者的用户命名空间输出。未映射的 ID 显示为 65534,目标任务的内部凭据保持 +全局 ID。成功打开的文件保存已渲染字节,之后切换空间或转交描述符继续读取 +原视图,重新打开时使用新调用者的空间。 + ``/proc/PID/uid_map``、``gid_map`` 和 ``setgroups`` 也适用于线程路径。 映射文件模式为 0644,setgroups 为 0600;按目标任务的有效 UID/GID 确定所有者, 不可 dump 的任务使用现有 root 所有权规则。路径访问遵守 proc 可见性、普通 DAC diff --git a/fs/proc/views.c b/fs/proc/views.c index 3bfbe210..a1dcefe5 100644 --- a/fs/proc/views.c +++ b/fs/proc/views.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -208,8 +209,10 @@ static void virtual_totals(struct task *t, struct memory_totals *out) } out->rss = address_space_user_resident_kib(&mm->as) * 1024; } -/** @brief Render actual credential, signal, affinity and memory state. - * @param t Borrowed live task. @param s Required output, execution-owned. +/** @brief Render status with IDs mapped through the current viewer namespace. + * @param t Borrowed live task with kernel-global credentials. + * @param s Required output, execution-owned. Open views retain rendered bytes. + * Mapping is allocation-free and leaves all target credentials unchanged. */ static void status(struct task *t, struct text_stream *s) { @@ -224,15 +227,17 @@ static void status(struct task *t, struct text_stream *s) field(s, "\nTgid:\t", sched_task_tgid(t), "\n"); field(s, "Pid:\t", t->pid, "\n"); field(s, "PPid:\t", t->parent_pid, "\n"); + const struct task *viewer = sched_current_task(); + const struct user_namespace *user_ns = viewer ? viewer->user_ns : NULL; uint32_t ids[] = {t->uid, t->euid, t->suid, t->fsuid, t->gid, t->egid, t->sgid, t->fsgid}; for (unsigned i = 0; i < 8; ++i) { text_string(s, i == 0 ? "Uid:\t" : i == 4 ? "\nGid:\t" : "\t"); - text_unsigned(s, ids[i]); + text_unsigned(s, user_namespace_id_from_kernel_munged(user_ns, i >= 4, ids[i])); } text_string(s, "\nGroups:\t"); if (t->groups) for (uint32_t i = 0; i < t->groups->count; ++i) { - text_unsigned(s, t->groups->ids[i]); + text_unsigned(s, user_namespace_id_from_kernel_munged(user_ns, true, t->groups->ids[i])); text_string(s, " "); } text_string(s, "\nUmask:\t"); diff --git a/tools/tests/procfs_raw_probe.c b/tools/tests/procfs_raw_probe.c index 0fb154ed..f0f61944 100644 --- a/tools/tests/procfs_raw_probe.c +++ b/tools/tests/procfs_raw_probe.c @@ -6,8 +6,11 @@ #include #include #include +#include -static char contents[65536]; +static char initial_contents[65536]; +static char *contents = initial_contents; +static size_t contents_capacity = sizeof(initial_contents); static long output = 1; static unsigned char thread_stack[32768] __attribute__((aligned(16))); static int thread_complete; @@ -135,8 +138,10 @@ static int udp_has_data(const char *text) return 0; } -/** @brief Open, read in seven-byte pieces, rewind and close an actual proc file. - * @param path Intrinsic path. @return Bytes in contents, including binary data. +/** @brief Read a complete proc file in seven-byte pieces, then rewind and close. + * Anonymous buffers grow for host-wide tables and replace prior buffers only + * after successful allocation. @param path Intrinsic path. + * @return Bytes retained in contents, including binary data. */ static size_t read_file(const char *path) { @@ -144,7 +149,21 @@ static size_t read_file(const char *path) require(fd >= 0, path); size_t used = 0; for (;;) { - require(used + 8 < sizeof(contents), "snapshot capacity"); + if (contents_capacity - used < 8) { + require(contents_capacity <= SIZE_MAX / 2, "snapshot capacity overflow"); + size_t capacity = contents_capacity * 2; + long address = call(__NR_mmap, 0, (long)capacity, LINUX_PROT_READ | LINUX_PROT_WRITE, + LINUX_MAP_PRIVATE | LINUX_MAP_ANONYMOUS, -1, 0); + require(address >= 0, "snapshot allocation"); + char *next = (char *)address; + for (size_t i = 0; i < used; ++i) + next[i] = contents[i]; + if (contents != initial_contents) + require(call(__NR_munmap, (long)contents, (long)contents_capacity, + 0, 0, 0, 0) == 0, "snapshot release"); + contents = next; + contents_capacity = capacity; + } long n = call(__NR_read, fd, (long)(contents + used), 7, 0, 0, 0); require(n >= 0 && n <= 7, path); if (!n) @@ -268,7 +287,7 @@ __attribute__((used, noreturn)) static void probe_main(void) require(contains(contents, "Threads:"), "thread-self status"); long tasks = call(__NR_open, (long)"/proc/self/task", 0, 0, 0, 0, 0); require(tasks >= 0, "task directory"); - require(call(__NR_getdents64, tasks, (long)contents, sizeof(contents), 0, 0, 0) > 0, + require(call(__NR_getdents64, tasks, (long)contents, (long)contents_capacity, 0, 0, 0) > 0, "task entries"); call(__NR_close, tasks, 0, 0, 0, 0, 0); size_t bytes = read_file("/proc/self/auxv"); diff --git a/tools/tests/procfs_views_test.c b/tools/tests/procfs_views_test.c index 06491e35..062356dc 100644 --- a/tools/tests/procfs_views_test.c +++ b/tools/tests/procfs_views_test.c @@ -14,6 +14,73 @@ static size_t read_all(const char *path) return n; } +/** @brief Check status IDs against the viewer namespace and captured open bytes. */ +static void namespace_status(void) +{ + unsigned before = proc_allocations; + struct task creator = {.cap_effective = UINT64_MAX}; + struct user_namespace *user_ns; + struct user_namespace_file map; + uint32_t written; + const char uid_map[] = "0 1000 8\n", gid_map[] = "40 100 8\n"; + assert(!current.user_ns); + assert(!user_namespace_create(&creator, &user_ns)); + assert(!user_namespace_file_open(user_ns, &creator, USER_NAMESPACE_UID_MAP, true, &map)); + assert(!user_namespace_file_write(&map, &creator, 0, uid_map, sizeof(uid_map) - 1, &written)); + user_namespace_file_close(&map); + assert(!user_namespace_file_open(user_ns, &creator, USER_NAMESPACE_GID_MAP, true, &map)); + assert(!user_namespace_file_write(&map, &creator, 0, gid_map, sizeof(gid_map) - 1, &written)); + user_namespace_file_close(&map); + + struct task *target = &extra_tasks[0]; + *target = (struct task){.pid = 100, .name = "namespace-status", + .uid = 1000, .euid = 1001, .suid = 1002, .fsuid = 9000, + .gid = 100, .egid = 101, .sgid = 102, .fsgid = 900}; + const uint32_t groups[] = {100, 103, 900}; + assert(!task_groups_set(target, groups, 3)); + visible_tasks = 2; + current.user_ns = user_ns; + read_all("/proc/100/status"); + assert(strstr(output, "Uid:\t0\t1\t2\t65534\n")); + assert(strstr(output, "Gid:\t40\t41\t42\t65534\n")); + assert(strstr(output, "Groups:\t40 43 65534 \n")); + read_all("/proc/100/task/100/status"); + assert(strstr(output, "Uid:\t0\t1\t2\t65534\n")); + + struct vfs_mount *mount = NULL; + struct vfs_namespace ns = {0}; + struct vfs_path root = {0}, path = {0}; + struct vfs_open_file *file = NULL; + assert(!proc_create_vfs_mount(&mount)); + assert(!vfs_namespace_init(&ns, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns, &root)); + assert(!vfs_path_lookup(&ns, &root, &root, "100/status", 0, &path)); + assert(!vfs_file_open(&path, 0, &file)); + current.user_ns = NULL; + user_namespace_put(user_ns); + uint32_t got; + assert(!vfs_file_read(file, 0, sliced, sizeof(sliced) - 1, &got)); + sliced[got] = 0; + assert(strstr(sliced, "Uid:\t0\t1\t2\t65534\n")); + assert(strstr(sliced, "Gid:\t40\t41\t42\t65534\n")); + assert(strstr(sliced, "Groups:\t40 43 65534 \n")); + read_all("/proc/100/status"); + assert(strstr(output, "Uid:\t1000\t1001\t1002\t9000\n")); + assert(strstr(output, "Gid:\t100\t101\t102\t900\n")); + assert(strstr(output, "Groups:\t100 103 900 \n")); + assert(target->uid == 1000 && target->fsuid == 9000); + assert(target->gid == 100 && target->fsgid == 900 && target->groups->ids[0] == 100); + vfs_file_close(file); + vfs_path_put(&path); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns)); + sched_task_identity_detach(target); + task_groups_release(target); + visible_tasks = 1; + assert(proc_allocations == before); +} + static void thread_paths(void) { extra_tasks[0] = (struct task){.pid = 100, .tgid = 42, .name = "worker", .cpu_ticks = 77}; @@ -290,6 +357,7 @@ static void long_snapshots(void) int main(void) { + namespace_status(); thread_paths(); thread_directory_links(); io_views(); From f315c93f4b3ea33012a49074ad4b592738284bb2 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 01:16:34 +0800 Subject: [PATCH 63/97] feat(userns): support clone and unshare namespace creation --- .../en/LC_MESSAGES/userspace-api/abi.po | 23 +-- .../en/LC_MESSAGES/userspace-api/procfs.po | 15 +- .../ja/LC_MESSAGES/userspace-api/abi.po | 23 +-- .../ja/LC_MESSAGES/userspace-api/procfs.po | 13 +- Documentation/userspace-api/abi.rst | 20 ++- Documentation/userspace-api/procfs.rst | 4 +- include/reliefnt/user_namespace.h | 29 ++++ kernel/sched/Kbuild | 2 +- kernel/sched/clone.c | 25 ++-- kernel/sched/user_namespace_task.c | 64 +++++++++ kernel/syscall/process/clone.c | 10 +- tools/tests/clone3_abi_test.c | 34 ++++- tools/tests/modules/scheduler.h | 1 + tools/tests/mount_namespace_task_test.c | 132 ++++++++++++++++++ 14 files changed, 336 insertions(+), 59 deletions(-) create mode 100644 kernel/sched/user_namespace_task.c diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index ea27b2e6..db9b9f40 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -72,15 +72,8 @@ msgstr "" "including unknown upper bits in the 64-bit argument, return ``EINVAL`` " "without applying any part of the request." -msgid "" -"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` " -"同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 " -"``EPERM``。" -msgstr "" -"With ``CLONE_NEWNS``, ``clone()`` and ``clone3()`` copy the mount tree " -"only for the child. Combining it with ``CLONE_FS`` returns ``EINVAL``. " -"Creating a mount namespace with any of these calls requires effective " -"``CAP_SYS_ADMIN``; without it the call returns ``EPERM``." +msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` 同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 初始用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。" +msgstr "With ``CLONE_NEWNS``, ``clone()`` and ``clone3()`` copy the mount tree only for the child. Combining it with ``CLONE_FS`` returns ``EINVAL``. Creating a mount namespace with any of these calls requires effective ``CAP_SYS_ADMIN`` in the initial user namespace. Missing authority returns ``EPERM``." msgid "" "新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | " @@ -404,3 +397,15 @@ msgstr "On success, ``statx()`` reports support for ``STATX_ATTR_MOUNT_ROOT`` in msgid "实际路径有挂载 ID 时,``statx()`` 在 ``stx_mask`` 中设置 ``STATX_MNT_ID``, 并在 ``stx_mnt_id`` 中返回与 ``/proc/self/mountinfo`` 一致的 ID,即使请求掩码 未指定该位。同一 inode 经不同挂载访问时可得到不同 ID。只有合成元数据、没有 实际挂载路径的对象不报告 ID。不支持 ``STATX_MNT_ID_UNIQUE``,不会将旧式 ID 标记为唯一 ID。输出页争用后重试时沿用同一份已完成的 inode 元数据、ID 和属性。" msgstr "If the actual path has a mount ID, ``statx()`` sets ``STATX_MNT_ID`` in ``stx_mask`` and returns the ID matching ``/proc/self/mountinfo`` in ``stx_mnt_id``, even if the request mask omits the bit. The same inode can have different IDs when accessed through different mounts. Objects with only synthetic metadata and no actual mount path do not report an ID. ``STATX_MNT_ID_UNIQUE`` is unsupported; legacy IDs are not marked as unique. A retry after output-page contention uses the same completed inode metadata, ID and attributes." + +msgid "创建用户命名空间" +msgstr "Creating user namespaces" + +msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUSER`` 为子任务建立独立用户空间, 不能与 ``CLONE_FS`` 或 ``CLONE_THREAD`` 组合。``unshare(CLONE_NEWUSER)`` 在当前任务建立用户空间并隐含取消文件系统状态共享;允许同时指定 ``CLONE_FS`` 或 ``CLONE_THREAD``,活动多线程组返回 ``EINVAL``。" +msgstr "``CLONE_NEWUSER`` in ``clone()`` and ``clone3()`` creates a separate user namespace for the child. Combining it with ``CLONE_FS`` or ``CLONE_THREAD`` returns ``EINVAL``. ``unshare(CLONE_NEWUSER)`` creates a user namespace for the caller and implicitly separates filesystem state. Explicit ``CLONE_FS`` or ``CLONE_THREAD`` is accepted. A live multithreaded group returns ``EINVAL``." + +msgid "创建者的有效 UID 和 GID 必须在其当前用户空间有映射,真实 root 必须等于当前 挂载树的根,否则返回 ``EPERM``。最多嵌套 32 层,超过时返回 ``ENOSPC``。 新空间初始 UID/GID 映射为空,通过 :doc:`procfs` 的映射文件建立映射。" +msgstr "The creator effective UID and GID must be mapped in its current user namespace, and its actual root must equal the mount tree root. Otherwise creation returns ``EPERM``. Nesting is limited to 32 levels, with ``ENOSPC`` beyond that limit. New UID/GID maps are empty and can be populated through the mapping files described in :doc:`procfs`." + +msgid "内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding 能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 用户空间与挂载树组合创建仍要求创建前具备初始用户空间的 ``CAP_SYS_ADMIN``。" +msgstr "Internal UID/GID values, supplementary groups and no_new_privs are retained. In the new namespace, permitted, effective and bounding sets contain every supported capability. Inheritable, ambient and securebits are cleared. Capability checks use namespace scope, and new authority applies to the namespace and its descendants. Unshare preserves dumpability and the parent-death signal. Preparation failure preserves credentials, filesystem sharing and process publication state. Combined user and mount namespace creation still requires initial-user-namespace ``CAP_SYS_ADMIN`` before creation." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po index ad13643a..f566efdd 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po @@ -384,19 +384,8 @@ msgstr "Bind and cloned mounts share the original instance policy. Separately cr msgid "用户命名空间映射" msgstr "User namespace mappings" -msgid "" -"``/proc/PID/uid_map``、``gid_map`` 和 ``setgroups`` 也适用于线程路径。 映射文件模式为 " -"0644,setgroups 为 0600;按目标任务的有效 UID/GID 确定所有者, 不可 dump 的任务使用现有 root " -"所有权规则。路径访问遵守 proc 可见性、普通 DAC 和挂载只读策略。当前 ``CLONE_NEWUSER`` 返回 " -"``EINVAL``;这些控制文件先提供 内核已建立空间的映射与策略接口。" -msgstr "" -"``/proc/PID/uid_map``, ``gid_map`` and ``setgroups`` also apply to thread" -" paths. Map files use mode 0644 and setgroups uses 0600. Ownership " -"follows the target effective UID/GID, with existing root ownership rules " -"for nondumpable tasks. Path access follows proc visibility, ordinary DAC " -"and read-only mount policy. ``CLONE_NEWUSER`` currently returns " -"``EINVAL``. These controls provide maps and policy for scopes already " -"established inside the kernel." +msgid "``/proc/PID/uid_map``、``gid_map`` 和 ``setgroups`` 也适用于线程路径。 映射文件模式为 0644,setgroups 为 0600;按目标任务的有效 UID/GID 确定所有者, 不可 dump 的任务使用现有 root 所有权规则。路径访问遵守 proc 可见性、普通 DAC 和挂载只读策略。``clone()``、``clone3()`` 和 ``unshare()`` 创建的用户空间初始 映射为空,建立映射前对外读取未映射身份为 65534。创建要求见 :doc:`abi`。" +msgstr "``/proc/PID/uid_map``, ``gid_map`` and ``setgroups`` also apply to thread paths. Map files use mode 0644 and setgroups uses 0600. Ownership follows the target effective UID/GID, with existing root ownership rules for nondumpable tasks. Path access follows proc visibility, ordinary DAC and read-only mount policy. User namespaces created by ``clone()``, ``clone3()`` and ``unshare()`` start with empty maps. Unmapped identities read as 65534 until mappings are established. Creation requirements are described in :doc:`abi`." msgid "" "打开时保留目标和打开者的用户空间及打开者有效 UID/GID、能力集合。后续读取和 写入使用所持空间,目标退出或 PID 被复用后仍访问原空间;旧" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 430fd45f..04689ae8 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -65,15 +65,8 @@ msgstr "" "の共有だけを解除し、マウントツリーは複製しません。フラグがゼロなら状態は変わりません。64 " "ビット引数の未知の上位ビットを含む未対応フラグを指定した場合は、要求を部分的に適用することなく ``EINVAL`` を返します。" -msgid "" -"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` " -"同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 " -"``EPERM``。" -msgstr "" -"``clone()`` と ``clone3()`` に ``CLONE_NEWNS`` " -"を指定すると、子タスクに対してのみマウントツリーを複製します。 ``CLONE_FS`` と同時に指定すると ``EINVAL`` " -"を返します。これらの呼び出しによるマウント名前空間の作成には有効な ``CAP_SYS_ADMIN`` が必要で、なければ ``EPERM`` " -"を返します。" +msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` 同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 初始用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。" +msgstr "``clone()`` と ``clone3()`` の ``CLONE_NEWNS`` は子タスク用にマウントツリーを複製します。``CLONE_FS`` との組み合わせは ``EINVAL`` を返します。これらのマウント名前空間作成操作には初期ユーザー名前空間で有効な ``CAP_SYS_ADMIN`` が必要で、権限が不足すると ``EPERM`` を返します。" msgid "" "新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | " @@ -359,3 +352,15 @@ msgstr "``statx()`` は成功時に ``stx_attributes_mask`` で ``STATX_ATTR_MOU msgid "实际路径有挂载 ID 时,``statx()`` 在 ``stx_mask`` 中设置 ``STATX_MNT_ID``, 并在 ``stx_mnt_id`` 中返回与 ``/proc/self/mountinfo`` 一致的 ID,即使请求掩码 未指定该位。同一 inode 经不同挂载访问时可得到不同 ID。只有合成元数据、没有 实际挂载路径的对象不报告 ID。不支持 ``STATX_MNT_ID_UNIQUE``,不会将旧式 ID 标记为唯一 ID。输出页争用后重试时沿用同一份已完成的 inode 元数据、ID 和属性。" msgstr "実際のパスにマウント ID がある場合、``statx()`` は要求マスクに該当ビットがなくても ``stx_mask`` に ``STATX_MNT_ID`` を設定し、``stx_mnt_id`` に ``/proc/self/mountinfo`` と一致する ID を返す。同じ inode でも異なるマウント経由では別の ID が返り得る。合成メタデータしかなく実際のマウントパスを持たないオブジェクトは ID を報告しない。``STATX_MNT_ID_UNIQUE`` は未対応であり、従来の ID を一意とはみなさない。出力ページの競合による再試行では、取得済みの inode メタデータ、ID、属性をそのまま使う。" + +msgid "创建用户命名空间" +msgstr "ユーザー名前空間の作成" + +msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUSER`` 为子任务建立独立用户空间, 不能与 ``CLONE_FS`` 或 ``CLONE_THREAD`` 组合。``unshare(CLONE_NEWUSER)`` 在当前任务建立用户空间并隐含取消文件系统状态共享;允许同时指定 ``CLONE_FS`` 或 ``CLONE_THREAD``,活动多线程组返回 ``EINVAL``。" +msgstr "``clone()`` と ``clone3()`` の ``CLONE_NEWUSER`` は子タスク用に独立したユーザー名前空間を作成します。``CLONE_FS`` または ``CLONE_THREAD`` との組み合わせは ``EINVAL`` を返します。``unshare(CLONE_NEWUSER)`` は呼び出し元にユーザー名前空間を作成し、ファイルシステム状態の共有を暗黙に解除します。``CLONE_FS`` または ``CLONE_THREAD`` の明示指定も受け付けます。活動中のマルチスレッドグループでは ``EINVAL`` を返します。" + +msgid "创建者的有效 UID 和 GID 必须在其当前用户空间有映射,真实 root 必须等于当前 挂载树的根,否则返回 ``EPERM``。最多嵌套 32 层,超过时返回 ``ENOSPC``。 新空间初始 UID/GID 映射为空,通过 :doc:`procfs` 的映射文件建立映射。" +msgstr "作成者の実効 UID と GID は現在のユーザー名前空間にマッピングされ、実際の root はマウントツリーのルートと一致する必要があります。条件を満たさない場合は ``EPERM`` を返します。ネストは 32 階層までで、超過すると ``ENOSPC`` を返します。新しい UID/GID マップは空で、:doc:`procfs` のマッピングファイルで設定できます。" + +msgid "内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding 能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 用户空间与挂载树组合创建仍要求创建前具备初始用户空间的 ``CAP_SYS_ADMIN``。" +msgstr "内部 UID/GID、補助グループ、no_new_privs は保持されます。新しい名前空間の permitted、effective、bounding 集合には対応するすべての能力が含まれ、inheritable、ambient、securebits はクリアされます。能力は名前空間のスコープで検査され、新しい権限はその空間と子孫に適用されます。unshare は dumpability と親死亡シグナルを保持します。準備失敗時は資格情報、ファイルシステム共有、プロセス公開状態を保持します。ユーザーとマウント名前空間の同時作成には、作成前の初期ユーザー名前空間での ``CAP_SYS_ADMIN`` が引き続き必要です。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po index b204d9cb..fa557b0e 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po @@ -340,17 +340,8 @@ msgstr "bind マウントとクローンされたマウントは元のインス msgid "用户命名空间映射" msgstr "ユーザー名前空間のマッピング" -msgid "" -"``/proc/PID/uid_map``、``gid_map`` 和 ``setgroups`` 也适用于线程路径。 映射文件模式为 " -"0644,setgroups 为 0600;按目标任务的有效 UID/GID 确定所有者, 不可 dump 的任务使用现有 root " -"所有权规则。路径访问遵守 proc 可见性、普通 DAC 和挂载只读策略。当前 ``CLONE_NEWUSER`` 返回 " -"``EINVAL``;这些控制文件先提供 内核已建立空间的映射与策略接口。" -msgstr "" -"``/proc/PID/uid_map``、``gid_map``、``setgroups`` はスレッドのパスにも適用します。マップのモードは " -"0644、setgroups は 0600 です。所有者は対象タスクの実効 UID/GID に従い、dump 不可のタスクには既存の root " -"所有権規則を使用します。パスへのアクセスは proc の可視性、通常の DAC、読み取り専用マウント方針に従います。現在 " -"``CLONE_NEWUSER`` は ``EINVAL`` " -"を返します。これらの制御ファイルはカーネル内部で作成済みの空間にマップと方針を提供します。" +msgid "``/proc/PID/uid_map``、``gid_map`` 和 ``setgroups`` 也适用于线程路径。 映射文件模式为 0644,setgroups 为 0600;按目标任务的有效 UID/GID 确定所有者, 不可 dump 的任务使用现有 root 所有权规则。路径访问遵守 proc 可见性、普通 DAC 和挂载只读策略。``clone()``、``clone3()`` 和 ``unshare()`` 创建的用户空间初始 映射为空,建立映射前对外读取未映射身份为 65534。创建要求见 :doc:`abi`。" +msgstr "``/proc/PID/uid_map``、``gid_map``、``setgroups`` はスレッドパスにも適用されます。マッピングファイルのモードは 0644、setgroups は 0600 です。所有者は対象タスクの実効 UID/GID に従い、ダンプ不可タスクには既存の root 所有規則を使います。パスアクセスは proc の可視性、通常の DAC、読み取り専用マウント方針に従います。``clone()``、``clone3()``、``unshare()`` が作成するユーザー名前空間のマップは初期状態で空です。マッピング設定まで未マッピング ID は 65534 として読み出されます。作成要件は :doc:`abi` を参照してください。" msgid "" "打开时保留目标和打开者的用户空间及打开者有效 UID/GID、能力集合。后续读取和 写入使用所持空间,目标退出或 PID 被复用后仍访问原空间;旧" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 90f02234..c754ad01 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -60,11 +60,29 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 ``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` 同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 -有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。 +初始用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。 新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | MS_PRIVATE`` 使子树停止传播。 +创建用户命名空间 +================ + +``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUSER`` 为子任务建立独立用户空间, +不能与 ``CLONE_FS`` 或 ``CLONE_THREAD`` 组合。``unshare(CLONE_NEWUSER)`` +在当前任务建立用户空间并隐含取消文件系统状态共享;允许同时指定 ``CLONE_FS`` +或 ``CLONE_THREAD``,活动多线程组返回 ``EINVAL``。 + +创建者的有效 UID 和 GID 必须在其当前用户空间有映射,真实 root 必须等于当前 +挂载树的根,否则返回 ``EPERM``。最多嵌套 32 层,超过时返回 ``ENOSPC``。 +新空间初始 UID/GID 映射为空,通过 :doc:`procfs` 的映射文件建立映射。 + +内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 +bounding 能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 +能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability +与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 +用户空间与挂载树组合创建仍要求创建前具备初始用户空间的 ``CAP_SYS_ADMIN``。 + 加入挂载命名空间 ================ diff --git a/Documentation/userspace-api/procfs.rst b/Documentation/userspace-api/procfs.rst index 6c551638..19f16f53 100644 --- a/Documentation/userspace-api/procfs.rst +++ b/Documentation/userspace-api/procfs.rst @@ -152,8 +152,8 @@ dup 共享已打开的视图,重新打开会生成新视图。快照不采用 ``/proc/PID/uid_map``、``gid_map`` 和 ``setgroups`` 也适用于线程路径。 映射文件模式为 0644,setgroups 为 0600;按目标任务的有效 UID/GID 确定所有者, 不可 dump 的任务使用现有 root 所有权规则。路径访问遵守 proc 可见性、普通 DAC -和挂载只读策略。当前 ``CLONE_NEWUSER`` 返回 ``EINVAL``;这些控制文件先提供 -内核已建立空间的映射与策略接口。 +和挂载只读策略。``clone()``、``clone3()`` 和 ``unshare()`` 创建的用户空间初始 +映射为空,建立映射前对外读取未映射身份为 65534。创建要求见 :doc:`abi`。 打开时保留目标和打开者的用户空间及打开者有效 UID/GID、能力集合。后续读取和 写入使用所持空间,目标退出或 PID 被复用后仍访问原空间;旧 inode 不能重新打开 diff --git a/include/reliefnt/user_namespace.h b/include/reliefnt/user_namespace.h index e59162a1..b2f985c6 100644 --- a/include/reliefnt/user_namespace.h +++ b/include/reliefnt/user_namespace.h @@ -124,6 +124,35 @@ void user_namespace_file_close(struct user_namespace_file *file); */ int user_namespace_create(const struct task *creator, struct user_namespace **out); +/** @brief Prepare a syscall-created scope after mapping and chroot admission. + * @param task Execution-owned creator with retained filesystem paths, required. + * @param out Required empty output receiving one owned namespace reference. + * @return Zero, -EPERM for unmapped effective IDs or a restricted root, or a + * namespace/path allocation error. No task state is changed. May call VFS, + * so the caller must not hold scheduler_lock. + */ +int sched_task_user_namespace_create(const struct task *task, struct user_namespace **out); + +/** @brief Consume a validated scope and reset namespace-local authority. + * @param task Execution-owned caller or unpublished child, required. + * @param ns Owned target reference, NULL for the initial namespace. + * Resets securebits, inheritable and ambient capabilities, and grants all + * supported permitted/effective/bounding capabilities in the target scope. + * Stored IDs, groups and no_new_privs survive. Scope-aware capability gains + * reset dumpability and the parent-death signal before publication. No + * allocation or user access. Releases the task's former namespace reference. + */ +void sched_task_user_namespace_install(struct task *task, struct user_namespace *ns); + +/** @brief Atomically create a user scope and separate the caller's FS state. + * @param task Current execution-owned task, required. + * @param new_mount_namespace Also snapshot the graph after caller authorization. + * @return Zero, -EINVAL for a live thread group, or a preparation error. + * Preparation runs outside scheduler_lock. Failures preserve credentials, + * root/cwd/umask sharing, namespace references and publication state. + */ +int sched_task_user_namespace_unshare(struct task *task, bool new_mount_namespace); + /** @brief Retain an existing namespace or the permanent initial scope. * @param ns Borrowed live namespace, nullable for the initial namespace. * @return The same pointer with one additional owned reference when non-NULL. diff --git a/kernel/sched/Kbuild b/kernel/sched/Kbuild index ee908b03..8260b73d 100644 --- a/kernel/sched/Kbuild +++ b/kernel/sched/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := accounting.o clone.o core.o exec.o fair.o fs.o identity.o kthread.o lookup.o oom.o rseq.o session.o signal.o tables.o task.o timers.o user_namespace.o wait.o +obj-y := accounting.o clone.o core.o exec.o fair.o fs.o identity.o kthread.o lookup.o oom.o rseq.o session.o signal.o tables.o task.o timers.o user_namespace.o user_namespace_task.o wait.o include $(srctree)/scripts/Makefile.module diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index 86b3e4ea..95b33016 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -136,23 +136,22 @@ void sched_vfork_child_done(struct task *child) int sched_clone_validate_flags(uint64_t flags,uint64_t tls) { const uint64_t supported = CSIGNAL | CLONE_VM | CLONE_VFORK | CLONE_FS | - CLONE_FILES | CLONE_SIGHAND | CLONE_PARENT | CLONE_THREAD | CLONE_SYSVSEM | CLONE_NEWNS | + CLONE_FILES | CLONE_SIGHAND | CLONE_PARENT | CLONE_THREAD | CLONE_SYSVSEM | CLONE_NEWNS | CLONE_NEWUSER | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED | CLONE_UNTRACED | CLONE_CHILD_SETTID | CLONE_CLEAR_SIGHAND; if ((flags & CLONE_NEWNS) && (flags & CLONE_FS)) return -LINUX_EINVAL; + if ((flags & CLONE_NEWUSER) && (flags & (CLONE_FS | CLONE_THREAD))) return -LINUX_EINVAL; if ((flags & CLONE_CLEAR_SIGHAND) && (flags & CLONE_SIGHAND)) return -22; if ((flags & CLONE_THREAD) && !(flags & CLONE_SIGHAND)) return -22; if ((flags & CLONE_SIGHAND) && !(flags & CLONE_VM)) return -22; - /* Linux without CONFIG_USER_NS rejects this in copy_creds(), before - * any privilege check for the other requested namespaces. */ - if (flags & CLONE_NEWUSER) return -LINUX_EINVAL; if (flags & (CLONE_NEWPID | CLONE_NEWNET)) { /* copy_process() rejects a new PID namespace in the parent's thread * group; copy_namespaces() otherwise checks CAP_SYS_ADMIN before * reaching the unavailable PID/network namespace backend. */ if ((flags & CLONE_NEWPID) && (flags & CLONE_THREAD)) return -LINUX_EINVAL; const struct task *parent = sched_current_task(); - return parent && (task_initial_capabilities(parent) & (1ULL << CAP_SYS_ADMIN)) + return (flags & CLONE_NEWUSER) || + (parent && (task_initial_capabilities(parent) & (1ULL << CAP_SYS_ADMIN))) ? -LINUX_EINVAL : -LINUX_EPERM; } if (flags & ~supported) return -RELIEFOS_ENOSYS; @@ -182,7 +181,9 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) * The child never borrows the parent's retained PID-identity object or pending * syscall lookup names/root/dirfd references or imported vector/transfer state, * including on early allocation failure. - * The child owns its inherited user namespace reference. Rollback releases it. + * CLONE_NEWUSER stages an empty-map scope outside scheduler_lock and gives the + * child full local authority. Other children retain the inherited scope. + * Every rollback releases the prepared or installed user namespace reference. */ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flags, uint64_t stack, uint64_t parent_tid, @@ -207,6 +208,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag uint32_t child_pid; bool files_retained = false; struct task_fs_paths snapshot = {0}; + struct user_namespace *user_ns = NULL; if (!parent || !parent_frame || parent->kind != TASK_KIND_USER || parent->state == TASK_EXITED || !(*sched_task_as(parent)).cr3) { kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); @@ -220,12 +222,14 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag return -LINUX_EAGAIN; } parent->nproc_exceeded = false; - if (flags & CLONE_NEWNS) { + if (flags & (CLONE_NEWNS | CLONE_NEWUSER)) { /* Execution ownership keeps admission and the source stable. VFS can * call into providers on failure, so take no scheduler lock or PID. */ kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); - int rc = sched_task_fs_snapshot(parent, &snapshot); + int rc = flags & CLONE_NEWUSER ? sched_task_user_namespace_create(parent, &user_ns) : 0; + if (!rc && (flags & CLONE_NEWNS)) rc = sched_task_fs_snapshot(parent, &snapshot); if (rc) { + user_namespace_put(user_ns); sched_task_identity_put(identity); return rc; } @@ -244,6 +248,10 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag task_zero(child); *child = *parent; child->user_ns = user_namespace_get(parent->user_ns); + if (user_ns) { + sched_task_user_namespace_install(child, user_ns); + user_ns = NULL; + } /* Borrowed by the shallow copy; only successful publication takes a charge. */ child->cgroup = NULL; /* Forked processes start unset and new threads use their existing leader. */ @@ -621,6 +629,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag fail_prepare: kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_fs_paths_put(&snapshot); + user_namespace_put(user_ns); sched_task_identity_put(identity); return -LINUX_ENOMEM; } diff --git a/kernel/sched/user_namespace_task.c b/kernel/sched/user_namespace_task.c new file mode 100644 index 00000000..d28fd1ce --- /dev/null +++ b/kernel/sched/user_namespace_task.c @@ -0,0 +1,64 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "internal.h" + +/** @copydoc sched_task_user_namespace_create */ +int sched_task_user_namespace_create(const struct task *task, struct user_namespace **out) +{ + if (!out) return -LINUX_EINVAL; + *out = NULL; + if (!task) return -LINUX_EINVAL; + if (user_namespace_id_from_kernel(task->user_ns, false, task->euid) == UINT32_MAX || + user_namespace_id_from_kernel(task->user_ns, true, task->egid) == UINT32_MAX) + return -LINUX_EPERM; + + struct vfs_path root = {0}; + int rc = vfs_namespace_root(sched_task_namespace(task), &root); + if (rc) return rc; + bool chrooted = !vfs_path_equal(&root, &sched_task_paths(task)->root); + vfs_path_put(&root); + if (chrooted) return -LINUX_EPERM; + return user_namespace_create(task, out); +} + +/** @copydoc sched_task_user_namespace_install */ +void sched_task_user_namespace_install(struct task *task, struct user_namespace *ns) +{ + const uint64_t capabilities = (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1; + struct user_namespace *old = task->user_ns; + bool subset = old == ns && !(capabilities & ~task->cap_permitted); + for (const struct user_namespace *scope = ns; scope; scope = scope->parent) { + if (scope->parent == old && scope->owner == task->euid) { + subset = true; + break; + } + } + if (!subset) { + sched_task_mm(task)->nondumpable = true; + task->pdeath_signal = 0; + __atomic_thread_fence(__ATOMIC_RELEASE); + } + task->user_ns = ns; + task->securebits = 0; + task->cap_inheritable = 0; + task->cap_ambient = 0; + task->cap_permitted = capabilities; + task->cap_effective = capabilities; + task->cap_bset = capabilities; + user_namespace_put(old); +} + +/** @copydoc sched_task_user_namespace_unshare */ +int sched_task_user_namespace_unshare(struct task *task, bool new_mount_namespace) +{ + if (thread_group_pending(sched_task_tgid(task), task)) return -LINUX_EINVAL; + struct user_namespace *ns = NULL; + int rc = sched_task_user_namespace_create(task, &ns); + if (rc) return rc; + rc = sched_task_fs_unshare(task, new_mount_namespace); + if (rc) { + user_namespace_put(ns); + return rc; + } + sched_task_user_namespace_install(task, ns); + return 0; +} diff --git a/kernel/syscall/process/clone.c b/kernel/syscall/process/clone.c index d09095b1..1805b8ee 100644 --- a/kernel/syscall/process/clone.c +++ b/kernel/syscall/process/clone.c @@ -135,16 +135,20 @@ int64_t syscall_clone3(const struct trap_frame *frame, uint64_t arguments, uint6 /** @brief Apply the supported Linux unshare flags without touching other tasks. * @param task Current task under execution ownership, outside scheduler_lock. - * @param flags Native 64-bit flag word. CLONE_NEWNS implies CLONE_FS. + * @param flags Native flags. CLONE_NEWNS and CLONE_NEWUSER imply CLONE_FS. * @return Zero (including a no-op for flags=0), or negative Linux errno. * Validate the entire request before preparing or publishing a snapshot. - * Mount graph creation requires CAP_SYS_ADMIN in the initial user namespace. + * User scope creation requires a single-threaded caller, mapped effective IDs + * and an unrestricted root. Mount graphs require initial-scope CAP_SYS_ADMIN. */ int64_t syscall_unshare(struct task *task, uint64_t flags) { - if (!task || (flags & ~(uint64_t)(CLONE_NEWNS | CLONE_FS))) return -LINUX_EINVAL; + uint64_t supported = CLONE_NEWNS | CLONE_NEWUSER | CLONE_FS; + if (flags & CLONE_NEWUSER) supported |= CLONE_THREAD; + if (!task || (flags & ~supported)) return -LINUX_EINVAL; if (!flags) return 0; bool new_namespace = (flags & CLONE_NEWNS) != 0; if (new_namespace && !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; + if (flags & CLONE_NEWUSER) return sched_task_user_namespace_unshare(task, new_namespace); return sched_task_fs_unshare(task, new_namespace); } diff --git a/tools/tests/clone3_abi_test.c b/tools/tests/clone3_abi_test.c index bb5817f4..afa373b7 100644 --- a/tools/tests/clone3_abi_test.c +++ b/tools/tests/clone3_abi_test.c @@ -36,7 +36,7 @@ static long clone3_child_stack(struct clone_args *args, uint64_t *observed) return result; } -/* ReliefNT has no user, PID, or network namespaces. Check both clone entry +/* ReliefNT has no PID or network namespaces. Check both clone entry * points because legacy clone passes the low-byte exit signal in flags. */ static int clone_unavailable_namespaces(void) { @@ -46,7 +46,8 @@ static int clone_unavailable_namespaces(void) uint64_t effective = caps[0].effective | ((uint64_t)caps[1].effective << 32); int privileged_error = effective & (1ULL << CAP_SYS_ADMIN) ? EINVAL : EPERM; const struct { uint64_t flags; int error; } cases[] = { - {CLONE_NEWUSER, EINVAL}, + {CLONE_NEWUSER | CLONE_FS, EINVAL}, + {CLONE_NEWUSER | CLONE_VM | CLONE_SIGHAND | CLONE_THREAD, EINVAL}, {CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET, EINVAL}, {CLONE_NEWPID, privileged_error}, {CLONE_NEWPID | CLONE_NEWNET, privileged_error}, @@ -67,10 +68,39 @@ static int clone_unavailable_namespaces(void) return 0; } +/** @brief Check empty user mappings and child-local capability initialization. */ +static int clone_user_namespaces(void) +{ + uid_t uid = getuid(), euid = geteuid(); + gid_t gid = getgid(), egid = getegid(); + for (unsigned versioned = 0; versioned < 2; ++versioned) { + struct clone_args args = {.flags = CLONE_NEWUSER, .exit_signal = SIGCHLD}; + long child = versioned ? syscall(SYS_clone3, &args, sizeof(args)) : + syscall(SYS_clone, CLONE_NEWUSER | SIGCHLD, 0UL, 0UL, 0UL, 0UL); + CHECK(child >= 0); + if (!child) { + struct __user_cap_header_struct header = {.version = _LINUX_CAPABILITY_VERSION_3}; + struct __user_cap_data_struct caps[_LINUX_CAPABILITY_U32S_3] = {0}; + if (getuid() != 65534 || geteuid() != 65534 || + getgid() != 65534 || getegid() != 65534 || + syscall(SYS_capget, &header, caps)) _exit(1); + uint64_t effective = caps[0].effective | ((uint64_t)caps[1].effective << 32); + uint64_t permitted = caps[0].permitted | ((uint64_t)caps[1].permitted << 32); + _exit(!(effective & (1ULL << CAP_SYS_ADMIN)) || permitted != effective || + caps[0].inheritable || caps[1].inheritable); + } + int status; + CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && !WEXITSTATUS(status)); + CHECK(getuid() == uid && geteuid() == euid && getgid() == gid && getegid() == egid); + } + return 0; +} + static int thread_clone3(void) { _Static_assert(sizeof(struct clone_args) == 88, "Linux clone_args size"); if (clone_unavailable_namespaces()) return 1; + if (clone_user_namespaces()) return 1; struct { struct clone_args args; uint64_t tail; } input = {0}; struct clone_args *args = &input.args; CHECK(syscall(SYS_clone3, NULL, 4097) == -1 && errno == E2BIG); diff --git a/tools/tests/modules/scheduler.h b/tools/tests/modules/scheduler.h index 7b757041..67a1a5d6 100644 --- a/tools/tests/modules/scheduler.h +++ b/tools/tests/modules/scheduler.h @@ -26,6 +26,7 @@ static void fixture_exec_other_exit(uint32_t pid, uint64_t code); #include "../../../kernel/sched/fs.c" #include "../../../kernel/sched/identity.c" #include "../../../kernel/sched/user_namespace.c" +#include "../../../kernel/sched/user_namespace_task.c" #include "../../../kernel/sched/tables.c" #include "../../../kernel/sched/lookup.c" #include "../../../kernel/sched/session.c" diff --git a/tools/tests/mount_namespace_task_test.c b/tools/tests/mount_namespace_task_test.c index 7f3a0e5e..8281e803 100644 --- a/tools/tests/mount_namespace_task_test.c +++ b/tools/tests/mount_namespace_task_test.c @@ -28,12 +28,17 @@ int task_fd_descriptor_flags(struct task *task, int fd) } static int mount_budget = -1; +static int user_namespace_budget = -1; static unsigned mount_allocations, charges; static const struct task *unpublished_child; /** @brief Fail the second snapshot attachment, after staging the first one. */ bool namespace_heap_admit(uint64_t size) { + if (size == sizeof(struct user_namespace) && user_namespace_budget >= 0) { + assert(!scheduler_lock.state); + return user_namespace_budget-- > 0; + } if (size != sizeof(struct vfs_mount) || mount_budget < 0) return true; assert(!scheduler_lock.state && unpublished_child && !unpublished_child->pid); ++mount_allocations; @@ -212,6 +217,129 @@ static void check_setns(struct task *task) puts("PASS mount namespace FD admission, covered root and lifetime"); } +/** @brief Publish one real proc-style namespace mapping or setgroups policy. */ +static void write_user_control(struct task *writer, struct user_namespace *target, + enum user_namespace_file_kind kind, const char *value) +{ + struct user_namespace_file file; + uint32_t written; + assert(!user_namespace_file_open(target, writer, kind, true, &file)); + assert(!user_namespace_file_write(&file, writer, 0, value, strlen(value), &written)); + assert(written == strlen(value)); + user_namespace_file_close(&file); +} + +/** @brief Check full local authority without changing stored global identities. */ +static void assert_user_scope(const struct task *task, const struct user_namespace *parent) +{ + const uint64_t capabilities = (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1; + assert(task->user_ns && task->user_ns->parent == parent && task->user_ns->owner == 1000); + assert(task->uid == 1000 && task->euid == 1000 && task->suid == 1000 && task->fsuid == 1000); + assert(task->gid == 100 && task->egid == 100 && task->sgid == 100 && task->fsgid == 100); + assert(task->cap_effective == capabilities && task->cap_permitted == capabilities); + assert(task->cap_bset == capabilities && !task->cap_inheritable && !task->cap_ambient); + assert(!task->securebits && !task_initial_capabilities(task)); + assert(task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN)); + assert(!task_ns_capable(task, NULL, CAP_SYS_ADMIN)); + assert(user_namespace_id_from_kernel_munged(task->user_ns, false, 1000) == 65534); +} + +/** @brief Exercise clone, clone3 and unshare user scopes, admission and rollback. */ +static void check_user_namespaces(struct task *parent, struct task *child, + struct clone_operands *user) +{ + assert(!sched_clone_validate_flags(CLONE_NEWUSER, 0)); + parent->uid = parent->euid = parent->suid = parent->fsuid = 1000; + parent->gid = parent->egid = parent->sgid = parent->fsgid = 100; + parent->cap_effective = 0; + parent->cap_permitted = parent->cap_inheritable = parent->cap_bset = parent->cap_ambient = 4; + parent->securebits = 0xff; + parent->pdeath_signal = 10; + sched_task_mm(parent)->nondumpable = false; + parent->groups = kernel_malloc(sizeof(*parent->groups) + sizeof(uint32_t)); + assert(parent->groups); + *parent->groups = (struct task_groups){.references = 1, .count = 1}; + parent->groups->ids[0] = 200; + struct vfs_namespace *mount_ns = sched_task_namespace(parent); + struct vfs_path root = sched_task_paths(parent)->root, cwd = sched_task_paths(parent)->cwd; + for (unsigned versioned = 0; versioned < 2; ++versioned) { + assert(clone_namespace(parent, user, versioned, CLONE_NEWUSER | CLONE_FS) == -LINUX_EINVAL); + assert(sched_clone_validate_flags(CLONE_NEWUSER | CLONE_THREAD | CLONE_SIGHAND | CLONE_VM, 0) + == -LINUX_EINVAL); + uint64_t created = proc_created; + unsigned old_charges = charges, pages = live_pages(); + uint64_t flags = CLONE_NEWUSER | CLONE_PARENT_SETTID | CLONE_CHILD_SETTID; + user->parent_tid = user->child_tid = 0x44444444; + user_namespace_budget = 0; + assert(clone_namespace(parent, user, versioned, flags) == -LINUX_ENOMEM); + user_namespace_budget = -1; + assert(!child->pid && !child->user_ns && proc_created == created && charges == old_charges); + assert(user->parent_tid == 0x44444444 && user->child_tid == 0x44444444); + shm_physical_budget = 0; + assert(clone_namespace(parent, user, versioned, flags) == -LINUX_ENOMEM); + shm_physical_budget = -1; + assert(!child->pid && !child->user_ns && proc_created == created && charges == old_charges); + assert(user->parent_tid == 0x44444444 && user->child_tid == 0x44444444); + assert(live_pages() == pages && parent->groups->references == 1); + + int64_t pid = clone_namespace(parent, user, versioned, flags); + assert(pid > 0 && child->pid == (uint32_t)pid && user->parent_tid == (uint32_t)pid); + assert_user_scope(child, NULL); + assert(!parent->user_ns && !parent->cap_effective && parent->cap_bset == 4); + assert(parent->securebits == 0xff && parent->pdeath_signal == 10); + assert(!sched_task_mm(parent)->nondumpable && !sched_task_mm(child)->nondumpable); + assert(!child->pdeath_signal && child->groups == parent->groups && parent->groups->references == 2); + assert(sched_task_namespace(child) == mount_ns); + assert(vfs_path_equal(&sched_task_paths(child)->root, &root)); + assert(vfs_path_equal(&sched_task_paths(child)->cwd, &cwd)); + write_user_control(parent, child->user_ns, USER_NAMESPACE_UID_MAP, "0 1000 1\n"); + write_user_control(parent, child->user_ns, USER_NAMESPACE_SETGROUPS, "deny\n"); + write_user_control(parent, child->user_ns, USER_NAMESPACE_GID_MAP, "0 100 1\n"); + assert(user_namespace_id_to_kernel(child->user_ns, false, 0) == 1000); + assert(user_namespace_id_to_kernel(child->user_ns, true, 0) == 100); + retire_child(child); + assert(parent->groups->references == 1 && live_pages() == pages); + } + + /* NEWUSER implies FS separation, but a live thread still prevents unshare. */ + assert(!task_promote_shared(parent, CLONE_FS)); + child->pid = 900; + child->tgid = parent->tgid; + child->state = TASK_READY; + assert(syscall_unshare(parent, CLONE_NEWUSER) == -LINUX_EINVAL); + child->pid = 0; + child->state = TASK_EXITED; + struct task sibling = {.shared_fs = parent->shared_fs}; + ++sibling.shared_fs->references; + user_namespace_budget = 0; + assert(syscall_unshare(parent, CLONE_NEWUSER | CLONE_FS) == -LINUX_ENOMEM); + user_namespace_budget = -1; + assert(!parent->user_ns && parent->shared_fs == sibling.shared_fs); + assert(parent->shared_fs->references == 2 && parent->securebits == 0xff); + assert(parent->pdeath_signal == 10 && !sched_task_mm(parent)->nondumpable); + assert(!syscall_unshare(parent, CLONE_NEWUSER)); + assert_user_scope(parent, NULL); + assert(!parent->shared_fs && sibling.shared_fs->references == 1); + assert(parent->pdeath_signal == 10 && !sched_task_mm(parent)->nondumpable); + assert(sched_task_namespace(parent) == mount_ns && sched_task_namespace(&sibling) == mount_ns); + assert(vfs_path_equal(&parent->fs_paths.root, &root) && vfs_path_equal(&parent->fs_paths.cwd, &cwd)); + struct user_namespace *scope = parent->user_ns; + assert(syscall_unshare(parent, CLONE_NEWUSER) == -LINUX_EPERM); + assert(parent->user_ns == scope && scope->references == 1); + write_user_control(parent, scope, USER_NAMESPACE_UID_MAP, "0 1000 1\n"); + assert(syscall_unshare(parent, CLONE_NEWUSER) == -LINUX_EPERM); + write_user_control(parent, scope, USER_NAMESPACE_SETGROUPS, "deny\n"); + write_user_control(parent, scope, USER_NAMESPACE_GID_MAP, "0 100 1\n"); + assert(!syscall_unshare(parent, CLONE_NEWUSER | CLONE_THREAD)); + assert_user_scope(parent, scope); + assert(scope->references == 1 && parent->user_ns->setgroups_denied); + user_namespace_put(parent->user_ns); + parent->user_ns = NULL; + sched_task_fs_release(&sibling); + task_groups_release(parent); + puts("PASS user namespace clone/clone3/unshare, local capabilities and atomic rollback"); +} + int main(void) { struct sched_task_object parent_object = {0}, child_object = {0}; @@ -319,8 +447,12 @@ int main(void) } parent->user_ns = NULL; user_namespace_put(user_scope); + for (unsigned versioned = 0; versioned < 2; ++versioned) + assert(clone_namespace(parent, user, versioned, CLONE_NEWUSER) == -LINUX_EPERM); + assert(syscall_unshare(parent, CLONE_NEWUSER) == -LINUX_EPERM); check_unshare(parent, child); check_setns(parent); + check_user_namespaces(parent, child, user); sched_task_fs_release(parent); vfs_reclaim_mounts(16); assert(!vfs_namespace_destroy(&ns) && !fs_backend_pins); From f23bb35e8210fb5edc1ff8cfeddd9acb84bb7961 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 01:33:55 +0800 Subject: [PATCH 64/97] feat(userns): add namespace handles and setns joins --- Documentation/core-api/mount-namespaces.rst | 32 ++-- .../LC_MESSAGES/core-api/mount-namespaces.po | 50 ++---- .../en/LC_MESSAGES/userspace-api/abi.po | 51 +++--- .../en/LC_MESSAGES/userspace-api/procfs.po | 9 ++ .../LC_MESSAGES/core-api/mount-namespaces.po | 45 ++---- .../ja/LC_MESSAGES/userspace-api/abi.po | 48 +++--- .../ja/LC_MESSAGES/userspace-api/procfs.po | 9 ++ Documentation/userspace-api/abi.rst | 32 ++-- Documentation/userspace-api/procfs.rst | 8 + fs/nsfs/namespace.c | 152 +++++++++++++++--- fs/proc/procfs.c | 23 +-- include/reliefnt/mount.h | 1 + include/reliefnt/nsfs.h | 39 ++++- include/reliefnt/user_namespace.h | 11 ++ kernel/sched/user_namespace_task.c | 10 ++ kernel/syscall/dispatch.c | 13 +- kernel/syscall/process/setns.c | 13 +- tools/tests/mount_backend_test.c | 26 +-- tools/tests/mount_namespace_task_test.c | 89 ++++++++++ tools/tests/procfs_directories_test.c | 32 ++++ tools/tests/procfs_raw_probe.c | 29 ++-- 21 files changed, 516 insertions(+), 206 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 79ff466b..93129409 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -66,18 +66,33 @@ VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载 因此快照失败不写回 TID、不计入 cgroup,也不发布子任务。快照及其回滚不持有 调度器自旋锁。接口的参数和权限见 :doc:`../userspace-api/abi`。 +``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 +有效 UID/GID 映射、chroot、线程组与分配检查。unshare 同时准备独立的文件系统 +状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 +no_new_privs,并初始化新空间的能力集合及 securebits。组合 ``CLONE_NEWNS`` +创建仍检查初始用户空间中的 ``CAP_SYS_ADMIN``。 + 句柄与切换 ========== -``/proc//ns/mnt`` 是 proc magic link。读取链接或跟随它需要通过与 +``/proc//ns/mnt`` 与 ``/proc//ns/user`` 是 proc magic link。 +读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 -PID 身份,旧链接不会因 PID 复用而指向新进程;每次成功跟随则取得目标当时的挂载图。 +PID 身份,每次成功跟随则取得目标当时的挂载图或用户空间。 + +跟随链接得到分离的 nsfs inode。mount 与 user 空间使用同一单调递增序列,首次 +显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 +返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。 +每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。 -跟随链接得到分离的 nsfs inode,以挂载图锚点的 ID 作为 inode 号,并用 -``mnt:[ID]`` 显示。持有该路径或打开的文件描述会保留挂载图,而不依赖原进程存活。 -``setns()`` 依据文件描述所持的 nsfs 路径选择图,不使用路径文字或重新查找 PID。 -切换时 root 和 cwd 一起替换为目标图当前可见的根,不采用目标进程的 chroot 或 -cwd;已有文件描述符和 umask 不变。准备失败不会部分切换。 +``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 +mount 切换时 root 和 cwd 一起替换为目标图当前可见的根,已有文件描述符和 +umask 保留。准备失败保留原图与路径。 + +user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 +重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 +集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 +空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。 引用释放 ======== @@ -199,6 +214,3 @@ SysV IPC 凭据 身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 用户空间检查。 - -内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 -``EINVAL``。其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 00b9c8bc..b0c286f8 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -140,33 +140,6 @@ msgstr "" msgid "句柄与切换" msgstr "Handles and Switching" -msgid "" -"``/proc//ns/mnt`` 是 proc magic link。读取链接或跟随它需要通过与 ``/proc//fd``" -" 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,旧链接不会因 PID " -"复用而指向新进程;每次成功跟随则取得目标当时的挂载图。" -msgstr "" -"``/proc//ns/mnt`` is a proc magic link. Reading or following it " -"requires the same ``PTRACE_MODE_READ_FSCREDS`` permission check as " -"``/proc//fd``. The link key retains the PID identity, so an old link" -" never resolves to a new process after PID reuse. Each successful follow " -"acquires the target’s current mount graph." - -msgid "" -"跟随链接得到分离的 nsfs inode,以挂载图锚点的 ID 作为 inode 号,并用 ``mnt:[ID]`` " -"显示。持有该路径或打开的文件描述会保留挂载图,而不依赖原进程存活。 ``setns()`` 依据文件描述所持的 nsfs " -"路径选择图,不使用路径文字或重新查找 PID。 切换时 root 和 cwd 一起替换为目标图当前可见的根,不采用目标进程的 chroot 或 " -"cwd;已有文件描述符和 umask 不变。准备失败不会部分切换。" -msgstr "" -"Following the link yields a detached nsfs inode whose inode number is the" -" mount graph anchor ID and whose display name is ``mnt:[ID]``. A held " -"path or open file description retains the graph independently of the " -"original process. ``setns()`` selects the graph from the file " -"description’s nsfs path, not from path text or a new PID lookup. It " -"replaces root and cwd together with the currently visible root of the " -"target graph, not the target process’s chroot or cwd. Existing file " -"descriptors and the umask are unchanged. Preparation failure leaves the " -"caller in the original namespace." - msgid "引用释放" msgstr "Reference release" @@ -320,14 +293,6 @@ msgstr "" "use the same identity translation rules. Existing DAC and set-ID clearing " "rules still apply." -msgid "" -"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 " -"``EINVAL``。其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。" -msgstr "" -"Internal allocation and reference interfaces are available. Userspace " -"``CLONE_NEWUSER`` currently returns ``EINVAL``. Remaining userspace ID " -"boundaries, creation entry points and user-namespace handles await integration." - msgid "socket 凭据" msgstr "Socket credentials" @@ -357,3 +322,18 @@ msgstr "Message queue, semaphore and shared-memory registries, permission checks msgid "``IPC_SET`` 先执行现有对象所有权与资源限制检查,再将输入的 UID/GID 全部 转换为全局 ID。任一输入未映射或为 ``UINT32_MAX`` 时返回 ``EINVAL``,对象的 身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 用户空间检查。" msgstr "``IPC_SET`` first performs the existing object ownership and resource-limit checks, then translates both input UID/GID values into global IDs. An unmapped input or ``UINT32_MAX`` returns ``EINVAL``, preserving the object identities, permissions, capacity and modification time. Success updates the owner and low 0777 permission bits while preserving creator identities and shared-memory lock and deletion flags. Global IPC administration and resource privileges are still checked in the initial user namespace." + +msgid "``/proc//ns/mnt`` 与 ``/proc//ns/user`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图或用户空间。" +msgstr "``/proc//ns/mnt`` and ``/proc//ns/user`` are proc magic links. Reading or following them requires the same ``PTRACE_MODE_READ_FSCREDS`` check as ``/proc//fd``. Link keys retain PID identity. Each successful follow captures the target task current mount graph or user namespace." + +msgid "``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare 同时准备独立的文件系统 状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 no_new_privs,并初始化新空间的能力集合及 securebits。组合 ``CLONE_NEWNS`` 创建仍检查初始用户空间中的 ``CAP_SYS_ADMIN``。" +msgstr "``CLONE_NEWUSER`` creates a user namespace for a clone child or an unshare caller. Effective UID/GID mapping, chroot, thread-group and allocation checks complete before installation. Unshare also prepares independent filesystem state. Any preparation failure rolls back the candidate namespace and paths. Creation preserves global identities, supplementary groups and no_new_privs, and initializes namespace capability sets and securebits. Combined ``CLONE_NEWNS`` creation still checks ``CAP_SYS_ADMIN`` in the initial user namespace." + +msgid "``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 mount 切换时 root 和 cwd 一起替换为目标图当前可见的根,已有文件描述符和 umask 保留。准备失败保留原图与路径。" +msgstr "``setns()`` authenticates the handle using its actual backend, inode and backend pin, then selects the namespace by type. A mount namespace switch sets root and cwd to the target graph visible root and preserves existing FDs and umask. Preparation failure preserves the original graph and paths." + +msgid "user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。" +msgstr "A user namespace switch requires a single thread, exclusive filesystem state and ``CAP_SYS_ADMIN`` in the target namespace, and rejects reentry into the current namespace. Success preserves root, cwd and global identities and reuses namespace installation to reset capability sets and securebits. Increased scoped authority restricts dumpability and clears the parent-death signal. A NULL pointer represents the initial user namespace. Authenticated handle types and the boolean query distinguish that valid identity from an invalid path." + +msgid "跟随链接得到分离的 nsfs inode。mount 与 user 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" +msgstr "Following a link obtains a detached nsfs inode. Mount and user namespaces share one monotonically increasing sequence. The first display or handle creation assigns an inode, and every handle for that namespace shares this identity. Exhausting the 64-bit sequence returns ``EOVERFLOW``. Labels are ``mnt:[inode]`` or ``user:[inode]``. Each typed backend retains its namespace. Final path release reclaims the backend and drops the namespace reference." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index db9b9f40..1510ae4e 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -84,36 +84,6 @@ msgstr "" "Shared mounts can still propagate events; use ``MS_REC | MS_PRIVATE`` to " "stop propagation for a subtree." -msgid "加入挂载命名空间" -msgstr "Joining a Mount Namespace" - -msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 返回 ``EINVAL``。不支持 pidfd、其他种类的命名空间或 nsfs 句柄的 bind mount。" -msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNS)`` accept a ``/proc//ns/mnt`` handle opened as an ordinary read-only FD. The caller needs effective ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` or the call returns ``EPERM``. Invalid or ``O_PATH`` FDs return ``EBADF``. An unsupported type, a non-nsfs FD, or ``CLONE_FS`` state shared with another task returns ``EINVAL``. Pidfds, other namespace types, and bind mounts of nsfs handles are unsupported." - -msgid "" -"切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。参见 " -":doc:`../core-api/mount-namespaces`。" -msgstr "" -"After switching, root and cwd both point to the visible root of the " -"target mount graph. Existing FDs and the umask are preserved. The handle " -"remains usable after the original process exits or changes namespaces. " -"See :doc:`../core-api/mount-namespaces`." - -msgid "" -"nsfs 句柄不是字节流。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 " -"FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 " -"``ESPIPE``。 ``NS_GET_NSTYPE`` 返回 ``CLONE_NEWNS``,``FIONREAD`` 写回零,不支持的 " -"namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" -msgstr "" -"An nsfs handle is not a byte stream. Opening it for writing or with " -"``O_TRUNC`` returns ``EPERM``; ``O_PATH`` ignores these open flags. " -"Scalar, positioned, and vectored reads on an ordinary FD return " -"``EINVAL``; writes return ``EBADF``. ``lseek()`` with a valid ``whence`` " -"returns ``ESPIPE``. ``NS_GET_NSTYPE`` returns ``CLONE_NEWNS``, " -"``FIONREAD`` writes back zero, and unsupported namespace ioctls return " -"``ENOTTY``. An ``O_PATH`` FD supports metadata queries but not read, " -"write, seek, or ioctl operations." - msgid "bind mount" msgstr "Bind Mounts" @@ -409,3 +379,24 @@ msgstr "The creator effective UID and GID must be mapped in its current user nam msgid "内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding 能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 用户空间与挂载树组合创建仍要求创建前具备初始用户空间的 ``CAP_SYS_ADMIN``。" msgstr "Internal UID/GID values, supplementary groups and no_new_privs are retained. In the new namespace, permitted, effective and bounding sets contain every supported capability. Inheritable, ambient and securebits are cleared. Capability checks use namespace scope, and new authority applies to the namespace and its descendants. Unshare preserves dumpability and the parent-death signal. Preparation failure preserves credentials, filesystem sharing and process publication state. Combined user and mount namespace creation still requires initial-user-namespace ``CAP_SYS_ADMIN`` before creation." + +msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` 句柄。调用者需要初始用户空间中有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" +msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNS)`` accept an ordinary read-only ``/proc//ns/mnt`` handle. The caller needs effective ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` in the initial user namespace or receives ``EPERM``. Sharing ``CLONE_FS`` state with another task returns ``EINVAL``." + +msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" +msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUSER)`` accept an ordinary read-only ``/proc//ns/user`` handle. Joining the current user namespace, having another live thread in the group, or sharing filesystem state with another task returns ``EINVAL``. The caller needs ``CAP_SYS_ADMIN`` in the target user namespace or receives ``EPERM``. Ancestors of the current namespace fail this authority check." + +msgid "nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS`` 或 ``CLONE_NEWUSER``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" +msgstr "An nsfs handle provides metadata and ioctls. Opening it for writing or with ``O_TRUNC`` returns ``EPERM``. ``O_PATH`` ignores these open flags. Scalar, positioned and vectored reads on an ordinary FD return ``EINVAL``, writes return ``EBADF``, and ``lseek()`` with a valid ``whence`` returns ``ESPIPE``. ``NS_GET_NSTYPE`` returns ``CLONE_NEWNS`` or ``CLONE_NEWUSER`` according to the handle type. ``FIONREAD`` writes zero. Unsupported namespace ioctls return ``ENOTTY``. An ``O_PATH`` FD supports metadata queries but cannot read, write, seek or issue ioctls." + +msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" +msgstr "After switching, root and cwd both point to the visible root of the target mount graph. Existing FDs and umask are preserved. Handles remain usable after the original process exits or changes namespaces." + +msgid "加入命名空间" +msgstr "Joining namespaces" + +msgid "成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask 保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" +msgstr "A successful user namespace join preserves global UID/GID, supplementary groups, no_new_privs, root, cwd and umask. The permitted, effective and bounding sets contain all supported capabilities. Inheritable, ambient and securebits are cleared. An increase in scoped authority clears the parent-death signal and restricts dumpability. Rejection preserves the original credentials and filesystem state." + +msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount 与 user 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" +msgstr "Invalid or ``O_PATH`` FDs return ``EBADF``. A non-nsfs FD, type mismatch or unsupported type returns ``EINVAL``. Mount and user handles are supported. Pidfds and bind mounts of nsfs handles remain pending. See :doc:`../core-api/mount-namespaces`." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po index f566efdd..1ecc20ea 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po @@ -442,3 +442,12 @@ msgstr "" msgid "``status`` 的四个 ``Uid``、四个 ``Gid`` 和 ``Groups`` 中的补充组按生成视图时 调用者的用户命名空间输出。未映射的 ID 显示为 65534,目标任务的内部凭据保持 全局 ID。成功打开的文件保存已渲染字节,之后切换空间或转交描述符继续读取 原视图,重新打开时使用新调用者的空间。" msgstr "The four ``Uid`` fields, four ``Gid`` fields and supplementary ``Groups`` in ``status`` use the user namespace of the caller generating the view. Unmapped IDs appear as 65534. The target task retains kernel-global credentials. A successfully opened file retains the rendered bytes across namespace changes or descriptor transfers. Reopening uses the new caller namespace." + +msgid "``ns/mnt``、``ns/user``" +msgstr "``ns/mnt``, ``ns/user``" + +msgid "``ns`` 目录枚举 ``mnt`` 和 ``user``。读取或跟随链接须通过现有 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接保留 PID 身份,每次跟随取得目标 当时的空间。nsfs 句柄在原进程退出或切换空间后继续保留原空间,链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。同一空间的句柄共享稳定 inode,不同空间 在共同的 nsfs 设备上使用独立 inode。切换接口见 :doc:`abi`。" +msgstr "The ``ns`` directory lists ``mnt`` and ``user``. Reading or following a link requires the existing ``PTRACE_MODE_READ_FSCREDS`` check. Links retain PID identity and capture the target namespace at each follow. An nsfs handle retains its original namespace after the process exits or changes namespaces. Link labels are ``mnt:[inode]`` or ``user:[inode]``. Handles for the same namespace share a stable inode, while distinct namespaces have distinct inodes on the common nsfs device. See :doc:`abi` for switching." + +msgid "目标任务的挂载与用户命名空间 magic link,跟随时取得保留空间的 nsfs 句柄。" +msgstr "Magic links for the target task mount and user namespaces. Following a link obtains an nsfs handle retaining that namespace." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 8c84c98f..b9b754c1 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -120,28 +120,6 @@ msgstr "" msgid "句柄与切换" msgstr "ハンドルと名前空間の切り替え" -msgid "" -"``/proc//ns/mnt`` 是 proc magic link。读取链接或跟随它需要通过与 ``/proc//fd``" -" 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,旧链接不会因 PID " -"复用而指向新进程;每次成功跟随则取得目标当时的挂载图。" -msgstr "" -"``/proc//ns/mnt`` は proc のマジックリンクです。リンクを読み取る場合もたどる場合も、 " -"``/proc//fd`` と同じ ``PTRACE_MODE_READ_FSCREDS`` の権限チェックが必要です。リンクのキーには" -" PID の識別情報が保持され、PID " -"が再利用されても古いリンクが新しいプロセスを指すことはありません。リンクをたどるたびに、その時点の対象のマウントグラフを取得します。" - -msgid "" -"跟随链接得到分离的 nsfs inode,以挂载图锚点的 ID 作为 inode 号,并用 ``mnt:[ID]`` " -"显示。持有该路径或打开的文件描述会保留挂载图,而不依赖原进程存活。 ``setns()`` 依据文件描述所持的 nsfs " -"路径选择图,不使用路径文字或重新查找 PID。 切换时 root 和 cwd 一起替换为目标图当前可见的根,不采用目标进程的 chroot 或 " -"cwd;已有文件描述符和 umask 不变。准备失败不会部分切换。" -msgstr "" -"リンクをたどると、マウントグラフのアンカー ID を inode 番号に持ち、 ``mnt:[ID]`` と表示される切り離された nsfs " -"inode が得られます。保持中のパスやオープンファイル記述がグラフを保持するため、元のプロセスが終了してもグラフは失われません。 " -"``setns()`` はパスの文字列や PID の再検索ではなく、オープンファイル記述が保持する nsfs " -"のパスからグラフを選びます。切り替え時には root と cwd を対象グラフで現在見えているルートに一緒に置き換え、対象プロセスの chroot" -" や cwd は引き継ぎません。既存のファイル記述子と umask は変わりません。準備に失敗した場合、名前空間は切り替わりません。" - msgid "引用释放" msgstr "参照の解放" @@ -278,14 +256,6 @@ msgstr "" "パス、組み込みデバイス、暗黙の端末に同じ識別情報の変換規則を適用し、" "既存の DAC と set-ID ビットの消去規則も引き続き適用します。" -msgid "" -"内核内部提供空间分配与引用接口。当前用户态 ``CLONE_NEWUSER`` 创建接口返回 " -"``EINVAL``。其余用户态 ID 边界、创建入口和用户空间句柄仍待接入。" -msgstr "" -"カーネル内部の空間割り当てと参照インターフェースを提供します。現在、ユーザー空間の " -"``CLONE_NEWUSER`` は ``EINVAL`` を返します。残りのユーザー空間 ID " -"境界、作成入口、ユーザー名前空間ハンドルの接続は今後の作業です。" - msgid "socket 凭据" msgstr "ソケットの資格情報" @@ -315,3 +285,18 @@ msgstr "メッセージキュー、セマフォ、共有メモリの登録表、 msgid "``IPC_SET`` 先执行现有对象所有权与资源限制检查,再将输入的 UID/GID 全部 转换为全局 ID。任一输入未映射或为 ``UINT32_MAX`` 时返回 ``EINVAL``,对象的 身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 用户空间检查。" msgstr "``IPC_SET`` は既存のオブジェクト所有権とリソース制限を確認してから、入力 UID/GID の両方をグローバル ID に変換します。未マッピングの入力または ``UINT32_MAX`` には ``EINVAL`` を返し、オブジェクトの ID、権限、容量、変更時刻を保持します。成功時は所有者と下位 0777 の権限ビットを更新し、作成者の ID と共有メモリのロックおよび削除フラグを保持します。グローバル IPC 管理とリソース特権は引き続き初期ユーザー名前空間で確認します。" + +msgid "``/proc//ns/mnt`` 与 ``/proc//ns/user`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图或用户空间。" +msgstr "``/proc//ns/mnt`` と ``/proc//ns/user`` は proc magic link です。読み取りと追跡には ``/proc//fd`` と同じ ``PTRACE_MODE_READ_FSCREDS`` 検査が必要です。リンクキーは PID の同一性を保持します。追跡が成功するたびに対象タスクの現在のマウントグラフまたはユーザー名前空間を取得します。" + +msgid "``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare 同时准备独立的文件系统 状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 no_new_privs,并初始化新空间的能力集合及 securebits。组合 ``CLONE_NEWNS`` 创建仍检查初始用户空间中的 ``CAP_SYS_ADMIN``。" +msgstr "``CLONE_NEWUSER`` は clone の子タスクまたは unshare の呼び出し元にユーザー名前空間を作成します。設定前に有効 UID/GID のマッピング、chroot、スレッドグループ、割り当ての検査を完了します。unshare は独立したファイルシステム状態も準備します。準備に失敗した場合は候補の名前空間とパスを解放します。作成時はグローバル ID、補助グループ、no_new_privs を保持し、新しい空間の能力集合と securebits を初期化します。``CLONE_NEWNS`` と組み合わせた作成には引き続き初期ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要です。" + +msgid "``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 mount 切换时 root 和 cwd 一起替换为目标图当前可见的根,已有文件描述符和 umask 保留。准备失败保留原图与路径。" +msgstr "``setns()`` は実際のバックエンド、inode、バックエンド pin でハンドルを認証し、型に応じて対象の名前空間を選びます。mount の切り替えでは root と cwd を対象グラフの可視ルートに設定し、既存の FD と umask を保持します。準備に失敗した場合は元のグラフとパスを保持します。" + +msgid "user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。" +msgstr "user の切り替えには単一スレッド、ファイルシステム状態の独占、対象名前空間の ``CAP_SYS_ADMIN`` が必要で、現在の名前空間への再参加は拒否します。成功時は root、cwd、グローバル ID を保持し、ユーザー名前空間の設定処理を再利用して能力集合と securebits をリセットします。作用域内の権限が増加するとダンプ可能性を制限し、親死亡シグナルを解除します。初期ユーザー名前空間は空ポインタで表し、ハンドル型の認証と真偽値の照会でこの有効な ID と無効なパスを区別します。" + +msgid "跟随链接得到分离的 nsfs inode。mount 与 user 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" +msgstr "リンクをたどると独立した nsfs inode を取得します。mount と user の名前空間は単調増加する共通の採番列を使います。最初の表示またはハンドル作成時に inode を割り当て、同じ名前空間のすべてのハンドルがその ID を共有します。64 ビットの採番列を使い切ると ``EOVERFLOW`` を返します。表示は ``mnt:[inode]`` または ``user:[inode]`` です。各バックエンドは型に応じた名前空間の参照を持ち、最後のパス解放時にバックエンドを回収して名前空間の参照を解放します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 04689ae8..303dadde 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -76,33 +76,6 @@ msgstr "" "は元のディレクトリを指し、既に開いているファイルの参照先は変わりません。共有マウントでは引き続きイベントが伝播します。サブツリーの伝播を止めるには" " ``MS_REC | MS_PRIVATE`` を使用します。" -msgid "加入挂载命名空间" -msgstr "マウント名前空間への参加" - -msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 返回 ``EINVAL``。不支持 pidfd、其他种类的命名空间或 nsfs 句柄的 bind mount。" -msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNS)`` は通常の読み取り専用 FD として開いた ``/proc//ns/mnt`` ハンドルを受け付けます。実効 ``CAP_SYS_ADMIN`` と ``CAP_SYS_CHROOT`` が必要で、なければ ``EPERM`` を返します。無効な FD または ``O_PATH`` FD は ``EBADF`` を返します。未対応の型、nsfs 以外の FD、ほかのタスクと共有されている ``CLONE_FS`` 状態では ``EINVAL`` を返します。pidfd、ほかの種類の名前空間、nsfs ハンドルの bind mount には対応していません。" - -msgid "" -"切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。参见 " -":doc:`../core-api/mount-namespaces`。" -msgstr "" -"切り替え後の root と cwd はいずれも対象のマウントグラフで見えているルートを指し、既存の FD と umask " -"は保持されます。元のプロセスが終了した後や名前空間を切り替えた後でもハンドルは使用できます。 :doc:`../core-api/mount-" -"namespaces` を参照してください。" - -msgid "" -"nsfs 句柄不是字节流。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 " -"FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 " -"``ESPIPE``。 ``NS_GET_NSTYPE`` 返回 ``CLONE_NEWNS``,``FIONREAD`` 写回零,不支持的 " -"namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" -msgstr "" -"nsfs ハンドルはバイトストリームではありません。書き込み用または ``O_TRUNC`` 付きで開くと ``EPERM`` になり、 " -"``O_PATH`` はこれらのフラグを無視します。通常の FD では単一バッファ、位置指定、ベクトルの読み取りは " -"``EINVAL``、書き込みは ``EBADF`` を返します。有効な ``whence`` での ``lseek()`` は " -"``ESPIPE`` を返します。 ``NS_GET_NSTYPE`` は ``CLONE_NEWNS`` を返し、 ``FIONREAD`` " -"はゼロを書き戻し、未対応の namespace ioctl は ``ENOTTY`` を返します。 ``O_PATH`` FD " -"ではメタデータを取得できますが、読み書き、シーク、ioctl はできません。" - msgid "bind mount" msgstr "bind mount" @@ -364,3 +337,24 @@ msgstr "作成者の実効 UID と GID は現在のユーザー名前空間に msgid "内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding 能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 用户空间与挂载树组合创建仍要求创建前具备初始用户空间的 ``CAP_SYS_ADMIN``。" msgstr "内部 UID/GID、補助グループ、no_new_privs は保持されます。新しい名前空間の permitted、effective、bounding 集合には対応するすべての能力が含まれ、inheritable、ambient、securebits はクリアされます。能力は名前空間のスコープで検査され、新しい権限はその空間と子孫に適用されます。unshare は dumpability と親死亡シグナルを保持します。準備失敗時は資格情報、ファイルシステム共有、プロセス公開状態を保持します。ユーザーとマウント名前空間の同時作成には、作成前の初期ユーザー名前空間での ``CAP_SYS_ADMIN`` が引き続き必要です。" + +msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` 句柄。调用者需要初始用户空间中有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" +msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNS)`` は通常の読み取り専用 ``/proc//ns/mnt`` ハンドルを受け付けます。呼び出し元には初期ユーザー名前空間の有効な ``CAP_SYS_ADMIN`` と ``CAP_SYS_CHROOT`` が必要で、欠けていれば ``EPERM`` を返します。他のタスクと ``CLONE_FS`` 状態を共有している場合は ``EINVAL`` を返します。" + +msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" +msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUSER)`` は通常の読み取り専用 ``/proc//ns/user`` ハンドルを受け付けます。現在のユーザー名前空間への再参加、同じグループの別の活動中スレッド、他のタスクとのファイルシステム状態の共有は ``EINVAL`` になります。対象ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。現在の名前空間の祖先はこの権限検査を通過できません。" + +msgid "nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS`` 或 ``CLONE_NEWUSER``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" +msgstr "nsfs ハンドルはメタデータと ioctl を提供します。書き込みモードまたは ``O_TRUNC`` で開くと ``EPERM`` を返し、``O_PATH`` はこれらのフラグを無視します。通常 FD のスカラー、位置指定、ベクトル読み取りは ``EINVAL``、書き込みは ``EBADF``、有効な ``whence`` の ``lseek()`` は ``ESPIPE`` を返します。``NS_GET_NSTYPE`` は実際の型に応じて ``CLONE_NEWNS`` または ``CLONE_NEWUSER`` を返し、``FIONREAD`` はゼロを書き込みます。未対応の namespace ioctl は ``ENOTTY`` を返します。``O_PATH`` FD はメタデータ照会に使えますが、読み書き、シーク、ioctl は実行できません。" + +msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" +msgstr "切り替え後の root と cwd は対象マウントグラフの可視ルートを指します。既存の FD と umask は保持されます。元のプロセスが終了した後や名前空間を切り替えた後もハンドルを使用できます。" + +msgid "加入命名空间" +msgstr "名前空間への参加" + +msgid "成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask 保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" +msgstr "ユーザー名前空間への参加が成功すると、グローバル UID/GID、補助グループ、no_new_privs、root、cwd、umask を保持します。permitted、effective、bounding にはサポートする全能力を設定し、inheritable、ambient、securebits をクリアします。作用域内の権限が増加すると親死亡シグナルを解除してダンプ可能性を制限します。検査失敗時は元の資格情報とファイルシステム状態を保持します。" + +msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount 与 user 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" +msgstr "無効な FD と ``O_PATH`` FD は ``EBADF`` を返します。nsfs 以外の FD、型の不一致、未対応の型は ``EINVAL`` を返します。mount と user のハンドルに対応します。pidfd と nsfs ハンドルの bind mount は未接続です。:doc:`../core-api/mount-namespaces` を参照してください。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po index fa557b0e..383387c4 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po @@ -387,3 +387,12 @@ msgstr "" msgid "``status`` 的四个 ``Uid``、四个 ``Gid`` 和 ``Groups`` 中的补充组按生成视图时 调用者的用户命名空间输出。未映射的 ID 显示为 65534,目标任务的内部凭据保持 全局 ID。成功打开的文件保存已渲染字节,之后切换空间或转交描述符继续读取 原视图,重新打开时使用新调用者的空间。" msgstr "``status`` の四つの ``Uid``、四つの ``Gid`` と補助 ``Groups`` は、ビューを生成する呼び出し元のユーザー名前空間で表示します。未マップの ID は 65534 となり、対象タスクの内部資格情報はグローバル ID を保持します。正常にオープンしたファイルは描画済みバイト列を保存するため、名前空間の切り替えや記述子の転送後も元のビューを読みます。再オープンでは新しい呼び出し元の空間を使用します。" + +msgid "``ns/mnt``、``ns/user``" +msgstr "``ns/mnt``、``ns/user``" + +msgid "``ns`` 目录枚举 ``mnt`` 和 ``user``。读取或跟随链接须通过现有 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接保留 PID 身份,每次跟随取得目标 当时的空间。nsfs 句柄在原进程退出或切换空间后继续保留原空间,链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。同一空间的句柄共享稳定 inode,不同空间 在共同的 nsfs 设备上使用独立 inode。切换接口见 :doc:`abi`。" +msgstr "``ns`` ディレクトリは ``mnt`` と ``user`` を列挙します。リンクの読み取りと追跡には既存の ``PTRACE_MODE_READ_FSCREDS`` 検査が必要です。リンクは PID の同一性を保持し、追跡するたびに対象の現在の名前空間を取得します。nsfs ハンドルは元のプロセスの終了や名前空間の切り替え後も元の名前空間を保持します。リンク表示は ``mnt:[inode]`` または ``user:[inode]`` です。同じ名前空間のハンドルは安定した inode を共有し、異なる名前空間は共通の nsfs デバイス上で別々の inode を使います。切り替えは :doc:`abi` を参照してください。" + +msgid "目标任务的挂载与用户命名空间 magic link,跟随时取得保留空间的 nsfs 句柄。" +msgstr "対象タスクのマウントおよびユーザー名前空間の magic link です。リンクをたどると、その名前空間を保持する nsfs ハンドルを取得します。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index c754ad01..8397f00c 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -83,22 +83,36 @@ bounding 能力集包含全部已支持能力,inheritable、ambient 和 secure 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 用户空间与挂载树组合创建仍要求创建前具备初始用户空间的 ``CAP_SYS_ADMIN``。 -加入挂载命名空间 -================ +加入命名空间 +============ ``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 -``/proc//ns/mnt`` 句柄。调用者需要有效的 ``CAP_SYS_ADMIN`` 和 -``CAP_SYS_CHROOT``,否则返回 ``EPERM``。无效 FD 或 ``O_PATH`` FD 返回 -``EBADF``;不支持的类型、非 nsfs FD 或仍与其他任务共享 ``CLONE_FS`` 状态 -返回 ``EINVAL``。不支持 pidfd、其他种类的命名空间或 nsfs 句柄的 bind mount。 +``/proc//ns/mnt`` 句柄。调用者需要初始用户空间中有效的 ``CAP_SYS_ADMIN`` +和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` +状态时返回 ``EINVAL``。 切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 -仍可在原进程退出或切换命名空间后使用。参见 :doc:`../core-api/mount-namespaces`。 +仍可在原进程退出或切换命名空间后使用。 + +``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 +``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 +任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 +``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。 + +成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask +保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 +ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 +检查失败保留原凭据与文件系统状态。 + +无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 +类型返回 ``EINVAL``。当前支持 mount 与 user 句柄,pidfd 和 nsfs 句柄的 bind +mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。 -nsfs 句柄不是字节流。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, +nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 -``NS_GET_NSTYPE`` 返回 ``CLONE_NEWNS``,``FIONREAD`` 写回零,不支持的 +``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS`` 或 ``CLONE_NEWUSER``。 +``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。 diff --git a/Documentation/userspace-api/procfs.rst b/Documentation/userspace-api/procfs.rst index 19f16f53..95abbbdd 100644 --- a/Documentation/userspace-api/procfs.rst +++ b/Documentation/userspace-api/procfs.rst @@ -98,6 +98,14 @@ flush 的独立统计行/扩展字段。同步统计不分配内存;异步记 * - ``fdinfo/FD`` - 共享 OFD 的位置、用户可见打开标志、该描述符的 CLOEXEC、mount ID/inode, 以及 eventfd/timerfd/epoll 的专项元数据;读取不消费事件或推进定时器。 + * - ``ns/mnt``、``ns/user`` + - 目标任务的挂载与用户命名空间 magic link,跟随时取得保留空间的 nsfs 句柄。 + +``ns`` 目录枚举 ``mnt`` 和 ``user``。读取或跟随链接须通过现有 +``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接保留 PID 身份,每次跟随取得目标 +当时的空间。nsfs 句柄在原进程退出或切换空间后继续保留原空间,链接显示为 +``mnt:[inode]`` 或 ``user:[inode]``。同一空间的句柄共享稳定 inode,不同空间 +在共同的 nsfs 设备上使用独立 inode。切换接口见 :doc:`abi`。 PSS 通过遍历实际用户 PTE,按物理页的用户映射数分摊;共享同一地址空间的 ``CLONE_VM`` 线程只统计一次,缓存引用和内核引用不增加分母。设备映射不计入 diff --git a/fs/nsfs/namespace.c b/fs/nsfs/namespace.c index e8b64003..fc229f61 100644 --- a/fs/nsfs/namespace.c +++ b/fs/nsfs/namespace.c @@ -1,34 +1,77 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include #include +#include +#include #include #include #include "../vfs/mount_internal.h" #define NSFS_DEVICE 204u #define NSFS_MAGIC 0x6e736673 -#define NSFS_LABEL_BYTES (sizeof("mnt:[]") + 20u) +#define NSFS_LABEL_BYTES (sizeof("user:[]") + 20u) + +/** @brief Typed backend capture retaining one namespace until final release. */ +struct nsfs_context { + uint64_t inode; + uint32_t type; + union { + struct vfs_namespace *mount; + struct user_namespace *user; + } ns; +}; + +static uint64_t next_inode = 1, initial_user_inode; static const struct vfs_backend_ops nsfs_ops; +/** @brief Assign a globally unique inode under sole VFS execution ownership. + * @param inode Namespace-owned identity, initially zero. + * @return Stable identity, or zero after the 64-bit allocator is exhausted. + * Assignment needs no allocation and never reuses a retired identity. + */ +static uint64_t nsfs_identity(uint64_t *inode) +{ + if (!*inode && next_inode) *inode = next_inode++; + return *inode; +} + /** @brief Test immutable namespace inode metadata in its own backend. */ -static bool nsfs_inode(const struct vfs_namespace *ns, const struct storage_node *node) +static bool nsfs_inode(const struct nsfs_context *context, const struct storage_node *node) { - return node->type == RELIEFOS_FS_TYPE_FILE && node->entry_id == ns->root->id; + return node->type == RELIEFOS_FS_TYPE_FILE && node->entry_id == context->inode; } -/** @copydoc nsfs_readlink */ -int nsfs_readlink(const struct vfs_namespace *ns, char *buffer, size_t capacity) +/** @brief Render a typed namespace identity without allocating a path. + * @param type CLONE_NEWNS or CLONE_NEWUSER. @param inode Assigned identity. + * @param buffer Required output. @param capacity Maximum bytes, without NUL. + * @return Copied byte count or -EOVERFLOW for an exhausted identity allocator. + */ +static int nsfs_label(uint32_t type, uint64_t inode, char *buffer, size_t capacity) { - if (!ns || !ns->root) return -ENOENT; + if (!inode) return -EOVERFLOW; struct text_stream text = {.buffer = buffer, .capacity = capacity > NSFS_LABEL_BYTES ? NSFS_LABEL_BYTES : (uint32_t)capacity}; - text_string(&text, "mnt:["); - text_unsigned(&text, ns->root->id); + text_string(&text, type == CLONE_NEWUSER ? "user:[" : "mnt:["); + text_unsigned(&text, inode); text_string(&text, "]"); return (int)text.written; } +/** @copydoc nsfs_readlink */ +int nsfs_readlink(struct vfs_namespace *ns, char *buffer, size_t capacity) +{ + if (!ns || !ns->root) return -ENOENT; + return nsfs_label(CLONE_NEWNS, nsfs_identity(&ns->nsfs_inode), buffer, capacity); +} + +/** @copydoc nsfs_user_readlink */ +int nsfs_user_readlink(struct user_namespace *ns, char *buffer, size_t capacity) +{ + return nsfs_label(CLONE_NEWUSER, + nsfs_identity(ns ? &ns->nsfs_inode : &initial_user_inode), buffer, capacity); +} + /** @brief A detached namespace backend has no named children. */ static int nsfs_lookup(void *context, const struct storage_node *parent, const char *name, struct storage_node *out) @@ -37,7 +80,7 @@ static int nsfs_lookup(void *context, const struct storage_node *parent, return -ENOENT; } -/** @brief Mark a handle inode while its mount keeps the graph alive. */ +/** @brief Mark an authentic handle inode while its backend retains the scope. */ static int nsfs_retain(void *context, const struct storage_node *node, void **pin) { *pin = NULL; @@ -47,23 +90,26 @@ static int nsfs_retain(void *context, const struct storage_node *node, void **pi return 0; } -/** @brief No per-dentry graph reference is needed while the backend is live. */ +/** @brief No per-dentry scope reference is needed while the backend is live. */ static void nsfs_release(void *context, const struct storage_node *node, void *pin) { (void)context; (void)node; (void)pin; } -/** @brief Compare inode identities in the same retained graph. */ +/** @brief Compare inode identities in the same retained namespace. */ static bool nsfs_same(void *context, const struct storage_node *a, const struct storage_node *b) { (void)context; return a->type == b->type && a->entry_id == b->entry_id; } -/** @brief Final backend release drops its graph pin, never under a spinlock. */ +/** @brief Drop the typed namespace capture and allocation outside spinlocks. */ static void nsfs_destroy(void *context) { - vfs_namespace_put(context); + struct nsfs_context *capture = context; + if (capture->type == CLONE_NEWUSER) user_namespace_put(capture->ns.user); + else vfs_namespace_put(capture->ns.mount); + kernel_free(capture); } /** @brief Namespace handles have metadata and ioctls, not a byte stream. */ @@ -85,7 +131,7 @@ static int nsfs_permissions(void *context, const struct vfs_path *path, return 0; } -/** @brief Use the permanent anchor ID as the exported namespace inode number. */ +/** @brief Export the stable namespace inode on the common nsfs device. */ static int nsfs_getattr(void *context, const struct vfs_path *path, struct linux_stat_abi *out) { (void)context; @@ -112,7 +158,8 @@ static int nsfs_display(void *context, const struct storage_node *node, char *bu { if (!nsfs_inode(context, node)) return -ENOENT; char label[NSFS_LABEL_BYTES]; - int length = nsfs_readlink(context, label, sizeof(label)); + const struct nsfs_context *capture = context; + int length = nsfs_label(capture->type, capture->inode, label, sizeof(label)); if (length < 0) return length; if ((size_t)length >= capacity) return -ENAMETOOLONG; __builtin_memcpy(buffer, label, (size_t)length); @@ -127,27 +174,84 @@ static const struct vfs_backend_ops nsfs_ops = { .display_name = nsfs_display, }; -/** @copydoc nsfs_create_path */ -int nsfs_create_path(struct vfs_namespace *ns, struct vfs_path *out) +/** @brief Retain a typed scope and publish its detached handle atomically. + * @param value Borrowed description of a live namespace with assigned inode. + * @param out Required empty output receiving one owned path. + * @return Zero or negative errno. Every failure balances allocations and refs. + * Execution ownership required; the caller's namespace ownership is retained. + */ +static int nsfs_create_handle(const struct nsfs_context *value, struct vfs_path *out) { if (!out) return -EINVAL; *out = (struct vfs_path){0}; - if (!ns || !ns->root) return -ENOENT; + if (!value->inode) return -EOVERFLOW; + struct nsfs_context *context = kernel_malloc(sizeof(*context)); + if (!context) return -ENOMEM; + *context = *value; + if (context->type == CLONE_NEWUSER) user_namespace_get(context->ns.user); + else vfs_namespace_get(context->ns.mount); struct storage_node root = {.type = RELIEFOS_FS_TYPE_DIR}; struct storage_node node = {.type = RELIEFOS_FS_TYPE_FILE, - .flags = STORAGE_NODE_FLAG_NSFS, .entry_id = ns->root->id}; + .flags = STORAGE_NODE_FLAG_NSFS, .entry_id = context->inode}; struct vfs_mount *mount; - int rc = vfs_mount_new(&nsfs_ops, vfs_namespace_get(ns), NULL, &root, &mount); - if (rc) { vfs_namespace_put(ns); return rc; } + int rc = vfs_mount_new(&nsfs_ops, context, NULL, &root, &mount); + if (rc) { nsfs_destroy(context); return rc; } rc = vfs_path_anonymous(mount, &node, out); vfs_mount_put(mount); return rc; } +/** @copydoc nsfs_create_path */ +int nsfs_create_path(struct vfs_namespace *ns, struct vfs_path *out) +{ + if (!out) return -EINVAL; + *out = (struct vfs_path){0}; + if (!ns || !ns->root) return -ENOENT; + const struct nsfs_context value = {.type = CLONE_NEWNS, + .inode = nsfs_identity(&ns->nsfs_inode), .ns.mount = ns}; + return nsfs_create_handle(&value, out); +} + +/** @copydoc nsfs_create_user_path */ +int nsfs_create_user_path(struct user_namespace *ns, struct vfs_path *out) +{ + const struct nsfs_context value = {.type = CLONE_NEWUSER, + .inode = nsfs_identity(ns ? &ns->nsfs_inode : &initial_user_inode), .ns.user = ns}; + return nsfs_create_handle(&value, out); +} + +/** @brief Authenticate provider, retained inode and backend pin together. + * @param path Borrowed path, nullable. @return Borrowed capture or NULL. + * Execution ownership and the held path stabilize the entire capture. + */ +static struct nsfs_context *nsfs_path_context(const struct vfs_path *path) +{ + if (!vfs_path_valid(path) || path->mount->ops != &nsfs_ops) return NULL; + struct nsfs_context *context = path->mount->context; + return path->dentry->backend_pin == context && + nsfs_inode(context, &path->dentry->node) ? context : NULL; +} + /** @copydoc nsfs_path_namespace */ struct vfs_namespace *nsfs_path_namespace(const struct vfs_path *path) { - if (!vfs_path_valid(path) || path->mount->ops != &nsfs_ops) return NULL; - struct vfs_namespace *ns = path->mount->context; - return path->dentry->backend_pin == ns && nsfs_inode(ns, &path->dentry->node) ? ns : NULL; + struct nsfs_context *context = nsfs_path_context(path); + return context && context->type == CLONE_NEWNS ? context->ns.mount : NULL; +} + +/** @copydoc nsfs_path_user_namespace */ +bool nsfs_path_user_namespace(const struct vfs_path *path, struct user_namespace **out) +{ + struct nsfs_context *context = nsfs_path_context(path); + *out = NULL; + if (!context || context->type != CLONE_NEWUSER) return false; + *out = context->ns.user; + return true; +} + +/** @copydoc nsfs_path_type */ +uint32_t nsfs_path_type(const struct vfs_path *path) +{ + struct nsfs_context *context = nsfs_path_context(path); + return context ? context->type : 0; } diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 318661e9..39cb8cc5 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -850,7 +850,7 @@ int proc_mount_node_identity(const char *name,struct task_identity **out,bool *m if(rc)return rc==-ESRCH ? -RELIEFOS_ENOENT : rc; *magic = file && (proc_fd_number(file) >= 0 || proc_text_eq(file, "cwd") || proc_text_eq(file, "root") || proc_text_eq(file, "exe") || - proc_text_eq(file, "ns/mnt")); + proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user")); return 0; } @@ -883,7 +883,7 @@ int proc_mount_magic_stat(const char *name,struct linux_stat_abi *out) * @param name Live intrinsic proc key, already checked against its retained PID. * @param out Receives one owned path; empty on failure. * @return Zero or negative errno. A namespace link captures the target's - * current graph, not the graph it had when the proc link was looked up. + * current mount or user namespace. The proc link retains only PID identity. */ int proc_mount_magic_target(const char *name,struct vfs_path *out) { @@ -896,6 +896,7 @@ int proc_mount_magic_target(const char *name,struct vfs_path *out) int fd=proc_fd_number(file);if(fd>=0)return proc_fd_get_path(task,fd,out); if(!proc_stat_mm_visible(sched_current_task(),task))return -RELIEFOS_EACCES; if (proc_text_eq(file, "ns/mnt")) return nsfs_create_path(sched_task_namespace(task), out); + if (proc_text_eq(file, "ns/user")) return nsfs_create_user_path(task->user_ns, out); struct task_fs_paths *paths=sched_task_paths(task); if(proc_text_eq(file,"cwd"))vfs_path_get(&paths->cwd,out); else if(proc_text_eq(file,"root"))vfs_path_get(&paths->root,out); @@ -1099,7 +1100,8 @@ int proc_lookup(const char *path, struct storage_node *out) uint32_t pid = 0; int kind = proc_path_kind(path, &file, &pid); if ((kind == 2 || kind == 3) && - (proc_text_eq(file, "ns") || proc_text_eq(file, "ns/mnt"))) { + (proc_text_eq(file, "ns") || proc_text_eq(file, "ns/mnt") || + proc_text_eq(file, "ns/user"))) { if (!(kind == 3 ? sched_current_task() : sched_find(pid))) return -RELIEFOS_ENOENT; if (out) *out = (struct storage_node){.flags = STORAGE_NODE_FLAG_PROC, .type = proc_text_eq(file, "ns") ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_SYMLINK}; @@ -1357,8 +1359,9 @@ int proc_readlink(const char *path, char *buffer, uint32_t capacity) } task = kind == 3 ? caller : sched_find(pid); if (!task) return -RELIEFOS_ENOENT; - if (proc_text_eq(file, "ns/mnt")) { + if (proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user")) { if (!proc_stat_mm_visible(caller, task)) return -RELIEFOS_EACCES; + if (proc_text_eq(file, "ns/user")) return nsfs_user_readlink(task->user_ns, buffer, capacity); return nsfs_readlink(sched_task_namespace(task), buffer, capacity); } if (!file || (!proc_text_eq(file, "exe") && !proc_text_eq(file, "cwd") && !proc_text_eq(file, "root") && proc_fd_number(file) < 0)) @@ -1388,7 +1391,7 @@ int proc_readlink(const char *path, char *buffer, uint32_t capacity) * and retains the provider; no scheduler lock spans a generated-file callback. * The process entries include unified cgroup membership. */ -/** @brief Enumerate a proc directory, including the live task's ns/mnt link. +/** @brief Enumerate a proc directory, including its live mount and user scopes. * @param path Required intrinsic proc directory key. * @param offset Required in/out continuation cookie. * @param entry Required output for the next entry. @@ -1493,9 +1496,10 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * if (kind == 3) pid = sched_current_pid(); if ((kind == 2 || kind == 3) && proc_text_eq(file, "ns")) { if (!sched_find(pid)) return -RELIEFOS_ENOENT; - if (*offset) return 0; - *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_SYMLINK, .name = "mnt"}; - *offset = 1; + static const char *const namespaces[] = {"mnt", "user"}; + if (*offset >= sizeof(namespaces) / sizeof(namespaces[0])) return 0; + *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_SYMLINK}; + proc_copy(entry->name, sizeof(entry->name), namespaces[(*offset)++]); return 1; } if ((kind == 2 || kind == 3) && file && proc_text_eq(file, "fd")) { @@ -1607,7 +1611,8 @@ int proc_control_permissions(const char *name, const struct storage_node *node, if (node->type == RELIEFOS_FS_TYPE_DIR || node->type == RELIEFOS_FS_TYPE_SYMLINK) { const char *leaf = NULL; struct task *owner = proc_view_task(name, &leaf); - if (owner && (proc_text_eq(leaf, "ns") || proc_text_eq(leaf, "ns/mnt"))) { + if (owner && (proc_text_eq(leaf, "ns") || proc_text_eq(leaf, "ns/mnt") || + proc_text_eq(leaf, "ns/user"))) { value->mode = node->type == RELIEFOS_FS_TYPE_DIR ? 0511 : 0777; if (!sched_task_mm(owner)->nondumpable) { value->uid = owner->euid; diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 0cf007ae..c0427b38 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -234,6 +234,7 @@ struct vfs_namespace *vfs_path_namespace(const struct vfs_path *path); struct vfs_namespace { struct vfs_mount *root,*mounts; uint64_t references; + uint64_t nsfs_inode; /* Lazy identity shared by every retained nsfs handle. */ uint64_t mount_generation; /* Successful visible mount graph changes. */ /* Only managed snapshots have a finalizer; boot/fixture storage is external. */ void (*release)(struct vfs_namespace *ns); diff --git a/include/reliefnt/nsfs.h b/include/reliefnt/nsfs.h index 1962113b..392299d4 100644 --- a/include/reliefnt/nsfs.h +++ b/include/reliefnt/nsfs.h @@ -1,10 +1,13 @@ /* SPDX-License-Identifier: Apache-2.0 */ #ifndef RELIEFNT_NSFS_H #define RELIEFNT_NSFS_H +#include #include +#include struct vfs_namespace; struct vfs_path; +struct user_namespace; /** @brief Create a detached nsfs path retaining the actual mount graph. * @param ns Borrowed live graph, stable under execution ownership. @@ -13,6 +16,14 @@ struct vfs_path; */ int nsfs_create_path(struct vfs_namespace *ns, struct vfs_path *out); +/** @brief Create an authentic nsfs path retaining a user namespace. + * @param ns Borrowed live scope, NULL selects the permanent initial scope. + * @param out Required empty destination receiving one owned path. + * @return Zero or negative errno, with an empty output on failure. + * Execution ownership required; takes one scope reference until final close. + */ +int nsfs_create_user_path(struct user_namespace *ns, struct vfs_path *out); + /** @brief Identify the mount graph from an authentic retained nsfs inode. * @param path Borrowed held path under execution ownership, nullable. * @return Borrowed graph valid while the path is held, or NULL for another @@ -20,11 +31,35 @@ int nsfs_create_path(struct vfs_namespace *ns, struct vfs_path *out); */ struct vfs_namespace *nsfs_path_namespace(const struct vfs_path *path); +/** @brief Identify a user scope through an authentic retained nsfs inode. + * @param path Borrowed path under execution ownership, nullable. + * @param out Required borrowed scope output, NULL for the initial scope. + * @return True for an authentic user handle. False clears the output. + * The returned scope stays live while the path is held. + */ +bool nsfs_path_user_namespace(const struct vfs_path *path, struct user_namespace **out); + +/** @brief Authenticate an nsfs inode and query its namespace type. + * @param path Borrowed held path under execution ownership, nullable. + * @return CLONE_NEWNS, CLONE_NEWUSER, or zero for another inode. + * No allocation, references, user access or textual name resolution. + */ +uint32_t nsfs_path_type(const struct vfs_path *path); + /** @brief Generate a namespace magic-link label without allocating a handle. - * @param ns Borrowed live graph, nullable. + * @param ns Borrowed live graph, nullable, under execution ownership. * @param buffer Required output, not NUL-terminated. * @param capacity Maximum bytes to copy. * @return Number of bytes copied (possibly truncated), or negative errno. */ -int nsfs_readlink(const struct vfs_namespace *ns, char *buffer, size_t capacity); +int nsfs_readlink(struct vfs_namespace *ns, char *buffer, size_t capacity); + +/** @brief Generate a user namespace magic-link label without allocating. + * @param ns Borrowed scope, NULL selects the initial scope. + * @param buffer Required output, not NUL-terminated. + * @param capacity Maximum bytes to copy. + * @return Copied byte count, possibly truncated, or negative errno. + * Execution ownership serializes lazy inode identity assignment. + */ +int nsfs_user_readlink(struct user_namespace *ns, char *buffer, size_t capacity); #endif diff --git a/include/reliefnt/user_namespace.h b/include/reliefnt/user_namespace.h index b2f985c6..c7d1a20c 100644 --- a/include/reliefnt/user_namespace.h +++ b/include/reliefnt/user_namespace.h @@ -13,6 +13,7 @@ struct user_namespace_id_map; */ struct user_namespace { uint64_t references; + uint64_t nsfs_inode; /* Execution-owned, stable across all namespace handles. */ struct user_namespace *parent; uint32_t owner; uint32_t level; @@ -153,6 +154,16 @@ void sched_task_user_namespace_install(struct task *task, struct user_namespace */ int sched_task_user_namespace_unshare(struct task *task, bool new_mount_namespace); +/** @brief Join an authorized user scope through an authenticated held handle. + * @param task Current execution-owned task, required. + * @param ns Borrowed target held by the caller, NULL for the initial scope. + * @return Zero, -EINVAL for the same scope, a live thread group or shared FS, + * or -EPERM without target CAP_SYS_ADMIN. All rejection paths preserve state. + * Retains the target on success and applies namespace-local credential reset. + * Allocation-free and called outside scheduler_lock. + */ +int sched_task_user_namespace_join(struct task *task, struct user_namespace *ns); + /** @brief Retain an existing namespace or the permanent initial scope. * @param ns Borrowed live namespace, nullable for the initial namespace. * @return The same pointer with one additional owned reference when non-NULL. diff --git a/kernel/sched/user_namespace_task.c b/kernel/sched/user_namespace_task.c index d28fd1ce..1130a1b3 100644 --- a/kernel/sched/user_namespace_task.c +++ b/kernel/sched/user_namespace_task.c @@ -62,3 +62,13 @@ int sched_task_user_namespace_unshare(struct task *task, bool new_mount_namespac sched_task_user_namespace_install(task, ns); return 0; } + +/** @copydoc sched_task_user_namespace_join */ +int sched_task_user_namespace_join(struct task *task, struct user_namespace *ns) +{ + if (task->user_ns == ns || thread_group_pending(sched_task_tgid(task), task) || + (task->shared_fs && task->shared_fs->references != 1)) return -LINUX_EINVAL; + if (!task_ns_capable(task, ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; + sched_task_user_namespace_install(task, user_namespace_get(ns)); + return 0; +} diff --git a/kernel/syscall/dispatch.c b/kernel/syscall/dispatch.c index f4c652a7..985bb2fb 100644 --- a/kernel/syscall/dispatch.c +++ b/kernel/syscall/dispatch.c @@ -124,16 +124,18 @@ static int64_t syscall_ioctl_nonblock(struct task *task, int fd, uint64_t argume return 0; } -/** @brief Handle ioctl on an already authenticated mount namespace inode. +/** @brief Handle ioctl on an already authenticated namespace inode. * @param task Live caller under execution ownership. + * @param type CLONE_NEWNS or CLONE_NEWUSER from the authenticated inode. * @param cmd Normalized 32-bit Linux request, after generic FD ioctls. * @param argument User int output for FIONREAD, ignored for other requests. * @return Namespace type, zero for a copied byte count, or negative errno * (including the private swap retry result). */ -static int64_t syscall_nsfs_ioctl(struct task *task, uint32_t cmd, uint64_t argument) +static int64_t syscall_nsfs_ioctl(struct task *task, uint32_t type, + uint32_t cmd, uint64_t argument) { - if (cmd == NS_GET_NSTYPE) return CLONE_NEWNS; + if (cmd == NS_GET_NSTYPE) return type; if (cmd != FIONREAD) return -LINUX_ENOTTY; int32_t available = 0; int prep = swap_prepare_user_range(task, argument, sizeof(available), true); @@ -168,8 +170,9 @@ bool syscall_ioctl_front(struct task *task, uint32_t fd, uint32_t cmd, return true; } struct task_file *file = task_file_for_io(task, (int32_t)fd); - if (file && nsfs_path_namespace(&file->path_ref)) { - *result = syscall_nsfs_ioctl(task, cmd, argument); + uint32_t type = file ? nsfs_path_type(&file->path_ref) : 0; + if (type) { + *result = syscall_nsfs_ioctl(task, type, cmd, argument); return true; } if (file && file->character_file) { diff --git a/kernel/syscall/process/setns.c b/kernel/syscall/process/setns.c index 886a419b..d44ed51d 100644 --- a/kernel/syscall/process/setns.c +++ b/kernel/syscall/process/setns.c @@ -5,12 +5,13 @@ #include #include -/** @brief Join a mount graph through an authentic namespace FD. +/** @brief Join a mount graph or user scope through an authentic namespace FD. * @param task Live caller; execution ownership keeps its FD table stable. * @param fd Descriptor number (not O_PATH or a pidfd). - * @param type Zero or CLONE_NEWNS. - * @return Zero or a negative descriptor, capability or graph error. + * @param type Zero, CLONE_NEWNS or CLONE_NEWUSER matching the held inode. + * @return Zero or a negative descriptor, capability or namespace error. * Mount graph entry requires CAP_SYS_ADMIN and CAP_SYS_CHROOT in the initial user namespace. + * User scope entry requires target CAP_SYS_ADMIN and exclusive thread/FS state. */ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) { @@ -18,7 +19,11 @@ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) struct task_file *file = task_file_for_fd(task, fd); if (!file) return -LINUX_EINVAL; /* Existing PTY or implicit stdio. */ if (file->flags & TASK_FILE_FLAG_PATH) return -LINUX_EBADF; - if (type && type != CLONE_NEWNS) return -LINUX_EINVAL; + uint32_t actual_type = nsfs_path_type(&file->path_ref); + if (!actual_type || (type && type != actual_type)) return -LINUX_EINVAL; + struct user_namespace *scope = NULL; + if (nsfs_path_user_namespace(&file->path_ref, &scope)) + return sched_task_user_namespace_join(task, scope); struct vfs_namespace *ns = nsfs_path_namespace(&file->path_ref); if (!ns) return -LINUX_EINVAL; const uint64_t required = (1ULL << CAP_SYS_ADMIN) | (1ULL << CAP_SYS_CHROOT); diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index da0f4a5c..f4c11584 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -168,7 +168,6 @@ static void real_instance_dispatch(struct storage_volume *volume) volume->fs_ops=counted_provider; } -uint64_t mm_total_memory_kib(void){return 65536;} /** @brief Check mountinfo against fixture-provided native or anonymous dev_t. * @param ns Actual namespace. @param root Retained root path. * @param type Expected filesystem type. @param flags Expected attachment policy. @@ -4648,7 +4647,7 @@ static struct vfs_namespace *namespace_handle_target; static int namespace_handle_lookup(const char *name, struct storage_node *node) { bool root = !strcmp(name, "/handles"); - if (!root && strcmp(name, "/handles/mnt")) return -ENOENT; + if (!root && strcmp(name, "/handles/mnt") && strcmp(name, "/handles/user")) return -ENOENT; *node = (struct storage_node){.type = root ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_SYMLINK, .flags = STORAGE_NODE_FLAG_PROC | (root ? 0 : STORAGE_NODE_FLAG_MAGIC_LINK)}; return 0; @@ -4657,12 +4656,14 @@ static int namespace_handle_lookup(const char *name, struct storage_node *node) /** @brief Resolve the fixture magic link to a real anonymous nsfs inode. */ static int namespace_handle_follow(const char *name, struct vfs_path *out) { + if (!strcmp(name, "/handles/user")) return nsfs_create_user_path(NULL, out); assert(!strcmp(name, "/handles/mnt")); return nsfs_create_path(namespace_handle_target, out); } /** @brief Open a retained nsfs handle through real pathname, DAC and FD logic. */ -static void runtime_namespace_handle_open(struct vfs_namespace *ns, const struct vfs_path *root) +static void runtime_namespace_handle_open(struct vfs_namespace *ns, const struct vfs_path *root, + bool user) { static const struct vfs_pseudo_provider provider = { .root = "/handles", .lookup = namespace_handle_lookup, .follow = namespace_handle_follow, @@ -4681,7 +4682,8 @@ static void runtime_namespace_handle_open(struct vfs_namespace *ns, const struct sched_task_limits(&actor)->nofile.rlim_cur = 32; vfs_path_get(root, &actor.fs_paths.root); vfs_path_get(root, &actor.fs_paths.cwd); - char name[] = "/namespace-handles/mnt"; + char name[32]; + strcpy(name, user ? "/namespace-handles/user" : "/namespace-handles/mnt"); lookup_user_base = (uintptr_t)name; lookup_user_bytes = sizeof(name); namespace_handle_target = ns; @@ -4691,8 +4693,11 @@ static void runtime_namespace_handle_open(struct vfs_namespace *ns, const struct LINUX_O_PATH | LINUX_O_RDWR | LINUX_O_TRUNC, 0); assert(fd >= 0 && pathfd >= 0 && fd != pathfd); struct task_file *handle = task_file_for_fd(&actor, fd); - assert(nsfs_path_namespace(&handle->path_ref) == ns); - assert(nsfs_path_namespace(&task_file_for_fd(&actor, pathfd)->path_ref) == ns); + assert(nsfs_path_namespace(&handle->path_ref) == (user ? NULL : ns)); + assert(nsfs_path_namespace(&task_file_for_fd(&actor, pathfd)->path_ref) == (user ? NULL : ns)); + assert(nsfs_path_type(&handle->path_ref) == (user ? CLONE_NEWUSER : CLONE_NEWNS)); + struct user_namespace *scope = (void *)1; + assert(nsfs_path_user_namespace(&handle->path_ref, &scope) == user && !scope); assert(task_fd_descriptor_flags(&actor, fd) == RELIEFOS_FD_CLOEXEC); assert(task_file_for_fd(&actor, pathfd)->flags & TASK_FILE_FLAG_PATH); @@ -4717,7 +4722,8 @@ static void runtime_namespace_handle_open(struct vfs_namespace *ns, const struct cgroup_tasks[0] = NULL; int64_t result = 0; - assert(syscall_ioctl_front(&actor, fd, NS_GET_NSTYPE, UINT64_MAX, &result) && result == CLONE_NEWNS); + assert(syscall_ioctl_front(&actor, fd, NS_GET_NSTYPE, UINT64_MAX, &result) && + result == (user ? CLONE_NEWUSER : CLONE_NEWNS)); assert(syscall_ioctl_front(&actor, fd, NSIO << 8 | 0xff, 0, &result) && result == -ENOTTY); assert(syscall_ioctl_front(&actor, fd, FIONREAD, UINT64_MAX, &result) && result == -EFAULT); int32_t value = 1; @@ -4748,7 +4754,8 @@ static void runtime_namespace_handle_open(struct vfs_namespace *ns, const struct vfs_path_put(&top); assert(!vfs_path_remove(ns, &point, true)); vfs_path_put(&point); - puts("PASS nsfs descriptors: open, I/O, seek, ioctl and graph release"); + puts(user ? "PASS user nsfs descriptors: open, I/O, seek, ioctl and initial scope" + : "PASS mount nsfs descriptors: open, I/O, seek, ioctl and graph release"); } int main(int argc,char **argv) @@ -4781,7 +4788,8 @@ int main(int argc,char **argv) assert(!vfs_namespace_init(&ns,mount));vfs_mount_put(mount); struct vfs_path root={0},old_dir={0},old_file={0},top={0},file={0}; assert(!vfs_namespace_root(&ns,&root)); - runtime_namespace_handle_open(&ns, &root); + runtime_namespace_handle_open(&ns, &root, false); + runtime_namespace_handle_open(&ns, &root, true); real_mount_description(&ns,&root,"tmpfs","rw"); /* A registered storage codec without the audited epoch capability must * remain live even when it uses the common native VFS adapter. */ diff --git a/tools/tests/mount_namespace_task_test.c b/tools/tests/mount_namespace_task_test.c index 8281e803..8f3a9aef 100644 --- a/tools/tests/mount_namespace_task_test.c +++ b/tools/tests/mount_namespace_task_test.c @@ -340,6 +340,94 @@ static void check_user_namespaces(struct task *parent, struct task *child, puts("PASS user namespace clone/clone3/unshare, local capabilities and atomic rollback"); } +/** @brief Catch forged scope handles, unauthorized joins and credential reuse. */ +static void check_user_setns(struct task *task, struct task *thread) +{ + struct vfs_path initial = {0}; + assert(!nsfs_create_user_path(NULL, &initial)); + vfs_path_get(&initial, &ordinary_file.path_ref); + assert(syscall_setns(task, 4, CLONE_NEWUSER) == -LINUX_EINVAL); + vfs_path_put(&ordinary_file.path_ref); + + task->cap_effective = 0; + struct user_namespace *target = NULL; + assert(!user_namespace_create(task, &target)); + assert(!nsfs_create_user_path(target, &handle_file.path_ref)); + user_namespace_put(target); + assert(target->references == 1); + assert(syscall_setns(task, 3, CLONE_NEWNS) == -LINUX_EINVAL); + handle_file.flags = TASK_FILE_FLAG_PATH; + assert(syscall_setns(task, 3, CLONE_NEWUSER) == -LINUX_EBADF); + handle_file.flags = 0; + + ordinary_file.node = *vfs_path_node(&handle_file.path_ref); + assert(!vfs_path_anonymous(sched_task_namespace(task)->root, &ordinary_file.node, + &ordinary_file.path_ref)); + assert(syscall_setns(task, 4, CLONE_NEWUSER) == -LINUX_EINVAL); + vfs_path_put(&ordinary_file.path_ref); + task->euid = 2000; + assert(syscall_setns(task, 3, CLONE_NEWUSER) == -LINUX_EPERM); + assert(!task->user_ns && target->references == 1); + task->euid = 1000; + + thread->pid = 902; + thread->tgid = task->tgid; + thread->state = TASK_READY; + assert(syscall_setns(task, 3, CLONE_NEWUSER) == -LINUX_EINVAL); + thread->pid = 0; + thread->state = TASK_EXITED; + assert(!task_promote_shared(task, CLONE_FS)); + struct task sibling = {.shared_fs = task->shared_fs}; + ++sibling.shared_fs->references; + assert(syscall_setns(task, 3, CLONE_NEWUSER) == -LINUX_EINVAL); + assert(!task->user_ns && task->shared_fs->references == 2 && target->references == 1); + sched_task_fs_release(&sibling); + + struct vfs_namespace *mount = sched_task_namespace(task); + struct vfs_path root = sched_task_paths(task)->root, cwd = sched_task_paths(task)->cwd; + task->cap_permitted = task->cap_inheritable = task->cap_bset = task->cap_ambient = 4; + task->securebits = 0xff; + task->pdeath_signal = 10; + task->no_new_privs = true; + sched_task_mm(task)->nondumpable = false; + assert(!syscall_setns(task, 3, 0)); /* The parent owner needs no effective cap. */ + assert(task->user_ns == target && target->references == 2); + assert_user_scope(task, NULL); + assert(task->no_new_privs && task->pdeath_signal == 10 && !sched_task_mm(task)->nondumpable); + assert(sched_task_namespace(task) == mount && *sched_task_umask(task) == 0027); + assert(vfs_path_equal(&sched_task_paths(task)->root, &root)); + assert(vfs_path_equal(&sched_task_paths(task)->cwd, &cwd)); + assert(syscall_setns(task, 3, 0) == -LINUX_EINVAL); + vfs_path_get(&initial, &ordinary_file.path_ref); + assert(syscall_setns(task, 4, CLONE_NEWUSER) == -LINUX_EPERM); + assert(task->user_ns == target && target->references == 2); + vfs_path_put(&ordinary_file.path_ref); + + struct task creator = {.user_ns = target, .euid = 2000}; + struct user_namespace *descendant = NULL; + assert(!user_namespace_create(&creator, &descendant)); + assert(!nsfs_create_user_path(descendant, &ordinary_file.path_ref)); + user_namespace_put(descendant); + task->cap_effective = 0; + assert(syscall_setns(task, 4, CLONE_NEWUSER) == -LINUX_EPERM); + assert(task->user_ns == target && target->references == 3); + task->cap_effective = UINT64_C(1) << CAP_SYS_ADMIN; + assert(!syscall_setns(task, 4, CLONE_NEWUSER)); + assert(task->user_ns == descendant && descendant->references == 2 && target->references == 2); + assert(sched_task_mm(task)->nondumpable && !task->pdeath_signal && task->no_new_privs); + assert(!task->securebits && !task->cap_inheritable && !task->cap_ambient); + assert(task->cap_effective == (UINT64_C(1) << (CAP_LAST_CAP + 1)) - 1); + assert(syscall_setns(task, 3, CLONE_NEWUSER) == -LINUX_EPERM); + + vfs_path_put(&ordinary_file.path_ref); + vfs_path_put(&handle_file.path_ref); + vfs_path_put(&initial); + assert(descendant->references == 1 && target->references == 1); + task->user_ns = NULL; + user_namespace_put(descendant); + puts("PASS user namespace setns ownership, scope reset, thread/FS rejection and handle lifetime"); +} + int main(void) { struct sched_task_object parent_object = {0}, child_object = {0}; @@ -453,6 +541,7 @@ int main(void) check_unshare(parent, child); check_setns(parent); check_user_namespaces(parent, child, user); + check_user_setns(parent, child); sched_task_fs_release(parent); vfs_reclaim_mounts(16); assert(!vfs_namespace_destroy(&ns) && !fs_backend_pins); diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index 83eb0b7c..846abbfb 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -800,6 +800,8 @@ static void test_proc_mount_namespace_handles(void) struct reliefos_dir_entry entry; assert(proc_readdir("/proc/43/ns", &cursor, &entry) == 1); assert(entry.type == RELIEFOS_FS_TYPE_SYMLINK && !strcmp(entry.name, "mnt")); + assert(proc_readdir("/proc/43/ns", &cursor, &entry) == 1); + assert(entry.type == RELIEFOS_FS_TYPE_SYMLINK && !strcmp(entry.name, "user")); assert(!proc_readdir("/proc/43/ns", &cursor, &entry)); cursor = 0; bool listed = false; @@ -847,6 +849,36 @@ static void test_proc_mount_namespace_handles(void) vfs_path_put(&fresh); } + struct vfs_path user = {0}, initial_user = {0}; + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/user", VFS_LOOKUP_FOLLOW, &initial_user)); + assert(!vfs_path_stat(&initial_user, &st) && st.st_dev == device && st.st_ino != current_ino); + uint64_t initial_user_ino = st.st_ino; + assert(!user_namespace_create(¤t, &foreign.user_ns)); + struct user_namespace *scope = foreign.user_ns; + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/user", VFS_LOOKUP_FOLLOW, &user)); + assert(scope->references == 2); + assert(!vfs_path_stat(&user, &st) && st.st_dev == device && st.st_ino != initial_user_ino); + assert(st.st_mode == (LINUX_S_IFREG | 0444)); + uint64_t user_ino = st.st_ino; + snprintf(label, sizeof(label), "user:[%" PRIu64 "]", user_ino); + char user_label[64] = {0}; + count = proc_readlink("/proc/43/ns/user", user_label, sizeof(user_label)); + assert(count == (int)strlen(label) && !memcmp(user_label, label, count)); + const char *const user_aliases[] = {"self/ns/user", "thread-self/ns/user", "42/task/42/ns/user"}; + for (unsigned i = 0; i < 3; ++i) { + assert(!vfs_path_lookup(&ns, &root, &root, user_aliases[i], VFS_LOOKUP_FOLLOW, &fresh)); + assert(!vfs_path_stat(&fresh, &st) && st.st_ino == initial_user_ino); + vfs_path_put(&fresh); + } + foreign.user_ns = NULL; + user_namespace_put(scope); + assert(scope->references == 1); + assert(!vfs_path_stat(&user, &st) && st.st_ino == user_ino); + assert(!vfs_path_format_link(&ns, &root, &user, user_label, sizeof(user_label))); + assert(!strcmp(user_label, label)); + vfs_path_put(&user); + vfs_path_put(&initial_user); + sched_task_identity_detach(&foreign); /* Retire the identity, reusing PID 43. */ assert(vfs_path_readlink(&link, label, sizeof(label), &length) == -ENOENT); assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/mnt", VFS_LOOKUP_FOLLOW, &fresh)); diff --git a/tools/tests/procfs_raw_probe.c b/tools/tests/procfs_raw_probe.c index f0f61944..7f2a5075 100644 --- a/tools/tests/procfs_raw_probe.c +++ b/tools/tests/procfs_raw_probe.c @@ -4,6 +4,7 @@ * -no-pie -Wl,-e,_start -Wl,-Ttext-segment=0x400000 -Iinclude/uapi. * PID 1 remains parked after its result; other invocations exit normally. */ #include +#include #include #include #include @@ -141,9 +142,10 @@ static int udp_has_data(const char *text) /** @brief Read a complete proc file in seven-byte pieces, then rewind and close. * Anonymous buffers grow for host-wide tables and replace prior buffers only * after successful allocation. @param path Intrinsic path. + * @param immutable Require identical bytes after rewind for immutable data. * @return Bytes retained in contents, including binary data. */ -static size_t read_file(const char *path) +static size_t read_file(const char *path, bool immutable) { long fd = call(__NR_open, (long)path, 0, 0, 0, 0, 0); require(fd >= 0, path); @@ -175,8 +177,11 @@ static size_t read_file(const char *path) char first[7]; long n = call(__NR_read, fd, (long)first, sizeof(first), 0, 0, 0); require(n >= 0 && n <= 7, "read after rewind"); - for (long i = 0; i < n; ++i) - require(first[i] == contents[i], "stable snapshot"); + if (immutable) { + require(n == (long)(used < sizeof(first) ? used : sizeof(first)), "immutable length"); + for (long i = 0; i < n; ++i) + require(first[i] == contents[i], "immutable contents"); + } require(call(__NR_close, fd, 0, 0, 0, 0, 0) == 0, "close snapshot"); return used; } @@ -215,7 +220,7 @@ __attribute__((used, noreturn)) static void child_probe(void) require(bytes == (long)length(expected), "thread-self link length"); for (long i = 0; i < bytes; ++i) require(actual[i] == expected[i], "thread-self TID"); - read_file("/proc/thread-self/status"); + read_file("/proc/thread-self/status", false); descriptor_path(expected, "Pid:\t", (unsigned)call(__NR_gettid, 0, 0, 0, 0, 0, 0)); require(contains(contents, expected), "thread status PID"); __atomic_store_n(&thread_complete, 1, __ATOMIC_RELEASE); @@ -277,20 +282,20 @@ __attribute__((used, noreturn)) static void probe_main(void) "/proc/self/limits", "/proc/self/io"}; for (size_t i = 0; i < sizeof(paths) / sizeof(*paths); ++i) - read_file(paths[i]); + read_file(paths[i], false); print("PASS raw proc nodes, short reads, seek and EOF\n"); - read_file("/proc/self/maps"); + read_file("/proc/self/maps", false); require(contains(contents, "r-xp"), "executable map"); - read_file("/proc/self/smaps_rollup"); + read_file("/proc/self/smaps_rollup", false); require(contains(contents, "Pss:"), "PSS rollup"); - read_file("/proc/thread-self/status"); + read_file("/proc/thread-self/status", false); require(contains(contents, "Threads:"), "thread-self status"); long tasks = call(__NR_open, (long)"/proc/self/task", 0, 0, 0, 0, 0); require(tasks >= 0, "task directory"); require(call(__NR_getdents64, tasks, (long)contents, (long)contents_capacity, 0, 0, 0) > 0, "task entries"); call(__NR_close, tasks, 0, 0, 0, 0, 0); - size_t bytes = read_file("/proc/self/auxv"); + size_t bytes = read_file("/proc/self/auxv", true); require(bytes && !(bytes % 16), "binary auxv size"); int pages = 0, end = 0; for (size_t at = 0; at + 16 <= bytes; at += 16) { @@ -312,7 +317,7 @@ __attribute__((used, noreturn)) static void probe_main(void) call(__NR_close, fd, 0, 0, 0, 0, 0); char path[64]; descriptor_path(path, "/proc/self/fdinfo/", (unsigned)alias); - read_file(path); + read_file(path, false); require(contains(contents, "pos:") && contains(contents, "flags:"), "fdinfo alias"); call(__NR_close, alias, 0, 0, 0, 0, 0); long socket = call(__NR_socket, 2, 2 | 0x800, 0, 0, 0, 0); @@ -326,10 +331,10 @@ __attribute__((used, noreturn)) static void probe_main(void) require(call(__NR_bind, socket, (long)&address, sizeof(address), 0, 0, 0) == 0, "UDP bind"); require(call(__NR_sendto, socket, (long)"hello", 5, 0, (long)&address, sizeof(address)) == 5, "UDP local send"); - read_file("/proc/net/udp"); + read_file("/proc/net/udp", false); require(udp_has_data(contents), "UDP live queue"); descriptor_path(path, "/proc/self/fdinfo/", (unsigned)socket); - read_file(path); + read_file(path, false); require(contains(contents, "ino:"), "socket inode"); call(__NR_close, socket, 0, 0, 0, 0, 0); require(create_thread(thread_stack + sizeof(thread_stack)) > 0, "clone thread"); From 0cfeb82a91ebbe8299f78fb5bdaa3a638f1ea634 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 02:01:14 +0800 Subject: [PATCH 65/97] feat(vfs): enforce user-owned mount namespace restrictions --- Documentation/core-api/mount-namespaces.rst | 36 ++++- .../LC_MESSAGES/core-api/mount-namespaces.po | 107 +++++++++++-- .../en/LC_MESSAGES/userspace-api/abi.po | 72 +++++++-- .../LC_MESSAGES/core-api/mount-namespaces.po | 88 +++++++++-- .../ja/LC_MESSAGES/userspace-api/abi.po | 63 ++++++-- Documentation/userspace-api/abi.rst | 27 +++- fs/vfs/file.c | 10 +- fs/vfs/mount_internal.h | 2 + fs/vfs/mount_tree.c | 117 ++++++++++++--- include/reliefnt/mount.h | 49 +++++- include/reliefnt/task/accessors.h | 3 +- kernel/sched/clone.c | 14 +- kernel/sched/fs.c | 11 +- kernel/sched/internal.h | 4 +- kernel/sched/user_namespace_task.c | 2 +- kernel/syscall/fs/mount.c | 15 +- kernel/syscall/process/clone.c | 7 +- kernel/syscall/process/setns.c | 9 +- tools/test_futimens.py | 1 + tools/test_initramfs.py | 1 + tools/test_inotify_vfs.py | 1 + tools/test_memory_pressure_open_path.py | 1 + tools/test_mount_tree.py | 3 +- tools/test_vfs_lookup_cache.py | 1 + tools/tests/mount_backend_test.c | 67 +++++++++ tools/tests/mount_namespace_task_test.c | 70 ++++++++- tools/tests/mount_tree_test.c | 142 ++++++++++++++++++ 27 files changed, 801 insertions(+), 122 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 93129409..20f863dc 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -8,6 +8,21 @@ 系统后端,共享目录项和文件内容,但挂载策略和写入者计数独立。挂载 ID 和对等 组号各自从 VFS 全局序列分配。 +每个挂载图持有不可变的 user owner 引用,空指针表示初始用户空间。 +``vfs_namespace_snapshot()`` 和 ``vfs_namespace_clone()`` 保留原 owner; +``vfs_namespace_clone_owned()`` 显式选择新图的 owner。owner 改变时,shared +副本转为跟随原组的 slave,保留上游传入传播;子图的事件只在其下游传播。 + +跨 owner 快照锁定继承的只读、nosuid、nodev、noexec 和完整 atime 选择。 +后端的有效只读状态固化到附件,即使后端后来可写,继承附件仍保持只读。 +remount 和 bind-remount 违反这些锁时,在调用后端前返回 ``EPERM``。 +现存锁在同 owner 快照和 bind 中继续保留。 + +继承的挂载覆盖关系也被锁定,单独 move、普通卸载或 lazy unmount 返回 +``EINVAL``。非递归 bind 若遗漏继承的锁定子挂载,同样返回 ``EINVAL``; +递归 bind 若需要剪除锁定的 unbindable 子树,返回 ``EPERM``。新 bind 根和 +跨 owner 传播的新根可整树摘除,其后代继续保留覆盖锁。 + 可选的 root 和 cwd 引用按原挂载对象和目录项重新绑定,而不是重新查找路径; 即使路径已被其他挂载覆盖,所指目录项也不变。已摘除的路径保持原样,其他活动 命名空间的路径返回 ``EXDEV``。所有分配完成后才发布新树并替换路径;失败时 @@ -69,8 +84,13 @@ VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载 ``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare 同时准备独立的文件系统 状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 -no_new_privs,并初始化新空间的能力集合及 securebits。组合 ``CLONE_NEWNS`` -创建仍检查初始用户空间中的 ``CAP_SYS_ADMIN``。 +no_new_privs,并初始化新空间的能力集合及 securebits。单独创建挂载空间要求 +当前用户空间的 ``CAP_SYS_ADMIN``;组合 ``CLONE_NEWUSER | CLONE_NEWNS`` +先准备用户空间,再以该候选空间作为新图 owner,任一步失败均整体回滚。 + +bind、bind-remount、move、传播类型修改和卸载要求挂载图 owner 的 +``CAP_SYS_ADMIN``。新后端创建、共享后端 remount 与新 mount API 当前还要求 +初始用户空间的 ``CAP_SYS_ADMIN``;后端 owner 尚待接通。 句柄与切换 ========== @@ -86,8 +106,10 @@ PID 身份,每次成功跟随则取得目标当时的挂载图或用户空间 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。 ``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 -mount 切换时 root 和 cwd 一起替换为目标图当前可见的根,已有文件描述符和 -umask 保留。准备失败保留原图与路径。 +mount 切换要求当前用户空间的 ``CAP_SYS_ADMIN``、``CAP_SYS_CHROOT`` 和 +目标图 owner 的 ``CAP_SYS_ADMIN``,并要求独占文件系统状态。root 和 cwd +一起替换为目标图当前可见的根,已有文件描述符和 umask 保留。准备失败保留 +原图与路径。 user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 @@ -101,6 +123,7 @@ user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SY ``vfs_namespace_retire()`` 就地摘除整棵树而不传播卸载,随后释放图本身。已持有 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 ``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。 +快照全部准备成功后才持有 owner 引用,图退役或销毁时释放它。 凭据权限作用域 ============== @@ -110,8 +133,9 @@ user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SY fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 释放。清理登录身份继续保留所属空间。 -文件系统 DAC 特权覆盖、挂载图管理、设备、网络、IPC、时钟、重启、模块、内存锁定 -和 OOM 调整等共享资源使用初始空间能力。信号、进程优先级、跨进程资源限制与 +挂载图管理按图 owner 授权。文件系统 DAC 特权覆盖、共享文件系统后端、设备、 +网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 +信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index b0c286f8..5bb17320 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -144,17 +144,17 @@ msgid "引用释放" msgstr "Reference release" msgid "" -"``vfs_namespace_clone()`` 返回一个受管理的图引用。最后一个图引用释放时, ``vfs_namespace_retire()``" -" 就地摘除整棵树而不传播卸载,随后释放图本身。已持有 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 " -"``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。" +"``vfs_namespace_clone()`` 返回一个受管理的图引用。最后一个图引用释放时, ``vfs_namespace_retire()`` " +"就地摘除整棵树而不传播卸载,随后释放图本身。已持有 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 " +"``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。 快照全部准备成功后才持有 owner 引用,图退役或销毁时释放它。" msgstr "" -"``vfs_namespace_clone()`` returns one managed graph reference. On the last " -"put, ``vfs_namespace_retire()`` detaches the whole tree locally without " -"propagating unmounts, then the graph itself is freed. Held paths remain " -"valid and the existing deferred queue handles backend teardown. Callers " -"still own storage for boot and test graphs. The strict " -"``vfs_namespace_destroy()`` refuses to destroy a graph with outstanding " -"graph or external path references." +"``vfs_namespace_clone()`` returns a managed graph reference. On the final graph reference " +"release, ``vfs_namespace_retire()`` detaches the entire tree locally without propagating " +"unmounts, then frees the graph itself. Retained paths remain valid and backends use the " +"existing deferred cleanup queue. Boot and test graph storage remains caller-managed. Strict " +"``vfs_namespace_destroy()`` rejects destruction while graph references or external path " +"references remain. A snapshot retains its owner reference only after all preparation " +"succeeds, and graph retirement or destruction releases it." msgid "游离挂载路径" msgstr "Detached mount paths" @@ -171,8 +171,21 @@ msgstr "Credential capability scope" msgid "任务凭据持有引用计数的用户命名空间,空指针表示初始空间。任务 UID/GID 使用 全局内核 ID。子空间记录创建者的有效 UID,并持有父空间引用,层级上限为 32。 fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 释放。清理登录身份继续保留所属空间。" msgstr "Task credentials hold a reference to a user namespace. A null pointer represents the initial namespace. Task UIDs and GIDs are global kernel IDs. A child namespace records its creator’s effective UID and retains its parent, with a nesting limit of 32. Fork and kernel-launched tasks inherit the reference. Exec keeps it, and wait or task-slot reuse releases the reference of a zombie. Clearing a login identity preserves the owning namespace." -msgid "文件系统 DAC 特权覆盖、挂载图管理、设备、网络、IPC、时钟、重启、模块、内存锁定 和 OOM 调整等共享资源使用初始空间能力。信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。" -msgstr "Filesystem DAC overrides, mount graph management, devices, networking, IPC, the system clock, reboot, modules, memory locking, and OOM adjustments use initial-namespace capabilities for shared resources. Signals, process priorities, cross-process resource limits, and ptrace authorize capability overrides in the target task’s owning namespace. Raising a hard resource limit still requires initial-namespace capability. Capabilities extend to descendant namespaces. A task in the parent namespace whose effective UID matches the child’s owner has capabilities in that child’s subtree. Ptrace’s capability subset check requires both tasks to be in the same user namespace. Capset, identity changes, securebits, and seccomp installation use the caller’s own namespace capabilities." +msgid "" +"挂载图管理按图 owner 授权。文件系统 DAC 特权覆盖、共享文件系统后端、设备、 网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 " +"信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner " +"相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp " +"安装使用调用方所属空间的能力集合。" +msgstr "" +"Mount graph management is authorized against the graph owner. Filesystem DAC privilege " +"overrides, shared filesystem backends, devices, networking, IPC, clocks, reboot, modules, " +"memory locking and OOM adjustments use initial-namespace capabilities for shared resources. " +"Signals, process priorities, cross-process resource limits and ptrace are authorized against " +"the target task namespace. Raising hard resource limits still requires initial-namespace " +"capabilities. Capabilities apply to descendant namespaces, and a task whose effective UID in " +"the parent matches a child namespace owner has capabilities over that subtree. Ptrace " +"capability-subset checks require both tasks to share a user namespace. Capset, identity " +"transitions, securebits and seccomp installation use the caller namespace capability sets." msgid "" "空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID 转换为全局内核 ID;转换接口通过 acquire " @@ -326,14 +339,76 @@ msgstr "``IPC_SET`` first performs the existing object ownership and resource-li msgid "``/proc//ns/mnt`` 与 ``/proc//ns/user`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图或用户空间。" msgstr "``/proc//ns/mnt`` and ``/proc//ns/user`` are proc magic links. Reading or following them requires the same ``PTRACE_MODE_READ_FSCREDS`` check as ``/proc//fd``. Link keys retain PID identity. Each successful follow captures the target task current mount graph or user namespace." -msgid "``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare 同时准备独立的文件系统 状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 no_new_privs,并初始化新空间的能力集合及 securebits。组合 ``CLONE_NEWNS`` 创建仍检查初始用户空间中的 ``CAP_SYS_ADMIN``。" -msgstr "``CLONE_NEWUSER`` creates a user namespace for a clone child or an unshare caller. Effective UID/GID mapping, chroot, thread-group and allocation checks complete before installation. Unshare also prepares independent filesystem state. Any preparation failure rolls back the candidate namespace and paths. Creation preserves global identities, supplementary groups and no_new_privs, and initializes namespace capability sets and securebits. Combined ``CLONE_NEWNS`` creation still checks ``CAP_SYS_ADMIN`` in the initial user namespace." +msgid "" +"``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare " +"同时准备独立的文件系统 状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 no_new_privs,并初始化新空间的能力集合及 " +"securebits。单独创建挂载空间要求 当前用户空间的 ``CAP_SYS_ADMIN``;组合 ``CLONE_NEWUSER | CLONE_NEWNS`` " +"先准备用户空间,再以该候选空间作为新图 owner,任一步失败均整体回滚。" +msgstr "" +"``CLONE_NEWUSER`` creates a user namespace for a clone child or the unshare caller, checking " +"effective UID/GID mappings, chroot, thread groups and allocations before installation. " +"Unshare also prepares independent filesystem state. Any preparation failure rolls back the " +"candidate namespace and paths. Creation preserves global identities, supplementary groups and" +" no_new_privs, and initializes the new namespace capability sets and securebits. Creating " +"only a mount namespace requires ``CAP_SYS_ADMIN`` in the current user namespace. Combined " +"``CLONE_NEWUSER | CLONE_NEWNS`` prepares the user namespace first and uses that candidate as " +"the new graph owner, rolling back both operations on any failure." -msgid "``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 mount 切换时 root 和 cwd 一起替换为目标图当前可见的根,已有文件描述符和 umask 保留。准备失败保留原图与路径。" -msgstr "``setns()`` authenticates the handle using its actual backend, inode and backend pin, then selects the namespace by type. A mount namespace switch sets root and cwd to the target graph visible root and preserves existing FDs and umask. Preparation failure preserves the original graph and paths." +msgid "" +"``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 mount 切换要求当前用户空间的 " +"``CAP_SYS_ADMIN``、``CAP_SYS_CHROOT`` 和 目标图 owner 的 ``CAP_SYS_ADMIN``,并要求独占文件系统状态。root 和 cwd " +"一起替换为目标图当前可见的根,已有文件描述符和 umask 保留。准备失败保留 原图与路径。" +msgstr "" +"``setns()`` authenticates the handle through its actual backend, inode and backend pin, then " +"acquires the target namespace according to its type. Mount joins require ``CAP_SYS_ADMIN`` " +"and ``CAP_SYS_CHROOT`` in the current user namespace, ``CAP_SYS_ADMIN`` in the target graph " +"owner, and exclusively owned filesystem state. Root and cwd are replaced together with the " +"currently visible target graph root. Existing file descriptors and umask are preserved. " +"Preparation failure preserves the original graph and paths." msgid "user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。" msgstr "A user namespace switch requires a single thread, exclusive filesystem state and ``CAP_SYS_ADMIN`` in the target namespace, and rejects reentry into the current namespace. Success preserves root, cwd and global identities and reuses namespace installation to reset capability sets and securebits. Increased scoped authority restricts dumpability and clears the parent-death signal. A NULL pointer represents the initial user namespace. Authenticated handle types and the boolean query distinguish that valid identity from an invalid path." msgid "跟随链接得到分离的 nsfs inode。mount 与 user 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" msgstr "Following a link obtains a detached nsfs inode. Mount and user namespaces share one monotonically increasing sequence. The first display or handle creation assigns an inode, and every handle for that namespace shares this identity. Exhausting the 64-bit sequence returns ``EOVERFLOW``. Labels are ``mnt:[inode]`` or ``user:[inode]``. Each typed backend retains its namespace. Final path release reclaims the backend and drops the namespace reference." + +msgid "" +"每个挂载图持有不可变的 user owner 引用,空指针表示初始用户空间。 ``vfs_namespace_snapshot()`` 和 " +"``vfs_namespace_clone()`` 保留原 owner; ``vfs_namespace_clone_owned()`` 显式选择新图的 owner。owner " +"改变时,shared 副本转为跟随原组的 slave,保留上游传入传播;子图的事件只在其下游传播。" +msgstr "" +"Each mount graph retains an immutable user owner reference, with NULL representing the " +"initial user namespace. ``vfs_namespace_snapshot()`` and ``vfs_namespace_clone()`` preserve " +"the original owner. ``vfs_namespace_clone_owned()`` explicitly selects the new graph owner. " +"When the owner changes, shared copies become slaves of the original group and retain incoming" +" propagation from upstream. Events in the child graph propagate only downstream." + +msgid "" +"跨 owner 快照锁定继承的只读、nosuid、nodev、noexec 和完整 atime 选择。 后端的有效只读状态固化到附件,即使后端后来可写,继承附件仍保持只读。 " +"remount 和 bind-remount 违反这些锁时,在调用后端前返回 ``EPERM``。 现存锁在同 owner 快照和 bind 中继续保留。" +msgstr "" +"Snapshots across owners lock inherited readonly, nosuid, nodev, noexec and the complete atime" +" selection. Effective backend readonly state is fixed on the attachment, so inherited " +"attachments remain readonly even if the backend later becomes writable. A remount or bind-" +"remount that violates these locks returns ``EPERM`` before invoking the backend. Same-owner " +"snapshots and bind mounts preserve existing locks." + +msgid "" +"继承的挂载覆盖关系也被锁定,单独 move、普通卸载或 lazy unmount 返回 ``EINVAL``。非递归 bind 若遗漏继承的锁定子挂载,同样返回 ``EINVAL``; " +"递归 bind 若需要剪除锁定的 unbindable 子树,返回 ``EPERM``。新 bind 根和 跨 owner 传播的新根可整树摘除,其后代继续保留覆盖锁。" +msgstr "" +"Inherited mount coverage is also locked. Moving or individually unmounting such an " +"attachment, including lazy unmount, returns ``EINVAL``. A nonrecursive bind that omits an " +"inherited locked child mount also returns ``EINVAL``. A recursive bind that would prune a " +"locked unbindable subtree returns ``EPERM``. A new bind root or a newly propagated root " +"across owners can be detached as a whole tree, while its descendants retain their coverage " +"locks." + +msgid "" +"bind、bind-remount、move、传播类型修改和卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。新后端创建、共享后端 remount 与新 mount " +"API 当前还要求 初始用户空间的 ``CAP_SYS_ADMIN``;后端 owner 尚待接通。" +msgstr "" +"Bind, bind-remount, move, propagation changes and unmount require ``CAP_SYS_ADMIN`` in the " +"mount graph owner. Fresh backend creation, shared-backend remount and the new mount API " +"currently also require ``CAP_SYS_ADMIN`` in the initial user namespace. Backend ownership " +"remains to be connected." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 1510ae4e..1ea7b14b 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -72,17 +72,26 @@ msgstr "" "including unknown upper bits in the 64-bit argument, return ``EINVAL`` " "without applying any part of the request." -msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` 同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 初始用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。" -msgstr "With ``CLONE_NEWNS``, ``clone()`` and ``clone3()`` copy the mount tree only for the child. Combining it with ``CLONE_FS`` returns ``EINVAL``. Creating a mount namespace with any of these calls requires effective ``CAP_SYS_ADMIN`` in the initial user namespace. Missing authority returns ``EPERM``." +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` 同用,否则返回 " +"``EINVAL``。单独创建挂载命名空间要求当前 用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。" +msgstr "" +"``CLONE_NEWNS`` in ``clone()`` and ``clone3()`` copies the mount tree only for the child. " +"Combining it with ``CLONE_FS`` returns ``EINVAL``. Creating only a mount namespace requires " +"effective ``CAP_SYS_ADMIN`` in the current user namespace and returns ``EPERM`` without that " +"capability." msgid "" -"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | " +"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。新图由创建者的当前用户空间拥有。相同 owner 的快照保留共享传播; 跨 owner 时 " +"shared 转为 slave,只接收原上游事件,并锁定继承的覆盖关系和 只读、nosuid、nodev、noexec、atime 限制。可用 ``MS_REC | " "MS_PRIVATE`` 使子树停止传播。" msgstr "" -"The old and new mount trees share file contents. Root and cwd retain " -"their directory identities, and existing open files are not rebound. " -"Shared mounts can still propagate events; use ``MS_REC | MS_PRIVATE`` to " -"stop propagation for a subtree." +"The original and new mount trees share file contents. Root and cwd retain their original " +"directory identities, and existing open files keep their bindings. The creator's current user" +" namespace owns the new graph. Same-owner snapshots preserve shared propagation. Across " +"owners, shared mounts become slaves that receive events only from the original upstream, and " +"inherited coverage plus readonly, nosuid, nodev, noexec and atime restrictions are locked. " +"``MS_REC | MS_PRIVATE`` stops propagation in the subtree." msgid "bind mount" msgstr "Bind Mounts" @@ -377,11 +386,31 @@ msgstr "``CLONE_NEWUSER`` in ``clone()`` and ``clone3()`` creates a separate use msgid "创建者的有效 UID 和 GID 必须在其当前用户空间有映射,真实 root 必须等于当前 挂载树的根,否则返回 ``EPERM``。最多嵌套 32 层,超过时返回 ``ENOSPC``。 新空间初始 UID/GID 映射为空,通过 :doc:`procfs` 的映射文件建立映射。" msgstr "The creator effective UID and GID must be mapped in its current user namespace, and its actual root must equal the mount tree root. Otherwise creation returns ``EPERM``. Nesting is limited to 32 levels, with ``ENOSPC`` beyond that limit. New UID/GID maps are empty and can be populated through the mapping files described in :doc:`procfs`." -msgid "内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding 能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 用户空间与挂载树组合创建仍要求创建前具备初始用户空间的 ``CAP_SYS_ADMIN``。" -msgstr "Internal UID/GID values, supplementary groups and no_new_privs are retained. In the new namespace, permitted, effective and bounding sets contain every supported capability. Inheritable, ambient and securebits are cleared. Capability checks use namespace scope, and new authority applies to the namespace and its descendants. Unshare preserves dumpability and the parent-death signal. Preparation failure preserves credentials, filesystem sharing and process publication state. Combined user and mount namespace creation still requires initial-user-namespace ``CAP_SYS_ADMIN`` before creation." +msgid "" +"内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding " +"能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 " +"dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 组合 ``CLONE_NEWUSER | CLONE_NEWNS`` 以新用户空间作为新挂载图" +" owner, 使用新空间的能力完成挂载图创建;候选空间或快照准备失败均整体回滚。" +msgstr "" +"Internal UID/GID, supplementary groups and no_new_privs are preserved. The new namespace's " +"permitted, effective and bounding capability sets contain all supported capabilities, while " +"inheritable, ambient and securebits are cleared. Capabilities are checked by namespace scope " +"and apply to the namespace and its descendants. Unshare preserves dumpability and the parent-" +"death signal. Preparation failures preserve original credentials, filesystem sharing state " +"and process publication state. Combined ``CLONE_NEWUSER | CLONE_NEWNS`` makes the new user " +"namespace the new mount graph owner and uses its capabilities to create the graph. Failure to" +" prepare either the candidate namespace or the snapshot rolls back the entire operation." -msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` 句柄。调用者需要初始用户空间中有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" -msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNS)`` accept an ordinary read-only ``/proc//ns/mnt`` handle. The caller needs effective ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` in the initial user namespace or receives ``EPERM``. Sharing ``CLONE_FS`` state with another task returns ``EINVAL``." +msgid "" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` " +"句柄。调用者需要当前用户空间中有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,以及目标挂载图 owner 的 " +"``CAP_SYS_ADMIN``,否则 返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" +msgstr "" +"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNS)`` accept a ``/proc//ns/mnt`` handle opened" +" for ordinary read access. The caller needs effective ``CAP_SYS_ADMIN`` and " +"``CAP_SYS_CHROOT`` in the current user namespace, plus ``CAP_SYS_ADMIN`` in the target mount " +"graph owner, or receives ``EPERM``. Sharing ``CLONE_FS`` state with another task returns " +"``EINVAL``." msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUSER)`` accept an ordinary read-only ``/proc//ns/user`` handle. Joining the current user namespace, having another live thread in the group, or sharing filesystem state with another task returns ``EINVAL``. The caller needs ``CAP_SYS_ADMIN`` in the target user namespace or receives ``EPERM``. Ancestors of the current namespace fail this authority check." @@ -400,3 +429,24 @@ msgstr "A successful user namespace join preserves global UID/GID, supplementary msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount 与 user 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" msgstr "Invalid or ``O_PATH`` FDs return ``EBADF``. A non-nsfs FD, type mismatch or unsupported type returns ``EINVAL``. Mount and user handles are supported. Pidfds and bind mounts of nsfs handles remain pending. See :doc:`../core-api/mount-namespaces`." + +msgid "" +"bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 owner " +"的覆盖挂载不能单独移动或卸载,普通与 lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 ``EINVAL``, 递归 bind 剪除锁定的 " +"unbindable 子树返回 ``EPERM``。新 bind 根与跨 owner 传播的新根允许整树摘除,后代的覆盖锁继续有效。" +msgstr "" +"Bind, bind-remount, move, propagation changes and unmount require ``CAP_SYS_ADMIN`` in the " +"mount graph owner. Covering mounts inherited from another owner cannot be moved or unmounted " +"individually. Both ordinary and lazy unmount return ``EINVAL``. A nonrecursive bind that " +"omits locked child mounts returns ``EINVAL``, and a recursive bind that prunes a locked " +"unbindable subtree returns ``EPERM``. New bind roots and newly propagated roots across owners" +" can be detached as a whole tree, with descendant coverage locks preserved." + +msgid "" +"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略且不调用后端。共享后端 remount、新后端创建和新 " +"mount API 当前还要求初始用户空间的 ``CAP_SYS_ADMIN``。" +msgstr "" +"Clearing inherited readonly, nosuid, nodev or noexec, or changing a locked atime selection, " +"returns ``EPERM`` while preserving attachment policy and without invoking the backend. " +"Shared-backend remount, fresh backend creation and the new mount API currently also require " +"``CAP_SYS_ADMIN`` in the initial user namespace." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index b9b754c1..43ac3fa5 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -124,14 +124,14 @@ msgid "引用释放" msgstr "参照の解放" msgid "" -"``vfs_namespace_clone()`` 返回一个受管理的图引用。最后一个图引用释放时, ``vfs_namespace_retire()``" -" 就地摘除整棵树而不传播卸载,随后释放图本身。已持有 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 " -"``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。" +"``vfs_namespace_clone()`` 返回一个受管理的图引用。最后一个图引用释放时, ``vfs_namespace_retire()`` " +"就地摘除整棵树而不传播卸载,随后释放图本身。已持有 的路径继续有效,后端由现有的延迟清理队列处理。启动图和测试图的存储仍由调用方 管理;严格的 " +"``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。 快照全部准备成功后才持有 owner 引用,图退役或销毁时释放它。" msgstr "" -"``vfs_namespace_clone()`` は管理対象グラフへの参照を一つ返します。最後の参照を解放すると、 " -"``vfs_namespace_retire()`` " -"がアンマウントを伝播させずにツリー全体を切り離し、その後グラフ自体を解放します。保持中のパスは有効なままで、既存の遅延処理キューがバックエンドを後処理します。起動時とテスト用のグラフの記憶領域は引き続き呼び出し側が管理します。厳格な" -" ``vfs_namespace_destroy()`` はグラフの参照や外部パス参照が残っている間は破棄を拒否します。" +"``vfs_namespace_clone()`` は管理対象グラフの参照を返します。最後のグラフ参照を解放すると、``vfs_namespace_retire()`` " +"はアンマウントを伝播せずツリー全体をその場で切り離し、グラフ自体を解放します。保持済みパスは有効なままで、バックエンドは既存の遅延クリーンアップキューで処理します。起動用およびテスト用グラフのストレージは呼び出し元が管理します。厳密な" +" ``vfs_namespace_destroy()`` はグラフ参照や外部パス参照が残る間は破棄を拒否します。スナップショットは準備がすべて成功してから owner " +"参照を取得し、グラフの退役または破棄時に解放します。" msgid "游离挂载路径" msgstr "切り離されたマウントのパス" @@ -148,8 +148,19 @@ msgstr "資格情報のケーパビリティの適用範囲" msgid "任务凭据持有引用计数的用户命名空间,空指针表示初始空间。任务 UID/GID 使用 全局内核 ID。子空间记录创建者的有效 UID,并持有父空间引用,层级上限为 32。 fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 释放。清理登录身份继续保留所属空间。" msgstr "タスクの資格情報は参照カウント付きのユーザー名前空間を保持します。NULL ポインターは初期名前空間を表します。タスクの UID と GID はグローバルなカーネル ID です。子名前空間は作成者の実効 UID を記録し、親の参照を保持します。入れ子の上限は 32 です。fork とカーネルによるタスク起動は参照を継承し、exec では参照を維持します。ゾンビタスクの参照は wait による回収時またはタスクスロットの再利用時に解放されます。ログイン ID を消去しても所属名前空間は維持されます。" -msgid "文件系统 DAC 特权覆盖、挂载图管理、设备、网络、IPC、时钟、重启、模块、内存锁定 和 OOM 调整等共享资源使用初始空间能力。信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。" -msgstr "ファイルシステムの DAC の上書き、マウントグラフの管理、デバイス、ネットワーク、IPC、システムクロック、再起動、モジュール、メモリロック、OOM 調整などの共有資源には、初期名前空間のケーパビリティが必要です。シグナル、プロセス優先度、別プロセスのリソース制限、ptrace のケーパビリティによる認可は、対象タスクが所属する名前空間で行います。ハードリミットの引き上げには引き続き初期名前空間のケーパビリティが必要です。ケーパビリティは子孫の名前空間にも適用されます。子名前空間の所有者と実効 UID が一致する親名前空間のタスクは、その子のサブツリーでケーパビリティを持ちます。ptrace でケーパビリティの部分集合を確認する際は、両タスクが同じユーザー名前空間に属する必要があります。capset、ID の変更、securebits、seccomp の設定には、呼び出し元が所属する名前空間のケーパビリティを使います。" +msgid "" +"挂载图管理按图 owner 授权。文件系统 DAC 特权覆盖、共享文件系统后端、设备、 网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 " +"信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner " +"相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp " +"安装使用调用方所属空间的能力集合。" +msgstr "" +"マウントグラフの管理権限はグラフの owner に対して検査します。ファイルシステム DAC " +"の特権回避、共有ファイルシステムバックエンド、デバイス、ネットワーク、IPC、時計、再起動、モジュール、メモリロック、および OOM 調整などの共有資源には初期名前空間の " +"capability を使用します。シグナル、プロセス優先度、プロセス間の資源制限、および ptrace " +"は対象タスクの名前空間に対して権限を検査します。ハード資源制限の引き上げには引き続き初期名前空間の capability が必要です。capability " +"は子孫の名前空間にも適用され、親名前空間の実効 UID が子名前空間の owner と一致するタスクは、そのサブツリーに対する capability を持ちます。ptrace の " +"capability 部分集合検査には同一ユーザー名前空間が必要です。capset、ID 変更、securebits、および seccomp のインストールには呼び出し元の名前空間の " +"capability 集合を使用します。" msgid "" "空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID 转换为全局内核 ID;转换接口通过 acquire " @@ -289,14 +300,65 @@ msgstr "``IPC_SET`` は既存のオブジェクト所有権とリソース制限 msgid "``/proc//ns/mnt`` 与 ``/proc//ns/user`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图或用户空间。" msgstr "``/proc//ns/mnt`` と ``/proc//ns/user`` は proc magic link です。読み取りと追跡には ``/proc//fd`` と同じ ``PTRACE_MODE_READ_FSCREDS`` 検査が必要です。リンクキーは PID の同一性を保持します。追跡が成功するたびに対象タスクの現在のマウントグラフまたはユーザー名前空間を取得します。" -msgid "``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare 同时准备独立的文件系统 状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 no_new_privs,并初始化新空间的能力集合及 securebits。组合 ``CLONE_NEWNS`` 创建仍检查初始用户空间中的 ``CAP_SYS_ADMIN``。" -msgstr "``CLONE_NEWUSER`` は clone の子タスクまたは unshare の呼び出し元にユーザー名前空間を作成します。設定前に有効 UID/GID のマッピング、chroot、スレッドグループ、割り当ての検査を完了します。unshare は独立したファイルシステム状態も準備します。準備に失敗した場合は候補の名前空間とパスを解放します。作成時はグローバル ID、補助グループ、no_new_privs を保持し、新しい空間の能力集合と securebits を初期化します。``CLONE_NEWNS`` と組み合わせた作成には引き続き初期ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要です。" +msgid "" +"``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare " +"同时准备独立的文件系统 状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 no_new_privs,并初始化新空间的能力集合及 " +"securebits。单独创建挂载空间要求 当前用户空间的 ``CAP_SYS_ADMIN``;组合 ``CLONE_NEWUSER | CLONE_NEWNS`` " +"先准备用户空间,再以该候选空间作为新图 owner,任一步失败均整体回滚。" +msgstr "" +"``CLONE_NEWUSER`` は clone の子タスクまたは unshare の呼び出し元にユーザー名前空間を作成し、インストール前に実効 UID/GID " +"マッピング、chroot、スレッドグループ、および割り当てを検査します。unshare " +"は独立したファイルシステム状態も準備します。準備に失敗すると候補の名前空間とパスをロールバックします。作成時にはグローバル ID、補助グループ、no_new_privs " +"を保持し、新しい名前空間の capability 集合と securebits を初期化します。マウント名前空間だけの作成には現在のユーザー名前空間の ``CAP_SYS_ADMIN``" +" が必要です。``CLONE_NEWUSER | CLONE_NEWNS`` の組み合わせでは先にユーザー名前空間を準備し、その候補を新しいグラフの owner " +"とします。どちらかが失敗すると全体をロールバックします。" -msgid "``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 mount 切换时 root 和 cwd 一起替换为目标图当前可见的根,已有文件描述符和 umask 保留。准备失败保留原图与路径。" -msgstr "``setns()`` は実際のバックエンド、inode、バックエンド pin でハンドルを認証し、型に応じて対象の名前空間を選びます。mount の切り替えでは root と cwd を対象グラフの可視ルートに設定し、既存の FD と umask を保持します。準備に失敗した場合は元のグラフとパスを保持します。" +msgid "" +"``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 mount 切换要求当前用户空间的 " +"``CAP_SYS_ADMIN``、``CAP_SYS_CHROOT`` 和 目标图 owner 的 ``CAP_SYS_ADMIN``,并要求独占文件系统状态。root 和 cwd " +"一起替换为目标图当前可见的根,已有文件描述符和 umask 保留。准备失败保留 原图与路径。" +msgstr "" +"``setns()`` は実際のバックエンド、inode、およびバックエンド pin でハンドルを認証し、型に応じて対象の名前空間を取得します。mount " +"の切り替えには、現在のユーザー名前空間の ``CAP_SYS_ADMIN`` と ``CAP_SYS_CHROOT``、対象グラフの owner における " +"``CAP_SYS_ADMIN``、およびファイルシステム状態の独占が必要です。root と cwd は対象グラフの現在見えるルートへ同時に置き換わり、既存のファイル記述子と umask" +" は保持されます。準備に失敗すると元のグラフとパスを維持します。" msgid "user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。" msgstr "user の切り替えには単一スレッド、ファイルシステム状態の独占、対象名前空間の ``CAP_SYS_ADMIN`` が必要で、現在の名前空間への再参加は拒否します。成功時は root、cwd、グローバル ID を保持し、ユーザー名前空間の設定処理を再利用して能力集合と securebits をリセットします。作用域内の権限が増加するとダンプ可能性を制限し、親死亡シグナルを解除します。初期ユーザー名前空間は空ポインタで表し、ハンドル型の認証と真偽値の照会でこの有効な ID と無効なパスを区別します。" msgid "跟随链接得到分离的 nsfs inode。mount 与 user 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" msgstr "リンクをたどると独立した nsfs inode を取得します。mount と user の名前空間は単調増加する共通の採番列を使います。最初の表示またはハンドル作成時に inode を割り当て、同じ名前空間のすべてのハンドルがその ID を共有します。64 ビットの採番列を使い切ると ``EOVERFLOW`` を返します。表示は ``mnt:[inode]`` または ``user:[inode]`` です。各バックエンドは型に応じた名前空間の参照を持ち、最後のパス解放時にバックエンドを回収して名前空間の参照を解放します。" + +msgid "" +"每个挂载图持有不可变的 user owner 引用,空指针表示初始用户空间。 ``vfs_namespace_snapshot()`` 和 " +"``vfs_namespace_clone()`` 保留原 owner; ``vfs_namespace_clone_owned()`` 显式选择新图的 owner。owner " +"改变时,shared 副本转为跟随原组的 slave,保留上游传入传播;子图的事件只在其下游传播。" +msgstr "" +"各マウントグラフは不変の user owner 参照を保持し、NULL は初期ユーザー名前空間を表します。``vfs_namespace_snapshot()`` と " +"``vfs_namespace_clone()`` は元の owner を保持し、``vfs_namespace_clone_owned()`` は新しいグラフの owner " +"を明示的に選択します。owner が変わると shared のコピーは元のグループに従う slave となり、上流からの伝播を受け続けます。子グラフのイベントは下流にのみ伝播します。" + +msgid "" +"跨 owner 快照锁定继承的只读、nosuid、nodev、noexec 和完整 atime 选择。 后端的有效只读状态固化到附件,即使后端后来可写,继承附件仍保持只读。 " +"remount 和 bind-remount 违反这些锁时,在调用后端前返回 ``EPERM``。 现存锁在同 owner 快照和 bind 中继续保留。" +msgstr "" +"owner をまたぐスナップショットは、継承した読み取り専用、nosuid、nodev、noexec、および atime " +"の選択全体をロックします。バックエンドの実効的な読み取り専用状態をアタッチメントに固定するため、バックエンドが後で書き込み可能になっても継承先は読み取り専用を維持します。これらのロックに違反する" +" remount と bind-remount は、バックエンドを呼び出す前に ``EPERM`` を返します。同一 owner のスナップショットと bind " +"も既存のロックを保持します。" + +msgid "" +"继承的挂载覆盖关系也被锁定,单独 move、普通卸载或 lazy unmount 返回 ``EINVAL``。非递归 bind 若遗漏继承的锁定子挂载,同样返回 ``EINVAL``; " +"递归 bind 若需要剪除锁定的 unbindable 子树,返回 ``EPERM``。新 bind 根和 跨 owner 传播的新根可整树摘除,其后代继续保留覆盖锁。" +msgstr "" +"継承したマウントの被覆関係もロックされます。個別の move、通常のアンマウント、および lazy unmount は ``EINVAL`` を返します。非再帰 bind " +"が継承したロック済み子マウントを省略する場合も ``EINVAL`` を返します。再帰 bind がロック済み unbindable サブツリーを除外する場合は ``EPERM`` " +"を返します。新しい bind ルートと owner をまたいで伝播した新しいルートはツリー全体として切り離せますが、子孫の被覆ロックは維持されます。" + +msgid "" +"bind、bind-remount、move、传播类型修改和卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。新后端创建、共享后端 remount 与新 mount " +"API 当前还要求 初始用户空间的 ``CAP_SYS_ADMIN``;后端 owner 尚待接通。" +msgstr "" +"bind、bind-remount、move、伝播タイプ変更、およびアンマウントには、マウントグラフの owner における ``CAP_SYS_ADMIN`` " +"が必要です。新規バックエンド作成、共有バックエンドの remount、および新しい mount API には、現在は初期ユーザー名前空間の ``CAP_SYS_ADMIN`` " +"も必要です。バックエンドの owner は今後接続します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 303dadde..9b3905d1 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -65,16 +65,24 @@ msgstr "" "の共有だけを解除し、マウントツリーは複製しません。フラグがゼロなら状態は変わりません。64 " "ビット引数の未知の上位ビットを含む未対応フラグを指定した場合は、要求を部分的に適用することなく ``EINVAL`` を返します。" -msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` 同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 初始用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。" -msgstr "``clone()`` と ``clone3()`` の ``CLONE_NEWNS`` は子タスク用にマウントツリーを複製します。``CLONE_FS`` との組み合わせは ``EINVAL`` を返します。これらのマウント名前空間作成操作には初期ユーザー名前空間で有効な ``CAP_SYS_ADMIN`` が必要で、権限が不足すると ``EPERM`` を返します。" +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` 同用,否则返回 " +"``EINVAL``。单独创建挂载命名空间要求当前 用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。" +msgstr "" +"``clone()`` と ``clone3()`` の ``CLONE_NEWNS`` は子タスクだけにマウントツリーをコピーします。``CLONE_FS`` との併用は " +"``EINVAL`` を返します。マウント名前空間だけの作成には現在のユーザー名前空間における実効 ``CAP_SYS_ADMIN`` が必要で、なければ ``EPERM`` " +"を返します。" msgid "" -"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。共享挂载仍可传播事件;可用 ``MS_REC | " +"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。新图由创建者的当前用户空间拥有。相同 owner 的快照保留共享传播; 跨 owner 时 " +"shared 转为 slave,只接收原上游事件,并锁定继承的覆盖关系和 只读、nosuid、nodev、noexec、atime 限制。可用 ``MS_REC | " "MS_PRIVATE`` 使子树停止传播。" msgstr "" -"新旧のマウントツリーはファイルの内容を共有します。root と cwd " -"は元のディレクトリを指し、既に開いているファイルの参照先は変わりません。共有マウントでは引き続きイベントが伝播します。サブツリーの伝播を止めるには" -" ``MS_REC | MS_PRIVATE`` を使用します。" +"新旧のマウントツリーはファイル内容を共有します。root と cwd " +"は元のディレクトリの同一性を保持し、既存のオープンファイルの結び付けも維持されます。作成者の現在のユーザー名前空間が新しいグラフを所有します。同一 owner " +"のスナップショットは共有伝播を保持します。owner をまたぐ場合、shared は元の上流からのみイベントを受ける slave " +"となり、継承した被覆関係と読み取り専用、nosuid、nodev、noexec、atime の制限がロックされます。``MS_REC | MS_PRIVATE`` " +"でサブツリーの伝播を停止できます。" msgid "bind mount" msgstr "bind mount" @@ -335,11 +343,28 @@ msgstr "``clone()`` と ``clone3()`` の ``CLONE_NEWUSER`` は子タスク用に msgid "创建者的有效 UID 和 GID 必须在其当前用户空间有映射,真实 root 必须等于当前 挂载树的根,否则返回 ``EPERM``。最多嵌套 32 层,超过时返回 ``ENOSPC``。 新空间初始 UID/GID 映射为空,通过 :doc:`procfs` 的映射文件建立映射。" msgstr "作成者の実効 UID と GID は現在のユーザー名前空間にマッピングされ、実際の root はマウントツリーのルートと一致する必要があります。条件を満たさない場合は ``EPERM`` を返します。ネストは 32 階層までで、超過すると ``ENOSPC`` を返します。新しい UID/GID マップは空で、:doc:`procfs` のマッピングファイルで設定できます。" -msgid "内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding 能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 用户空间与挂载树组合创建仍要求创建前具备初始用户空间的 ``CAP_SYS_ADMIN``。" -msgstr "内部 UID/GID、補助グループ、no_new_privs は保持されます。新しい名前空間の permitted、effective、bounding 集合には対応するすべての能力が含まれ、inheritable、ambient、securebits はクリアされます。能力は名前空間のスコープで検査され、新しい権限はその空間と子孫に適用されます。unshare は dumpability と親死亡シグナルを保持します。準備失敗時は資格情報、ファイルシステム共有、プロセス公開状態を保持します。ユーザーとマウント名前空間の同時作成には、作成前の初期ユーザー名前空間での ``CAP_SYS_ADMIN`` が引き続き必要です。" +msgid "" +"内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding " +"能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 " +"dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 组合 ``CLONE_NEWUSER | CLONE_NEWNS`` 以新用户空间作为新挂载图" +" owner, 使用新空间的能力完成挂载图创建;候选空间或快照准备失败均整体回滚。" +msgstr "" +"内部 UID/GID、補助グループ、および no_new_privs は保持されます。新しい名前空間の permitted、effective、bounding capability " +"集合には対応済みの全 capability が入り、inheritable、ambient、securebits はクリアされます。capability " +"は名前空間のスコープに従って検査し、その名前空間と子孫に適用します。unshare は dumpability " +"と親死亡シグナルを保持します。準備失敗時は元の資格情報、ファイルシステム共有状態、およびプロセス公開状態を維持します。``CLONE_NEWUSER | CLONE_NEWNS`` " +"の組み合わせでは新しいユーザー名前空間を新しいマウントグラフの owner とし、その capability " +"でグラフを作成します。候補名前空間またはスナップショットの準備に失敗すると全体をロールバックします。" -msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` 句柄。调用者需要初始用户空间中有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" -msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNS)`` は通常の読み取り専用 ``/proc//ns/mnt`` ハンドルを受け付けます。呼び出し元には初期ユーザー名前空間の有効な ``CAP_SYS_ADMIN`` と ``CAP_SYS_CHROOT`` が必要で、欠けていれば ``EPERM`` を返します。他のタスクと ``CLONE_FS`` 状態を共有している場合は ``EINVAL`` を返します。" +msgid "" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` " +"句柄。调用者需要当前用户空间中有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,以及目标挂载图 owner 的 " +"``CAP_SYS_ADMIN``,否则 返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" +msgstr "" +"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNS)`` は、通常の読み取り専用で開いた ``/proc//ns/mnt`` " +"ハンドルを受け付けます。呼び出し元には現在のユーザー名前空間の実効 ``CAP_SYS_ADMIN`` と ``CAP_SYS_CHROOT``、および対象マウントグラフの owner " +"における ``CAP_SYS_ADMIN`` が必要で、満たさなければ ``EPERM`` を返します。他タスクと ``CLONE_FS`` 状態を共有している場合は " +"``EINVAL`` を返します。" msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUSER)`` は通常の読み取り専用 ``/proc//ns/user`` ハンドルを受け付けます。現在のユーザー名前空間への再参加、同じグループの別の活動中スレッド、他のタスクとのファイルシステム状態の共有は ``EINVAL`` になります。対象ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。現在の名前空間の祖先はこの権限検査を通過できません。" @@ -358,3 +383,21 @@ msgstr "ユーザー名前空間への参加が成功すると、グローバル msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount 与 user 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" msgstr "無効な FD と ``O_PATH`` FD は ``EBADF`` を返します。nsfs 以外の FD、型の不一致、未対応の型は ``EINVAL`` を返します。mount と user のハンドルに対応します。pidfd と nsfs ハンドルの bind mount は未接続です。:doc:`../core-api/mount-namespaces` を参照してください。" + +msgid "" +"bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 owner " +"的覆盖挂载不能单独移动或卸载,普通与 lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 ``EINVAL``, 递归 bind 剪除锁定的 " +"unbindable 子树返回 ``EPERM``。新 bind 根与跨 owner 传播的新根允许整树摘除,后代的覆盖锁继续有效。" +msgstr "" +"bind、bind-remount、move、伝播タイプ変更、およびアンマウントには、マウントグラフの owner における ``CAP_SYS_ADMIN`` が必要です。他の " +"owner から継承した被覆マウントは個別に移動またはアンマウントできず、通常のアンマウントも lazy unmount も ``EINVAL`` を返します。非再帰 bind " +"がロック済み子マウントを省略すると ``EINVAL``、再帰 bind がロック済み unbindable サブツリーを除外すると ``EPERM`` を返します。新しい bind " +"ルートと owner をまたいで伝播した新しいルートはツリー全体として切り離せますが、子孫の被覆ロックは保持されます。" + +msgid "" +"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略且不调用后端。共享后端 remount、新后端创建和新 " +"mount API 当前还要求初始用户空间的 ``CAP_SYS_ADMIN``。" +msgstr "" +"継承した読み取り専用、nosuid、nodev、noexec を解除するか、ロック済み atime 選択を変更すると ``EPERM`` " +"を返し、アタッチメントポリシーを維持してバックエンドを呼び出しません。共有バックエンドの remount、新規バックエンド作成、および新しい mount API " +"には、現在は初期ユーザー名前空間の ``CAP_SYS_ADMIN`` も必要です。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 8397f00c..c4964739 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -59,11 +59,14 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 返回 ``EINVAL``,不会部分应用请求。 ``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 -``CLONE_FS`` 同用,否则返回 ``EINVAL``。上述创建挂载命名空间的操作均要求 -初始用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。 +``CLONE_FS`` 同用,否则返回 ``EINVAL``。单独创建挂载命名空间要求当前 +用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。 新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 -绑定。共享挂载仍可传播事件;可用 ``MS_REC | MS_PRIVATE`` 使子树停止传播。 +绑定。新图由创建者的当前用户空间拥有。相同 owner 的快照保留共享传播; +跨 owner 时 shared 转为 slave,只接收原上游事件,并锁定继承的覆盖关系和 +只读、nosuid、nodev、noexec、atime 限制。可用 ``MS_REC | MS_PRIVATE`` +使子树停止传播。 创建用户命名空间 ================ @@ -81,14 +84,16 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 bounding 能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 -用户空间与挂载树组合创建仍要求创建前具备初始用户空间的 ``CAP_SYS_ADMIN``。 +组合 ``CLONE_NEWUSER | CLONE_NEWNS`` 以新用户空间作为新挂载图 owner, +使用新空间的能力完成挂载图创建;候选空间或快照准备失败均整体回滚。 加入命名空间 ============ ``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 -``/proc//ns/mnt`` 句柄。调用者需要初始用户空间中有效的 ``CAP_SYS_ADMIN`` -和 ``CAP_SYS_CHROOT``,否则返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` +``/proc//ns/mnt`` 句柄。调用者需要当前用户空间中有效的 ``CAP_SYS_ADMIN`` +和 ``CAP_SYS_CHROOT``,以及目标挂载图 owner 的 ``CAP_SYS_ADMIN``,否则 +返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。 切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 @@ -132,11 +137,21 @@ bind mount 挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。 +bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 +``CAP_SYS_ADMIN``。继承自其他 owner 的覆盖挂载不能单独移动或卸载,普通与 +lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 ``EINVAL``, +递归 bind 剪除锁定的 unbindable 子树返回 ``EPERM``。新 bind 根与跨 owner +传播的新根允许整树摘除,后代的覆盖锁继续有效。 + ``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。 +清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 +``EPERM``,保留附件策略且不调用后端。共享后端 remount、新后端创建和新 +mount API 当前还要求初始用户空间的 ``CAP_SYS_ADMIN``。 + 只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。 diff --git a/fs/vfs/file.c b/fs/vfs/file.c index 48b97129..099d36b0 100644 --- a/fs/vfs/file.c +++ b/fs/vfs/file.c @@ -130,6 +130,7 @@ uint64_t vfs_path_mount_flags(const struct vfs_path *path) * @param flags Only per-mount bits and optional strictatime selector. * @return Zero or negative state/unsupported errno, preserving state on error. * A lazily detached attachment keeps its policy until retirement. + * Inherited policy-lock changes return EPERM before publication. * Pure execution-owned publication, no callbacks/allocation/ownership change. */ int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags) @@ -137,7 +138,9 @@ int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags) if(!mount || !mount->references)return -EINVAL; if(mount->ns || mount->point.mount || mount->lazy_detached || mount->exposed_detached)return -EBUSY; if(flags&~(VFS_MOUNT_POLICY_MASK|MS_STRICTATIME))return -EOPNOTSUPP; - mount->policy=vfs_policy_bits(flags);return 0; + uint64_t policy=vfs_policy_bits(flags); + if((policy^mount->policy)&mount->locked_policy)return -EPERM; + mount->policy=policy;return 0; } /** @brief Change only the exact attached root's policy for MS_BIND|MS_REMOUNT. @@ -148,6 +151,7 @@ int vfs_mount_set_flags(struct vfs_mount *mount,uint64_t flags) * or EBUSY for a readonly transition with local writers. Validation and * policy publication are serialized by execution ownership, with no backend * reconfiguration. Omitted atime flags preserve the attachment's selection. + * Inherited restriction or atime-lock changes return EPERM before mutation. */ int vfs_path_bind_remount(const struct vfs_path *path,uint64_t flags) { @@ -159,6 +163,7 @@ int vfs_path_bind_remount(const struct vfs_path *path,uint64_t flags) else if(flags&MS_NOATIME)flags&=~MS_RELATIME; else flags|=MS_RELATIME; uint64_t policy=vfs_policy_bits(flags); + if((policy^mount->policy)&mount->locked_policy)return -EPERM; if(mount->writers && (policy&MS_RDONLY) && !(vfs_path_mount_flags(path)&MS_RDONLY))return -EBUSY; mount->policy=policy; vfs_namespace_changed(mount->ns); @@ -168,10 +173,12 @@ int vfs_path_bind_remount(const struct vfs_path *path,uint64_t flags) /** @brief Reconfigure the selected attachment after shared backend preparation. * @param path Borrowed attached or exposed unpublished filesystem root. * @param flags Requested supported MS flags; omitted atime preserves old bits. + * @param options Optional copied filesystem-specific configuration. * @return Zero or input/unsupported/readonly/backend errno. Failed preparation * leaves mount policy unchanged. Execution ownership required; no graph/module * lock spans the optional shared-policy callback. Strictatime clears noatime * and relatime. All other attachment policy changes affect this mount alone. + * Inherited lock violations return EPERM before any backend callback. */ static int vfs_remount(const struct vfs_path *path,uint64_t flags,const char *options) { @@ -182,6 +189,7 @@ static int vfs_remount(const struct vfs_path *path,uint64_t flags,const char *op const uint64_t atime=MS_NOATIME|MS_NODIRATIME|MS_RELATIME; uint64_t policy=vfs_policy_bits(flags),shared=flags&VFS_SUPER_POLICY_MASK; if(!(flags&(atime|MS_STRICTATIME)))policy|=mount->policy&atime; + if((policy^mount->policy)&mount->locked_policy)return -EPERM; int rc=0; if(mount->ops->remount_options) rc=mount->ops->remount_options(mount->context,shared,options); diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 3bba58a4..6c32adff 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -44,6 +44,7 @@ struct vfs_mount { void *context; struct module *owner; uint64_t references,id,policy,peer_group; /* Zero group is not shared. */ + uint64_t locked_policy; /* Inherited restrictions and exact atime selection. */ uint64_t staged_peer_group; /* Tentative group of an original mount during MS_MOVE. */ uint64_t propagation_pins; /* Shared backend lifetime references, not open paths. */ uint64_t writers; /* Open writable file descriptions on this attachment. */ @@ -51,6 +52,7 @@ struct vfs_mount { bool unmount_selected; /* Scratch under the VFS execution writer. */ bool propagation_copy; /* Receiver can detach beneath an unrelated root cover. */ bool unbindable; /* Pruned by recursive bind; never a valid bind source. */ + bool locked_topology; /* This inherited cover cannot be removed independently. */ bool lazy_detached; /* No namespace edges; retained paths still work. */ bool exposed_detached; /* Unpublished root explicitly handed to a caller. */ char *source,*filesystem; diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index b30c81d2..b80550dd 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -3,6 +3,7 @@ #include #include #include +#include /* Standalone VFS fixtures can omit the scheduler's poll wait queue. */ extern void kernel_poll_readiness_notify(void) __attribute__((weak)); @@ -97,6 +98,10 @@ bool vfs_path_equal(const struct vfs_path *left,const struct vfs_path *right) bool vfs_path_is_mount_root(const struct vfs_path *path) {return vfs_path_valid(path) && path->dentry==path->mount->root;} +/** @copydoc vfs_path_mount_locked */ +bool vfs_path_mount_locked(const struct vfs_path *path) +{return vfs_path_valid(path) && path->mount->locked_topology;} + const struct storage_node *vfs_path_node(const struct vfs_path *path) {return vfs_path_valid(path) ? &path->dentry->node : NULL;} void *vfs_path_context(const struct vfs_path *path) @@ -440,6 +445,7 @@ static int vfs_bind_clone(const struct vfs_path *view,const struct vfs_path *bac if(!mount){module_put(original->owner);return -ENOMEM;} *mount=(struct vfs_mount){.ops=original->ops,.context=original->context, .owner=original->owner,.references=1,.root=view->dentry,.policy=original->policy, + .locked_policy=original->locked_policy,.locked_topology=original->locked_topology, .propagation_backing=propagation}; vfs_path_get(backing,&mount->bind_source); if(propagation)++backing->mount->propagation_pins; @@ -571,20 +577,35 @@ static void vfs_snapshot_rebind(struct vfs_path *path,struct vfs_mount *copy) vfs_path_get(&replacement,path);vfs_path_put(&old); } +/** @brief Preserve restrictions and coverage inherited from another owner. + * @param mount Private staged attachment under execution ownership. + * Captures effective readonly before locking policy, including all atime bits. + * No allocation or backend changes. Existing locks remain in force. + */ +static void vfs_lock_inherited_mount(struct vfs_mount *mount) +{ + mount->policy|=vfs_super_flags(mount)&MS_RDONLY; + mount->locked_policy|=(mount->policy&(MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC))| + MS_NOATIME|MS_NODIRATIME|MS_RELATIME; + mount->locked_topology=true; +} + /** @brief Clone every attachment and then publish exact graph relationships. * @param dest Empty caller-owned namespace at its final address. * @param source Live source graph, stable under execution ownership. + * @param owner Borrowed authority scope retained only after staging succeeds. * @param root Optional owned task root to rebind, empty or detached allowed. * @param cwd Optional owned working directory to rebind, empty or detached allowed. * @return Zero or negative errno before publishing any change. Copies retain * the native backing, not intermediate attachment references. Topology is - * translated and the copies join their original peers and upstream groups - * only after every allocation succeeds. + * translated only after every allocation succeeds. Changing authority turns + * shared mounts into downstream slaves and locks inherited restrictions. */ -int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace *source, - struct vfs_path *root,struct vfs_path *cwd) +static int vfs_namespace_snapshot_owned(struct vfs_namespace *dest,const struct vfs_namespace *source, + struct user_namespace *owner, + struct vfs_path *root,struct vfs_path *cwd) { - if(!dest || !source || dest->root || dest->mounts || !source->root)return -EINVAL; + if(!dest || !source || dest->root || dest->mounts || dest->user_ns || !source->root)return -EINVAL; if(root==cwd)cwd=NULL; int rc=vfs_snapshot_path_check(source,root); if(!rc)rc=vfs_snapshot_path_check(source,cwd); @@ -610,22 +631,32 @@ int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace struct vfs_mount *copy=batch.pending; for(const struct vfs_mount *mount=source->mounts;mount;mount=mount->next,copy=copy->next) { copy->id=--id; - copy->peer_group=mount->peer_group; + bool different_owner=owner!=source->user_ns; + copy->peer_group=different_owner ? 0 : mount->peer_group; copy->unbindable=mount->unbindable; copy->propagation_copy=mount->propagation_copy; - copy->master=mount->master; + copy->master=different_owner && mount->peer_group ? (struct vfs_mount *)mount : mount->master; + if(different_owner)vfs_lock_inherited_mount(copy); struct vfs_path point={vfs_snapshot_mount(source->mounts,batch.pending,mount->point.mount), mount->point.dentry}; vfs_path_get(&point,©->point); } struct vfs_mount *root_copy=root ? vfs_snapshot_mount(source->mounts,batch.pending,root->mount) : NULL; struct vfs_mount *cwd_copy=cwd ? vfs_snapshot_mount(source->mounts,batch.pending,cwd->mount) : NULL; + dest->user_ns=user_namespace_get(owner); dest->root=vfs_snapshot_mount(source->mounts,batch.pending,source->root); vfs_finish_mount_batch(dest,&batch,0); vfs_snapshot_rebind(root,root_copy);vfs_snapshot_rebind(cwd,cwd_copy); return 0; } +/** @copydoc vfs_namespace_snapshot */ +int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace *source, + struct vfs_path *root,struct vfs_path *cwd) +{ + return vfs_namespace_snapshot_owned(dest,source,source ? source->user_ns : NULL,root,cwd); +} + /** @brief Retire and free a heap-owned graph when its last reference is gone. * @param ns Managed namespace with zero remaining references, execution-owned. * Mounts and backends may outlive it through ordinary paths and deferred puts. @@ -643,11 +674,18 @@ static void vfs_namespace_release_snapshot(struct vfs_namespace *ns) */ int vfs_namespace_clone(const struct vfs_namespace *source,struct vfs_path *root, struct vfs_path *cwd,struct vfs_namespace **out) +{ + return vfs_namespace_clone_owned(source,source ? source->user_ns : NULL,root,cwd,out); +} + +/** @copydoc vfs_namespace_clone_owned */ +int vfs_namespace_clone_owned(const struct vfs_namespace *source,struct user_namespace *owner, + struct vfs_path *root,struct vfs_path *cwd,struct vfs_namespace **out) { if(!out)return -EINVAL;*out=NULL; struct vfs_namespace *ns=kernel_malloc(sizeof(*ns));if(!ns)return -ENOMEM; *ns=(struct vfs_namespace){0}; - int rc=vfs_namespace_snapshot(ns,source,root,cwd); + int rc=vfs_namespace_snapshot_owned(ns,source,owner,root,cwd); if(rc){kernel_free(ns);return rc;} ns->release=vfs_namespace_release_snapshot; *out=vfs_namespace_get(ns);return 0; @@ -736,16 +774,21 @@ static struct vfs_mount *vfs_staged_peer(const struct vfs_mount_batch *batch, /** @brief Find the next direct submount within the selected directory view. * @param view The original mount and the directory bounding its subtree. * @param candidate Start of a suffix of the unchanged namespace mount list. - * @return Borrowed matching bindable attachment or NULL. An unbindable - * attachment prunes its branch; a mount through another attachment is not - * part of the view even when its backing dentry is shared. + * @param out Receives a borrowed bindable child or NULL at the end. + * @return Zero or EPERM when pruning an inherited locked unbindable cover + * would expose underlying content. An unlocked unbindable branch is skipped. */ -static struct vfs_mount *vfs_bind_child_mount(const struct vfs_path *view,struct vfs_mount *candidate) +static int vfs_bind_child_mount(const struct vfs_path *view,struct vfs_mount *candidate, + struct vfs_mount **out) { - for(;candidate;candidate=candidate->next) - if(candidate->point.mount==view->mount && !candidate->unbindable && - vfs_dentry_below(candidate->point.dentry,view->dentry))return candidate; - return NULL; + *out=NULL; + for(;candidate;candidate=candidate->next) { + if(candidate->point.mount!=view->mount || + !vfs_dentry_below(candidate->point.dentry,view->dentry))continue; + if(!candidate->unbindable){*out=candidate;return 0;} + if(candidate->locked_topology)return -EPERM; + } + return 0; } enum vfs_mount_copy { VFS_COPY_BIND,VFS_COPY_PEER,VFS_COPY_SLAVE }; @@ -758,12 +801,13 @@ enum vfs_mount_copy { VFS_COPY_BIND,VFS_COPY_PEER,VFS_COPY_SLAVE }; * @param recursive True to copy bindable child mounts. * @param shared True if the destination parent is shared. * @param kind A direct bind, or a replay sharing or following the source group. + * @param lock_tree Lock copies crossing from the event owner's authority. * @param out Receives the staged tree root, possibly NULL on failure. * @return Zero or negative errno. No backend graph changes or path replay. */ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_path *source, const struct vfs_path *target,struct vfs_mount *mounts, - bool recursive,bool shared,enum vfs_mount_copy kind, + bool recursive,bool shared,enum vfs_mount_copy kind,bool lock_tree, struct vfs_mount **out) { struct vfs_path view=*source,point=*target; @@ -788,18 +832,22 @@ static int vfs_stage_bind_tree(struct vfs_mount_batch *batch,const struct vfs_pa copy->peer_group=group; copy->master=kind==VFS_COPY_SLAVE ? view.mount : view.mount->master; copy->propagation_copy=kind!=VFS_COPY_BIND; + if(lock_tree)vfs_lock_inherited_mount(copy); vfs_stage_mount(batch,copy,&point); - if(!*out)*out=copy; + if(!*out){*out=copy;copy->locked_topology=false;} if(!recursive)return 0; /* Walk the two trees in step. Their mountpoint dentries are shared; * only the parent attachment changes. The inventory stays fixed. */ - struct vfs_mount *child=vfs_bind_child_mount(&view,mounts); + struct vfs_mount *child=NULL; + rc=vfs_bind_child_mount(&view,mounts,&child); + if(rc)return rc; while(!child && view.mount!=source->mount) { struct vfs_mount *previous=view.mount; copy=copy->point.mount; view=(struct vfs_path){previous->point.mount,copy->root}; - child=vfs_bind_child_mount(&view,previous->next); + rc=vfs_bind_child_mount(&view,previous->next,&child); + if(rc)return rc; } if(!child)return 0; view=(struct vfs_path){child,child->root}; @@ -842,7 +890,7 @@ static int vfs_stage_propagation(struct vfs_mount_batch *batch, struct vfs_mount *copy; struct vfs_mount *inventory=prior->ns ? prior->ns->mounts : batch->pending; int rc=vfs_stage_bind_tree(batch,&view,&point,inventory,recursive,peer->peer_group!=0, - kind,©); + kind,peer->ns->user_ns!=target->mount->ns->user_ns,©); if(rc)return rc; struct vfs_mount *cover=vfs_covering(peer->ns,&point); if(cover!=origin)copy->staged_cover=cover; @@ -896,6 +944,8 @@ int vfs_mount_attach_path(struct vfs_namespace *ns,const struct vfs_path *source * @param target Borrowed retained destination path in ns, of compatible type. * @param recursive True to copy the source's bindable descendant branches. * @return Zero or negative errno without consuming IDs or partially publishing. + * Rejects EINVAL when a nonrecursive bind omits locked inherited children, + * and EPERM when recursive copying would prune a locked unbindable child. */ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target,bool recursive) @@ -907,11 +957,15 @@ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, (target->dentry->node.type==RELIEFOS_FS_TYPE_DIR))return -ENOTDIR; if(source->dentry->disconnected || target->dentry->disconnected)return -ENOENT; if(vfs_covering(ns,target))return -EBUSY; + if(!recursive) + for(struct vfs_mount *child=ns->mounts;child;child=child->next) + if(child!=source->mount && child->locked_topology && vfs_mount_under_root(child,source)) + return -EINVAL; struct vfs_mount_batch batch={.next_id=next_mount_id,.next_peer_id=next_peer_id}; struct vfs_mount *first; bool shared=target->mount->peer_group!=0; - int rc=vfs_stage_bind_tree(&batch,source,target,ns->mounts,recursive,shared,VFS_COPY_BIND,&first); + int rc=vfs_stage_bind_tree(&batch,source,target,ns->mounts,recursive,shared,VFS_COPY_BIND,false,&first); if(!rc)rc=vfs_stage_propagation(&batch,first,target,recursive); return vfs_finish_mount_batch(NULL,&batch,rc); } @@ -920,6 +974,7 @@ static int vfs_bind_tree(struct vfs_namespace *ns,const struct vfs_path *source, * @param ns Execution-owned namespace. @param source Retained source path. * @param target Retained destination path of compatible type. * @return Zero or negative errno without partial publication. + * Omitting locked inherited children returns EINVAL. New root coverage is unlocked. */ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path *target) { @@ -930,6 +985,8 @@ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source,const * @param ns Execution-owned namespace. @param source Retained subtree root. * @param target Retained destination path of compatible type. * @return Zero or negative errno without partial publication. + * Pruning locked unbindable descendants returns EPERM. The new root is + * detachable; inherited descendant coverage and all policy locks survive. */ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target) @@ -975,6 +1032,7 @@ static int vfs_move_into_shared(struct vfs_namespace *ns,struct vfs_mount *origi * @param target Retained destination path of compatible type in ns. * @return Zero or negative errno before mutation. Moving out of a shared * parent or moving any unbindable mount into a shared parent is invalid. + * A locked inherited root returns EINVAL before staging or graph mutation. */ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_path *target) { @@ -982,6 +1040,7 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source,const struct vfs_mount *mount=source->mount; if(mount->ns!=ns || target->mount->ns!=ns)return -EXDEV; if(source->dentry!=mount->root)return -EINVAL; + if(mount->locked_topology)return -EINVAL; if(mount==ns->root || !mount->point.mount)return -EBUSY; if((source->dentry->node.type==RELIEFOS_FS_TYPE_DIR)!= (target->dentry->node.type==RELIEFOS_FS_TYPE_DIR))return -EINVAL; @@ -1173,6 +1232,7 @@ static void vfs_finish_unmounts(struct vfs_mount *pending,int status,bool lazy) * @param ns Borrowed execution-owned namespace. * @param path Retained origin root, excluding the permanent anchor. * @return Zero or negative errno; failures leave all attachments intact. + * A locked inherited root returns EINVAL before provider preflight. */ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path) { @@ -1180,6 +1240,7 @@ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path) struct vfs_mount *root=path->mount; if(root->ns!=ns)return -EXDEV; if(path->dentry!=root->root)return -EINVAL; + if(root->locked_topology)return -EINVAL; if(root==ns->root || !root->point.mount)return -EBUSY; for(struct vfs_mount *child=ns->mounts;child;child=child->next) if(child->point.mount==root)return -EBUSY; @@ -1195,12 +1256,15 @@ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path) * @param path Held selected mount root, excluding the permanent anchor. * @return Zero or negative errno before mutation. Retained paths keep their * objects; no allocation, sync, busy preflight or final backend finish here. + * A locked inherited root returns EINVAL; an unlocked root may detach its + * entire tree while locked descendant coverage remains intact. */ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path) { if(!ns || !vfs_path_valid(path))return -EINVAL; struct vfs_mount *root=path->mount; if(root->ns!=ns || path->dentry!=root->root)return -EINVAL; + if(root->locked_topology)return -EINVAL; if(root==ns->root || !root->point.mount)return -EBUSY; vfs_finish_unmounts(vfs_select_unmounts(ns,root,true),0,true);return 0; } @@ -1210,21 +1274,24 @@ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path) * @param lazy True to defer backend finish even after the last path is gone. * Repairs weak propagation links before releasing paths. Does not propagate * unmount or run provider busy checks against mountpoint pins from this graph. + * Releases the graph's retained user owner after disconnecting attachments. */ static void vfs_detach_namespace(struct vfs_namespace *ns,bool lazy) { if(!ns)return; struct vfs_mount *mounts=ns->mounts; + struct user_namespace *owner=ns->user_ns; for(struct vfs_mount *mount=mounts;mount;mount=mount->next) { vfs_clear_mount_membership(mount);mount->lazy_detached=lazy; } *ns=(struct vfs_namespace){0}; vfs_release_detached_mounts(mounts); + user_namespace_put(owner); } /** @brief Retire the complete graph locally, including the namespace anchor. * @param ns Last-owner namespace storage, or NULL, under VFS execution. - * Held paths survive; does not wait for backend finish. + * Held paths survive; releases the user owner without waiting for backend finish. */ void vfs_namespace_retire(struct vfs_namespace *ns) {vfs_detach_namespace(ns,true);} @@ -1241,6 +1308,7 @@ void vfs_namespace_abort_bootstrap(struct vfs_namespace *ns) * @param ns Boot/fixture storage with stable address, under execution ownership. * @return Zero, EINVAL for invalid storage, EBUSY for live references, or the * provider's preflight error. Failure leaves the entire graph attached. + * Successful destruction releases the graph's retained user owner. */ int vfs_namespace_destroy(struct vfs_namespace *ns) { @@ -1265,7 +1333,8 @@ int vfs_namespace_destroy(struct vfs_namespace *ns) } vfs_unlink_mount(leaf);vfs_release_detached_mounts(leaf); } - *ns=(struct vfs_namespace){0};return 0; + struct user_namespace *owner=ns->user_ns; + *ns=(struct vfs_namespace){0};user_namespace_put(owner);return 0; } int vfs_path_lookup_child_for_walk(const struct vfs_path *parent,const char *name,struct vfs_path *out) diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index c0427b38..32eaa095 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -12,6 +12,7 @@ #define VFS_PROPAGATION_MASK (MS_SHARED|MS_PRIVATE|MS_SLAVE|MS_UNBINDABLE) struct module; +struct user_namespace; struct vfs_mount; struct vfs_dentry; struct vfs_rename; @@ -233,6 +234,7 @@ struct vfs_namespace *vfs_path_namespace(const struct vfs_path *path); /** @brief Mount graph plus its execution-owned lifetime, independent of paths. */ struct vfs_namespace { struct vfs_mount *root,*mounts; + struct user_namespace *user_ns; /* Owned immutable authority scope; NULL is initial. */ uint64_t references; uint64_t nsfs_inode; /* Lazy identity shared by every retained nsfs handle. */ uint64_t mount_generation; /* Successful visible mount graph changes. */ @@ -308,7 +310,8 @@ int vfs_namespace_context_mountpoint(const struct vfs_namespace *ns,const void * * @param path Retained attached or exposed unpublished filesystem root. * @param flags Supported final filesystem/mount policy, excluding MS_REMOUNT. * @return Zero or negative type/unsupported/busy/provider errno. Provider - * validates before committing; caller separately checks CAP_SYS_ADMIN. + * validates before committing; inherited policy locks reject with EPERM before + * callbacks. Caller separately checks CAP_SYS_ADMIN. * Execution-owned task context without graph/module locks across callbacks. */ int vfs_path_remount(const struct vfs_path *path,uint64_t flags); @@ -318,7 +321,8 @@ int vfs_path_remount(const struct vfs_path *path,uint64_t flags); * @param options Optional copied filesystem-specific data validated by its backend. * @return Zero or negative option/type/provider errno. Unsupported data leaves * the attachment unchanged. The retained mount determines the filesystem type. - * Caller holds execution ownership and has checked CAP_SYS_ADMIN. + * Inherited policy locks return EPERM before backend callbacks. Caller holds + * execution ownership and has checked CAP_SYS_ADMIN. */ int vfs_path_remount_options(const struct vfs_path *path,uint64_t flags,const char *options); /** @brief Apply bind-remount flags only to the exact selected attachment. @@ -328,6 +332,7 @@ int vfs_path_remount_options(const struct vfs_path *path,uint64_t flags,const ch * @return Zero or negative errno, leaving policy unchanged on failure. A new * readonly transition with writers on this attachment returns EBUSY; shared * backend flags stay effective and no provider reconfiguration is invoked. + * Inherited restriction or atime-lock changes return EPERM before mutation. */ int vfs_path_bind_remount(const struct vfs_path *path,uint64_t flags); struct vfs_boot_mount { @@ -585,7 +590,8 @@ bool vfs_reclaim_pending(void); /** @brief Set initial policy on one detached, owned mount without changing its backend. * @param mount Owned mount not yet exposed or published, required. * @param flags Per-attachment MS flags, with optional MS_STRICTATIME input. - * @return Zero, EINVAL/EBUSY for invalid state, or EOPNOTSUPP for other flags. + * @return Zero, EINVAL/EBUSY for invalid state, EOPNOTSUPP for other flags, + * or EPERM for an inherited policy-lock violation. * Execution ownership required; pure field publication, no callbacks, I/O, * allocation or ownership transfer. Shared readonly state remains effective. */ @@ -605,7 +611,8 @@ int vfs_namespace_init(struct vfs_namespace *ns,struct vfs_mount *root); * @return Zero or negative errno, leaving dest and both paths unchanged on * failure. Held paths in source retain the same dentry on the corresponding * new mount, even under an overmount; detached paths and empty slots remain - * unchanged. Live paths outside source are rejected. Mount IDs and policy + * unchanged. Retains the source user owner and its existing inherited locks. + * Live paths outside source are rejected. Mount IDs and policy * are independent; shared copies join the same peer groups and slaves keep * their upstream groups. No filesystem lookup or backend creation is needed. */ @@ -617,22 +624,36 @@ int vfs_namespace_snapshot(struct vfs_namespace *dest,const struct vfs_namespace * @param cwd Optional owned cwd to rebind by attachment/dentry identity. * @param out Receives one owned namespace reference, NULL on failure. * @return Zero or negative errno with both path slots unchanged on error. - * Release the result with vfs_namespace_put(), not retire or destroy. + * Retains the source user owner and inherited locks. Release the result with + * vfs_namespace_put(), not retire or destroy. */ int vfs_namespace_clone(const struct vfs_namespace *source,struct vfs_path *root, struct vfs_path *cwd,struct vfs_namespace **out); +/** @brief Snapshot a mount graph for an explicitly selected authority scope. + * @param source Borrowed live graph under execution ownership. + * @param owner Borrowed user namespace retained on success, NULL for initial. + * @param root Optional owned task root to rebind by identity. + * @param cwd Optional owned working directory to rebind by identity. + * @param out Receives one managed graph reference, NULL on failure. + * @return Zero or negative errno without changing paths or source on failure. + * A different owner converts shared mounts to slaves and locks inherited + * restrictions, atime selection and mount coverage. No backend is created. + */ +int vfs_namespace_clone_owned(const struct vfs_namespace *source,struct user_namespace *owner, + struct vfs_path *root,struct vfs_path *cwd,struct vfs_namespace **out); /** @brief Disconnect all mounts for last-owner namespace teardown. * @param ns Caller-owned namespace with no remaining graph users, or NULL. * Serialized VFS execution. Repairs weak propagation links in surviving * graphs without sending unmount events, checking busy paths or flushing * backends. Held paths survive; final backend cleanup is deferred. The caller - * owns the namespace storage. + * owns the namespace storage. Releases the graph's user-owner reference. */ void vfs_namespace_retire(struct vfs_namespace *ns); /** @brief Destroy a namespace only when every external path/handle has gone. * @param ns Namespace to clear; NULL is invalid. * @return Zero or -EBUSY without partial detach on an external reference. - * Serialized task context; final backend callbacks can perform I/O. + * Serialized task context; final backend callbacks can perform I/O. Successful + * destruction releases the graph's user-owner reference. */ int vfs_namespace_destroy(struct vfs_namespace *ns); /** @brief Get the currently visible namespace root for a new task FS state. @@ -699,6 +720,8 @@ int vfs_mount_set_propagation(struct vfs_namespace *ns,const struct vfs_path *pa * duplicating provider destruction. Inherits the source's peer and master * groups, and propagates across eligible graphs under a shared destination. * Child mounts are not copied and an unbindable source returns EINVAL. + * Omitting locked inherited children returns EINVAL. The new root may detach + * independently while its policy locks remain inherited. */ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); @@ -712,6 +735,8 @@ int vfs_mount_bind(struct vfs_namespace *ns,const struct vfs_path *source, * Eligible destination peers and slaves, even in another namespace, each * receive a bindable tree. * Unbindable descendant branches are skipped; an unbindable source is rejected. + * Pruning a locked unbindable child returns EPERM. The new root is detachable, + * and copied descendants retain their inherited coverage and policy locks. */ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); @@ -725,6 +750,7 @@ int vfs_mount_bind_recursive(struct vfs_namespace *ns,const struct vfs_path *sou * EINVAL. A shared destination publishes peer and slave copies of the tree * across eligible graphs. The original subtree moves intact; allocations * finish before commit. + * A locked inherited source root returns EINVAL before mutation. */ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *target); @@ -735,6 +761,7 @@ int vfs_mount_move(struct vfs_namespace *ns,const struct vfs_path *source, * receiver with unrelated children is skipped, except root covers that can be * reparented. Other held paths on selected mounts in any namespace keep the * entire operation busy. Success does not consume the caller's path. + * A locked inherited root returns EINVAL before provider preflight. */ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path); /** @brief Lazily disconnect a subtree and eligible propagated attachments. @@ -744,8 +771,16 @@ int vfs_mount_unmount(struct vfs_namespace *ns,const struct vfs_path *path); * except root covers that can be reparented. The whole batch spans eligible * namespaces. Held paths remain usable and final cleanup is deferred. No * allocations or synchronous backend flush. + * A locked inherited root returns EINVAL. An unlocked root may detach its + * whole tree, retaining locked descendant coverage within that tree. */ int vfs_mount_unmount_lazy(struct vfs_namespace *ns,const struct vfs_path *path); +/** @brief Query whether inherited coverage prevents direct mount removal. + * @param path Borrowed retained path, nullable, under execution ownership. + * @return True for an attachment locked by a cross-owner snapshot or replay. + * No allocation, I/O or ownership change. Allows rejection before a sync. + */ +bool vfs_path_mount_locked(const struct vfs_path *path); /** @brief Prepare retained directory-name changes before a backend rename. * @param ns Shared namespace, serialized by the execution transaction. * @param source Held source dentry, excluding a mount root or covered point. diff --git a/include/reliefnt/task/accessors.h b/include/reliefnt/task/accessors.h index d50c3af0..8cc56bd9 100644 --- a/include/reliefnt/task/accessors.h +++ b/include/reliefnt/task/accessors.h @@ -231,11 +231,12 @@ bool sched_task_fs_shared_outside_group(const struct task *task); /** @brief Detach the caller's CLONE_FS state, optionally cloning its mount graph. * @param task Live calling task under execution ownership; required. * @param new_namespace True for CLONE_NEWNS (caller checks CAP_SYS_ADMIN). + * @param owner Borrowed authority scope for the new graph, ignored for CLONE_FS. * @return Zero or the original VFS error with the caller and peers unchanged. * Called without scheduler_lock. Installs new path and scalar state before * putting old references, which may retire the old mount graph. */ -int sched_task_fs_unshare(struct task *task, bool new_namespace); +int sched_task_fs_unshare(struct task *task, bool new_namespace, struct user_namespace *owner); /** @brief Install a borrowed mount graph at its current visible root. * @param task Live caller under execution ownership, outside scheduler_lock. diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index 95b33016..11aaedac 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -131,7 +131,8 @@ void sched_vfork_child_done(struct task *child) * @param flags Linux clone flags and exit signal. @param tls Requested TLS base. * @return Zero or the original clone validation errno; no allocation, locks, * user access or state changes occur. - * Privilege checks for the existing mount graph use initial user namespace capabilities. + * A new graph requires current-scope CAP_SYS_ADMIN unless CLONE_NEWUSER + * creates its owning scope in the same operation. */ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) { @@ -151,13 +152,13 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) if ((flags & CLONE_NEWPID) && (flags & CLONE_THREAD)) return -LINUX_EINVAL; const struct task *parent = sched_current_task(); return (flags & CLONE_NEWUSER) || - (parent && (task_initial_capabilities(parent) & (1ULL << CAP_SYS_ADMIN))) + (parent && task_ns_capable(parent, parent->user_ns, CAP_SYS_ADMIN)) ? -LINUX_EINVAL : -LINUX_EPERM; } if (flags & ~supported) return -RELIEFOS_ENOSYS; - if (flags & CLONE_NEWNS) { + if ((flags & CLONE_NEWNS) && !(flags & CLONE_NEWUSER)) { const struct task *parent = sched_current_task(); - if (!parent || !(task_initial_capabilities(parent) & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; + if (!parent || !task_ns_capable(parent, parent->user_ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; } if ((flags & CLONE_SETTLS) && tls >= RELIEFNT_USER_TLS_LIMIT) return -RELIEFOS_EPERM; return 0; @@ -183,6 +184,8 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) * including on early allocation failure. * CLONE_NEWUSER stages an empty-map scope outside scheduler_lock and gives the * child full local authority. Other children retain the inherited scope. + * A new mount graph retains the candidate user scope or the parent's current + * scope and locks inherited attachments when its owner changes. * Every rollback releases the prepared or installed user namespace reference. */ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flags, @@ -227,7 +230,8 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag * call into providers on failure, so take no scheduler lock or PID. */ kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); int rc = flags & CLONE_NEWUSER ? sched_task_user_namespace_create(parent, &user_ns) : 0; - if (!rc && (flags & CLONE_NEWNS)) rc = sched_task_fs_snapshot(parent, &snapshot); + if (!rc && (flags & CLONE_NEWNS)) + rc = sched_task_fs_snapshot(parent, user_ns ? user_ns : parent->user_ns, &snapshot); if (rc) { user_namespace_put(user_ns); sched_task_identity_put(identity); diff --git a/kernel/sched/fs.c b/kernel/sched/fs.c index 5a8c62ca..4d7c641e 100644 --- a/kernel/sched/fs.c +++ b/kernel/sched/fs.c @@ -59,17 +59,19 @@ void sched_task_fs_inherit(struct task *task,const struct task *parent) /** @brief Stage a new mount namespace while retaining the exact source paths. * @param task Borrowed source, including any CLONE_FS shared state. + * @param owner Borrowed user scope to own the new graph, NULL for initial. * @param out Empty destination for the owned cloned state. * @return Zero or negative errno. On failure all tentative references are put. */ -int sched_task_fs_snapshot(const struct task *task, struct task_fs_paths *out) +int sched_task_fs_snapshot(const struct task *task, struct user_namespace *owner, + struct task_fs_paths *out) { const struct task_fs_paths *source = sched_task_paths(task); if (!source->ns) return -LINUX_ENODEV; struct task_fs_paths paths = {0}; vfs_path_get(&source->root, &paths.root); vfs_path_get(&source->cwd, &paths.cwd); - int rc = vfs_namespace_clone(source->ns, &paths.root, &paths.cwd, &paths.ns); + int rc = vfs_namespace_clone_owned(source->ns, owner, &paths.root, &paths.cwd, &paths.ns); if (rc) sched_task_fs_paths_put(&paths); else *out = paths; return rc; @@ -88,14 +90,15 @@ static void task_shared_fs_put(struct task_fs_state *shared) /** @brief Replace only the calling task's filesystem state after preparation. * @param task Execution-owned caller with validated flags and capability. * @param new_namespace Snapshot the mount graph as well as separating CLONE_FS. + * @param owner Borrowed authority scope for a new graph, ignored for CLONE_FS. * @return Zero or negative errno; failures leave every old owner unchanged. */ -int sched_task_fs_unshare(struct task *task, bool new_namespace) +int sched_task_fs_unshare(struct task *task, bool new_namespace, struct user_namespace *owner) { struct task_fs_state *shared = task->shared_fs; struct task_fs_paths next = {0}; if (new_namespace) { - int rc = sched_task_fs_snapshot(task, &next); + int rc = sched_task_fs_snapshot(task, owner, &next); if (rc) return rc; } else { if (!shared) return 0; diff --git a/kernel/sched/internal.h b/kernel/sched/internal.h index c5ea3418..546f88fa 100644 --- a/kernel/sched/internal.h +++ b/kernel/sched/internal.h @@ -693,11 +693,13 @@ void sched_vfork_child_done(struct task *child); /** @brief Prepare independent paths in a new managed mount namespace. * @param task Source task whose filesystem state is borrowed. + * @param owner Borrowed user scope retained by the new graph, NULL for initial. * @param out Empty output that owns the new namespace, root and cwd on success. * @return Zero or the original VFS error, leaving the source and output intact. * Requires execution ownership without scheduler_lock; rollback can put mounts. */ -int sched_task_fs_snapshot(const struct task *task, struct task_fs_paths *out); +int sched_task_fs_snapshot(const struct task *task, struct user_namespace *owner, + struct task_fs_paths *out); /** @brief Detach and release owned namespace and path references. * @param paths Owned state to clear before final provider puts. diff --git a/kernel/sched/user_namespace_task.c b/kernel/sched/user_namespace_task.c index 1130a1b3..4468ed6b 100644 --- a/kernel/sched/user_namespace_task.c +++ b/kernel/sched/user_namespace_task.c @@ -54,7 +54,7 @@ int sched_task_user_namespace_unshare(struct task *task, bool new_mount_namespac struct user_namespace *ns = NULL; int rc = sched_task_user_namespace_create(task, &ns); if (rc) return rc; - rc = sched_task_fs_unshare(task, new_mount_namespace); + rc = sched_task_fs_unshare(task, new_mount_namespace, ns); if (rc) { user_namespace_put(ns); return rc; diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 6989b9ab..260b04f1 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -55,6 +55,7 @@ static int mount_bind(struct vfs_namespace *ns,struct task *task,uint64_t source * forced/expire operations are unsupported. * Only ordinary unmount can wait in sync; both discard redundant lookup refs * before detaching. The local path pins the provider across the operation. + * Inherited locked coverage returns EINVAL before a provider sync. */ static int mount_unmount(struct vfs_namespace *ns,struct task *task,uint64_t target,uint32_t flags) { @@ -64,6 +65,7 @@ static int mount_unmount(struct vfs_namespace *ns,struct task *task,uint64_t tar struct vfs_lookup_result found={0}; int rc=resolve_user_object_at_flags(ns,task,LINUX_AT_FDCWD,target,false,false, flags&UMOUNT_NOFOLLOW ? 0 : VFS_LOOKUP_FOLLOW,&found); + if(!rc && vfs_path_mount_locked(&found.path))rc=-LINUX_EINVAL; if(!rc && !(flags&MNT_DETACH))rc=vfs_path_sync(&found.path,true,false); if(!rc) { /* Dropping the redundant path references may drop the scope's graph @@ -204,7 +206,7 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * /** @brief Apply a Linux mount operation using retry-stable actual objects. * @param ns Borrowed live namespace under execution ownership. - * @param task Calling task, required; CAP_SYS_ADMIN checked before user input. + * @param task Calling task, required; graph-owner CAP_SYS_ADMIN checked before user input. * @param number Linux MOUNT or UMOUNT2 operation number. * @param a0 User source/label, or unmount target pointer; ignored for remount * and propagation changes. @@ -217,27 +219,32 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * * @return Zero or negative Linux errno/internal EAGAIN. Text and lookup state * remain scope-owned across waits; temporary unscoped allocations are always * freed. The resulting graph owns backend lifetime, without target prefixes. - * The mounted graph is owned by the initial user namespace. + * Fresh backends, shared-backend remount and the new mount API additionally + * require initial-user CAP_SYS_ADMIN until backend ownership is represented. */ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_t number, uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4) { - if(!task || !(task_initial_capabilities(task)&(1ULL<user_ns : NULL,CAP_SYS_ADMIN))return -RELIEFOS_EPERM; if(!ns)return -RELIEFOS_ENOENT; - if(number==__NR_fsopen || number==__NR_fsconfig || number==__NR_fsmount || number==__NR_move_mount) + if(number==__NR_fsopen || number==__NR_fsconfig || number==__NR_fsmount || number==__NR_move_mount) { + if(!task_ns_capable(task,NULL,CAP_SYS_ADMIN))return -RELIEFOS_EPERM; return syscall_new_mount_control(ns,task,number,a0,a1,a2,a3,a4); + } if(number==LINUX_SYS_UMOUNT2)return mount_unmount(ns,task,a0,(uint32_t)a1); if(number!=LINUX_SYS_MOUNT)return -RELIEFOS_ENOSYS; if((a3&MS_MGC_MSK)==MS_MGC_VAL)a3&=~MS_MGC_MSK; a3&=~MS_SILENT; if(a3&MS_REMOUNT) { if(a3&MS_BIND)return mount_bind_remount(ns,task,a1,a3&~(MS_REMOUNT|MS_BIND)); + if(!task_ns_capable(task,NULL,CAP_SYS_ADMIN))return -RELIEFOS_EPERM; return mount_remount(ns,task,a1,a3&~MS_REMOUNT,a4); } if(a3&MS_BIND)return a3&~(MS_BIND|MS_REC) ? -RELIEFOS_EOPNOTSUPP : mount_bind(ns,task,a0,a1,(a3&MS_REC)!=0); if(a3&VFS_PROPAGATION_MASK)return mount_propagation(ns,task,a1,a3); if(a3&MS_MOVE)return a3!=MS_MOVE ? -RELIEFOS_EOPNOTSUPP : mount_move(ns,task,a0,a1); + if(!task_ns_capable(task,NULL,CAP_SYS_ADMIN))return -RELIEFOS_EPERM; const uint64_t supported=MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_SYNCHRONOUS|MS_DIRSYNC| MS_NOATIME|MS_NODIRATIME|MS_RELATIME|MS_STRICTATIME|MS_LAZYTIME; if(a3&~supported)return -RELIEFOS_EOPNOTSUPP; diff --git a/kernel/syscall/process/clone.c b/kernel/syscall/process/clone.c index 1805b8ee..0c423282 100644 --- a/kernel/syscall/process/clone.c +++ b/kernel/syscall/process/clone.c @@ -139,7 +139,8 @@ int64_t syscall_clone3(const struct trap_frame *frame, uint64_t arguments, uint6 * @return Zero (including a no-op for flags=0), or negative Linux errno. * Validate the entire request before preparing or publishing a snapshot. * User scope creation requires a single-threaded caller, mapped effective IDs - * and an unrestricted root. Mount graphs require initial-scope CAP_SYS_ADMIN. + * and an unrestricted root. A new mount graph requires current-scope + * CAP_SYS_ADMIN, or is owned by the user scope created in the same operation. */ int64_t syscall_unshare(struct task *task, uint64_t flags) { @@ -148,7 +149,7 @@ int64_t syscall_unshare(struct task *task, uint64_t flags) if (!task || (flags & ~supported)) return -LINUX_EINVAL; if (!flags) return 0; bool new_namespace = (flags & CLONE_NEWNS) != 0; - if (new_namespace && !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -LINUX_EPERM; if (flags & CLONE_NEWUSER) return sched_task_user_namespace_unshare(task, new_namespace); - return sched_task_fs_unshare(task, new_namespace); + if (new_namespace && !task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; + return sched_task_fs_unshare(task, new_namespace, task->user_ns); } diff --git a/kernel/syscall/process/setns.c b/kernel/syscall/process/setns.c index d44ed51d..de5309e2 100644 --- a/kernel/syscall/process/setns.c +++ b/kernel/syscall/process/setns.c @@ -10,7 +10,8 @@ * @param fd Descriptor number (not O_PATH or a pidfd). * @param type Zero, CLONE_NEWNS or CLONE_NEWUSER matching the held inode. * @return Zero or a negative descriptor, capability or namespace error. - * Mount graph entry requires CAP_SYS_ADMIN and CAP_SYS_CHROOT in the initial user namespace. + * Mount graph entry requires current-scope CAP_SYS_ADMIN and CAP_SYS_CHROOT, + * plus CAP_SYS_ADMIN in the target graph's owning user scope. * User scope entry requires target CAP_SYS_ADMIN and exclusive thread/FS state. */ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) @@ -26,8 +27,8 @@ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) return sched_task_user_namespace_join(task, scope); struct vfs_namespace *ns = nsfs_path_namespace(&file->path_ref); if (!ns) return -LINUX_EINVAL; - const uint64_t required = (1ULL << CAP_SYS_ADMIN) | (1ULL << CAP_SYS_CHROOT); - /* Existing mount graphs are owned by the initial user namespace. */ - if ((task_initial_capabilities(task) & required) != required) return -LINUX_EPERM; + if (!task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN) || + !task_ns_capable(task, task->user_ns, CAP_SYS_CHROOT) || + !task_ns_capable(task, ns->user_ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; return sched_task_fs_join_namespace(task, ns); } diff --git a/tools/test_futimens.py b/tools/test_futimens.py index 95113e43..dd98cc8c 100644 --- a/tools/test_futimens.py +++ b/tools/test_futimens.py @@ -25,6 +25,7 @@ 'fs/security/access.c', 'kernel/syscall/fs/path.c', 'kernel/syscall/fs/lookup_state.c', 'kernel/syscall/fd/descriptor.c', 'kernel/device/character.c', 'kernel/syscall/io/vector.c', 'kernel/syscall/fd/pty_descriptor.c', 'kernel/sched/tables.c', 'kernel/device/mapping.c', 'kernel/sched/fs.c', + 'kernel/sched/user_namespace.c', ] subprocess.run(['clang', '-std=c11', *flags, f'tools/tests/{name}.c', *sources, '-o', str(binary)], cwd=ROOT, env={**os.environ, 'TMPDIR': str(TMP)}, check=True) diff --git a/tools/test_initramfs.py b/tools/test_initramfs.py index c6b7c63d..cd26769e 100644 --- a/tools/test_initramfs.py +++ b/tools/test_initramfs.py @@ -30,6 +30,7 @@ def test_root_objects_links_devices_and_rollback(self): "tools/tests/initramfs_test.c", "fs/initramfs/archive.c", "fs/initramfs/unpack.c", "fs/initramfs/view.c", "fs/initramfs/records.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/dentry.c", + "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=ROOT, check=True) subprocess.run([str(binary), str(archive)], check=True, timeout=30) diff --git a/tools/test_inotify_vfs.py b/tools/test_inotify_vfs.py index 91a47a4a..dc47fcc1 100644 --- a/tools/test_inotify_vfs.py +++ b/tools/test_inotify_vfs.py @@ -14,6 +14,7 @@ "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/inotify_vfs_test.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/dentry.c", + "kernel/sched/user_namespace.c", "fs/vfs/file.c", "fs/vfs/mutation.c", "fs/vfs/attributes.c", "fs/vfs/notify.c", "fs/vfs/inode.c", "fs/notify/core.c", "fs/notify/queue.c", "fs/notify/watch.c", "fs/notify/limits.c", "-o", str(binary), diff --git a/tools/test_memory_pressure_open_path.py b/tools/test_memory_pressure_open_path.py index ed1561c1..bf2f57b0 100644 --- a/tools/test_memory_pressure_open_path.py +++ b/tools/test_memory_pressure_open_path.py @@ -45,6 +45,7 @@ def main(): "kernel/sched/oom.c", "kernel/sync/wait.c", "block/core/storage_wait.c", "mm/reclaim/pressure.c", "mm/reclaim/wait.c", "mm/cache/page_cache.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/attributes.c", + "kernel/sched/user_namespace.c", "fs/vfs/exec_file.c", "mm/swap/area.c", "mm/swap/slot.c", "mm/swap/paging.c", "-Wl,--wrap=vfs_exec_source_get", "-Wl,--wrap=vfs_exec_source_put", "-Wl,--wrap=swap_backend_page_io", "-o", binary] diff --git a/tools/test_mount_tree.py b/tools/test_mount_tree.py index 2708eeb9..4ed94b98 100644 --- a/tools/test_mount_tree.py +++ b/tools/test_mount_tree.py @@ -17,7 +17,8 @@ def test_namespace_paths_and_owner_lifetime(self): "-fno-pie", "-no-pie", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_tree_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", - "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "kernel/module/lifecycle.c", "kernel/params/value.c", + "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "kernel/sched/user_namespace.c", + "kernel/module/lifecycle.c", "kernel/params/value.c", "kernel/module/layout.c", "kernel/module/symbols.c", "-o", str(binary) ], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=20) diff --git a/tools/test_vfs_lookup_cache.py b/tools/test_vfs_lookup_cache.py index a3789552..c8fc9229 100644 --- a/tools/test_vfs_lookup_cache.py +++ b/tools/test_vfs_lookup_cache.py @@ -19,6 +19,7 @@ def test_lookup_cache(self): "-fno-pie", "-no-pie", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/vfs_lookup_cache_test.c", "fs/vfs/mount_tree.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/lookup_cache.c", + "kernel/sched/user_namespace.c", "-o", str(binary), ], cwd=ROOT, check=True) for case in ("positive", "negative", "generation", "parents", "dynamic", "stale_retain", "errors", diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index f4c11584..172c09c7 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2663,6 +2663,13 @@ static void runtime_boot_objects(struct vfs_namespace *ns,const struct vfs_path puts("PASS boot runtime actual objects: RAM root, >5KiB depth, literal symlink removal, same-FS mount boundary, modes and OOM cleanup"); } +/** @brief Invoke a mount syscall with the production lookup retry scope. + * @param ns Borrowed mount graph. @param task Execution-owned fixture actor. + * @param number Linux syscall number. @param a0 First syscall operand. + * @param a1 Second syscall operand. @param a2 Third syscall operand. + * @param a3 Fourth syscall operand. @param a4 Fifth syscall operand. + * @return Syscall result; EAGAIN retains the scope for a later retry. + */ static int64_t scoped_mount_call(struct vfs_namespace *ns,struct task *task,uint64_t number, uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4) { @@ -2673,6 +2680,65 @@ static int64_t scoped_mount_call(struct vfs_namespace *ns,struct task *task,uint return rc; } +/** @brief Check graph-owner authority through real mount syscall entry points. + * @param ns Borrowed initial-scope graph. @param root Retained graph root. + * @param fs Initial graph's writable tmpfs, used for fixture directories. + */ +static void runtime_mount_user_authority(struct vfs_namespace *ns,const struct vfs_path *root, + struct tmpfs_super *fs) +{ + struct {char source[32],target[32],next[32],type[8],root[2];} user={ + "/userns-source","/userns-target","/userns-next","tmpfs","/"}; + assert(!tmpfs_create(fs,user.source,LINUX_S_IFDIR|0755,NULL,NULL)); + assert(!tmpfs_create(fs,user.target,LINUX_S_IFDIR|0755,NULL,NULL)); + assert(!tmpfs_create(fs,user.next,LINUX_S_IFDIR|0755,NULL,NULL)); + struct task creator={.euid=5000}; + struct user_namespace *owner=NULL; + assert(!user_namespace_create(&creator,&owner)); + struct task actor={.pid=911,.user_ns=owner,.euid=5000,.fsuid=1000,.fsgid=1000, + .cap_effective=1ULL<user_ns, true, 0) == 100); retire_child(child); assert(parent->groups->references == 1 && live_pages() == pages); + + uint64_t mount_id = next_mount_id; + unpublished_child = child; + mount_budget = 1; + assert(clone_namespace(parent, user, versioned, flags | CLONE_NEWNS) == -LINUX_ENOMEM); + mount_budget = -1; + assert(!child->pid && !child->user_ns && next_mount_id == mount_id); + assert(sched_task_namespace(parent) == mount_ns && parent->groups->references == 1); + assert(clone_namespace(parent, user, versioned, flags | CLONE_NEWNS) > 0); + assert_user_scope(child, NULL); + assert(sched_task_namespace(child)->user_ns == child->user_ns); + assert(child->user_ns->references == 2); + assert(vfs_path_mount_locked(&sched_task_paths(child)->root)); + retire_child(child); + assert(live_pages() == pages && parent->groups->references == 1); } /* NEWUSER implies FS separation, but a live thread still prevents unshare. */ @@ -330,9 +345,16 @@ static void check_user_namespaces(struct task *parent, struct task *child, assert(syscall_unshare(parent, CLONE_NEWUSER) == -LINUX_EPERM); write_user_control(parent, scope, USER_NAMESPACE_SETGROUPS, "deny\n"); write_user_control(parent, scope, USER_NAMESPACE_GID_MAP, "0 100 1\n"); - assert(!syscall_unshare(parent, CLONE_NEWUSER | CLONE_THREAD)); + unpublished_child = child; + mount_budget = 1; + assert(syscall_unshare(parent, CLONE_NEWUSER | CLONE_NEWNS) == -LINUX_ENOMEM); + mount_budget = -1; + assert(parent->user_ns == scope && sched_task_namespace(parent) == mount_ns); + assert(scope->references == 1); + assert(!syscall_unshare(parent, CLONE_NEWUSER | CLONE_NEWNS | CLONE_THREAD)); assert_user_scope(parent, scope); assert(scope->references == 1 && parent->user_ns->setgroups_denied); + assert(sched_task_namespace(parent)->user_ns == parent->user_ns && parent->user_ns->references == 2); user_namespace_put(parent->user_ns); parent->user_ns = NULL; sched_task_fs_release(&sibling); @@ -428,6 +450,39 @@ static void check_user_setns(struct task *task, struct task *thread) puts("PASS user namespace setns ownership, scope reset, thread/FS rejection and handle lifetime"); } +/** @brief Require both local join capabilities and authority over the graph owner. */ +static void check_mount_user_setns(struct task *task) +{ + struct user_namespace *owner = NULL; + assert(!user_namespace_create(task, &owner)); + struct vfs_namespace *old = sched_task_namespace(task), *target = NULL; + assert(!vfs_namespace_clone_owned(old, owner, NULL, NULL, &target)); + assert(!nsfs_create_path(old, &ordinary_file.path_ref)); + assert(!nsfs_create_path(target, &handle_file.path_ref)); + vfs_namespace_put(target); + task->user_ns = owner; + assert(owner->references == 2); + assert(syscall_setns(task, 4, CLONE_NEWNS) == -LINUX_EPERM); + const uint64_t admin = UINT64_C(1) << CAP_SYS_ADMIN, chroot = UINT64_C(1) << CAP_SYS_CHROOT; + const uint64_t denied[] = {0, admin, chroot}; + for (unsigned i = 0; i < sizeof(denied) / sizeof(denied[0]); ++i) { + task->cap_effective = denied[i]; + assert(syscall_setns(task, 3, CLONE_NEWNS) == -LINUX_EPERM); + assert(sched_task_namespace(task) == old); + } + task->cap_effective = admin | chroot; + assert(!syscall_setns(task, 3, CLONE_NEWNS)); + assert(sched_task_namespace(task) == target && target->user_ns == owner); + assert(!syscall_unshare(task, CLONE_NEWNS)); + assert(sched_task_namespace(task) != target && sched_task_namespace(task)->user_ns == owner); + vfs_path_put(&ordinary_file.path_ref); + vfs_path_put(&handle_file.path_ref); + assert(owner->references == 2); + task->user_ns = NULL; + user_namespace_put(owner); + puts("PASS mount namespace user ownership, local unshare and scoped setns authority"); +} + int main(void) { struct sched_task_object parent_object = {0}, child_object = {0}; @@ -525,7 +580,10 @@ int main(void) assert(!user_namespace_create(parent, &user_scope)); parent->user_ns = user_scope; for (unsigned versioned = 0; versioned < 2; ++versioned) { - assert(clone_namespace(parent, user, versioned, CLONE_NEWNS) == -LINUX_EPERM); + assert(clone_namespace(parent, user, versioned, CLONE_NEWNS) > 0); + assert_snapshot(child, parent); + assert(sched_task_namespace(child)->user_ns == user_scope && user_scope->references == 3); + retire_child(child); assert(clone_namespace(parent, user, versioned, 0) > 0); assert(child->user_ns == user_scope && user_scope->references == 2); task_clear_identity(child); @@ -542,11 +600,15 @@ int main(void) check_setns(parent); check_user_namespaces(parent, child, user); check_user_setns(parent, child); + check_mount_user_setns(parent); sched_task_fs_release(parent); - vfs_reclaim_mounts(16); + /* Retiring nsfs captures can enqueue their graphs and backing mounts. */ + while (vfs_reclaim_mounts(16)) {} assert(!vfs_namespace_destroy(&ns) && !fs_backend_pins); address_space_destroy(sched_task_as(parent)); - assert(!live_pages() && !writable_aliases && !vfs_reclaim_pending()); + assert(!live_pages()); + assert(!writable_aliases); + assert(!vfs_reclaim_pending()); current_task[0] = NULL; current_pid[0] = 0; tasks = NULL; diff --git a/tools/tests/mount_tree_test.c b/tools/tests/mount_tree_test.c index 9626ffdd..ed5988b8 100644 --- a/tools/tests/mount_tree_test.c +++ b/tools/tests/mount_tree_test.c @@ -7,6 +7,7 @@ #include #include #include +#include #include "../../fs/vfs/mount_internal.h" #include "../../kernel/module/internal.h" @@ -407,6 +408,145 @@ static void namespace_snapshot_objects(struct module *owner) puts("PASS mount namespace snapshot: covered task paths, independent policy and IDs, atomic rollback and deferred retirement"); } +static uint64_t inherited_backend_flags; +static unsigned inherited_remounts; + +/** @brief Return the fixture backend's shared policy. */ +static uint64_t inherited_flags(void *context) +{assert(context==&c);return inherited_backend_flags;} + +/** @brief Count actual backend reconfiguration after attachment validation. */ +static int inherited_remount(void *context,uint64_t flags) +{assert(context==&c);++inherited_remounts;inherited_backend_flags=flags;return 0;} + +/** @brief Check owner retention, lower-privilege policy and inseparable covers. */ +static void namespace_user_ownership(void) +{ + struct task creator={0}; + struct user_namespace *owner=NULL; + assert(!user_namespace_create(&creator,&owner)); + struct vfs_namespace source={0},same_owner={0}; + struct vfs_mount *mount=mount_new(&a,NULL); + assert(!vfs_mount_set_flags(mount,MS_STRICTATIME)); + assert(!vfs_namespace_init(&source,mount));vfs_mount_put(mount); + struct vfs_path root={0};assert(!vfs_namespace_root(&source,&root)); + struct vfs_path slot=find(&source,&root,&root,"mnt",2); + const uint64_t restrictions=MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOATIME|MS_NODIRATIME; + mount=mount_new(&b,NULL);assert(!vfs_mount_set_flags(mount,restrictions)); + assert(!vfs_mount_attach(&source,mount,&slot));vfs_mount_put(mount);vfs_path_put(&slot); + struct vfs_path parent=find(&source,&root,&root,"mnt",1); + slot=find(&source,&root,&parent,"child",3); + struct vfs_backend_ops readonly_ops=ops; + readonly_ops.mount_flags=inherited_flags;readonly_ops.remount=inherited_remount; + struct storage_node child_node=node(&c_entries[0]); + inherited_backend_flags=MS_RDONLY;inherited_remounts=0; + assert(!vfs_mount_new(&readonly_ops,&c,NULL,&child_node,&mount)); + assert(!vfs_mount_attach(&source,mount,&slot));vfs_mount_put(mount);vfs_path_put(&slot); + assert(!vfs_mount_set_propagation(&source,&parent,MS_SHARED)); + + size_t before=allocations; + uint64_t next=vfs_mount_next_id(),group=vfs_mount_next_peer_id(); + struct vfs_namespace *copy=NULL; + unsigned failures=0; + for(unsigned nth=1;nth<=16;++nth) { + fail_after=nth;allocation_attempts=0; + int rc=vfs_namespace_clone_owned(&source,owner,NULL,NULL,©); + fail_after=0; + if(!rc)break; + assert(rc==-ENOMEM && !copy && owner->references==1); + assert(allocations==before && vfs_mount_next_id()==next && vfs_mount_next_peer_id()==group); + ++failures; + } + assert(copy && failures>=4 && copy->user_ns==owner && owner->references==2); + assert(!vfs_namespace_snapshot(&same_owner,copy,NULL,NULL)); + assert(same_owner.user_ns==owner && owner->references==3); + vfs_namespace_retire(&same_owner);assert(owner->references==2); + while(vfs_reclaim_mounts(32)){} + + struct vfs_path copied_root={0};assert(!vfs_namespace_root(copy,&copied_root)); + struct vfs_path copied_parent=find(copy,&copied_root,&copied_root,"mnt",1); + struct vfs_path child=find(copy,&copied_root,&copied_parent,"child",1); + struct vfs_path target=find(copy,&copied_root,&copied_root,"other",3); + assert(vfs_path_mount_locked(&copied_root) && vfs_path_mount_locked(&copied_parent)); + assert(!copied_parent.mount->peer_group && copied_parent.mount->master==parent.mount); + assert(vfs_path_mount_flags(&copied_parent)==restrictions); + inherited_backend_flags=0; + assert(vfs_path_mount_flags(&child)&MS_RDONLY); + assert(vfs_path_bind_remount(&child,0)==-EPERM); + assert(vfs_path_remount(&child,0)==-EPERM && !inherited_remounts); + const uint64_t locked[]={MS_NOSUID,MS_NODEV,MS_NOEXEC,MS_NOATIME,MS_NODIRATIME}; + for(unsigned i=0;ireferences==1); + user_namespace_put(owner); + vfs_path_put(&parent);vfs_path_put(&root);vfs_namespace_retire(&source); + while(vfs_reclaim_mounts(32)){} + assert(!vfs_reclaim_pending() && !allocations);no_pins(&a);no_pins(&b);no_pins(&c); + puts("PASS mount user ownership: atomic snapshots, policy locks, strictatime and inseparable inherited covers"); +} + +/** @brief Lock propagated descendants across owners while allowing whole-tree removal. */ +static void cross_owner_propagation(void) +{ + struct task creator={0}; + struct user_namespace *owner=NULL; + assert(!user_namespace_create(&creator,&owner)); + struct vfs_namespace source={0},*copy=NULL; + struct vfs_mount *mount=mount_new(&a,NULL); + assert(!vfs_namespace_init(&source,mount));vfs_mount_put(mount); + struct vfs_path root={0};assert(!vfs_namespace_root(&source,&root)); + assert(!vfs_mount_set_propagation(&source,&root,MS_SHARED)); + assert(!vfs_namespace_clone_owned(&source,owner,NULL,NULL,©)); + struct vfs_path copied_root={0};assert(!vfs_namespace_root(copy,&copied_root)); + assert(!copied_root.mount->peer_group && copied_root.mount->master==root.mount); + struct vfs_path point=find(&source,&root,&root,"mnt",2); + mount=mount_new(&b,NULL); + assert(!vfs_mount_attach(&source,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); + struct vfs_path parent=find(&source,&root,&root,"mnt",1); + point=find(&source,&root,&parent,"child",3); + mount=mount_new(&c,NULL); + assert(!vfs_mount_attach(&source,mount,&point));vfs_mount_put(mount);vfs_path_put(&point); + point=find(&source,&root,&root,"other",3); + assert(!vfs_mount_bind_recursive(&source,&parent,&point));vfs_path_put(&point); + struct vfs_path replica=find(copy,&copied_root,&copied_root,"other",1); + struct vfs_path descendant=find(copy,&copied_root,&replica,"child",1); + assert(!vfs_path_mount_locked(&replica) && vfs_path_mount_locked(&descendant)); + assert(vfs_mount_unmount_lazy(copy,&descendant)==-EINVAL); + assert(!vfs_mount_unmount_lazy(copy,&replica)); + struct vfs_path origin=find(&source,&root,&root,"other/child",1); + assert(vfs_path_namespace(&origin)==&source);vfs_path_put(&origin); + vfs_path_put(&descendant);vfs_path_put(&replica);vfs_path_put(&copied_root); + vfs_namespace_put(copy);assert(owner->references==1);user_namespace_put(owner); + vfs_path_put(&parent);vfs_path_put(&root);vfs_namespace_retire(&source); + while(vfs_reclaim_mounts(32)){} + assert(!vfs_reclaim_pending() && !allocations);no_pins(&a);no_pins(&b);no_pins(&c); + puts("PASS cross-owner propagation: removable new root and locked inherited descendants"); +} + static int cross_unmount_error; static unsigned cross_unmount_checks; @@ -808,6 +948,8 @@ static void bound_directory_objects(void) int main(void) { + namespace_user_ownership(); + cross_owner_propagation(); bound_directory_objects(); mount_table_objects(); cross_namespace_events(); From 8d21958abefc32d391c987d42d4d26a8edf1963e Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 02:24:04 +0800 Subject: [PATCH 66/97] feat(vfs): support user-owned filesystem mounts and contexts --- Documentation/core-api/mount-namespaces.rst | 13 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 58 +++++-- .../en/LC_MESSAGES/userspace-api/abi.po | 85 +++++++-- .../userspace-api/device-filesystems.po | 33 ++-- .../LC_MESSAGES/core-api/mount-namespaces.po | 47 +++-- .../ja/LC_MESSAGES/userspace-api/abi.po | 75 ++++++-- .../userspace-api/device-filesystems.po | 30 ++-- Documentation/userspace-api/abi.rst | 25 ++- .../userspace-api/device-filesystems.rst | 3 + fs/vfs/mount_internal.h | 1 + fs/vfs/mount_tree.c | 26 ++- include/reliefnt/mount.h | 14 ++ kernel/syscall/device/device_open.c | 6 +- kernel/syscall/fs/Kbuild | 2 +- kernel/syscall/fs/mount.c | 47 +++-- kernel/syscall/fs/mount_api.c | 38 ++-- kernel/syscall/fs/mount_options.c | 86 +++++++++ kernel/syscall/internal.h | 24 ++- tools/test_mount_backend.py | 2 +- tools/tests/mount_backend_test.c | 164 +++++++++++++++++- 20 files changed, 648 insertions(+), 131 deletions(-) create mode 100644 kernel/syscall/fs/mount_options.c diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 20f863dc..2f2ab409 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -89,8 +89,14 @@ no_new_privs,并初始化新空间的能力集合及 securebits。单独创建 先准备用户空间,再以该候选空间作为新图 owner,任一步失败均整体回滚。 bind、bind-remount、move、传播类型修改和卸载要求挂载图 owner 的 -``CAP_SYS_ADMIN``。新后端创建、共享后端 remount 与新 mount API 当前还要求 -初始用户空间的 ``CAP_SYS_ADMIN``;后端 owner 尚待接通。 +``CAP_SYS_ADMIN``。新建 tmpfs 和 devpts 捕获调用者的用户空间作为文件系统 +owner,创建和共享后端 remount 要求该 owner 的 ``CAP_SYS_ADMIN``。其他后端 +保留初始用户空间 owner,其中 proc 仍使用全局 PID 视图。 + +``vfs_mount_set_user_namespace()`` 在首次暴露根路径前设置文件系统 owner。 +bind 和挂载图快照保留该引用,最后一个挂载在后端成功退役后释放它。子用户 +空间拥有的文件系统拒绝设备打开,原生 devpts PTY 除外;bind-remount 清除 +附件的 ``nodev`` 也保留此限制。 句柄与切换 ========== @@ -133,7 +139,8 @@ user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SY fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 释放。清理登录身份继续保留所属空间。 -挂载图管理按图 owner 授权。文件系统 DAC 特权覆盖、共享文件系统后端、设备、 +挂载图管理按图 owner 授权,文件系统创建和重配置按后端 owner 授权。 +文件系统 DAC 特权覆盖、普通设备、 网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 5bb17320..fa27363e 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -172,20 +172,25 @@ msgid "任务凭据持有引用计数的用户命名空间,空指针表示初 msgstr "Task credentials hold a reference to a user namespace. A null pointer represents the initial namespace. Task UIDs and GIDs are global kernel IDs. A child namespace records its creator’s effective UID and retains its parent, with a nesting limit of 32. Fork and kernel-launched tasks inherit the reference. Exec keeps it, and wait or task-slot reuse releases the reference of a zombie. Clearing a login identity preserves the owning namespace." msgid "" -"挂载图管理按图 owner 授权。文件系统 DAC 特权覆盖、共享文件系统后端、设备、 网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 " -"信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner " -"相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp " -"安装使用调用方所属空间的能力集合。" +"挂载图管理按图 owner 授权,文件系统创建和重配置按后端 owner 授权。 文件系统 DAC 特权覆盖、普通设备、 " +"网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 信号、进程优先级、跨进程资源限制与 ptrace " +"按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner " +"相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 " +"seccomp 安装使用调用方所属空间的能力集合。" msgstr "" -"Mount graph management is authorized against the graph owner. Filesystem DAC privilege " -"overrides, shared filesystem backends, devices, networking, IPC, clocks, reboot, modules, " -"memory locking and OOM adjustments use initial-namespace capabilities for shared resources. " -"Signals, process priorities, cross-process resource limits and ptrace are authorized against " -"the target task namespace. Raising hard resource limits still requires initial-namespace " -"capabilities. Capabilities apply to descendant namespaces, and a task whose effective UID in " -"the parent matches a child namespace owner has capabilities over that subtree. Ptrace " -"capability-subset checks require both tasks to share a user namespace. Capset, identity " -"transitions, securebits and seccomp installation use the caller namespace capability sets." +"Mount graph management is authorized against the graph owner. Filesystem " +"creation and reconfiguration are authorized against the backend owner. " +"Filesystem DAC privilege overrides, ordinary devices, networking, IPC, " +"clocks, reboot, modules, memory locking and OOM adjustments use " +"capabilities in the initial namespace. Signals, process priority, " +"cross-process resource limits and ptrace check the target task’s namespace." +" Raising hard resource limits still requires initial-namespace " +"capabilities. Capabilities apply to descendant namespaces. A task in the " +"parent namespace whose effective UID matches a child namespace’s owner has " +"capabilities throughout that subtree. The ptrace capability-set subset " +"check requires both tasks to share a user namespace. capset, identity " +"changes, securebits and seccomp installation use the caller’s namespace " +"capability sets." msgid "" "空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID 转换为全局内核 ID;转换接口通过 acquire " @@ -405,10 +410,25 @@ msgstr "" "locks." msgid "" -"bind、bind-remount、move、传播类型修改和卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。新后端创建、共享后端 remount 与新 mount " -"API 当前还要求 初始用户空间的 ``CAP_SYS_ADMIN``;后端 owner 尚待接通。" +"bind、bind-remount、move、传播类型修改和卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。新建 tmpfs 和 " +"devpts 捕获调用者的用户空间作为文件系统 owner,创建和共享后端 remount 要求该 owner 的 " +"``CAP_SYS_ADMIN``。其他后端 保留初始用户空间 owner,其中 proc 仍使用全局 PID 视图。" msgstr "" -"Bind, bind-remount, move, propagation changes and unmount require ``CAP_SYS_ADMIN`` in the " -"mount graph owner. Fresh backend creation, shared-backend remount and the new mount API " -"currently also require ``CAP_SYS_ADMIN`` in the initial user namespace. Backend ownership " -"remains to be connected." +"Bind, bind-remount, move, propagation changes and unmount require " +"CAP_SYS_ADMIN in the mount graph owner. New tmpfs and devpts filesystems " +"capture the caller’s user namespace as their filesystem owner. Creation and" +" shared-backend remount require CAP_SYS_ADMIN in that owner. Other backends" +" retain the initial user namespace as owner, including proc with its global" +" PID view." + +msgid "" +"``vfs_mount_set_user_namespace()`` 在首次暴露根路径前设置文件系统 owner。 bind " +"和挂载图快照保留该引用,最后一个挂载在后端成功退役后释放它。子用户 空间拥有的文件系统拒绝设备打开,原生 devpts PTY " +"除外;bind-remount 清除 附件的 ``nodev`` 也保留此限制。" +msgstr "" +"``vfs_mount_set_user_namespace()`` sets the filesystem owner before its " +"first root path is exposed. Bind views and mount graph snapshots retain " +"this reference, which the final mount releases after successful backend " +"retirement. Filesystems owned by a child user namespace reject device opens" +" except for native devpts PTYs. This restriction also applies after " +"bind-remount clears the attachment’s ``nodev`` policy." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 1ea7b14b..08337fd2 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -338,17 +338,60 @@ msgstr "Filesystem Contexts and Detached Mounts" msgid "由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 ``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 mountinfo 报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 inode 引用释放且相关缓存回收后,设备号才能重用。" msgstr "Tmpfs instances created by ``mount(2)`` or a filesystem context, and the initial ``/dev/shm``, do not occupy disk volume slots. Each instance has a distinct anonymous device number; ``stat`` and mountinfo report the same device number, and bind mounts share the original instance's number. The number may be reused only after the last mount and inode references are released and their caches are retired." -msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" -msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` creates a filesystem context. The caller needs effective ``CAP_SYS_ADMIN``. ``FSCONFIG_SET_STRING`` in ``fsconfig`` accepts the existing tmpfs options, including ``size``, ``nr_blocks``, ``nr_inodes``, ``mode``, ``uid`` and ``gid``. ``FSCONFIG_SET_FLAG`` accepts ``ro`` and ``rw``. ``FSCONFIG_CMD_CREATE`` creates the filesystem using the configured options and may be retried after failure. The context belongs to the open-file description, is shared after dup or fork, and is released with the final reference." +msgid "" +"``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文,捕获打开者的用户 空间作为文件系统 " +"owner。``fsopen``、``fsmount`` 和 ``move_mount`` 要求 挂载图 owner 的 " +"``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 " +"``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 " +"``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` " +"要求上下文 owner 的 ``CAP_SYS_ADMIN``,使用已设置 选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 " +"fork 后共享,最后一个引用释放时清理。" +msgstr "" +"``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` creates a filesystem context and " +"captures the opener’s user namespace as filesystem owner. ``fsopen``, " +"``fsmount`` and ``move_mount`` require ``CAP_SYS_ADMIN`` in the mount graph" +" owner. ``FSCONFIG_SET_STRING`` through ``fsconfig`` accepts the existing " +"tmpfs options, including ``size``, ``nr_blocks``, ``nr_inodes``, ``mode``, " +"``uid`` and ``gid``. ``FSCONFIG_SET_FLAG`` accepts ``ro`` and ``rw``. " +"``FSCONFIG_CMD_CREATE`` requires ``CAP_SYS_ADMIN`` in the context owner and" +" creates a filesystem from the configured options. Failed creation can be " +"retried. The open file description owns the context, which is shared by dup" +" or fork and cleaned up when its last reference is released." -msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 ``fsmount`` 指定。策略及重配置语义见 :doc:`procfs`。" -msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` also creates an independent proc context. ``FSCONFIG_CMD_CREATE``, ``fsmount`` and ``move_mount`` create and attach the mount. ``FSCONFIG_SET_STRING`` accepts supported ``hidepid`` and ``gid`` parameters. Mount attributes are specified with ``fsmount``. See :doc:`procfs` for the policy and reconfiguration semantics." +msgid "" +"``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 " +"``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 " +"``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 ``fsmount`` " +"指定。proc 的全局 PID 视图保留初始用户空间 owner,CREATE 要求 该 owner 的 " +"``CAP_SYS_ADMIN``。策略及重配置语义见 :doc:`procfs`。" +msgstr "" +"``fsopen(\"proc\", FSOPEN_CLOEXEC)`` also creates an independent proc " +"context. ``FSCONFIG_CMD_CREATE``, ``fsmount`` and ``move_mount`` then " +"create and attach the mount. ``FSCONFIG_SET_STRING`` accepts the supported " +"``hidepid`` and ``gid`` parameters, and ``fsmount`` supplies mount " +"attributes. Proc’s global PID view retains the initial user namespace as " +"owner. CREATE requires ``CAP_SYS_ADMIN`` in that owner. See :doc:`procfs` " +"for policy and reconfiguration semantics." msgid "tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 ``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo 中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" msgstr "Both tmpfs and proc contexts accept the ``source`` parameter with ``FSCONFIG_SET_STRING``. Its value may be empty or contain commas and is limited to 255 bytes. If unset, the source is displayed as ``none``. Setting it twice in the same configuration phase returns ``EINVAL``. Setting parameters after successful creation and before successful ``fsmount`` returns ``EBUSY``. After a successful ``fsmount`` and each successful reconfiguration, a new ``source`` may be set for the next configuration phase. Reconfiguration does not change the existing mount's source in mountinfo. If creation or reconfiguration fails, the pending source remains available for retry." -msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" -msgstr "``fsmount`` returns an ``O_PATH`` descriptor for the detached mount root. It supports ``FSMOUNT_CLOEXEC`` and the readonly, nosuid, nodev, noexec and atime attributes. Files can be accessed relative to this descriptor, and the directory can be reopened via ``/proc/self/fd``. After success, the context can set new options with ``fsconfig`` and update the shared filesystem with ``FSCONFIG_CMD_RECONFIGURE``. Pending options remain after a configuration failure, so the operation can be retried after closing write descriptors that prevent a readonly transition." +msgid "" +"``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` " +"以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` " +"重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` " +"更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。RECONFIGURE 要求 实际文件系统 owner 的 " +"``CAP_SYS_ADMIN``,上下文传递后也执行此权限检查。" +msgstr "" +"``fsmount`` returns an ``O_PATH`` descriptor for the detached mount root. " +"It supports ``FSMOUNT_CLOEXEC`` and readonly, nosuid, nodev, noexec and " +"atime attributes. Files can be accessed relative to the descriptor, and the" +" directory can be reopened through ``/proc/self/fd``. After success, the " +"context accepts new options through ``fsconfig`` and updates the shared " +"filesystem with ``FSCONFIG_CMD_RECONFIGURE``. Failed configuration retains " +"pending options, allowing retry after closing write descriptors that " +"prevent a readonly transition. RECONFIGURE requires ``CAP_SYS_ADMIN`` in " +"the actual filesystem owner, including after the context is transferred." msgid "``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 ``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" msgstr "``move_mount`` attaches the held mount root at a destination and supports the empty-path and symbolic-link flags for both source and destination. Attachment follows the existing propagation rules when the destination mount is shared. ``MOUNT_ATTR_NOSYMFOLLOW`` and ``MOVE_MOUNT_BENEATH`` return ``EINVAL``, allowing callers to use their corresponding compatibility fallbacks." @@ -443,10 +486,28 @@ msgstr "" " can be detached as a whole tree, with descendant coverage locks preserved." msgid "" -"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略且不调用后端。共享后端 remount、新后端创建和新 " -"mount API 当前还要求初始用户空间的 ``CAP_SYS_ADMIN``。" +"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略。新建 " +"tmpfs/devpts 使用调用者用户空间的文件系统 owner,其他后端使用初始用户空间 owner。共享后端 remount 要求文件系统 " +"owner 的 ``CAP_SYS_ADMIN``,bind 别名保留同一 owner。" +msgstr "" +"Clearing inherited readonly, nosuid, nodev or noexec restrictions, or " +"changing the locked atime selection, returns ``EPERM`` and preserves the " +"attachment policy. New tmpfs/devpts filesystems use the caller’s user " +"namespace as filesystem owner. Other backends use the initial user " +"namespace. Shared-backend remount requires ``CAP_SYS_ADMIN`` in the " +"filesystem owner, which bind aliases also retain." + +msgid "" +"tmpfs、devtmpfs、devpts 的 ``uid/gid`` 和 proc 的 ``gid`` 在 mount、remount 或 " +"``FSCONFIG_SET_STRING`` 时按实际写入者的用户空间转换为全局 ID。tmpfs 和 devtmpfs 还要求该 ID " +"能在文件系统 owner 空间表示。十进制输入支持前导零, 未映射、溢出或无效 ID 返回 ``EINVAL``。上下文保存转换后的值,CREATE " +"和 RECONFIGURE 使用这些值;参数写入只要求有效上下文描述符,失败保留原配置。" msgstr "" -"Clearing inherited readonly, nosuid, nodev or noexec, or changing a locked atime selection, " -"returns ``EPERM`` while preserving attachment policy and without invoking the backend. " -"Shared-backend remount, fresh backend creation and the new mount API currently also require " -"``CAP_SYS_ADMIN`` in the initial user namespace." +"The ``uid/gid`` options of tmpfs, devtmpfs and devpts, and proc’s ``gid`` " +"option, are translated from the actual writer’s user namespace to global " +"IDs during mount, remount or ``FSCONFIG_SET_STRING``. tmpfs and devtmpfs " +"also require the ID to be representable in the filesystem owner’s " +"namespace. Decimal input accepts leading zeros. Unmapped, overflowing or " +"invalid IDs return ``EINVAL``. Contexts retain the translated values for " +"CREATE and RECONFIGURE. Writing parameters requires a valid context " +"descriptor, and failure preserves the previous configuration." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 1c32d176..1be5ca47 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -20,14 +20,21 @@ msgstr "Device and control group filesystems" msgid "设备节点创建" msgstr "Device node creation" -msgid "``mknod`` 和 ``mknodat`` 可在 tmpfs、devtmpfs、ext2 和 ext4 上创建字符及块 设备节点,保存 Linux 编码的设备号。新节点的所有者、组和权限遵循目录权限、 组继承及进程的 ``umask``。除字符设备 ``0:0`` 以外,创建设备需要有效的 ``CAP_MKNOD``;只读挂载拒绝创建。设备的后续打开遵循挂载的 ``nodev`` 策略。" +msgid "" +"``mknod`` 和 ``mknodat`` 可在 tmpfs、devtmpfs、ext2 和 ext4 上创建字符及块 设备节点,保存 Linux" +" 编码的设备号。新节点的所有者、组和权限遵循目录权限、 组继承及进程的 ``umask``。除字符设备 ``0:0`` 以外,创建设备需要有效的 " +"``CAP_MKNOD``;只读挂载拒绝创建。设备的后续打开遵循挂载的 ``nodev`` 策略。 子用户空间拥有的文件系统还会拒绝设备打开,原生 " +"devpts PTY 除外。该文件系统 限制随 bind 保留,独立于附件的 ``nodev`` 策略。" msgstr "" -"``mknod`` and ``mknodat`` create character and block device nodes on tmpfs, " -"devtmpfs, ext2 and ext4, retaining the Linux-encoded device number. The " -"owner, group and permissions follow directory access rules, group inheritance " -"and the process ``umask``. Creation requires effective ``CAP_MKNOD`` except " -"for character device ``0:0``. Read-only mounts reject creation. Subsequent " -"device opens obey the mount's ``nodev`` policy." +"``mknod`` and ``mknodat`` create character and block device nodes on tmpfs," +" devtmpfs, ext2 and ext4, storing Linux-encoded device numbers. Ownership, " +"group and permissions follow directory permissions, group inheritance and " +"the process ``umask``. Creating devices other than character device ``0:0``" +" requires effective ``CAP_MKNOD``. Readonly mounts reject creation. " +"Subsequent opens honor the mount’s ``nodev`` policy. Filesystems owned by " +"child user namespaces also reject device opens except for native devpts " +"PTYs. This filesystem restriction is retained across bind mounts and " +"applies independently of attachment ``nodev`` policy." msgid "devtmpfs" msgstr "devtmpfs" @@ -135,12 +142,14 @@ msgstr "devpts mount options" msgid "" "``uid=``、``gid=``:新从端的十进制所有者;未指定时使用创建 PTY 的进程的 ``fsuid``、``fsgid``。根目录和 " -"``ptmx`` 归挂载者,根目录初始权限为 ``0755``。" +"``ptmx`` 归挂载者,根目录初始权限为 ``0755``。 显式 ID 按 mount 或 remount 调用者的用户空间映射,未映射 ID " +"返回 ``EINVAL``。" msgstr "" -"``uid=`` and ``gid=`` set the decimal owner IDs for new slaves. When " -"omitted, they default to the PTY creator's ``fsuid`` and ``fsgid``. The " -"mounter owns the root directory and ``ptmx``. The root directory starts " -"with mode ``0755``." +"``uid=`` and ``gid=`` specify decimal ownership IDs for new slaves. When " +"omitted, the creating process’s ``fsuid`` and ``fsgid`` are used. The mount" +" creator owns the root directory and ``ptmx``. The root starts with mode " +"``0755``. Explicit IDs are mapped through the user namespace of the mount " +"or remount caller. Unmapped IDs return ``EINVAL``." msgid "" "``mode=``、``ptmxmode=``:八进制权限,最多保留 ``07777``。默认从端为 ``0600``、``ptmx`` 为 " diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 43ac3fa5..521cb976 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -149,18 +149,20 @@ msgid "任务凭据持有引用计数的用户命名空间,空指针表示初 msgstr "タスクの資格情報は参照カウント付きのユーザー名前空間を保持します。NULL ポインターは初期名前空間を表します。タスクの UID と GID はグローバルなカーネル ID です。子名前空間は作成者の実効 UID を記録し、親の参照を保持します。入れ子の上限は 32 です。fork とカーネルによるタスク起動は参照を継承し、exec では参照を維持します。ゾンビタスクの参照は wait による回収時またはタスクスロットの再利用時に解放されます。ログイン ID を消去しても所属名前空間は維持されます。" msgid "" -"挂载图管理按图 owner 授权。文件系统 DAC 特权覆盖、共享文件系统后端、设备、 网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 " -"信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner " -"相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp " -"安装使用调用方所属空间的能力集合。" +"挂载图管理按图 owner 授权,文件系统创建和重配置按后端 owner 授权。 文件系统 DAC 特权覆盖、普通设备、 " +"网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 信号、进程优先级、跨进程资源限制与 ptrace " +"按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner " +"相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 " +"seccomp 安装使用调用方所属空间的能力集合。" msgstr "" -"マウントグラフの管理権限はグラフの owner に対して検査します。ファイルシステム DAC " -"の特権回避、共有ファイルシステムバックエンド、デバイス、ネットワーク、IPC、時計、再起動、モジュール、メモリロック、および OOM 調整などの共有資源には初期名前空間の " -"capability を使用します。シグナル、プロセス優先度、プロセス間の資源制限、および ptrace " -"は対象タスクの名前空間に対して権限を検査します。ハード資源制限の引き上げには引き続き初期名前空間の capability が必要です。capability " -"は子孫の名前空間にも適用され、親名前空間の実効 UID が子名前空間の owner と一致するタスクは、そのサブツリーに対する capability を持ちます。ptrace の " -"capability 部分集合検査には同一ユーザー名前空間が必要です。capset、ID 変更、securebits、および seccomp のインストールには呼び出し元の名前空間の " -"capability 集合を使用します。" +"マウントグラフの管理はグラフ owner に基づいて認可され、ファイルシステムの作成と再構成はバックエンド owner " +"に基づいて認可されます。ファイルシステムの DAC " +"特権による上書き、通常のデバイス、ネットワーク、IPC、時計、再起動、モジュール、メモリロック、OOM " +"調整には初期名前空間の能力を使用します。シグナル、プロセス優先度、他プロセスのリソース制限、ptrace " +"は対象タスクの名前空間に基づいて認可されます。ハードリミットの引き上げには引き続き初期名前空間の能力が必要です。能力は子孫名前空間にも適用され、親名前空間で実効" +" UID が子名前空間の owner と一致するタスクは、その部分木全体の能力を持ちます。ptrace " +"の能力集合の部分集合検査には、両タスクが同じユーザー名前空間に属する必要があります。capset、ID 切り替え、securebits、seccomp" +" の設定には、呼び出し元の名前空間の能力集合を使用します。" msgid "" "空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID 转换为全局内核 ID;转换接口通过 acquire " @@ -356,9 +358,22 @@ msgstr "" "を返します。新しい bind ルートと owner をまたいで伝播した新しいルートはツリー全体として切り離せますが、子孫の被覆ロックは維持されます。" msgid "" -"bind、bind-remount、move、传播类型修改和卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。新后端创建、共享后端 remount 与新 mount " -"API 当前还要求 初始用户空间的 ``CAP_SYS_ADMIN``;后端 owner 尚待接通。" +"bind、bind-remount、move、传播类型修改和卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。新建 tmpfs 和 " +"devpts 捕获调用者的用户空间作为文件系统 owner,创建和共享后端 remount 要求该 owner 的 " +"``CAP_SYS_ADMIN``。其他后端 保留初始用户空间 owner,其中 proc 仍使用全局 PID 视图。" msgstr "" -"bind、bind-remount、move、伝播タイプ変更、およびアンマウントには、マウントグラフの owner における ``CAP_SYS_ADMIN`` " -"が必要です。新規バックエンド作成、共有バックエンドの remount、および新しい mount API には、現在は初期ユーザー名前空間の ``CAP_SYS_ADMIN`` " -"も必要です。バックエンドの owner は今後接続します。" +"bind、bind-remount、move、伝播属性の変更とアンマウントには、マウントグラフの owner における CAP_SYS_ADMIN " +"が必要です。新しい tmpfs と devpts は、呼び出し元のユーザー名前空間をファイルシステム owner " +"として保持します。作成と共有バックエンドの remount には、その owner における CAP_SYS_ADMIN " +"が必要です。他のバックエンドは初期ユーザー名前空間を owner とし、proc はグローバルな PID ビューを使用します。" + +msgid "" +"``vfs_mount_set_user_namespace()`` 在首次暴露根路径前设置文件系统 owner。 bind " +"和挂载图快照保留该引用,最后一个挂载在后端成功退役后释放它。子用户 空间拥有的文件系统拒绝设备打开,原生 devpts PTY " +"除外;bind-remount 清除 附件的 ``nodev`` 也保留此限制。" +msgstr "" +"``vfs_mount_set_user_namespace()`` は、最初のルートパスを公開する前にファイルシステム owner " +"を設定します。bind " +"ビューとマウントグラフのスナップショットはこの参照を保持し、最後のマウントがバックエンドの正常な退役後に解放します。子ユーザー名前空間が所有するファイルシステムは、ネイティブ" +" devpts PTY を除くデバイスのオープンを拒否します。bind-remount でアタッチメントの ``nodev`` " +"を解除しても、この制限は適用されます。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 9b3905d1..053a09a8 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -295,17 +295,55 @@ msgstr "ファイルシステムコンテキストと未接続マウント" msgid "由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 ``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 mountinfo 报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 inode 引用释放且相关缓存回收后,设备号才能重用。" msgstr "``mount(2)`` またはファイルシステムコンテキストで作成した tmpfs インスタンスと、起動時の ``/dev/shm`` は、ディスクのボリュームスロットを消費しません。各インスタンスは個別の匿名デバイス番号を持ち、``stat`` と mountinfo は同じ番号を報告します。バインドマウントは元のインスタンスの番号を共有します。最後のマウント参照と inode 参照が解放され、関連するキャッシュが破棄された後にのみ、番号を再利用できます。" -msgid "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。" -msgstr "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` はファイルシステムコンテキストを作成します。呼び出し元には有効な ``CAP_SYS_ADMIN`` が必要です。``fsconfig`` の ``FSCONFIG_SET_STRING`` は ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid``、``gid`` などの既存の tmpfs オプションを受け付けます。``FSCONFIG_SET_FLAG`` は ``ro`` と ``rw`` を受け付けます。``FSCONFIG_CMD_CREATE`` は設定済みオプションでファイルシステムを作成し、失敗後に再試行できます。コンテキストはオープンファイル記述に属し、dup または fork 後に共有され、最後の参照が解放されると破棄されます。" +msgid "" +"``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文,捕获打开者的用户 空间作为文件系统 " +"owner。``fsopen``、``fsmount`` 和 ``move_mount`` 要求 挂载图 owner 的 " +"``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 " +"``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 " +"``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` " +"要求上下文 owner 的 ``CAP_SYS_ADMIN``,使用已设置 选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 " +"fork 后共享,最后一个引用释放时清理。" +msgstr "" +"``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` " +"はファイルシステムコンテキストを作成し、オープンしたタスクのユーザー名前空間をファイルシステム owner " +"として保持します。``fsopen``、``fsmount``、``move_mount`` には、マウントグラフ owner における " +"``CAP_SYS_ADMIN`` が必要です。``fsconfig`` の ``FSCONFIG_SET_STRING`` " +"は、``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid``、``gid`` を含む既存の " +"tmpfs オプションを受け付けます。``FSCONFIG_SET_FLAG`` は ``ro`` と ``rw`` " +"を受け付けます。``FSCONFIG_CMD_CREATE`` はコンテキスト owner における ``CAP_SYS_ADMIN`` " +"を要求し、設定済みのオプションでファイルシステムを作成します。作成失敗後は再試行できます。コンテキストはオープンファイル記述が所有し、dup や " +"fork で共有され、最後の参照の解放時に破棄されます。" -msgid "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 ``fsmount`` 指定。策略及重配置语义见 :doc:`procfs`。" -msgstr "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` でも独立した proc コンテキストを作成できます。``FSCONFIG_CMD_CREATE``、``fsmount``、``move_mount`` でマウントを作成して接続します。``FSCONFIG_SET_STRING`` は対応する ``hidepid`` と ``gid`` のパラメーターを受け付けます。マウント属性は ``fsmount`` で指定します。ポリシーと再設定の意味は :doc:`procfs` を参照してください。" +msgid "" +"``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 " +"``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 " +"``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 ``fsmount`` " +"指定。proc 的全局 PID 视图保留初始用户空间 owner,CREATE 要求 该 owner 的 " +"``CAP_SYS_ADMIN``。策略及重配置语义见 :doc:`procfs`。" +msgstr "" +"``fsopen(\"proc\", FSOPEN_CLOEXEC)`` でも独立した proc コンテキストを作成できます。続いて " +"``FSCONFIG_CMD_CREATE``、``fsmount``、``move_mount`` " +"でマウントを作成して接続します。``FSCONFIG_SET_STRING`` は対応する ``hidepid`` と ``gid`` " +"を受け付け、マウント属性は ``fsmount`` で指定します。proc のグローバル PID ビューは初期ユーザー名前空間を owner " +"として保持し、CREATE にはその owner における ``CAP_SYS_ADMIN`` が必要です。ポリシーと再構成の意味は " +":doc:`procfs` を参照してください。" msgid "tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 ``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo 中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" msgstr "tmpfs と proc のコンテキストはどちらも ``FSCONFIG_SET_STRING`` の ``source`` パラメーターを受け付けます。値は最大 255 バイトで、空文字列やカンマを含む文字列も使用できます。未設定の場合、ソースは ``none`` と表示されます。同じ設定段階で重複して設定すると ``EINVAL`` を返します。作成が成功した後、``fsmount`` が成功する前にパラメーターを設定すると ``EBUSY`` を返します。``fsmount`` の成功後と各再設定の成功後には、次の設定段階で新しい ``source`` を設定できます。再設定は既存マウントの mountinfo に表示されるソースを変更しません。作成または再設定に失敗した場合、保留中のソースは保持され、再試行できます。" -msgid "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。" -msgstr "``fsmount`` は未接続マウントのルートを指す ``O_PATH`` ディスクリプタを返し、``FSMOUNT_CLOEXEC`` と読み取り専用、nosuid、nodev、noexec、atime の属性をサポートします。このディスクリプタを基点にファイルへアクセスでき、``/proc/self/fd`` からディレクトリを開き直すこともできます。成功後、コンテキストは ``fsconfig`` で新しいオプションを設定し、``FSCONFIG_CMD_RECONFIGURE`` で共有ファイルシステムを更新できます。設定失敗時には保留中のオプションが保持されるため、読み取り専用への変更を妨げる書き込みディスクリプタを閉じて再試行できます。" +msgid "" +"``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` " +"以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` " +"重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` " +"更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。RECONFIGURE 要求 实际文件系统 owner 的 " +"``CAP_SYS_ADMIN``,上下文传递后也执行此权限检查。" +msgstr "" +"``fsmount`` は、切り離されたマウントのルートを指す ``O_PATH`` 記述子を返します。``FSMOUNT_CLOEXEC`` と " +"readonly、nosuid、nodev、noexec、atime " +"属性に対応します。この記述子を基準にファイルへアクセスでき、``/proc/self/fd`` からディレクトリを再オープンできます。成功後は " +"``fsconfig`` で新しいオプションを設定し、``FSCONFIG_CMD_RECONFIGURE`` " +"で共有ファイルシステムを更新できます。設定失敗時は保留中のオプションを保持し、読み取り専用への移行を妨げる書き込み記述子を閉じた後に再試行できます。RECONFIGURE" +" には、実際のファイルシステム owner における ``CAP_SYS_ADMIN`` が必要です。コンテキストの受け渡し後もこの権限を検査します。" msgid "``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 ``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" msgstr "``move_mount`` は保持しているマウントルートを宛先に接続し、接続元と宛先の空パスおよびシンボリックリンクのフラグをサポートします。宛先のマウントが共有されている場合、接続には既存の伝播規則が適用されます。``MOUNT_ATTR_NOSYMFOLLOW`` と ``MOVE_MOUNT_BENEATH`` は ``EINVAL`` を返すため、呼び出し元はそれぞれの互換フォールバックを利用できます。" @@ -395,9 +433,24 @@ msgstr "" "ルートと owner をまたいで伝播した新しいルートはツリー全体として切り離せますが、子孫の被覆ロックは保持されます。" msgid "" -"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略且不调用后端。共享后端 remount、新后端创建和新 " -"mount API 当前还要求初始用户空间的 ``CAP_SYS_ADMIN``。" +"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略。新建 " +"tmpfs/devpts 使用调用者用户空间的文件系统 owner,其他后端使用初始用户空间 owner。共享后端 remount 要求文件系统 " +"owner 的 ``CAP_SYS_ADMIN``,bind 别名保留同一 owner。" +msgstr "" +"継承した readonly、nosuid、nodev、noexec の解除や、固定された atime 設定の変更は ``EPERM`` " +"を返し、アタッチメントのポリシーを保持します。新しい tmpfs/devpts は、呼び出し元のユーザー名前空間をファイルシステム owner " +"とします。他のバックエンドは初期ユーザー名前空間を owner とします。共有バックエンドの remount には、ファイルシステム owner " +"における ``CAP_SYS_ADMIN`` が必要です。bind エイリアスも同じ owner を保持します。" + +msgid "" +"tmpfs、devtmpfs、devpts 的 ``uid/gid`` 和 proc 的 ``gid`` 在 mount、remount 或 " +"``FSCONFIG_SET_STRING`` 时按实际写入者的用户空间转换为全局 ID。tmpfs 和 devtmpfs 还要求该 ID " +"能在文件系统 owner 空间表示。十进制输入支持前导零, 未映射、溢出或无效 ID 返回 ``EINVAL``。上下文保存转换后的值,CREATE " +"和 RECONFIGURE 使用这些值;参数写入只要求有效上下文描述符,失败保留原配置。" msgstr "" -"継承した読み取り専用、nosuid、nodev、noexec を解除するか、ロック済み atime 選択を変更すると ``EPERM`` " -"を返し、アタッチメントポリシーを維持してバックエンドを呼び出しません。共有バックエンドの remount、新規バックエンド作成、および新しい mount API " -"には、現在は初期ユーザー名前空間の ``CAP_SYS_ADMIN`` も必要です。" +"tmpfs、devtmpfs、devpts の ``uid/gid`` と proc の ``gid`` " +"は、mount、remount、``FSCONFIG_SET_STRING`` の実行時に、実際の書き込み元のユーザー名前空間からグローバル ID " +"に変換されます。tmpfs と devtmpfs では、その ID がファイルシステム owner の名前空間でも表現可能である必要があります。10 " +"進入力は先頭のゼロを受け付けます。未マッピング、オーバーフロー、無効な ID は ``EINVAL`` " +"を返します。コンテキストは変換後の値を保存し、CREATE と RECONFIGURE " +"が使用します。パラメーターの書き込みには有効なコンテキスト記述子が必要で、失敗時は以前の設定を保持します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index a795006a..4c6f6c0a 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -20,14 +20,20 @@ msgstr "デバイスとコントロールグループのファイルシステム msgid "设备节点创建" msgstr "デバイスノードの作成" -msgid "``mknod`` 和 ``mknodat`` 可在 tmpfs、devtmpfs、ext2 和 ext4 上创建字符及块 设备节点,保存 Linux 编码的设备号。新节点的所有者、组和权限遵循目录权限、 组继承及进程的 ``umask``。除字符设备 ``0:0`` 以外,创建设备需要有效的 ``CAP_MKNOD``;只读挂载拒绝创建。设备的后续打开遵循挂载的 ``nodev`` 策略。" +msgid "" +"``mknod`` 和 ``mknodat`` 可在 tmpfs、devtmpfs、ext2 和 ext4 上创建字符及块 设备节点,保存 Linux" +" 编码的设备号。新节点的所有者、组和权限遵循目录权限、 组继承及进程的 ``umask``。除字符设备 ``0:0`` 以外,创建设备需要有效的 " +"``CAP_MKNOD``;只读挂载拒绝创建。设备的后续打开遵循挂载的 ``nodev`` 策略。 子用户空间拥有的文件系统还会拒绝设备打开,原生 " +"devpts PTY 除外。该文件系统 限制随 bind 保留,独立于附件的 ``nodev`` 策略。" msgstr "" -"``mknod`` と ``mknodat`` は tmpfs、devtmpfs、ext2、ext4 上にキャラクター " -"デバイスおよびブロックデバイスのノードを作成し、Linux 形式のデバイス番号を保存する。" -"新しいノードの所有者、グループ、権限はディレクトリのアクセス権、グループ継承、" -"プロセスの ``umask`` に従う。キャラクターデバイス ``0:0`` を除き、作成には " -"有効な ``CAP_MKNOD`` が必要である。読み取り専用マウントでは作成できない。" -"デバイスを開く際にはマウントの ``nodev`` ポリシーが適用される。" +"``mknod`` と ``mknodat`` は、tmpfs、devtmpfs、ext2、ext4 " +"上に文字デバイスとブロックデバイスのノードを作成し、Linux " +"形式のデバイス番号を保存します。新しいノードの所有者、グループ、アクセス権は、ディレクトリのアクセス権、グループ継承、プロセスの ``umask`` " +"に従います。文字デバイス ``0:0`` 以外の作成には有効な ``CAP_MKNOD`` " +"が必要です。読み取り専用マウントでは作成を拒否します。その後のオープンはマウントの ``nodev`` " +"ポリシーに従います。子ユーザー名前空間が所有するファイルシステムも、ネイティブ devpts PTY " +"を除くデバイスのオープンを拒否します。このファイルシステムの制限は bind マウントにも引き継がれ、アタッチメントの ``nodev`` " +"ポリシーとは独立して適用されます。" msgid "devtmpfs" msgstr "devtmpfs" @@ -124,11 +130,13 @@ msgstr "devpts のマウントオプション" msgid "" "``uid=``、``gid=``:新从端的十进制所有者;未指定时使用创建 PTY 的进程的 ``fsuid``、``fsgid``。根目录和 " -"``ptmx`` 归挂载者,根目录初始权限为 ``0755``。" +"``ptmx`` 归挂载者,根目录初始权限为 ``0755``。 显式 ID 按 mount 或 remount 调用者的用户空间映射,未映射 ID " +"返回 ``EINVAL``。" msgstr "" -"``uid=`` と ``gid=`` は新規スレーブの所有者 ID を 10 進数で指定します。省略時は PTY 作成プロセスの " -"``fsuid`` と ``fsgid`` が使われます。ルートディレクトリと ``ptmx`` " -"の所有者はマウントを行ったユーザーで、ルートディレクトリの初期権限は ``0755`` です。" +"``uid=`` と ``gid=`` は新しいスレーブの所有者 ID を 10 進数で指定します。省略時は PTY 作成元プロセスの " +"``fsuid`` と ``fsgid`` を使用します。ルートディレクトリと ``ptmx`` はマウント実行者が所有し、ルートの初期モードは " +"``0755`` です。明示した ID は mount または remount 呼び出し元のユーザー名前空間でマッピングされ、未マッピングの ID は" +" ``EINVAL`` を返します。" msgid "" "``mode=``、``ptmxmode=``:八进制权限,最多保留 ``07777``。默认从端为 ``0600``、``ptmx`` 为 " diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index c4964739..61e56f2b 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -149,8 +149,9 @@ lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 ` 挂载点的只读标志不会使其可写。 清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 -``EPERM``,保留附件策略且不调用后端。共享后端 remount、新后端创建和新 -mount API 当前还要求初始用户空间的 ``CAP_SYS_ADMIN``。 +``EPERM``,保留附件策略。新建 tmpfs/devpts 使用调用者用户空间的文件系统 +owner,其他后端使用初始用户空间 owner。共享后端 remount 要求文件系统 +owner 的 ``CAP_SYS_ADMIN``,bind 别名保留同一 owner。 只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 @@ -163,13 +164,21 @@ dup、fork 和文件映射持有的同一打开文件描述也会延续这项限 文件系统上下文和游离挂载 ======================== -``fsopen("tmpfs", FSOPEN_CLOEXEC)`` 创建文件系统上下文。调用者需要有效的 -``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs +``fsopen("tmpfs", FSOPEN_CLOEXEC)`` 创建文件系统上下文,捕获打开者的用户 +空间作为文件系统 owner。``fsopen``、``fsmount`` 和 ``move_mount`` 要求 +挂载图 owner 的 ``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 ``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 -``FSCONFIG_CMD_CREATE`` 使用已设置选项创建文件系统,创建失败可重试。 +``FSCONFIG_CMD_CREATE`` 要求上下文 owner 的 ``CAP_SYS_ADMIN``,使用已设置 +选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 fork 后共享,最后一个引用释放时清理。 +tmpfs、devtmpfs、devpts 的 ``uid/gid`` 和 proc 的 ``gid`` 在 mount、remount +或 ``FSCONFIG_SET_STRING`` 时按实际写入者的用户空间转换为全局 ID。tmpfs +和 devtmpfs 还要求该 ID 能在文件系统 owner 空间表示。十进制输入支持前导零, +未映射、溢出或无效 ID 返回 ``EINVAL``。上下文保存转换后的值,CREATE 和 +RECONFIGURE 使用这些值;参数写入只要求有效上下文描述符,失败保留原配置。 + 由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 ``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 mountinfo 报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 @@ -178,7 +187,8 @@ inode 引用释放且相关缓存回收后,设备号才能重用。 ``fsopen("proc", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 -``fsmount`` 指定。策略及重配置语义见 :doc:`procfs`。 +``fsmount`` 指定。proc 的全局 PID 视图保留初始用户空间 owner,CREATE 要求 +该 owner 的 ``CAP_SYS_ADMIN``。策略及重配置语义见 :doc:`procfs`。 tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 @@ -191,7 +201,8 @@ tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数 以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` 更新共享文件系统。配置失败时 -待处理选项保留,关闭阻止只读转换的写入描述符后可重试。 +待处理选项保留,关闭阻止只读转换的写入描述符后可重试。RECONFIGURE 要求 +实际文件系统 owner 的 ``CAP_SYS_ADMIN``,上下文传递后也执行此权限检查。 ``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 684a0c8c..6fe7b4a4 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -9,6 +9,8 @@ 设备节点,保存 Linux 编码的设备号。新节点的所有者、组和权限遵循目录权限、 组继承及进程的 ``umask``。除字符设备 ``0:0`` 以外,创建设备需要有效的 ``CAP_MKNOD``;只读挂载拒绝创建。设备的后续打开遵循挂载的 ``nodev`` 策略。 +子用户空间拥有的文件系统还会拒绝设备打开,原生 devpts PTY 除外。该文件系统 +限制随 bind 保留,独立于附件的 ``nodev`` 策略。 devtmpfs ======== @@ -74,6 +76,7 @@ devpts 挂载选项 * ``uid=``、``gid=``:新从端的十进制所有者;未指定时使用创建 PTY 的进程的 ``fsuid``、``fsgid``。根目录和 ``ptmx`` 归挂载者,根目录初始权限为 ``0755``。 + 显式 ID 按 mount 或 remount 调用者的用户空间映射,未映射 ID 返回 ``EINVAL``。 * ``mode=``、``ptmxmode=``:八进制权限,最多保留 ``07777``。默认从端为 ``0600``、``ptmx`` 为 ``0000``。若直接通过符号链接或绑定挂载打开 ``ptmx``, 可用 ``ptmxmode=0666`` 或相应的 ``chmod`` 让非特权用户访问。 diff --git a/fs/vfs/mount_internal.h b/fs/vfs/mount_internal.h index 6c32adff..630d7cad 100644 --- a/fs/vfs/mount_internal.h +++ b/fs/vfs/mount_internal.h @@ -43,6 +43,7 @@ struct vfs_mount { const struct vfs_backend_ops *ops; void *context; struct module *owner; + struct user_namespace *user_ns; /* Retained immutable filesystem authority. */ uint64_t references,id,policy,peer_group; /* Zero group is not shared. */ uint64_t locked_policy; /* Inherited restrictions and exact atime selection. */ uint64_t staged_peer_group; /* Tentative group of an original mount during MS_MOVE. */ diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index b80550dd..681cf9fd 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -49,6 +49,8 @@ bool vfs_reclaim_pending(void) {return retired_count!=0;} * @return True after successful final destroy/free/module put, false when * finish asks for retry. Execution ownership required; no graph/module lock * spans callbacks. Failure consumes no ownership and never invokes destroy. + * The filesystem user namespace survives retries and is released only after + * the backing path or native backend has completed final teardown. */ static bool vfs_finish_retirement(struct vfs_mount *mount) { @@ -57,14 +59,16 @@ static bool vfs_finish_retirement(struct vfs_mount *mount) if(mount->propagation_backing)--backing.mount->propagation_pins; if(vfs_notify_mount_retired)vfs_notify_mount_retired(mount); struct module *owner=mount->owner; + struct user_namespace *user_ns=mount->user_ns; kernel_free(mount->source);kernel_free(mount); - vfs_path_put(&backing);module_put(owner);return true; + vfs_path_put(&backing);user_namespace_put(user_ns);module_put(owner);return true; } if(mount->ops->finish && mount->ops->finish(mount->context))return false; if(vfs_notify_mount_retired)vfs_notify_mount_retired(mount); struct module *owner=mount->owner; + struct user_namespace *user_ns=mount->user_ns; if(mount->ops->destroy)mount->ops->destroy(mount->context); - kernel_free(mount->source);kernel_free(mount);module_put(owner);return true; + kernel_free(mount->source);kernel_free(mount);user_namespace_put(user_ns);module_put(owner);return true; } /** @brief Retry the initial bounded FIFO batch, retaining each failed owner. @@ -107,6 +111,10 @@ const struct storage_node *vfs_path_node(const struct vfs_path *path) void *vfs_path_context(const struct vfs_path *path) {return vfs_path_valid(path) ? path->mount->context : NULL;} +/** @copydoc vfs_path_user_namespace */ +struct user_namespace *vfs_path_user_namespace(const struct vfs_path *path) +{return vfs_path_valid(path) ? path->mount->user_ns : NULL;} + void vfs_path_get(const struct vfs_path *source,struct vfs_path *out) { if(!out || source==out)return; @@ -210,6 +218,17 @@ int vfs_mount_set_source(struct vfs_mount *mount,const char *source) return vfs_mount_describe(mount,source,mount->filesystem ? mount->filesystem : "none",mount->device); } +/** @copydoc vfs_mount_set_user_namespace */ +int vfs_mount_set_user_namespace(struct vfs_mount *mount,struct user_namespace *owner) +{ + if(!mount)return -EINVAL; + if(mount->ns || mount->point.mount || mount->bind_source.mount || + mount->lazy_detached || mount->exposed_detached)return -EBUSY; + struct user_namespace *old=mount->user_ns; + mount->user_ns=user_namespace_get(owner); + user_namespace_put(old);return 0; +} + /** @brief Construct an owned detached root after live provider admission. * @param ops Persistent callbacks with lookup/retain/release/same_node required. * @param context Borrowed backend transferred to final cleanup on success. @@ -444,7 +463,8 @@ static int vfs_bind_clone(const struct vfs_path *view,const struct vfs_path *bac struct vfs_mount *mount=kernel_malloc(sizeof(*mount)); if(!mount){module_put(original->owner);return -ENOMEM;} *mount=(struct vfs_mount){.ops=original->ops,.context=original->context, - .owner=original->owner,.references=1,.root=view->dentry,.policy=original->policy, + .owner=original->owner,.user_ns=user_namespace_get(original->user_ns), + .references=1,.root=view->dentry,.policy=original->policy, .locked_policy=original->locked_policy,.locked_topology=original->locked_topology, .propagation_backing=propagation}; vfs_path_get(backing,&mount->bind_source); diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 32eaa095..6ad28ea4 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -568,6 +568,14 @@ void vfs_walk_cancel(struct vfs_walk **state); */ int vfs_mount_new(const struct vfs_backend_ops *ops,void *context,struct module *owner, const struct storage_node *root,struct vfs_mount **out); +/** @brief Retain a filesystem's authority scope before exposing its first root. + * @param mount Privately owned new backend mount, required; never a bind clone. + * @param owner Borrowed user scope, NULL for the initial namespace. + * @return Zero, EINVAL for NULL mount or EBUSY after exposure/attachment. + * Execution ownership required. Bind views retain this immutable owner and + * final backend retirement releases it after successful provider teardown. + */ +int vfs_mount_set_user_namespace(struct vfs_mount *mount,struct user_namespace *owner); /** @brief Drop an owned mount handle; retire its root before final teardown. * @param mount Owned reference or NULL; task context under execution ownership. * Lazy detach or a failed finish retains context/code in the retirement queue. @@ -847,6 +855,12 @@ const char *vfs_path_name(const struct vfs_path *path); * @return Backend context or NULL. No ownership transfer. */ void *vfs_path_context(const struct vfs_path *path); +/** @brief Borrow the immutable filesystem authority retained by a path. + * @param path Retained path, nullable, under execution ownership. + * @return Borrowed user namespace; NULL represents the initial scope or an + * invalid path. The caller retains its path throughout authorization. + */ +struct user_namespace *vfs_path_user_namespace(const struct vfs_path *path); /** @brief Read a retained backend file without replaying a namespace pathname. * @param path Borrowed held file under execution ownership. * @param offset Positional byte offset; no OFD cursor is changed. diff --git a/kernel/syscall/device/device_open.c b/kernel/syscall/device/device_open.c index 4e8fb7f1..283abf47 100644 --- a/kernel/syscall/device/device_open.c +++ b/kernel/syscall/device/device_open.c @@ -59,6 +59,8 @@ static int device_ptmx_open(struct task *task, const struct vfs_path *path, uint * @return Descriptor or negative errno. PTY/DRM/audio ownership and failure * rollback use the existing device lifecycles. Devpts slaves resolve through * their held instance/inode identity before global device-number dispatch. + * A filesystem owned by a child user namespace rejects device access except + * its native devpts PTYs, independently of attachment nodev policy. * No mount/module registry spinlock spans any driver callback or wait. */ int task_open_device_path(struct task *task,const struct vfs_path *path,uint32_t flags, @@ -66,7 +68,9 @@ int task_open_device_path(struct task *task,const struct vfs_path *path,uint32_t { const struct storage_node *node=vfs_path_node(path); if(!node)return -RELIEFOS_EINVAL; - if(vfs_path_mount_flags(path)&MS_NODEV)return -RELIEFOS_EACCES; + if((vfs_path_mount_flags(path)&MS_NODEV) || + (vfs_path_user_namespace(path) && !(node->flags&STORAGE_NODE_FLAG_DEVPTS))) + return -RELIEFOS_EACCES; struct storage_node device;bool native=(node->flags&STORAGE_NODE_FLAG_RDEV)!=0; bool devpts = (node->flags & STORAGE_NODE_FLAG_DEVPTS) != 0; if (devpts && !(node->flags & STORAGE_NODE_FLAG_PTY)) diff --git a/kernel/syscall/fs/Kbuild b/kernel/syscall/fs/Kbuild index 84df314f..f00a5359 100644 --- a/kernel/syscall/fs/Kbuild +++ b/kernel/syscall/fs/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := create.o directory.o filesystem.o fs.o legacy_filesystem.o locks.o lookup_state.o metadata.o mount.o mount_api.o mutation.o path.o permissions.o size.o stat.o sync.o timestamps.o xattr.o +obj-y := create.o directory.o filesystem.o fs.o legacy_filesystem.o locks.o lookup_state.o metadata.o mount.o mount_api.o mount_options.o mutation.o path.o permissions.o size.o stat.o sync.o timestamps.o xattr.o include $(srctree)/scripts/Makefile.module diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 260b04f1..0f6f4869 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -111,27 +111,38 @@ static int mount_propagation(struct vfs_namespace *ns,struct task *task,uint64_t /** @brief Validate and apply policy to the actual selected filesystem root. * @param ns Borrowed execution-owned namespace. - * @param task Authorized calling task with retry-stable lookup scope. + * @param task Graph-authorized caller with retry-stable lookup scope. * @param target User target pathname pointer, required. * @param flags Final requested policy with MS_REMOUNT already stripped. * @param options_user Optional user filesystem data copied before use. * @return Zero or lookup/type/unsupported/busy/provider errno. Linux retains * existing atime policy when remount supplies none of its controlling bits. * Local path owns provider lifetime; no graph/module lock spans the callback. + * Filesystem-owner CAP_SYS_ADMIN is checked against the resolved backend. + * UID/GID inputs use the caller's user namespace before atomic reconfiguration. */ static int mount_remount(struct vfs_namespace *ns,struct task *task,uint64_t target,uint64_t flags, uint64_t options_user) { struct vfs_lookup_result found={0}; struct task_user_text options={0}; + char *mapped=NULL; int rc=task_lookup_user_text(task,options_user,VFS_PATH_MAX,true,&options); if(!rc)rc=resolve_user_object_at_flags(ns,task,LINUX_AT_FDCWD,target,false,false,VFS_LOOKUP_FOLLOW,&found); + if(!rc && !task_ns_capable(task,vfs_path_user_namespace(&found.path),CAP_SYS_ADMIN)) + rc=-RELIEFOS_EPERM; + if(!rc) { + uint32_t node_flags=vfs_path_node(&found.path)->flags; + const char *type=node_flags&STORAGE_NODE_FLAG_DEVPTS ? "devpts" : + node_flags&STORAGE_NODE_FLAG_TMPFS ? "tmpfs" : node_flags&STORAGE_NODE_FLAG_PROC ? "proc" : ""; + rc=syscall_mount_options(task,vfs_path_user_namespace(&found.path),type,options.text,&mapped); + } if(!rc) { const uint64_t atime=MS_NOATIME|MS_NODIRATIME|MS_RELATIME|MS_STRICTATIME; if(!(flags&atime))flags|=vfs_path_mount_flags(&found.path)&atime; - rc=vfs_path_remount_options(&found.path,flags,options.text); + rc=vfs_path_remount_options(&found.path,flags,mapped ? mapped : options.text); } - vfs_path_put(&found.path);kernel_free(options.allocation);return rc; + vfs_path_put(&found.path);kernel_free(mapped);kernel_free(options.allocation);return rc; } /** @brief Construct one supported backend without publishing a pathname alias. @@ -206,8 +217,8 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * /** @brief Apply a Linux mount operation using retry-stable actual objects. * @param ns Borrowed live namespace under execution ownership. - * @param task Calling task, required; graph-owner CAP_SYS_ADMIN checked before user input. - * @param number Linux MOUNT or UMOUNT2 operation number. + * @param task Calling task, required; graph operations check graph-owner CAP_SYS_ADMIN. + * @param number Linux MOUNT, UMOUNT2 or filesystem-context operation number. * @param a0 User source/label, or unmount target pointer; ignored for remount * and propagation changes. * @param a1 Mount target pointer, or unmount low-32-bit flags. @@ -219,16 +230,19 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * * @return Zero or negative Linux errno/internal EAGAIN. Text and lookup state * remain scope-owned across waits; temporary unscoped allocations are always * freed. The resulting graph owns backend lifetime, without target prefixes. - * Fresh backends, shared-backend remount and the new mount API additionally - * require initial-user CAP_SYS_ADMIN until backend ownership is represented. + * tmpfs/devpts creation captures the caller's user scope. Other backends use + * their initial resource owner. Remount authorizes the actual backend owner. + * Context parameter writes are descriptor operations; commit checks its owner. */ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_t number, uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4) { + if(!task)return -RELIEFOS_EPERM; + if(number==__NR_fsconfig) + return syscall_new_mount_control(ns,task,number,a0,a1,a2,a3,a4); if(!task || !task_ns_capable(task,ns ? ns->user_ns : NULL,CAP_SYS_ADMIN))return -RELIEFOS_EPERM; if(!ns)return -RELIEFOS_ENOENT; - if(number==__NR_fsopen || number==__NR_fsconfig || number==__NR_fsmount || number==__NR_move_mount) { - if(!task_ns_capable(task,NULL,CAP_SYS_ADMIN))return -RELIEFOS_EPERM; + if(number==__NR_fsopen || number==__NR_fsmount || number==__NR_move_mount) { return syscall_new_mount_control(ns,task,number,a0,a1,a2,a3,a4); } if(number==LINUX_SYS_UMOUNT2)return mount_unmount(ns,task,a0,(uint32_t)a1); @@ -237,22 +251,28 @@ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_ a3&=~MS_SILENT; if(a3&MS_REMOUNT) { if(a3&MS_BIND)return mount_bind_remount(ns,task,a1,a3&~(MS_REMOUNT|MS_BIND)); - if(!task_ns_capable(task,NULL,CAP_SYS_ADMIN))return -RELIEFOS_EPERM; return mount_remount(ns,task,a1,a3&~MS_REMOUNT,a4); } if(a3&MS_BIND)return a3&~(MS_BIND|MS_REC) ? -RELIEFOS_EOPNOTSUPP : mount_bind(ns,task,a0,a1,(a3&MS_REC)!=0); if(a3&VFS_PROPAGATION_MASK)return mount_propagation(ns,task,a1,a3); if(a3&MS_MOVE)return a3!=MS_MOVE ? -RELIEFOS_EOPNOTSUPP : mount_move(ns,task,a0,a1); - if(!task_ns_capable(task,NULL,CAP_SYS_ADMIN))return -RELIEFOS_EPERM; const uint64_t supported=MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_SYNCHRONOUS|MS_DIRSYNC| MS_NOATIME|MS_NODIRATIME|MS_RELATIME|MS_STRICTATIME|MS_LAZYTIME; if(a3&~supported)return -RELIEFOS_EOPNOTSUPP; struct task_user_text type={0},source={0},options={0};struct vfs_lookup_result target={0}; struct vfs_mount *mount=NULL; + char *mapped=NULL; + struct user_namespace *owner=NULL; int rc=task_lookup_user_text(task,a2,VFS_NAME_MAX+1,true,&type); + if(!rc) { + if(!__builtin_strcmp(type.text,"tmpfs") || !__builtin_strcmp(type.text,"devpts")) + owner=task->user_ns; + if(!task_ns_capable(task,owner,CAP_SYS_ADMIN))rc=-RELIEFOS_EPERM; + } if(!rc)rc=task_lookup_user_text(task,a0,VFS_PATH_MAX,true,&source); if(!rc)rc=task_lookup_user_text(task,a4,VFS_PATH_MAX,true,&options); + if(!rc)rc=syscall_mount_options(task,owner,type.text,options.text,&mapped); if(!rc)rc=resolve_user_object_at_flags(ns,task,LINUX_AT_FDCWD,a1,false,false,VFS_LOOKUP_FOLLOW,&target); if(!rc && vfs_path_node(&target.path)->type!=RELIEFOS_FS_TYPE_DIR)rc=-RELIEFOS_ENOTDIR; uint64_t flags=a3; @@ -260,9 +280,10 @@ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_ if(flags&MS_STRICTATIME)flags&=~(MS_NOATIME|MS_RELATIME); storage_set_io_async_context(false); if(!rc)storage_release_task_io(task->pid); - if(!rc)rc=mount_backend(ns,task,source.text,a0,type.text,options.text,flags,&mount); + if(!rc)rc=mount_backend(ns,task,source.text,a0,type.text,mapped ? mapped : options.text,flags,&mount); + if(!rc)rc=vfs_mount_set_user_namespace(mount,owner); if(!rc)rc=vfs_mount_set_flags(mount,flags&(VFS_MOUNT_POLICY_MASK|MS_STRICTATIME)); if(!rc)rc=vfs_mount_attach(ns,mount,&target.path); vfs_mount_put(mount);vfs_path_put(&target.path); - kernel_free(type.allocation);kernel_free(source.allocation);kernel_free(options.allocation);return rc; + kernel_free(mapped);kernel_free(type.allocation);kernel_free(source.allocation);kernel_free(options.allocation);return rc; } diff --git a/kernel/syscall/fs/mount_api.c b/kernel/syscall/fs/mount_api.c index 0965d220..a672afac 100644 --- a/kernel/syscall/fs/mount_api.c +++ b/kernel/syscall/fs/mount_api.c @@ -11,6 +11,7 @@ enum syscall_fs_type { /* A context belongs to one open-file description, including its duplicates. */ struct syscall_fs_context { struct vfs_path root; + struct user_namespace *user_ns; char *source; uint32_t uid, gid; enum syscall_fs_type type; @@ -25,6 +26,7 @@ void syscall_fs_context_release(void *object) struct syscall_fs_context *context = object; if (!context) return; vfs_path_put(&context->root); + user_namespace_put(context->user_ns); kernel_free(context->source); kernel_free(context); } @@ -32,7 +34,8 @@ void syscall_fs_context_release(void *object) /** @brief Create a supported filesystem configuration owned by a new descriptor. * @param task Calling descriptor-table owner. @param type_user User filesystem name. * @param flags Native fsopen flags. @return Descriptor or negative errno. - * Text survives lookup retries and failed allocation leaves no descriptor. + * Captures tmpfs user ownership at fsopen. proc keeps the initial PID-view + * owner. Failed allocation leaves no descriptor or namespace reference. */ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t flags) { @@ -50,7 +53,8 @@ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t fl } if (!rc) { *context = (struct syscall_fs_context){.uid = task->fsuid, .gid = task->fsgid, - .type = filesystem}; + .type = filesystem,.user_ns = user_namespace_get( + filesystem == SYSCALL_FS_TMPFS ? task->user_ns : NULL)}; struct task_file *file = NULL; int fd = task_allocate_fd(task, 0, &file); if (fd < 0) rc = fd; @@ -61,7 +65,7 @@ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t fl file->aux = (uint64_t)(uintptr_t)context; rc = fd; } - if (rc < 0) kernel_free(context); + if (rc < 0) syscall_fs_context_release(context); } kernel_free(type.allocation); return rc; @@ -86,12 +90,14 @@ static int mount_api_context(struct task *task, int32_t fd, struct syscall_fs_co * @param task Caller with an optional retry scope. @param context Live context. * @param command SET_FLAG or SET_STRING. @param key_user Required key. * @param value_user String value or NULL for a flag. - * @return Zero or input, option, allocation or retry errno. + * @return Zero or input, option, allocation or retry errno. Identity strings + * use the writer's namespace once; the pending data stores global IDs. */ static int mount_api_parameter(struct task *task, struct syscall_fs_context *context, uint32_t command, uint64_t key_user, uint64_t value_user) { struct task_user_text key = {0}, value = {0}; + char *mapped = NULL; int rc = task_lookup_user_text(task, key_user, VFS_NAME_MAX + 1, false, &key); bool source = !rc && !__builtin_strcmp(key.text, "source"); if (!rc && command == FSCONFIG_SET_STRING) { @@ -137,33 +143,40 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con __builtin_memcpy(option, key.text, key_length); option[key_length] = '='; __builtin_memcpy(option + key_length + 1, value.text, value_length + 1); - rc = context->type == SYSCALL_FS_PROC ? proc_validate_mount_options(option) : - tmpfs_validate_options(option); + rc = syscall_mount_options(task, context->user_ns, + context->type == SYSCALL_FS_PROC ? "proc" : "tmpfs", option, &mapped); + const char *normalized = mapped ? mapped : option; + if (!rc) rc = context->type == SYSCALL_FS_PROC ? proc_validate_mount_options(normalized) : + tmpfs_validate_options(normalized); if (rc) goto done; size_t used = __builtin_strlen(context->options); - size_t extra = key_length + value_length + 1; + size_t extra = __builtin_strlen(normalized); if (used + (used != 0) + extra + 1 > sizeof(context->options)) { rc = -RELIEFOS_EINVAL; goto done; } if (used) context->options[used++] = ','; - __builtin_memcpy(context->options + used, option, extra + 1); + __builtin_memcpy(context->options + used, normalized, extra + 1); done: + kernel_free(mapped); kernel_free(key.allocation); kernel_free(value.allocation); return rc; } /** @brief Create or reconfigure the context's filesystem transactionally. + * @param task Borrowed caller with stable user-namespace authority. * @param context Borrowed context. @param command CREATE or RECONFIGURE. * @return Zero or negative state, option, busy or resource errno. - * Pending parameters are consumed only after a successful operation. + * CREATE requires context-owner ADMIN, RECONFIGURE checks the actual backend + * owner. Pending parameters are consumed only after a successful operation. */ -static int mount_api_commit(struct syscall_fs_context *context, uint32_t command) +static int mount_api_commit(struct task *task,struct syscall_fs_context *context, uint32_t command) { int rc; if (command == FSCONFIG_CMD_CREATE) { if (context->created) return -RELIEFOS_EBUSY; + if (!task_ns_capable(task,context->user_ns,CAP_SYS_ADMIN)) return -RELIEFOS_EPERM; struct vfs_mount *mount = NULL; uint64_t flags = context->readonly_change > 0 ? MS_RDONLY : 0; if (context->type == SYSCALL_FS_PROC) @@ -172,11 +185,14 @@ static int mount_api_commit(struct syscall_fs_context *context, uint32_t command rc = storage_new_tmpfs_mount("none", flags, context->options, context->uid, context->gid, &mount); if (!rc) rc = vfs_mount_set_source(mount, context->source ? context->source : "none"); + if (!rc) rc = vfs_mount_set_user_namespace(mount, context->user_ns); if (!rc) rc = vfs_mount_detached_root(mount, &context->root); vfs_mount_put(mount); if (!rc) context->created = true; } else { if (!context->mounted) return -RELIEFOS_EBUSY; + if (!task_ns_capable(task,vfs_path_user_namespace(&context->root),CAP_SYS_ADMIN)) + return -RELIEFOS_EPERM; uint64_t flags = vfs_path_mount_flags(&context->root); if (context->readonly_change > 0) flags |= MS_RDONLY; else if (context->readonly_change < 0) flags &= ~MS_RDONLY; @@ -214,7 +230,7 @@ static int64_t mount_api_config(struct task *task, int32_t fd, uint32_t command, } if (command == FSCONFIG_CMD_CREATE || command == FSCONFIG_CMD_RECONFIGURE) { if (key || value) return -RELIEFOS_EINVAL; - return mount_api_commit(context, command); + return mount_api_commit(task,context, command); } return -RELIEFOS_EOPNOTSUPP; } diff --git a/kernel/syscall/fs/mount_options.c b/kernel/syscall/fs/mount_options.c new file mode 100644 index 00000000..1730db33 --- /dev/null +++ b/kernel/syscall/fs/mount_options.c @@ -0,0 +1,86 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "../internal.h" + +/** @brief Map one decimal mount identity from the writer's user namespace. + * @param task Borrowed writer with stable credentials. + * @param owner Filesystem scope, NULL for the initial namespace. + * @param group True for a group identity. + * @param require_owner True when the filesystem must represent the identity. + * @param begin First value byte. @param end Exclusive value end. + * @param out Receives the global identity on success. + * @return Zero or EINVAL for syntax, overflow or an unmapped identity. + */ +static int mount_option_identity(const struct task *task, struct user_namespace *owner, + bool group, bool require_owner, const char *begin, + const char *end, uint32_t *out) +{ + if (begin == end) return -RELIEFOS_EINVAL; + uint32_t value = 0; + for (const char *p = begin; p != end; ++p) { + uint32_t digit = (uint32_t)(*p - '0'); + if (digit > 9 || value > (UINT32_MAX - digit) / 10) return -RELIEFOS_EINVAL; + value = value * 10 + digit; + } + value = user_namespace_id_to_kernel(task->user_ns, group, value); + if (value == UINT32_MAX || (require_owner && + user_namespace_id_from_kernel(owner, group, value) == UINT32_MAX)) return -RELIEFOS_EINVAL; + *out = value; + return 0; +} + +/** @copydoc syscall_mount_options */ +int syscall_mount_options(const struct task *task, struct user_namespace *owner, + const char *filesystem, const char *options, char **out) +{ + *out = NULL; + bool tmpfs = !__builtin_strcmp(filesystem, "tmpfs") || !__builtin_strcmp(filesystem, "devtmpfs"); + bool devpts = !__builtin_strcmp(filesystem, "devpts"); + bool proc = !__builtin_strcmp(filesystem, "proc"); + if (!options || !*options || (!tmpfs && !devpts && !proc)) return 0; + char *mapped = kernel_malloc(VFS_PATH_MAX); + if (!mapped) return -RELIEFOS_ENOMEM; + size_t used = 0; + int rc = 0; + const char *item = options; + while (*item) { + const char *end = item; + while (*end && *end != ',') ++end; + size_t length = (size_t)(end - item); + char digits[10]; + size_t count = 0; + bool uid = length >= 4 && !__builtin_memcmp(item, "uid=", 4); + bool gid = length >= 4 && !__builtin_memcmp(item, "gid=", 4); + if (gid || (uid && !proc)) { + uint32_t identity; + rc = mount_option_identity(task, owner, gid, tmpfs, item + 4, end, &identity); + if (rc) break; + do { + digits[count++] = (char)('0' + identity % 10); + identity /= 10; + } while (identity); + length = 4 + count; + } + size_t separator = *end == ','; + if (used + length + separator >= VFS_PATH_MAX) { + rc = -RELIEFOS_EINVAL; + break; + } + if (count) { + __builtin_memcpy(mapped + used, item, 4); + used += 4; + while (count) mapped[used++] = digits[--count]; + } else { + __builtin_memcpy(mapped + used, item, length); + used += length; + } + if (separator) mapped[used++] = ','; + item = end + separator; + } + if (rc) { + kernel_free(mapped); + return rc; + } + mapped[used] = 0; + *out = mapped; + return 0; +} diff --git a/kernel/syscall/internal.h b/kernel/syscall/internal.h index fb163278..8ef8a8f7 100644 --- a/kernel/syscall/internal.h +++ b/kernel/syscall/internal.h @@ -1401,8 +1401,9 @@ int64_t syscall_fallocate_object(struct task *task,int32_t fd,uint32_t mode,uint int64_t syscall_sync_object(struct vfs_namespace *ns,struct task *task,uint64_t number,int32_t fd); /** @brief Implement mount operations in the one actual referenced namespace. * @param ns Borrowed live namespace under execution ownership, required. - * @param task Calling task with actual root/cwd, required; CAP_SYS_ADMIN checked. - * @param number Linux MOUNT or UMOUNT2 syscall number. + * @param task Calling task with actual root/cwd, required; graph operations + * require graph-owner CAP_SYS_ADMIN and backend changes require its owner. + * @param number Linux MOUNT, UMOUNT2 or filesystem-context syscall number. * @param a0 User source pathname/label, or UMOUNT2 target pathname. * @param a1 User MOUNT target pathname, or low-32-bit UMOUNT2 flags. * @param a2 User filesystem type, ignored for remount/move/unmount. @@ -1412,11 +1413,25 @@ int64_t syscall_sync_object(struct vfs_namespace *ns,struct task *task,uint64_t * Copied inputs and actual operands survive EAGAIN. Completed unmount sync * retires its own scoped lookup before busy checking, while a local path * protects the provider. No diagnostic path replay or lock across callbacks. - * The mounted graph is owned by the initial user namespace. + * Filesystem-context parameters use the writer's identity mapping, with + * capability admission deferred to CREATE or RECONFIGURE. */ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_t number, uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4); +/** @brief Copy mount options with caller-local identities converted to global IDs. + * @param task Borrowed writer with stable user namespace and credentials. + * @param owner Borrowed filesystem authority, NULL for initial scope. + * @param filesystem Required kernel filesystem name. + * @param options Copied kernel data, nullable, bounded by VFS_PATH_MAX. + * @param out Required owned-copy output; NULL when the input needs no conversion. + * @return Zero or negative EINVAL/ENOMEM. tmpfs IDs must also map in owner. + * Device filesystems and proc gid use the writer mapping. Failure changes no + * live policy and consumes no input. Caller frees a returned copy. + */ +int syscall_mount_options(const struct task *task,struct user_namespace *owner, + const char *filesystem,const char *options,char **out); + /** @brief Execute an admitted Linux filesystem-context or mount-fd operation. * @param ns Retained caller namespace. @param task Authorized calling task. * @param number Native syscall number. @param a0 First ABI argument. @@ -1428,7 +1443,8 @@ int64_t syscall_new_mount_control(struct vfs_namespace *ns,struct task *task,uin uint64_t a0,uint64_t a1,uint64_t a2,uint64_t a3,uint64_t a4); /** @brief Release the filesystem context owned by a final open-file description. - * @param context Owned context, nullable. Releases its retained filesystem root. + * @param context Owned context, nullable. Releases its retained filesystem root + * and captured filesystem user namespace after final descriptor teardown. */ void syscall_fs_context_release(void *context); diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index 2b25310e..1f1198e5 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -31,7 +31,7 @@ def test_real_tmpfs_without_text_routing(self): "fs/notify/core.c", "fs/notify/limits.c", "fs/notify/queue.c", "fs/notify/watch.c", "fs/vfs/filesystems.c", "fs/vfs/filesystem_instance.c", "fs/ext_common/journal.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/kernel_file.c", "fs/vfs/kernel_path.c", "fs/vfs/exec_file.c", "fs/vfs/attributes.c", "fs/vfs/initial.c", "fs/vfs/storage_initial.c", "fs/vfs/storage_attributes.c", "fs/vfs/storage_access.c", "fs/vfs/storage_backend.c", "fs/vfs/mutation.c", "fs/vfs/storage_mutation.c", "fs/vfs/storage_create.c", "fs/vfs/storage_security.c", "fs/vfs/write_access.c", "fs/devpts/devpts.c", "drivers/tty/pty/core.c", "drivers/tty/pty/ring.c", "drivers/tty/pty/line_discipline.c", "drivers/tty/pty/session.c", "drivers/tty/pty/vt.c", "kernel/syscall/device/device_open.c", "kernel/syscall/device/device_io.c", "kernel/syscall/fs/stat.c", "fs/vfs/storage_mount.c", "fs/vfs/fat_options.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "fs/security/access.c", "lib/text_utf16.c", "fs/devfs/mount.c", "fs/devfs/devtmpfs.c", "fs/devfs/devtmpfs_nodes.c", "fs/devfs/device.c", "fs/devfs/identity.c", "fs/vfs/pseudo.c", "kernel/exec/runtime.c", "kernel/exec/pending.c", "kernel/syscall/process/exec.c", "kernel/syscall/system/user_string.c", - "kernel/syscall/ipc/unix_path.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/create.c", "kernel/syscall/fs/mount.c", "kernel/syscall/fs/mount_api.c", "kernel/syscall/fs/mutation.c", "kernel/syscall/fs/directory.c", "kernel/syscall/fs/size.c", "kernel/syscall/fs/sync.c", "kernel/syscall/fs/path.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fd/descriptor.c", "kernel/syscall/fd/open.c", "kernel/device/character.c", "kernel/syscall/io/vector.c", "kernel/syscall/fd/pty_descriptor.c", "kernel/sched/tables.c", "kernel/device/mapping.c", "kernel/sched/fs.c", "kernel/sync/wait.c", "-o", str(binary) + "kernel/syscall/ipc/unix_path.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/create.c", "kernel/syscall/fs/mount.c", "kernel/syscall/fs/mount_api.c", "kernel/syscall/fs/mount_options.c", "kernel/syscall/fs/mutation.c", "kernel/syscall/fs/directory.c", "kernel/syscall/fs/size.c", "kernel/syscall/fs/sync.c", "kernel/syscall/fs/path.c", "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fd/descriptor.c", "kernel/syscall/fd/open.c", "kernel/device/character.c", "kernel/syscall/io/vector.c", "kernel/syscall/fd/pty_descriptor.c", "kernel/sched/tables.c", "kernel/device/mapping.c", "kernel/sched/fs.c", "kernel/sync/wait.c", "-o", str(binary) ], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=20) for filesystem in ("ext2", "ext4"): diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 172c09c7..5d3a1b73 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -2717,13 +2717,8 @@ static void runtime_mount_user_authority(struct vfs_namespace *ns,const struct v assert(!scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,0,target,0,MS_PRIVATE,0)); assert(!scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,target,next,0,MS_MOVE,0)); - /* Backend authority is still initial-scope until backend owners exist. */ + /* An inherited backend still belongs to its original user scope. */ assert(scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,0,next,0,MS_REMOUNT,0)==-EPERM); - assert(scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,0,target,(uintptr_t)user.type,0,0)==-EPERM); - assert(scoped_mount_call(owned,&actor,__NR_fsopen,(uintptr_t)user.type,0,0,0,0)==-EPERM); - assert(scoped_mount_call(owned,&actor,__NR_fsconfig,0,6,0,0,0)==-EPERM); - assert(scoped_mount_call(owned,&actor,__NR_fsmount,0,0,0,0,0)==-EPERM); - assert(scoped_mount_call(owned,&actor,__NR_move_mount,0,0,0,0,0)==-EPERM); assert(scoped_mount_call(owned,&actor,LINUX_SYS_UMOUNT2,(uintptr_t)user.root,0,0,0,0)==-EINVAL); assert(scoped_mount_call(owned,&actor,LINUX_SYS_UMOUNT2,(uintptr_t)user.root,MNT_DETACH,0,0,0)==-EINVAL); assert(!scoped_mount_call(owned,&actor,LINUX_SYS_UMOUNT2,next,0,0,0,0)); @@ -2739,6 +2734,162 @@ static void runtime_mount_user_authority(struct vfs_namespace *ns,const struct v puts("PASS mount syscall authority: graph owner, local capabilities, inherited coverage and backend boundary"); } +/** @brief Exercise scoped backends, mapped options and transferred contexts. + * @param ns Initial graph. @param root Retained initial root. + * @param fs Writable initial tmpfs for fixture mountpoints. + */ +static void runtime_mount_user_backends(struct vfs_namespace *ns,const struct vfs_path *root, + struct tmpfs_super *fs) +{ + struct { + char target[32],alias[32],pts[32],tmpfs[8],devpts[8],proc[8],device[16]; + char options[96],uid[4],gid[4],value[32],empty[1],root[2]; + } user={"/userfs-target","/userfs-alias","/userfs-pts","tmpfs","devpts","proc", + "devtmpfs","uid=1,gid=2,mode=0750","uid","gid","3","","/"}; + const char *directories[]={user.target,user.alias,user.pts}; + for(unsigned i=0;i<3;++i)assert(!tmpfs_create(fs,directories[i],LINUX_S_IFDIR|0755,NULL,NULL)); + struct task creator={.euid=5000,.cap_effective=UINT64_MAX}; + struct user_namespace *owner=NULL,*sibling=NULL; + assert(!user_namespace_create(&creator,&owner)); + assert(!user_namespace_create(&creator,&sibling)); + for(unsigned group=0;group<2;++group) { + struct user_namespace_file control; + assert(!user_namespace_file_open(owner,&creator, + group ? USER_NAMESPACE_GID_MAP : USER_NAMESPACE_UID_MAP,true,&control)); + uint32_t written=0; + assert(!user_namespace_file_write(&control,&creator,0,"0 1000 32\n",10,&written) && written==10); + user_namespace_file_close(&control); + } + struct task actor={.pid=912,.user_ns=owner,.euid=1000,.fsuid=1000,.fsgid=1000, + .cap_effective=1ULL<nofile.rlim_cur=32; + vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); + struct vfs_namespace *owned=NULL; + assert(!vfs_namespace_clone_owned(ns,owner,&actor.fs_paths.root,&actor.fs_paths.cwd,&owned)); + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + uint64_t target=(uintptr_t)user.target,alias=(uintptr_t)user.alias,options=(uintptr_t)user.options; + uint64_t type=(uintptr_t)user.tmpfs; + + /* The former initial-scope gate prevents this real tmpfs publication. */ + assert(!scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,0,target,type,0,options)); + struct vfs_path mounted={0},bound={0}; + assert(!vfs_path_lookup(owned,&actor.fs_paths.root,&actor.fs_paths.cwd,user.target,0,&mounted)); + struct reliefos_permissions permissions; + assert(!vfs_path_permissions(&mounted,&permissions,false)); + assert(permissions.uid==1001 && permissions.gid==1002 && permissions.mode==0750); + assert(!scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,target,alias,0,MS_BIND,0)); + assert(!vfs_path_lookup(owned,&actor.fs_paths.root,&actor.fs_paths.cwd,user.alias,0,&bound)); + assert(!scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,0,alias,0,MS_REMOUNT|MS_RDONLY,options)); + assert(vfs_path_mount_flags(&mounted)&MS_RDONLY); + strcpy(user.options,"uid=32"); + assert(scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,0,alias,0,MS_REMOUNT,options)==-EINVAL); + assert(vfs_path_mount_flags(&bound)&MS_RDONLY); + strcpy(user.options,"uid=0,gid=0"); + assert(!scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,0,alias,0,MS_REMOUNT,options)); + assert(!vfs_path_permissions(&mounted,&permissions,false) && permissions.uid==1001); + struct vfs_path device={0}; + struct reliefos_permissions device_mode={0666,1000,1000}; + assert(!vfs_path_create_device(&mounted,"null",LINUX_S_IFCHR,&device_mode,0x103,&device)); + assert(task_open_device_path(&actor,&device,LINUX_O_RDWR,NULL)==-EACCES); + vfs_path_put(&device); + assert(!scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,0,alias,0,MS_BIND|MS_REMOUNT,0)); + assert(!vfs_path_lookup_child(&bound,"null",&device)); + assert(task_open_device_path(&actor,&device,LINUX_O_RDWR,NULL)==-EACCES); + vfs_path_put(&device); + vfs_path_put(&mounted);vfs_path_put(&bound); + assert(!scoped_mount_call(owned,&actor,LINUX_SYS_UMOUNT2,alias,0,0,0,0)); + assert(!scoped_mount_call(owned,&actor,LINUX_SYS_UMOUNT2,target,0,0,0,0)); + + /* Invalid local IDs and allocation failures leave the mountpoint uncovered. */ + const char *invalid[]={"uid=32","gid=4294967295","uid=4294967296","uid=-1","uid=1x"}; + for(unsigned i=0;i=0); + task_pty_release_entry(task_pty_fd_for_fd(&actor,master)); + uint32_t pty_id=0; + assert(!devpts_new_pty(&mounted,actor.pid,1000,1000,&pty_id)); + assert(!vfs_path_lookup(owned,&actor.fs_paths.root,&actor.fs_paths.cwd,"/userfs-pts/0",0,&bound)); + assert(!vfs_path_permissions(&bound,&permissions,false)); + assert(permissions.uid==1003 && permissions.gid==1004 && permissions.mode==0620); + assert(!pty_destroy(actor.pid,pty_id));vfs_path_put(&bound);vfs_path_put(&mounted); + assert(!scoped_mount_call(owned,&actor,LINUX_SYS_UMOUNT2,(uintptr_t)user.pts,0,0,0,0)); + + uint64_t references=owner->references; + sched_task_limits(&actor)->nofile.rlim_cur=0; + assert(scoped_mount_call(owned,&actor,__NR_fsopen,type,0,0,0,0)==-EMFILE); + assert(owner->references==references); + sched_task_limits(&actor)->nofile.rlim_cur=32; + int context=scoped_mount_call(owned,&actor,__NR_fsopen,type,0,0,0,0); + assert(context>=0 && owner->references==references+1); + assert(!scoped_mount_call(owned,&actor,__NR_fsconfig,context,1,(uintptr_t)user.uid,(uintptr_t)user.value,0)); + strcpy(user.value,"32"); + assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,1,(uintptr_t)user.gid,(uintptr_t)user.value,0)==-EINVAL); + + /* Parameters use the writer's mapping, while CREATE retains the opener scope. */ + actor.user_ns=NULL;actor.cap_effective=0; + strcpy(user.value,"42"); + assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,1,(uintptr_t)user.uid,(uintptr_t)user.value,0)==-EINVAL); + strcpy(user.value,"1005"); + assert(!scoped_mount_call(owned,&actor,__NR_fsconfig,context,1,(uintptr_t)user.gid,(uintptr_t)user.value,0)); + assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,6,0,0,0)==-EPERM); + actor.user_ns=sibling;actor.cap_effective=1ULL<=0); + struct task_file *file=task_file_for_fd(&actor,mountfd); + assert(!vfs_path_permissions(&file->path_ref,&permissions,false)); + assert(permissions.uid==1003 && permissions.gid==1005); + actor.user_ns=sibling; + assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,7,0,0,0)==-EPERM); + actor.user_ns=owner;actor.cap_effective=0; + assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,7,0,0,0)==-EPERM); + actor.cap_effective=1ULL<=0); + assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,6,0,0,0)==-EPERM); + task_discard_file_fd(&actor,context); + lookup_user_base=lookup_user_bytes=0; + sched_task_pty_release(&actor); + vfs_path_put(&actor.fs_paths.cwd);vfs_path_put(&actor.fs_paths.root); + vfs_namespace_put(owned); + while(vfs_reclaim_pending())vfs_reclaim_mounts(UINT32_MAX); + assert(owner->references==1); + user_namespace_put(owner);user_namespace_put(sibling); + for(unsigned i=0;i<3;++i)assert(!tmpfs_unlink(fs,directories[i],true)); + puts("PASS scoped filesystems: mapped tmpfs/devpts, backend remount, context transfer, rollback and lifetime"); +} + /** @brief Exercise the detached tmpfs lifecycle used by systemd credentials. */ static void runtime_new_mount_api(struct vfs_namespace *ns,const struct vfs_path *root, struct tmpfs_super *fs) @@ -4879,6 +5030,7 @@ int main(int argc,char **argv) runtime_attachment_policies(&ns,&root); runtime_mount_syscalls(&ns,&root,fs); runtime_mount_user_authority(&ns,&root,fs); + runtime_mount_user_backends(&ns,&root,fs); runtime_file_bind(&ns,&root,fs); runtime_recursive_bind(&ns,&root,fs); runtime_shared_mounts(&ns,&root); From 3add01cdd4db166755ccea826deeaaf25580e901 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 03:29:57 +0800 Subject: [PATCH 67/97] feat(uts): support user-owned hostname namespaces and sysctls --- Documentation/core-api/mount-namespaces.rst | 34 ++++- .../LC_MESSAGES/core-api/mount-namespaces.po | 24 ++- .../en/LC_MESSAGES/userspace-api/abi.po | 33 +++- .../LC_MESSAGES/core-api/mount-namespaces.po | 24 ++- .../ja/LC_MESSAGES/userspace-api/abi.po | 33 +++- Documentation/userspace-api/abi.rst | 42 +++++- fs/nsfs/namespace.c | 38 ++++- fs/proc/internal.h | 6 + fs/proc/mount.c | 2 +- fs/proc/procfs.c | 54 +++++-- fs/security/access.c | 5 +- fs/vfs/attributes.c | 8 + fs/vfs/pseudo.c | 19 ++- include/reliefnt/mount.h | 14 ++ include/reliefnt/nsfs.h | 27 +++- include/reliefnt/permissions.h | 5 +- include/reliefnt/pseudo_fs.h | 2 + include/reliefnt/task/accessors.h | 6 +- include/reliefnt/task/types.h | 2 + include/reliefnt/user_namespace.h | 10 +- include/reliefnt/uts.h | 53 ++++++- kernel/init/uts.c | 99 ++++++++++-- kernel/sched/clone.c | 21 ++- kernel/sched/internal.h | 1 + kernel/sched/session.c | 3 +- kernel/sched/task.c | 4 +- kernel/sched/user_namespace_task.c | 28 +++- kernel/sched/wait.c | 4 +- kernel/syscall/process/clone.c | 10 +- kernel/syscall/process/process.c | 3 +- kernel/syscall/process/setns.c | 15 +- tools/test_linux_inventory.py | 2 +- tools/test_lock_profile.py | 4 +- tools/test_memory_reporting.py | 6 +- tools/test_procfs.py | 2 +- tools/test_rootfs.py | 5 +- tools/tests/modules/scheduler.h | 1 + tools/tests/mount_namespace_task_test.c | 141 +++++++++++++++++- tools/tests/procfs_directories_test.c | 136 ++++++++++++++++- tools/tests/rootfs_uts_test.c | 5 + 40 files changed, 820 insertions(+), 111 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 2f2ab409..25c0679b 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -70,6 +70,12 @@ VFS 只登记已发布的 shared 和 slave 挂载。传播关系不延长挂载 重新查找 PID,因此目标退出后也可继续读取。若所持查看根已被延迟摘除,读取返回 空列表;若传入属于其他活动图的查看根,渲染器返回 ``EXDEV``。 +``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 读取调用者 +UTS 空间的名称并追加换行,权限为全局 UID/GID 0 的 ``0644``。写打开和每次 +写入检查全局有效 UID 0,写回选择实际调用者当时的 UTS 空间。继承或传递的 FD +沿用这一规则。VFS 检查实际挂载的只读策略。sysctl 名称最多 64 字节,写入在 +首个换行或 NUL 处停止并补零,具体用户接口见 :doc:`../userspace-api/abi`。 + 用户态创建 ========== @@ -88,6 +94,13 @@ no_new_privs,并初始化新空间的能力集合及 securebits。单独创建 当前用户空间的 ``CAP_SYS_ADMIN``;组合 ``CLONE_NEWUSER | CLONE_NEWNS`` 先准备用户空间,再以该候选空间作为新图 owner,任一步失败均整体回滚。 +``CLONE_NEWUTS`` 为 clone 子任务或 unshare 调用者复制当前 hostname 和 +domainname,并持有当前用户空间作为不可变 owner。同时创建用户空间时使用 +候选用户空间作为 owner,准备失败释放候选空间及其引用。普通 fork 和未指定 +``CLONE_NEWUTS`` 的 clone 取得原 UTS 空间的共享引用。单独创建要求当前用户 +空间的 ``CAP_SYS_ADMIN``,UTS 创建允许共享 ``CLONE_FS`` 状态,单独 unshare +UTS 保留该共享状态。 + bind、bind-remount、move、传播类型修改和卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。新建 tmpfs 和 devpts 捕获调用者的用户空间作为文件系统 owner,创建和共享后端 remount 要求该 owner 的 ``CAP_SYS_ADMIN``。其他后端 @@ -101,14 +114,15 @@ bind 和挂载图快照保留该引用,最后一个挂载在后端成功退役 句柄与切换 ========== -``/proc//ns/mnt`` 与 ``/proc//ns/user`` 是 proc magic link。 +``/proc//ns/mnt``、``/proc//ns/user`` 与 ``/proc//ns/uts`` +是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 -PID 身份,每次成功跟随则取得目标当时的挂载图或用户空间。 +PID 身份,每次成功跟随则取得目标当时的挂载图、用户空间或 UTS 空间。 -跟随链接得到分离的 nsfs inode。mount 与 user 空间使用同一单调递增序列,首次 +跟随链接得到分离的 nsfs inode。mount、user 与 UTS 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 -返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。 +返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]``、``user:[inode]`` 或 ``uts:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。 ``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 @@ -122,6 +136,10 @@ user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SY 集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。 +UTS 切换要求当前用户空间和目标 UTS owner 用户空间两侧的 ``CAP_SYS_ADMIN``, +允许共享文件系统状态。成功时替换任务的 UTS 引用并释放旧引用。 +``NS_GET_NSTYPE`` 对 UTS 句柄返回 ``CLONE_NEWUTS``。 + 引用释放 ======== @@ -131,6 +149,12 @@ user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SY 管理;严格的 ``vfs_namespace_destroy()`` 在仍有图引用或外部路径引用时拒绝销毁。 快照全部准备成功后才持有 owner 引用,图退役或销毁时释放它。 +``struct uts_namespace`` 使用原子引用计数,任务和 nsfs 后端分别持有引用, +最后一个引用释放时同时释放 owner 用户空间。空指针表示永久初始 UTS 空间。 +hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护。 +``sethostname()`` 和 ``setdomainname()`` 按 UTS owner 的 ``CAP_SYS_ADMIN`` +授权,按长度复制 0 至 64 字节,保留换行与内嵌 NUL,尾部补零。 + 凭据权限作用域 ============== @@ -153,7 +177,7 @@ ptrace 的能力集合子集检查要求双方位于同一用户空间。capset 初始空间使用恒等映射,``UINT32_MAX`` 为无效 ID。每个父空间范围必须完整落在 同一映射段内,本地与父范围均不能重叠或包含无效 ID。 -proc 控制文件在打开时保留目标空间、打开者空间及其标量凭据。写入使用捕获权限 +用户空间映射与 setgroups 控制文件在打开时保留目标空间、打开者空间及其标量凭据。写入使用捕获权限 和当前调用者权限,目标退出或 PID 重用后仍操作原空间。所有映射与 setgroups 策略提交由现有独占执行权串行化,候选解析、权限和分配失败均不发布状态;最后 一个空间引用释放映射并逐级释放父空间。用户接口见 :doc:`../userspace-api/procfs`。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index fa27363e..7bc874a9 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -206,11 +206,11 @@ msgstr "" "invalid ID." msgid "" -"proc 控制文件在打开时保留目标空间、打开者空间及其标量凭据。写入使用捕获权限 和当前调用者权限,目标退出或 PID " +"用户空间映射与 setgroups 控制文件在打开时保留目标空间、打开者空间及其标量凭据。写入使用捕获权限 和当前调用者权限,目标退出或 PID " "重用后仍操作原空间。所有映射与 setgroups 策略提交由现有独占执行权串行化,候选解析、权限和分配失败均不发布状态;最后 " "一个空间引用释放映射并逐级释放父空间。用户接口见 :doc:`../userspace-api/procfs`。" msgstr "" -"Opening a proc control retains the target scope, opener scope and scalar " +"Opening a user namespace mapping or setgroups control retains the target scope, opener scope and scalar " "opener credentials. Writes check captured and current authority and keep " "operating on the retained scope after task exit or PID reuse. Existing " "exclusive execution ownership serializes all map and setgroups policy " @@ -341,8 +341,8 @@ msgstr "Message queue, semaphore and shared-memory registries, permission checks msgid "``IPC_SET`` 先执行现有对象所有权与资源限制检查,再将输入的 UID/GID 全部 转换为全局 ID。任一输入未映射或为 ``UINT32_MAX`` 时返回 ``EINVAL``,对象的 身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 用户空间检查。" msgstr "``IPC_SET`` first performs the existing object ownership and resource-limit checks, then translates both input UID/GID values into global IDs. An unmapped input or ``UINT32_MAX`` returns ``EINVAL``, preserving the object identities, permissions, capacity and modification time. Success updates the owner and low 0777 permission bits while preserving creator identities and shared-memory lock and deletion flags. Global IPC administration and resource privileges are still checked in the initial user namespace." -msgid "``/proc//ns/mnt`` 与 ``/proc//ns/user`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图或用户空间。" -msgstr "``/proc//ns/mnt`` and ``/proc//ns/user`` are proc magic links. Reading or following them requires the same ``PTRACE_MODE_READ_FSCREDS`` check as ``/proc//fd``. Link keys retain PID identity. Each successful follow captures the target task current mount graph or user namespace." +msgid "``/proc//ns/mnt``、``/proc//ns/user`` 与 ``/proc//ns/uts`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图、用户空间或 UTS 空间。" +msgstr "``/proc//ns/mnt``, ``/proc//ns/user`` and ``/proc//ns/uts`` are proc magic links. Reading or following them requires the same ``PTRACE_MODE_READ_FSCREDS`` check as ``/proc//fd``. Link keys retain PID identity. Each successful follow captures the target task current mount graph, user namespace or UTS namespace." msgid "" "``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare " @@ -374,8 +374,8 @@ msgstr "" msgid "user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。" msgstr "A user namespace switch requires a single thread, exclusive filesystem state and ``CAP_SYS_ADMIN`` in the target namespace, and rejects reentry into the current namespace. Success preserves root, cwd and global identities and reuses namespace installation to reset capability sets and securebits. Increased scoped authority restricts dumpability and clears the parent-death signal. A NULL pointer represents the initial user namespace. Authenticated handle types and the boolean query distinguish that valid identity from an invalid path." -msgid "跟随链接得到分离的 nsfs inode。mount 与 user 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" -msgstr "Following a link obtains a detached nsfs inode. Mount and user namespaces share one monotonically increasing sequence. The first display or handle creation assigns an inode, and every handle for that namespace shares this identity. Exhausting the 64-bit sequence returns ``EOVERFLOW``. Labels are ``mnt:[inode]`` or ``user:[inode]``. Each typed backend retains its namespace. Final path release reclaims the backend and drops the namespace reference." +msgid "跟随链接得到分离的 nsfs inode。mount、user 与 UTS 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]``、``user:[inode]`` 或 ``uts:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" +msgstr "Following a link obtains a detached nsfs inode. Mount, user and UTS namespaces share one monotonically increasing sequence. The first display or handle creation assigns an inode, and every handle for that namespace shares this identity. Exhausting the 64-bit sequence returns ``EOVERFLOW``. Labels are ``mnt:[inode]``, ``user:[inode]`` or ``uts:[inode]``. Each typed backend retains its namespace. Final path release reclaims the backend and drops the namespace reference." msgid "" "每个挂载图持有不可变的 user owner 引用,空指针表示初始用户空间。 ``vfs_namespace_snapshot()`` 和 " @@ -432,3 +432,15 @@ msgstr "" "retirement. Filesystems owned by a child user namespace reject device opens" " except for native devpts PTYs. This restriction also applies after " "bind-remount clears the attachment’s ``nodev`` policy." + +msgid "``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 读取调用者 UTS 空间的名称并追加换行,权限为全局 UID/GID 0 的 ``0644``。写打开和每次 写入检查全局有效 UID 0,写回选择实际调用者当时的 UTS 空间。继承或传递的 FD 沿用这一规则。VFS 检查实际挂载的只读策略。sysctl 名称最多 64 字节,写入在 首个换行或 NUL 处停止并补零,具体用户接口见 :doc:`../userspace-api/abi`。" +msgstr "``/proc/sys/kernel/hostname`` and ``/proc/sys/kernel/domainname`` read names from the caller's UTS namespace and append a newline. They have mode ``0644`` and global UID/GID 0 ownership. Opening for writing and every write check for global effective UID 0. Writes select the actual caller's UTS namespace at write time. Inherited or passed FDs follow the same rule. VFS checks the read-only policy of the actual mount. Sysctl names are at most 64 bytes. Writes stop at the first newline or NUL and zero-pad the end. See :doc:`../userspace-api/abi` for the user interface." + +msgid "``CLONE_NEWUTS`` 为 clone 子任务或 unshare 调用者复制当前 hostname 和 domainname,并持有当前用户空间作为不可变 owner。同时创建用户空间时使用 候选用户空间作为 owner,准备失败释放候选空间及其引用。普通 fork 和未指定 ``CLONE_NEWUTS`` 的 clone 取得原 UTS 空间的共享引用。单独创建要求当前用户 空间的 ``CAP_SYS_ADMIN``,UTS 创建允许共享 ``CLONE_FS`` 状态,单独 unshare UTS 保留该共享状态。" +msgstr "``CLONE_NEWUTS`` copies the current hostname and domainname for a clone child or the unshare caller and retains the current user namespace as its immutable owner. Creating a user namespace in the same operation uses the candidate user namespace as owner. Preparation failure releases candidate namespaces and their references. Ordinary fork and clone without ``CLONE_NEWUTS`` acquire a shared reference to the original UTS namespace. Creating only UTS requires ``CAP_SYS_ADMIN`` in the current user namespace. UTS creation permits shared ``CLONE_FS`` state, and unsharing only UTS preserves that sharing." + +msgid "UTS 切换要求当前用户空间和目标 UTS owner 用户空间两侧的 ``CAP_SYS_ADMIN``, 允许共享文件系统状态。成功时替换任务的 UTS 引用并释放旧引用。 ``NS_GET_NSTYPE`` 对 UTS 句柄返回 ``CLONE_NEWUTS``。" +msgstr "UTS switching requires ``CAP_SYS_ADMIN`` in both the current user namespace and the target UTS owner user namespace, and permits shared filesystem state. Success replaces the task's UTS reference and releases the old reference. ``NS_GET_NSTYPE`` returns ``CLONE_NEWUTS`` for a UTS handle." + +msgid "``struct uts_namespace`` 使用原子引用计数,任务和 nsfs 后端分别持有引用, 最后一个引用释放时同时释放 owner 用户空间。空指针表示永久初始 UTS 空间。 hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护。 ``sethostname()`` 和 ``setdomainname()`` 按 UTS owner 的 ``CAP_SYS_ADMIN`` 授权,按长度复制 0 至 64 字节,保留换行与内嵌 NUL,尾部补零。" +msgstr "``struct uts_namespace`` uses atomic reference counting. Tasks and nsfs backends each retain references. Releasing the final reference also releases the owner user namespace. A null pointer denotes the permanent initial UTS namespace. A short-held UTS spinlock protects hostname and domainname copies, reads and updates. ``sethostname()`` and ``setdomainname()`` authorize against ``CAP_SYS_ADMIN`` in the UTS owner, copy 0 to 64 bytes by length, preserve newlines and embedded NUL bytes, and zero-pad the end." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 08337fd2..61f063c6 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -123,8 +123,8 @@ msgstr "``RELIEFOS_PR_SET_UNAME_LINUX`` (``0x52550001``): arg2 is 0 or 1 to disa msgid "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):所有参数为零, 返回当前选择 0 或 1。" msgstr "``RELIEFOS_PR_GET_UNAME_LINUX`` (``0x52550002``): all arguments must be zero; returns the current selection, 0 or 1." -msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" -msgstr "Invalid values and nonzero reserved arguments return EINVAL without changing state. New tasks use ReliefNT by default. fork, vfork, and clone copy the calling task's selection, and exec preserves it. Other existing tasks are unaffected; threads may also set their selection independently. The switch changes only the ``sysname`` returned by ``uname(2)`` to Linux; other fields, global UTS state, and procfs are unchanged. Both the standard libc prctl wrapper and raw syscalls are supported. Linux personality values retain their existing meaning." +msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、UTS 命名空间状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" +msgstr "Invalid values and nonzero reserved arguments return EINVAL without changing state. New tasks use ReliefNT by default. fork, vfork, and clone copy the calling task's selection, and exec preserves it. Other existing tasks are unaffected; threads may also set their selection independently. The switch changes only the ``sysname`` returned by ``uname(2)`` to Linux; other fields, UTS namespace state, and procfs are unchanged. Both the standard libc prctl wrapper and raw syscalls are supported. Linux personality values retain their existing meaning." msgid "挂载传播" msgstr "Mount propagation" @@ -458,8 +458,8 @@ msgstr "" msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUSER)`` accept an ordinary read-only ``/proc//ns/user`` handle. Joining the current user namespace, having another live thread in the group, or sharing filesystem state with another task returns ``EINVAL``. The caller needs ``CAP_SYS_ADMIN`` in the target user namespace or receives ``EPERM``. Ancestors of the current namespace fail this authority check." -msgid "nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS`` 或 ``CLONE_NEWUSER``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" -msgstr "An nsfs handle provides metadata and ioctls. Opening it for writing or with ``O_TRUNC`` returns ``EPERM``. ``O_PATH`` ignores these open flags. Scalar, positioned and vectored reads on an ordinary FD return ``EINVAL``, writes return ``EBADF``, and ``lseek()`` with a valid ``whence`` returns ``ESPIPE``. ``NS_GET_NSTYPE`` returns ``CLONE_NEWNS`` or ``CLONE_NEWUSER`` according to the handle type. ``FIONREAD`` writes zero. Unsupported namespace ioctls return ``ENOTTY``. An ``O_PATH`` FD supports metadata queries but cannot read, write, seek or issue ioctls." +msgid "nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS``、``CLONE_NEWUSER`` 或 ``CLONE_NEWUTS``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" +msgstr "An nsfs handle provides metadata and ioctls. Opening it for writing or with ``O_TRUNC`` returns ``EPERM``. ``O_PATH`` ignores these open flags. Scalar, positioned and vectored reads on an ordinary FD return ``EINVAL``, writes return ``EBADF``, and ``lseek()`` with a valid ``whence`` returns ``ESPIPE``. ``NS_GET_NSTYPE`` returns ``CLONE_NEWNS``, ``CLONE_NEWUSER`` or ``CLONE_NEWUTS`` according to the handle type. ``FIONREAD`` writes zero. Unsupported namespace ioctls return ``ENOTTY``. An ``O_PATH`` FD supports metadata queries but cannot read, write, seek or issue ioctls." msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" msgstr "After switching, root and cwd both point to the visible root of the target mount graph. Existing FDs and umask are preserved. Handles remain usable after the original process exits or changes namespaces." @@ -470,8 +470,8 @@ msgstr "Joining namespaces" msgid "成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask 保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" msgstr "A successful user namespace join preserves global UID/GID, supplementary groups, no_new_privs, root, cwd and umask. The permitted, effective and bounding sets contain all supported capabilities. Inheritable, ambient and securebits are cleared. An increase in scoped authority clears the parent-death signal and restricts dumpability. Rejection preserves the original credentials and filesystem state." -msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount 与 user 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" -msgstr "Invalid or ``O_PATH`` FDs return ``EBADF``. A non-nsfs FD, type mismatch or unsupported type returns ``EINVAL``. Mount and user handles are supported. Pidfds and bind mounts of nsfs handles remain pending. See :doc:`../core-api/mount-namespaces`." +msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount、user 与 UTS 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" +msgstr "Invalid or ``O_PATH`` FDs return ``EBADF``. A non-nsfs FD, type mismatch or unsupported type returns ``EINVAL``. Mount, user and UTS handles are supported. Pidfds and bind mounts of nsfs handles remain pending. See :doc:`../core-api/mount-namespaces`." msgid "" "bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 owner " @@ -511,3 +511,24 @@ msgstr "" "invalid IDs return ``EINVAL``. Contexts retain the translated values for " "CREATE and RECONFIGURE. Writing parameters requires a valid context " "descriptor, and failure preserves the previous configuration." + +msgid "UTS 命名空间与主机名" +msgstr "UTS namespaces and hostnames" + +msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUTS`` 为子任务复制调用者当前的 hostname 和 NIS domainname,``unshare(CLONE_NEWUTS)`` 为调用任务创建同样的 副本。新空间由调用者当前用户空间拥有,同时指定 ``CLONE_NEWUSER`` 时由新建 用户空间拥有。单独创建 UTS 空间要求当前用户空间的 ``CAP_SYS_ADMIN``,缺少 时返回 ``EPERM``。普通 fork 和未指定 ``CLONE_NEWUTS`` 的 clone 共享原 UTS 空间。UTS 创建可与 ``CLONE_FS`` 共享并用,单独 unshare UTS 保留文件系统共享。" +msgstr "``CLONE_NEWUTS`` in ``clone()`` and ``clone3()`` copies the caller's current hostname and NIS domainname for the child. ``unshare(CLONE_NEWUTS)`` creates the same copy for the caller. The caller's current user namespace owns the new namespace. When combined with ``CLONE_NEWUSER``, the newly created user namespace owns it. Creating only a UTS namespace requires ``CAP_SYS_ADMIN`` in the current user namespace. Missing capability returns ``EPERM``. Ordinary fork and clone without ``CLONE_NEWUTS`` share the original UTS namespace. UTS creation supports sharing with ``CLONE_FS``, and unsharing only UTS preserves filesystem sharing." + +msgid "``uname()`` 的 ``nodename`` 和 ``domainname`` 来自调用任务的 UTS 空间。 ``sethostname()`` 和 ``setdomainname()`` 要求该 UTS 空间 owner 用户空间的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。长度为 0 至 64 字节,超出返回 ``EINVAL``。名称按长度复制,保留换行及内嵌 NUL,尾部补零。" +msgstr "The ``nodename`` and ``domainname`` fields of ``uname()`` come from the calling task's UTS namespace. ``sethostname()`` and ``setdomainname()`` require ``CAP_SYS_ADMIN`` in the user namespace that owns this UTS namespace. Missing capability returns ``EPERM``. Lengths range from 0 to 64 bytes. Out-of-range lengths return ``EINVAL``. Names are copied by length, preserving newlines and embedded NUL bytes, with zero padding at the end." + +msgid "``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 的权限为 ``0644``,归全局 UID/GID 0 所有。写打开及每次写入要求调用者的全局有效 UID 为 0,缺少时返回 ``EACCES``,该判断独立于 fsuid 和 DAC capabilities,执行权限 检查返回 ``EACCES``。写入按当时调用者的 UTS 空间立即生效,已经打开 或经 dup、fork 继承的 FD 也使用实际写入者的当前空间。只读 proc 挂载或只读 bind 挂载上的写入返回 ``EROFS``。" +msgstr "``/proc/sys/kernel/hostname`` and ``/proc/sys/kernel/domainname`` have mode ``0644`` and global UID/GID 0 ownership. Opening for writing and every write require the caller global effective UID to be zero, returning ``EACCES`` otherwise. This check is independent of fsuid and DAC capabilities. Execute access returns ``EACCES``. Writes immediately affect the current writer UTS namespace, including through already-open FDs or descriptors inherited by dup or fork. Writes through a read-only proc or bind mount return ``EROFS``." + +msgid "这两个 sysctl 读取名称至首个 NUL,并追加换行。写入最多保留 64 字节的名称, 在首个换行或 NUL 处停止并补零,成功时报告接受的输入字节数。零长度写入保留 名称。它们与 ``uname()`` 及主机名系统调用访问同一份 UTS 名称。" +msgstr "Reads from these two sysctls return the name up to the first NUL and append a newline. Writes retain at most 64 bytes of the name, stop at the first newline or NUL, and zero-pad the end. Successful writes report the accepted input byte count. A zero-length write preserves the name. These files access the same UTS names as ``uname()`` and the hostname syscalls." + +msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUTS)`` 接受普通只读的 ``/proc//ns/uts`` 句柄。调用者需要当前用户空间和目标 UTS owner 用户 空间两侧的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。切换允许共享 ``CLONE_FS`` 状态,root、cwd 和 umask 保留。句柄持有目标 UTS 空间的引用, 目标进程退出或切换空间后仍可使用。" +msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUTS)`` accept an ordinary read-only ``/proc//ns/uts`` handle. The caller needs ``CAP_SYS_ADMIN`` in both the current user namespace and the user namespace that owns the target UTS namespace. Missing capability returns ``EPERM``. Switching permits shared ``CLONE_FS`` state and preserves root, cwd and umask. The handle retains the target UTS namespace and remains usable after the target process exits or switches namespaces." + +msgid "当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 文件 I/O 规则推进。此处尚未实现 Linux strict sysctl 对忽略写入保留偏移的行为。" +msgstr "When the current position is beyond the name end, a write preserves the name and reports the accepted input byte count. The file position still advances under ordinary file I/O rules. Preserving the offset for ignored writes as Linux strict sysctl does remains pending." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 521cb976..c5397c8e 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -175,11 +175,11 @@ msgstr "" "は無効な ID を表します。親空間の各範囲は単一の区間内に収まり、ローカル範囲と親範囲はそれぞれ重複せず、無効な ID を含められません。" msgid "" -"proc 控制文件在打开时保留目标空间、打开者空间及其标量凭据。写入使用捕获权限 和当前调用者权限,目标退出或 PID " +"用户空间映射与 setgroups 控制文件在打开时保留目标空间、打开者空间及其标量凭据。写入使用捕获权限 和当前调用者权限,目标退出或 PID " "重用后仍操作原空间。所有映射与 setgroups 策略提交由现有独占执行权串行化,候选解析、权限和分配失败均不发布状态;最后 " "一个空间引用释放映射并逐级释放父空间。用户接口见 :doc:`../userspace-api/procfs`。" msgstr "" -"proc " +"ユーザー名前空間のマッピングまたは setgroups " "制御ファイルを開くと、対象空間、オープンした側の空間とスカラー資格情報を保持します。書き込みは保持した権限と現在の呼び出し元の権限を検査し、対象の終了や" " PID の再利用後も元の空間を操作します。既存の排他的実行所有権がマップと setgroups " "方針の公開を直列化します。解析、権限検査、割り当ての失敗時は状態を保持します。空間の最後の参照を解放するとマップと親空間の参照を順次解放します。ユーザーインターフェースは" @@ -299,8 +299,8 @@ msgstr "メッセージキュー、セマフォ、共有メモリの登録表、 msgid "``IPC_SET`` 先执行现有对象所有权与资源限制检查,再将输入的 UID/GID 全部 转换为全局 ID。任一输入未映射或为 ``UINT32_MAX`` 时返回 ``EINVAL``,对象的 身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 用户空间检查。" msgstr "``IPC_SET`` は既存のオブジェクト所有権とリソース制限を確認してから、入力 UID/GID の両方をグローバル ID に変換します。未マッピングの入力または ``UINT32_MAX`` には ``EINVAL`` を返し、オブジェクトの ID、権限、容量、変更時刻を保持します。成功時は所有者と下位 0777 の権限ビットを更新し、作成者の ID と共有メモリのロックおよび削除フラグを保持します。グローバル IPC 管理とリソース特権は引き続き初期ユーザー名前空間で確認します。" -msgid "``/proc//ns/mnt`` 与 ``/proc//ns/user`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图或用户空间。" -msgstr "``/proc//ns/mnt`` と ``/proc//ns/user`` は proc magic link です。読み取りと追跡には ``/proc//fd`` と同じ ``PTRACE_MODE_READ_FSCREDS`` 検査が必要です。リンクキーは PID の同一性を保持します。追跡が成功するたびに対象タスクの現在のマウントグラフまたはユーザー名前空間を取得します。" +msgid "``/proc//ns/mnt``、``/proc//ns/user`` 与 ``/proc//ns/uts`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图、用户空间或 UTS 空间。" +msgstr "``/proc//ns/mnt``、``/proc//ns/user``、``/proc//ns/uts`` は proc magic link です。読み取りと追跡には ``/proc//fd`` と同じ ``PTRACE_MODE_READ_FSCREDS`` 検査が必要です。リンクキーは PID の同一性を保持します。追跡が成功するたびに対象タスクの現在のマウントグラフ、ユーザー名前空間または UTS 名前空間を取得します。" msgid "" "``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare " @@ -328,8 +328,8 @@ msgstr "" msgid "user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。" msgstr "user の切り替えには単一スレッド、ファイルシステム状態の独占、対象名前空間の ``CAP_SYS_ADMIN`` が必要で、現在の名前空間への再参加は拒否します。成功時は root、cwd、グローバル ID を保持し、ユーザー名前空間の設定処理を再利用して能力集合と securebits をリセットします。作用域内の権限が増加するとダンプ可能性を制限し、親死亡シグナルを解除します。初期ユーザー名前空間は空ポインタで表し、ハンドル型の認証と真偽値の照会でこの有効な ID と無効なパスを区別します。" -msgid "跟随链接得到分离的 nsfs inode。mount 与 user 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" -msgstr "リンクをたどると独立した nsfs inode を取得します。mount と user の名前空間は単調増加する共通の採番列を使います。最初の表示またはハンドル作成時に inode を割り当て、同じ名前空間のすべてのハンドルがその ID を共有します。64 ビットの採番列を使い切ると ``EOVERFLOW`` を返します。表示は ``mnt:[inode]`` または ``user:[inode]`` です。各バックエンドは型に応じた名前空間の参照を持ち、最後のパス解放時にバックエンドを回収して名前空間の参照を解放します。" +msgid "跟随链接得到分离的 nsfs inode。mount、user 与 UTS 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]``、``user:[inode]`` 或 ``uts:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" +msgstr "リンクをたどると独立した nsfs inode を取得します。mount、user、UTS の名前空間は単調増加する共通の採番列を使います。最初の表示またはハンドル作成時に inode を割り当て、同じ名前空間のすべてのハンドルがその ID を共有します。64 ビットの採番列を使い切ると ``EOVERFLOW`` を返します。表示は ``mnt:[inode]``、``user:[inode]`` または ``uts:[inode]`` です。各バックエンドは型に応じた名前空間の参照を持ち、最後のパス解放時にバックエンドを回収して名前空間の参照を解放します。" msgid "" "每个挂载图持有不可变的 user owner 引用,空指针表示初始用户空间。 ``vfs_namespace_snapshot()`` 和 " @@ -377,3 +377,15 @@ msgstr "" "ビューとマウントグラフのスナップショットはこの参照を保持し、最後のマウントがバックエンドの正常な退役後に解放します。子ユーザー名前空間が所有するファイルシステムは、ネイティブ" " devpts PTY を除くデバイスのオープンを拒否します。bind-remount でアタッチメントの ``nodev`` " "を解除しても、この制限は適用されます。" + +msgid "``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 读取调用者 UTS 空间的名称并追加换行,权限为全局 UID/GID 0 的 ``0644``。写打开和每次 写入检查全局有效 UID 0,写回选择实际调用者当时的 UTS 空间。继承或传递的 FD 沿用这一规则。VFS 检查实际挂载的只读策略。sysctl 名称最多 64 字节,写入在 首个换行或 NUL 处停止并补零,具体用户接口见 :doc:`../userspace-api/abi`。" +msgstr "``/proc/sys/kernel/hostname`` と ``/proc/sys/kernel/domainname`` は呼び出し元の UTS 名前空間の名前を読み取り、改行を追加します。モードは ``0644``、所有者はグローバル UID/GID 0 です。書き込み用のオープンと毎回の書き込みでグローバル実効 UID 0 を検査し、書き込み時の実際の呼び出し元の UTS 名前空間を選択します。継承または受け渡しした FD も同じ規則に従います。VFS は実際のマウントの読み取り専用ポリシーを検査します。sysctl の名前は最大 64 バイトです。書き込みは最初の改行または NUL で停止し、末尾をゼロで埋めます。ユーザーインターフェースは :doc:`../userspace-api/abi` を参照してください。" + +msgid "``CLONE_NEWUTS`` 为 clone 子任务或 unshare 调用者复制当前 hostname 和 domainname,并持有当前用户空间作为不可变 owner。同时创建用户空间时使用 候选用户空间作为 owner,准备失败释放候选空间及其引用。普通 fork 和未指定 ``CLONE_NEWUTS`` 的 clone 取得原 UTS 空间的共享引用。单独创建要求当前用户 空间的 ``CAP_SYS_ADMIN``,UTS 创建允许共享 ``CLONE_FS`` 状态,单独 unshare UTS 保留该共享状态。" +msgstr "``CLONE_NEWUTS`` は clone の子タスクまたは unshare の呼び出し元に現在の hostname と domainname をコピーし、現在のユーザー名前空間を不変の owner として保持します。同時にユーザー名前空間を作成する場合は、候補ユーザー名前空間を owner にします。準備に失敗すると候補名前空間とその参照を解放します。通常の fork と ``CLONE_NEWUTS`` を指定しない clone は元の UTS 名前空間の共有参照を取得します。UTS だけの作成には、現在のユーザー名前空間の ``CAP_SYS_ADMIN`` が必要です。UTS の作成は ``CLONE_FS`` 状態の共有を許可し、UTS だけの unshare はその共有を保持します。" + +msgid "UTS 切换要求当前用户空间和目标 UTS owner 用户空间两侧的 ``CAP_SYS_ADMIN``, 允许共享文件系统状态。成功时替换任务的 UTS 引用并释放旧引用。 ``NS_GET_NSTYPE`` 对 UTS 句柄返回 ``CLONE_NEWUTS``。" +msgstr "UTS の切り替えには、現在のユーザー名前空間と対象 UTS の owner ユーザー名前空間の両方の ``CAP_SYS_ADMIN`` が必要で、ファイルシステム状態の共有を許可します。成功するとタスクの UTS 参照を置き換えて旧参照を解放します。UTS ハンドルの ``NS_GET_NSTYPE`` は ``CLONE_NEWUTS`` を返します。" + +msgid "``struct uts_namespace`` 使用原子引用计数,任务和 nsfs 后端分别持有引用, 最后一个引用释放时同时释放 owner 用户空间。空指针表示永久初始 UTS 空间。 hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护。 ``sethostname()`` 和 ``setdomainname()`` 按 UTS owner 的 ``CAP_SYS_ADMIN`` 授权,按长度复制 0 至 64 字节,保留换行与内嵌 NUL,尾部补零。" +msgstr "``struct uts_namespace`` はアトミックな参照カウントを使用し、タスクと nsfs バックエンドがそれぞれ参照を保持します。最後の参照を解放すると owner ユーザー名前空間も解放します。NULL ポインターは永続的な初期 UTS 名前空間を表します。hostname と domainname のコピー、読み取り、更新は短時間保持する UTS スピンロックで保護します。``sethostname()`` と ``setdomainname()`` は UTS owner の ``CAP_SYS_ADMIN`` で認可し、長さに従って 0 から 64 バイトをコピーします。改行と埋め込み NUL を保持し、末尾をゼロで埋めます。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 053a09a8..5750eff3 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -114,8 +114,8 @@ msgstr "``RELIEFOS_PR_SET_UNAME_LINUX``(``0x52550001``):arg2 を 0 また msgid "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):所有参数为零, 返回当前选择 0 或 1。" msgstr "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):すべての引数をゼロにし、現在の選択 0 または 1 を取得します。" -msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" -msgstr "不正な値やゼロ以外の予約引数には、状態を変更せず EINVAL を返します。新しいタスクは既定で ReliefNT を使用します。fork、vfork、clone は呼び出しタスクの選択をコピーし、exec は選択を保持します。既存の別タスクは影響を受けず、スレッドも独立に選択できます。このスイッチは ``uname(2)`` の ``sysname`` だけを Linux に変更し、他のフィールド、グローバルな UTS 状態、procfs は変更しません。標準 libc の prctl ラッパーとシステムコールの直接呼び出しに対応し、personality 値の意味は変更しません。" +msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、UTS 命名空间状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" +msgstr "不正な値やゼロ以外の予約引数には、状態を変更せず EINVAL を返します。新しいタスクは既定で ReliefNT を使用します。fork、vfork、clone は呼び出しタスクの選択をコピーし、exec は選択を保持します。既存の別タスクは影響を受けず、スレッドも独立に選択できます。このスイッチは ``uname(2)`` の ``sysname`` だけを Linux に変更し、他のフィールド、UTS 名前空間の状態、procfs は変更しません。標準 libc の prctl ラッパーとシステムコールの直接呼び出しに対応し、personality 値の意味は変更しません。" msgid "挂载传播" msgstr "マウントの伝播" @@ -407,8 +407,8 @@ msgstr "" msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUSER)`` は通常の読み取り専用 ``/proc//ns/user`` ハンドルを受け付けます。現在のユーザー名前空間への再参加、同じグループの別の活動中スレッド、他のタスクとのファイルシステム状態の共有は ``EINVAL`` になります。対象ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。現在の名前空間の祖先はこの権限検査を通過できません。" -msgid "nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS`` 或 ``CLONE_NEWUSER``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" -msgstr "nsfs ハンドルはメタデータと ioctl を提供します。書き込みモードまたは ``O_TRUNC`` で開くと ``EPERM`` を返し、``O_PATH`` はこれらのフラグを無視します。通常 FD のスカラー、位置指定、ベクトル読み取りは ``EINVAL``、書き込みは ``EBADF``、有効な ``whence`` の ``lseek()`` は ``ESPIPE`` を返します。``NS_GET_NSTYPE`` は実際の型に応じて ``CLONE_NEWNS`` または ``CLONE_NEWUSER`` を返し、``FIONREAD`` はゼロを書き込みます。未対応の namespace ioctl は ``ENOTTY`` を返します。``O_PATH`` FD はメタデータ照会に使えますが、読み書き、シーク、ioctl は実行できません。" +msgid "nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS``、``CLONE_NEWUSER`` 或 ``CLONE_NEWUTS``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" +msgstr "nsfs ハンドルはメタデータと ioctl を提供します。書き込みモードまたは ``O_TRUNC`` で開くと ``EPERM`` を返し、``O_PATH`` はこれらのフラグを無視します。通常 FD のスカラー、位置指定、ベクトル読み取りは ``EINVAL``、書き込みは ``EBADF``、有効な ``whence`` の ``lseek()`` は ``ESPIPE`` を返します。``NS_GET_NSTYPE`` は実際の型に応じて ``CLONE_NEWNS``、``CLONE_NEWUSER`` または ``CLONE_NEWUTS`` を返し、``FIONREAD`` はゼロを書き込みます。未対応の namespace ioctl は ``ENOTTY`` を返します。``O_PATH`` FD はメタデータ照会に使えますが、読み書き、シーク、ioctl は実行できません。" msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" msgstr "切り替え後の root と cwd は対象マウントグラフの可視ルートを指します。既存の FD と umask は保持されます。元のプロセスが終了した後や名前空間を切り替えた後もハンドルを使用できます。" @@ -419,8 +419,8 @@ msgstr "名前空間への参加" msgid "成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask 保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" msgstr "ユーザー名前空間への参加が成功すると、グローバル UID/GID、補助グループ、no_new_privs、root、cwd、umask を保持します。permitted、effective、bounding にはサポートする全能力を設定し、inheritable、ambient、securebits をクリアします。作用域内の権限が増加すると親死亡シグナルを解除してダンプ可能性を制限します。検査失敗時は元の資格情報とファイルシステム状態を保持します。" -msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount 与 user 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" -msgstr "無効な FD と ``O_PATH`` FD は ``EBADF`` を返します。nsfs 以外の FD、型の不一致、未対応の型は ``EINVAL`` を返します。mount と user のハンドルに対応します。pidfd と nsfs ハンドルの bind mount は未接続です。:doc:`../core-api/mount-namespaces` を参照してください。" +msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount、user 与 UTS 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" +msgstr "無効な FD と ``O_PATH`` FD は ``EBADF`` を返します。nsfs 以外の FD、型の不一致、未対応の型は ``EINVAL`` を返します。mount、user、UTS のハンドルに対応します。pidfd と nsfs ハンドルの bind mount は未接続です。:doc:`../core-api/mount-namespaces` を参照してください。" msgid "" "bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 owner " @@ -454,3 +454,24 @@ msgstr "" "進入力は先頭のゼロを受け付けます。未マッピング、オーバーフロー、無効な ID は ``EINVAL`` " "を返します。コンテキストは変換後の値を保存し、CREATE と RECONFIGURE " "が使用します。パラメーターの書き込みには有効なコンテキスト記述子が必要で、失敗時は以前の設定を保持します。" + +msgid "UTS 命名空间与主机名" +msgstr "UTS 名前空間とホスト名" + +msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUTS`` 为子任务复制调用者当前的 hostname 和 NIS domainname,``unshare(CLONE_NEWUTS)`` 为调用任务创建同样的 副本。新空间由调用者当前用户空间拥有,同时指定 ``CLONE_NEWUSER`` 时由新建 用户空间拥有。单独创建 UTS 空间要求当前用户空间的 ``CAP_SYS_ADMIN``,缺少 时返回 ``EPERM``。普通 fork 和未指定 ``CLONE_NEWUTS`` 的 clone 共享原 UTS 空间。UTS 创建可与 ``CLONE_FS`` 共享并用,单独 unshare UTS 保留文件系统共享。" +msgstr "``clone()`` と ``clone3()`` の ``CLONE_NEWUTS`` は、呼び出し元の現在の hostname と NIS domainname を子タスク用にコピーします。``unshare(CLONE_NEWUTS)`` は呼び出し元用に同じコピーを作成します。新しい名前空間の owner は呼び出し元の現在のユーザー名前空間です。``CLONE_NEWUSER`` も指定すると、新しく作成したユーザー名前空間が owner になります。UTS 名前空間だけを作成する場合、現在のユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。通常の fork と ``CLONE_NEWUTS`` を指定しない clone は元の UTS 名前空間を共有します。UTS の作成は ``CLONE_FS`` による共有と併用でき、UTS だけの unshare はファイルシステム状態の共有を保持します。" + +msgid "``uname()`` 的 ``nodename`` 和 ``domainname`` 来自调用任务的 UTS 空间。 ``sethostname()`` 和 ``setdomainname()`` 要求该 UTS 空间 owner 用户空间的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。长度为 0 至 64 字节,超出返回 ``EINVAL``。名称按长度复制,保留换行及内嵌 NUL,尾部补零。" +msgstr "``uname()`` の ``nodename`` と ``domainname`` は呼び出し元タスクの UTS 名前空間から取得します。``sethostname()`` と ``setdomainname()`` には、この UTS 名前空間の owner ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。長さは 0 から 64 バイトで、範囲外は ``EINVAL`` を返します。名前は長さに従ってコピーし、改行と埋め込み NUL を保持して末尾をゼロで埋めます。" + +msgid "``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 的权限为 ``0644``,归全局 UID/GID 0 所有。写打开及每次写入要求调用者的全局有效 UID 为 0,缺少时返回 ``EACCES``,该判断独立于 fsuid 和 DAC capabilities,执行权限 检查返回 ``EACCES``。写入按当时调用者的 UTS 空间立即生效,已经打开 或经 dup、fork 继承的 FD 也使用实际写入者的当前空间。只读 proc 挂载或只读 bind 挂载上的写入返回 ``EROFS``。" +msgstr "``/proc/sys/kernel/hostname`` と ``/proc/sys/kernel/domainname`` のモードは ``0644`` で、所有者はグローバル UID/GID 0 です。書き込み用のオープンと毎回の書き込みで、呼び出し元のグローバル実効 UID が 0 である必要があり、満たさない場合は ``EACCES`` を返します。この判定は fsuid と DAC capabilities に依存せず、実行権限の検査は ``EACCES`` を返します。書き込みはその時点の呼び出し元の UTS 名前空間に直ちに反映されます。オープン済み FD や dup、fork で継承した FD も、実際の書き込み元の現在の名前空間を使用します。読み取り専用の proc マウントまたは bind マウント経由の書き込みは ``EROFS`` を返します。" + +msgid "这两个 sysctl 读取名称至首个 NUL,并追加换行。写入最多保留 64 字节的名称, 在首个换行或 NUL 处停止并补零,成功时报告接受的输入字节数。零长度写入保留 名称。它们与 ``uname()`` 及主机名系统调用访问同一份 UTS 名称。" +msgstr "この 2 つの sysctl の読み取りは、最初の NUL までの名前に改行を追加して返します。書き込みは名前を最大 64 バイト保持し、最初の改行または NUL で停止して末尾をゼロで埋めます。成功時は受け付けた入力バイト数を返します。長さゼロの書き込みは名前を保持します。これらのファイルは ``uname()`` およびホスト名システムコールと同じ UTS 名を参照します。" + +msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUTS)`` 接受普通只读的 ``/proc//ns/uts`` 句柄。调用者需要当前用户空间和目标 UTS owner 用户 空间两侧的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。切换允许共享 ``CLONE_FS`` 状态,root、cwd 和 umask 保留。句柄持有目标 UTS 空间的引用, 目标进程退出或切换空间后仍可使用。" +msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUTS)`` は、通常の読み取り専用 ``/proc//ns/uts`` ハンドルを受け付けます。現在のユーザー名前空間と、対象 UTS 名前空間の owner ユーザー名前空間の両方で ``CAP_SYS_ADMIN`` が必要です。欠けていれば ``EPERM`` を返します。切り替え時に ``CLONE_FS`` 状態を共有でき、root、cwd、umask を保持します。ハンドルは対象 UTS 名前空間の参照を保持し、対象プロセスの終了や名前空間の切り替え後も使用できます。" + +msgid "当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 文件 I/O 规则推进。此处尚未实现 Linux strict sysctl 对忽略写入保留偏移的行为。" +msgstr "現在位置が名前の末尾を超える書き込みは名前を保持し、受け付けた入力バイト数を返します。ファイル位置は通常のファイル I/O 規則に従って進みます。Linux strict sysctl のように無視した書き込みの位置を保持する動作は未実装です。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 61e56f2b..58175751 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -34,7 +34,7 @@ vDSO 的 ELF 符号版本、辅助向量、vvar 邻接映射及时间读取均 非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 -``sysname`` 改为 Linux,其余字段、全局 UTS 状态及 procfs 均不改变。 +``sysname`` 改为 Linux,其余字段、UTS 命名空间状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。 孤儿进程接管 @@ -87,6 +87,35 @@ bounding 能力集包含全部已支持能力,inheritable、ambient 和 secure 组合 ``CLONE_NEWUSER | CLONE_NEWNS`` 以新用户空间作为新挂载图 owner, 使用新空间的能力完成挂载图创建;候选空间或快照准备失败均整体回滚。 +UTS 命名空间与主机名 +==================== + +``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUTS`` 为子任务复制调用者当前的 +hostname 和 NIS domainname,``unshare(CLONE_NEWUTS)`` 为调用任务创建同样的 +副本。新空间由调用者当前用户空间拥有,同时指定 ``CLONE_NEWUSER`` 时由新建 +用户空间拥有。单独创建 UTS 空间要求当前用户空间的 ``CAP_SYS_ADMIN``,缺少 +时返回 ``EPERM``。普通 fork 和未指定 ``CLONE_NEWUTS`` 的 clone 共享原 UTS +空间。UTS 创建可与 ``CLONE_FS`` 共享并用,单独 unshare UTS 保留文件系统共享。 + +``uname()`` 的 ``nodename`` 和 ``domainname`` 来自调用任务的 UTS 空间。 +``sethostname()`` 和 ``setdomainname()`` 要求该 UTS 空间 owner 用户空间的 +``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。长度为 0 至 64 字节,超出返回 +``EINVAL``。名称按长度复制,保留换行及内嵌 NUL,尾部补零。 + +``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 的权限为 +``0644``,归全局 UID/GID 0 所有。写打开及每次写入要求调用者的全局有效 UID +为 0,缺少时返回 ``EACCES``,该判断独立于 fsuid 和 DAC capabilities,执行权限 +检查返回 ``EACCES``。写入按当时调用者的 UTS 空间立即生效,已经打开 +或经 dup、fork 继承的 FD 也使用实际写入者的当前空间。只读 proc 挂载或只读 +bind 挂载上的写入返回 ``EROFS``。 + +这两个 sysctl 读取名称至首个 NUL,并追加换行。写入最多保留 64 字节的名称, +在首个换行或 NUL 处停止并补零,成功时报告接受的输入字节数。零长度写入保留 +名称。它们与 ``uname()`` 及主机名系统调用访问同一份 UTS 名称。 + +当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 +文件 I/O 规则推进。此处尚未实现 Linux strict sysctl 对忽略写入保留偏移的行为。 + 加入命名空间 ============ @@ -109,14 +138,21 @@ bounding 能力集包含全部已支持能力,inheritable、ambient 和 secure ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。 +``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUTS)`` 接受普通只读的 +``/proc//ns/uts`` 句柄。调用者需要当前用户空间和目标 UTS owner 用户 +空间两侧的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。切换允许共享 +``CLONE_FS`` 状态,root、cwd 和 umask 保留。句柄持有目标 UTS 空间的引用, +目标进程退出或切换空间后仍可使用。 + 无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 -类型返回 ``EINVAL``。当前支持 mount 与 user 句柄,pidfd 和 nsfs 句柄的 bind +类型返回 ``EINVAL``。当前支持 mount、user 与 UTS 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。 nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 -``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS`` 或 ``CLONE_NEWUSER``。 +``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS``、``CLONE_NEWUSER`` 或 +``CLONE_NEWUTS``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。 diff --git a/fs/nsfs/namespace.c b/fs/nsfs/namespace.c index fc229f61..7f476a1b 100644 --- a/fs/nsfs/namespace.c +++ b/fs/nsfs/namespace.c @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -18,10 +19,11 @@ struct nsfs_context { union { struct vfs_namespace *mount; struct user_namespace *user; + struct uts_namespace *uts; } ns; }; -static uint64_t next_inode = 1, initial_user_inode; +static uint64_t next_inode = 1, initial_user_inode, initial_uts_inode; static const struct vfs_backend_ops nsfs_ops; @@ -43,7 +45,7 @@ static bool nsfs_inode(const struct nsfs_context *context, const struct storage_ } /** @brief Render a typed namespace identity without allocating a path. - * @param type CLONE_NEWNS or CLONE_NEWUSER. @param inode Assigned identity. + * @param type CLONE_NEWNS, CLONE_NEWUSER or CLONE_NEWUTS. @param inode Assigned identity. * @param buffer Required output. @param capacity Maximum bytes, without NUL. * @return Copied byte count or -EOVERFLOW for an exhausted identity allocator. */ @@ -52,7 +54,10 @@ static int nsfs_label(uint32_t type, uint64_t inode, char *buffer, size_t capaci if (!inode) return -EOVERFLOW; struct text_stream text = {.buffer = buffer, .capacity = capacity > NSFS_LABEL_BYTES ? NSFS_LABEL_BYTES : (uint32_t)capacity}; - text_string(&text, type == CLONE_NEWUSER ? "user:[" : "mnt:["); + const char *prefix = "mnt:["; + if (type == CLONE_NEWUSER) prefix = "user:["; + if (type == CLONE_NEWUTS) prefix = "uts:["; + text_string(&text, prefix); text_unsigned(&text, inode); text_string(&text, "]"); return (int)text.written; @@ -72,6 +77,13 @@ int nsfs_user_readlink(struct user_namespace *ns, char *buffer, size_t capacity) nsfs_identity(ns ? &ns->nsfs_inode : &initial_user_inode), buffer, capacity); } +/** @copydoc nsfs_uts_readlink */ +int nsfs_uts_readlink(struct uts_namespace *ns, char *buffer, size_t capacity) +{ + return nsfs_label(CLONE_NEWUTS, + nsfs_identity(ns ? &ns->nsfs_inode : &initial_uts_inode), buffer, capacity); +} + /** @brief A detached namespace backend has no named children. */ static int nsfs_lookup(void *context, const struct storage_node *parent, const char *name, struct storage_node *out) @@ -108,6 +120,7 @@ static void nsfs_destroy(void *context) { struct nsfs_context *capture = context; if (capture->type == CLONE_NEWUSER) user_namespace_put(capture->ns.user); + else if (capture->type == CLONE_NEWUTS) uts_namespace_put(capture->ns.uts); else vfs_namespace_put(capture->ns.mount); kernel_free(capture); } @@ -189,6 +202,7 @@ static int nsfs_create_handle(const struct nsfs_context *value, struct vfs_path if (!context) return -ENOMEM; *context = *value; if (context->type == CLONE_NEWUSER) user_namespace_get(context->ns.user); + else if (context->type == CLONE_NEWUTS) uts_namespace_get(context->ns.uts); else vfs_namespace_get(context->ns.mount); struct storage_node root = {.type = RELIEFOS_FS_TYPE_DIR}; struct storage_node node = {.type = RELIEFOS_FS_TYPE_FILE, @@ -220,6 +234,14 @@ int nsfs_create_user_path(struct user_namespace *ns, struct vfs_path *out) return nsfs_create_handle(&value, out); } +/** @copydoc nsfs_create_uts_path */ +int nsfs_create_uts_path(struct uts_namespace *ns, struct vfs_path *out) +{ + const struct nsfs_context value = {.type = CLONE_NEWUTS, + .inode = nsfs_identity(ns ? &ns->nsfs_inode : &initial_uts_inode), .ns.uts = ns}; + return nsfs_create_handle(&value, out); +} + /** @brief Authenticate provider, retained inode and backend pin together. * @param path Borrowed path, nullable. @return Borrowed capture or NULL. * Execution ownership and the held path stabilize the entire capture. @@ -249,6 +271,16 @@ bool nsfs_path_user_namespace(const struct vfs_path *path, struct user_namespace return true; } +/** @copydoc nsfs_path_uts_namespace */ +bool nsfs_path_uts_namespace(const struct vfs_path *path, struct uts_namespace **out) +{ + struct nsfs_context *context = nsfs_path_context(path); + *out = NULL; + if (!context || context->type != CLONE_NEWUTS) return false; + *out = context->ns.uts; + return true; +} + /** @copydoc nsfs_path_type */ uint32_t nsfs_path_type(const struct vfs_path *path) { diff --git a/fs/proc/internal.h b/fs/proc/internal.h index 02a9bfc8..b63d607f 100644 --- a/fs/proc/internal.h +++ b/fs/proc/internal.h @@ -28,6 +28,12 @@ void proc_memory_close(void *view); */ int proc_control_permissions(const char *name, const struct storage_node *node, struct reliefos_permissions *value, bool write); +/** @brief Apply UTS sysctl DAC using global effective identity. + * @param name Intrinsic retained key. @param task Borrowed caller credentials. + * @param access Validated FS_ACCESS mask. @return Zero, -EACCES, or + * -EOPNOTSUPP for other files. Mount policy precedes this nonblocking query. + */ +int proc_control_access(const char *name,const struct task *task,uint32_t access); /** @brief Commit a whole proc control write after normal VFS authorization. * @param name Intrinsic live key. @param offset File position. @param buffer * Validated bytes. @param length Byte count. @param written Completed bytes. diff --git a/fs/proc/mount.c b/fs/proc/mount.c index f8609369..ccc26734 100644 --- a/fs/proc/mount.c +++ b/fs/proc/mount.c @@ -146,7 +146,7 @@ int proc_create_vfs_mount_options(const char *options,struct vfs_mount **out) .read=proc_read,.readdir=proc_readdir,.readlink=proc_readlink, .get_identity=proc_key_identity,.identity_alive=proc_key_alive,.put_identity=proc_key_put, .follow=proc_mount_magic_target,.stat_link=proc_mount_magic_stat, - .permissions=proc_control_permissions,.getattr=proc_getattr, + .permissions=proc_control_permissions,.access=proc_control_access,.getattr=proc_getattr, .open=proc_file_open,.read_open=proc_file_read,.write_open=proc_file_write,.close=proc_file_close, .poll_open=proc_file_poll,.authorize=proc_key_authorize, .entry_visible=proc_entry_visible,.reconfigure=proc_reconfigure}; diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 39cb8cc5..cb5a1aab 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -44,6 +44,17 @@ static int proc_text_eq(const char *a, const char *b) return *a == 0 && *b == 0; } +/** @brief Identify the two writable UTS sysctl leaves by intrinsic key. + * @param name Borrowed backend name. @return One for hostname, two for + * domainname, or zero for other files. No task or namespace is captured. + */ +static int proc_uts_key(const char *name) +{ + if (proc_text_eq(name, "/proc/sys/kernel/hostname")) return 1; + if (proc_text_eq(name, "/proc/sys/kernel/domainname")) return 2; + return 0; +} + static void proc_copy(char *dst, uint32_t capacity, const char *src) { uint32_t i = 0; @@ -532,6 +543,10 @@ struct proc_open_view { int proc_file_open(const char *name,uint32_t flags,void **out) { (void)flags;if(!out)return -RELIEFOS_EINVAL;*out=NULL; + if (proc_uts_key(name) && (flags & LINUX_O_ACCMODE) != LINUX_O_RDONLY) { + struct task *caller = sched_current_task(); + if (!caller || caller->euid) return -EACCES; + } struct task *namespace_task = NULL; int namespace_kind = proc_userns_key(name, &namespace_task); if (namespace_kind) { @@ -850,7 +865,7 @@ int proc_mount_node_identity(const char *name,struct task_identity **out,bool *m if(rc)return rc==-ESRCH ? -RELIEFOS_ENOENT : rc; *magic = file && (proc_fd_number(file) >= 0 || proc_text_eq(file, "cwd") || proc_text_eq(file, "root") || proc_text_eq(file, "exe") || - proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user")); + proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user") || proc_text_eq(file, "ns/uts")); return 0; } @@ -883,7 +898,7 @@ int proc_mount_magic_stat(const char *name,struct linux_stat_abi *out) * @param name Live intrinsic proc key, already checked against its retained PID. * @param out Receives one owned path; empty on failure. * @return Zero or negative errno. A namespace link captures the target's - * current mount or user namespace. The proc link retains only PID identity. + * current mount, user or UTS namespace. The proc link retains only PID identity. */ int proc_mount_magic_target(const char *name,struct vfs_path *out) { @@ -897,6 +912,7 @@ int proc_mount_magic_target(const char *name,struct vfs_path *out) if(!proc_stat_mm_visible(sched_current_task(),task))return -RELIEFOS_EACCES; if (proc_text_eq(file, "ns/mnt")) return nsfs_create_path(sched_task_namespace(task), out); if (proc_text_eq(file, "ns/user")) return nsfs_create_user_path(task->user_ns, out); + if (proc_text_eq(file, "ns/uts")) return nsfs_create_uts_path(task->uts_ns, out); struct task_fs_paths *paths=sched_task_paths(task); if(proc_text_eq(file,"cwd"))vfs_path_get(&paths->cwd,out); else if(proc_text_eq(file,"root"))vfs_path_get(&paths->root,out); @@ -1101,7 +1117,7 @@ int proc_lookup(const char *path, struct storage_node *out) int kind = proc_path_kind(path, &file, &pid); if ((kind == 2 || kind == 3) && (proc_text_eq(file, "ns") || proc_text_eq(file, "ns/mnt") || - proc_text_eq(file, "ns/user"))) { + proc_text_eq(file, "ns/user") || proc_text_eq(file, "ns/uts"))) { if (!(kind == 3 ? sched_current_task() : sched_find(pid))) return -RELIEFOS_ENOENT; if (out) *out = (struct storage_node){.flags = STORAGE_NODE_FLAG_PROC, .type = proc_text_eq(file, "ns") ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_SYMLINK}; @@ -1359,9 +1375,10 @@ int proc_readlink(const char *path, char *buffer, uint32_t capacity) } task = kind == 3 ? caller : sched_find(pid); if (!task) return -RELIEFOS_ENOENT; - if (proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user")) { + if (proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user") || proc_text_eq(file, "ns/uts")) { if (!proc_stat_mm_visible(caller, task)) return -RELIEFOS_EACCES; if (proc_text_eq(file, "ns/user")) return nsfs_user_readlink(task->user_ns, buffer, capacity); + if (proc_text_eq(file, "ns/uts")) return nsfs_uts_readlink(task->uts_ns, buffer, capacity); return nsfs_readlink(sched_task_namespace(task), buffer, capacity); } if (!file || (!proc_text_eq(file, "exe") && !proc_text_eq(file, "cwd") && !proc_text_eq(file, "root") && proc_fd_number(file) < 0)) @@ -1496,7 +1513,7 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * if (kind == 3) pid = sched_current_pid(); if ((kind == 2 || kind == 3) && proc_text_eq(file, "ns")) { if (!sched_find(pid)) return -RELIEFOS_ENOENT; - static const char *const namespaces[] = {"mnt", "user"}; + static const char *const namespaces[] = {"mnt", "user", "uts"}; if (*offset >= sizeof(namespaces) / sizeof(namespaces[0])) return 0; *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_SYMLINK}; proc_copy(entry->name, sizeof(entry->name), namespaces[(*offset)++]); @@ -1607,12 +1624,12 @@ int proc_control_permissions(const char *name, const struct storage_node *node, value->gid = namespace_task->egid; } } - if (proc_inotify_key && proc_inotify_key(name)) value->mode = 0644; + if (proc_uts_key(name) || (proc_inotify_key && proc_inotify_key(name))) value->mode = 0644; if (node->type == RELIEFOS_FS_TYPE_DIR || node->type == RELIEFOS_FS_TYPE_SYMLINK) { const char *leaf = NULL; struct task *owner = proc_view_task(name, &leaf); if (owner && (proc_text_eq(leaf, "ns") || proc_text_eq(leaf, "ns/mnt") || - proc_text_eq(leaf, "ns/user"))) { + proc_text_eq(leaf, "ns/user") || proc_text_eq(leaf, "ns/uts"))) { value->mode = node->type == RELIEFOS_FS_TYPE_DIR ? 0511 : 0777; if (!sched_task_mm(owner)->nondumpable) { value->uid = owner->euid; @@ -1630,6 +1647,15 @@ int proc_control_permissions(const char *name, const struct storage_node *node, return 0; } +/** @copydoc proc_control_access */ +int proc_control_access(const char *name,const struct task *task,uint32_t access) +{ + if (!proc_uts_key(name)) return -EOPNOTSUPP; + if (access & FS_ACCESS_EXEC) return -EACCES; + if ((access & FS_ACCESS_WRITE) && (!task || task->euid)) return -EACCES; + return 0; +} + /** @brief Test ASCII whitespace used by a stripped integer control. * @param c Input byte. @return True for the six standard whitespace bytes. */ @@ -1671,11 +1697,12 @@ static int proc_oom_parse(const void *buffer, uint32_t length, int *out) } /** @brief Recognize a live generated control committed by its write callback. - * @param name Intrinsic key. @return True for namespace, OOM, inotify or lock controls. + * @param name Intrinsic key. @return True for namespace, UTS, OOM, inotify or lock controls. */ bool proc_control_immediate(const char *name) { if (proc_userns_key(name, NULL)) return true; + if (proc_uts_key(name)) return true; if (proc_inotify_key && proc_inotify_key(name)) return true; if (proc_oom_key(name, NULL) == 1) return true; #ifdef CONFIG_LOCK_STAT @@ -1691,6 +1718,7 @@ bool proc_control_immediate(const char *name) int proc_control_truncate(const char *name, uint64_t length) { if (proc_userns_key(name, NULL)) return length ? -EINVAL : 0; + if (proc_uts_key(name)) return length ? -EINVAL : 0; if (proc_inotify_key && proc_inotify_key(name)) return length ? -EINVAL : 0; if (proc_oom_key(name, NULL) == 1) return length ? -EINVAL : 0; #ifdef CONFIG_LOCK_STAT @@ -1700,18 +1728,26 @@ int proc_control_truncate(const char *name, uint64_t length) #endif } -/** @brief Apply one authorized whole-value OOM or lock diagnostic write. +/** @brief Apply one authorized live proc control write. * @param name Intrinsic live key. @param offset File position, ignored for OOM. * @param buffer Validated bytes. @param length Exact byte count. @param written * Required output, cleared on failure. @return Zero or negative errno. * VFS DAC and PID identity precede this callback; OOM capability and inherited * minimum policy are checked by the producer under the sole outer writer. + * UTS sysctls use global effective-root DAC on every write and select the + * writer's live UTS scope. Namespace-local capabilities do not bypass this DAC. */ int proc_control_write(const char *name, uint64_t offset, const void *buffer, uint32_t length, uint32_t *written) { if (!written) return -EINVAL; *written = 0; + int uts = proc_uts_key(name); + if (uts) { + struct task *caller = sched_current_task(); + if (!caller || caller->euid) return -EACCES; + return linux_uts_write(buffer, length, offset, uts == 2, written); + } if (proc_inotify_key && proc_inotify_key(name)) return proc_inotify_write(name, offset, buffer, length, written); struct task *task = NULL; diff --git a/fs/security/access.c b/fs/security/access.c index 855dfe51..a7a2cf84 100644 --- a/fs/security/access.c +++ b/fs/security/access.c @@ -211,6 +211,7 @@ int fs_permissions_check_mode(const struct fs_access_cred *cred,bool directory, return -RELIEFOS_EACCES; } +/** @copydoc fs_permissions_check_path */ int fs_permissions_check_path(const struct task *task,const struct vfs_path *path, uint32_t access,bool real_ids) { @@ -225,7 +226,9 @@ int fs_permissions_check_path(const struct task *task,const struct vfs_path *pat (node->type==RELIEFOS_FS_TYPE_FILE || node->type==RELIEFOS_FS_TYPE_DIR || node->type==RELIEFOS_FS_TYPE_SYMLINK))return -RELIEFOS_EROFS; if(node->type==RELIEFOS_FS_TYPE_FILE && (access&FS_ACCESS_EXEC) && (flags&MS_NOEXEC))return -RELIEFOS_EACCES; - struct reliefos_permissions value;int ret=vfs_path_permissions(path,&value,false); + int ret = vfs_path_access(path, task, access); + if (ret != -RELIEFOS_EOPNOTSUPP) return ret; + struct reliefos_permissions value;ret=vfs_path_permissions(path,&value,false); if(ret<0)return ret; struct fs_access_cred cred=fs_access_credentials(task,real_ids); return fs_permissions_check_mode(&cred,node->type==RELIEFOS_FS_TYPE_DIR,&value,access); diff --git a/fs/vfs/attributes.c b/fs/vfs/attributes.c index f002f382..29b9484f 100644 --- a/fs/vfs/attributes.c +++ b/fs/vfs/attributes.c @@ -2,6 +2,14 @@ #include "mount_internal.h" #include +/** @copydoc vfs_path_access */ +int vfs_path_access(const struct vfs_path *path,const struct task *task,uint32_t access) +{ + if (!vfs_path_valid(path)) return -EINVAL; + const struct vfs_backend_ops *ops = path->mount->ops; + return ops->access ? ops->access(path->mount->context, path, task, access) : -EOPNOTSUPP; +} + int vfs_stat_basic(const struct storage_node *node,struct linux_stat_abi *out) { if(node->size>INT64_MAX)return -EOVERFLOW; diff --git a/fs/vfs/pseudo.c b/fs/vfs/pseudo.c index d2a18ffe..d03b716c 100644 --- a/fs/vfs/pseudo.c +++ b/fs/vfs/pseudo.c @@ -314,6 +314,23 @@ static int pseudo_node_permissions(void *value,const struct vfs_path *path, context->provider->permissions(key->name,node,permissions,write) : -EOPNOTSUPP; } +/** @brief Apply provider-specific DAC to a live intrinsic inode identity. + * @param value Pinned pseudo context. @param path Borrowed retained inode. + * @param task Borrowed caller credentials. @param access FS_ACCESS mask. + * @return Provider decision or -EOPNOTSUPP for ordinary mode DAC. Instance + * authorization precedes the optional callback, without graph locks or I/O. + */ +static int pseudo_node_access(void *value,const struct vfs_path *path, + const struct task *task,uint32_t access) +{ + struct pseudo_mount *context = value; + struct pseudo_key *key = pseudo_key_find(context, vfs_path_node(path)->entry_id); + if (!pseudo_key_live(context, key)) return -ENOENT; + int rc = pseudo_key_authorize(context, key); + if (rc) return rc; + return context->provider->access ? context->provider->access(key->name, task, access) : -EOPNOTSUPP; +} + static uint64_t pseudo_mount_flags(void *value) {return ((const struct pseudo_mount *)value)->provider->mount_flags;} @@ -415,7 +432,7 @@ int vfs_pseudo_mount_new_with_state(const struct vfs_pseudo_provider *provider, .release=pseudo_node_release,.same_node=pseudo_node_same,.readlink=pseudo_node_readlink, .follow_link=pseudo_node_follow,.stat_link=pseudo_node_stat_link,.destroy=pseudo_context_destroy, .read=pseudo_node_read,.write=pseudo_node_write,.truncate=pseudo_node_truncate, - .readdir=pseudo_node_readdir,.permissions=pseudo_node_permissions, + .readdir=pseudo_node_readdir,.permissions=pseudo_node_permissions,.access=pseudo_node_access, .file_open=pseudo_file_open,.file_read=pseudo_file_read,.file_write=pseudo_file_write, .file_close=pseudo_file_close, .file_poll=pseudo_file_poll, diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 6ad28ea4..cb7ce73c 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -13,6 +13,7 @@ struct module; struct user_namespace; +struct task; struct vfs_mount; struct vfs_dentry; struct vfs_rename; @@ -162,6 +163,11 @@ struct vfs_backend_ops { * path; callbacks run under the caller's execution transaction. */ int (*permissions)(void *context,const struct vfs_path *path, struct reliefos_permissions *value,bool write); + /* Optional inode-specific DAC after common mount-policy checks. The path + * pins the provider throughout this execution-owned nonblocking query. + * EOPNOTSUPP requests ordinary mode/fsuid/capability authorization. */ + int (*access)(void *context,const struct vfs_path *path, + const struct task *task,uint32_t access); /* Pure shared-state query. Initial creation also snapshots legacy/default * attachment bits once; later policy queries use only shared flags. */ uint64_t (*mount_flags)(void *context); @@ -930,6 +936,14 @@ int vfs_path_listxattr(const struct vfs_path *path,void *names,uint32_t capacity * spans backend I/O. A filesystem lacking metadata support returns EOPNOTSUPP. */ int vfs_path_permissions(const struct vfs_path *path,struct reliefos_permissions *value,bool write); +/** @brief Query optional inode-specific DAC through an authentic held path. + * @param path Borrowed retained inode and provider. + * @param task Borrowed authorization credentials, nullable for kernel callers. + * @param access Validated FS_ACCESS mask after common mount-policy checks. + * @return Zero, a negative access error, or -EOPNOTSUPP for ordinary DAC. + * Execution-owned nonblocking query, without a graph lock or new references. + */ +int vfs_path_access(const struct vfs_path *path,const struct task *task,uint32_t access); /** @brief Read the policy of the actual mount containing a held object. * @param path Borrowed valid path under execution ownership. * @return Attachment MS bits plus current shared readonly/sync policy, or zero diff --git a/include/reliefnt/nsfs.h b/include/reliefnt/nsfs.h index 392299d4..1a3924da 100644 --- a/include/reliefnt/nsfs.h +++ b/include/reliefnt/nsfs.h @@ -8,6 +8,7 @@ struct vfs_namespace; struct vfs_path; struct user_namespace; +struct uts_namespace; /** @brief Create a detached nsfs path retaining the actual mount graph. * @param ns Borrowed live graph, stable under execution ownership. @@ -24,6 +25,14 @@ int nsfs_create_path(struct vfs_namespace *ns, struct vfs_path *out); */ int nsfs_create_user_path(struct user_namespace *ns, struct vfs_path *out); +/** @brief Create an authentic nsfs path retaining a UTS namespace. + * @param ns Borrowed live scope, NULL for the permanent initial scope. + * @param out Required empty destination receiving one owned path. + * @return Zero or negative errno; failure leaves the output empty. + * Execution ownership required. The path retains the scope until final close. + */ +int nsfs_create_uts_path(struct uts_namespace *ns, struct vfs_path *out); + /** @brief Identify the mount graph from an authentic retained nsfs inode. * @param path Borrowed held path under execution ownership, nullable. * @return Borrowed graph valid while the path is held, or NULL for another @@ -39,9 +48,17 @@ struct vfs_namespace *nsfs_path_namespace(const struct vfs_path *path); */ bool nsfs_path_user_namespace(const struct vfs_path *path, struct user_namespace **out); +/** @brief Identify a UTS scope through an authentic retained nsfs inode. + * @param path Borrowed held path under execution ownership, nullable. + * @param out Required borrowed output, NULL for the initial scope. + * @return True for a UTS handle; false clears the output. + * The held path keeps the returned scope live. + */ +bool nsfs_path_uts_namespace(const struct vfs_path *path, struct uts_namespace **out); + /** @brief Authenticate an nsfs inode and query its namespace type. * @param path Borrowed held path under execution ownership, nullable. - * @return CLONE_NEWNS, CLONE_NEWUSER, or zero for another inode. + * @return CLONE_NEWNS, CLONE_NEWUSER, CLONE_NEWUTS, or zero for another inode. * No allocation, references, user access or textual name resolution. */ uint32_t nsfs_path_type(const struct vfs_path *path); @@ -62,4 +79,12 @@ int nsfs_readlink(struct vfs_namespace *ns, char *buffer, size_t capacity); * Execution ownership serializes lazy inode identity assignment. */ int nsfs_user_readlink(struct user_namespace *ns, char *buffer, size_t capacity); + +/** @brief Render a UTS magic-link label without allocating a handle. + * @param ns Borrowed scope, NULL for the initial scope. + * @param buffer Required output, without NUL. @param capacity Maximum bytes. + * @return Copied byte count, possibly truncated, or negative errno. + * Execution ownership serializes lazy inode identity assignment. + */ +int nsfs_uts_readlink(struct uts_namespace *ns, char *buffer, size_t capacity); #endif diff --git a/include/reliefnt/permissions.h b/include/reliefnt/permissions.h index 01f62894..032152d4 100644 --- a/include/reliefnt/permissions.h +++ b/include/reliefnt/permissions.h @@ -37,8 +37,9 @@ int fs_permissions_check_mode(const struct fs_access_cred *cred,bool directory, * @param task Borrowed credentials, NULL for trusted kernel capability access. * @param path Borrowed held path, stable under execution ownership. * @param access FS_ACCESS_* mask; no pathname traversal is performed. - * @param real_ids Select real IDs/permitted root capabilities for access(2). - * @return Zero or negative errno; uid zero alone never grants capabilities. + * @param real_ids Select real IDs/permitted root capabilities for ordinary access(2) DAC. + * @return Zero or negative errno. Mount policy precedes optional inode-specific + * DAC; other inodes use mode/fsuid/capability checks. UID zero does not add capabilities. * Metadata I/O may sleep without graph locks; caller keeps the path pinned. */ int fs_permissions_check_path(const struct task *task,const struct vfs_path *path, diff --git a/include/reliefnt/pseudo_fs.h b/include/reliefnt/pseudo_fs.h index d0535ae5..5573bc29 100644 --- a/include/reliefnt/pseudo_fs.h +++ b/include/reliefnt/pseudo_fs.h @@ -33,6 +33,8 @@ struct vfs_pseudo_provider { int (*stat_link)(const char *name,struct linux_stat_abi *out); int (*permissions)(const char *intrinsic,const struct storage_node *node, struct reliefos_permissions *value,bool write); + /* Optional intrinsic-key DAC; EOPNOTSUPP selects ordinary inode mode DAC. */ + int (*access)(const char *intrinsic,const struct task *task,uint32_t access); /* Optional nonblocking per-open capture. An owned state is consumed by * close even on failed open; NULL means ordinary stateless reads. Reads * through captured state remain valid after the inode identity retires. diff --git a/include/reliefnt/task/accessors.h b/include/reliefnt/task/accessors.h index 8cc56bd9..1bb39f2e 100644 --- a/include/reliefnt/task/accessors.h +++ b/include/reliefnt/task/accessors.h @@ -300,7 +300,8 @@ static inline struct kernel_sigqueue *sched_task_process_signal_queue(struct tas /** @brief Validate clone flags, namespace privilege and TLS before TID access. * @param flags Linux clone flags and optional exit signal. @param tls TLS base. * @return Zero or the scheduler's original validation errno; no locks or I/O. - * Mount namespace creation requires initial user namespace CAP_SYS_ADMIN. + * Mount and UTS creation require current-scope CAP_SYS_ADMIN unless the same + * operation creates a user namespace that owns the new scopes. */ int sched_clone_validate_flags(uint64_t flags,uint64_t tls); /** @brief Clone or share a user's resources and owned filesystem paths. @@ -314,7 +315,8 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls); * Execution transaction required; takes scheduler_lock. CLONE_FS shares the * actual root/cwd owner; ordinary fork retains independent path references. * CLONE_NEWNS prepares a distinct graph before reserving a task ID. - * The child retains the caller's user namespace through publication or rollback. + * User and UTS scopes are retained through publication or rollback. NEWUSER + * creates an empty-map credential scope; NEWUTS copies the current names. */ int64_t sched_clone_current(const struct trap_frame *frame, uint64_t flags, uint64_t stack, uint64_t parent_tid, diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index 5482fca8..eaa95d64 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -534,6 +534,8 @@ struct task_lookup_scope { struct task { /* Lazily allocated PID identity, retained independently by proc inodes. */ struct task_identity *identity_token; + /* Owned UTS scope, retained across exec and until task retirement. */ + struct uts_namespace *uts_ns; /* Owned non-root membership or zombie charge, protected by scheduler_lock. */ struct cgroup *cgroup; uint64_t proc_read_chars, proc_write_chars, proc_read_calls, proc_write_calls; diff --git a/include/reliefnt/user_namespace.h b/include/reliefnt/user_namespace.h index c7d1a20c..8b95137e 100644 --- a/include/reliefnt/user_namespace.h +++ b/include/reliefnt/user_namespace.h @@ -145,14 +145,16 @@ int sched_task_user_namespace_create(const struct task *task, struct user_namesp */ void sched_task_user_namespace_install(struct task *task, struct user_namespace *ns); -/** @brief Atomically create a user scope and separate the caller's FS state. +/** @brief Atomically prepare and install requested user, UTS and filesystem scopes. * @param task Current execution-owned task, required. - * @param new_mount_namespace Also snapshot the graph after caller authorization. + * @param flags Validated CLONE_NEWUSER, CLONE_NEWNS, CLONE_NEWUTS and CLONE_FS flags. * @return Zero, -EINVAL for a live thread group, or a preparation error. * Preparation runs outside scheduler_lock. Failures preserve credentials, - * root/cwd/umask sharing, namespace references and publication state. + * root/cwd/umask sharing, namespace references and publication state. UTS-only + * requests preserve CLONE_FS sharing. New mount and UTS scopes require current + * CAP_SYS_ADMIN or use authority from the user scope created in this operation. */ -int sched_task_user_namespace_unshare(struct task *task, bool new_mount_namespace); +int sched_task_namespaces_unshare(struct task *task, uint64_t flags); /** @brief Join an authorized user scope through an authenticated held handle. * @param task Current execution-owned task, required. diff --git a/include/reliefnt/uts.h b/include/reliefnt/uts.h index b2430adb..df03c005 100644 --- a/include/reliefnt/uts.h +++ b/include/reliefnt/uts.h @@ -1,19 +1,66 @@ +/* SPDX-License-Identifier: Apache-2.0 */ #ifndef RELIEFNT_UTS_H #define RELIEFNT_UTS_H #include +struct user_namespace; + +/** @brief Shared host identity with an immutable credential owner. + * NULL denotes the permanent initial scope. References are atomic; names use + * the short UTS lock. Namespace identity assignment requires execution ownership. + */ +struct uts_namespace { + uint64_t references; + uint64_t nsfs_inode; + struct user_namespace *user_ns; + char hostname[65]; + char domainname[65]; +}; + +/** @brief Copy a live host identity into a new owned namespace. + * @param source Borrowed source, NULL for the initial scope. + * @param owner Borrowed user scope retained by the new namespace. + * @param out Required output, cleared on failure; owns one reference on success. + * @return Zero, -EINVAL or -ENOMEM. No capability checks or task publication. + * Caller holds execution ownership outside scheduler_lock. + */ +int uts_namespace_create(const struct uts_namespace *source, struct user_namespace *owner, + struct uts_namespace **out); + +/** @brief Retain an existing UTS namespace without allocating. + * @param ns Borrowed live scope, NULL for the permanent initial scope. + * @return The same pointer with one additional owned reference. + */ +struct uts_namespace *uts_namespace_get(struct uts_namespace *ns); + +/** @brief Drop a UTS reference and release its owner on final destruction. + * @param ns Owned scope reference, nullable for the permanent initial scope. + * Does not acquire the UTS lock or access task state. + */ +void uts_namespace_put(struct uts_namespace *ns); /* Native identity; callers may opt into Linux sysname through ReliefNT prctl. */ #define LINUX_UTS_SYSNAME "ReliefNT" /** - * @brief Copy a coherent snapshot under the UTS spinlock. + * @brief Copy the current task's coherent host identity under the UTS spinlock. * @param hostname Writable 65-byte kernel buffer for the hostname. * @param domainname Writable 65-byte kernel buffer for the NIS domain. */ void linux_uts_names(char hostname[65], char domainname[65]); -/** @brief Set a captured kernel name (0..64 bytes); domain selects NIS domain. +/** @brief Set a captured name in the current task's UTS namespace. * @param name Captured kernel bytes, nullable only when length is zero. * @param length Byte count, at most 64; embedded NUL is preserved like Linux. * @param domain Nonzero selects the NIS domain, zero selects the hostname. - * @return Zero or negative EINVAL. Caller performs capability/user-pointer checks. + * @return Zero or negative EINVAL. Caller checks capability in the UTS owner + * and captures user memory first. A missing task selects the initial scope. */ int linux_uts_set(const char *name, uint32_t length, int domain); +/** @brief Apply a proc sysctl string write to the caller's live UTS scope. + * @param buffer Captured bytes, nullable only for zero length. + * @param length Input byte count. @param offset Byte position within the name. + * @param domain Nonzero selects domainname. @param written Required accepted + * byte count, cleared on failure. @return Zero or -EINVAL. Copies at most + * 64 bytes, stopping at NUL/newline; offsets beyond the current name are ignored. + * Caller checks sysctl DAC and mount policy. One short lock serializes updates. + */ +int linux_uts_write(const void *buffer, uint32_t length, uint64_t offset, + int domain, uint32_t *written); #endif diff --git a/kernel/init/uts.c b/kernel/init/uts.c index fbfc6d91..09e9dea1 100644 --- a/kernel/init/uts.c +++ b/kernel/init/uts.c @@ -1,38 +1,107 @@ -/* Shared UTS state for uname, hostname syscalls, and procfs. */ +/* SPDX-License-Identifier: Apache-2.0 */ +/* Namespaced UTS state for uname, hostname syscalls, and procfs. */ #include #include +#include +#include +#include +#include static struct kernel_spinlock uts_lock = KERNEL_SPINLOCK_INIT; -static char uts_hostname[65] = "reliefos"; -static char uts_domainname[65] = "(none)"; +static struct uts_namespace initial_uts = { + .hostname = "reliefos", .domainname = "(none)", +}; -/** @brief Snapshot both names under a short lock. - * @param hostname Writable 65-byte kernel buffer. - * @param domainname Writable 65-byte kernel buffer. +/** @copydoc uts_namespace_get */ +struct uts_namespace *uts_namespace_get(struct uts_namespace *ns) +{ + if (ns) __atomic_add_fetch(&ns->references, 1, __ATOMIC_RELAXED); + return ns; +} + +/** @copydoc uts_namespace_put */ +void uts_namespace_put(struct uts_namespace *ns) +{ + if (!ns || __atomic_sub_fetch(&ns->references, 1, __ATOMIC_ACQ_REL)) return; + user_namespace_put(ns->user_ns); + kernel_free(ns); +} + +/** @copydoc uts_namespace_create */ +int uts_namespace_create(const struct uts_namespace *source, struct user_namespace *owner, + struct uts_namespace **out) +{ + if (!out) return -LINUX_EINVAL; + *out = NULL; + struct uts_namespace *ns = kernel_malloc(sizeof(*ns)); + if (!ns) return -LINUX_ENOMEM; + *ns = (struct uts_namespace){.references = 1, .user_ns = user_namespace_get(owner)}; + if (!source) source = &initial_uts; + uint64_t flags; + kernel_spin_lock_irqsave(&uts_lock, &flags); + __builtin_memcpy(ns->hostname, source->hostname, sizeof(ns->hostname)); + __builtin_memcpy(ns->domainname, source->domainname, sizeof(ns->domainname)); + kernel_spin_unlock_irqrestore(&uts_lock, flags); + *out = ns; + return 0; +} + +/** @brief Select the execution-owned caller's live identity or initial scope. + * @return Borrowed scope, stable until the execution transaction completes. */ +static struct uts_namespace *uts_current(void) +{ + struct task *task = sched_current_task(); + return task && task->uts_ns ? task->uts_ns : &initial_uts; +} + +/** @copydoc linux_uts_names */ void linux_uts_names(char hostname[65], char domainname[65]) { + struct uts_namespace *ns = uts_current(); uint64_t flags; kernel_spin_lock_irqsave(&uts_lock, &flags); - __builtin_memcpy(hostname, uts_hostname, 65); - __builtin_memcpy(domainname, uts_domainname, 65); + __builtin_memcpy(hostname, ns->hostname, 65); + __builtin_memcpy(domainname, ns->domainname, 65); kernel_spin_unlock_irqrestore(&uts_lock, flags); } -/** @brief Atomically replace a captured kernel name without touching user memory under the lock. - * @param name Kernel input bytes, nullable when length is zero. - * @param length Length in bytes, zero through 64. - * @param domain Nonzero selects NIS domain, otherwise hostname. - * @return Zero or negative EINVAL; rejected input leaves the previous name intact. - */ +/** @copydoc linux_uts_set */ int linux_uts_set(const char *name, uint32_t length, int domain) { char value[65] = {0}; uint64_t flags; if (length > 64 || (!name && length)) return -22; if (length) __builtin_memcpy(value, name, length); + struct uts_namespace *ns = uts_current(); + kernel_spin_lock_irqsave(&uts_lock, &flags); + __builtin_memcpy(domain ? ns->domainname : ns->hostname, value, sizeof(value)); + kernel_spin_unlock_irqrestore(&uts_lock, flags); + return 0; +} + +/** @copydoc linux_uts_write */ +int linux_uts_write(const void *buffer, uint32_t length, uint64_t offset, + int domain, uint32_t *written) +{ + if (!written) return -LINUX_EINVAL; + *written = 0; + if (!buffer && length) return -LINUX_EINVAL; + if (!length) return 0; + struct uts_namespace *ns = uts_current(); + const char *bytes = buffer; + uint64_t flags; kernel_spin_lock_irqsave(&uts_lock, &flags); - __builtin_memcpy(domain ? uts_domainname : uts_hostname, value, sizeof(value)); + char *name = domain ? ns->domainname : ns->hostname; + uint32_t end = 0; + while (end < 64 && name[end]) ++end; + if (offset <= end) { + uint32_t position = (uint32_t)offset, consumed = 0; + while (position < 64 && consumed < length && bytes[consumed] && bytes[consumed] != '\n') + name[position++] = bytes[consumed++]; + __builtin_memset(name + position, 0, 65 - position); + } kernel_spin_unlock_irqrestore(&uts_lock, flags); + *written = length; return 0; } diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index 11aaedac..13916d11 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -131,13 +131,14 @@ void sched_vfork_child_done(struct task *child) * @param flags Linux clone flags and exit signal. @param tls Requested TLS base. * @return Zero or the original clone validation errno; no allocation, locks, * user access or state changes occur. - * A new graph requires current-scope CAP_SYS_ADMIN unless CLONE_NEWUSER + * New mount and UTS scopes require current-scope CAP_SYS_ADMIN unless CLONE_NEWUSER * creates its owning scope in the same operation. */ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) { const uint64_t supported = CSIGNAL | CLONE_VM | CLONE_VFORK | CLONE_FS | - CLONE_FILES | CLONE_SIGHAND | CLONE_PARENT | CLONE_THREAD | CLONE_SYSVSEM | CLONE_NEWNS | CLONE_NEWUSER | + CLONE_FILES | CLONE_SIGHAND | CLONE_PARENT | CLONE_THREAD | CLONE_SYSVSEM | + CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED | CLONE_UNTRACED | CLONE_CHILD_SETTID | CLONE_CLEAR_SIGHAND; if ((flags & CLONE_NEWNS) && (flags & CLONE_FS)) return -LINUX_EINVAL; @@ -156,7 +157,7 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) ? -LINUX_EINVAL : -LINUX_EPERM; } if (flags & ~supported) return -RELIEFOS_ENOSYS; - if ((flags & CLONE_NEWNS) && !(flags & CLONE_NEWUSER)) { + if ((flags & (CLONE_NEWNS | CLONE_NEWUTS)) && !(flags & CLONE_NEWUSER)) { const struct task *parent = sched_current_task(); if (!parent || !task_ns_capable(parent, parent->user_ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; } @@ -186,7 +187,8 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) * child full local authority. Other children retain the inherited scope. * A new mount graph retains the candidate user scope or the parent's current * scope and locks inherited attachments when its owner changes. - * Every rollback releases the prepared or installed user namespace reference. + * CLONE_NEWUTS copies names into a scope owned by the candidate user namespace. + * Other children share the source UTS scope. Every rollback releases both scopes. */ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flags, uint64_t stack, uint64_t parent_tid, @@ -212,6 +214,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag bool files_retained = false; struct task_fs_paths snapshot = {0}; struct user_namespace *user_ns = NULL; + struct uts_namespace *uts_ns = NULL; if (!parent || !parent_frame || parent->kind != TASK_KIND_USER || parent->state == TASK_EXITED || !(*sched_task_as(parent)).cr3) { kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); @@ -225,14 +228,17 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag return -LINUX_EAGAIN; } parent->nproc_exceeded = false; - if (flags & (CLONE_NEWNS | CLONE_NEWUSER)) { + if (flags & (CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS)) { /* Execution ownership keeps admission and the source stable. VFS can * call into providers on failure, so take no scheduler lock or PID. */ kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); int rc = flags & CLONE_NEWUSER ? sched_task_user_namespace_create(parent, &user_ns) : 0; + if (!rc && (flags & CLONE_NEWUTS)) + rc = uts_namespace_create(parent->uts_ns, user_ns ? user_ns : parent->user_ns, &uts_ns); if (!rc && (flags & CLONE_NEWNS)) rc = sched_task_fs_snapshot(parent, user_ns ? user_ns : parent->user_ns, &snapshot); if (rc) { + uts_namespace_put(uts_ns); user_namespace_put(user_ns); sched_task_identity_put(identity); return rc; @@ -252,6 +258,8 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag task_zero(child); *child = *parent; child->user_ns = user_namespace_get(parent->user_ns); + child->uts_ns = flags & CLONE_NEWUTS ? uts_ns : uts_namespace_get(parent->uts_ns); + uts_ns = NULL; if (user_ns) { sched_task_user_namespace_install(child, user_ns); user_ns = NULL; @@ -607,6 +615,8 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag sched_task_fs_release(child); user_namespace_put(child->user_ns); child->user_ns = NULL; + uts_namespace_put(child->uts_ns); + child->uts_ns = NULL; if (!child->shared_mm) { address_space_destroy(sched_task_as(child)); sched_task_vma_release(child); @@ -633,6 +643,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag fail_prepare: kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_fs_paths_put(&snapshot); + uts_namespace_put(uts_ns); user_namespace_put(user_ns); sched_task_identity_put(identity); return -LINUX_ENOMEM; diff --git a/kernel/sched/internal.h b/kernel/sched/internal.h index 546f88fa..e31bf678 100644 --- a/kernel/sched/internal.h +++ b/kernel/sched/internal.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include diff --git a/kernel/sched/session.c b/kernel/sched/session.c index b7fe124a..afca51af 100644 --- a/kernel/sched/session.c +++ b/kernel/sched/session.c @@ -53,7 +53,7 @@ void task_clear_identity(struct task *task) * @brief Inherit identity and independent filesystem references from a parent. * @param task New task with private filesystem state under execution ownership. * @param parent Stable source task; NULL leaves the destination unchanged. - * Retains supplemental groups, the owning user namespace and mount/dentry references + * Retains supplemental groups, user and UTS namespaces and mount/dentry references * without allocating or resolving cached path strings. The destination initially * has no owned credential references. Caller serializes publication with scheduler_lock. */ @@ -63,6 +63,7 @@ void task_copy_identity_from_parent(struct task *task, const struct task *parent return; } task->user_ns = user_namespace_get(parent->user_ns); + task->uts_ns = uts_namespace_get(parent->uts_ns); task->uid = parent->uid; task->gid = parent->gid; task->euid = parent->euid; diff --git a/kernel/sched/task.c b/kernel/sched/task.c index 98d26854..5f084817 100644 --- a/kernel/sched/task.c +++ b/kernel/sched/task.c @@ -195,7 +195,7 @@ uint32_t task_allocate_pid(void) * Caller holds scheduler_lock. Retires old PID identities before reuse so held * proc inodes cannot retarget. Preserves recycled thread CPU time on its still * published group leader; releases no filesystem or device resources here. - * Recycling releases the old task's owning user namespace reference. + * Recycling releases the old task's user and UTS namespace references. */ struct task *alloc_task_slot(void) { @@ -211,6 +211,8 @@ struct task *alloc_task_slot(void) sched_task_identity_detach(tasks[i]); user_namespace_put(tasks[i]->user_ns); tasks[i]->user_ns = NULL; + uts_namespace_put(tasks[i]->uts_ns); + tasks[i]->uts_ns = NULL; struct sched_task_object *object = (struct sched_task_object *)tasks[i]; object->futex_exit = (struct futex_exit_cursor){0}; object->exec_prepared = NULL; diff --git a/kernel/sched/user_namespace_task.c b/kernel/sched/user_namespace_task.c index 4468ed6b..fda230d0 100644 --- a/kernel/sched/user_namespace_task.c +++ b/kernel/sched/user_namespace_task.c @@ -47,19 +47,33 @@ void sched_task_user_namespace_install(struct task *task, struct user_namespace user_namespace_put(old); } -/** @copydoc sched_task_user_namespace_unshare */ -int sched_task_user_namespace_unshare(struct task *task, bool new_mount_namespace) +/** @copydoc sched_task_namespaces_unshare */ +int sched_task_namespaces_unshare(struct task *task, uint64_t flags) { - if (thread_group_pending(sched_task_tgid(task), task)) return -LINUX_EINVAL; + bool new_user = (flags & CLONE_NEWUSER) != 0; + bool new_mount = (flags & CLONE_NEWNS) != 0; + bool new_uts = (flags & CLONE_NEWUTS) != 0; + if (new_user && thread_group_pending(sched_task_tgid(task), task)) return -LINUX_EINVAL; + if (!new_user && (new_mount || new_uts) && + !task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; struct user_namespace *ns = NULL; - int rc = sched_task_user_namespace_create(task, &ns); - if (rc) return rc; - rc = sched_task_fs_unshare(task, new_mount_namespace, ns); + struct uts_namespace *uts = NULL; + int rc = new_user ? sched_task_user_namespace_create(task, &ns) : 0; + if (!rc && new_uts) + rc = uts_namespace_create(task->uts_ns, new_user ? ns : task->user_ns, &uts); + if (!rc && (flags & (CLONE_NEWUSER | CLONE_NEWNS | CLONE_FS))) + rc = sched_task_fs_unshare(task, new_mount, new_user ? ns : task->user_ns); if (rc) { + uts_namespace_put(uts); user_namespace_put(ns); return rc; } - sched_task_user_namespace_install(task, ns); + if (new_user) sched_task_user_namespace_install(task, ns); + if (new_uts) { + struct uts_namespace *old = task->uts_ns; + task->uts_ns = uts; + uts_namespace_put(old); + } return 0; } diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index b6ee988d..44a0d6fa 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -171,7 +171,7 @@ static void sched_wait_usage(struct linux_rusage *out, const struct task *task) * execute outside it. WNOWAIT observes without consuming or logging a reap. * Consuming a zombie releases its cgroup charge and invalidates its retained * PID identity before PID unpublish. - * A consuming reap also releases the zombie's owning user namespace reference. + * A consuming reap also releases the zombie's user and UTS namespace references. */ static int64_t sched_wait_child(uint32_t waiter_pid, int32_t wanted_pid, const struct task_identity *identity, @@ -296,6 +296,8 @@ static int64_t sched_wait_child(uint32_t waiter_pid, int32_t wanted_pid, sched_task_identity_detach(reap_task); user_namespace_put(reap_task->user_ns); reap_task->user_ns = NULL; + uts_namespace_put(reap_task->uts_ns); + reap_task->uts_ns = NULL; task_release_limits(reap_task); reap_task->flags &= ~(TASK_FLAG_WAITABLE_CHILD | TASK_FLAG_REAP_IN_PROGRESS); task_copy_name(reap_task, "reaped"); diff --git a/kernel/syscall/process/clone.c b/kernel/syscall/process/clone.c index 0c423282..5e62e50f 100644 --- a/kernel/syscall/process/clone.c +++ b/kernel/syscall/process/clone.c @@ -139,17 +139,15 @@ int64_t syscall_clone3(const struct trap_frame *frame, uint64_t arguments, uint6 * @return Zero (including a no-op for flags=0), or negative Linux errno. * Validate the entire request before preparing or publishing a snapshot. * User scope creation requires a single-threaded caller, mapped effective IDs - * and an unrestricted root. A new mount graph requires current-scope + * and an unrestricted root. A new mount graph or UTS scope requires current-scope * CAP_SYS_ADMIN, or is owned by the user scope created in the same operation. + * UTS-only unshare retains the existing filesystem sharing arrangement. */ int64_t syscall_unshare(struct task *task, uint64_t flags) { - uint64_t supported = CLONE_NEWNS | CLONE_NEWUSER | CLONE_FS; + uint64_t supported = CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS | CLONE_FS; if (flags & CLONE_NEWUSER) supported |= CLONE_THREAD; if (!task || (flags & ~supported)) return -LINUX_EINVAL; if (!flags) return 0; - bool new_namespace = (flags & CLONE_NEWNS) != 0; - if (flags & CLONE_NEWUSER) return sched_task_user_namespace_unshare(task, new_namespace); - if (new_namespace && !task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; - return sched_task_fs_unshare(task, new_namespace, task->user_ns); + return sched_task_namespaces_unshare(task, flags); } diff --git a/kernel/syscall/process/process.c b/kernel/syscall/process/process.c index 8b98904e..8e72910d 100644 --- a/kernel/syscall/process/process.c +++ b/kernel/syscall/process/process.c @@ -934,7 +934,8 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, struct task *task = sched_current_task(); char captured[RELIEFOS_UTSNAME_LEN] = {0}; int32_t length = (int32_t)a1; /* native syscall takes int, not size_t */ - if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_SYS_ADMIN))) return -RELIEFOS_EPERM; + if (!task || !task_ns_capable(task, task->uts_ns ? task->uts_ns->user_ns : NULL, + CAP_SYS_ADMIN)) return -RELIEFOS_EPERM; if (length < 0 || length >= (int32_t)RELIEFOS_UTSNAME_LEN) return -RELIEFOS_EINVAL; if (length) { int prep=process_prepare_user(task,a0,(uint32_t)length,false);if(prep)return prep; } if (length && !user_range_ok(a0, (uint32_t)length)) return -RELIEFOS_EFAULT; diff --git a/kernel/syscall/process/setns.c b/kernel/syscall/process/setns.c index de5309e2..271aebf3 100644 --- a/kernel/syscall/process/setns.c +++ b/kernel/syscall/process/setns.c @@ -1,18 +1,20 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" #include +#include #include #include #include -/** @brief Join a mount graph or user scope through an authentic namespace FD. +/** @brief Join a mount, user or UTS scope through an authentic namespace FD. * @param task Live caller; execution ownership keeps its FD table stable. * @param fd Descriptor number (not O_PATH or a pidfd). - * @param type Zero, CLONE_NEWNS or CLONE_NEWUSER matching the held inode. + * @param type Zero or CLONE_NEWNS/CLONE_NEWUSER/CLONE_NEWUTS matching the inode. * @return Zero or a negative descriptor, capability or namespace error. * Mount graph entry requires current-scope CAP_SYS_ADMIN and CAP_SYS_CHROOT, * plus CAP_SYS_ADMIN in the target graph's owning user scope. * User scope entry requires target CAP_SYS_ADMIN and exclusive thread/FS state. + * UTS entry requires local and owner CAP_SYS_ADMIN; FS sharing is retained. */ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) { @@ -25,6 +27,15 @@ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) struct user_namespace *scope = NULL; if (nsfs_path_user_namespace(&file->path_ref, &scope)) return sched_task_user_namespace_join(task, scope); + struct uts_namespace *uts = NULL; + if (nsfs_path_uts_namespace(&file->path_ref, &uts)) { + if (!task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN) || + !task_ns_capable(task, uts ? uts->user_ns : NULL, CAP_SYS_ADMIN)) return -LINUX_EPERM; + struct uts_namespace *old = task->uts_ns; + task->uts_ns = uts_namespace_get(uts); + uts_namespace_put(old); + return 0; + } struct vfs_namespace *ns = nsfs_path_namespace(&file->path_ref); if (!ns) return -LINUX_EINVAL; if (!task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN) || diff --git a/tools/test_linux_inventory.py b/tools/test_linux_inventory.py index d9385b4f..129cf188 100644 --- a/tools/test_linux_inventory.py +++ b/tools/test_linux_inventory.py @@ -12,7 +12,7 @@ def host(): '-Iinclude','-Iinclude','-Iinclude/uapi', '-Iinclude','tools/tests/linux_inventory_test.c','fs/vfs/mount_tree.c', 'fs/vfs/lookup_cache.c', 'fs/vfs/path.c','fs/vfs/mount_table.c','fs/vfs/file.c','fs/vfs/open.c','fs/vfs/pseudo.c', 'fs/vfs/attributes.c','fs/proc/mount.c','fs/nsfs/namespace.c','fs/proc/views.c','kernel/syscall/fd/proc.c','fs/vfs/exec_file.c', - 'fs/sysfs/mount.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','kernel/sched/user_namespace.c','fs/security/access.c','-o',executable]) + 'fs/sysfs/mount.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','kernel/sched/user_namespace.c','kernel/init/uts.c','fs/security/access.c','-o',executable]) run([executable]) if __name__ == "__main__": diff --git a/tools/test_lock_profile.py b/tools/test_lock_profile.py index 57cfc689..2e1d42ca 100644 --- a/tools/test_lock_profile.py +++ b/tools/test_lock_profile.py @@ -23,7 +23,7 @@ binary = str(Path(directory) / "proc") sources = ["tools/tests/lock_profile_proc_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", - "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "fs/security/access.c"] + "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "fs/security/access.c"] if (ROOT / "kernel/sync/profile.c").exists(): sources.append("kernel/sync/profile.c") subprocess.run(["cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", @@ -51,6 +51,6 @@ "-Iinclude", "-Iinclude/uapi", "tools/tests/lock_profile_sync_io_test.c", "tools/tests/task8_host_stubs/writable_alias_model.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "tools/tests/task8_host_stubs/user_ram_unreached.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", - "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "fs/security/access.c", "kernel/sync/profile.c", + "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "fs/security/access.c", "kernel/sync/profile.c", "-o", binary], cwd=ROOT, check=True) subprocess.run([binary], cwd=ROOT, check=True, timeout=10) diff --git a/tools/test_memory_reporting.py b/tools/test_memory_reporting.py index 2e6e90b8..c2f7761d 100644 --- a/tools/test_memory_reporting.py +++ b/tools/test_memory_reporting.py @@ -46,7 +46,7 @@ def run_cases(output, cases): if "swap-stream" in cases: binary = str(output / "memory_reporting_swap") sources = ["tools/tests/memory_reporting_swap_test.c", "fs/proc/memory.c", - "mm/swap/area.c", "mm/swap/slot.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", + "mm/swap/area.c", "mm/swap/slot.c", "fs/vfs/mount_tree.c", "kernel/sched/user_namespace.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/dentry.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "kernel/module/lifecycle.c", "kernel/params/value.c", "kernel/module/layout.c", "kernel/module/symbols.c"] @@ -74,7 +74,7 @@ def run_cases(output, cases): "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", - "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/sched/oom.c", "fs/security/access.c", + "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "kernel/sched/oom.c", "fs/security/access.c", "fs/proc/memory.c", "mm/reclaim/stats.c", "mm/reclaim/oom.c"] proc_command = [clang, "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", @@ -91,7 +91,7 @@ def run_cases(output, cases): "-fno-omit-frame-pointer", "-ffunction-sections", "-fdata-sections", "-DCONFIG_SWAP=1", "-DRELIEFNT_CACHE_PROBE=1", "-DRELIEFNT_DIRTY_PROBE=1", "-fno-pie", "-no-pie", "-Wl,--gc-sections", "-Iinclude", "-Iinclude/uapi"] sources = ["tools/tests/memory_reporting_test.c", "kernel/sched/core.c", "kernel/sched/accounting.c", "kernel/sched/wait.c", - "kernel/sched/oom.c", "kernel/sync/wait.c", "mm/reclaim/pressure.c", "mm/reclaim/wait.c", + "kernel/sched/oom.c", "kernel/sched/user_namespace.c", "kernel/sync/wait.c", "mm/reclaim/pressure.c", "mm/reclaim/wait.c", "mm/cache/page_cache.c", "mm/reclaim/stats.c", "kernel/exec/usercopy.c", "kernel/exec/usercopy_task.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/attributes.c", "fs/vfs/exec_file.c", "mm/swap/area.c", "mm/swap/slot.c", "mm/swap/paging.c", "-Wl,--wrap=vfs_exec_source_get", "-Wl,--wrap=vfs_exec_source_put", diff --git a/tools/test_procfs.py b/tools/test_procfs.py index 8f165fd8..6ebc9698 100644 --- a/tools/test_procfs.py +++ b/tools/test_procfs.py @@ -20,7 +20,7 @@ def test_real_procfs_directory_lookup_and_enumeration(self): "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", - "kernel/sched/identity.c", "kernel/sched/user_namespace.c", + "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "fs/security/access.c", "-o", executable], cwd=ROOT, check=True) subprocess.run([executable], check=True, timeout=10) diff --git a/tools/test_rootfs.py b/tools/test_rootfs.py index 7a1cdf17..ded82301 100644 --- a/tools/test_rootfs.py +++ b/tools/test_rootfs.py @@ -19,9 +19,12 @@ def test_kernel_modules(self): extra = (["fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", - "fs/security/access.c"] if name in ("procfs_directories", "rootfs_paths") else []) + "fs/security/access.c", "kernel/init/uts.c"] if name in ("procfs_directories", "rootfs_paths") else []) + if name == "rootfs_uts": + extra = ["kernel/sched/user_namespace.c"] if name in ("linux_permissions", "chroot_paths"): extra = ['fs/vfs/mount_tree.c', 'fs/vfs/lookup_cache.c', 'fs/vfs/mount_table.c', 'fs/vfs/path.c', 'fs/vfs/dentry.c', 'fs/vfs/file.c', 'fs/vfs/open.c', 'fs/vfs/attributes.c', 'fs/vfs/mutation.c', 'fs/security/access.c', 'kernel/syscall/fs/create.c', 'kernel/syscall/fs/mutation.c'] + extra.append("kernel/sched/user_namespace.c") subprocess.run(["cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", diff --git a/tools/tests/modules/scheduler.h b/tools/tests/modules/scheduler.h index 67a1a5d6..c1404e04 100644 --- a/tools/tests/modules/scheduler.h +++ b/tools/tests/modules/scheduler.h @@ -26,6 +26,7 @@ static void fixture_exec_other_exit(uint32_t pid, uint64_t code); #include "../../../kernel/sched/fs.c" #include "../../../kernel/sched/identity.c" #include "../../../kernel/sched/user_namespace.c" +#include "../../../kernel/init/uts.c" #include "../../../kernel/sched/user_namespace_task.c" #include "../../../kernel/sched/tables.c" #include "../../../kernel/sched/lookup.c" diff --git a/tools/tests/mount_namespace_task_test.c b/tools/tests/mount_namespace_task_test.c index 34b8d322..d5701865 100644 --- a/tools/tests/mount_namespace_task_test.c +++ b/tools/tests/mount_namespace_task_test.c @@ -29,12 +29,17 @@ int task_fd_descriptor_flags(struct task *task, int fd) static int mount_budget = -1; static int user_namespace_budget = -1; +static int uts_namespace_budget = -1; static unsigned mount_allocations, charges; static const struct task *unpublished_child; /** @brief Fail the second snapshot attachment, after staging the first one. */ bool namespace_heap_admit(uint64_t size) { + if (size == sizeof(struct uts_namespace) && uts_namespace_budget >= 0) { + assert(!scheduler_lock.state); + return uts_namespace_budget-- > 0; + } if (size == sizeof(struct user_namespace) && user_namespace_budget >= 0) { assert(!scheduler_lock.state); return user_namespace_budget-- > 0; @@ -94,6 +99,7 @@ static void retire_child(struct task *child) kernel_free(child->exec_data); sched_task_identity_detach(child); user_namespace_put(child->user_ns); + uts_namespace_put(child->uts_ns); task_zero(child); child->state = TASK_EXITED; child->running_cpu = SCHED_CPU_NONE; @@ -322,7 +328,7 @@ static void check_user_namespaces(struct task *parent, struct task *child, child->tgid = parent->tgid; child->state = TASK_READY; assert(syscall_unshare(parent, CLONE_NEWUSER) == -LINUX_EINVAL); - child->pid = 0; + child->pid = child->tgid = 0; child->state = TASK_EXITED; struct task sibling = {.shared_fs = parent->shared_fs}; ++sibling.shared_fs->references; @@ -396,7 +402,7 @@ static void check_user_setns(struct task *task, struct task *thread) thread->tgid = task->tgid; thread->state = TASK_READY; assert(syscall_setns(task, 3, CLONE_NEWUSER) == -LINUX_EINVAL); - thread->pid = 0; + thread->pid = thread->tgid = 0; thread->state = TASK_EXITED; assert(!task_promote_shared(task, CLONE_FS)); struct task sibling = {.shared_fs = task->shared_fs}; @@ -483,6 +489,135 @@ static void check_mount_user_setns(struct task *task) puts("PASS mount namespace user ownership, local unshare and scoped setns authority"); } +/** @brief Exercise UTS sharing, owned copies and every namespace preparation rollback. */ +static void check_uts_creation(struct task *parent, struct task *child, + struct clone_operands *user) +{ + assert(!parent->uts_ns && !parent->user_ns); + assert(!uts_namespace_create(NULL, NULL, &parent->uts_ns)); + assert(!linux_uts_set("parent", 6, 0) && !linux_uts_set("parent.domain", 13, 1)); + struct uts_namespace *source = parent->uts_ns; + const uint64_t admin = UINT64_C(1) << CAP_SYS_ADMIN; + for (unsigned versioned = 0; versioned < 2; ++versioned) { + parent->cap_effective = 0; + assert(clone_namespace(parent, user, versioned, CLONE_NEWUTS) == -LINUX_EPERM); + parent->cap_effective = admin; + assert(clone_namespace(parent, user, versioned, 0) > 0); + assert(child->uts_ns == source && source->references == 2); + assert(!linux_uts_set("shared", 6, 0) && !strcmp(child->uts_ns->hostname, "shared")); + retire_child(child); + assert(source->references == 1); + + uint64_t created = proc_created, mount_id = next_mount_id; + unsigned old_charges = charges, pages = live_pages(); + const uint64_t flags = CLONE_NEWUTS | CLONE_PARENT_SETTID | CLONE_CHILD_SETTID; + user->parent_tid = user->child_tid = 0x44444444; + uts_namespace_budget = 0; + assert(clone_namespace(parent, user, versioned, flags) == -LINUX_ENOMEM); + uts_namespace_budget = -1; + unpublished_child = child; + mount_budget = 1; + assert(clone_namespace(parent, user, versioned, flags | CLONE_NEWNS) == -LINUX_ENOMEM); + mount_budget = -1; + shm_physical_budget = 0; + assert(clone_namespace(parent, user, versioned, flags) == -LINUX_ENOMEM); + shm_physical_budget = -1; + assert(!child->pid && !child->uts_ns && !child->user_ns); + assert(source->references == 1 && proc_created == created && charges == old_charges); + assert(next_mount_id == mount_id && live_pages() == pages); + assert(user->parent_tid == 0x44444444 && user->child_tid == 0x44444444); + + assert(clone_namespace(parent, user, versioned, CLONE_NEWUTS | CLONE_FS) > 0); + assert(child->uts_ns != source && !child->uts_ns->user_ns && source->references == 1); + assert(!strcmp(child->uts_ns->hostname, "shared") && + !strcmp(child->uts_ns->domainname, "parent.domain")); + assert(child->shared_fs == parent->shared_fs); + current_task[0] = child; + current_pid[0] = child->pid; + assert(!linux_uts_set("isolated", 8, 0)); + current_task[0] = parent; + current_pid[0] = parent->pid; + char hostname[65], domainname[65]; + linux_uts_names(hostname, domainname); + assert(!strcmp(hostname, "shared") && !strcmp(domainname, "parent.domain")); + retire_child(child); + + parent->cap_effective = 0; + assert(clone_namespace(parent, user, versioned, CLONE_NEWUSER | CLONE_NEWUTS) > 0); + assert(child->uts_ns->user_ns == child->user_ns && child->user_ns->references == 2); + assert(task_ns_capable(child, child->uts_ns->user_ns, CAP_SYS_ADMIN)); + assert(!task_ns_capable(child, source->user_ns, CAP_SYS_ADMIN)); + retire_child(child); + parent->cap_effective = admin; + } + + assert(!task_promote_shared(parent, CLONE_FS)); + struct task sibling = {.shared_fs = parent->shared_fs}; + ++sibling.shared_fs->references; + parent->cap_effective = 0; + assert(syscall_unshare(parent, CLONE_NEWUTS) == -LINUX_EPERM); + parent->cap_effective = admin; + uts_namespace_budget = 0; + assert(syscall_unshare(parent, CLONE_NEWUTS) == -LINUX_ENOMEM); + uts_namespace_budget = -1; + unpublished_child = child; + mount_budget = 1; + assert(syscall_unshare(parent, CLONE_NEWUTS | CLONE_NEWNS) == -LINUX_ENOMEM); + mount_budget = -1; + assert(parent->uts_ns == source && source->references == 1); + assert(parent->shared_fs == sibling.shared_fs && parent->shared_fs->references == 2); + assert(!syscall_unshare(parent, CLONE_NEWUTS)); + assert(parent->uts_ns != source && !strcmp(parent->uts_ns->hostname, "shared")); + assert(parent->shared_fs == sibling.shared_fs && parent->shared_fs->references == 2); + sched_task_fs_release(&sibling); + puts("PASS UTS fork sharing, clone/clone3 ownership, unshare and atomic rollback"); +} + +/** @brief Check authenticated UTS handles, dual authority and retained shared FS state. */ +static void check_uts_setns(struct task *task) +{ + struct user_namespace *owner = NULL; + struct uts_namespace *target = NULL; + assert(!user_namespace_create(task, &owner)); + assert(!uts_namespace_create(task->uts_ns, owner, &target)); + assert(!nsfs_create_uts_path(target, &handle_file.path_ref)); + assert(!nsfs_create_uts_path(NULL, &ordinary_file.path_ref)); + uts_namespace_put(target); + assert(target->references == 1 && owner->references == 2); + assert(syscall_setns(task, 3, CLONE_NEWNS) == -LINUX_EINVAL); + handle_file.flags = TASK_FILE_FLAG_PATH; + assert(syscall_setns(task, 3, CLONE_NEWUTS) == -LINUX_EBADF); + handle_file.flags = 0; + struct uts_namespace *old = task->uts_ns; + task->cap_effective = 0; + assert(syscall_setns(task, 3, CLONE_NEWUTS) == -LINUX_EPERM); + assert(task->uts_ns == old && target->references == 1); + task->cap_effective = UINT64_C(1) << CAP_SYS_ADMIN; + assert(!task_promote_shared(task, CLONE_FS)); + struct task sibling = {.shared_fs = task->shared_fs}; + ++sibling.shared_fs->references; + assert(!syscall_setns(task, 3, 0)); + assert(task->uts_ns == target && target->references == 2); + assert(task->shared_fs == sibling.shared_fs && task->shared_fs->references == 2); + assert(!syscall_setns(task, 3, CLONE_NEWUTS) && target->references == 2); + task->user_ns = owner; + assert(syscall_setns(task, 4, CLONE_NEWUTS) == -LINUX_EPERM); + task->cap_effective = 0; + assert(syscall_setns(task, 3, CLONE_NEWUTS) == -LINUX_EPERM); + task->cap_effective = UINT64_C(1) << CAP_SYS_ADMIN; + assert(!syscall_setns(task, 3, CLONE_NEWUTS)); + task->user_ns = NULL; + user_namespace_put(owner); + vfs_path_put(&handle_file.path_ref); + while (vfs_reclaim_mounts(16)) {} + assert(target->references == 1 && target->user_ns->references == 1); + assert(!syscall_setns(task, 4, CLONE_NEWUTS) && !task->uts_ns); + assert(task->shared_fs == sibling.shared_fs); + vfs_path_put(&ordinary_file.path_ref); + sched_task_fs_release(&sibling); + puts("PASS UTS setns typed handles, local/owner authority, shared FS and held lifetime"); +} + int main(void) { struct sched_task_object parent_object = {0}, child_object = {0}; @@ -601,6 +736,8 @@ int main(void) check_user_namespaces(parent, child, user); check_user_setns(parent, child); check_mount_user_setns(parent); + check_uts_creation(parent, child, user); + check_uts_setns(parent); sched_task_fs_release(parent); /* Retiring nsfs captures can enqueue their graphs and backing mounts. */ while (vfs_reclaim_mounts(16)) {} diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index 846abbfb..1170d999 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -4,6 +4,7 @@ #include #include #include +#include #include "../../include/reliefnt/audio.h" #include #include @@ -290,8 +291,6 @@ static const struct reliefos_system_info fixture_system = { const struct reliefos_system_info *reliefnt_system_info(void) { return &fixture_system; } const char *userland_boot_cmdline(void) { return ""; } -void linux_uts_names(char host[65], char domain[65]) -{ strcpy(host, "fixture-host"); strcpy(domain, "(none)"); } #ifndef TEST_REAL_INVENTORY int cpu_inventory_read(uint64_t o,void *b,uint32_t n,uint32_t *r) { (void)o;(void)b;(void)n;*r=0;return 0; } int sysfs_lookup(const char *p,struct storage_node *n) { (void)p;(void)n;return -2; } @@ -802,6 +801,8 @@ static void test_proc_mount_namespace_handles(void) assert(entry.type == RELIEFOS_FS_TYPE_SYMLINK && !strcmp(entry.name, "mnt")); assert(proc_readdir("/proc/43/ns", &cursor, &entry) == 1); assert(entry.type == RELIEFOS_FS_TYPE_SYMLINK && !strcmp(entry.name, "user")); + assert(proc_readdir("/proc/43/ns", &cursor, &entry) == 1); + assert(entry.type == RELIEFOS_FS_TYPE_SYMLINK && !strcmp(entry.name, "uts")); assert(!proc_readdir("/proc/43/ns", &cursor, &entry)); cursor = 0; bool listed = false; @@ -879,7 +880,50 @@ static void test_proc_mount_namespace_handles(void) vfs_path_put(&user); vfs_path_put(&initial_user); + struct vfs_path uts = {0}, initial_uts = {0}, uts_link = {0}; + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/uts", VFS_LOOKUP_FOLLOW, &initial_uts)); + assert(!vfs_path_stat(&initial_uts, &st) && st.st_dev == device && st.st_ino != initial_user_ino); + uint64_t initial_uts_ino = st.st_ino; + assert(!uts_namespace_create(NULL, NULL, &foreign.uts_ns)); + struct uts_namespace *uts_scope = foreign.uts_ns; + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/uts", 0, &uts_link)); + current.cap_effective = 0; + assert(vfs_path_readlink(&uts_link, label, sizeof(label), &length) == -EACCES); + assert(vfs_path_lookup(&ns, &root, &root, "43/ns/uts", VFS_LOOKUP_FOLLOW, &uts) == -EACCES); + current.cap_effective = UINT64_C(1) << CAP_SYS_PTRACE; + proc_allocation_budget = 0; + assert(vfs_path_lookup(&ns, &root, &root, "43/ns/uts", VFS_LOOKUP_FOLLOW, &uts) == -ENOMEM); + proc_allocation_budget = -1; + assert(!uts.mount && uts_scope->references == 1); + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/uts", VFS_LOOKUP_FOLLOW, &uts)); + assert(nsfs_path_type(&uts) == CLONE_NEWUTS && uts_scope->references == 2); + assert(!vfs_path_stat(&uts, &st) && st.st_mode == (LINUX_S_IFREG | 0444)); + uint64_t uts_ino = st.st_ino; + assert(uts_ino != initial_uts_ino && uts_ino != user_ino && uts_ino != ino); + snprintf(label, sizeof(label), "uts:[%" PRIu64 "]", uts_ino); + char uts_label[64] = {0}; + count = proc_readlink("/proc/43/ns/uts", uts_label, sizeof(uts_label)); + assert(count == (int)strlen(label) && !memcmp(uts_label, label, count)); + const char *const uts_aliases[] = {"self/ns/uts", "thread-self/ns/uts", "42/task/42/ns/uts"}; + for (unsigned i = 0; i < 3; ++i) { + assert(!vfs_path_lookup(&ns, &root, &root, uts_aliases[i], VFS_LOOKUP_FOLLOW, &fresh)); + assert(!vfs_path_stat(&fresh, &st) && st.st_ino == initial_uts_ino); + vfs_path_put(&fresh); + } + foreign.uts_ns = NULL; + uts_namespace_put(uts_scope); + assert(uts_scope->references == 1); sched_task_identity_detach(&foreign); /* Retire the identity, reusing PID 43. */ + assert(vfs_path_readlink(&uts_link, uts_label, sizeof(uts_label), &length) == -ENOENT); + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/uts", VFS_LOOKUP_FOLLOW, &fresh)); + assert(!vfs_path_stat(&fresh, &st) && st.st_ino == initial_uts_ino); + vfs_path_put(&fresh); + assert(!vfs_path_stat(&uts, &st) && st.st_ino == uts_ino); + assert(!vfs_path_format_link(&ns, &root, &uts, uts_label, sizeof(uts_label))); + assert(!strcmp(uts_label, label)); + vfs_path_put(&uts); + vfs_path_put(&initial_uts); + vfs_path_put(&uts_link); assert(vfs_path_readlink(&link, label, sizeof(label), &length) == -ENOENT); assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/mnt", VFS_LOOKUP_FOLLOW, &fresh)); assert(!vfs_path_stat(&fresh, &st) && st.st_ino == current_ino); @@ -903,7 +947,91 @@ static void test_proc_mount_namespace_handles(void) assert(!vfs_reclaim_pending()); assert(!vfs_namespace_destroy(&ns)); assert(proc_allocations == before); - puts("PASS proc namespace aliases, permissions, stable identity and PID reuse"); + puts("PASS proc mount/user/UTS handles, aliases, permissions, OOM, stable identity and PID reuse"); +} + +/** @brief Exercise live UTS sysctl writes, scoped names and mount restrictions. */ +static void test_proc_uts_controls(void) +{ + unsigned before = proc_allocations; + uint32_t old_euid = current.euid, old_fsuid = current.fsuid; + uint64_t old_caps = current.cap_effective; + current.euid = current.fsuid = 0; + current.cap_effective = UINT64_MAX; + struct vfs_namespace ns = {0}; + struct vfs_mount *mount = NULL; + struct vfs_path root = {0}, host = {0}, domain = {0}; + struct vfs_open_file *opened = NULL; + assert(!proc_create_vfs_mount(&mount) && !vfs_namespace_init(&ns, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns, &root)); + assert(!vfs_path_lookup(&ns, &root, &root, "sys/kernel/hostname", 0, &host)); + assert(!vfs_path_lookup(&ns, &root, &root, "sys/kernel/domainname", 0, &domain)); + struct linux_stat_abi st; + assert(!vfs_path_stat(&host, &st) && st.st_mode == (LINUX_S_IFREG | 0644)); + assert(!st.st_uid && !st.st_gid); + current.fsuid = 1000; + current.cap_effective = 0; + assert(!fs_permissions_check_path(¤t, &host, FS_ACCESS_WRITE, false)); + assert(!fs_permissions_check_path(¤t, &domain, FS_ACCESS_READ | FS_ACCESS_WRITE, false)); + assert(fs_permissions_check_path(¤t, &host, FS_ACCESS_EXEC, false) == -EACCES); + current.fsuid = 0; + current.euid = 1000; + current.cap_effective = UINT64_MAX; + assert(fs_permissions_check_path(¤t, &host, FS_ACCESS_WRITE, false) == -EACCES); + assert(!fs_permissions_check_path(¤t, &host, FS_ACCESS_READ, false)); + current.euid = 0; + assert(!vfs_file_open(&host, LINUX_O_RDWR, &opened) && !opened); + assert(!vfs_path_truncate(&host, 0)); + assert(vfs_path_truncate(&host, 1) == -EINVAL); + uint32_t written, got; + char text[80] = {0}; + assert(!vfs_path_write(&host, 0, "parent-host\nignored", 19, &written) && written == 19); + assert(!vfs_path_read(&host, 0, text, sizeof(text), &got) && got == 12); + assert(!memcmp(text, "parent-host\n", got)); + assert(!uts_namespace_create(NULL, NULL, ¤t.uts_ns)); + assert(!vfs_path_write(&host, 0, "child", 5, &written) && written == 5); + assert(!vfs_path_write(&host, 5, "-host\n", 6, &written) && written == 6); + assert(!vfs_path_read(&host, 0, text, sizeof(text), &got) && got == 11); + assert(!memcmp(text, "child-host\n", got)); + assert(!vfs_path_write(&host, 20, "ignored", 7, &written) && written == 7); + assert(!vfs_path_write(&domain, 0, "domain\0ignored", 14, &written) && written == 14); + char hostname[65], domainname[65]; + linux_uts_names(hostname, domainname); + assert(!strcmp(hostname, "child-host") && !strcmp(domainname, "domain")); + memset(text, 'x', sizeof(text)); + assert(!vfs_path_write(&host, 0, text, sizeof(text), &written) && written == sizeof(text)); + linux_uts_names(hostname, domainname); + assert(strlen(hostname) == 64 && hostname[63] == 'x'); + assert(!vfs_path_write(&host, 0, NULL, 0, &written) && !written); + linux_uts_names(hostname, domainname); + assert(strlen(hostname) == 64); + assert(!vfs_path_write(&host, 0, "\n", 1, &written) && written == 1); + linux_uts_names(hostname, domainname); + assert(!hostname[0]); + + /* UTS sysctl DAC uses global effective root even inside a child scope. */ + current.euid = 1000; + assert(vfs_path_write(&host, 0, "denied", 6, &written) == -EACCES && !written); + assert(vfs_file_open(&host, LINUX_O_WRONLY, &opened) == -EACCES && !opened); + current.euid = 0; + assert(!vfs_path_bind_remount(&root, MS_RDONLY)); + assert(vfs_path_write(&host, 0, "readonly", 8, &written) == -EROFS && !written); + assert(vfs_path_truncate(&host, 0) == -EROFS); + assert(!vfs_path_bind_remount(&root, 0)); + uts_namespace_put(current.uts_ns); + current.uts_ns = NULL; + linux_uts_names(hostname, domainname); + assert(!strcmp(hostname, "parent-host")); + assert(!linux_uts_set("fixture-host", 12, 0)); + vfs_path_put(&host); + vfs_path_put(&domain); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns) && proc_allocations == before); + current.euid = old_euid; + current.fsuid = old_fsuid; + current.cap_effective = old_caps; + puts("PASS live UTS sysctl scopes, string bounds, authorization and readonly views"); } /** @brief Verify stable boot identity, fresh UUIDs and entropy retry via proc mounts. */ @@ -1116,6 +1244,8 @@ static void test_proc_user_namespace_controls(void) int main(void) { + test_proc_uts_controls(); + assert(!linux_uts_set("fixture-host", 12, 0)); test_proc_random_uuid(); test_proc_fd_metadata(); test_proc_fd_object_link(); diff --git a/tools/tests/rootfs_uts_test.c b/tools/tests/rootfs_uts_test.c index 92e9de4a..8068727f 100644 --- a/tools/tests/rootfs_uts_test.c +++ b/tools/tests/rootfs_uts_test.c @@ -1,8 +1,13 @@ #include #include #include +#include #include "../../kernel/init/uts.c" static unsigned locked; +static struct task *current; +struct task *sched_current_task(void) { return current; } +void *kernel_malloc(size_t size) { assert(!locked); return malloc(size); } +void kernel_free(void *memory) { assert(!locked); free(memory); } void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) { (void)lock; assert(!locked); locked=1; *flags=0; } void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) From b1db89b57529828e8f2c6a7f7966b8a6ddb75d34 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 03:47:01 +0800 Subject: [PATCH 68/97] feat(netlink): provide receive packet info and membership queries --- .../LC_MESSAGES/userspace-api/descriptors.po | 6 ++ .../LC_MESSAGES/userspace-api/descriptors.po | 6 ++ Documentation/userspace-api/descriptors.rst | 12 +++ include/reliefnt/netlink.h | 3 + include/uapi/linux/netlink.h | 4 + kernel/syscall/ipc/socket.c | 39 +++++--- net/socket/netlink.c | 83 ++++++++++++++--- tools/tests/ipv6_control_test.c | 67 ++++++++++++++ tools/tests/ipv6_vector_stubs.c | 1 + tools/tests/socket_batch_abi_test.c | 84 +++++++++++++++++- tools/tests/socket_batch_unix_test.c | 88 +++++++++++++++++-- .../task8_host_stubs/descriptor_unreached.c | 1 + ...-collector-green-2-socket_dispatch_stubs.c | 2 +- tools/tests/task8_socket_receive_test.c | 38 ++++++++ 14 files changed, 402 insertions(+), 32 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index 2cadaf94..31790342 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -419,3 +419,9 @@ msgstr "At startup, detected ISO9660 discs are tried at ``/media/cdrom0``, ``/me msgid "``flock`` 支持普通文件和实际打开的设备节点,包括 ``/dev/console``。 设备描述符以只读、只写或读写方式打开时,均可取得共享锁或独占锁。锁使用实际 打开的设备 inode 身份,硬链接和 bind 别名共享锁,独立创建的设备节点及独立 文件系统实例各自持锁。``dup`` 共享锁所有权,解锁或最后一个打开文件描述 引用关闭时释放锁。引导期无路径设备保留固有节点身份。``O_PATH`` 和匿名 eventfd 描述符返回 ``EBADF``。" msgstr "``flock`` supports regular files and opened device nodes, including ``/dev/console``. Read-only, write-only and read/write device descriptors can acquire shared or exclusive locks. Locks use the actual opened device inode identity. Hardlink and bind aliases share locks, while separately created device nodes and independent filesystem instances have independent locks. ``dup`` shares lock ownership. Unlocking or closing the final open-file-description reference releases the lock. Pathless bootstrap devices retain their intrinsic node identity. ``O_PATH`` and anonymous eventfd descriptors return ``EBADF``." + +msgid "``AF_NETLINK`` 的 ``SOL_NETLINK/NETLINK_PKTINFO`` 使用原生 32 位整数, 默认关闭,设置非零值启用;不足一个整数的设置将其关闭,查询至少需要一个整数。 状态由共享 OFD 持有。启用后,``recvmsg`` 在凭据之前返回 ``SOL_NETLINK`` 的 ``NETLINK_PKTINFO`` 控制消息,载荷 ``nl_pktinfo.group`` 是从 1 开始的目标组号, 单播为 0。省略源地址输出时仍返回该元数据。控制缓冲区不足时返回可容纳的部分并 设置 ``MSG_CTRUNC``,输出页准备失败时尚未接收数据报。" +msgstr "``AF_NETLINK`` ``SOL_NETLINK/NETLINK_PKTINFO`` uses a native 32-bit integer, is disabled by default and accepts any nonzero value to enable it. A setter shorter than one integer disables it, and a getter requires at least one integer. Shared OFDs retain the setting. When enabled, ``recvmsg`` returns a ``SOL_NETLINK`` ``NETLINK_PKTINFO`` control message before credentials. Its ``nl_pktinfo.group`` payload is the 1-based destination group number, or 0 for unicast. This metadata also appears when source-address output is omitted. A short control buffer receives the portion that fits and sets ``MSG_CTRUNC``. Output-page preparation failures occur before receiving the datagram." + +msgid "``NETLINK_LIST_MEMBERSHIPS`` 查询当前组成员位图。尚未初始化成员存储时, 返回长度 0;成功加入或退出组后保留一个 32 位字,覆盖本内核支持的 32 个组号, 最后一个组退出后仍可查询全零位图。容量不足一个字时不复制数据,长度始终报告 所需字节数,容量为 0 时可探测长度。加入和退出继续使用既有协议组与权限检查。" +msgstr "``NETLINK_LIST_MEMBERSHIPS`` queries the current membership bitmap. Before membership storage is initialized, its returned length is 0. A successful join or leave retains one 32-bit word covering this kernel's 32 supported group indices. Leaving the last group preserves an all-zero queryable bitmap. Capacities shorter than one word copy no data. The length always reports the required bytes, and zero capacity probes that length. Joining and leaving retain the existing protocol-group and permission checks." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index 54758794..e666bab9 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -362,3 +362,9 @@ msgstr "起動時、検出された ISO9660 ディスクのマウントを ``/me msgid "``flock`` 支持普通文件和实际打开的设备节点,包括 ``/dev/console``。 设备描述符以只读、只写或读写方式打开时,均可取得共享锁或独占锁。锁使用实际 打开的设备 inode 身份,硬链接和 bind 别名共享锁,独立创建的设备节点及独立 文件系统实例各自持锁。``dup`` 共享锁所有权,解锁或最后一个打开文件描述 引用关闭时释放锁。引导期无路径设备保留固有节点身份。``O_PATH`` 和匿名 eventfd 描述符返回 ``EBADF``。" msgstr "``flock`` は通常ファイルと、``/dev/console`` を含む開かれたデバイスノードに対応します。読み取り専用、書き込み専用、読み書きのデバイス記述子はいずれも共有ロックと排他ロックを取得できます。ロックは実際に開いたデバイス inode の識別情報を使用します。ハードリンクと bind の別名はロックを共有し、個別に作成したデバイスノードと独立したファイルシステムのインスタンスは独立したロックを持ちます。``dup`` はロックの所有権を共有します。明示的な解除または開いたファイル記述への最後の参照を閉じるとロックを解放します。起動時のパスを持たないデバイスは固有のノード識別情報を保持します。``O_PATH`` と匿名 eventfd 記述子は ``EBADF`` を返します。" + +msgid "``AF_NETLINK`` 的 ``SOL_NETLINK/NETLINK_PKTINFO`` 使用原生 32 位整数, 默认关闭,设置非零值启用;不足一个整数的设置将其关闭,查询至少需要一个整数。 状态由共享 OFD 持有。启用后,``recvmsg`` 在凭据之前返回 ``SOL_NETLINK`` 的 ``NETLINK_PKTINFO`` 控制消息,载荷 ``nl_pktinfo.group`` 是从 1 开始的目标组号, 单播为 0。省略源地址输出时仍返回该元数据。控制缓冲区不足时返回可容纳的部分并 设置 ``MSG_CTRUNC``,输出页准备失败时尚未接收数据报。" +msgstr "``AF_NETLINK`` の ``SOL_NETLINK/NETLINK_PKTINFO`` はネイティブの 32 ビット整数を使い、既定では無効で、非ゼロ値で有効になります。整数より短い設定は無効化し、取得には整数一つ分以上が必要です。設定は共有 OFD が保持します。有効時の ``recvmsg`` は資格情報より前に ``SOL_NETLINK`` の ``NETLINK_PKTINFO`` 制御メッセージを返します。``nl_pktinfo.group`` は 1 始まりの宛先グループ番号で、ユニキャストでは 0 です。送信元アドレスの出力を省略しても返されます。制御バッファが短い場合は収まる部分を返し、``MSG_CTRUNC`` を設定します。出力ページの準備に失敗した時点では、データグラムをまだ受信していません。" + +msgid "``NETLINK_LIST_MEMBERSHIPS`` 查询当前组成员位图。尚未初始化成员存储时, 返回长度 0;成功加入或退出组后保留一个 32 位字,覆盖本内核支持的 32 个组号, 最后一个组退出后仍可查询全零位图。容量不足一个字时不复制数据,长度始终报告 所需字节数,容量为 0 时可探测长度。加入和退出继续使用既有协议组与权限检查。" +msgstr "``NETLINK_LIST_MEMBERSHIPS`` は現在の所属グループのビットマップを取得します。所属情報の格納領域が未初期化なら長さ 0 を返します。参加または離脱に成功すると、本カーネルの 32 個のグループ番号を表す 32 ビットのワード一つを保持します。最後のグループから離脱した後も、すべてゼロのビットマップを取得できます。容量が一ワード未満ならデータをコピーしません。長さは常に必要バイト数を示し、容量 0 でその長さを調べられます。参加と離脱には既存のプロトコルグループおよび権限検査が適用されます。" diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index fffd3054..f79b5805 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -153,6 +153,18 @@ UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``a 按可用容量返回部分消息并设置 ``MSG_CTRUNC``。交换页等待后的重试保留已接收 数据包及其时间戳选项状态。 +``AF_NETLINK`` 的 ``SOL_NETLINK/NETLINK_PKTINFO`` 使用原生 32 位整数, +默认关闭,设置非零值启用;不足一个整数的设置将其关闭,查询至少需要一个整数。 +状态由共享 OFD 持有。启用后,``recvmsg`` 在凭据之前返回 ``SOL_NETLINK`` 的 +``NETLINK_PKTINFO`` 控制消息,载荷 ``nl_pktinfo.group`` 是从 1 开始的目标组号, +单播为 0。省略源地址输出时仍返回该元数据。控制缓冲区不足时返回可容纳的部分并 +设置 ``MSG_CTRUNC``,输出页准备失败时尚未接收数据报。 + +``NETLINK_LIST_MEMBERSHIPS`` 查询当前组成员位图。尚未初始化成员存储时, +返回长度 0;成功加入或退出组后保留一个 32 位字,覆盖本内核支持的 32 个组号, +最后一个组退出后仍可查询全零位图。容量不足一个字时不复制数据,长度始终报告 +所需字节数,容量为 0 时可探测长度。加入和退出继续使用既有协议组与权限检查。 + ``AF_NETLINK`` 的 ``SO_ATTACH_FILTER`` 接受最多 4096 条经典 BPF 指令, ``SO_DETACH_FILTER`` 移除当前过滤器。过滤器在单播回复和多播通知入队前执行, 零返回值丢弃数据报,其他返回值限制接收长度。报文整数按网络字节序读取, diff --git a/include/reliefnt/netlink.h b/include/reliefnt/netlink.h index f520cbf8..b6458615 100644 --- a/include/reliefnt/netlink.h +++ b/include/reliefnt/netlink.h @@ -35,6 +35,9 @@ int task_netlink_recv_staged(struct task_file *file,void *data,uint32_t length,u /** @brief Check whether the recipient requested SCM_CREDENTIALS. * @param file Retained socket description. @return True when SO_PASSCRED is enabled. */ bool task_netlink_passcred(const struct task_file *file); +/** @brief Check whether the recipient requested SOL_NETLINK/NETLINK_PKTINFO. + * @param file Retained socket description. @return True when packet info is enabled. */ +bool task_netlink_pktinfo(const struct task_file *file); /* Publish KOBJ_CHANGE to group 1. All input is kernel-owned and is copied * before return. properties contains NUL-terminated environment entries. */ void netlink_uevent_change(const char *devpath, const char *subsystem, diff --git a/include/uapi/linux/netlink.h b/include/uapi/linux/netlink.h index dbfdbf91..57d39a35 100644 --- a/include/uapi/linux/netlink.h +++ b/include/uapi/linux/netlink.h @@ -10,7 +10,10 @@ #define SOL_NETLINK 270 #define NETLINK_ADD_MEMBERSHIP 1 #define NETLINK_DROP_MEMBERSHIP 2 +#define NETLINK_PKTINFO 3 +#define NETLINK_LIST_MEMBERSHIPS 9 struct sockaddr_nl { sa_family_t nl_family; uint16_t nl_pad; uint32_t nl_pid, nl_groups; }; +struct nl_pktinfo { uint32_t group; }; struct nlmsghdr { uint32_t nlmsg_len; uint16_t nlmsg_type, nlmsg_flags; uint32_t nlmsg_seq, nlmsg_pid; }; struct nlmsgerr { int32_t error; struct nlmsghdr msg; }; #define NLMSG_ALIGN(n) (((n) + 3u) & ~3u) @@ -34,5 +37,6 @@ struct nlmsgerr { int32_t error; struct nlmsghdr msg; }; #define NLM_F_CREATE 0x400 #define NLM_F_APPEND 0x800 _Static_assert(sizeof(struct sockaddr_nl)==12, "Linux sockaddr_nl"); +_Static_assert(sizeof(struct nl_pktinfo)==4, "Linux nl_pktinfo"); _Static_assert(sizeof(struct nlmsghdr)==16, "Linux nlmsghdr"); #endif diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 08466e23..7196e788 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -2574,6 +2574,8 @@ complete_message: ; * @note Netlink SO_PASSCRED reflects the sender metadata of the dequeued * datagram for both kernel and userspace events, mapping global UID/GID into * the receiving caller's user namespace at final control-message copyout. + * NETLINK_PKTINFO precedes credentials and reports the destination group index, + * including zero for unicast, independently of source-address output. */ static int64_t inet_message(struct task_file *file, uint64_t user_header, struct msghdr message, uint32_t flags, bool receiving, @@ -2582,6 +2584,7 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, bool packet = file->kind == TASK_FILE_KIND_PACKET; bool netlink = file->kind == TASK_FILE_KIND_NETLINK; bool netlink_passcred = receiving && netlink && task_netlink_passcred(file); + bool netlink_pktinfo = receiving && netlink && task_netlink_pktinfo(file); bool udp = file->kind == TASK_FILE_KIND_UDP; bool datagram = udp || packet || netlink; if (flags & ~(MSG_DONTWAIT | MSG_NOSIGNAL | MSG_PEEK | MSG_TRUNC | MSG_WAITALL | MSG_CMSG_CLOEXEC)) @@ -2611,8 +2614,9 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, if (prep) return prep; if (copied && !user_range_writable((uintptr_t)message.msg_name, copied)) return -LINUX_EFAULT; } - if (receiving && (udp || packet || netlink_passcred) && message.msg_controllen && message.msg_control) { - uint64_t limit = netlink_passcred ? CMSG_SPACE(sizeof(struct ucred)) : 88; + if (receiving && (udp || packet || netlink_passcred || netlink_pktinfo) && message.msg_controllen && message.msg_control) { + uint64_t limit = netlink ? (netlink_passcred ? CMSG_SPACE(sizeof(struct ucred)) : 0) + + (netlink_pktinfo ? CMSG_SPACE(sizeof(struct nl_pktinfo)) : 0) : 88; uint64_t copied = message.msg_controllen < limit ? message.msg_controllen : limit; int prep = socket_user_prepare(sched_current_task(), (uintptr_t)message.msg_control, copied, true); if (prep) return prep; @@ -2680,7 +2684,7 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, struct net_udp_rx_info udp_info = {0}; struct ucred netlink_credentials = {0}; if (netlink) ret = task_netlink_recv_staged(file, payload, output_size, - (flags & ~MSG_CMSG_CLOEXEC) | MSG_TRUNC, message.msg_name ? &source : NULL, + (flags & ~MSG_CMSG_CLOEXEC) | MSG_TRUNC, (message.msg_name || netlink_pktinfo) ? &source : NULL, &source_length, netlink_passcred ? &netlink_credentials : NULL); #ifdef CONFIG_SWAP else if(packet)ret=task_packet_recv_ex(file,payload,output_size,(flags & ~MSG_CMSG_CLOEXEC)|MSG_TRUNC, @@ -2710,21 +2714,28 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, } output->flags = datagram && (uint64_t)ret > size ? MSG_TRUNC : 0; uint64_t used = 0; - if (netlink_passcred) { + if (netlink_pktinfo || netlink_passcred) { + const struct sockaddr_nl *from = (const void *)&source; + const struct nl_pktinfo pktinfo = {.group = (uint32_t)__builtin_ffs((int)from->nl_groups)}; struct ucred credentials = socket_user_credentials(sched_current_task(), netlink_credentials); - const uint64_t available = message.msg_control ? message.msg_controllen : 0; - if (available < CMSG_LEN(sizeof(netlink_credentials))) - output->flags |= MSG_CTRUNC; - if (available >= CMSG_LEN(0)) { + for (unsigned which = 0; which < 2; ++which) { + if (!(which == 0 ? netlink_pktinfo : netlink_passcred)) continue; + const void *value = which == 0 ? (const void *)&pktinfo : (const void *)&credentials; + uint64_t value_size = which == 0 ? sizeof(pktinfo) : sizeof(credentials); + const uint64_t available = message.msg_control && message.msg_controllen > used ? + message.msg_controllen - used : 0; + if (available < CMSG_LEN(value_size)) output->flags |= MSG_CTRUNC; + if (available < CMSG_LEN(0)) continue; uint64_t copy = available - CMSG_LEN(0); - if (copy > sizeof(netlink_credentials)) - copy = sizeof(netlink_credentials); + if (copy > value_size) copy = value_size; const struct cmsghdr header = { - .cmsg_len = CMSG_LEN(copy), .cmsg_level = SOL_SOCKET, .cmsg_type = SCM_CREDENTIALS, + .cmsg_len = CMSG_LEN(copy), .cmsg_level = which == 0 ? SOL_NETLINK : SOL_SOCKET, + .cmsg_type = which == 0 ? NETLINK_PKTINFO : SCM_CREDENTIALS, }; - __builtin_memcpy(message.msg_control, &header, sizeof(header)); - __builtin_memcpy((uint8_t *)message.msg_control + CMSG_LEN(0), &credentials, copy); - used = CMSG_SPACE(copy) < available ? CMSG_SPACE(copy) : available; + uint8_t *control = (uint8_t *)message.msg_control + used; + __builtin_memcpy(control, &header, sizeof(header)); + __builtin_memcpy(control + CMSG_LEN(0), value, copy); + used += CMSG_SPACE(copy) < available ? CMSG_SPACE(copy) : available; } } if ((udp || packet) && (udp_info.pktinfo || udp_info.hoplimit || udp_info.old_hoplimit)) { diff --git a/net/socket/netlink.c b/net/socket/netlink.c index df757396..e4798bcf 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -45,6 +45,7 @@ struct netlink_socket { uint32_t port, queued_bytes, groups; int type, protocol; bool bound, connected, overrun, passcred; + bool pktinfo, memberships_initialized; bool reuse_address; /* Socket option state; port ownership is unchanged. */ }; struct nl_builder { @@ -399,7 +400,7 @@ static int nl_initial_snapshot(void) nl_snapshot_ready=true; return 0; } -/** @brief Change the socket's supported multicast membership transactionally. +/** @brief Change membership transactionally, retaining an initialized query bitmap. * @param s Subscriber. @param groups New Linux group mask. @return Zero or errno. */ static int nl_set_groups(struct netlink_socket *s, uint32_t groups) { @@ -407,11 +408,13 @@ static int nl_set_groups(struct netlink_socket *s, uint32_t groups) if (groups & ~NL_UEVENT_GROUPS) return -LINUX_EOPNOTSUPP; s->groups = groups; + s->memberships_initialized |= groups != 0; return 0; } if (groups & ~NL_SUPPORTED_GROUPS) return -LINUX_EOPNOTSUPP; if (groups) { int rc=nl_initial_snapshot(); if (rc) return rc; } s->groups=groups; + s->memberships_initialized |= groups != 0; if (!groups) { for (struct netlink_socket *it=netlink_sockets;it;it=it->next) if (it->protocol == NETLINK_ROUTE && it->groups) return 0; @@ -1212,6 +1215,14 @@ bool task_netlink_passcred(const struct task_file *file) return s && s->passcred; } +/** @brief Check the recipient's NETLINK_PKTINFO setting under execution ownership. + * @param file Retained socket description. @return True when packet info is enabled. */ +bool task_netlink_pktinfo(const struct task_file *file) +{ + const struct netlink_socket *s = nl_socket(file); + return s && s->pktinfo; +} + /** @brief Return current socket readiness under execution ownership. * @param file Retained OFD. @param events Requested bits. @return Ready bits or POLLNVAL. */ short task_netlink_poll(const struct task_file *file,short events) @@ -1270,6 +1281,64 @@ static int nl_export_address(struct task *task,uint64_t address,uint64_t length, *(uint32_t *)(uintptr_t)length=sizeof(*value); return 0; } +/** @brief Set netlink receive metadata or export the supported membership bitmap. + * @param task Current caller under execution ownership. @param s Socket state. + * @param setting Select setsockopt. @param option SOL_NETLINK option number. + * @param address User option value. @param length Value size or user socklen pointer. + * @return Zero, negative errno or a user-memory preparation retry marker. + * @note Short packet-info setters disable the option. Getters require a full int. + * Membership queries copy complete words and report the required bitmap size. + */ +static int nl_protocol_option(struct task *task, struct netlink_socket *s, bool setting, + uint64_t option, uint64_t address, uint64_t length) +{ + if (setting) { + if ((int32_t)length < 0) return -LINUX_EINVAL; + if (option == NETLINK_PKTINFO) { + int32_t enable = 0; + if (length >= sizeof(enable)) { + int rc = socket_user_import(task, address, &enable, sizeof(enable)); + if (rc) return rc; + } + s->pktinfo = enable != 0; + return 0; + } + if (option != NETLINK_ADD_MEMBERSHIP && option != NETLINK_DROP_MEMBERSHIP) + return -LINUX_ENOPROTOOPT; + if (length < sizeof(uint32_t)) return -LINUX_EINVAL; + uint32_t group; + int rc = socket_user_import(task, address, &group, sizeof(group)); + if (rc) return rc; + if (!group || group > 32) return -LINUX_EINVAL; + uint32_t mask = 1u << (group - 1); + if (!(mask & (s->protocol == NETLINK_ROUTE ? NL_SUPPORTED_GROUPS : NL_UEVENT_GROUPS))) + return -LINUX_EOPNOTSUPP; + rc = nl_set_groups(s, option == NETLINK_ADD_MEMBERSHIP ? s->groups | mask : s->groups & ~mask); + if (!rc) s->memberships_initialized = true; + return rc; + } + uint32_t capacity; + int rc = socket_user_length(task, length, &capacity); + if (rc) return rc; + if ((int32_t)capacity < 0) return -LINUX_EINVAL; + uint32_t value, copied, required; + if (option == NETLINK_PKTINFO) { + if (capacity < sizeof(value)) return -LINUX_EINVAL; + value = s->pktinfo; + copied = required = sizeof(value); + } else if (option == NETLINK_LIST_MEMBERSHIPS) { + value = s->groups; + required = s->memberships_initialized ? sizeof(value) : 0; + copied = capacity >= required ? required : 0; + } else return -LINUX_ENOPROTOOPT; + rc = socket_user_prepare(task, address, copied, true); + if (rc) return rc; + if (copied && !user_range_writable(address, copied)) return -LINUX_EFAULT; + if (copied) __builtin_memcpy((void *)(uintptr_t)address, &value, copied); + *(uint32_t *)(uintptr_t)length = required; + return 0; +} + /** @brief Dispatch socket creation, bind, connect, name and supported options. * @param number Native syscall. @param a0 First argument. @param a1 Second argument. * @param a2 Third argument. @param a3 Fourth argument. @param a4 Fifth argument. @@ -1332,16 +1401,8 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, return nl_export_address(task,a1,a2,&result); } if (number==__NR_setsockopt || number==__NR_getsockopt) { - if (a1==SOL_NETLINK && number==__NR_setsockopt && - (a2==NETLINK_ADD_MEMBERSHIP || a2==NETLINK_DROP_MEMBERSHIP)) { - if (a432) return -LINUX_EINVAL; - uint32_t mask=1u<<(group-1); - if (!(mask & (s->protocol == NETLINK_ROUTE ? NL_SUPPORTED_GROUPS : NL_UEVENT_GROUPS))) - return -LINUX_EOPNOTSUPP; - return nl_set_groups(s,a2==NETLINK_ADD_MEMBERSHIP ? s->groups|mask : s->groups&~mask); - } + if (a1 == SOL_NETLINK) + return nl_protocol_option(task, s, number == __NR_setsockopt, a2, a3, a4); if (a1!=SOL_SOCKET) return -LINUX_ENOPROTOOPT; if (number == __NR_setsockopt) { if (a2 == SO_ATTACH_FILTER) { diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 6ff5a58f..2a3b97fb 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -215,6 +215,72 @@ static void check_netlink_reuseaddr(void) puts("PASS route and kobject netlink SO_REUSEADDR: state and exclusive port binding"); } +/** @brief Verify packet-info state and multicast membership query boundaries. */ +static void check_netlink_metadata_options(void) +{ + const unsigned baseline = allocations; + const int protocols[] = {NETLINK_ROUTE, NETLINK_KOBJECT_UEVENT}; + for (unsigned i = 0; i < sizeof(protocols) / sizeof(protocols[0]); ++i) { + int fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[i], 0, 0); + int other = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[i], 0, 0); + assert(fd >= 0 && other >= 0); + int32_t value = -1; + uint32_t size = sizeof(value); + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_PKTINFO, + (uintptr_t)&value, (uintptr_t)&size) && !value && size == sizeof(value)); + value = -7; + assert(!call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_PKTINFO, + (uintptr_t)&value, sizeof(value))); + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_PKTINFO, + (uintptr_t)&value, (uintptr_t)&size) && value == 1); + assert(!call(__NR_getsockopt, other, SOL_NETLINK, NETLINK_PKTINFO, + (uintptr_t)&value, (uintptr_t)&size) && !value); + assert(call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_PKTINFO, 0, sizeof(value)) == -LINUX_EFAULT); + assert(call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_PKTINFO, 0, UINT32_MAX) == -LINUX_EINVAL); + size = sizeof(value) - 1; + assert(call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_PKTINFO, + (uintptr_t)&value, (uintptr_t)&size) == -LINUX_EINVAL); + assert(!call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_PKTINFO, 0, 1)); + size = sizeof(value); + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_PKTINFO, + (uintptr_t)&value, (uintptr_t)&size) && !value); + + uint32_t groups[2] = {UINT32_MAX, UINT32_MAX}; + size = sizeof(groups); + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, + (uintptr_t)groups, (uintptr_t)&size) && !size && groups[0] == UINT32_MAX); + uint32_t group = i ? 2 : 1; + assert(!call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group))); + for (unsigned capacity = 0; capacity <= sizeof(groups); ++capacity) { + groups[0] = groups[1] = UINT32_MAX; + size = capacity; + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, + (uintptr_t)groups, (uintptr_t)&size) && size == sizeof(uint32_t)); + assert(groups[0] == (capacity >= sizeof(uint32_t) ? 1u << (group - 1) : UINT32_MAX)); + assert(groups[1] == UINT32_MAX); + } + size = 0; + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, + 0, (uintptr_t)&size) && size == sizeof(uint32_t)); + size = sizeof(groups); + assert(call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, + 0, (uintptr_t)&size) == -LINUX_EFAULT); + assert(!call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, + (uintptr_t)&group, sizeof(group))); + size = sizeof(groups); + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, + (uintptr_t)groups, (uintptr_t)&size) && size == sizeof(uint32_t) && !groups[0]); + size = UINT32_MAX; + assert(call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, + (uintptr_t)groups, (uintptr_t)&size) == -LINUX_EINVAL); + task_netlink_release(&files[other]); files[other] = (struct task_file){0}; + task_netlink_release(&files[fd]); files[fd] = (struct task_file){0}; + } + assert(allocations == baseline); + puts("PASS netlink metadata options: per-OFD state, short buffers and membership lifecycle"); +} + /** @brief Route processed device notifications without exposing the kernel group. */ static void check_uevent_userspace_delivery(void) { @@ -450,6 +516,7 @@ int main(void) check_netlink_reuseaddr(); check_uevent_userspace_delivery(); assert(!net_interface_register(2)); + check_netlink_metadata_options(); check_netlink_filter(); net_config.local_ip=0x0a00020f; net_config.subnet_mask=0xffffff00; int fd = (int)call(__NR_socket,AF_NETLINK,SOCK_RAW|SOCK_NONBLOCK,NETLINK_ROUTE,0,0); diff --git a/tools/tests/ipv6_vector_stubs.c b/tools/tests/ipv6_vector_stubs.c index 68c6cafb..f4ddaf59 100644 --- a/tools/tests/ipv6_vector_stubs.c +++ b/tools/tests/ipv6_vector_stubs.c @@ -6,6 +6,7 @@ __attribute__((noreturn)) void task_netlink_recv_staged(void) { __builtin_trap() __attribute__((noreturn)) void task_netlink_send(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_cancel_wait(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_passcred(void) { __builtin_trap(); } +__attribute__((noreturn)) void task_netlink_pktinfo(void) { __builtin_trap(); } __attribute__((noreturn)) void task_packet_recv(void) { __builtin_trap(); } __attribute__((noreturn)) void task_packet_recv_ex(void) { __builtin_trap(); } __attribute__((noreturn)) void task_packet_recv_staged(void) { __builtin_trap(); } diff --git a/tools/tests/socket_batch_abi_test.c b/tools/tests/socket_batch_abi_test.c index 0be905a3..326fb189 100644 --- a/tools/tests/socket_batch_abi_test.c +++ b/tools/tests/socket_batch_abi_test.c @@ -3,6 +3,8 @@ #endif #include #include +#include +#include #include #include #include @@ -94,5 +96,85 @@ static int socket_batch_syscalls(void) } #ifndef SOCKET_BATCH_EMBEDDED -int main(void) { return socket_batch_syscalls(); } +/** @brief Compare netlink metadata options and ancillary truncation with Linux. */ +static int netlink_metadata_syscalls(void) +{ + int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_ROUTE); + MMSG_CHECK(fd >= 0); + int value = -1; + socklen_t size = sizeof(value); + MMSG_CHECK(!getsockopt(fd, SOL_NETLINK, NETLINK_PKTINFO, &value, &size) && !value); + value = -7; + MMSG_CHECK(!setsockopt(fd, SOL_NETLINK, NETLINK_PKTINFO, &value, sizeof(value))); + MMSG_CHECK(!getsockopt(fd, SOL_NETLINK, NETLINK_PKTINFO, &value, &size) && value == 1); + size = sizeof(value) - 1; + MMSG_CHECK(getsockopt(fd, SOL_NETLINK, NETLINK_PKTINFO, &value, &size) == -1 && errno == EINVAL); + MMSG_CHECK(!setsockopt(fd, SOL_NETLINK, NETLINK_PKTINFO, NULL, 1)); + size = sizeof(value); + MMSG_CHECK(!getsockopt(fd, SOL_NETLINK, NETLINK_PKTINFO, &value, &size) && !value); + uint32_t groups[2] = {UINT32_MAX, UINT32_MAX}; + size = sizeof(groups); + MMSG_CHECK(!getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &size) && !size); + value = RTNLGRP_LINK; + MMSG_CHECK(!setsockopt(fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &value, sizeof(value))); + for (unsigned capacity = 0; capacity <= sizeof(groups); ++capacity) { + groups[0] = groups[1] = UINT32_MAX; + size = capacity; + MMSG_CHECK(!getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &size)); + MMSG_CHECK(size >= sizeof(uint32_t) && !(size % sizeof(uint32_t))); + MMSG_CHECK(groups[0] == (capacity >= sizeof(uint32_t) ? RTMGRP_LINK : UINT32_MAX)); + if (capacity < sizeof(groups)) MMSG_CHECK(groups[1] == UINT32_MAX); + } + MMSG_CHECK(!setsockopt(fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, &value, sizeof(value))); + size = sizeof(groups); + MMSG_CHECK(!getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &size) && !groups[0]); + value = 1; + MMSG_CHECK(!setsockopt(fd, SOL_NETLINK, NETLINK_PKTINFO, &value, sizeof(value))); + const struct sockaddr_nl kernel = {.nl_family = AF_NETLINK}; + for (unsigned passcred = 0; passcred < 2; ++passcred) { + value = passcred; + MMSG_CHECK(!setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &value, sizeof(value))); + for (unsigned capacity = 0; capacity <= 64; ++capacity) { + const struct { struct nlmsghdr header; struct ifinfomsg link; } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_GETLINK, + .nlmsg_flags = NLM_F_REQUEST, .nlmsg_seq = capacity + 1}, + .link = {.ifi_family = AF_UNSPEC, .ifi_index = 1}, + }; + MMSG_CHECK(sendto(fd, &request, sizeof(request), 0, + (const void *)&kernel, sizeof(kernel)) == sizeof(request)); + unsigned char payload[65536]; + union { struct cmsghdr alignment; unsigned char bytes[64]; } control; + memset(control.bytes, 0xa5, sizeof(control.bytes)); + struct iovec vector = {payload, sizeof(payload)}; + struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_control = control.bytes, .msg_controllen = capacity}; + MMSG_CHECK(recvmsg(fd, &message, 0) > 0); + MMSG_CHECK(((struct nlmsghdr *)(void *)payload)->nlmsg_type == RTM_NEWLINK); + MMSG_CHECK(!!(message.msg_flags & MSG_CTRUNC) == (capacity < (passcred ? 52u : 20u))); + unsigned used = 0; + for (unsigned which = 0; which < 1 + passcred; ++which) { + unsigned available = capacity - used; + if (available < CMSG_LEN(0)) continue; + struct cmsghdr *header = (void *)(control.bytes + used); + unsigned value_size = which ? sizeof(struct ucred) : sizeof(struct nl_pktinfo); + unsigned copied = available - CMSG_LEN(0); + if (copied > value_size) copied = value_size; + MMSG_CHECK(header->cmsg_level == (which ? SOL_SOCKET : SOL_NETLINK)); + MMSG_CHECK(header->cmsg_type == (which ? SCM_CREDENTIALS : NETLINK_PKTINFO)); + MMSG_CHECK(header->cmsg_len == CMSG_LEN(copied)); + for (unsigned byte = 0; byte < copied; ++byte) + MMSG_CHECK(((unsigned char *)CMSG_DATA(header))[byte] == 0); + used += CMSG_SPACE(copied) < available ? CMSG_SPACE(copied) : available; + } + MMSG_CHECK(message.msg_controllen == used); + for (unsigned byte = capacity; byte < sizeof(control.bytes); ++byte) + MMSG_CHECK(control.bytes[byte] == 0xa5); + } + } + MMSG_CHECK(!close(fd)); + puts("PASS native netlink metadata: short options, membership words, packet info, credentials and truncation"); + return 0; +} + +int main(void) { return socket_batch_syscalls() || netlink_metadata_syscalls(); } #endif diff --git a/tools/tests/socket_batch_unix_test.c b/tools/tests/socket_batch_unix_test.c index ad6ee378..d39e13d1 100644 --- a/tools/tests/socket_batch_unix_test.c +++ b/tools/tests/socket_batch_unix_test.c @@ -2,6 +2,7 @@ #include #include #include +#include #include "../../kernel/syscall/ipc/socket.c" #include "../../kernel/syscall/ipc/socket_batch.c" @@ -18,6 +19,8 @@ static long allocation_budget = -1; static unsigned pty_holds; static struct linux_timespec fixture_realtime = {100, 123456789}; static bool netlink_credentials_fixture; +static bool netlink_pktinfo_fixture; +static unsigned netlink_receive_calls; static const struct ucred netlink_sender = {41, 1002, 3003}; /* AF_UNIX cases must not cross into another socket family's backend. */ int task_udp_recv(struct task_file *f, void *b, uint32_t n, uint32_t flags, uint64_t a, uint64_t l) @@ -60,17 +63,28 @@ int task_netlink_recv(struct task_file *file, void *data, uint32_t length, int task_netlink_recv_staged(struct task_file *file, void *data, uint32_t length, uint32_t flags, void *source, uint32_t *source_length, struct ucred *credentials) { - assert(netlink_credentials_fixture && file->kind == TASK_FILE_KIND_NETLINK); - assert(length && flags == (MSG_PEEK | MSG_TRUNC) && !source); + assert((netlink_credentials_fixture || netlink_pktinfo_fixture) && file->kind == TASK_FILE_KIND_NETLINK); + assert(flags == (MSG_PEEK | MSG_TRUNC)); + if (!length) { + assert(!source && !source_length && !credentials); + return 1; + } + ++netlink_receive_calls; *(char *)data = 'n'; *source_length = 0; - assert(credentials); - *credentials = netlink_sender; + if (source) { + *(struct sockaddr_nl *)source = (struct sockaddr_nl){.nl_family = AF_NETLINK, .nl_groups = RTMGRP_IPV6_ROUTE}; + *source_length = sizeof(struct sockaddr_nl); + } + if (credentials) *credentials = netlink_sender; return 1; } /** @brief Enable credentials only for the explicit netlink copyout fixture. */ bool task_netlink_passcred(const struct task_file *file) -{ assert(netlink_credentials_fixture && file->kind == TASK_FILE_KIND_NETLINK); return true; } +{ assert(file->kind == TASK_FILE_KIND_NETLINK); return netlink_credentials_fixture; } +/** @brief Enable packet info only for the explicit netlink copyout fixture. */ +bool task_netlink_pktinfo(const struct task_file *file) +{ assert(file->kind == TASK_FILE_KIND_NETLINK); return netlink_pktinfo_fixture; } int net_socket_error(int32_t h, bool c) { (void)h; (void)c; abort(); } int net_socket_recv(struct reliefos_net_socket_io *r, uint32_t p) { (void)r; (void)p; abort(); } int net_socket_send(struct reliefos_net_socket_io *r, uint32_t p) { (void)r; (void)p; abort(); } @@ -458,6 +472,69 @@ static void check_namespace_credentials(void) puts("PASS namespace socket credentials: input authority, overflow, PEEK snapshots, peer and netlink copyout"); } +/** @brief Check combined netlink control output and pre-consumption faults. */ +static void check_netlink_packet_info(void) +{ + struct task_file file = {.kind = TASK_FILE_KIND_NETLINK}; + netlink_pktinfo_fixture = true; + for (unsigned passcred = 0; passcred < 2; ++passcred) { + netlink_credentials_fixture = passcred; + for (unsigned capacity = 0; capacity <= 64; ++capacity) { + unsigned char control[64] __attribute__((aligned(8))); + memset(control, 0xa5, sizeof(control)); + char byte = 0; + struct iovec vector = {&byte, 1}; + struct sockaddr_nl source = {0}; + struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_control = control, .msg_controllen = capacity, + .msg_name = capacity & 1 ? &source : NULL, .msg_namelen = sizeof(source)}; + struct socket_message_result result = {0}; + assert(inet_message(&file, (uintptr_t)&message, message, MSG_PEEK, true, 1, &result) == 1); + assert(byte == 'n'); + assert(!!(result.flags & MSG_CTRUNC) == (capacity < (passcred ? 52u : 20u))); + unsigned used = 0; + if (capacity >= CMSG_LEN(0)) { + struct cmsghdr *header = (void *)control; + unsigned copied = capacity - CMSG_LEN(0); + if (copied > sizeof(struct nl_pktinfo)) copied = sizeof(struct nl_pktinfo); + assert(header->cmsg_level == SOL_NETLINK && header->cmsg_type == NETLINK_PKTINFO); + assert(header->cmsg_len == CMSG_LEN(copied)); + const struct nl_pktinfo expected = {.group = 11}; + assert(!memcmp(CMSG_DATA(header), &expected, copied)); + used = CMSG_SPACE(copied) < capacity ? CMSG_SPACE(copied) : capacity; + } + if (passcred && capacity - used >= CMSG_LEN(0)) { + struct cmsghdr *header = (void *)(control + used); + unsigned copied = capacity - used - CMSG_LEN(0); + if (copied > sizeof(struct ucred)) copied = sizeof(struct ucred); + assert(header->cmsg_level == SOL_SOCKET && header->cmsg_type == SCM_CREDENTIALS); + assert(header->cmsg_len == CMSG_LEN(copied)); + assert(!memcmp(CMSG_DATA(header), &netlink_sender, copied)); + used += CMSG_SPACE(copied) < capacity - used ? CMSG_SPACE(copied) : capacity - used; + } + assert(message.msg_controllen == used); + if (capacity & 1) assert(source.nl_family == AF_NETLINK && source.nl_groups == RTMGRP_IPV6_ROUTE); + for (unsigned i = capacity; i < sizeof(control); ++i) assert(control[i] == 0xa5); + } + } +#ifndef CONFIG_SWAP + char byte = 0; + struct iovec vector = {&byte, 1}; + unsigned char control[64]; + struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_control = control, .msg_controllen = sizeof(control)}; + struct socket_message_result result = {0}; + unsigned received = netlink_receive_calls; + readonly = (uintptr_t)control; + assert(inet_message(&file, (uintptr_t)&message, message, MSG_PEEK, true, 1, &result) == -LINUX_EFAULT); + assert(netlink_receive_calls == received && !byte); + readonly = 0; +#endif + netlink_credentials_fixture = netlink_pktinfo_fixture = false; + assert(!allocations); + puts("PASS netlink packet info: group indices, optional source, credentials, truncation and output faults"); +} + int main(void) { current.kind = TASK_KIND_USER; @@ -645,6 +722,7 @@ int main(void) } check_unix_stream_outq(); check_namespace_credentials(); + check_netlink_packet_info(); puts("PASS actual Unix mmsg: packet boundaries, WAITFORONE, blocking resume, length faults, SCM_RIGHTS references/CLOEXEC"); return 0; } diff --git a/tools/tests/task8_host_stubs/descriptor_unreached.c b/tools/tests/task8_host_stubs/descriptor_unreached.c index 4358cb2c..55ad46c6 100644 --- a/tools/tests/task8_host_stubs/descriptor_unreached.c +++ b/tools/tests/task8_host_stubs/descriptor_unreached.c @@ -11,6 +11,7 @@ UNREACHED(task_netlink_recv) UNREACHED(task_netlink_send) UNREACHED(task_netlink_poll) UNREACHED(task_netlink_passcred) +UNREACHED(task_netlink_pktinfo) UNREACHED(task_netlink_recv_staged) UNREACHED(syscall_netlink) UNREACHED(task_packet_address_size) diff --git a/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c b/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c index e410d7ae..15700c39 100644 --- a/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c +++ b/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c @@ -7,7 +7,7 @@ TRAP(kernel_wait_queue_wake_one) TRAP(net_socket_address) TRAP(net_socket_connec TRAP(net_socket_get_timeout_ticks) TRAP(net_socket_open) TRAP(net_socket_pin_fd) TRAP(net_socket_set_timeout_ticks) TRAP(net_socket_shutdown_fd) TRAP(syscall_packet) TRAP(syscall_udp) TRAP(task_discard_file_fd) -TRAP(task_netlink_cancel_wait) TRAP(syscall_netlink) +TRAP(syscall_netlink) TRAP(net_interface_device_option) TRAP(net_socket_accept_commit) TRAP(net_socket_accept_peek) TRAP(net_socket_address6) TRAP(net_socket_bind6_fd) TRAP(net_socket_bound_device) TRAP(net_socket_connect6_fd) TRAP(net_socket_family) diff --git a/tools/tests/task8_socket_receive_test.c b/tools/tests/task8_socket_receive_test.c index cc7b8c37..6ca9f509 100644 --- a/tools/tests/task8_socket_receive_test.c +++ b/tools/tests/task8_socket_receive_test.c @@ -19,6 +19,9 @@ static uintptr_t device_user_page,device_physical_page; static unsigned pins; static bool contended,blocked_writing=true; static struct socket_send_stage *owned_stage; +/** @brief Verify that a contended netlink output cancels the current wait. */ +void task_netlink_cancel_wait(struct task_file *file, struct task *task) +{ assert(netlink_pktinfo_fixture && file->kind == TASK_FILE_KIND_NETLINK && task == ¤t); } struct socket_send_stage *sched_socket_stage(const struct task *task) { assert(task==¤t);return owned_stage; } bool sched_socket_stage_set(struct task *task,struct socket_send_stage *stage) @@ -68,6 +71,40 @@ static void send_one(uint8_t value) assert(!peers[1].rights);peers[1].rights=r; } +/** @brief Prepare packet-info output before consuming a netlink datagram. */ +static void check_netlink_control_retry(void) +{ + struct task_file file = {.kind = TASK_FILE_KIND_NETLINK, + .flags = TASK_FILE_FLAG_SOCKET | TASK_FILE_FLAG_SOCKET_INET}; + struct iovec vector = {output, sizeof(output)}; + struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_control = control, .msg_controllen = sizeof(control)}; + struct trap_frame frame = {.rax = LINUX_SYS_RECVMSG, .rdi = 4, + .rsi = (uintptr_t)&message, .rdx = MSG_PEEK}; + struct socket_message_result result = {0}; + netlink_pktinfo_fixture = true; + unsigned received = netlink_receive_calls; + current.syscall_file = &file; + task_lookup_scope_begin(¤t, &frame); + readonly = (uintptr_t)control; + contended = true; + assert(task_socket_message(¤t, &file, (uintptr_t)&message, MSG_PEEK, + true, false, &result) == KERNEL_SYSCALL_SWAP_CONTENDED); + assert(netlink_receive_calls == received); + contended = false; + task_lookup_scope_begin(¤t, &frame); + assert(task_socket_message(¤t, &file, (uintptr_t)&message, MSG_PEEK, + true, false, &result) == 1); + const struct cmsghdr *header = (const void *)control; + assert(netlink_receive_calls == received + 1 && output[0] == 'n'); + assert(header->cmsg_level == SOL_NETLINK && header->cmsg_type == NETLINK_PKTINFO); + assert(((const struct nl_pktinfo *)(const void *)CMSG_DATA(header))->group == 11); + task_lookup_scope_cancel(¤t); + current.syscall_file = NULL; + netlink_pktinfo_fixture = false; + assert(!allocations && !pins); +} + #ifdef TASK8_DEVICE_SOCKET_TEST int inherited_task8_socket_receive_main(void) #else @@ -75,6 +112,7 @@ int main(void) #endif { current.kind=TASK_KIND_USER;current.pid=current.tgid=10;current.uid=current.gid=100;current.state=TASK_READY; + check_netlink_control_retry(); for(unsigned i=0;i<2;++i){peers[i]=(struct unix_socket){.used=1,.refs=1,.handle=i+1,.type=SOCK_DGRAM, .state=UNIX_SOCKET_CONNECTED,.peer_handle=2-i,.receive_timeout=UINT64_MAX,.send_timeout=UINT64_MAX}; endpoints[i]=(struct task_file){.used=1,.references=1,.aux=i+1, From b9b0d4bfdf9e0bdf178814e3e6b16594f487a694 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 03:58:23 +0800 Subject: [PATCH 69/97] fix(fs): mount writable devtmpfs before starting userspace --- .../userspace-api/device-filesystems.po | 3 + .../userspace-api/device-filesystems.po | 3 + .../userspace-api/device-filesystems.rst | 5 ++ fs/vfs/storage_initial.c | 14 ++++- tools/test_mount_backend.py | 1 + tools/tests/mount_backend_test.c | 55 +++++++++++++++---- 6 files changed, 68 insertions(+), 13 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 1be5ca47..c3b19df3 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -53,6 +53,9 @@ msgstr "" "VFS permission checks. Device opens are dispatched to drivers by inode " "type and ``st_rdev``; a ``nodev`` mount rejects device opens." +msgid "内核在启动用户态之前将共享可写 devtmpfs 挂到初始命名空间的 ``/dev``, 因此 PID 1 可以创建 ``/dev/log`` 等符号链接。``/dev/shm`` 使用独立的 tmpfs 挂载,根目录归 root,权限为 ``01777``。初始命名空间组装失败时, 公开挂载与独立 shm 一并撤回,共享 devtmpfs 的私有 backing 继续保留。" +msgstr "The kernel mounts shared writable devtmpfs at ``/dev`` in the initial namespace before starting userspace, allowing PID 1 to create symlinks such as ``/dev/log``. ``/dev/shm`` uses a separate tmpfs mount with a root-owned directory and mode ``01777``. If initial namespace assembly fails, the public mounts and independent shm are rolled back while the private backing of shared devtmpfs survives." + msgid "设备生命周期" msgstr "Device lifecycle" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index 4c6f6c0a..b6278e2f 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -51,6 +51,9 @@ msgstr "" "VFS 権限検査が適用されます。デバイスのオープンは inode の種類と ``st_rdev`` " "に基づいてドライバーへ振り分けられ、``nodev`` のマウントでは拒否されます。" +msgid "内核在启动用户态之前将共享可写 devtmpfs 挂到初始命名空间的 ``/dev``, 因此 PID 1 可以创建 ``/dev/log`` 等符号链接。``/dev/shm`` 使用独立的 tmpfs 挂载,根目录归 root,权限为 ``01777``。初始命名空间组装失败时, 公开挂载与独立 shm 一并撤回,共享 devtmpfs 的私有 backing 继续保留。" +msgstr "カーネルはユーザー空間の起動前に、共有された書き込み可能な devtmpfs を初期名前空間の ``/dev`` にマウントします。PID 1 は ``/dev/log`` などのシンボリックリンクを作成できます。``/dev/shm`` は独立した tmpfs マウントで、ルートディレクトリの所有者は root、モードは ``01777`` です。初期名前空間の構築に失敗すると、公開マウントと独立した shm をロールバックし、共有 devtmpfs のプライベート backing は保持します。" + msgid "设备生命周期" msgstr "デバイスのライフサイクル" diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 6fe7b4a4..1afaaa5b 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -21,6 +21,11 @@ devtmpfs 设备节点使用现有 VFS 权限检查。设备打开按 inode 的类型和 ``st_rdev`` 分派到驱动,``nodev`` 挂载拒绝打开设备。 +内核在启动用户态之前将共享可写 devtmpfs 挂到初始命名空间的 ``/dev``, +因此 PID 1 可以创建 ``/dev/log`` 等符号链接。``/dev/shm`` 使用独立的 +tmpfs 挂载,根目录归 root,权限为 ``01777``。初始命名空间组装失败时, +公开挂载与独立 shm 一并撤回,共享 devtmpfs 的私有 backing 继续保留。 + 设备生命周期 ------------ diff --git a/fs/vfs/storage_initial.c b/fs/vfs/storage_initial.c index fdfdd931..219d1f10 100644 --- a/fs/vfs/storage_initial.c +++ b/fs/vfs/storage_initial.c @@ -40,8 +40,14 @@ static int storage_initial_root(void *context,struct vfs_mount **out) if(rc){vfs_mount_put(*out);*out=NULL;} return rc; } -static int storage_initial_devfs(void *context,struct vfs_mount **out) -{(void)context;return devfs_create_vfs_mount(out);} +/** @brief Attach shared writable device storage before userspace starts. + * @param context Unused factory context. + * @param out Receives one detached public devtmpfs mount, empty on failure. + * @return Zero or negative constructor errno. Exclusive boot execution; + * rollback releases this attachment while the private backing survives. + */ +static int storage_initial_devtmpfs(void *context,struct vfs_mount **out) +{(void)context;return devtmpfs_create_vfs_mount("devtmpfs",0,NULL,out);} static int storage_initial_procfs(void *context,struct vfs_mount **out) {(void)context;return proc_create_vfs_mount(out);} static int storage_initial_sysfs(void *context,struct vfs_mount **out) @@ -64,6 +70,8 @@ static int storage_initial_shm(void *context,struct vfs_mount **out) * @return Zero after root/providers/boot attachments and explicit fresh shm * are all published, or negative errno after complete assembly rollback. A * failed constructor/attachment never publishes a partial system namespace. + * The shared writable devtmpfs backing survives rollback and later public + * unmounts; the sticky shm attachment has its own temporary lifetime. * The caller owns exclusive boot execution; no graph/module lock spans I/O. * Reserved ESP identity and ready optical instances define initial roles. * Skip optical attachments when their mountpoint parent is absent; the @@ -75,7 +83,7 @@ int storage_namespace_bootstrap(void) if(vfs_system_namespace())return -EBUSY; if(!g_volumes[0].ready)return -ENODEV; struct vfs_boot_mount mounts[STORAGE_MAX_VOLUMES+3]={ - {.target="/dev",.create=storage_initial_devfs}, + {.target="/dev",.create=storage_initial_devtmpfs}, {.target="/proc",.create=storage_initial_procfs}, {.target="/sys",.create=storage_initial_sysfs} }; diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index 1f1198e5..cbffaea2 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -23,6 +23,7 @@ def test_real_tmpfs_without_text_routing(self): "-Wl,--gc-sections", "-Wl,--wrap=storage_ext4_read_inode", "-Wl,--wrap=storage_read_device", "-Wl,--wrap=storage_inode_stat", "-Wl,--wrap=storage_backend_commit_rename_metadata", "-Wl,--wrap=storage_cluster_write", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_backend_test.c", "kernel/dma/buffer.c", "drivers/storage/ahci/dma.c", "drivers/storage/ahci/interrupt.c", "drivers/storage/nvme/queue.c", "block/partition/mbr.c", "fs/cgroup/filesystem.c", "fs/cgroup/hierarchy.c", "fs/vfs/notify.c", "fs/nsfs/namespace.c", "kernel/sched/user_namespace.c", + "kernel/init/uts.c", "kernel/syscall/dispatch.c", "kernel/syscall/io/legacy_io.c", "kernel/syscall/io/io.c", "kernel/syscall/io/file_io.c", "kernel/syscall/io/seek.c", "kernel/syscall/io/transfer.c", "kernel/syscall/io/directory.c", "kernel/syscall/fs/metadata.c", "tools/tests/mount_backend_io_boundaries.c", diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 5d3a1b73..41ff159d 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -1577,9 +1577,20 @@ static void initial_namespace(void) /* Only these two factory boundaries use independent RAM roots in this storage * bootstrap fixture. The procfs/inventory suites exercise the real providers; - * this test composes the real root/devfs/volume/shm builder and its rollback. */ + * this test composes the real root/devtmpfs/volume/shm builder and rollback. */ static bool initial_sysfs_error; static char proc_fixture_options[128]; +static struct storage_volume *boot_device_volume; +/** @brief Check boot rollback retires every temporary runtime instance. + * @return None. The shared device backing retains exactly one private mount. + */ +static void initial_runtime_retired(void) +{ + assert(boot_device_volume && boot_device_volume->vfs_mounts==1); + for(uint32_t id=STORAGE_RUNTIME_TMPFS_FIRST;id<=STORAGE_RUNTIME_TMPFS_LAST;++id) + assert(storage_mounted_volume(id)== + (id==boot_device_volume->volume_id ? boot_device_volume : NULL)); +} /** @brief Validate the proc options used by this constructor-boundary fixture. */ int proc_validate_mount_options(const char *options) { @@ -1663,7 +1674,7 @@ static void initial_root_access_policy(void) } } vfs_path_put(&file);vfs_path_put(&root);assert(!vfs_namespace_destroy(ns)); - assert(!storage_mounted_volume(STORAGE_RUNTIME_TMPFS_FIRST)); + initial_runtime_retired(); } g_volumes[0].mount_flags=saved_flags;g_volumes[0].fs_ops=saved_ops; g_volumes[0].read_only_reason=saved_readonly;test_wall_seconds=saved_clock; @@ -1671,7 +1682,7 @@ static void initial_root_access_policy(void) puts("PASS boot root default relatime, explicit noatime/strictatime, statfs, cross-second reads and unchanged volume flags"); } -/** @brief Verify boot assembly can mount and roll back shm with every disk slot occupied. +/** @brief Verify writable boot devices and rollback with every disk slot occupied. * @param rootfs Borrowed base tmpfs for the boot mountpoints. */ static void production_initial_namespace(struct tmpfs_super *rootfs) @@ -1692,7 +1703,8 @@ static void production_initial_namespace(struct tmpfs_super *rootfs) initial_sysfs_error=true; assert(storage_namespace_bootstrap()==-EIO && !vfs_system_namespace()); - assert(!storage_mounted_volume(STORAGE_RUNTIME_TMPFS_FIRST));initial_sysfs_error=false; + boot_device_volume=storage_mounted_volume(STORAGE_RUNTIME_TMPFS_FIRST); + initial_runtime_retired();initial_sysfs_error=false; bool success=false; for(int budget=0;budget<80;++budget) { test_fail_heap_after=budget;int rc=storage_namespace_bootstrap();test_fail_heap_after=-1; @@ -1711,8 +1723,31 @@ static void production_initial_namespace(struct tmpfs_super *rootfs) assert(!vfs_path_lookup(ns,&root,&root,"/mnt",0,&alias_point)); assert(!storage_create_vfs_mount(&g_volumes[2],NULL,&alias_mount)); assert(!vfs_mount_attach(ns,alias_mount,&alias_point));vfs_mount_put(alias_mount);vfs_path_put(&alias_point); + struct vfs_path devices={0},journal_link={0}; + struct reliefos_permissions link_mode={0777,0,0}; + const char *journal_target="/run/systemd/journal/dev-log"; + assert(!vfs_path_lookup(ns,&root,&root,"/dev",0,&devices)); + assert(!strcmp(devices.mount->filesystem,"devtmpfs")); + assert(vfs_path_context(&devices)==boot_device_volume); + assert(!(vfs_path_mount_flags(&devices)&MS_RDONLY)); + assert(!vfs_path_create_node(&devices,"log",LINUX_S_IFLNK,&link_mode, + journal_target,&journal_link)); + char target[64]={0};size_t target_length=0; + assert(!vfs_path_readlink(&journal_link,target,sizeof(target),&target_length)); + assert(target_length==strlen(journal_target) && !memcmp(target,journal_target,target_length)); + struct vfs_mount *device_alias=NULL;struct vfs_path alias_root={0},alias_link={0}; + assert(!devtmpfs_create_vfs_mount(NULL,0,NULL,&device_alias)); + assert(!vfs_mount_detached_root(device_alias,&alias_root));vfs_mount_put(device_alias); + assert(!vfs_path_lookup_child(&alias_root,"log",&alias_link)); + assert(vfs_path_same_inode(&journal_link,&alias_link)); + vfs_path_put(&alias_link);vfs_path_put(&alias_root); + assert(!vfs_path_remove(ns,&journal_link,false)); + vfs_path_put(&journal_link);vfs_path_put(&devices); assert(!vfs_path_lookup(ns,&root,&root,"/dev/null",0,&node)); - assert(vfs_path_node(&node)->first_cluster==STORAGE_DEV_KIND_NULL);vfs_path_put(&node); + struct linux_stat_abi device_status; + assert(!vfs_path_stat(&node,&device_status)); + assert((device_status.st_mode&LINUX_S_IFMT)==LINUX_S_IFCHR && device_status.st_rdev==0x103); + vfs_path_put(&node); assert(!vfs_path_lookup(ns,&root,&root,"/proc",0,&node));assert(vfs_path_node(&node)->volume_id==4);vfs_path_put(&node); assert(!vfs_path_lookup(ns,&root,&root,"/sys",0,&node));assert(vfs_path_node(&node)->volume_id==5);vfs_path_put(&node); assert(!vfs_path_lookup(ns,&root,&root,"/mnt/new",0,&node));assert(vfs_path_node(&node)->volume_id==2);vfs_path_put(&node); @@ -1738,7 +1773,7 @@ static void production_initial_namespace(struct tmpfs_super *rootfs) assert(!vfs_namespace_destroy(ns)); assert(!storage_mounted_volume(shm_id));success=true; } - assert(!storage_mounted_volume(STORAGE_RUNTIME_TMPFS_FIRST)); + initial_runtime_retired(); for(unsigned slot=STORAGE_VOLUME_DYNAMIC_FIRST;slotmount_flags==original_flags); assert(vfs_path_mount_flags(&existing_root)==existing_policy);vfs_path_put(&existing_root); vfs_path_put(&file);vfs_path_put(&root);assert(!vfs_namespace_destroy(ns)); - assert(!storage_mounted_volume(STORAGE_RUNTIME_TMPFS_FIRST)); + initial_runtime_retired(); for(unsigned slot=4;slot<=5;++slot) { assert(g_volumes[slot].ready && g_volumes[slot].tmpfs && !storage_inode_volume_busy(slot)); tmpfs_destroy(g_volumes[slot].tmpfs);g_volumes[slot]=(struct storage_volume){0}; @@ -5107,8 +5142,8 @@ int main(int argc,char **argv) if(argc==3)ext_family(argv[1],argv[2]); if(argc==2)iso_filesystem(argv[1]); if(argc==4)cluster_filesystem(argv[1],argv[2],!strcmp(argv[3],"exfat")); - /* devtmpfs retains a private backing reference for the kernel lifetime. - * Run it after the tests which assert full runtime tmpfs retirement. */ + /* The boot device backing survives namespace teardown. Further mounts + * exercise the same retained filesystem through the ordinary syscall. */ assert(!tmpfs_new(0,0,"size=0,nr_inodes=0",0,0,&fs)); g_volumes[0]=(struct storage_volume){.volume_id=0,.kind=STORAGE_VOLUME_ANONYMOUS, .ready=true,.filesystem=STORAGE_FILESYSTEM_TMPFS,.fs_ops=&storage_tmpfs_ops,.tmpfs=fs}; From 50c93fbf482a8aa2a43d634ccce8aceabf3ef377 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 04:17:46 +0800 Subject: [PATCH 70/97] feat(net): retain network namespace identity for Unix sockets --- Documentation/core-api/mount-namespaces.rst | 7 + .../LC_MESSAGES/core-api/mount-namespaces.po | 9 ++ .../LC_MESSAGES/userspace-api/descriptors.po | 9 ++ .../LC_MESSAGES/core-api/mount-namespaces.po | 9 ++ .../LC_MESSAGES/userspace-api/descriptors.po | 9 ++ Documentation/userspace-api/descriptors.rst | 7 + include/reliefnt/net_namespace.h | 38 +++++ include/reliefnt/proc_stats.h | 2 +- include/reliefnt/task/types.h | 2 + kernel/sched/clone.c | 6 +- kernel/sched/internal.h | 1 + kernel/sched/session.c | 7 +- kernel/sched/task.c | 2 + kernel/sched/wait.c | 2 + kernel/syscall/ipc/socket.c | 42 +++-- net/Kbuild | 2 +- net/namespace/Kbuild | 4 + net/namespace/namespace.c | 32 ++++ tools/test_ipv6_transport.py | 1 + tools/test_linux_socket_batches.py | 2 +- tools/test_poll_wakeup.py | 1 + tools/tests/descriptor_table_test.c | 151 +++++++++++++++++- tools/tests/modules/scheduler.h | 1 + tools/tests/mount_namespace_task_test.c | 11 ++ tools/tests/poll_wakeup_test.c | 4 +- 25 files changed, 333 insertions(+), 28 deletions(-) create mode 100644 include/reliefnt/net_namespace.h create mode 100644 net/namespace/Kbuild create mode 100644 net/namespace/namespace.c diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 25c0679b..a68ff001 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -155,6 +155,13 @@ hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护 ``sethostname()`` 和 ``setdomainname()`` 按 UTS owner 的 ``CAP_SYS_ADMIN`` 授权,按长度复制 0 至 64 字节,保留换行与内嵌 NUL,尾部补零。 +网络空间生命周期 +================ + +``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,监听端创建的服务端连接继承监听端空间。 + +当前网络身份提供 Unix 抽象地址和 proc 枚举的作用域。接口、路由、IPv4/IPv6、TCP/UDP 与 netlink 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。 + 凭据权限作用域 ============== diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 7bc874a9..45e548f4 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -444,3 +444,12 @@ msgstr "UTS switching requires ``CAP_SYS_ADMIN`` in both the current user namesp msgid "``struct uts_namespace`` 使用原子引用计数,任务和 nsfs 后端分别持有引用, 最后一个引用释放时同时释放 owner 用户空间。空指针表示永久初始 UTS 空间。 hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护。 ``sethostname()`` 和 ``setdomainname()`` 按 UTS owner 的 ``CAP_SYS_ADMIN`` 授权,按长度复制 0 至 64 字节,保留换行与内嵌 NUL,尾部补零。" msgstr "``struct uts_namespace`` uses atomic reference counting. Tasks and nsfs backends each retain references. Releasing the final reference also releases the owner user namespace. A null pointer denotes the permanent initial UTS namespace. A short-held UTS spinlock protects hostname and domainname copies, reads and updates. ``sethostname()`` and ``setdomainname()`` authorize against ``CAP_SYS_ADMIN`` in the UTS owner, copy 0 to 64 bytes by length, preserve newlines and embedded NUL bytes, and zero-pad the end." + +msgid "网络空间生命周期" +msgstr "Network namespace lifetime" + +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,监听端创建的服务端连接继承监听端空间。" +msgstr "``net_namespace_create()`` creates a reference-counted network identity with an immutable user owner. A null pointer denotes the permanent initial network namespace. Tasks share the identity on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix socket independently retains its creating network namespace until its final reference closes. Server connections inherit the listener namespace." + +msgid "当前网络身份提供 Unix 抽象地址和 proc 枚举的作用域。接口、路由、IPv4/IPv6、TCP/UDP 与 netlink 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。" +msgstr "The current network identity scopes Unix abstract addresses and proc enumeration. Interface, route, IPv4/IPv6, TCP/UDP and netlink state isolation are subsequent integration steps. Clone requests using ``CLONE_NEWNET`` return ``EPERM`` or ``EINVAL`` according to authority. Unshare requests return ``EINVAL``. Userspace creation and switching will be connected after complete network state isolation." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index 31790342..d2ca6d63 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -425,3 +425,12 @@ msgstr "``AF_NETLINK`` ``SOL_NETLINK/NETLINK_PKTINFO`` uses a native 32-bit inte msgid "``NETLINK_LIST_MEMBERSHIPS`` 查询当前组成员位图。尚未初始化成员存储时, 返回长度 0;成功加入或退出组后保留一个 32 位字,覆盖本内核支持的 32 个组号, 最后一个组退出后仍可查询全零位图。容量不足一个字时不复制数据,长度始终报告 所需字节数,容量为 0 时可探测长度。加入和退出继续使用既有协议组与权限检查。" msgstr "``NETLINK_LIST_MEMBERSHIPS`` queries the current membership bitmap. Before membership storage is initialized, its returned length is 0. A successful join or leave retains one 32-bit word covering this kernel's 32 supported group indices. Leaving the last group preserves an all-zero queryable bitmap. Capacities shorter than one word copy no data. The length always reports the required bytes, and zero capacity probes that length. Joining and leaving retain the existing protocol-group and permission checks." + +msgid "Unix 套接字网络作用域" +msgstr "Unix socket network scope" + +msgid "``AF_UNIX`` 抽象地址按套接字创建时的网络空间匹配,名称按显式长度比较并保留内嵌 NUL。不同空间可以绑定相同名称,同一空间内重复绑定返回 ``EADDRINUSE``。任务切换空间、fork、复制或传递文件描述符后,已有套接字继续持有原空间。``accept`` 连接继承监听端的空间。``/proc/net/unix`` 只枚举调用者当前网络空间内的套接字。" +msgstr "``AF_UNIX`` abstract addresses match within the network namespace where the socket was created. Names use their explicit lengths and preserve embedded NUL bytes. Different namespaces can bind the same name, while duplicate binds within one namespace return ``EADDRINUSE``. Existing sockets retain their original namespace across task namespace changes, fork, descriptor duplication and descriptor transfer. Accepted connections inherit the listener namespace. ``/proc/net/unix`` enumerates sockets in the current caller network namespace." + +msgid "文件系统套接字通过路径解析取得的真实 inode 身份匹配,具有相应路径权限的其他网络空间可连接同一 inode。硬链接和 bind 别名共享端点身份,移除后重新创建的同名节点拥有独立身份。套接字持有的 inode 与网络空间引用随最后一个打开文件描述释放。" +msgstr "Filesystem sockets match the actual inode identity obtained by path resolution. Other network namespaces with the required path permissions can connect to the same inode. Hard links and bind aliases share endpoint identity. A same-name node recreated after removal has an independent identity. The socket releases its inode and network namespace references when its final open file description is released." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index c5397c8e..003eaafa 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -389,3 +389,12 @@ msgstr "UTS の切り替えには、現在のユーザー名前空間と対象 U msgid "``struct uts_namespace`` 使用原子引用计数,任务和 nsfs 后端分别持有引用, 最后一个引用释放时同时释放 owner 用户空间。空指针表示永久初始 UTS 空间。 hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护。 ``sethostname()`` 和 ``setdomainname()`` 按 UTS owner 的 ``CAP_SYS_ADMIN`` 授权,按长度复制 0 至 64 字节,保留换行与内嵌 NUL,尾部补零。" msgstr "``struct uts_namespace`` はアトミックな参照カウントを使用し、タスクと nsfs バックエンドがそれぞれ参照を保持します。最後の参照を解放すると owner ユーザー名前空間も解放します。NULL ポインターは永続的な初期 UTS 名前空間を表します。hostname と domainname のコピー、読み取り、更新は短時間保持する UTS スピンロックで保護します。``sethostname()`` と ``setdomainname()`` は UTS owner の ``CAP_SYS_ADMIN`` で認可し、長さに従って 0 から 64 バイトをコピーします。改行と埋め込み NUL を保持し、末尾をゼロで埋めます。" + +msgid "网络空间生命周期" +msgstr "ネットワーク名前空間の寿命" + +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,监听端创建的服务端连接继承监听端空间。" +msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク識別を作成します。空ポインターは永続的な初期ネットワーク名前空間を表します。タスクは fork 時に識別を共有し、exec と ID のクリア後も参照を保持し、wait による回収またはスロット再利用時に解放します。各 Unix ソケットは作成時のネットワーク名前空間を独立して保持し、最後の参照を閉じると解放します。サーバー側の接続はリスナーの名前空間を継承します。" + +msgid "当前网络身份提供 Unix 抽象地址和 proc 枚举的作用域。接口、路由、IPv4/IPv6、TCP/UDP 与 netlink 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。" +msgstr "現在のネットワーク識別は Unix 抽象アドレスと proc 列挙のスコープを提供します。インターフェイス、経路、IPv4/IPv6、TCP/UDP、netlink の状態分離は後続の統合作業です。``CLONE_NEWNET`` を指定した clone は権限に応じて ``EPERM`` または ``EINVAL`` を返し、unshare は ``EINVAL`` を返します。ネットワーク状態の分離が完了した後で、ユーザー空間の作成と切り替え入口を接続します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index e666bab9..e090fc40 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -368,3 +368,12 @@ msgstr "``AF_NETLINK`` の ``SOL_NETLINK/NETLINK_PKTINFO`` はネイティブの msgid "``NETLINK_LIST_MEMBERSHIPS`` 查询当前组成员位图。尚未初始化成员存储时, 返回长度 0;成功加入或退出组后保留一个 32 位字,覆盖本内核支持的 32 个组号, 最后一个组退出后仍可查询全零位图。容量不足一个字时不复制数据,长度始终报告 所需字节数,容量为 0 时可探测长度。加入和退出继续使用既有协议组与权限检查。" msgstr "``NETLINK_LIST_MEMBERSHIPS`` は現在の所属グループのビットマップを取得します。所属情報の格納領域が未初期化なら長さ 0 を返します。参加または離脱に成功すると、本カーネルの 32 個のグループ番号を表す 32 ビットのワード一つを保持します。最後のグループから離脱した後も、すべてゼロのビットマップを取得できます。容量が一ワード未満ならデータをコピーしません。長さは常に必要バイト数を示し、容量 0 でその長さを調べられます。参加と離脱には既存のプロトコルグループおよび権限検査が適用されます。" + +msgid "Unix 套接字网络作用域" +msgstr "Unix ソケットのネットワークスコープ" + +msgid "``AF_UNIX`` 抽象地址按套接字创建时的网络空间匹配,名称按显式长度比较并保留内嵌 NUL。不同空间可以绑定相同名称,同一空间内重复绑定返回 ``EADDRINUSE``。任务切换空间、fork、复制或传递文件描述符后,已有套接字继续持有原空间。``accept`` 连接继承监听端的空间。``/proc/net/unix`` 只枚举调用者当前网络空间内的套接字。" +msgstr "``AF_UNIX`` 抽象アドレスはソケット作成時のネットワーク名前空間内で照合されます。名前は明示された長さで比較し、埋め込まれた NUL を保持します。異なる名前空間では同じ名前をバインドでき、同一空間での重複は ``EADDRINUSE`` を返します。タスクの名前空間変更、fork、記述子の複製や転送後も既存ソケットは元の空間を保持します。``accept`` 接続はリスナーの空間を継承します。``/proc/net/unix`` は呼び出し元の現在のネットワーク名前空間に属するソケットを列挙します。" + +msgid "文件系统套接字通过路径解析取得的真实 inode 身份匹配,具有相应路径权限的其他网络空间可连接同一 inode。硬链接和 bind 别名共享端点身份,移除后重新创建的同名节点拥有独立身份。套接字持有的 inode 与网络空间引用随最后一个打开文件描述释放。" +msgstr "ファイルシステムソケットはパス解決で取得した実際の inode 識別で照合されます。必要なパス権限を持つ他のネットワーク名前空間からも同じ inode に接続できます。ハードリンクと bind 別名はエンドポイント識別を共有します。削除後に同名で再作成されたノードは独立した識別を持ちます。ソケットが保持する inode とネットワーク名前空間の参照は最後のオープンファイル記述の解放時に解放されます。" diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index f79b5805..62aafd6f 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -214,3 +214,10 @@ TCP 的 ``setsockopt/getsockopt(SOL_TCP, TCP_NODELAY)`` 接受原生整数标志 查看根之外的挂载根不出现在 chroot 视图中;可见记录保留实际 ID,因此其 parent ID 可能位于查看范围之外。路径字段转义空格、制表符、换行和反斜线。 分段读取使用同一图顺序和字节偏移,不依赖反向插入的内部链表布局。 + +Unix 套接字网络作用域 +======================== + +``AF_UNIX`` 抽象地址按套接字创建时的网络空间匹配,名称按显式长度比较并保留内嵌 NUL。不同空间可以绑定相同名称,同一空间内重复绑定返回 ``EADDRINUSE``。任务切换空间、fork、复制或传递文件描述符后,已有套接字继续持有原空间。``accept`` 连接继承监听端的空间。``/proc/net/unix`` 只枚举调用者当前网络空间内的套接字。 + +文件系统套接字通过路径解析取得的真实 inode 身份匹配,具有相应路径权限的其他网络空间可连接同一 inode。硬链接和 bind 别名共享端点身份,移除后重新创建的同名节点拥有独立身份。套接字持有的 inode 与网络空间引用随最后一个打开文件描述释放。 diff --git a/include/reliefnt/net_namespace.h b/include/reliefnt/net_namespace.h new file mode 100644 index 00000000..cccb4ef7 --- /dev/null +++ b/include/reliefnt/net_namespace.h @@ -0,0 +1,38 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_NET_NAMESPACE_H +#define RELIEFNT_NET_NAMESPACE_H + +#include + +struct user_namespace; + +/** @brief Reference-counted network identity with an immutable user owner. + * NULL denotes the permanent initial network namespace. Tasks and sockets own + * independent references. Execution ownership serializes namespace publication. + */ +struct net_namespace { + uint64_t references; + struct user_namespace *user_ns; +}; + +/** @brief Allocate an empty network identity and retain its user owner. + * @param owner Borrowed user namespace, NULL for the initial user namespace. + * @param out Required output, cleared on failure, owning one reference on success. + * @return Zero, -EINVAL or -ENOMEM. Caller supplies execution ownership and + * authorization. The identity does not copy interfaces or protocol state. + */ +int net_namespace_create(struct user_namespace *owner, struct net_namespace **out); + +/** @brief Retain a live network identity without allocating or taking locks. + * @param ns Borrowed namespace, nullable for the permanent initial namespace. + * @return The same pointer with one additional owned reference. + */ +struct net_namespace *net_namespace_get(struct net_namespace *ns); + +/** @brief Release a network identity and its owner after the final reference. + * @param ns Owned reference, nullable for the permanent initial namespace. + * Does not acquire scheduler or network locks or access task state. + */ +void net_namespace_put(struct net_namespace *ns); + +#endif diff --git a/include/reliefnt/proc_stats.h b/include/reliefnt/proc_stats.h index d81f11a1..07e948eb 100644 --- a/include/reliefnt/proc_stats.h +++ b/include/reliefnt/proc_stats.h @@ -71,7 +71,7 @@ void net_udp_proc_emit(struct text_stream *s); * @param s Required output stream; caller holds execution ownership. */ void net_loopback_proc_emit(struct text_stream *s); -/** @brief Emit UNIX sockets under caller execution ownership, without pointers. +/** @brief Emit UNIX sockets from the caller's network namespace without pointers. * @param s Required output stream; abstract names use the Linux @ convention. */ void unix_proc_emit(struct text_stream *s); diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index eaa95d64..a9fea313 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -536,6 +536,8 @@ struct task { struct task_identity *identity_token; /* Owned UTS scope, retained across exec and until task retirement. */ struct uts_namespace *uts_ns; + /* Owned network scope, retained independently by each created socket. */ + struct net_namespace *net_ns; /* Owned non-root membership or zombie charge, protected by scheduler_lock. */ struct cgroup *cgroup; uint64_t proc_read_chars, proc_write_chars, proc_read_calls, proc_write_calls; diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index 13916d11..03e8d4c6 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -188,7 +188,8 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) * A new mount graph retains the candidate user scope or the parent's current * scope and locks inherited attachments when its owner changes. * CLONE_NEWUTS copies names into a scope owned by the candidate user namespace. - * Other children share the source UTS scope. Every rollback releases both scopes. + * Other children share the source UTS scope. Network identity is shared by every + * child. Every rollback releases its retained namespace references. */ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flags, uint64_t stack, uint64_t parent_tid, @@ -259,6 +260,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag *child = *parent; child->user_ns = user_namespace_get(parent->user_ns); child->uts_ns = flags & CLONE_NEWUTS ? uts_ns : uts_namespace_get(parent->uts_ns); + child->net_ns = net_namespace_get(parent->net_ns); uts_ns = NULL; if (user_ns) { sched_task_user_namespace_install(child, user_ns); @@ -617,6 +619,8 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag child->user_ns = NULL; uts_namespace_put(child->uts_ns); child->uts_ns = NULL; + net_namespace_put(child->net_ns); + child->net_ns = NULL; if (!child->shared_mm) { address_space_destroy(sched_task_as(child)); sched_task_vma_release(child); diff --git a/kernel/sched/internal.h b/kernel/sched/internal.h index e31bf678..f6cf1a1c 100644 --- a/kernel/sched/internal.h +++ b/kernel/sched/internal.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include diff --git a/kernel/sched/session.c b/kernel/sched/session.c index afca51af..30aa5607 100644 --- a/kernel/sched/session.c +++ b/kernel/sched/session.c @@ -19,7 +19,7 @@ void task_copy_identity_text(char *dst, size_t cap, const char *src) } /** - * @brief Clear task identity and capabilities while retaining its owning user namespace. + * @brief Clear task identity and capabilities while retaining its namespaces. * @param task Execution-owned task, nullable. Releases supplemental groups. */ void task_clear_identity(struct task *task) @@ -53,8 +53,8 @@ void task_clear_identity(struct task *task) * @brief Inherit identity and independent filesystem references from a parent. * @param task New task with private filesystem state under execution ownership. * @param parent Stable source task; NULL leaves the destination unchanged. - * Retains supplemental groups, user and UTS namespaces and mount/dentry references - * without allocating or resolving cached path strings. The destination initially + * Retains supplemental groups, user, UTS and network namespaces, and mount/dentry + * references without allocating or resolving cached path strings. The destination initially * has no owned credential references. Caller serializes publication with scheduler_lock. */ void task_copy_identity_from_parent(struct task *task, const struct task *parent) @@ -64,6 +64,7 @@ void task_copy_identity_from_parent(struct task *task, const struct task *parent } task->user_ns = user_namespace_get(parent->user_ns); task->uts_ns = uts_namespace_get(parent->uts_ns); + task->net_ns = net_namespace_get(parent->net_ns); task->uid = parent->uid; task->gid = parent->gid; task->euid = parent->euid; diff --git a/kernel/sched/task.c b/kernel/sched/task.c index 5f084817..19fd2413 100644 --- a/kernel/sched/task.c +++ b/kernel/sched/task.c @@ -213,6 +213,8 @@ struct task *alloc_task_slot(void) tasks[i]->user_ns = NULL; uts_namespace_put(tasks[i]->uts_ns); tasks[i]->uts_ns = NULL; + net_namespace_put(tasks[i]->net_ns); + tasks[i]->net_ns = NULL; struct sched_task_object *object = (struct sched_task_object *)tasks[i]; object->futex_exit = (struct futex_exit_cursor){0}; object->exec_prepared = NULL; diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index 44a0d6fa..a6a0a326 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -298,6 +298,8 @@ static int64_t sched_wait_child(uint32_t waiter_pid, int32_t wanted_pid, reap_task->user_ns = NULL; uts_namespace_put(reap_task->uts_ns); reap_task->uts_ns = NULL; + net_namespace_put(reap_task->net_ns); + reap_task->net_ns = NULL; task_release_limits(reap_task); reap_task->flags &= ~(TASK_FLAG_WAITABLE_CHILD | TASK_FLAG_REAP_IN_PROGRESS); task_copy_name(reap_task, "reaped"); diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 7196e788..fc7b0603 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -3,6 +3,7 @@ #include #include "unix_path.h" #include +#include #include #include #include @@ -131,6 +132,7 @@ enum unix_socket_state { UNIX_SOCKET_OPEN = 0, UNIX_SOCKET_LISTEN = 1, UNIX_SOCKET_CONNECTED = 2 }; struct unix_socket { + struct net_namespace *net_ns; /* Owned creating scope, independent of owner_pid. */ uint32_t used; uint32_t refs; uint32_t gc_roots; @@ -396,20 +398,22 @@ static struct unix_socket *unix_from_handle(uint32_t handle) /** * @brief Find a bound AF_UNIX endpoint by abstract or filesystem address. + * @param ns Borrowed creating network namespace used for abstract names. * @param path User-visible socket address bytes. * @param length Address byte count. * @param object Held filesystem inode, NULL for counted abstract names. * Serialized execution context; compares actual provider identity without I/O. * @return Matching live socket, or null when no endpoint is bound. */ -static struct unix_socket *unix_find_path(const char *path, uint32_t length, const struct vfs_path *object) +static struct unix_socket *unix_find_path(struct net_namespace *ns, const char *path, + uint32_t length, const struct vfs_path *object) { for (struct unix_socket *socket = unix_sockets; socket; socket = socket->registry_next) { if (!socket || !socket->used || !socket->bound || !socket->path_len) continue; if (object && vfs_path_node(object)) { if (vfs_path_same_inode(&socket->bound_inode,object)) return socket; - } else if (!socket->path[0] && socket->path_len == length) { + } else if (socket->net_ns == ns && !socket->path[0] && socket->path_len == length) { uint32_t j; for (j = 0; j < length && path[j] == socket->path[j]; ++j) {} if (j == length) return socket; @@ -418,7 +422,7 @@ static struct unix_socket *unix_find_path(const char *path, uint32_t length, con return NULL; } -/** @brief Assign a currently unused counted abstract name to an unbound socket. +/** @brief Assign an unused counted abstract name within the socket's network scope. * @param socket Borrowed execution-owned endpoint; existing names stay intact. * No filesystem lookup, allocation or provider reference is involved. */ @@ -431,7 +435,7 @@ static void unix_autobind(struct unix_socket *socket) socket->path[0] = 0; for (unsigned i = 0; i < 5; ++i) socket->path[i + 1] = "0123456789abcdef"[(id >> (4 * i)) & 15]; - } while (unix_find_path(socket->path, 6, NULL)); + } while (unix_find_path(socket->net_ns, socket->path, 6, NULL)); socket->path_len = 6; socket->bound = true; } @@ -461,9 +465,10 @@ static int unix_address_out(const struct unix_socket *socket, uint64_t address, * @brief Allocate and register a stable AF_UNIX socket object. * @param owner_pid Socket owner process identifier. * @param type Socket type. + * @param ns Borrowed creating network namespace, retained until final release. * @return New socket or null when either object or handle allocation fails. */ -static struct unix_socket *unix_alloc(uint32_t owner_pid, uint32_t type) +static struct unix_socket *unix_alloc(uint32_t owner_pid, uint32_t type, struct net_namespace *ns) { struct unix_socket *socket = NULL; socket = (struct unix_socket *)kernel_malloc(sizeof(*socket)); @@ -473,6 +478,7 @@ static struct unix_socket *unix_alloc(uint32_t owner_pid, uint32_t type) .state = UNIX_SOCKET_OPEN, .type = type, .receive_timeout = UINT64_MAX, .send_timeout = UINT64_MAX, .receive_lowwater = 1, + .net_ns = net_namespace_get(ns), }; struct task *owner = sched_find(owner_pid); if (owner) socket->credentials = (struct ucred){(int32_t)sched_task_tgid(owner), owner->euid, owner->egid}; @@ -480,6 +486,7 @@ static struct unix_socket *unix_alloc(uint32_t owner_pid, uint32_t type) socket->handle = kernel_object_insert(kernel_objects(), socket, KERNEL_OBJECT_SOCKET); if (!socket->handle) { + net_namespace_put(socket->net_ns); kernel_free(socket); return NULL; } @@ -531,8 +538,8 @@ static bool unix_stream_retire_tx(struct unix_socket *socket, uint64_t limit) /** * @brief Drop one AF_UNIX socket reference and remove its final object safely. * @param handle Stable kernel object handle, ignored when already retired. - * Final teardown releases the bound inode and its provider after removing the - * endpoint from the registry. Serialized task context; no graph/module lock + * Final teardown releases the bound inode, its provider and network scope after + * removing the endpoint from the registry. Serialized task context; no graph/module lock * spans final backend puts or peer wakeups. */ static void unix_release_handle(uint32_t handle) @@ -582,6 +589,7 @@ static void unix_release_handle(uint32_t handle) while (*link && *link != socket) link = &(*link)->registry_next; if (*link == socket) *link = socket->registry_next; vfs_path_put(&socket->bound_inode); + net_namespace_put(socket->net_ns); kernel_free(socket); } @@ -914,7 +922,7 @@ static int unix_packet_peer(struct unix_socket *socket, const void *address, (uintptr_t)address,length,false,&target); if(result)return result; if(!target.length)return -RELIEFOS_EINVAL; - *out=unix_find_path(target.path,target.length,&target.object); + *out=unix_find_path(socket->net_ns,target.path,target.length,&target.object); vfs_path_put(&target.object); if (!*out) return -LINUX_ECONNREFUSED; if ((*out)->type != socket->type) return -LINUX_EPROTOTYPE; @@ -2949,7 +2957,7 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, if ((int)a0 != AF_UNIX) return -LINUX_EAFNOSUPPORT; if (type != SOCK_STREAM && type != SOCK_DGRAM && type != SOCK_SEQPACKET) return -LINUX_ESOCKTNOSUPPORT; if (a2 != 0 && a2 != AF_UNIX) return -LINUX_EPROTONOSUPPORT; - socket = unix_alloc(task->pid, type); + socket = unix_alloc(task->pid, type, task->net_ns); if (!socket) return -RELIEFOS_ENOMEM; { int fd = unix_alloc_fd(task, socket); @@ -2976,9 +2984,9 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, (a2 != 0 && a2 != AF_UNIX) || (a1 & ~(uint32_t)(15 | SOCK_NONBLOCK | SOCK_CLOEXEC))) { return -RELIEFOS_EINVAL; } - left = unix_alloc(task->pid, type); + left = unix_alloc(task->pid, type, task->net_ns); if (!left) return -RELIEFOS_ENOMEM; - right = unix_alloc(task->pid, type); + right = unix_alloc(task->pid, type, task->net_ns); if (!right) { unix_release_handle(left->handle); return -RELIEFOS_ENOMEM; @@ -3018,7 +3026,7 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, int ret=syscall_unix_address(task_lookup_namespace(task), task,a1,(uint32_t)a2,true,&target); if(ret)return ret; if(!target.length){unix_autobind(socket);return 0;} - if(!vfs_path_node(&target.object) && unix_find_path(target.path,target.length,NULL)) + if(!vfs_path_node(&target.object) && unix_find_path(socket->net_ns,target.path,target.length,NULL)) return -RELIEFOS_EADDRINUSE; socket->bound_inode=target.object; for(unsigned i=0;ipath[i]=target.path[i]; @@ -3069,7 +3077,7 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, if (ret == -RELIEFOS_EAGAIN) return KERNEL_SYSCALL_UNIX_CONNECT_IO_WAIT; if(ret)return ret; if(!target.length)return -RELIEFOS_EINVAL; - listener=unix_find_path(target.path,target.length,&target.object); + listener=unix_find_path(socket->net_ns,target.path,target.length,&target.object); vfs_path_put(&target.object); if (listener && listener->type != socket->type) return -LINUX_EPROTOTYPE; if (!listener || listener->state != UNIX_SOCKET_LISTEN) return -LINUX_ECONNREFUSED; @@ -3079,7 +3087,7 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, } ret = unix_pending_reserve(listener, listener->pending_count + 1u); if (ret < 0) return ret; - server = unix_alloc(listener->owner_pid, listener->type); + server = unix_alloc(listener->owner_pid, listener->type, listener->net_ns); if (!server) return -RELIEFOS_ENOMEM; server->state = UNIX_SOCKET_CONNECTED; server->passcred = listener->passcred; @@ -3496,15 +3504,17 @@ int64_t syscall_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, return unix_socket_dispatch(number, a0, a1, a2, a3); } -/** @brief Render live UNIX socket metadata with no kernel pointer disclosure. +/** @brief Render live UNIX socket metadata in the caller's network namespace. * @param s Required slice; caller holds execution ownership over registry. * References, type, state and names come from actual live socket objects. */ void unix_proc_emit(struct text_stream *s) { + const struct task *task = sched_current_task(); + struct net_namespace *ns = task ? task->net_ns : NULL; text_string(s, "Num RefCount Protocol Flags Type St Inode Path\n"); for (struct unix_socket *u = unix_sockets; u; u = u->registry_next) { - if (!u->used) + if (!u->used || u->net_ns != ns) continue; text_string(s, "0000000000000000: "); text_hex(s, u->refs, 8); diff --git a/net/Kbuild b/net/Kbuild index 90dfee36..65defe88 100644 --- a/net/Kbuild +++ b/net/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := interface/ ipv4/ ipv6/ link/ services/ socket/ tcp/ core.o input.o utility.o proc.o +obj-y := interface/ ipv4/ ipv6/ link/ namespace/ services/ socket/ tcp/ core.o input.o utility.o proc.o include $(srctree)/scripts/Makefile.module diff --git a/net/namespace/Kbuild b/net/namespace/Kbuild new file mode 100644 index 00000000..64af3d88 --- /dev/null +++ b/net/namespace/Kbuild @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: Apache-2.0 +obj-y := namespace.o + +include $(srctree)/scripts/Makefile.module diff --git a/net/namespace/namespace.c b/net/namespace/namespace.c new file mode 100644 index 00000000..3939b4bc --- /dev/null +++ b/net/namespace/namespace.c @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include +#include +#include +#include + +/** @copydoc net_namespace_create */ +int net_namespace_create(struct user_namespace *owner, struct net_namespace **out) +{ + if (!out) return -LINUX_EINVAL; + *out = NULL; + struct net_namespace *ns = kernel_malloc(sizeof(*ns)); + if (!ns) return -LINUX_ENOMEM; + *ns = (struct net_namespace){.references = 1, .user_ns = user_namespace_get(owner)}; + *out = ns; + return 0; +} + +/** @copydoc net_namespace_get */ +struct net_namespace *net_namespace_get(struct net_namespace *ns) +{ + if (ns) __atomic_add_fetch(&ns->references, 1, __ATOMIC_RELAXED); + return ns; +} + +/** @copydoc net_namespace_put */ +void net_namespace_put(struct net_namespace *ns) +{ + if (!ns || __atomic_sub_fetch(&ns->references, 1, __ATOMIC_ACQ_REL)) return; + user_namespace_put(ns->user_ns); + kernel_free(ns); +} diff --git a/tools/test_ipv6_transport.py b/tools/test_ipv6_transport.py index c759b358..72caf7ad 100644 --- a/tools/test_ipv6_transport.py +++ b/tools/test_ipv6_transport.py @@ -21,6 +21,7 @@ "tools/tests/ipv6_vector_test.c", "tools/tests/ipv6_vector_stubs.c", "kernel/syscall/io/vector.c", "kernel/syscall/ipc/socket.c", "kernel/sched/user_namespace.c", + "net/namespace/namespace.c", "kernel/syscall/fs/lookup_state.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) binary = out / "ipv6_tcp_test" diff --git a/tools/test_linux_socket_batches.py b/tools/test_linux_socket_batches.py index 49f6f1e3..30dfe5e4 100644 --- a/tools/test_linux_socket_batches.py +++ b/tools/test_linux_socket_batches.py @@ -17,7 +17,7 @@ subprocess.run(["cc", "-std=c11", "-g", "-O1", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude", "-Iinclude/uapi", - "-Iinclude", "tools/tests/socket_batch_unix_test.c", "kernel/sched/user_namespace.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "-o", output], + "-Iinclude", "tools/tests/socket_batch_unix_test.c", "kernel/sched/user_namespace.c", "net/namespace/namespace.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "-o", output], cwd=root, check=True) subprocess.run([output], cwd=root, check=True, timeout=20) output = str(Path(directory) / "socket_batch_abi") diff --git a/tools/test_poll_wakeup.py b/tools/test_poll_wakeup.py index e82d8c07..6e17fcc8 100644 --- a/tools/test_poll_wakeup.py +++ b/tools/test_poll_wakeup.py @@ -17,6 +17,7 @@ "-Iinclude", "tools/tests/poll_wakeup_test.c", *kernel_sources("syscall_dispatch"), "kernel/sched/identity.c", "kernel/syscall/process/pidfd.c", + "kernel/sched/user_namespace.c", "net/namespace/namespace.c", "kernel/sync/wait.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "-o", str(binary), ], cwd=ROOT, check=True) subprocess.run([str(binary)], cwd=ROOT, check=True, timeout=20) diff --git a/tools/tests/descriptor_table_test.c b/tools/tests/descriptor_table_test.c index 92298ae9..31c1d0a6 100644 --- a/tools/tests/descriptor_table_test.c +++ b/tools/tests/descriptor_table_test.c @@ -10,6 +10,7 @@ #include #include #include +#include #include "../../fs/fs_internal.h" #include /** @brief Keep device discovery outside this descriptor-table fixture. @@ -635,7 +636,7 @@ static void test_unix_socket_registry_growth(void) enum { SOCKETS = 40 }; struct unix_socket *sockets[SOCKETS]; for (unsigned i = 0; i < SOCKETS; ++i) { - sockets[i] = unix_alloc(1000u + i, SOCK_DGRAM); + sockets[i] = unix_alloc(1000u + i, SOCK_DGRAM, NULL); assert(sockets[i]); for (unsigned j = 0; j < i; ++j) { assert(sockets[i] != sockets[j]); @@ -648,6 +649,113 @@ static void test_unix_socket_registry_growth(void) puts("PASS AF_UNIX registry grows beyond the former 32 sockets and releases stable handles"); } +/** @brief Preserve counted abstract names and socket scope across task changes. */ +static void test_unix_network_namespace(void) +{ + struct task *task = descriptor_audio_task(1802); + struct user_namespace *owner = NULL; + struct net_namespace *first = NULL, *second = NULL; + assert(!user_namespace_create(task, &owner)); + assert(!net_namespace_create(owner, &first)); + assert(!net_namespace_create(NULL, &second)); + assert(owner->references == 2 && first->references == 1 && second->references == 1); + assert(net_namespace_create(owner, NULL) == -LINUX_EINVAL); + struct net_namespace *failed = first; + fail_allocation = 1; + assert(net_namespace_create(owner, &failed) == -LINUX_ENOMEM && !failed); + fail_allocation = 0; + assert(owner->references == 2 && first->references == 1); + + descriptor_socket_task = task; + struct sockaddr_un address = {.sun_family = AF_UNIX}; + const char name[] = "scope\0counted"; + memcpy(address.sun_path + 1, name, sizeof(name) - 1); + socklen_t length = offsetof(struct sockaddr_un, sun_path) + sizeof(name); + int initial_fd = (int)syscall_socket_dispatch(__NR_socket, AF_UNIX, SOCK_DGRAM, 0, 0, 0, 0); + assert(initial_fd >= 0); + assert(!syscall_socket_dispatch(__NR_bind, initial_fd, (uintptr_t)&address, length, 0, 0, 0)); + + task->net_ns = net_namespace_get(first); + int first_fd = (int)syscall_socket_dispatch(__NR_socket, AF_UNIX, SOCK_DGRAM, 0, 0, 0, 0); + assert(first_fd >= 0); + assert(!syscall_socket_dispatch(__NR_bind, first_fd, (uintptr_t)&address, length, 0, 0, 0)); + int duplicate_fd = (int)syscall_socket_dispatch(__NR_socket, AF_UNIX, SOCK_DGRAM, 0, 0, 0, 0); + assert(duplicate_fd >= 0); + assert(syscall_socket_dispatch(__NR_bind, duplicate_fd, (uintptr_t)&address, length, 0, 0, 0) == -LINUX_EADDRINUSE); + + net_namespace_put(task->net_ns); + task->net_ns = net_namespace_get(second); + int second_fd = (int)syscall_socket_dispatch(__NR_socket, AF_UNIX, SOCK_DGRAM, 0, 0, 0, 0); + assert(second_fd >= 0); + struct unix_socket *first_socket = unix_from_file(task_file_for_fd(task, first_fd)); + struct unix_socket *second_socket = unix_from_file(task_file_for_fd(task, second_fd)); + struct unix_socket *peer = NULL; + assert(unix_packet_peer(second_socket, &address, length, &peer) == -LINUX_ECONNREFUSED); + assert(!syscall_socket_dispatch(__NR_bind, second_fd, (uintptr_t)&address, length, 0, 0, 0)); + assert(!unix_packet_peer(first_socket, &address, length, &peer) && peer == first_socket); + assert(!unix_packet_peer(second_socket, &address, length, &peer) && peer == second_socket); + + /* Transferring the OFD preserves its creator scope in a different task. */ + struct task_file transferred = {0}; + assert(!task_file_reference(&transferred, task_file_for_fd(task, first_fd))); + struct task *receiver = descriptor_audio_task(1803); + receiver->net_ns = net_namespace_get(second); + descriptor_socket_task = receiver; + assert(!unix_packet_peer(unix_from_file(task_file_description(&transferred)), &address, length, &peer)); + assert(peer == first_socket); + clear_task_file(&transferred); + net_namespace_put(receiver->net_ns); + free(receiver); + descriptor_socket_task = task; + + char proc[2048] = {0}, visible[64], hidden[64]; + struct text_stream stream = {.buffer = proc, .capacity = sizeof(proc) - 1}; + unix_proc_emit(&stream); + snprintf(visible, sizeof(visible), " %llu ", (unsigned long long)((1ULL << 60) | second_socket->handle)); + snprintf(hidden, sizeof(hidden), " %llu ", (unsigned long long)((1ULL << 60) | first_socket->handle)); + assert(strstr(proc, visible) && !strstr(proc, hidden)); + + /* A listener keeps its original scope even after its owner changes scope. */ + address.sun_path[1] = 'l'; + int listener_fd = (int)syscall_socket_dispatch(__NR_socket, AF_UNIX, SOCK_STREAM, 0, 0, 0, 0); + int client_fd = (int)syscall_socket_dispatch(__NR_socket, AF_UNIX, SOCK_STREAM, 0, 0, 0, 0); + assert(listener_fd >= 0 && client_fd >= 0); + assert(!syscall_socket_dispatch(__NR_bind, listener_fd, (uintptr_t)&address, length, 0, 0, 0)); + assert(!syscall_socket_dispatch(__NR_listen, listener_fd, 1, 0, 0, 0, 0)); + net_namespace_put(task->net_ns); + task->net_ns = net_namespace_get(first); + assert(!syscall_socket_dispatch(__NR_connect, client_fd, (uintptr_t)&address, length, 0, 0, 0)); + int accepted_fd = (int)syscall_socket_dispatch(__NR_accept, listener_fd, 0, 0, 0, 0, 0); + assert(accepted_fd >= 0); + memset(proc, 0, sizeof(proc)); + stream = (struct text_stream){.buffer = proc, .capacity = sizeof(proc) - 1}; + unix_proc_emit(&stream); + snprintf(hidden, sizeof(hidden), " %llu ", (unsigned long long)task_file_for_fd(task, accepted_fd)->socket_ino); + assert(!strstr(proc, hidden)); + + uint64_t references = first->references; + fail_allocation = 1; + assert(syscall_socket_dispatch(__NR_socket, AF_UNIX, SOCK_STREAM, 0, 0, 0, 0) == -LINUX_ENOMEM); + fail_allocation = 0; + assert(first->references == references); + struct task_file *occupied; + while (task_allocate_fd(task, 0, &occupied) >= 0) {} + assert(syscall_socket_dispatch(__NR_socket, AF_UNIX, SOCK_STREAM, 0, 0, 0, 0) == -LINUX_EMFILE); + assert(first->references == references); + syscall_release_task_files(task); + assert(!unix_sockets && first->references == 2 && second->references == 1); + net_namespace_put(task->net_ns); + task->net_ns = NULL; + net_namespace_put(first); + net_namespace_put(second); + assert(owner->references == 1); + user_namespace_put(owner); + sched_task_file_release(task); + descriptor_socket_task = NULL; + free(task); + puts("PASS network namespace owner, counted UNIX isolation, OFD transfer, accept scope and rollback"); +} + /** @brief Verify Linux AF_UNIX backlog zero, one, and negative boundaries. */ static void test_unix_listener_backlog_boundaries(void) { @@ -960,8 +1068,8 @@ static void test_audio_pcm_descriptions(void) static void descriptor_socket_pair(struct task *sender, struct task *receiver, int *send_fd, int *receive_fd) { - struct unix_socket *left = unix_alloc(sender->pid, SOCK_DGRAM); - struct unix_socket *right = unix_alloc(receiver->pid, SOCK_DGRAM); + struct unix_socket *left = unix_alloc(sender->pid, SOCK_DGRAM, sender->net_ns); + struct unix_socket *right = unix_alloc(receiver->pid, SOCK_DGRAM, receiver->net_ns); assert(left && right); left->state = right->state = UNIX_SOCKET_CONNECTED; left->peer_handle = right->handle; @@ -1368,6 +1476,41 @@ static void writer_namespace_close(struct vfs_namespace *ns,struct task *task,st assert(!vfs_namespace_destroy(ns) && !writer_path_pins); } +/** @brief Resolve shared filesystem socket inodes across network scopes. */ +static void test_unix_network_namespace_path(void) +{ + struct task *task = descriptor_audio_task(1804); + struct net_namespace *first = NULL, *second = NULL; + assert(!net_namespace_create(NULL, &first)); + assert(!net_namespace_create(NULL, &second)); + descriptor_inode = (struct storage_inode_ref){.references = 1, + .node = {.type = RELIEFOS_FS_TYPE_SOCKET, .first_cluster = 502}}; + struct vfs_namespace ns = {0}; + struct vfs_path root = {0}, path = {0}, alias = {0}; + writer_namespace_open(&ns, task, &root); + assert(!vfs_path_lookup(&ns, &root, &root, "module.ko", 0, &path)); + vfs_path_get(&path, &alias); + struct unix_socket *socket = unix_alloc(task->pid, SOCK_DGRAM, first); + assert(socket); + socket->bound = true; + socket->path_len = sizeof("module.ko"); + memcpy(socket->path, "module.ko", socket->path_len); + vfs_path_get(&path, &socket->bound_inode); + assert(unix_find_path(second, "module.ko", sizeof("module.ko"), &alias) == socket); + assert(unix_find_path(NULL, "renamed", sizeof("renamed"), &alias) == socket); + assert(!unix_find_path(second, "module.ko", sizeof("module.ko"), NULL)); + unix_release_handle(socket->handle); + assert(first->references == 1 && second->references == 1); + vfs_path_put(&alias); + vfs_path_put(&path); + writer_namespace_close(&ns, task, &root); + net_namespace_put(first); + net_namespace_put(second); + sched_task_file_release(task); + free(task); + puts("PASS filesystem UNIX inode identity remains reachable across network scopes"); +} + /** @brief Catch raw local chown IDs, partial mutation and changed lookup errors. */ static void test_namespace_chown(void) { @@ -3447,6 +3590,8 @@ int main(void) test_nonblocking_drm_read_dispatch(); test_audio_write_batch(); kernel_objects_init(); + test_unix_network_namespace(); + test_unix_network_namespace_path(); test_unix_socket_registry_growth(); test_unix_listener_backlog_boundaries(); test_unix_listener_backlog_growth(); diff --git a/tools/tests/modules/scheduler.h b/tools/tests/modules/scheduler.h index c1404e04..15aeed47 100644 --- a/tools/tests/modules/scheduler.h +++ b/tools/tests/modules/scheduler.h @@ -27,6 +27,7 @@ static void fixture_exec_other_exit(uint32_t pid, uint64_t code); #include "../../../kernel/sched/identity.c" #include "../../../kernel/sched/user_namespace.c" #include "../../../kernel/init/uts.c" +#include "../../../net/namespace/namespace.c" #include "../../../kernel/sched/user_namespace_task.c" #include "../../../kernel/sched/tables.c" #include "../../../kernel/sched/lookup.c" diff --git a/tools/tests/mount_namespace_task_test.c b/tools/tests/mount_namespace_task_test.c index d5701865..587cbbcd 100644 --- a/tools/tests/mount_namespace_task_test.c +++ b/tools/tests/mount_namespace_task_test.c @@ -100,6 +100,7 @@ static void retire_child(struct task *child) sched_task_identity_detach(child); user_namespace_put(child->user_ns); uts_namespace_put(child->uts_ns); + net_namespace_put(child->net_ns); task_zero(child); child->state = TASK_EXITED; child->running_cpu = SCHED_CPU_NONE; @@ -676,6 +677,9 @@ int main(void) uint64_t capability = 1ULL << CAP_SYS_ADMIN; parent->cap_permitted = capability; parent->cap_effective = capability; + struct net_namespace *network = NULL; + assert(!net_namespace_create(NULL, &network)); + parent->net_ns = network; for (unsigned versioned = 0; versioned < 2; ++versioned) { parent->cap_effective = 0; assert(clone_namespace(parent, user, versioned, CLONE_NEWNS) == -LINUX_EPERM); @@ -695,6 +699,7 @@ int main(void) mount_budget = -1; assert(mount_allocations == 2 && next_mount_id == mount_id); assert(!child->pid && child->state == TASK_EXITED && !child->identity_token); + assert(network->references == 1); assert(proc_created == before && charges == old_charges); assert(user->parent_tid == 0x44444444 && user->child_tid == 0x44444444); assert(ns.references == 1 && root->references == root_refs && volume->references == refs); @@ -708,7 +713,9 @@ int main(void) assert(((struct clone_operands *)mm_phys_to_virt(tid))->child_tid == (uint32_t)pid); assert(proc_created == before + 1 && charges == old_charges + 1); assert_snapshot(child, parent); + assert(child->net_ns == network && network->references == 2); retire_child(child); + assert(network->references == 1); assert(ns.references == 1 && root->references == root_refs && volume->references == refs); } struct user_namespace *user_scope; @@ -723,6 +730,7 @@ int main(void) assert(child->user_ns == user_scope && user_scope->references == 2); task_clear_identity(child); assert(child->user_ns == user_scope); + assert(child->net_ns == network && network->references == 2); retire_child(child); assert(user_scope->references == 1); } @@ -738,6 +746,9 @@ int main(void) check_mount_user_setns(parent); check_uts_creation(parent, child, user); check_uts_setns(parent); + assert(parent->net_ns == network && network->references == 1); + parent->net_ns = NULL; + net_namespace_put(network); sched_task_fs_release(parent); /* Retiring nsfs captures can enqueue their graphs and backing mounts. */ while (vfs_reclaim_mounts(16)) {} diff --git a/tools/tests/poll_wakeup_test.c b/tools/tests/poll_wakeup_test.c index 2fbfab7b..b53b459d 100644 --- a/tools/tests/poll_wakeup_test.c +++ b/tools/tests/poll_wakeup_test.c @@ -234,8 +234,8 @@ short audio_timer_poll(const struct task_file *file, short events) static void setup_socketpair(struct unix_socket **reader_out, struct unix_socket **writer_out) { - struct unix_socket *reader = unix_alloc(current.pid, SOCK_STREAM); - struct unix_socket *writer = unix_alloc(current.pid, SOCK_STREAM); + struct unix_socket *reader = unix_alloc(current.pid, SOCK_STREAM, current.net_ns); + struct unix_socket *writer = unix_alloc(current.pid, SOCK_STREAM, current.net_ns); assert(reader && writer); reader->state = writer->state = UNIX_SOCKET_CONNECTED; reader->peer_handle = writer->handle; From 1640744393e19890f246d50fe58f646750b39298 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 04:35:10 +0800 Subject: [PATCH 71/97] feat(net): scope netlink ports and delivery to network namespaces --- Documentation/core-api/mount-namespaces.rst | 13 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 20 +- .../LC_MESSAGES/userspace-api/descriptors.po | 4 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 20 +- .../LC_MESSAGES/userspace-api/descriptors.po | 4 +- Documentation/userspace-api/descriptors.rst | 2 +- include/reliefnt/netlink.h | 10 +- net/socket/netlink.c | 53 +++-- tools/test_ipv6_control.py | 1 + tools/tests/ipv6_control_test.c | 184 ++++++++++++++++++ 10 files changed, 276 insertions(+), 35 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index a68ff001..e42727ff 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -158,9 +158,18 @@ hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护 网络空间生命周期 ================ -``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,监听端创建的服务端连接继承监听端空间。 +``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。 -当前网络身份提供 Unix 抽象地址和 proc 枚举的作用域。接口、路由、IPv4/IPv6、TCP/UDP 与 netlink 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。 +当前网络身份为 Unix 抽象地址、proc 枚举和 netlink 端口及消息投递提供作用域。接口、路由与 IPv4/IPv6、TCP/UDP 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。 + +netlink 端口与事件 +================== + +``NETLINK_ROUTE`` 和 ``NETLINK_KOBJECT_UEVENT`` 的端口绑定按网络空间和协议匹配,显式端口与自动端口采用相同规则。传递文件描述符或调用任务切换空间后,套接字使用创建时保留的空间;最后一个打开文件描述释放空间引用。套接字分配或文件描述符分配失败时回收候选状态。 + +udev 的用户态组 2 多播和 worker 端口单播只投递到发送套接字所属空间。接收者位于其他空间时,单播返回 ``ECONNREFUSED``。发送要求初始用户空间的 ``CAP_NET_ADMIN``。全局设备的内核组 1 通知投递到由初始用户空间拥有的网络空间,使用子用户空间作为 owner 的网络空间不接收此类未标记通知。 + +当前接口、地址和路由表属于初始网络空间,相应的路由通知与 ``ENOBUFS`` 丢失报告只投递到该空间的订阅者。其首个路由订阅者建立快照基线,最后一个订阅者离开时释放基线。其他空间的订阅和关闭不延长该基线的生命周期。 凭据权限作用域 ============== diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 45e548f4..57089eb6 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -448,8 +448,20 @@ msgstr "``struct uts_namespace`` uses atomic reference counting. Tasks and nsfs msgid "网络空间生命周期" msgstr "Network namespace lifetime" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,监听端创建的服务端连接继承监听端空间。" -msgstr "``net_namespace_create()`` creates a reference-counted network identity with an immutable user owner. A null pointer denotes the permanent initial network namespace. Tasks share the identity on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix socket independently retains its creating network namespace until its final reference closes. Server connections inherit the listener namespace." +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" +msgstr "``net_namespace_create()`` creates a reference-counted network identity with an immutable user owner. A null pointer denotes the permanent initial network namespace. Tasks share the identity on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix and netlink socket independently retains its creating network namespace until its final reference closes. Unix server connections inherit the listener namespace." -msgid "当前网络身份提供 Unix 抽象地址和 proc 枚举的作用域。接口、路由、IPv4/IPv6、TCP/UDP 与 netlink 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。" -msgstr "The current network identity scopes Unix abstract addresses and proc enumeration. Interface, route, IPv4/IPv6, TCP/UDP and netlink state isolation are subsequent integration steps. Clone requests using ``CLONE_NEWNET`` return ``EPERM`` or ``EINVAL`` according to authority. Unshare requests return ``EINVAL``. Userspace creation and switching will be connected after complete network state isolation." +msgid "当前网络身份为 Unix 抽象地址、proc 枚举和 netlink 端口及消息投递提供作用域。接口、路由与 IPv4/IPv6、TCP/UDP 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。" +msgstr "The current network identity scopes Unix abstract addresses, proc enumeration, netlink ports and message delivery. Interface, route, IPv4/IPv6 and TCP/UDP state isolation are subsequent integration steps. Clone requests using ``CLONE_NEWNET`` return ``EPERM`` or ``EINVAL`` according to authority. Unshare requests return ``EINVAL``. Userspace creation and switching will be connected after complete network state isolation." + +msgid "netlink 端口与事件" +msgstr "Netlink ports and events" + +msgid "``NETLINK_ROUTE`` 和 ``NETLINK_KOBJECT_UEVENT`` 的端口绑定按网络空间和协议匹配,显式端口与自动端口采用相同规则。传递文件描述符或调用任务切换空间后,套接字使用创建时保留的空间;最后一个打开文件描述释放空间引用。套接字分配或文件描述符分配失败时回收候选状态。" +msgstr "``NETLINK_ROUTE`` and ``NETLINK_KOBJECT_UEVENT`` match bound ports by network namespace and protocol. Explicit and automatic ports follow the same rule. After descriptor transfer or a caller namespace change, sockets use their retained creating namespace. The final open file description releases that reference. Socket or descriptor allocation failure reclaims candidate state." + +msgid "udev 的用户态组 2 多播和 worker 端口单播只投递到发送套接字所属空间。接收者位于其他空间时,单播返回 ``ECONNREFUSED``。发送要求初始用户空间的 ``CAP_NET_ADMIN``。全局设备的内核组 1 通知投递到由初始用户空间拥有的网络空间,使用子用户空间作为 owner 的网络空间不接收此类未标记通知。" +msgstr "Userspace udev group 2 multicast and worker-port unicast stay within the sending socket's namespace. Unicast returns ``ECONNREFUSED`` when the receiver exists only in another namespace. Sending requires ``CAP_NET_ADMIN`` in the initial user namespace. Kernel group 1 notifications for global devices reach network namespaces owned by the initial user namespace. Networks owned by child user namespaces do not receive these untagged notifications." + +msgid "当前接口、地址和路由表属于初始网络空间,相应的路由通知与 ``ENOBUFS`` 丢失报告只投递到该空间的订阅者。其首个路由订阅者建立快照基线,最后一个订阅者离开时释放基线。其他空间的订阅和关闭不延长该基线的生命周期。" +msgstr "The current interface, address and route tables belong to the initial network namespace. Route notifications and ``ENOBUFS`` loss reports reach only its subscribers. Its first route subscriber establishes a snapshot baseline, and its final subscriber releases that baseline. Subscriptions and closes in other namespaces do not extend its lifetime." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index d2ca6d63..7181e62e 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -272,13 +272,13 @@ msgstr "" msgid "" "``AF_UNIX`` 和 ``AF_NETLINK`` 的 ``SOL_SOCKET/SO_REUSEADDR`` 使用原生 32 位 " "整数,默认读回 0;设置非零值后读回 1,设置 0 清除。该状态不改变地址绑定规则: " -"UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 " +"UNIX 地址和同一网络空间、同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 " "监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。" msgstr "" "``SOL_SOCKET/SO_REUSEADDR`` on ``AF_UNIX`` and ``AF_NETLINK`` uses a native " "32-bit integer. It reads as 0 by default, reads as 1 after setting a nonzero " "value, and is cleared by setting 0. This state does not change binding rules: " -"UNIX addresses and netlink ports within the same protocol still cannot be bound " +"UNIX addresses and netlink ports within the same network namespace and protocol still cannot be bound " "twice. UNIX ``accept`` does not inherit the listener's option. Netlink group " "membership, permissions, and filtering are unchanged." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 003eaafa..5ab14dc9 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -393,8 +393,20 @@ msgstr "``struct uts_namespace`` はアトミックな参照カウントを使 msgid "网络空间生命周期" msgstr "ネットワーク名前空間の寿命" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,监听端创建的服务端连接继承监听端空间。" -msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク識別を作成します。空ポインターは永続的な初期ネットワーク名前空間を表します。タスクは fork 時に識別を共有し、exec と ID のクリア後も参照を保持し、wait による回収またはスロット再利用時に解放します。各 Unix ソケットは作成時のネットワーク名前空間を独立して保持し、最後の参照を閉じると解放します。サーバー側の接続はリスナーの名前空間を継承します。" +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" +msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク識別を作成します。空ポインターは永続的な初期ネットワーク名前空間を表します。タスクは fork 時に識別を共有し、exec と ID のクリア後も参照を保持し、wait による回収またはスロット再利用時に解放します。各 Unix および netlink ソケットは作成時のネットワーク名前空間を独立して保持し、最後の参照を閉じると解放します。Unix のサーバー側接続はリスナーの名前空間を継承します。" -msgid "当前网络身份提供 Unix 抽象地址和 proc 枚举的作用域。接口、路由、IPv4/IPv6、TCP/UDP 与 netlink 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。" -msgstr "現在のネットワーク識別は Unix 抽象アドレスと proc 列挙のスコープを提供します。インターフェイス、経路、IPv4/IPv6、TCP/UDP、netlink の状態分離は後続の統合作業です。``CLONE_NEWNET`` を指定した clone は権限に応じて ``EPERM`` または ``EINVAL`` を返し、unshare は ``EINVAL`` を返します。ネットワーク状態の分離が完了した後で、ユーザー空間の作成と切り替え入口を接続します。" +msgid "当前网络身份为 Unix 抽象地址、proc 枚举和 netlink 端口及消息投递提供作用域。接口、路由与 IPv4/IPv6、TCP/UDP 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。" +msgstr "現在のネットワーク識別は Unix 抽象アドレス、proc 列挙、netlink ポートとメッセージ配信のスコープを提供します。インターフェイス、経路、IPv4/IPv6、TCP/UDP の状態分離は後続の統合作業です。``CLONE_NEWNET`` を指定した clone は権限に応じて ``EPERM`` または ``EINVAL`` を返し、unshare は ``EINVAL`` を返します。ネットワーク状態の分離が完了した後で、ユーザー空間の作成と切り替え入口を接続します。" + +msgid "netlink 端口与事件" +msgstr "netlink のポートとイベント" + +msgid "``NETLINK_ROUTE`` 和 ``NETLINK_KOBJECT_UEVENT`` 的端口绑定按网络空间和协议匹配,显式端口与自动端口采用相同规则。传递文件描述符或调用任务切换空间后,套接字使用创建时保留的空间;最后一个打开文件描述释放空间引用。套接字分配或文件描述符分配失败时回收候选状态。" +msgstr "``NETLINK_ROUTE`` と ``NETLINK_KOBJECT_UEVENT`` のポートバインドは、ネットワーク名前空間とプロトコルで照合します。明示的なポートと自動割り当てポートは同じ規則に従います。FD の受け渡しや呼び出し元の名前空間変更後も、ソケットは作成時に保持した名前空間を使用します。最後のオープンファイル記述がその参照を解放します。ソケットまたは FD の割り当てに失敗した場合は候補状態を回収します。" + +msgid "udev 的用户态组 2 多播和 worker 端口单播只投递到发送套接字所属空间。接收者位于其他空间时,单播返回 ``ECONNREFUSED``。发送要求初始用户空间的 ``CAP_NET_ADMIN``。全局设备的内核组 1 通知投递到由初始用户空间拥有的网络空间,使用子用户空间作为 owner 的网络空间不接收此类未标记通知。" +msgstr "udev のユーザー空間グループ 2 マルチキャストと worker ポートへのユニキャストは、送信ソケットの名前空間内にのみ配信します。受信先が他の名前空間にしか存在しない場合、ユニキャストは ``ECONNREFUSED`` を返します。送信には初期ユーザー名前空間の ``CAP_NET_ADMIN`` が必要です。グローバルデバイスのカーネルグループ 1 通知は、初期ユーザー名前空間が所有するネットワーク名前空間に配信します。子ユーザー名前空間が所有するネットワーク名前空間には、この未タグ付け通知を配信しません。" + +msgid "当前接口、地址和路由表属于初始网络空间,相应的路由通知与 ``ENOBUFS`` 丢失报告只投递到该空间的订阅者。其首个路由订阅者建立快照基线,最后一个订阅者离开时释放基线。其他空间的订阅和关闭不延长该基线的生命周期。" +msgstr "現在のインターフェイス、アドレス、経路テーブルは初期ネットワーク名前空間に属します。経路通知と ``ENOBUFS`` の欠落報告は、その購読者にのみ配信します。最初の経路購読者がスナップショットの基準を作成し、最後の購読者が離れると解放します。他の名前空間での購読やクローズは、この基準の寿命を延長しません。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index e090fc40..c3804e1b 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -236,12 +236,12 @@ msgstr "" msgid "" "``AF_UNIX`` 和 ``AF_NETLINK`` 的 ``SOL_SOCKET/SO_REUSEADDR`` 使用原生 32 位 " "整数,默认读回 0;设置非零值后读回 1,设置 0 清除。该状态不改变地址绑定规则: " -"UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 " +"UNIX 地址和同一网络空间、同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 " "监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。" msgstr "" "``AF_UNIX`` と ``AF_NETLINK`` の ``SOL_SOCKET/SO_REUSEADDR`` はネイティブの 32 ビット整数を使用します。" "既定値は 0 で、非ゼロの値を設定すると 1 が返り、0 を設定すると解除されます。" -"バインド規則は変わらず、UNIX アドレスと同一プロトコル内の netlink ポートの重複バインドはできません。" +"バインド規則は変わらず、UNIX アドレスと同一ネットワーク名前空間・プロトコル内の netlink ポートの重複バインドはできません。" "UNIX の ``accept`` はリスナーの設定を継承しません。netlink のグループへの参加、権限、フィルタリングは変わりません。" msgid "" diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index 62aafd6f..04719d5c 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -130,7 +130,7 @@ TCP 的 ``recvfrom/recvmsg`` 支持 ``MSG_PEEK``:重复预读保留相同的 ``AF_UNIX`` 和 ``AF_NETLINK`` 的 ``SOL_SOCKET/SO_REUSEADDR`` 使用原生 32 位 整数,默认读回 0;设置非零值后读回 1,设置 0 清除。该状态不改变地址绑定规则: -UNIX 地址和同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 +UNIX 地址和同一网络空间、同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。 ``AF_UNIX`` 流套接字的 ``SIOCOUTQ``(与 ``TIOCOUTQ`` 同号)向原生 32 位整数 diff --git a/include/reliefnt/netlink.h b/include/reliefnt/netlink.h index b6458615..c02bfb50 100644 --- a/include/reliefnt/netlink.h +++ b/include/reliefnt/netlink.h @@ -38,8 +38,12 @@ bool task_netlink_passcred(const struct task_file *file); /** @brief Check whether the recipient requested SOL_NETLINK/NETLINK_PKTINFO. * @param file Retained socket description. @return True when packet info is enabled. */ bool task_netlink_pktinfo(const struct task_file *file); -/* Publish KOBJ_CHANGE to group 1. All input is kernel-owned and is copied - * before return. properties contains NUL-terminated environment entries. */ +/** @brief Publish an untagged global KOBJ_CHANGE to kernel-event group 1. + * Networks owned by the initial user namespace receive the event. + * @param devpath Kernel-owned device path. @param subsystem Kernel subsystem name. + * @param properties Kernel-owned NUL-terminated environment entries. + * @param length Property bytes, copied before return under execution ownership. + */ void netlink_uevent_change(const char *devpath, const char *subsystem, const char *properties, uint32_t length); /** @brief Query queued datagrams and send readiness. @@ -48,7 +52,7 @@ short task_netlink_poll(const struct task_file *file,short events); /** @brief Inspect the next queued datagram size. * @param file Retained OFD. @return Bytes, zero or negative errno. */ int task_netlink_available(const struct task_file *file); -/** @brief Retire the final OFD and its owned queue. +/** @brief Retire the final OFD, its owned queue and creating network reference. * @param file Final OFD under execution ownership. */ void task_netlink_release(struct task_file *file); /** @brief Cancel a task's netlink wait without retaining user memory. diff --git a/net/socket/netlink.c b/net/socket/netlink.c index e4798bcf..3218d7de 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -40,6 +41,7 @@ struct netlink_message { }; struct netlink_socket { struct netlink_socket *next; + struct net_namespace *net_ns; /* Owned creating scope, independent of the FD holder. */ struct netlink_message *head, *tail; struct socket_filter *filter; uint32_t port, queued_bytes, groups; @@ -75,18 +77,19 @@ static bool nl_snapshot_ready; static struct netlink_socket *nl_socket(const struct task_file *file) { return file && file->kind == TASK_FILE_KIND_NETLINK ? (void *)(uintptr_t)file->aux : NULL; } -/** @brief Test a nonzero port against every bound endpoint. +/** @brief Test a nonzero port against bound endpoints in the creating scope. * @param port Proposed ID. @param except Socket excluded from the comparison. - * @return True when another socket in the protocol already owns it. */ + * @return True when another socket in the same namespace and protocol owns it. */ static bool nl_port_used(uint32_t port, const struct netlink_socket *except) { for (struct netlink_socket *s = netlink_sockets; s; s = s->next) - if (s != except && s->protocol == except->protocol && s->bound && s->port == port) + if (s != except && s->net_ns == except->net_ns && + s->protocol == except->protocol && s->bound && s->port == port) return true; return false; } -/** @brief Assign a unique kernel-chosen port to an unbound OFD. +/** @brief Assign a kernel-chosen port unique in an unbound OFD's creating scope. * @param s Socket. @param task Current task. @return Zero or ENOSPC. */ static int nl_autobind(struct netlink_socket *s, const struct task *task) { @@ -401,6 +404,7 @@ static int nl_initial_snapshot(void) } /** @brief Change membership transactionally, retaining an initialized query bitmap. + * Initial-network route subscribers own the current global interface baseline. * @param s Subscriber. @param groups New Linux group mask. @return Zero or errno. */ static int nl_set_groups(struct netlink_socket *s, uint32_t groups) { @@ -412,23 +416,23 @@ static int nl_set_groups(struct netlink_socket *s, uint32_t groups) return 0; } if (groups & ~NL_SUPPORTED_GROUPS) return -LINUX_EOPNOTSUPP; - if (groups) { int rc=nl_initial_snapshot(); if (rc) return rc; } + if (groups && !s->net_ns) { int rc=nl_initial_snapshot(); if (rc) return rc; } s->groups=groups; s->memberships_initialized |= groups != 0; if (!groups) { for (struct netlink_socket *it=netlink_sockets;it;it=it->next) - if (it->protocol == NETLINK_ROUTE && it->groups) return 0; + if (!it->net_ns && it->protocol == NETLINK_ROUTE && it->groups) return 0; nl_forget_snapshot(); } return 0; } -/** @brief Report notification loss to every interested subscriber. +/** @brief Report initial-network notification loss to its interested subscribers. * @param group Linux multicast group bit. */ static void nl_overrun(uint32_t group) { for (struct netlink_socket *s=netlink_sockets;s;s=s->next) - if (s->protocol == NETLINK_ROUTE && (s->groups & group)) s->overrun=true; + if (!s->net_ns && s->protocol == NETLINK_ROUTE && (s->groups & group)) s->overrun=true; kernel_poll_readiness_notify(); } @@ -463,7 +467,9 @@ static int nl_queue_datagram(struct netlink_socket *s, uint32_t port, uint32_t g return (int)admitted; } -/** @brief Fan out to subscribed sockets, reporting per-recipient queue overruns. +/** @brief Fan out within the sender's retained scope, reporting queue overruns. + * Kernel route notifications describe the initial network. Untagged global + * device events reach networks owned by the initial user namespace. * @param protocol Netlink protocol. @param group Linux group bit. * @param data Validated datagram. @param length Datagram length. * @param sender Sending socket, excluded from fanout, or NULL for kernel. @@ -473,9 +479,17 @@ static void nl_multicast(int protocol, uint32_t group, const void *data, uint32_ const struct netlink_socket *sender, const struct ucred *credentials) { bool notified = false; + const struct net_namespace *scope = sender ? sender->net_ns : NULL; + bool global_device_event = !sender && protocol == NETLINK_KOBJECT_UEVENT; for (struct netlink_socket *s = netlink_sockets; s; s = s->next) { if (s == sender || s->protocol != protocol || !(s->groups & group)) continue; + if (global_device_event) { + if (s->net_ns && s->net_ns->user_ns) + continue; + } else if (s->net_ns != scope) { + continue; + } int result = nl_queue_datagram(s, sender ? sender->port : 0, group, data, length, credentials); if (result < 0) s->overrun = true; @@ -485,6 +499,7 @@ static void nl_multicast(int protocol, uint32_t group, const void *data, uint32_ kernel_poll_readiness_notify(); } +/** @copydoc netlink_uevent_change */ void netlink_uevent_change(const char *devpath, const char *subsystem, const char *properties, uint32_t length) { @@ -536,7 +551,7 @@ static bool nl_same_route(const struct net_ipv6_route *a,const struct net_ipv6_r static bool nl_equal_route(const struct net_ipv6_route *a,const struct net_ipv6_route *b) { return nl_same_route(a,b) && a->metric==b->metric && a->flags==b->flags && a->valid_until==b->valid_until; } -/** @brief Queue a bounded native event for every subscribed OFD. +/** @brief Queue a bounded initial-network event for its subscribed OFDs. * @param group Linux group bit. @param type Message type. @param value Copied address, * route or Ethernet snapshot according to group. @param up Link readiness for link events. */ static void nl_publish(uint32_t group,uint16_t type,const void *value,bool up) @@ -544,7 +559,7 @@ static void nl_publish(uint32_t group,uint16_t type,const void *value,bool up) (void)up; bool interested=false; for (struct netlink_socket *s=netlink_sockets;s;s=s->next) - if (s->protocol == NETLINK_ROUTE && (s->groups & group)) { interested=true; break; } + if (!s->net_ns && s->protocol == NETLINK_ROUTE && (s->groups & group)) { interested=true; break; } if (!interested) return; struct netlink_message *message=kernel_malloc(sizeof(*message)+NL_MESSAGE_MAX); if (!message) { nl_overrun(group); return; } @@ -557,7 +572,7 @@ static void nl_publish(uint32_t group,uint16_t type,const void *value,bool up) kernel_free(message); } -/** @brief Diff owned address, route and link snapshots into multicast events. +/** @brief Diff initial-network address, route and link snapshots into its events. * Changes are detected under the existing execution owner; allocation failure * is surfaced as ENOBUFS to subscribers and the previous baseline is retained. */ void netlink_ipv6_changed(void) @@ -1005,7 +1020,7 @@ static int nl_request(struct nl_builder *b, const struct nlmsghdr *h) return 0; } -/** @brief Deliver a udev datagram to the userspace multicast group or a worker port. +/** @brief Deliver a udev datagram within its socket's retained creating scope. * @param sender Sending socket under execution ownership. @param data Validated bytes. * @param length Nonzero bounded payload size. @param address Explicit user destination. * @param address_length User address size. @return Bytes accepted or negative errno. @@ -1045,7 +1060,8 @@ static int nl_uevent_send(struct netlink_socket *sender, const void *data, uint3 } else { rc = -LINUX_ECONNREFUSED; for (struct netlink_socket *s = netlink_sockets; s; s = s->next) { - if (s->protocol != sender->protocol || !s->bound || s->port != dst.nl_pid) + if (s->net_ns != sender->net_ns || s->protocol != sender->protocol || + !s->bound || s->port != dst.nl_pid) continue; rc = nl_queue_datagram(s, sender->port, 0, payload, length, &credentials); if (rc > 0) @@ -1241,7 +1257,7 @@ int task_netlink_available(const struct task_file *file) return !s ? -LINUX_EBADF : s->head ? (int)s->head->length : 0; } -/** @brief Free final socket ownership, its filter and queued datagrams. +/** @brief Free final socket ownership, its namespace, filter and queued datagrams. * @param file Final OFD. */ void task_netlink_release(struct task_file *file) { @@ -1253,11 +1269,12 @@ void task_netlink_release(struct task_file *file) if (s->protocol == NETLINK_ROUTE && s->groups) { bool subscribers=false; for (struct netlink_socket *it=netlink_sockets;it;it=it->next) - if (it->protocol == NETLINK_ROUTE && it->groups) { subscribers=true; break; } + if (!it->net_ns && it->protocol == NETLINK_ROUTE && it->groups) { subscribers=true; break; } if (!subscribers) nl_forget_snapshot(); } while (s->head) { struct netlink_message *m=s->head; s->head=m->next; kernel_free(m); } kernel_free(s->filter); + net_namespace_put(s->net_ns); kernel_free(s); file->aux=0; } @@ -1344,6 +1361,7 @@ static int nl_protocol_option(struct task *task, struct netlink_socket *s, bool * @param a2 Third argument. @param a3 Fourth argument. @param a4 Fifth argument. * @param a5 Sixth argument. @return Syscall result or negative errno. * @note SO_REUSEADDR stores per-socket state without allowing duplicate ports. + * Published sockets retain their creating namespace after FD allocation succeeds. * Filter replacement is published only after the candidate is fully validated. */ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, uint64_t a3,uint64_t a4,uint64_t a5) @@ -1361,7 +1379,8 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, struct netlink_socket *s=kernel_malloc(sizeof(*s)); if (!s) return -LINUX_ENOMEM; struct task_file *file; int fd=task_allocate_fd(task,0,&file); if (fd<0) { kernel_free(s); return fd; } - *s=(struct netlink_socket){.next=netlink_sockets,.type=type,.protocol=(int)a2}; netlink_sockets=s; + *s=(struct netlink_socket){.next=netlink_sockets,.net_ns=net_namespace_get(task->net_ns), + .type=type,.protocol=(int)a2}; netlink_sockets=s; file->flags=TASK_FILE_FLAG_SOCKET|TASK_FILE_FLAG_SOCKET_INET|RELIEFOS_O_RDWR| ((a1&SOCK_NONBLOCK) ? RELIEFOS_O_NONBLOCK : 0); file->fd_flags=(a1&SOCK_CLOEXEC) ? RELIEFOS_FD_CLOEXEC : 0; diff --git a/tools/test_ipv6_control.py b/tools/test_ipv6_control.py index c7b7498d..53f21f1b 100644 --- a/tools/test_ipv6_control.py +++ b/tools/test_ipv6_control.py @@ -13,5 +13,6 @@ "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", "tools/tests/ipv6_control_test.c", "net/socket/filter.c", + "net/namespace/namespace.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 2a3b97fb..5edfbf8b 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -4,6 +4,7 @@ #include #include #include +#include #if __has_include("../../net/socket/netlink.c") #include "../../net/socket/netlink.c" #include "../../net/interface/state.c" @@ -180,6 +181,185 @@ static void check_dump_boundaries(int fd) assert(nl_socket(&files[fd])->queued_bytes==0); } +/** @brief Keep explicit and automatic netlink port bindings in their creating scope. */ +static void check_netlink_namespace_ports(void) +{ + const int protocols[] = {NETLINK_ROUTE, NETLINK_KOBJECT_UEVENT}; + for (unsigned i = 0; i < sizeof(protocols) / sizeof(protocols[0]); ++i) { + struct net_namespace *scope; + assert(!net_namespace_create(NULL, &scope)); + const struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_pid = 42}; + const struct sockaddr_nl automatic = {.nl_family = AF_NETLINK}; + int initial = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[i], 0, 0); + assert(initial >= 0); + assert(!call(__NR_bind, initial, (uintptr_t)&address, sizeof(address), 0, 0)); + current.net_ns = scope; + int isolated = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[i], 0, 0); + int duplicate = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[i], 0, 0); + assert(isolated >= 0 && duplicate >= 0); + assert(!call(__NR_bind, isolated, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(call(__NR_bind, duplicate, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EADDRINUSE); + current.pid = 42; + assert(!call(__NR_bind, duplicate, (uintptr_t)&automatic, sizeof(automatic), 0, 0)); + struct sockaddr_nl assigned = {0}; + uint32_t size = sizeof(assigned); + assert(!call(__NR_getsockname, duplicate, (uintptr_t)&assigned, (uintptr_t)&size, 0, 0)); + assert(assigned.nl_pid && assigned.nl_pid != 42); + task_netlink_release(&files[duplicate]); files[duplicate] = (struct task_file){0}; + task_netlink_release(&files[initial]); files[initial] = (struct task_file){0}; + current.net_ns = NULL; + initial = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[i], 0, 0); + assert(initial >= 0); + assert(!call(__NR_bind, initial, (uintptr_t)&automatic, sizeof(automatic), 0, 0)); + size = sizeof(assigned); + assert(!call(__NR_getsockname, initial, (uintptr_t)&assigned, (uintptr_t)&size, 0, 0)); + assert(assigned.nl_pid == 42); + assert(scope->references == 2); + net_namespace_put(scope); /* The moved socket now owns the last reference. */ + task_netlink_release(&files[isolated]); files[isolated] = (struct task_file){0}; + task_netlink_release(&files[initial]); files[initial] = (struct task_file){0}; + current = (struct task){0}; + assert(!allocations); + } + puts("PASS netlink namespace ports: explicit, automatic, moved FD and retained identity"); +} + +/** @brief Keep processed udev unicast and multicast in the sender socket's scope. */ +static void check_netlink_namespace_delivery(void) +{ + struct net_namespace *first, *second; + assert(!net_namespace_create(NULL, &first)); + assert(!net_namespace_create(NULL, &second)); + current.pid = 651; + current.cap_effective = 1ULL << CAP_NET_ADMIN; + const struct sockaddr_nl sender_address = {.nl_family = AF_NETLINK, .nl_pid = 42, .nl_groups = 2}; + const struct sockaddr_nl receiver_address = {.nl_family = AF_NETLINK, .nl_pid = 77, .nl_groups = 2}; + const struct sockaddr_nl multicast = {.nl_family = AF_NETLINK, .nl_groups = 2}; + const struct sockaddr_nl unicast = {.nl_family = AF_NETLINK, .nl_pid = 77}; + const struct sockaddr_nl absent = {.nl_family = AF_NETLINK, .nl_pid = 78}; + current.net_ns = first; + int sender = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT, 0, 0); + int receiver = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT, 0, 0); + assert(sender >= 0 && receiver >= 0); + assert(!call(__NR_bind, sender, (uintptr_t)&sender_address, sizeof(sender_address), 0, 0)); + assert(!call(__NR_bind, receiver, (uintptr_t)&receiver_address, sizeof(receiver_address), 0, 0)); + current.net_ns = second; + int other_sender = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT, 0, 0); + int other_receiver = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT, 0, 0); + assert(other_sender >= 0 && other_receiver >= 0); + assert(!call(__NR_bind, other_sender, (uintptr_t)&sender_address, sizeof(sender_address), 0, 0)); + assert(!call(__NR_bind, other_receiver, (uintptr_t)&receiver_address, sizeof(receiver_address), 0, 0)); + const char payload[] = "scoped-device"; + char output[64]; + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&multicast, sizeof(multicast)) == sizeof(payload)); + assert(receive(receiver, output, sizeof(output)) == sizeof(payload)); + assert(!memcmp(output, payload, sizeof(payload))); + assert(receive(sender, output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(other_sender, output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(other_receiver, output, sizeof(output)) == -LINUX_EAGAIN); + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&unicast, sizeof(unicast)) == sizeof(payload)); + assert(receive(receiver, output, sizeof(output)) == sizeof(payload)); + assert(receive(other_receiver, output, sizeof(output)) == -LINUX_EAGAIN); + task_netlink_release(&files[receiver]); files[receiver] = (struct task_file){0}; + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&unicast, sizeof(unicast)) == -LINUX_ECONNREFUSED); + assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, + (uintptr_t)&absent, sizeof(absent)) == -LINUX_ECONNREFUSED); + current.net_ns = NULL; + for (int fd = 0; fd < 4; ++fd) { + task_netlink_release(&files[fd]); files[fd] = (struct task_file){0}; + } + assert(first->references == 1 && second->references == 1); + net_namespace_put(first); net_namespace_put(second); + current = (struct task){0}; + assert(!allocations); + puts("PASS netlink namespace delivery: same-port unicast, multicast and moved sender FD"); +} + +/** @brief Scope route events and global device events to their actual owners. */ +static void check_netlink_namespace_events(void) +{ + struct user_namespace *owner; + struct net_namespace *root_owned, *user_owned; + assert(!user_namespace_create(¤t, &owner)); + assert(!net_namespace_create(NULL, &root_owned)); + assert(!net_namespace_create(owner, &user_owned)); + user_namespace_put(owner); + struct net_namespace *scopes[] = {NULL, root_owned, user_owned}; + int subscribers[3]; + const struct sockaddr_nl kernel_group = {.nl_family = AF_NETLINK, .nl_groups = 1}; + for (unsigned i = 0; i < 3; ++i) { + current.net_ns = scopes[i]; + subscribers[i] = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT, 0, 0); + assert(subscribers[i] >= 0); + assert(!call(__NR_bind, subscribers[i], (uintptr_t)&kernel_group, sizeof(kernel_group), 0, 0)); + } + char output[512]; + netlink_uevent_change("/devices/test", "test", "STATE=ready\0", sizeof("STATE=ready\0") - 1); + assert(receive(subscribers[0], output, sizeof(output)) > 0); + assert(receive(subscribers[1], output, sizeof(output)) > 0); + assert(receive(subscribers[2], output, sizeof(output)) == -LINUX_EAGAIN); + for (unsigned i = 0; i < 3; ++i) { + task_netlink_release(&files[subscribers[i]]); + files[subscribers[i]] = (struct task_file){0}; + } + const struct sockaddr_nl route_group = {.nl_family = AF_NETLINK, .nl_groups = RTMGRP_IPV6_IFADDR}; + for (unsigned i = 0; i < 3; ++i) { + current.net_ns = scopes[i]; + subscribers[i] = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(subscribers[i] >= 0); + assert(!call(__NR_bind, subscribers[i], (uintptr_t)&route_group, sizeof(route_group), 0, 0)); + } + additional_address = true; + netlink_ipv6_changed(); + assert(receive(subscribers[0], output, sizeof(output)) > 0); + assert(receive(subscribers[1], output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(subscribers[2], output, sizeof(output)) == -LINUX_EAGAIN); + allocation_fail_after = 0; + netlink_ipv6_changed(); + allocation_fail_after = -1; + assert(receive(subscribers[0], output, sizeof(output)) == -LINUX_ENOBUFS); + assert(receive(subscribers[1], output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(subscribers[2], output, sizeof(output)) == -LINUX_EAGAIN); + current.net_ns = NULL; + for (unsigned i = 0; i < 3; ++i) { + task_netlink_release(&files[subscribers[i]]); + files[subscribers[i]] = (struct task_file){0}; + } + assert(root_owned->references == 1 && user_owned->references == 1); + net_namespace_put(root_owned); net_namespace_put(user_owned); + additional_address = false; + current = (struct task){0}; + assert(!allocations); + puts("PASS netlink namespace events: route notifications, overruns and device-event user owner"); +} + +/** @brief Balance namespace references on socket allocation and FD-table failures. */ +static void check_netlink_namespace_failures(void) +{ + struct net_namespace *scope; + assert(!net_namespace_create(NULL, &scope)); + current.net_ns = scope; + allocation_fail_after = 0; + assert(call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0) == -LINUX_ENOMEM); + allocation_fail_after = -1; + assert(scope->references == 1); + for (unsigned i = 0; i < 4; ++i) + assert(call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0) == i); + assert(scope->references == 5); + assert(call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0) == -LINUX_EMFILE); + assert(scope->references == 5); + current.net_ns = NULL; + net_namespace_put(scope); + for (unsigned i = 0; i < 4; ++i) { + task_netlink_release(&files[i]); files[i] = (struct task_file){0}; + } + assert(!allocations); + puts("PASS netlink namespace cleanup: ENOMEM, EMFILE and final socket release"); +} + /** @brief Verify SO_REUSEADDR state without changing netlink port exclusivity. */ static void check_netlink_reuseaddr(void) { @@ -513,6 +693,10 @@ static void check_netlink_filter(void) int main(void) { + check_netlink_namespace_ports(); + check_netlink_namespace_delivery(); + check_netlink_namespace_events(); + check_netlink_namespace_failures(); check_netlink_reuseaddr(); check_uevent_userspace_delivery(); assert(!net_interface_register(2)); From 48b10f7c5bdb388476912e193ec740652352f42f Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 05:08:46 +0800 Subject: [PATCH 72/97] feat(net): isolate interfaces and IPv4 routes by network namespace --- Documentation/core-api/mount-namespaces.rst | 23 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 46 +-- .../en/LC_MESSAGES/userspace-api/ipv6.po | 27 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 41 +- .../ja/LC_MESSAGES/userspace-api/ipv6.po | 25 +- Documentation/userspace-api/ipv6.rst | 14 +- include/reliefnt/net.h | 9 +- include/reliefnt/net_interface.h | 140 +++++-- include/reliefnt/net_ipv6.h | 3 +- include/reliefnt/net_namespace.h | 9 +- include/reliefnt/netlink.h | 14 + kernel/syscall/device/legacy_ioctl.c | 5 - kernel/syscall/ipc/socket.c | 12 +- net/core.c | 8 +- net/input.c | 4 +- net/interface/config.c | 10 +- net/interface/ioctl.c | 125 +++--- net/interface/routes.c | 98 ++--- net/interface/socket.c | 13 +- net/interface/state.c | 86 ++-- net/internal.h | 8 +- net/ipv4/core.c | 6 +- net/ipv4/udp.c | 8 +- net/ipv6/core.c | 26 +- net/link/arp.c | 14 +- net/namespace/namespace.c | 13 +- net/proc.c | 46 ++- net/socket/control.c | 10 +- net/socket/netlink.c | 371 +++++++++++------- net/socket/packet.c | 14 +- net/socket/udp.c | 20 +- net/tcp/input.c | 2 +- net/tcp/output.c | 14 +- net/tcp/socket.c | 16 +- tools/tests/ipv6_control_test.c | 292 +++++++++++++- tools/tests/ipv6_protocol_test.c | 6 +- tools/tests/ipv6_tcp_test.c | 10 +- tools/tests/ipv6_transport_test.c | 2 +- tools/tests/net_interface_test.c | 20 +- tools/tests/net_multi_interface_test.c | 50 +-- tools/tests/net_multinic_data_test.c | 16 +- tools/tests/net_packet_test.c | 12 +- tools/tests/net_rx_budget_test.c | 2 +- tools/tests/socket_batch_unix_test.c | 43 ++ tools/tests/udp_socket_test.c | 12 +- 45 files changed, 1135 insertions(+), 610 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index e42727ff..68675eba 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -158,9 +158,15 @@ hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护 网络空间生命周期 ================ -``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。 +``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。 -当前网络身份为 Unix 抽象地址、proc 枚举和 netlink 端口及消息投递提供作用域。接口、路由与 IPv4/IPv6、TCP/UDP 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。 +每个网络空间独立持有 loopback、接口列表和显式 IPv4 路由。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时分配 ``127.0.0.1/8``。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由和 owner 引用。 + +网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口和 IPv4 路由查询、修改及 netlink 控制面使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。IPv6 和 transport 状态隔离仍待完成。 + +``/proc/net/dev`` 和 ``route`` 按调用者当前网络 scope 输出。非初始空间的 ``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``if_inet6`` 和 ``ipv6_route`` 为空,``unix`` 按真实 socket scope 枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。 + +用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 IPv6 与 transport 隔离完成后接通。 netlink 端口与事件 ================== @@ -169,7 +175,9 @@ netlink 端口与事件 udev 的用户态组 2 多播和 worker 端口单播只投递到发送套接字所属空间。接收者位于其他空间时,单播返回 ``ECONNREFUSED``。发送要求初始用户空间的 ``CAP_NET_ADMIN``。全局设备的内核组 1 通知投递到由初始用户空间拥有的网络空间,使用子用户空间作为 owner 的网络空间不接收此类未标记通知。 -当前接口、地址和路由表属于初始网络空间,相应的路由通知与 ``ENOBUFS`` 丢失报告只投递到该空间的订阅者。其首个路由订阅者建立快照基线,最后一个订阅者离开时释放基线。其他空间的订阅和关闭不延长该基线的生命周期。 +每个网络空间的首个路由订阅者建立独立快照基线,IPv6 地址、IPv6 路由和链路快照全部捕获成功后才发布基线和订阅。状态变化同样在完整捕获后发布通知并替换基线,捕获失败按受影响 scope 报告 overrun。通知及 ``ENOBUFS`` 丢失报告按 scope 投递。该空间最后一个订阅关闭或退订时释放基线。 + +路由多播组当前支持 ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR`` 和 ``RTMGRP_IPV6_ROUTE``。IPv4 地址和 IPv4 路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。 凭据权限作用域 ============== @@ -179,14 +187,7 @@ udev 的用户态组 2 多播和 worker 端口单播只投递到发送套接字 fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 释放。清理登录身份继续保留所属空间。 -挂载图管理按图 owner 授权,文件系统创建和重配置按后端 owner 授权。 -文件系统 DAC 特权覆盖、普通设备、 -网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 -信号、进程优先级、跨进程资源限制与 -ptrace 按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 -后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。 -ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits -及 seccomp 安装使用调用方所属空间的能力集合。 +挂载图管理按图 owner 授权,文件系统创建和重配置按后端 owner 授权。接口、IPv4 路由及 netlink 路由控制面修改按 socket 网络 scope 的 user owner 授权。文件系统 DAC 特权覆盖、普通设备、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。udev 用户态消息发送也要求初始用户空间的能力。信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权。提升硬资源上限仍要求初始空间能力。能力可作用于后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。 空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID 转换为全局内核 ID;转换接口通过 acquire 读取完整映射,无分配和调度器锁。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 57089eb6..78faff45 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -171,26 +171,8 @@ msgstr "Credential capability scope" msgid "任务凭据持有引用计数的用户命名空间,空指针表示初始空间。任务 UID/GID 使用 全局内核 ID。子空间记录创建者的有效 UID,并持有父空间引用,层级上限为 32。 fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 释放。清理登录身份继续保留所属空间。" msgstr "Task credentials hold a reference to a user namespace. A null pointer represents the initial namespace. Task UIDs and GIDs are global kernel IDs. A child namespace records its creator’s effective UID and retains its parent, with a nesting limit of 32. Fork and kernel-launched tasks inherit the reference. Exec keeps it, and wait or task-slot reuse releases the reference of a zombie. Clearing a login identity preserves the owning namespace." -msgid "" -"挂载图管理按图 owner 授权,文件系统创建和重配置按后端 owner 授权。 文件系统 DAC 特权覆盖、普通设备、 " -"网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 信号、进程优先级、跨进程资源限制与 ptrace " -"按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner " -"相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 " -"seccomp 安装使用调用方所属空间的能力集合。" -msgstr "" -"Mount graph management is authorized against the graph owner. Filesystem " -"creation and reconfiguration are authorized against the backend owner. " -"Filesystem DAC privilege overrides, ordinary devices, networking, IPC, " -"clocks, reboot, modules, memory locking and OOM adjustments use " -"capabilities in the initial namespace. Signals, process priority, " -"cross-process resource limits and ptrace check the target task’s namespace." -" Raising hard resource limits still requires initial-namespace " -"capabilities. Capabilities apply to descendant namespaces. A task in the " -"parent namespace whose effective UID matches a child namespace’s owner has " -"capabilities throughout that subtree. The ptrace capability-set subset " -"check requires both tasks to share a user namespace. capset, identity " -"changes, securebits and seccomp installation use the caller’s namespace " -"capability sets." +msgid "挂载图管理按图 owner 授权,文件系统创建和重配置按后端 owner 授权。接口、IPv4 路由及 netlink 路由控制面修改按 socket 网络 scope 的 user owner 授权。文件系统 DAC 特权覆盖、普通设备、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。udev 用户态消息发送也要求初始用户空间的能力。信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权。提升硬资源上限仍要求初始空间能力。能力可作用于后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。" +msgstr "Mount graph management is authorized against the graph owner. Filesystem creation and reconfiguration are authorized against the backend owner. Interface, IPv4 route and netlink route control-plane mutations are authorized against the user owner of the socket’s network scope. Filesystem DAC privilege overrides, ordinary devices, IPC, clocks, reboot, modules, memory locking and OOM adjustments use capabilities in the initial namespace. Sending userspace udev messages also requires initial-user-namespace capabilities. Signals, process priority, cross-process resource limits and ptrace check the target task’s namespace. Raising hard resource limits still requires initial-namespace capabilities. Capabilities apply to descendant namespaces. A task in the parent namespace whose effective UID matches a child namespace’s owner has capabilities throughout that subtree. The ptrace capability-set subset check requires both tasks to share a user namespace. capset, identity changes, securebits and seccomp installation use the caller’s namespace capability sets." msgid "" "空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID 转换为全局内核 ID;转换接口通过 acquire " @@ -448,11 +430,20 @@ msgstr "``struct uts_namespace`` uses atomic reference counting. Tasks and nsfs msgid "网络空间生命周期" msgstr "Network namespace lifetime" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" -msgstr "``net_namespace_create()`` creates a reference-counted network identity with an immutable user owner. A null pointer denotes the permanent initial network namespace. Tasks share the identity on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix and netlink socket independently retains its creating network namespace until its final reference closes. Unix server connections inherit the listener namespace." +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" +msgstr "``net_namespace_create()`` creates a reference-counted network namespace with an immutable user owner. ``NULL`` denotes the permanent initial network namespace. Tasks share the namespace on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix and netlink socket independently retains its creating network namespace until its final reference closes. Unix server connections inherit the listener namespace." + +msgid "每个网络空间独立持有 loopback、接口列表和显式 IPv4 路由。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时分配 ``127.0.0.1/8``。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由和 owner 引用。" +msgstr "Each network namespace owns independent loopback state, an interface list and explicit IPv4 routes. A new namespace starts with ``lo`` down and unaddressed. Bringing it up for the first time assigns ``127.0.0.1/8``. Physical NIC registration and ingress remain in the initial network namespace. The final namespace reference releases its interface list, explicit IPv4 routes and owner reference." -msgid "当前网络身份为 Unix 抽象地址、proc 枚举和 netlink 端口及消息投递提供作用域。接口、路由与 IPv4/IPv6、TCP/UDP 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。" -msgstr "The current network identity scopes Unix abstract addresses, proc enumeration, netlink ports and message delivery. Interface, route, IPv4/IPv6 and TCP/UDP state isolation are subsequent integration steps. Clone requests using ``CLONE_NEWNET`` return ``EPERM`` or ``EINVAL`` according to authority. Unshare requests return ``EINVAL``. Userspace creation and switching will be connected after complete network state isolation." +msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口和 IPv4 路由查询、修改及 netlink 控制面使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。IPv6 和 transport 状态隔离仍待完成。" +msgstr "Network namespaces scope Unix abstract addresses, proc enumeration, netlink ports and message delivery. Interface and IPv4 route queries and mutations, together with the netlink control plane, use the network scope retained when the socket was created. Mutations require ``CAP_NET_ADMIN`` in that scope’s user owner. IPv6 address and route dumps are empty in non-initial namespaces, and IPv6 mutations that pass authorization return ``EOPNOTSUPP``. IPv6 and transport state isolation remain pending." + +msgid "``/proc/net/dev`` 和 ``route`` 按调用者当前网络 scope 输出。非初始空间的 ``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``if_inet6`` 和 ``ipv6_route`` 为空,``unix`` 按真实 socket scope 枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。" +msgstr "``/proc/net/dev`` and ``route`` use the caller’s current network scope. In non-initial namespaces, ``arp``, ``udp``, ``tcp``, ``tcp6``, ``udp6`` and ``raw6`` contain only headers, while ``if_inet6`` and ``ipv6_route`` are empty. ``unix`` enumerates sockets by their actual scope. The ``lo`` counters in ``dev`` currently report zero in non-initial namespaces." + +msgid "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 IPv6 与 transport 隔离完成后接通。" +msgstr "Userspace network namespace entry points through ``CLONE_NEWNET``, ``unshare()`` and ``setns()`` remain disabled. Clone requests using ``CLONE_NEWNET`` return ``EPERM`` or ``EINVAL`` according to authority. Unshare requests return ``EINVAL``. Userspace creation and switching will be connected after IPv6 and transport isolation is complete." msgid "netlink 端口与事件" msgstr "Netlink ports and events" @@ -463,5 +454,8 @@ msgstr "``NETLINK_ROUTE`` and ``NETLINK_KOBJECT_UEVENT`` match bound ports by ne msgid "udev 的用户态组 2 多播和 worker 端口单播只投递到发送套接字所属空间。接收者位于其他空间时,单播返回 ``ECONNREFUSED``。发送要求初始用户空间的 ``CAP_NET_ADMIN``。全局设备的内核组 1 通知投递到由初始用户空间拥有的网络空间,使用子用户空间作为 owner 的网络空间不接收此类未标记通知。" msgstr "Userspace udev group 2 multicast and worker-port unicast stay within the sending socket's namespace. Unicast returns ``ECONNREFUSED`` when the receiver exists only in another namespace. Sending requires ``CAP_NET_ADMIN`` in the initial user namespace. Kernel group 1 notifications for global devices reach network namespaces owned by the initial user namespace. Networks owned by child user namespaces do not receive these untagged notifications." -msgid "当前接口、地址和路由表属于初始网络空间,相应的路由通知与 ``ENOBUFS`` 丢失报告只投递到该空间的订阅者。其首个路由订阅者建立快照基线,最后一个订阅者离开时释放基线。其他空间的订阅和关闭不延长该基线的生命周期。" -msgstr "The current interface, address and route tables belong to the initial network namespace. Route notifications and ``ENOBUFS`` loss reports reach only its subscribers. Its first route subscriber establishes a snapshot baseline, and its final subscriber releases that baseline. Subscriptions and closes in other namespaces do not extend its lifetime." +msgid "每个网络空间的首个路由订阅者建立独立快照基线,IPv6 地址、IPv6 路由和链路快照全部捕获成功后才发布基线和订阅。状态变化同样在完整捕获后发布通知并替换基线,捕获失败按受影响 scope 报告 overrun。通知及 ``ENOBUFS`` 丢失报告按 scope 投递。该空间最后一个订阅关闭或退订时释放基线。" +msgstr "The first route subscriber in each network namespace establishes an independent snapshot baseline. The baseline and subscription are published only after IPv6 address, IPv6 route and link snapshots have all been captured successfully. State changes likewise publish notifications and replace the baseline after a complete capture. Capture failures report overruns within the affected scope. Notifications and ``ENOBUFS`` loss reports are delivered by scope. Closing or unsubscribing the final subscriber in that namespace releases its baseline." + +msgid "路由多播组当前支持 ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR`` 和 ``RTMGRP_IPV6_ROUTE``。IPv4 地址和 IPv4 路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。" +msgstr "The supported route multicast groups are ``RTMGRP_LINK``, ``RTMGRP_IPV6_IFADDR`` and ``RTMGRP_IPV6_ROUTE``. IPv4 address and IPv4 route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``." \ No newline at end of file diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po index 78ff7a6f..e5872098 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po @@ -57,16 +57,11 @@ msgstr "" msgid "配置与观测" msgstr "Configuration and Observation" -msgid "" -"``AF_NETLINK`` / ``NETLINK_ROUTE`` 提供链路、地址和路由查询,IPv6 地址和路由 修改需要 ``CAP_NET_ADMIN``。支持链路、IPv6 " -"地址和路由变更订阅;接收队列 溢出报告 ``ENOBUFS``,调用者应重新查询。``getifaddrs()`` 可以通过标准查询 获取 IPv6 地址。保留 Linux IPv6 地址、路由 " -"ioctl,并根据 socket family 选择相应参数布局。" -msgstr "" -"``AF_NETLINK`` / ``NETLINK_ROUTE`` provides link, address, and route queries; changing IPv6 " -"addresses or routes requires ``CAP_NET_ADMIN``. Subscriptions cover link, IPv6 address, and route " -"changes. Receive queue overflow reports ``ENOBUFS`` and callers should query again. " -"``getifaddrs()`` can obtain IPv6 addresses through standard queries. Linux IPv6 address and route " -"ioctls are retained, with argument layouts selected by socket family." +msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。``getifaddrs()`` 可以通过标准查询获取初始空间的 IPv6 地址。保留 Linux IPv6 地址、路由 ioctl,并根据 socket family 选择相应参数布局。" +msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` provides link, address and route queries and mutations within the network scope captured at socket creation. That scope is retained after FD transfer. Mutations require ``CAP_NET_ADMIN`` in the network scope’s user owner. IPv6 address and route dumps are empty in non-initial namespaces, and IPv6 mutations that pass authorization return ``EOPNOTSUPP``. ``getifaddrs()`` can obtain IPv6 addresses in the initial namespace through standard queries. Linux IPv6 address and route ioctls are retained, with argument layouts selected by socket family." + +msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" +msgstr "Route multicast supports link, IPv6 address and IPv6 route groups. IPv4 address and route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``. Each network namespace maintains its own subscription snapshots, published after all captures succeed and released when its final subscriber closes or unsubscribes. Change notifications and overruns are delivered by network scope. Receive queue overflow reports ``ENOBUFS``, and callers should query again." msgid "" "多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 " @@ -77,13 +72,11 @@ msgstr "" "empty query result. Receivers must still iterate all messages in each datagram until the matching " "``NLMSG_DONE`` or an error arrives." -msgid "" -"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局;其中地址 scope 的编码与 " -"rtnetlink 的 scope 值不同。 快照复制出内部状态,不借出跨等待有效的内核指针。" -msgstr "" -"``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6``, and ``raw6`` use Linux text layouts; " -"address scope encoding differs from rtnetlink scope values. Snapshots copy internal state rather " -"than lending kernel pointers that remain valid across waits." +msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。快照复制出内部状态,跨等待仅保留副本。按调用者当前网络 scope 读取时,非初始空间的 IPv6 地址和路由表为空,``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text layouts. Address scope encoding differs from rtnetlink scope values. Snapshots copy internal state and retain only copies across waits. Reads use the caller’s current network scope. In non-initial namespaces, IPv6 address and route tables are empty, while ``tcp6``, ``udp6`` and ``raw6`` contain only headers." + +msgid "接口、loopback 和显式 IPv4 路由已有独立网络空间状态,物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 IPv6 与 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。" +msgstr "Interfaces, loopback and explicit IPv4 routes already have independent network namespace state. Physical NIC registration and ingress remain in the initial namespace. Userspace network namespace entry points through ``CLONE_NEWNET``, ``unshare()`` and ``setns()`` will be connected after IPv6 and transport isolation is complete. See :doc:`../core-api/mount-namespaces` for internal lifetime and proc scope details." msgid "范围与标准" msgstr "Scope and Standards" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 5ab14dc9..978a2280 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -148,21 +148,8 @@ msgstr "資格情報のケーパビリティの適用範囲" msgid "任务凭据持有引用计数的用户命名空间,空指针表示初始空间。任务 UID/GID 使用 全局内核 ID。子空间记录创建者的有效 UID,并持有父空间引用,层级上限为 32。 fork 和内核启动继承空间引用,exec 保留该引用;僵尸任务在 wait 回收或槽位重用时 释放。清理登录身份继续保留所属空间。" msgstr "タスクの資格情報は参照カウント付きのユーザー名前空間を保持します。NULL ポインターは初期名前空間を表します。タスクの UID と GID はグローバルなカーネル ID です。子名前空間は作成者の実効 UID を記録し、親の参照を保持します。入れ子の上限は 32 です。fork とカーネルによるタスク起動は参照を継承し、exec では参照を維持します。ゾンビタスクの参照は wait による回収時またはタスクスロットの再利用時に解放されます。ログイン ID を消去しても所属名前空間は維持されます。" -msgid "" -"挂载图管理按图 owner 授权,文件系统创建和重配置按后端 owner 授权。 文件系统 DAC 特权覆盖、普通设备、 " -"网络、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。 信号、进程优先级、跨进程资源限制与 ptrace " -"按目标任务所属空间授权;提升硬资源上限仍要求初始空间能力。能力可作用于 后代空间,父空间中有效 UID 与子空间 owner " -"相同的任务拥有该子树的能力。 ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 " -"seccomp 安装使用调用方所属空间的能力集合。" -msgstr "" -"マウントグラフの管理はグラフ owner に基づいて認可され、ファイルシステムの作成と再構成はバックエンド owner " -"に基づいて認可されます。ファイルシステムの DAC " -"特権による上書き、通常のデバイス、ネットワーク、IPC、時計、再起動、モジュール、メモリロック、OOM " -"調整には初期名前空間の能力を使用します。シグナル、プロセス優先度、他プロセスのリソース制限、ptrace " -"は対象タスクの名前空間に基づいて認可されます。ハードリミットの引き上げには引き続き初期名前空間の能力が必要です。能力は子孫名前空間にも適用され、親名前空間で実効" -" UID が子名前空間の owner と一致するタスクは、その部分木全体の能力を持ちます。ptrace " -"の能力集合の部分集合検査には、両タスクが同じユーザー名前空間に属する必要があります。capset、ID 切り替え、securebits、seccomp" -" の設定には、呼び出し元の名前空間の能力集合を使用します。" +msgid "挂载图管理按图 owner 授权,文件系统创建和重配置按后端 owner 授权。接口、IPv4 路由及 netlink 路由控制面修改按 socket 网络 scope 的 user owner 授权。文件系统 DAC 特权覆盖、普通设备、IPC、时钟、重启、模块、内存锁定和 OOM 调整等共享资源使用初始空间能力。udev 用户态消息发送也要求初始用户空间的能力。信号、进程优先级、跨进程资源限制与 ptrace 按目标任务所属空间授权。提升硬资源上限仍要求初始空间能力。能力可作用于后代空间,父空间中有效 UID 与子空间 owner 相同的任务拥有该子树的能力。ptrace 的能力集合子集检查要求双方位于同一用户空间。capset、身份切换、securebits 及 seccomp 安装使用调用方所属空间的能力集合。" +msgstr "マウントグラフの管理はグラフ owner に基づいて認可され、ファイルシステムの作成と再構成はバックエンド owner に基づいて認可されます。インターフェース、IPv4 ルート、netlink ルート制御面の変更は socket のネットワーク scope の user owner に基づいて認可されます。ファイルシステムの DAC 特権による上書き、通常のデバイス、IPC、時計、再起動、モジュール、メモリロック、OOM 調整には初期名前空間の能力を使用します。udev ユーザー空間メッセージの送信にも初期ユーザー名前空間の能力が必要です。シグナル、プロセス優先度、他プロセスのリソース制限、ptrace は対象タスクの名前空間に基づいて認可されます。ハードリミットの引き上げには引き続き初期名前空間の能力が必要です。能力は子孫名前空間にも適用され、親名前空間で実効 UID が子名前空間の owner と一致するタスクは、その部分木全体の能力を持ちます。ptrace の能力集合の部分集合検査には、両タスクが同じユーザー名前空間に属する必要があります。capset、ID 切り替え、securebits、seccomp の設定には、呼び出し元の名前空間の能力集合を使用します。" msgid "" "空间持有一次发布、发布后不可变的 UID/GID 范围映射。映射发布前将父空间 ID 转换为全局内核 ID;转换接口通过 acquire " @@ -393,11 +380,20 @@ msgstr "``struct uts_namespace`` はアトミックな参照カウントを使 msgid "网络空间生命周期" msgstr "ネットワーク名前空間の寿命" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络身份,空指针表示永久初始网络空间。任务在 fork 时共享该身份,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" -msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク識別を作成します。空ポインターは永続的な初期ネットワーク名前空間を表します。タスクは fork 時に識別を共有し、exec と ID のクリア後も参照を保持し、wait による回収またはスロット再利用時に解放します。各 Unix および netlink ソケットは作成時のネットワーク名前空間を独立して保持し、最後の参照を閉じると解放します。Unix のサーバー側接続はリスナーの名前空間を継承します。" +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" +msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク名前空間を作成します。``NULL`` は永続的な初期ネットワーク名前空間を表します。タスクは fork 時にこの空間を共有し、exec と ID の消去を通じて参照を保持し、wait による回収時またはスロットの再利用時に解放します。各 Unix および netlink ソケットは作成時のネットワーク名前空間を個別に保持し、最後の参照が閉じられると解放します。Unix のサーバー側接続はリスナーの名前空間を継承します。" + +msgid "每个网络空间独立持有 loopback、接口列表和显式 IPv4 路由。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时分配 ``127.0.0.1/8``。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由和 owner 引用。" +msgstr "各ネットワーク名前空間は独立した loopback 状態、インターフェース一覧、明示的な IPv4 ルートを保持します。新しい空間の ``lo`` は初期状態で down かつアドレス未設定で、最初に up にすると ``127.0.0.1/8`` が設定されます。物理 NIC の登録と ingress は引き続き初期ネットワーク名前空間に属します。空間の最後の参照が解放されると、インターフェース一覧、明示的な IPv4 ルート、owner 参照も解放されます。" -msgid "当前网络身份为 Unix 抽象地址、proc 枚举和 netlink 端口及消息投递提供作用域。接口、路由与 IPv4/IPv6、TCP/UDP 状态隔离属于后续接入步骤。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换入口将在完整网络状态隔离后接通。" -msgstr "現在のネットワーク識別は Unix 抽象アドレス、proc 列挙、netlink ポートとメッセージ配信のスコープを提供します。インターフェイス、経路、IPv4/IPv6、TCP/UDP の状態分離は後続の統合作業です。``CLONE_NEWNET`` を指定した clone は権限に応じて ``EPERM`` または ``EINVAL`` を返し、unshare は ``EINVAL`` を返します。ネットワーク状態の分離が完了した後で、ユーザー空間の作成と切り替え入口を接続します。" +msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口和 IPv4 路由查询、修改及 netlink 控制面使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。IPv6 和 transport 状态隔离仍待完成。" +msgstr "ネットワーク名前空間は Unix 抽象アドレス、proc 列挙、netlink ポートとメッセージ配信の適用範囲を定めます。インターフェースと IPv4 ルートの照会・変更、および netlink 制御面は、ソケット作成時に保持したネットワーク scope を使用します。変更にはその scope の user owner に対する ``CAP_NET_ADMIN`` が必要です。非初期空間の IPv6 アドレスとルートの dump は空で、認可を通過した IPv6 変更は ``EOPNOTSUPP`` を返します。IPv6 と transport の状態分離は今後の対応です。" + +msgid "``/proc/net/dev`` 和 ``route`` 按调用者当前网络 scope 输出。非初始空间的 ``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``if_inet6`` 和 ``ipv6_route`` 为空,``unix`` 按真实 socket scope 枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。" +msgstr "``/proc/net/dev`` と ``route`` は呼び出し元の現在のネットワーク scope を使用します。非初期空間では ``arp``、``udp``、``tcp``、``tcp6``、``udp6``、``raw6`` は表ヘッダーのみを出力し、``if_inet6`` と ``ipv6_route`` は空になります。``unix`` は実際の socket scope に従って列挙します。非初期空間の ``dev`` における ``lo`` のカウンターは現在ゼロです。" + +msgid "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 IPv6 与 transport 隔离完成后接通。" +msgstr "``CLONE_NEWNET``、``unshare()``、``setns()`` によるユーザー空間のネットワーク名前空間操作は引き続き無効です。``CLONE_NEWNET`` を指定した clone は権限に応じて ``EPERM`` または ``EINVAL`` を返し、unshare は ``EINVAL`` を返します。ユーザー空間からの作成と切り替えは IPv6 と transport の分離完了後に接続します。" msgid "netlink 端口与事件" msgstr "netlink のポートとイベント" @@ -408,5 +404,8 @@ msgstr "``NETLINK_ROUTE`` と ``NETLINK_KOBJECT_UEVENT`` のポートバイン msgid "udev 的用户态组 2 多播和 worker 端口单播只投递到发送套接字所属空间。接收者位于其他空间时,单播返回 ``ECONNREFUSED``。发送要求初始用户空间的 ``CAP_NET_ADMIN``。全局设备的内核组 1 通知投递到由初始用户空间拥有的网络空间,使用子用户空间作为 owner 的网络空间不接收此类未标记通知。" msgstr "udev のユーザー空間グループ 2 マルチキャストと worker ポートへのユニキャストは、送信ソケットの名前空間内にのみ配信します。受信先が他の名前空間にしか存在しない場合、ユニキャストは ``ECONNREFUSED`` を返します。送信には初期ユーザー名前空間の ``CAP_NET_ADMIN`` が必要です。グローバルデバイスのカーネルグループ 1 通知は、初期ユーザー名前空間が所有するネットワーク名前空間に配信します。子ユーザー名前空間が所有するネットワーク名前空間には、この未タグ付け通知を配信しません。" -msgid "当前接口、地址和路由表属于初始网络空间,相应的路由通知与 ``ENOBUFS`` 丢失报告只投递到该空间的订阅者。其首个路由订阅者建立快照基线,最后一个订阅者离开时释放基线。其他空间的订阅和关闭不延长该基线的生命周期。" -msgstr "現在のインターフェイス、アドレス、経路テーブルは初期ネットワーク名前空間に属します。経路通知と ``ENOBUFS`` の欠落報告は、その購読者にのみ配信します。最初の経路購読者がスナップショットの基準を作成し、最後の購読者が離れると解放します。他の名前空間での購読やクローズは、この基準の寿命を延長しません。" +msgid "每个网络空间的首个路由订阅者建立独立快照基线,IPv6 地址、IPv6 路由和链路快照全部捕获成功后才发布基线和订阅。状态变化同样在完整捕获后发布通知并替换基线,捕获失败按受影响 scope 报告 overrun。通知及 ``ENOBUFS`` 丢失报告按 scope 投递。该空间最后一个订阅关闭或退订时释放基线。" +msgstr "各ネットワーク名前空間の最初のルート購読者が独立したスナップショット基準を作成します。IPv6 アドレス、IPv6 ルート、リンクの全スナップショットの取得が成功してから、基準と購読を公開します。状態変更時も完全な取得後に通知を公開し、基準を置き換えます。取得失敗時の overrun は影響を受けた scope 内に報告します。通知と ``ENOBUFS`` による損失報告は scope ごとに配信します。その空間の最後の購読者が閉じるか購読を解除すると、基準を解放します。" + +msgid "路由多播组当前支持 ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR`` 和 ``RTMGRP_IPV6_ROUTE``。IPv4 地址和 IPv4 路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。" +msgstr "現在対応するルートマルチキャストグループは ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR``、``RTMGRP_IPV6_ROUTE`` です。IPv4 アドレスと IPv4 ルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。" \ No newline at end of file diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po index 8a4232fa..0cbb8185 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po @@ -52,15 +52,11 @@ msgstr "" msgid "配置与观测" msgstr "設定と観測" -msgid "" -"``AF_NETLINK`` / ``NETLINK_ROUTE`` 提供链路、地址和路由查询,IPv6 地址和路由 修改需要 ``CAP_NET_ADMIN``。支持链路、IPv6 " -"地址和路由变更订阅;接收队列 溢出报告 ``ENOBUFS``,调用者应重新查询。``getifaddrs()`` 可以通过标准查询 获取 IPv6 地址。保留 Linux IPv6 地址、路由 " -"ioctl,并根据 socket family 选择相应参数布局。" -msgstr "" -"``AF_NETLINK`` / ``NETLINK_ROUTE`` はリンク、アドレス、経路の問い合わせを提供し、IPv6 アドレスや経路の変更には ``CAP_NET_ADMIN`` " -"が必要です。リンク、IPv6 アドレス、経路変更の購読に対応します。受信キューのオーバーフローは ``ENOBUFS`` " -"を報告し、呼び出し側は再問い合わせを行う必要があります。``getifaddrs()`` は標準問い合わせで IPv6 アドレスを取得できます。Linux の IPv6 アドレス/経路 ioctl" -" を保持し、socket family に応じた引数配置を選びます。" +msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。``getifaddrs()`` 可以通过标准查询获取初始空间的 IPv6 地址。保留 Linux IPv6 地址、路由 ioctl,并根据 socket family 选择相应参数布局。" +msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` は socket 作成時のネットワーク scope 内でリンク、アドレス、ルートの照会と変更を提供し、FD 転送後もその scope を保持します。変更にはネットワーク scope の user owner に対する ``CAP_NET_ADMIN`` が必要です。非初期空間の IPv6 アドレスとルートの dump は空で、認可を通過した IPv6 変更は ``EOPNOTSUPP`` を返します。``getifaddrs()`` は標準の照会を通じて初期空間の IPv6 アドレスを取得できます。Linux の IPv6 アドレスとルートの ioctl を維持し、socket family に応じた引数レイアウトを選択します。" + +msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" +msgstr "ルートマルチキャストはリンク、IPv6 アドレス、IPv6 ルートのグループに対応します。IPv4 アドレスとルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。各ネットワーク名前空間は独立した購読スナップショットを保持し、すべての取得が成功してから公開します。最後の購読者が閉じるか購読を解除すると解放します。変更通知と overrun はネットワーク scope ごとに配信し、受信キューのオーバーフローは ``ENOBUFS`` を報告するため、呼び出し元は再照会してください。" msgid "" "多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 " @@ -69,12 +65,11 @@ msgstr "" "複数部分からなる問い合わせでは、データと終端の ``NLMSG_DONE`` を別々のデータグラムとして送信します。終端マーカーは要求のシーケンス番号と受信ポート ID " "を保持し、結果が空でも送信します。受信側は引き続き各データグラム内の全メッセージを走査し、対応する番号の ``NLMSG_DONE`` またはエラーを待つ必要があります。" -msgid "" -"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局;其中地址 scope 的编码与 " -"rtnetlink 的 scope 值不同。 快照复制出内部状态,不借出跨等待有效的内核指针。" -msgstr "" -"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト配置を使います。ただしアドレス " -"scope の符号化は rtnetlink の scope 値と異なります。スナップショットは内部状態をコピーし、待機をまたいで有効なカーネルポインターを貸し出すことはありません。" +msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。快照复制出内部状态,跨等待仅保留副本。按调用者当前网络 scope 读取时,非初始空间的 IPv6 地址和路由表为空,``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキストレイアウトを使用します。アドレス scope の符号化は rtnetlink の scope 値と異なります。スナップショットは内部状態をコピーし、待機をまたいで保持するのはコピーのみです。読み取りには呼び出し元の現在のネットワーク scope を使用します。非初期空間では IPv6 アドレス表とルート表は空で、``tcp6``、``udp6``、``raw6`` は表ヘッダーのみを出力します。" + +msgid "接口、loopback 和显式 IPv4 路由已有独立网络空间状态,物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 IPv6 与 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。" +msgstr "インターフェース、loopback、明示的な IPv4 ルートは独立したネットワーク名前空間の状態を持ちます。物理 NIC の登録と ingress は引き続き初期空間に属します。``CLONE_NEWNET``、``unshare()``、``setns()`` によるユーザー空間のネットワーク名前空間操作は IPv6 と transport の分離完了後に接続します。内部のライフサイクルと proc の適用範囲は :doc:`../core-api/mount-namespaces` を参照してください。" msgid "范围与标准" msgstr "範囲と標準" diff --git a/Documentation/userspace-api/ipv6.rst b/Documentation/userspace-api/ipv6.rst index a057ee0b..f9ada916 100644 --- a/Documentation/userspace-api/ipv6.rst +++ b/Documentation/userspace-api/ipv6.rst @@ -32,19 +32,17 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 配置与观测 ========== -``AF_NETLINK`` / ``NETLINK_ROUTE`` 提供链路、地址和路由查询,IPv6 地址和路由 -修改需要 ``CAP_NET_ADMIN``。支持链路、IPv6 地址和路由变更订阅;接收队列 -溢出报告 ``ENOBUFS``,调用者应重新查询。``getifaddrs()`` 可以通过标准查询 -获取 IPv6 地址。保留 Linux IPv6 地址、路由 ioctl,并根据 socket family -选择相应参数布局。 +``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。``getifaddrs()`` 可以通过标准查询获取初始空间的 IPv6 地址。保留 Linux IPv6 地址、路由 ioctl,并根据 socket family 选择相应参数布局。 + +路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。 多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。 -``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 -Linux 文本布局;其中地址 scope 的编码与 rtnetlink 的 scope 值不同。 -快照复制出内部状态,不借出跨等待有效的内核指针。 +``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。快照复制出内部状态,跨等待仅保留副本。按调用者当前网络 scope 读取时,非初始空间的 IPv6 地址和路由表为空,``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。 + +接口、loopback 和显式 IPv4 路由已有独立网络空间状态,物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 IPv6 与 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。 范围与标准 ========== diff --git a/include/reliefnt/net.h b/include/reliefnt/net.h index f3fde222..71727077 100644 --- a/include/reliefnt/net.h +++ b/include/reliefnt/net.h @@ -11,6 +11,7 @@ #include struct task; +struct net_namespace; /** * @brief Probe and configure the network stack: load DNS policy, init the NIC, and try a DHCP lease. @@ -303,9 +304,13 @@ void net_driver_detached(void); void net_device_info(uint32_t *flags, uint64_t *mac_value, uint32_t *local_ip); /** @brief Execute a native Linux interface/route ioctl with checked user memory. - * Changes require initial user namespace CAP_NET_ADMIN. + * @param ns Borrowed socket network scope, NULL for the initial network. + * @param request Native ioctl number. @param address User argument address. + * @return Zero, negative errno, or a user-memory prerequisite wait marker. + * Changes require CAP_NET_ADMIN in the network's user owner. The caller holds + * execution ownership and retains the namespace across user-memory retries. */ -int net_interface_ioctl(uint32_t request, uint64_t address); +int net_interface_ioctl(struct net_namespace *ns, uint32_t request, uint64_t address); /** @brief Report whether the primary compatibility NIC is administratively up and ready. */ bool net_interface_ready(void); diff --git a/include/reliefnt/net_interface.h b/include/reliefnt/net_interface.h index ae2bfd33..5c6d4520 100644 --- a/include/reliefnt/net_interface.h +++ b/include/reliefnt/net_interface.h @@ -5,9 +5,12 @@ #include #include +struct net_namespace; + /* IPv4 values in this interface are in host byte order. Calls run under the * network execution owner; pointers returned by get are borrowed until the - * interface is removed. Interface indices are never reused. */ + * interface is removed. Scope arguments are borrowed, with NULL selecting the + * permanent initial network. Physical interface indices are never reused. */ #define NET_IF_LOOPBACK 1u #define NET_IF_NAME_LEN 16u @@ -24,6 +27,12 @@ struct net_ipv4_route { uint32_t destination, mask, gateway, ifindex, metric, flags; }; +/** @brief One namespace-owned, explicitly configured IPv4 route. */ +struct net_ipv4_route_node { + struct net_ipv4_route_node *next; + struct net_ipv4_route route; +}; + struct net_ipv4_path { uint32_t source, destination, next_hop, ifindex; }; @@ -32,45 +41,116 @@ struct net_ipv4_path { int net_interface_register(uint32_t index); /** @brief Remove a hardware interface and its routes; no borrowed pointer survives. */ void net_interface_remove(uint32_t index); -/** @brief Return the live hardware state for index, or NULL; loopback is virtual. */ -struct net_interface *net_interface_get(uint32_t index); -/** @brief Return the next live index after index, including loopback, or zero. */ -uint32_t net_interface_next(uint32_t after); -/** @brief Resolve an exact interface name to its index, or zero if absent. */ -uint32_t net_interface_index(const char *name); -/** @brief Write a NUL-terminated live interface name; false when absent. */ -bool net_interface_name(uint32_t index, char out[NET_IF_NAME_LEN]); -/** @brief Test for a live hardware interface or loopback. */ -bool net_interface_exists(uint32_t index); -/** @brief Test administrative and carrier readiness for an interface. */ -bool net_interface_is_ready(uint32_t index); -/** @brief Test the administrative state of an interface. */ -bool net_interface_is_up(uint32_t index); -/** @brief Set administrative state after authorization; zero or a negative errno. */ -int net_interface_set_up(uint32_t index, bool up); -/** @brief Resolve an assigned IPv4 address to its interface, or zero. */ -uint32_t net_interface_for_ipv4(uint32_t ip); -/** @brief Copy the interface's IPv4 configuration, or return a negative errno. */ -int net_interface_get_config(uint32_t index, struct reliefos_net_config *out); -/** @brief Replace one NIC's primary IPv4 address, mask, and broadcast. */ -int net_interface_configure_ipv4(uint32_t index, uint32_t address, +/** @brief Borrow an interface, including the namespace's own loopback. + * @param ns Borrowed network, NULL for the permanent initial network. + * @param index Interface index. + * @return State until hardware removal or final namespace release, or NULL. + */ +struct net_interface *net_interface_get(struct net_namespace *ns, uint32_t index); +/** @brief Enumerate one network's live interface indices, including loopback. + * @param ns Borrowed network, NULL for the initial network. + * @param after Exclusive lower index bound, zero to start. + * @return Next index, or zero at the end. No state is allocated or retained. + */ +uint32_t net_interface_next(struct net_namespace *ns, uint32_t after); +/** @brief Resolve an exact interface name within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param name NUL-terminated name, nullable. + * @return Live index, or zero when absent or invalid. + */ +uint32_t net_interface_index(struct net_namespace *ns, const char *name); +/** @brief Write a live interface's name within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param index Interface index. @param out Required name buffer. + * @return True with a NUL-terminated name, false when absent or invalid. + */ +bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[NET_IF_NAME_LEN]); +/** @brief Test for a live interface within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param index Interface index. @return True for a visible interface. + */ +bool net_interface_exists(struct net_namespace *ns, uint32_t index); +/** @brief Test administrative and carrier readiness within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param index Interface index. @return True when up and ready for traffic. + */ +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index); +/** @brief Test the administrative state within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param index Interface index. @return True for a visible, up interface. + */ +bool net_interface_is_up(struct net_namespace *ns, uint32_t index); +/** @brief Set administrative state after the caller authorizes the operation. + * @param ns Borrowed network, NULL for the initial network. + * @param index Interface index. @param up Requested administrative state. + * @return Zero or -ENODEV. First enabling an unconfigured loopback assigns + * 127.0.0.1/8. The caller publishes notifications after dependent state changes. + */ +int net_interface_set_up(struct net_namespace *ns, uint32_t index, bool up); +/** @brief Resolve a local IPv4 address within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param ip Host-order IPv4 address. + * @return Assigned interface, or zero. Configured 127/8 loopback accepts the + * entire 127/8 range. Administrative state is checked by the routing caller. + */ +uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip); +/** @brief Copy an interface's IPv4 configuration within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param index Interface index. @param out Required configuration output. + * @return Zero, -EINVAL or -ENODEV. Hardware flags are refreshed in the copy. + */ +int net_interface_get_config(struct net_namespace *ns, uint32_t index, struct reliefos_net_config *out); +/** @brief Replace one interface's primary IPv4 address, mask, and broadcast. + * @param ns Borrowed network, NULL for the initial network. + * @param index Interface index, including loopback. @param address Host-order IP. + * @param mask Contiguous host-order mask. @param broadcast Host-order broadcast. + * @return Zero or negative errno. Invalid input preserves configuration. + * Clears DHCP state, clears the gateway on address removal, and publishes + * changes to this network's subscribers. Caller supplies authorization. + */ +int net_interface_configure_ipv4(struct net_namespace *ns, uint32_t index, uint32_t address, uint32_t mask, uint32_t broadcast); /** @brief Access the first live NIC's compatibility state, or stable fallback. */ struct reliefos_net_config *net_interface_legacy_config(void); /** @brief Access the first live NIC's administrative flag, or stable fallback. */ bool *net_interface_legacy_up(void); -/** @brief Select a live IPv4 route and source; source/scope zero mean automatic. */ -int net_ipv4_route_lookup(uint32_t destination, uint32_t source, uint32_t scope, +/** @brief Select a live IPv4 route and source within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param destination Host-order destination. @param source Assigned source or zero. + * @param scope Required interface index, or zero for automatic selection. + * @param out Required selected path output, written only on success. + * @return Zero or a negative Linux routing errno. No state is retained. + */ +int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32_t source, uint32_t scope, struct net_ipv4_path *out); -/** @brief Add, replace, or remove a checked IPv4 route. */ -int net_ipv4_route_update(const struct net_ipv4_route *route, bool remove, bool replace); -/** @brief Copy a route snapshot and return the total number of routes. */ -uint32_t net_ipv4_routes(struct net_ipv4_route *out, uint32_t capacity); +/** @brief Add, replace or remove an authorized IPv4 route within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param route Required copied input with host-order addresses. + * @param remove Delete a matching route. @param replace Allow replacement. + * @return Zero or negative errno. Invalid input and allocation failure preserve + * existing routes. The network owns explicit entries until deletion or release. + * The caller publishes notifications after success. + */ +int net_ipv4_route_update(struct net_namespace *ns, const struct net_ipv4_route *route, bool remove, bool replace); +/** @brief Copy connected, default and explicit routes within one network. + * @param ns Borrowed network, NULL for the initial network. + * @param out Optional snapshot array. @param capacity Maximum copied entries. + * @return Total route count, including entries beyond capacity. Allocation-free. + */ +uint32_t net_ipv4_routes(struct net_namespace *ns, struct net_ipv4_route *out, uint32_t capacity); + +/** @brief Remove every explicit IPv4 route for a detached interface. + * @param ns Borrowed network, NULL for the initial network. + * @param index Removed interface index. Execution ownership is required. + * Frees owned entries before the corresponding interface state is released. + */ +void net_ipv4_routes_remove_interface(struct net_namespace *ns, uint32_t index); /** @brief Set/query a bound device with Linux socket permissions and usercopy. + * @param ns Borrowed creating network, NULL for the initial network. * @param set Update when true. @param address User name. @param length Size or socklen pointer. * @param index Current/output bound index. @return Zero or negative errno. */ -int net_interface_device_option(bool set, uint64_t address, uint64_t length, uint32_t *index); +int net_interface_device_option(struct net_namespace *ns, bool set, uint64_t address, uint64_t length, uint32_t *index); #endif diff --git a/include/reliefnt/net_ipv6.h b/include/reliefnt/net_ipv6.h index 62dc06a3..3e1005c6 100644 --- a/include/reliefnt/net_ipv6.h +++ b/include/reliefnt/net_ipv6.h @@ -151,6 +151,7 @@ void net_ipv6_socket_error_on(uint32_t ifindex,const uint8_t *packet,uint32_t le /** @brief Render tcp6/udp6/raw6 socket state without driving I/O. * @param stream Slice output. @param leaf Requested standard proc basename. */ void net_ipv6_transport_proc_emit(struct text_stream *stream,const char *leaf); -/** @brief Notify subscribed route-netlink consumers of IPv6 state changes. */ +/** @brief Notify initial-network route subscribers of protocol state changes. + * Runs under execution ownership and retains the previous baseline on OOM. */ void netlink_ipv6_changed(void); #endif diff --git a/include/reliefnt/net_namespace.h b/include/reliefnt/net_namespace.h index cccb4ef7..ed630195 100644 --- a/include/reliefnt/net_namespace.h +++ b/include/reliefnt/net_namespace.h @@ -3,6 +3,7 @@ #define RELIEFNT_NET_NAMESPACE_H #include +#include struct user_namespace; @@ -13,13 +14,17 @@ struct user_namespace; struct net_namespace { uint64_t references; struct user_namespace *user_ns; + struct net_interface *interfaces; + struct net_interface loopback; + struct net_ipv4_route_node *ipv4_routes; }; /** @brief Allocate an empty network identity and retain its user owner. * @param owner Borrowed user namespace, NULL for the initial user namespace. * @param out Required output, cleared on failure, owning one reference on success. * @return Zero, -EINVAL or -ENOMEM. Caller supplies execution ownership and - * authorization. The identity does not copy interfaces or protocol state. + * authorization. The namespace starts with its own down, unconfigured loopback + * and empty IPv4 routing table. Hardware interfaces stay in the initial network. */ int net_namespace_create(struct user_namespace *owner, struct net_namespace **out); @@ -29,7 +34,7 @@ int net_namespace_create(struct user_namespace *owner, struct net_namespace **ou */ struct net_namespace *net_namespace_get(struct net_namespace *ns); -/** @brief Release a network identity and its owner after the final reference. +/** @brief Release a network identity, owned interfaces, IPv4 routes and user owner. * @param ns Owned reference, nullable for the permanent initial namespace. * Does not acquire scheduler or network locks or access task state. */ diff --git a/include/reliefnt/netlink.h b/include/reliefnt/netlink.h index c02bfb50..e0d620b6 100644 --- a/include/reliefnt/netlink.h +++ b/include/reliefnt/netlink.h @@ -5,6 +5,7 @@ #include struct task; struct task_file; +struct net_namespace; #define TASK_FILE_KIND_NETLINK 4u /** @brief Handle a netlink socket operation under execution ownership. * @param number Native syscall number. @param a0 First argument. @param a1 Second argument. @@ -52,6 +53,19 @@ short task_netlink_poll(const struct task_file *file,short events); /** @brief Inspect the next queued datagram size. * @param file Retained OFD. @return Bytes, zero or negative errno. */ int task_netlink_available(const struct task_file *file); +/** @brief Execute an interface ioctl in the pinned socket's creating network. + * @param file Retained netlink OFD under execution ownership. + * @param request Native interface ioctl. @param address User argument address. + * @return Zero, negative errno, or a user-memory prerequisite wait marker. + * Mutations authorize against the network's immutable user owner. + */ +int task_netlink_ioctl(struct task_file *file, uint32_t request, uint64_t address); +/** @brief Publish changes to a network's subscribed route sockets. + * @param ns Borrowed network scope, NULL for the initial network. + * Runs under execution ownership. Allocation failure reports ENOBUFS only to + * this scope's subscribers and retains their previous change baseline. + */ +void netlink_network_changed(struct net_namespace *ns); /** @brief Retire the final OFD, its owned queue and creating network reference. * @param file Final OFD under execution ownership. */ void task_netlink_release(struct task_file *file); diff --git a/kernel/syscall/device/legacy_ioctl.c b/kernel/syscall/device/legacy_ioctl.c index 1401913e..5df629e3 100644 --- a/kernel/syscall/device/legacy_ioctl.c +++ b/kernel/syscall/device/legacy_ioctl.c @@ -346,11 +346,6 @@ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t /* Generic ioctl requests have already been handled. */ return -LINUX_ENOTTY; } - /* Linux interface ioctls are independent of socket protocol. musl - * uses an AF_UNIX datagram socket for if_nametoindex/if_indextoname. */ - if (file && (file->flags & TASK_FILE_FLAG_SOCKET_UNIX) && - a1 >= 0x8900 && a1 <= 0x89ff) - return net_interface_ioctl((uint32_t)a1, a2); if (file && (file->flags & TASK_FILE_FLAG_SOCKET_UNIX)) return task_socket_ioctl(file, a1, a2); if (file && (file->flags & TASK_FILE_FLAG_SOCKET_INET) && task_inet_family(file) == AF_INET6 && diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index fc7b0603..cd91016d 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -1149,16 +1149,20 @@ uint64_t task_socket_write_generation(const struct task_file *file) } /** - * @brief Query queued input bytes or stream send-buffer charge, or set nonblocking mode. + * @brief Handle UNIX socket queue, nonblocking and network-interface ioctls. * @param file Retained socket open file description. - * @param request Native FIONREAD, stream SIOCOUTQ (TIOCOUTQ), or FIONBIO. - * @param address User pointer to one 32-bit result or input flag. + * @param request Native queue, nonblocking or interface ioctl number. + * @param address User pointer to the request-specific result or input record. * @return Zero, a negative Linux errno, or a private output retry status. + * Interface queries and changes use the socket's creating network, including + * after FD transfer. Mutations authorize against that network's user owner. */ int task_socket_ioctl(struct task_file *file, uint64_t request, uint64_t address) { struct unix_socket *socket = unix_from_file(file); if (!socket) return -RELIEFOS_EBADF; + if (request >= 0x8900 && request <= 0x89ff) + return net_interface_ioctl(socket->net_ns, (uint32_t)request, address); if (request == FIONBIO) { int prep=socket_user_prepare(sched_current_task(),address,sizeof(int32_t),false); if(prep)return prep; @@ -1373,7 +1377,7 @@ static int inet_socket_option(bool setting, int level, int option, uint32_t index = 0; int result = net_socket_bound_device(handle, false, &index); if (result < 0) return result; - result = net_interface_device_option(setting, address, length, &index); + result = net_interface_device_option(NULL, setting, address, length, &index); if (result < 0) return result; return setting ? net_socket_bound_device(handle, true, &index) : 0; } diff --git a/net/core.c b/net/core.c index 0a2861dd..0cd3a931 100644 --- a/net/core.c +++ b/net/core.c @@ -63,7 +63,7 @@ void net_init(void) int net_is_ready(void) { for (uint32_t index = netdev_next(0); index; index = netdev_next(index)) - if (net_interface_is_ready(index)) return 1; + if (net_interface_is_ready(NULL, index)) return 1; return 0; } @@ -89,7 +89,7 @@ void net_device_attached(uint32_t ifindex) console_error("[reliefnt] network interface %u registration failed: %d\n", ifindex, result); return; } - net_ipv6_link_changed_on(ifindex, net_interface_is_up(ifindex)); + net_ipv6_link_changed_on(ifindex, net_interface_is_up(NULL, ifindex)); netlink_ipv6_changed(); } @@ -125,9 +125,9 @@ void net_device_retry_registration(void) { if (!net_registration_pending) return; for (uint32_t index = netdev_next(0); index; index = netdev_next(index)) { - if (net_interface_get(index)) continue; + if (net_interface_get(NULL, index)) continue; if (!net_interface_register(index)) { - net_ipv6_link_changed_on(index, net_interface_is_up(index)); + net_ipv6_link_changed_on(index, net_interface_is_up(NULL, index)); netlink_ipv6_changed(); } return; diff --git a/net/input.c b/net/input.c index dba93927..1dae5769 100644 --- a/net/input.c +++ b/net/input.c @@ -72,7 +72,7 @@ void net_poll_once(struct net_arp_wait *arp_wait, uint32_t ifindex = netdev_next(previous); if (!ifindex) ifindex = netdev_next(0); previous = ifindex; - if (ifindex && net_interface_is_up(ifindex)) { + if (ifindex && net_interface_is_up(NULL, ifindex)) { int ret = netdev_poll(ifindex, frame, sizeof(frame), &len); if (ret > 0 && len) { net_packet_input_on(ifindex, frame, len); @@ -112,7 +112,7 @@ void net_poll_rx_budget(uint32_t budget) uint32_t length=0; int result=netdev_poll_notified(id,frame,sizeof(frame),&length); more=result>0 || result==-90 || result==-74; - if (result>0 && length && net_interface_is_up(id)) { + if (result>0 && length && net_interface_is_up(NULL, id)) { net_packet_input_on(id,frame,length); net_process_frame(id,frame,length,NULL,NULL,NULL,NULL); } diff --git a/net/interface/config.c b/net/interface/config.c index 2e85e4b4..a47fad4a 100644 --- a/net/interface/config.c +++ b/net/interface/config.c @@ -234,8 +234,8 @@ void net_update_config_flags(void) */ void net_set_static_fallback(void) { - uint32_t index = net_interface_next(NET_IF_LOOPBACK); - struct net_interface *iface = net_interface_get(index); + uint32_t index = net_interface_next(NULL, NET_IF_LOOPBACK); + struct net_interface *iface = net_interface_get(NULL, index); net_arp_cache_clear_on(index); if (iface) { iface->broadcast = 0; iface->default_metric = 0; } net_dhcp_dns_ip = 0; @@ -266,8 +266,8 @@ static void net_expire_lease(void) */ void net_apply_dhcp_offer(const struct net_dhcp_offer *offer) { - uint32_t index = net_interface_next(NET_IF_LOOPBACK); - struct net_interface *iface = net_interface_get(index); + uint32_t index = net_interface_next(NULL, NET_IF_LOOPBACK); + struct net_interface *iface = net_interface_get(NULL, index); net_arp_cache_clear_on(index); net_config.local_ip = offer->yiaddr; net_config.subnet_mask = offer->subnet_mask ? offer->subnet_mask : RELIEFOS_NET_DEFAULT_SUBNET_MASK; @@ -461,7 +461,7 @@ int net_ipv6_interface_ioctl(uint32_t request, uint64_t address) struct task *task = sched_current_task(); if (request != SIOCSIFADDR && request != SIOCDIFADDR && request != SIOCADDRT && request != SIOCDELRT) - return net_interface_ioctl(request, address); + return net_interface_ioctl(NULL, request, address); if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_NET_ADMIN))) return -LINUX_EPERM; if (request == SIOCSIFADDR || request == SIOCDIFADDR) { struct in6_ifreq input; diff --git a/net/interface/ioctl.c b/net/interface/ioctl.c index 5bd0f0f8..81be86b6 100644 --- a/net/interface/ioctl.c +++ b/net/interface/ioctl.c @@ -2,9 +2,17 @@ #include "../internal.h" #include #include +#include +#include +#include -/** @brief Export whole IPv4 ifreq records for all configured interfaces. */ -static int interface_conf(struct task *task, uint64_t address) +/** @brief Export whole IPv4 ifreq records for a network's configured interfaces. + * @param ns Borrowed network, NULL for the initial network. + * @param task Calling task for user-memory validation. + * @param address User pointer to the native ifconf record. + * @return Zero, negative errno or a user-memory prerequisite wait marker. + */ +static int interface_conf(struct net_namespace *ns, struct task *task, uint64_t address) { struct ifconf conf; int rc = socket_user_import(task, address, &conf, sizeof(conf)); @@ -14,9 +22,9 @@ static int interface_conf(struct task *task, uint64_t address) if (!user_range_writable(address, sizeof(conf))) return -LINUX_EFAULT; if (conf.ifc_len < 0) return -LINUX_EINVAL; uint32_t count = 0; - for (uint32_t index = net_interface_next(0); index; index = net_interface_next(index)) { + for (uint32_t index = net_interface_next(ns, 0); index; index = net_interface_next(ns, index)) { struct reliefos_net_config config; - if (!net_interface_get_config(index, &config) && config.local_ip) ++count; + if (!net_interface_get_config(ns, index, &config) && config.local_ip) ++count; } uint32_t available = count * sizeof(struct ifreq); if (!conf.ifc_buf) conf.ifc_len = (int32_t)available; @@ -29,12 +37,12 @@ static int interface_conf(struct task *task, uint64_t address) if (rc) return rc; if (!user_range_writable(conf.ifc_buf, bytes)) return -LINUX_EFAULT; uint32_t written = 0; - for (uint32_t index = net_interface_next(0); index && written < room; - index = net_interface_next(index)) { + for (uint32_t index = net_interface_next(ns, 0); index && written < room; + index = net_interface_next(ns, index)) { struct reliefos_net_config config; - if (net_interface_get_config(index, &config) || !config.local_ip) continue; + if (net_interface_get_config(ns, index, &config) || !config.local_ip) continue; struct ifreq result = {0}; - (void)net_interface_name(index, result.ifr_name); + (void)net_interface_name(ns, index, result.ifr_name); result.data.addr.sa_family = AF_INET; net_put_u32((uint8_t *)&result.data.addr + 4, config.local_ip); net_memcpy((void *)(uintptr_t)(conf.ifc_buf + written * sizeof(result)), @@ -48,13 +56,17 @@ static int interface_conf(struct task *task, uint64_t address) return 0; } -/** @brief Select the best connected NIC for a legacy gateway-only request. */ -static uint32_t interface_for_gateway(uint32_t gateway) +/** @brief Select the best connected NIC for a legacy gateway-only request. + * @param ns Borrowed network, NULL for the initial network. + * @param gateway Host-order gateway address. + * @return Matching interface index, or zero when no connected NIC matches. + */ +static uint32_t interface_for_gateway(struct net_namespace *ns, uint32_t gateway) { uint32_t selected = 0, best_mask = 0; - for (uint32_t index = net_interface_next(NET_IF_LOOPBACK); index; - index = net_interface_next(index)) { - struct net_interface *iface = net_interface_get(index); + for (uint32_t index = net_interface_next(ns, NET_IF_LOOPBACK); index; + index = net_interface_next(ns, index)) { + struct net_interface *iface = net_interface_get(ns, index); if (!iface || !iface->config.local_ip || (gateway & iface->config.subnet_mask) != (iface->config.local_ip & iface->config.subnet_mask)) continue; @@ -65,8 +77,15 @@ static uint32_t interface_for_gateway(uint32_t gateway) return selected; } -/** @brief Apply an authorized IPv4 route ioctl without retaining user pointers. */ -static int interface_route(struct task *task, uint32_t request, uint64_t address) +/** @brief Apply an authorized IPv4 route ioctl without retaining user pointers. + * @param ns Borrowed network, NULL for the initial network. + * @param task Calling task for user-memory validation. + * @param request Native route add or delete request. + * @param address User pointer to the native route record. + * @return Zero, negative errno or a user-memory prerequisite wait marker. + * Success publishes changes to this network's route subscribers. + */ +static int interface_route(struct net_namespace *ns, struct task *task, uint32_t request, uint64_t address) { struct rtentry input; int rc = socket_user_import(task, address, &input, sizeof(input)); @@ -96,38 +115,39 @@ static int interface_route(struct task *task, uint32_t request, uint64_t address if (!name[i]) { terminated = true; break; } } if (!terminated) return -LINUX_EINVAL; - route.ifindex = net_interface_index(name); + route.ifindex = net_interface_index(ns, name); if (!route.ifindex) return -LINUX_ENODEV; - } else if (route.gateway) route.ifindex = interface_for_gateway(route.gateway); + } else if (route.gateway) route.ifindex = interface_for_gateway(ns, route.gateway); else if (request == SIOCDELRT && !route.mask) { - for (uint32_t index = net_interface_next(NET_IF_LOOPBACK); index; - index = net_interface_next(index)) { - struct net_interface *iface = net_interface_get(index); + for (uint32_t index = net_interface_next(ns, NET_IF_LOOPBACK); index; + index = net_interface_next(ns, index)) { + struct net_interface *iface = net_interface_get(ns, index); if (iface && iface->config.gateway_ip) { route.ifindex = index; break; } } } else { struct net_ipv4_path path; - if (!net_ipv4_route_lookup(route.destination, 0, 0, &path)) route.ifindex = path.ifindex; + if (!net_ipv4_route_lookup(ns, route.destination, 0, 0, &path)) route.ifindex = path.ifindex; } if (!route.ifindex) return -LINUX_ENETUNREACH; if (request == SIOCDELRT && !route.mask && !route.gateway) { - struct net_interface *iface = net_interface_get(route.ifindex); + struct net_interface *iface = net_interface_get(ns, route.ifindex); if (!iface || !iface->config.gateway_ip) return -LINUX_ESRCH; route.gateway = iface->config.gateway_ip; route.flags |= RTF_GATEWAY; } - rc = net_ipv4_route_update(&route, request == SIOCDELRT, false); + rc = net_ipv4_route_update(ns, &route, request == SIOCDELRT, false); if (!rc) { - net_arp_cache_clear_on(route.ifindex); - netlink_ipv6_changed(); + if (!ns && route.ifindex != NET_IF_LOOPBACK) net_arp_cache_clear_on(route.ifindex); + netlink_network_changed(ns); } return rc; } -int net_interface_configure_ipv4(uint32_t index, uint32_t address, +/** @copydoc net_interface_configure_ipv4 */ +int net_interface_configure_ipv4(struct net_namespace *ns, uint32_t index, uint32_t address, uint32_t mask, uint32_t broadcast) { - struct net_interface *iface = net_interface_get(index); + struct net_interface *iface = net_interface_get(ns, index); if (!iface) return index == NET_IF_LOOPBACK ? -LINUX_EOPNOTSUPP : -LINUX_ENODEV; if (((~mask) & ((~mask) + 1u)) || address >= 0xe0000000u) return -LINUX_EINVAL; iface->config.local_ip = address; @@ -136,23 +156,23 @@ int net_interface_configure_ipv4(uint32_t index, uint32_t address, if (!address) iface->config.gateway_ip = 0; iface->config.source = address ? RELIEFOS_NET_CONFIG_SOURCE_STATIC : RELIEFOS_NET_CONFIG_SOURCE_NONE; iface->config.lease_seconds = iface->config.dhcp_server_ip = 0; - net_arp_cache_clear_on(index); - netlink_ipv6_changed(); + if (!ns && index != NET_IF_LOOPBACK) net_arp_cache_clear_on(index); + netlink_network_changed(ns); return 0; } /** @copydoc net_interface_ioctl */ -int net_interface_ioctl(uint32_t request, uint64_t address) +int net_interface_ioctl(struct net_namespace *ns, uint32_t request, uint64_t address) { bool change = request == SIOCSIFFLAGS || request == SIOCSIFADDR || request == SIOCSIFNETMASK || request == SIOCSIFBRDADDR || request == SIOCSIFMTU || request == SIOCADDRT || request == SIOCDELRT; struct task *task = sched_current_task(); - if (change && (!task || !(task_initial_capabilities(task) & (1ULL << CAP_NET_ADMIN)))) + if (change && !task_ns_capable(task, ns ? ns->user_ns : NULL, CAP_NET_ADMIN)) return -LINUX_EPERM; if (request == SIOCADDRT || request == SIOCDELRT) - return interface_route(task, request, address); - if (request == SIOCGIFCONF) return interface_conf(task, address); + return interface_route(ns, task, request, address); + if (request == SIOCGIFCONF) return interface_conf(ns, task, address); switch (request) { case SIOCGIFNAME: case SIOCGIFINDEX: case SIOCGIFHWADDR: case SIOCGIFFLAGS: case SIOCSIFFLAGS: case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFNETMASK: @@ -171,15 +191,15 @@ int net_interface_ioctl(uint32_t request, uint64_t address) uint32_t index; if (request == SIOCGIFNAME) { index = (uint32_t)req.data.value; - if (!net_interface_name(index, req.ifr_name)) return -LINUX_ENODEV; + if (!net_interface_name(ns, index, req.ifr_name)) return -LINUX_ENODEV; net_memcpy((void *)(uintptr_t)address, &req, sizeof(req)); return 0; } req.ifr_name[IFNAMSIZ - 1] = 0; - index = net_interface_index(req.ifr_name); + index = net_interface_index(ns, req.ifr_name); if (!index) return -LINUX_ENODEV; bool loop = index == NET_IF_LOOPBACK; - struct net_interface *iface = net_interface_get(index); + struct net_interface *iface = net_interface_get(ns, index); switch (request) { case SIOCGIFINDEX: req.data.value = (int32_t)index; break; case SIOCGIFHWADDR: @@ -189,18 +209,18 @@ int net_interface_ioctl(uint32_t request, uint64_t address) break; case SIOCGIFFLAGS: req.data.flags = (loop ? IFF_LOOPBACK : IFF_BROADCAST | IFF_MULTICAST) | - (net_interface_is_up(index) ? IFF_UP : 0) | - (net_interface_is_ready(index) ? IFF_RUNNING : 0); + (net_interface_is_up(ns, index) ? IFF_UP : 0) | + (net_interface_is_ready(ns, index) ? IFF_RUNNING : 0); break; case SIOCSIFFLAGS: { uint32_t allowed = IFF_UP | IFF_RUNNING | (loop ? IFF_LOOPBACK : IFF_BROADCAST | IFF_MULTICAST); if ((uint16_t)req.data.flags & ~allowed) return -LINUX_EOPNOTSUPP; bool up = !!(req.data.flags & IFF_UP); - if (net_interface_is_up(index) != up) { - rc = net_interface_set_up(index, up); + if (net_interface_is_up(ns, index) != up) { + rc = net_interface_set_up(ns, index, up); if (rc) return rc; - if (!loop) net_ipv6_link_changed_on(index, up); - netlink_ipv6_changed(); + if (!ns && !loop) net_ipv6_link_changed_on(index, up); + netlink_network_changed(ns); } break; } @@ -213,10 +233,9 @@ int net_interface_ioctl(uint32_t request, uint64_t address) break; default: { struct reliefos_net_config config; - rc = net_interface_get_config(index, &config); + rc = net_interface_get_config(ns, index, &config); if (rc) return rc; if (change) { - if (loop) return -LINUX_EOPNOTSUPP; if (req.data.addr.sa_family != AF_INET) return -LINUX_EAFNOSUPPORT; uint32_t ip = net_get_u32((uint8_t *)&req.data.addr + 4); if (request == SIOCSIFNETMASK && ((~ip) & ((~ip) + 1u))) return -LINUX_EINVAL; @@ -224,7 +243,7 @@ int net_interface_ioctl(uint32_t request, uint64_t address) uint32_t local = request == SIOCSIFADDR ? ip : iface->config.local_ip; uint32_t mask = request == SIOCSIFNETMASK ? ip : iface->config.subnet_mask; uint32_t broadcast = request == SIOCSIFBRDADDR ? ip : local | ~mask; - rc = net_interface_configure_ipv4(index,local,mask,broadcast); + rc = net_interface_configure_ipv4(ns, index,local,mask,broadcast); if (rc) return rc; } else { if (!config.local_ip) return -LINUX_EADDRNOTAVAIL; @@ -241,19 +260,25 @@ int net_interface_ioctl(uint32_t request, uint64_t address) return 0; } +/** @copydoc net_interface_ready */ bool net_interface_ready(void) { - uint32_t index = net_interface_next(NET_IF_LOOPBACK); - return index && net_interface_is_ready(index); + struct net_namespace *ns = NULL; + uint32_t index = net_interface_next(ns, NET_IF_LOOPBACK); + return index && net_interface_is_ready(ns, index); } +/** @copydoc net_interface_present */ bool net_interface_present(void) { - return net_interface_next(NET_IF_LOOPBACK) != 0; + struct net_namespace *ns = NULL; + return net_interface_next(ns, NET_IF_LOOPBACK) != 0; } +/** @copydoc net_interface_admin_up */ bool net_interface_admin_up(void) { - uint32_t index = net_interface_next(NET_IF_LOOPBACK); - return index && net_interface_is_up(index); + struct net_namespace *ns = NULL; + uint32_t index = net_interface_next(ns, NET_IF_LOOPBACK); + return index && net_interface_is_up(ns, index); } diff --git a/net/interface/routes.c b/net/interface/routes.c index f908c3b5..05334c95 100644 --- a/net/interface/routes.c +++ b/net/interface/routes.c @@ -1,21 +1,18 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include #include +#include #include #include -struct ipv4_route_node { - struct ipv4_route_node *next; - struct net_ipv4_route route; -}; -static struct ipv4_route_node *ipv4_routes; +static struct net_ipv4_route_node *ipv4_routes; -/** @brief Remove all explicitly configured routes belonging to a detached NIC. */ -void net_ipv4_routes_remove_interface(uint32_t index) +/** @copydoc net_ipv4_routes_remove_interface */ +void net_ipv4_routes_remove_interface(struct net_namespace *ns, uint32_t index) { - struct ipv4_route_node **slot = &ipv4_routes; + struct net_ipv4_route_node **slot = ns ? &ns->ipv4_routes : &ipv4_routes; while (*slot) { - struct ipv4_route_node *entry = *slot; + struct net_ipv4_route_node *entry = *slot; if (entry->route.ifindex != index) { slot = &entry->next; continue; } *slot = entry->next; kernel_free(entry); @@ -30,16 +27,15 @@ static void ipv4_snapshot_add(struct net_ipv4_route *out, uint32_t capacity, ++*count; } -uint32_t net_ipv4_routes(struct net_ipv4_route *out, uint32_t capacity) +/** @copydoc net_ipv4_routes */ +uint32_t net_ipv4_routes(struct net_namespace *ns, struct net_ipv4_route *out, uint32_t capacity) { uint32_t count = 0; - ipv4_snapshot_add(out, capacity, &count, (struct net_ipv4_route){ - .destination = 0x7f000000u, .mask = 0xff000000u, - .ifindex = NET_IF_LOOPBACK, .flags = RTF_UP}); - for (uint32_t index = net_interface_next(NET_IF_LOOPBACK); index; - index = net_interface_next(index)) { - struct net_interface *iface = net_interface_get(index); - if (!iface || !iface->config.local_ip) continue; + for (uint32_t index = net_interface_next(ns, 0); index; + index = net_interface_next(ns, index)) { + struct net_interface *iface = net_interface_get(ns, index); + if (!iface || !iface->config.local_ip || + (index == NET_IF_LOOPBACK && !iface->up)) continue; ipv4_snapshot_add(out, capacity, &count, (struct net_ipv4_route){ .destination = iface->config.local_ip & iface->config.subnet_mask, .mask = iface->config.subnet_mask, .ifindex = index, .flags = RTF_UP}); @@ -48,18 +44,25 @@ uint32_t net_ipv4_routes(struct net_ipv4_route *out, uint32_t capacity) .gateway = iface->config.gateway_ip, .ifindex = index, .metric = iface->default_metric, .flags = RTF_UP | RTF_GATEWAY}); } - for (struct ipv4_route_node *entry = ipv4_routes; entry; entry = entry->next) + for (struct net_ipv4_route_node *entry = ns ? ns->ipv4_routes : ipv4_routes; entry; entry = entry->next) ipv4_snapshot_add(out, capacity, &count, entry->route); return count; } -/** @brief Replace the current candidate when the route has a better priority. */ -static void ipv4_consider(const struct net_ipv4_route *candidate, uint32_t destination, +/** @brief Replace the current candidate when a usable route has better priority. + * @param ns Borrowed network, NULL for the initial network. + * @param candidate Borrowed route being considered. + * @param destination Host-order destination address. + * @param scope Required interface, or zero for automatic selection. + * @param best In/out selected route. + * @param found In/out flag indicating whether a route has been selected. + */ +static void ipv4_consider(struct net_namespace *ns, const struct net_ipv4_route *candidate, uint32_t destination, uint32_t scope, struct net_ipv4_route *best, bool *found) { if ((scope && candidate->ifindex != scope) || (destination & candidate->mask) != candidate->destination || - !net_interface_is_ready(candidate->ifindex)) return; + !net_interface_is_ready(ns, candidate->ifindex)) return; if (!*found || candidate->mask > best->mask || (candidate->mask == best->mask && candidate->metric < best->metric) || (candidate->mask == best->mask && candidate->metric == best->metric && @@ -69,32 +72,33 @@ static void ipv4_consider(const struct net_ipv4_route *candidate, uint32_t desti } } -int net_ipv4_route_lookup(uint32_t destination, uint32_t source, uint32_t scope, +/** @copydoc net_ipv4_route_lookup */ +int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32_t source, uint32_t scope, struct net_ipv4_path *out) { if (!out) return -LINUX_EINVAL; - if (scope && !net_interface_exists(scope)) return -LINUX_ENODEV; - if (source && !net_interface_for_ipv4(source)) return -LINUX_EADDRNOTAVAIL; + if (scope && !net_interface_exists(ns, scope)) return -LINUX_ENODEV; + if (source && !net_interface_for_ipv4(ns, source)) return -LINUX_EADDRNOTAVAIL; - uint32_t local = net_interface_for_ipv4(destination); + uint32_t local = net_interface_for_ipv4(ns, destination); if (local) { if (scope && scope != local) return -LINUX_ENETUNREACH; - if (!net_interface_is_up(local)) return -LINUX_ENETDOWN; + if (!net_interface_is_up(ns, local)) return -LINUX_ENETDOWN; *out = (struct net_ipv4_path){.source = source ? source : - (local == NET_IF_LOOPBACK ? 0x7f000001u : destination), + (local == NET_IF_LOOPBACK ? net_interface_get(ns, local)->config.local_ip : destination), .destination = destination, .next_hop = destination, .ifindex = local}; return 0; } if (destination == UINT32_MAX) { uint32_t index = scope; if (!index) { - for (index = net_interface_next(NET_IF_LOOPBACK); index; - index = net_interface_next(index)) - if (net_interface_is_ready(index)) break; + for (index = net_interface_next(ns, NET_IF_LOOPBACK); index; + index = net_interface_next(ns, index)) + if (net_interface_is_ready(ns, index)) break; } if (!index || index == NET_IF_LOOPBACK) return -LINUX_ENETUNREACH; - if (!net_interface_is_ready(index)) return -LINUX_ENETDOWN; - struct net_interface *iface = net_interface_get(index); + if (!net_interface_is_ready(ns, index)) return -LINUX_ENETDOWN; + struct net_interface *iface = net_interface_get(ns, index); *out = (struct net_ipv4_path){.source = source ? source : iface->config.local_ip, .destination = destination, .next_hop = destination, .ifindex = index}; return 0; @@ -102,24 +106,25 @@ int net_ipv4_route_lookup(uint32_t destination, uint32_t source, uint32_t scope, struct net_ipv4_route best = {0}; bool found = false; - for (uint32_t index = net_interface_next(NET_IF_LOOPBACK); index; - index = net_interface_next(index)) { - struct net_interface *iface = net_interface_get(index); - if (!iface || !iface->config.local_ip) continue; + for (uint32_t index = net_interface_next(ns, 0); index; + index = net_interface_next(ns, index)) { + struct net_interface *iface = net_interface_get(ns, index); + if (!iface || !iface->config.local_ip || + (index == NET_IF_LOOPBACK && !iface->up)) continue; struct net_ipv4_route connected = { .destination = iface->config.local_ip & iface->config.subnet_mask, .mask = iface->config.subnet_mask, .ifindex = index, .flags = RTF_UP}; - ipv4_consider(&connected, destination, scope, &best, &found); + ipv4_consider(ns, &connected, destination, scope, &best, &found); if (iface->config.gateway_ip) { struct net_ipv4_route def = {.gateway = iface->config.gateway_ip, .ifindex = index, .metric = iface->default_metric, .flags = RTF_UP | RTF_GATEWAY}; - ipv4_consider(&def, destination, scope, &best, &found); + ipv4_consider(ns, &def, destination, scope, &best, &found); } } - for (struct ipv4_route_node *entry = ipv4_routes; entry; entry = entry->next) - ipv4_consider(&entry->route, destination, scope, &best, &found); + for (struct net_ipv4_route_node *entry = ns ? ns->ipv4_routes : ipv4_routes; entry; entry = entry->next) + ipv4_consider(ns, &entry->route, destination, scope, &best, &found); if (!found) return -LINUX_ENETUNREACH; - struct net_interface *iface = net_interface_get(best.ifindex); + struct net_interface *iface = net_interface_get(ns, best.ifindex); if (!source && (!iface || !iface->config.local_ip)) return -LINUX_EADDRNOTAVAIL; *out = (struct net_ipv4_path){.source = source ? source : iface->config.local_ip, .destination = destination, .next_hop = best.gateway ? best.gateway : destination, @@ -127,7 +132,8 @@ int net_ipv4_route_lookup(uint32_t destination, uint32_t source, uint32_t scope, return 0; } -int net_ipv4_route_update(const struct net_ipv4_route *input, bool remove, bool replace) +/** @copydoc net_ipv4_route_update */ +int net_ipv4_route_update(struct net_namespace *ns, const struct net_ipv4_route *input, bool remove, bool replace) { if (!input || ((~input->mask) & ((~input->mask) + 1u)) || (input->flags & ~(RTF_UP | RTF_GATEWAY | RTF_HOST))) return -LINUX_EINVAL; @@ -135,7 +141,7 @@ int net_ipv4_route_update(const struct net_ipv4_route *input, bool remove, bool route.destination &= route.mask; if (!!route.gateway != !!(route.flags & RTF_GATEWAY)) return -LINUX_EINVAL; if ((route.flags & RTF_HOST) && route.mask != UINT32_MAX) return -LINUX_EINVAL; - struct net_interface *iface = net_interface_get(route.ifindex); + struct net_interface *iface = net_interface_get(ns, route.ifindex); if (!iface) return -LINUX_ENODEV; if (!remove && route.gateway && (!iface->config.local_ip || (route.gateway & iface->config.subnet_mask) != @@ -158,7 +164,7 @@ int net_ipv4_route_update(const struct net_ipv4_route *input, bool remove, bool return 0; } - struct ipv4_route_node **slot = &ipv4_routes; + struct net_ipv4_route_node **slot = ns ? &ns->ipv4_routes : &ipv4_routes; while (*slot) { struct net_ipv4_route *r = &(*slot)->route; if (r->destination == route.destination && r->mask == route.mask && @@ -167,7 +173,7 @@ int net_ipv4_route_update(const struct net_ipv4_route *input, bool remove, bool } if (remove) { if (!*slot) return -LINUX_ESRCH; - struct ipv4_route_node *entry = *slot; + struct net_ipv4_route_node *entry = *slot; *slot = entry->next; kernel_free(entry); return 0; @@ -177,7 +183,7 @@ int net_ipv4_route_update(const struct net_ipv4_route *input, bool remove, bool (*slot)->route = route; return 0; } - struct ipv4_route_node *entry = kernel_malloc(sizeof(*entry)); + struct net_ipv4_route_node *entry = kernel_malloc(sizeof(*entry)); if (!entry) return -LINUX_ENOMEM; entry->route = route; entry->next = NULL; diff --git a/net/interface/socket.c b/net/interface/socket.c index 4cc50c64..11903938 100644 --- a/net/interface/socket.c +++ b/net/interface/socket.c @@ -1,5 +1,7 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include +#include +#include #include #include #include @@ -7,14 +9,15 @@ #include /** @brief Apply Linux SO_BINDTODEVICE validation for one socket's bound index. + * @param ns Borrowed creating network, NULL for the initial network. * @param set Update when true, query otherwise. @param address User name buffer. * @param length Input byte count for updates, user socklen_t pointer for queries. * @param index Current bound device; changed only after a successful update. * @return Zero or negative errno. User memory is copied with the socket helpers * under execution ownership. Updating a bound socket requires CAP_NET_RAW in - * the initial user namespace. No provider pointer escapes. + * the network owner user namespace. No provider pointer escapes. */ -int net_interface_device_option(bool set, uint64_t address, uint64_t length, uint32_t *index) +int net_interface_device_option(struct net_namespace *ns, bool set, uint64_t address, uint64_t length, uint32_t *index) { if (!index) return -LINUX_EINVAL; struct task *task = sched_current_task(); @@ -28,9 +31,9 @@ int net_interface_device_option(bool set, uint64_t address, uint64_t length, uin int result = socket_user_import(task, address, name, size); if (result) return result; } - uint32_t selected = name[0] ? net_interface_index(name) : 0; + uint32_t selected = name[0] ? net_interface_index(ns, name) : 0; if (name[0] && !selected) return -LINUX_ENODEV; - if (*index && !(task_initial_capabilities(task) & (1ULL << CAP_NET_RAW))) return -LINUX_EPERM; + if (*index && !task_ns_capable(task, ns ? ns->user_ns : NULL, CAP_NET_RAW)) return -LINUX_EPERM; *index = selected; return 0; } @@ -41,7 +44,7 @@ int net_interface_device_option(bool set, uint64_t address, uint64_t length, uin uint32_t size = 0; if (*index) { if (capacity < sizeof(name)) return -LINUX_EINVAL; - if (!net_interface_name(*index, name)) return -LINUX_ENODEV; + if (!net_interface_name(ns, *index, name)) return -LINUX_ENODEV; while (size < sizeof(name) && name[size]) ++size; ++size; } diff --git a/net/interface/state.c b/net/interface/state.c index db055752..60f1377c 100644 --- a/net/interface/state.c +++ b/net/interface/state.c @@ -2,17 +2,19 @@ #include #include #include +#include #include /* All state is serialized by the existing network execution owner. */ static struct net_interface *interfaces; static struct reliefos_net_config fallback_config; static bool fallback_up = true; -static bool loopback_up = true; - -/* Defined by the IPv4 routing table; remove before releasing interface state. */ -void net_ipv4_routes_remove_interface(uint32_t index); +static struct net_interface initial_loopback = { + .index = NET_IF_LOOPBACK, .up = true, + .config = {.local_ip = 0x7f000001u, .subnet_mask = 0xff000000u}, +}; +/** @copydoc net_interface_register */ int net_interface_register(uint32_t index) { if (index <= NET_IF_LOOPBACK) return -LINUX_EINVAL; @@ -29,40 +31,46 @@ int net_interface_register(uint32_t index) return 0; } +/** @copydoc net_interface_remove */ void net_interface_remove(uint32_t index) { struct net_interface **slot = &interfaces; while (*slot && (*slot)->index != index) slot = &(*slot)->next; if (!*slot) return; struct net_interface *iface = *slot; - net_ipv4_routes_remove_interface(index); + net_ipv4_routes_remove_interface(NULL, index); *slot = iface->next; kernel_free(iface); } -struct net_interface *net_interface_get(uint32_t index) +/** @copydoc net_interface_get */ +struct net_interface *net_interface_get(struct net_namespace *ns, uint32_t index) { - for (struct net_interface *iface = interfaces; iface; iface = iface->next) + if (index == NET_IF_LOOPBACK) return ns ? &ns->loopback : &initial_loopback; + for (struct net_interface *iface = ns ? ns->interfaces : interfaces; iface; iface = iface->next) if (iface->index == index) return iface; return NULL; } -uint32_t net_interface_next(uint32_t after) +/** @copydoc net_interface_next */ +uint32_t net_interface_next(struct net_namespace *ns, uint32_t after) { if (after < NET_IF_LOOPBACK) return NET_IF_LOOPBACK; - for (struct net_interface *iface = interfaces; iface; iface = iface->next) + for (struct net_interface *iface = ns ? ns->interfaces : interfaces; iface; iface = iface->next) if (iface->index > after) return iface->index; return 0; } -bool net_interface_exists(uint32_t index) +/** @copydoc net_interface_exists */ +bool net_interface_exists(struct net_namespace *ns, uint32_t index) { - return index == NET_IF_LOOPBACK || net_interface_get(index) != NULL; + return index == NET_IF_LOOPBACK || net_interface_get(ns, index) != NULL; } -bool net_interface_name(uint32_t index, char out[NET_IF_NAME_LEN]) +/** @copydoc net_interface_name */ +bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[NET_IF_NAME_LEN]) { - if (!out || !net_interface_exists(index)) return false; + if (!out || !net_interface_exists(ns, index)) return false; __builtin_memset(out, 0, NET_IF_NAME_LEN); if (index == NET_IF_LOOPBACK) { out[0] = 'l'; out[1] = 'o'; @@ -76,7 +84,8 @@ bool net_interface_name(uint32_t index, char out[NET_IF_NAME_LEN]) return true; } -uint32_t net_interface_index(const char *name) +/** @copydoc net_interface_index */ +uint32_t net_interface_index(struct net_namespace *ns, const char *name) { if (!name) return 0; if (!__builtin_strcmp(name, "lo")) return NET_IF_LOOPBACK; @@ -91,51 +100,56 @@ uint32_t net_interface_index(const char *name) value = value * 10u + (uint32_t)(name[i] - '0'); } uint32_t index = value + 2u; - return net_interface_get(index) ? index : 0; + return net_interface_get(ns, index) ? index : 0; } -bool net_interface_is_up(uint32_t index) +/** @copydoc net_interface_is_up */ +bool net_interface_is_up(struct net_namespace *ns, uint32_t index) { - if (index == NET_IF_LOOPBACK) return loopback_up; - struct net_interface *iface = net_interface_get(index); + struct net_interface *iface = net_interface_get(ns, index); return iface && iface->up; } -int net_interface_set_up(uint32_t index, bool up) +/** @copydoc net_interface_set_up */ +int net_interface_set_up(struct net_namespace *ns, uint32_t index, bool up) { - if (index == NET_IF_LOOPBACK) { loopback_up = up; return 0; } - struct net_interface *iface = net_interface_get(index); + struct net_interface *iface = net_interface_get(ns, index); if (!iface) return -LINUX_ENODEV; + if (index == NET_IF_LOOPBACK && up && !iface->config.local_ip) { + iface->config.local_ip = 0x7f000001u; + iface->config.subnet_mask = 0xff000000u; + } iface->up = up; return 0; } -bool net_interface_is_ready(uint32_t index) +/** @copydoc net_interface_is_ready */ +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { - if (index == NET_IF_LOOPBACK) return loopback_up; - struct net_interface *iface = net_interface_get(index); - return iface && iface->up && netdev_is_ready(index); + struct net_interface *iface = net_interface_get(ns, index); + return iface && iface->up && (index == NET_IF_LOOPBACK || netdev_is_ready(index)); } -uint32_t net_interface_for_ipv4(uint32_t ip) +/** @copydoc net_interface_for_ipv4 */ +uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip) { - if ((ip >> 24) == 127) return NET_IF_LOOPBACK; + struct net_interface *loopback = net_interface_get(ns, NET_IF_LOOPBACK); + if ((ip >> 24) == 127 && (loopback->config.local_ip >> 24) == 127) + return NET_IF_LOOPBACK; if (!ip) return 0; - for (struct net_interface *iface = interfaces; iface; iface = iface->next) + if (loopback->config.local_ip == ip) return NET_IF_LOOPBACK; + for (struct net_interface *iface = ns ? ns->interfaces : interfaces; iface; iface = iface->next) if (iface->config.local_ip == ip) return iface->index; return 0; } -int net_interface_get_config(uint32_t index, struct reliefos_net_config *out) +/** @copydoc net_interface_get_config */ +int net_interface_get_config(struct net_namespace *ns, uint32_t index, struct reliefos_net_config *out) { if (!out) return -LINUX_EINVAL; - if (index == NET_IF_LOOPBACK) { - *out = (struct reliefos_net_config){.local_ip = 0x7f000001u, - .subnet_mask = 0xff000000u}; - return 0; - } - struct net_interface *iface = net_interface_get(index); + struct net_interface *iface = net_interface_get(ns, index); if (!iface) return -LINUX_ENODEV; + if (index == NET_IF_LOOPBACK) { *out = iface->config; return 0; } struct e1000_info info = {0}; netdev_get_info(index, &info); *out = iface->config; @@ -148,11 +162,13 @@ int net_interface_get_config(uint32_t index, struct reliefos_net_config *out) return 0; } +/** @copydoc net_interface_legacy_config */ struct reliefos_net_config *net_interface_legacy_config(void) { return interfaces ? &interfaces->config : &fallback_config; } +/** @copydoc net_interface_legacy_up */ bool *net_interface_legacy_up(void) { return interfaces ? &interfaces->up : &fallback_up; diff --git a/net/internal.h b/net/internal.h index deefe18a..4297595d 100644 --- a/net/internal.h +++ b/net/internal.h @@ -1099,12 +1099,8 @@ int net_http_get(struct reliefos_net_http_get *request); */ void net_device_info(uint32_t *flags, uint64_t *mac_value, uint32_t *local_ip); -/** @brief Apply/query eth0 through the Linux native interface ioctl ABI. - * Only the real Ethernet interface and the supported default route are exposed. - * Unsupported routing/features return an error rather than retaining inert state. - * Changes require initial user namespace CAP_NET_ADMIN. - */ -int net_interface_ioctl(uint32_t request, uint64_t address); +/** @copydoc net_interface_ioctl */ +int net_interface_ioctl(struct net_namespace *ns, uint32_t request, uint64_t address); /** @brief Report the real administrative and hardware state of eth0. */ bool net_interface_ready(void); diff --git a/net/ipv4/core.c b/net/ipv4/core.c index ae35a847..e2d47a17 100644 --- a/net/ipv4/core.c +++ b/net/ipv4/core.c @@ -15,7 +15,7 @@ static uint16_t net_packet_ip_id; */ static int net_ip_for_us(uint32_t dst_ip) { - return net_interface_for_ipv4(dst_ip) != 0 || + return net_interface_for_ipv4(NULL, dst_ip) != 0 || dst_ip == 0xffffffffu || dst_ip == 0; } @@ -107,7 +107,7 @@ int net_ipv4_send_raw_on(uint32_t ifindex, uint32_t destination, uint32_t source uint8_t frame[1514] = {0}; uint8_t *ip = frame + 14; struct net_ipv4_path path; - int route = net_ipv4_route_lookup(destination, source, ifindex, &path); + int route = net_ipv4_route_lookup(NULL, destination, source, ifindex, &path); if (route < 0) return route; ifindex = path.ifindex; source = path.source; @@ -132,7 +132,7 @@ int net_ipv4_send_raw_on(uint32_t ifindex, uint32_t destination, uint32_t source else if (net_resolve_mac_on(ifindex, path.next_hop, 1000, frame) < 0) return -LINUX_EHOSTUNREACH; net_memcpy(frame + 6, netdev_mac(ifindex), 6); net_put_u16(frame + 12, 0x0800); - int ret = net_interface_is_ready(ifindex) ? netdev_send(ifindex, frame, length + header + 14) : -LINUX_ENETDOWN; + int ret = net_interface_is_ready(NULL, ifindex) ? netdev_send(ifindex, frame, length + header + 14) : -LINUX_ENETDOWN; return ret < 0 ? ret : (int)length; } diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c index 8b100dd6..0c5fecf2 100644 --- a/net/ipv4/udp.c +++ b/net/ipv4/udp.c @@ -45,7 +45,7 @@ int net_send_udp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint32_t sr net_put_u16(udp + 4, udp_len); net_put_u16(udp + 6, 0); net_memcpy(udp + 8, payload, payload_len); - return net_interface_is_ready(ifindex) ? netdev_send(ifindex, frame, 42u + payload_len) : -LINUX_ENETDOWN; + return net_interface_is_ready(NULL, ifindex) ? netdev_send(ifindex, frame, 42u + payload_len) : -LINUX_ENETDOWN; } /** @@ -119,10 +119,10 @@ int net_ipv4_send_udp_on(uint32_t ifindex, uint32_t source, uint32_t destination { if (length > 1472 || (length && !data)) return -LINUX_EMSGSIZE; struct net_ipv4_path path; - int result = net_ipv4_route_lookup(destination, source, ifindex, &path); + int result = net_ipv4_route_lookup(NULL, destination, source, ifindex, &path); if (result < 0) return result; uint8_t mac[6]; - struct net_interface *interface = net_interface_get(path.ifindex); + struct net_interface *interface = net_interface_get(NULL, path.ifindex); if (destination == UINT32_MAX || (interface && destination == interface->broadcast)) net_memcpy(mac, net_broadcast_mac, 6); else if (net_resolve_mac_on(path.ifindex, path.next_hop, 1000, mac) < 0) @@ -150,7 +150,7 @@ int net_send_udp_to_mac(const uint8_t *mac, uint32_t source, uint32_t destinatio uint16_t source_port, uint16_t destination_port, const uint8_t *data, uint32_t length) { struct net_ipv4_path path; - int result = net_ipv4_route_lookup(destination, source, 0, &path); + int result = net_ipv4_route_lookup(NULL, destination, source, 0, &path); if (result < 0) return result; return net_send_udp_to_mac_on(path.ifindex, mac, source, destination, source_port, destination_port, data, length); diff --git a/net/ipv6/core.c b/net/ipv6/core.c index bcab80c4..97828e51 100644 --- a/net/ipv6/core.c +++ b/net/ipv6/core.c @@ -270,7 +270,7 @@ uint32_t net_ipv6_neighbors(struct net_ipv6_neighbor *out,uint32_t capacity) * @param ifindex Interface. @param delta One to join or minus one to leave. @return Zero or errno. */ int net_ipv6_multicast_change(const struct in6_addr *address,uint32_t ifindex,int delta) { - if(!address || !ipv6_multicast(address) || !net_interface_exists(ifindex) || (delta!=1 && delta!=-1))return -LINUX_EINVAL; + if(!address || !ipv6_multicast(address) || !net_interface_exists(NULL, ifindex) || (delta!=1 && delta!=-1))return -LINUX_EINVAL; struct ipv6_group_slot *g=ipv6_find_group(address,ifindex); if(delta<0){if(!g)return -LINUX_EADDRNOTAVAIL;if(--g->refs==0){ /* Keep the group briefly to send an MLD state-change record. */ @@ -285,7 +285,7 @@ int net_ipv6_multicast_change(const struct in6_addr *address,uint32_t ifindex,in * @param remove Remove rather than add. @return Zero or negative errno. */ int net_ipv6_route_update(const struct net_ipv6_route *route,bool remove) { - if(!route || route->prefix_length>128 || !net_interface_exists(route->ifindex) || + if(!route || route->prefix_length>128 || !net_interface_exists(NULL, route->ifindex) || ipv6_multicast(&route->gateway))return -LINUX_EINVAL; struct net_ipv6_route normalized=*route;ipv6_mask(&normalized.destination,normalized.prefix_length); struct ipv6_route_slot *free_slot=0; @@ -335,7 +335,7 @@ static int ipv6_connected_route(const struct in6_addr *address,uint32_t bits,uin * @param autonomous True for router-derived addresses. @return Zero or negative errno. */ static int ipv6_address_set(const struct net_ipv6_address *address,bool remove,bool autonomous) { - if(!address || address->prefix_length>128 || !net_interface_exists(address->ifindex) || + if(!address || address->prefix_length>128 || !net_interface_exists(NULL, address->ifindex) || ipv6_multicast(&address->address) || ipv6_unspecified(&address->address) || address->preferred_until>address->valid_until)return -LINUX_EINVAL; struct ipv6_address_slot *slot=ipv6_find_address(&address->address,address->ifindex); @@ -386,7 +386,7 @@ int net_ipv6_address_update(const struct net_ipv6_address *address,bool remove) int net_ipv6_route(const struct in6_addr *destination,uint32_t scope, const struct in6_addr *bound,struct net_ipv6_path *out_path) { - if(!destination || !out_path || ipv6_unspecified(destination) || (scope && !net_interface_exists(scope)))return -LINUX_EINVAL; + if(!destination || !out_path || ipv6_unspecified(destination) || (scope && !net_interface_exists(NULL, scope)))return -LINUX_EINVAL; uint64_t now=time_uptime_ms();uint32_t ifindex=0,mtu=IPV6_LINK_MTU; struct in6_addr next=*destination; struct ipv6_address_slot *local=ipv6_find_address(destination,scope); @@ -423,7 +423,7 @@ int net_ipv6_route(const struct in6_addr *destination,uint32_t scope, if(scope && scope!=ifindex)return -LINUX_ENETUNREACH; if(ifindex!=1){ struct ipv6_link *link=ipv6_link(ifindex,false); - if(!link || !link->up || !net_interface_is_ready(ifindex))return -LINUX_ENETDOWN; + if(!link || !link->up || !net_interface_is_ready(NULL, ifindex))return -LINUX_ENETDOWN; if(mtu!=65575)mtu=link->mtu; if(ipv6_equal(destination,&ipv6_loop))return -LINUX_ENETUNREACH; } @@ -458,7 +458,7 @@ static int ipv6_send_frame(uint32_t ifindex,const uint8_t mac[6],const struct in uint32_t flowinfo,const uint8_t *payload,uint32_t length) { struct ipv6_link *link=ipv6_link(ifindex,false); - if(!link || !link->up || !net_interface_is_ready(ifindex))return -LINUX_ENETDOWN; + if(!link || !link->up || !net_interface_is_ready(NULL, ifindex))return -LINUX_ENETDOWN; if(length>IPV6_LINK_MTU-40)return -LINUX_EMSGSIZE; uint8_t frame[14+IPV6_LINK_MTU];uint8_t *ip=frame+14;const uint8_t *flow=(const uint8_t *)&flowinfo; net_memcpy(frame,mac,6);net_memcpy(frame+6,netdev_mac(ifindex),6);net_put_u16(frame+12,IPV6_ETHERTYPE);ip[0]=(uint8_t)(0x60|(flow[0]&15)); @@ -563,9 +563,9 @@ int net_ipv6_output(const struct net_ipv6_path *path,uint8_t protocol,const void { if(length>65535)return -LINUX_EMSGSIZE; if(!path || (!data && length) || hops < -1 || hops>255 || - !net_interface_exists(path->ifindex))return -LINUX_EINVAL; + !net_interface_exists(NULL, path->ifindex))return -LINUX_EINVAL; struct ipv6_link *link=path->ifindex==1?0:ipv6_link(path->ifindex,false); - if(path->ifindex!=1 && (!link || !link->up || !net_interface_is_ready(path->ifindex)))return -LINUX_ENETDOWN; + if(path->ifindex!=1 && (!link || !link->up || !net_interface_is_ready(NULL, path->ifindex)))return -LINUX_ENETDOWN; if(dont_fragment && length+40>path->mtu)return -LINUX_EMSGSIZE; struct ipv6_address_slot *dst=ipv6_find_address(&path->destination,path->ifindex); if(path->ifindex==1 || (dst && !(dst->value.flags&(NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED)))) @@ -1029,7 +1029,7 @@ void net_ipv6_input_on(uint32_t ifindex,const uint8_t *frame,uint32_t length) { struct ipv6_link *link=ipv6_link(ifindex,false); if(!frame || length<54 || net_get_u16(frame+12)!=IPV6_ETHERTYPE || - !link || !link->up || !net_interface_is_ready(ifindex))return; + !link || !link->up || !net_interface_is_ready(NULL, ifindex))return; ipv6_receive_ip(frame+14,length-14,ifindex,frame+6,false); } void net_ipv6_input(const uint8_t *frame,uint32_t length) @@ -1078,7 +1078,7 @@ static void ipv6_clear_link_state(uint32_t ifindex) int net_ipv6_link_changed_on(uint32_t ifindex,bool up) { if(!ipv6_initialized)return 0; - if(ifindex==1 || !net_interface_exists(ifindex))return -LINUX_ENODEV; + if(ifindex==1 || !net_interface_exists(NULL, ifindex))return -LINUX_ENODEV; bool enabled=up && netdev_is_ready(ifindex); struct ipv6_link *link=ipv6_link(ifindex,enabled); if(!link)return enabled?-LINUX_ENOMEM:0; @@ -1129,13 +1129,13 @@ void net_ipv6_init(void) (void)net_ipv6_address_update(&loop,false); struct net_ipv6_route route={0};route.destination=ipv6_loop;route.ifindex=1;route.prefix_length=128; route.valid_until=IPV6_FOREVER;route.flags=RTF_UP|RTF_HOST;(void)net_ipv6_route_update(&route,false); - for(uint32_t i=netdev_next(0);i;i=netdev_next(i))(void)net_ipv6_link_changed_on(i,net_interface_is_up(i)); + for(uint32_t i=netdev_next(0);i;i=netdev_next(i))(void)net_ipv6_link_changed_on(i,net_interface_is_up(NULL, i)); } /** @brief Check if task-context receive or timer service should continue. */ bool net_ipv6_maintenance_pending(void) { if(ipv6_initialized)for(uint32_t i=netdev_next(0);i;i=netdev_next(i)) - if(net_interface_is_ready(i))return true; + if(net_interface_is_ready(NULL, i))return true; for(uint32_t i=0;iup)!=up)(void)net_ipv6_link_changed_on(i,up); } uint64_t now=time_uptime_ms(); diff --git a/net/link/arp.c b/net/link/arp.c index 630d4561..cf153c34 100644 --- a/net/link/arp.c +++ b/net/link/arp.c @@ -61,7 +61,7 @@ static void net_write_arp_on(uint32_t ifindex, uint8_t frame[42], uint16_t op, const uint8_t dst_mac[6], const uint8_t target_mac[6], uint32_t target_ip) { struct reliefos_net_config config = {0}; - net_interface_get_config(ifindex, &config); + net_interface_get_config(NULL, ifindex, &config); net_write_eth_on(ifindex, frame, dst_mac, ETH_TYPE_ARP); net_put_u16(frame + 14, ARP_HTYPE_ETHERNET); net_put_u16(frame + 16, ETH_TYPE_IPV4); @@ -92,8 +92,8 @@ void net_handle_arp_on(uint32_t ifindex, const uint8_t *frame, uint32_t len, arp_wait->done = 1; } struct reliefos_net_config config = {0}; - if (op == ARP_OPER_REQUEST && !net_interface_get_config(ifindex, &config) && - config.local_ip && target_ip == config.local_ip && net_interface_is_ready(ifindex)) { + if (op == ARP_OPER_REQUEST && !net_interface_get_config(NULL, ifindex, &config) && + config.local_ip && target_ip == config.local_ip && net_interface_is_ready(NULL, ifindex)) { uint8_t reply[42]; net_write_arp_on(ifindex, reply, ARP_OPER_REPLY, sender_mac, sender_mac, sender_ip); (void)netdev_send(ifindex, reply, sizeof(reply)); @@ -114,13 +114,13 @@ void net_handle_arp(const uint8_t *frame, uint32_t len, struct net_arp_wait *wai int net_resolve_mac_on(uint32_t ifindex, uint32_t ip, uint32_t timeout_ms, uint8_t out_mac[6]) { if (!out_mac || !ip) return -LINUX_EINVAL; - if (!net_interface_is_ready(ifindex)) return -LINUX_ENETDOWN; + if (!net_interface_is_ready(NULL, ifindex)) return -LINUX_ENETDOWN; if (net_arp_lookup_on(ifindex, ip, out_mac)) return 0; struct net_arp_wait wait = {.ifindex = ifindex, .ip = ip}; uint64_t start = time_uptime_ms(), next_request = start; uint32_t spins = 0; while (!net_timeout_expired(start, timeout_ms, spins++)) { - if (!net_interface_is_ready(ifindex)) return -LINUX_ENETDOWN; + if (!net_interface_is_ready(NULL, ifindex)) return -LINUX_ENETDOWN; uint64_t now = time_uptime_ms(); if (now >= next_request) { uint8_t frame[42], zero[6] = {0}; @@ -145,7 +145,7 @@ int net_resolve_mac_on(uint32_t ifindex, uint32_t ip, uint32_t timeout_ms, uint8 int net_resolve_mac(uint32_t ip, uint32_t timeout_ms, uint8_t out_mac[6]) { struct net_ipv4_path path; - int result = net_ipv4_route_lookup(ip, 0, 0, &path); + int result = net_ipv4_route_lookup(NULL, ip, 0, 0, &path); if (result < 0) return result; return net_resolve_mac_on(path.ifindex, ip, timeout_ms, out_mac); } @@ -158,7 +158,7 @@ void net_arp_proc_emit(struct text_stream *stream) for (uint32_t i = 0; i < NET_ARP_CACHE_SIZE; ++i) { const struct net_arp_cache_entry *entry = &net_arp_cache[i]; char name[NET_IF_NAME_LEN]; - if (!entry->ip || !net_interface_name(entry->ifindex, name)) continue; + if (!entry->ip || !net_interface_name(NULL, entry->ifindex, name)) continue; for (int byte = 3; byte >= 0; --byte) { text_unsigned(stream, (entry->ip >> (byte * 8)) & 255); if (byte) text_string(stream, "."); diff --git a/net/namespace/namespace.c b/net/namespace/namespace.c index 3939b4bc..7cc46ad8 100644 --- a/net/namespace/namespace.c +++ b/net/namespace/namespace.c @@ -11,7 +11,8 @@ int net_namespace_create(struct user_namespace *owner, struct net_namespace **ou *out = NULL; struct net_namespace *ns = kernel_malloc(sizeof(*ns)); if (!ns) return -LINUX_ENOMEM; - *ns = (struct net_namespace){.references = 1, .user_ns = user_namespace_get(owner)}; + *ns = (struct net_namespace){.references = 1, .user_ns = user_namespace_get(owner), + .loopback = {.index = NET_IF_LOOPBACK}}; *out = ns; return 0; } @@ -27,6 +28,16 @@ struct net_namespace *net_namespace_get(struct net_namespace *ns) void net_namespace_put(struct net_namespace *ns) { if (!ns || __atomic_sub_fetch(&ns->references, 1, __ATOMIC_ACQ_REL)) return; + while (ns->interfaces) { + struct net_interface *iface = ns->interfaces; + ns->interfaces = iface->next; + kernel_free(iface); + } + while (ns->ipv4_routes) { + struct net_ipv4_route_node *route = ns->ipv4_routes; + ns->ipv4_routes = route->next; + kernel_free(route); + } user_namespace_put(ns->user_ns); kernel_free(ns); } diff --git a/net/proc.c b/net/proc.c index edaa026a..d20f0092 100644 --- a/net/proc.c +++ b/net/proc.c @@ -34,7 +34,7 @@ static int proc_ipv6_addresses(struct text_stream *s) for (uint32_t i=0;iifindex,name)) continue; + if (!net_interface_name(NULL, a->ifindex,name)) continue; proc_ipv6(s,&a->address); text_string(s," "); text_hex(s,a->ifindex,2); text_string(s," "); text_hex(s,a->prefix_length,2); text_string(s," "); text_hex(s,proc_ipv6_scope(a->scope),2); @@ -58,7 +58,7 @@ static int proc_ipv6_routes(struct text_stream *s) for (uint32_t i=0;iifindex,name)) continue; + if (!net_interface_name(NULL, r->ifindex,name)) continue; proc_ipv6(s,&r->destination); text_string(s," "); text_hex(s,r->prefix_length,2); text_string(s," "); proc_ipv6(s,&zero); text_string(s," 00 "); proc_ipv6(s,&r->gateway); text_string(s," "); text_hex(s,r->metric,8); @@ -75,19 +75,23 @@ static void proc_ip(struct text_stream *s, uint32_t ip) { text_hex(s, __builtin_bswap32(ip), 8); } -/** @brief Render core network state without driving the NIC or timers. +/** @brief Render the caller's network state without driving the NIC or timers. * @param s Required slice. @param leaf Known name inside proc/net. * @return Zero or ENOENT. Execution-owned; no code/reference escapes. */ int net_proc_emit(struct text_stream *s, const char *leaf) { + struct task *task = sched_current_task(); + struct net_namespace *ns = task ? task->net_ns : NULL; if (!__builtin_strcmp(leaf, "if_inet6")) - return proc_ipv6_addresses(s); + return ns ? 0 : proc_ipv6_addresses(s); if (!__builtin_strcmp(leaf, "ipv6_route")) - return proc_ipv6_routes(s); + return ns ? 0 : proc_ipv6_routes(s); if (!__builtin_strcmp(leaf, "tcp6") || !__builtin_strcmp(leaf, "udp6") || !__builtin_strcmp(leaf, "raw6")) { - net_ipv6_transport_proc_emit(s,leaf); + if (!ns) net_ipv6_transport_proc_emit(s,leaf); + else text_string(s, " sl local_address rem_address st tx_queue rx_queue tr tm->when " + "retrnsmt uid timeout inode\n"); return 0; } if (!__builtin_strcmp(leaf, "dev")) { @@ -95,12 +99,13 @@ int net_proc_emit(struct text_stream *s, const char *leaf) "Transmit\n face |bytes packets errs drop fifo frame compressed " "multicast|bytes packets errs drop fifo colls carrier compressed\n"); /* Loopback datagrams are accounted by their owner rather than the NIC. */ - net_loopback_proc_emit(s); - for (uint32_t index=net_interface_next(NET_IF_LOOPBACK);index; - index=net_interface_next(index)) { + if (!ns) net_loopback_proc_emit(s); + else text_string(s, " lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n"); + for (uint32_t index=net_interface_next(ns, NET_IF_LOOPBACK);index; + index=net_interface_next(ns, index)) { struct net_proc_counters c; char name[NET_IF_NAME_LEN]; - if (!net_interface_name(index,name)) continue; + if (!net_interface_name(ns, index,name)) continue; netdev_counters(index,&c); text_string(s, " "); text_string(s,name); text_string(s, ":"); uint64_t fields[] = {c.rx_bytes, c.rx_packets, c.rx_errors, c.rx_drops, 0, 0, 0, 0, @@ -114,14 +119,14 @@ int net_proc_emit(struct text_stream *s, const char *leaf) } else if (!__builtin_strcmp(leaf, "route")) { text_string(s, "Iface\tDestination\tGateway " "\tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n"); - uint32_t count=net_ipv4_routes(NULL,0); + uint32_t count=net_ipv4_routes(ns, NULL,0); if (count > UINT32_MAX / sizeof(struct net_ipv4_route)) return -LINUX_ENOMEM; struct net_ipv4_route *routes=count ? kernel_malloc((size_t)count*sizeof(*routes)) : NULL; if (count && !routes) return -LINUX_ENOMEM; - if (net_ipv4_routes(routes,count)>count) { kernel_free(routes); return -LINUX_EAGAIN; } + if (net_ipv4_routes(ns, routes,count)>count) { kernel_free(routes); return -LINUX_EAGAIN; } for (uint32_t i=0;iwhen " + "retrnsmt uid timeout inode\n"); + } else if (!__builtin_strcmp(leaf, "unix")) unix_proc_emit(s); else if (!__builtin_strcmp(leaf, "tcp")) { text_string(s, " sl local_address rem_address st tx_queue rx_queue tr tm->when " "retrnsmt uid timeout inode\n"); uint32_t index = 0; - for (struct net_socket *n = net_sockets; n; n = n->registry_next) { + for (struct net_socket *n = ns ? NULL : net_sockets; n; n = n->registry_next) { if (!n->used || !n->local_port || n->ipv6) continue; unsigned state = n->state == RELIEFOS_NET_TCP_SYN_SENT ? 2 diff --git a/net/socket/control.c b/net/socket/control.c index 8655649f..37415114 100644 --- a/net/socket/control.c +++ b/net/socket/control.c @@ -16,7 +16,8 @@ * @param file Borrowed socket OFD under execution ownership. * @param request Native ioctl number. @param address User argument address. * @return Zero, negative errno, or a user-memory prerequisite wait marker. - * Interface changes use initial user namespace CAP_NET_ADMIN. + * Netlink interface changes use the retained network's user owner. Internet + * transport and private control operations currently use the initial network. */ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) { @@ -39,8 +40,11 @@ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) *(int *)(uintptr_t)address = bytes; return 0; } - if (request >= 0x8900 && request <= 0x89ff) - return net_interface_ioctl(request, address); + if (request >= 0x8900 && request <= 0x89ff) { + if (file->kind == TASK_FILE_KIND_NETLINK) + return task_netlink_ioctl(file, request, address); + return net_interface_ioctl(NULL, request, address); + } if (request != RELIEFOS_NET_CONTROL_IOCTL) return -LINUX_ENOTTY; struct reliefos_net_control control; int rc=socket_user_import(task,address,&control,sizeof(control));if(rc)return rc; diff --git a/net/socket/netlink.c b/net/socket/netlink.c index 3218d7de..57e392b2 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -52,24 +53,29 @@ struct netlink_socket { }; struct nl_builder { struct netlink_message *message, *completion; + struct net_namespace *net_ns; /* Borrowed from the request's retained socket. */ uint32_t used, port; }; static struct netlink_socket *netlink_sockets; static uint32_t netlink_auto_port = 0x80000000u; static uint64_t netlink_ino; static uint64_t uevent_seqnum; -static struct net_ipv6_address *nl_previous_addresses; -static struct net_ipv6_route *nl_previous_routes; -static uint32_t nl_previous_address_count, nl_previous_route_count; struct nl_link_state { uint32_t index; char name[NET_IF_NAME_LEN]; uint8_t mac[6]; bool up, active; }; -static struct nl_link_state *nl_previous_links; -static uint32_t nl_previous_link_count; -static bool nl_snapshot_ready; +/** @brief Change baseline borrowed from a namespace's retained route subscribers. */ +struct nl_snapshot { + struct nl_snapshot *next; + struct net_namespace *net_ns; + struct net_ipv6_address *addresses; + struct net_ipv6_route *routes; + struct nl_link_state *links; + uint32_t address_count, route_count, link_count; +}; +static struct nl_snapshot *nl_snapshots; #define NL_SUPPORTED_GROUPS (RTMGRP_LINK|RTMGRP_IPV6_IFADDR|RTMGRP_IPV6_ROUTE) /** @brief Resolve the netlink socket attached to an open description. @@ -237,8 +243,8 @@ static int nl_link_snapshot(struct nl_builder *b, uint32_t seq, bool multi, static int nl_link(struct nl_builder *b, uint32_t seq, int index, bool multi) { struct nl_link_state link = {.index=(uint32_t)index}; - if (!net_interface_name(link.index,link.name)) return -LINUX_ENODEV; - link.up = net_interface_is_up(link.index); + if (!net_interface_name(b->net_ns, link.index,link.name)) return -LINUX_ENODEV; + link.up = net_interface_is_up(b->net_ns, link.index); if (link.index != NET_IF_LOOPBACK) { struct e1000_info info = {0}; netdev_get_info(link.index,&info); link.active = info.active != 0; @@ -259,7 +265,7 @@ static int nl_address4(struct nl_builder *b, uint32_t seq, uint32_t index, *m = (struct ifaddrmsg){.ifa_family=AF_INET,.ifa_prefixlen=prefix,.ifa_flags=IFA_F_PERMANENT, .ifa_scope=index==1 ? RT_SCOPE_HOST : RT_SCOPE_UNIVERSE,.ifa_index=index}; char name[NET_IF_NAME_LEN]; - if (!net_interface_name(index,name)) return -LINUX_ENODEV; + if (!net_interface_name(b->net_ns, index,name)) return -LINUX_ENODEV; if (nl_attr(b,start,IFA_ADDRESS,&ip,4) || nl_attr(b,start,IFA_LOCAL,&ip,4) || nl_attr(b,start,IFA_LABEL,name,__builtin_strlen(name)+1) || (index!=NET_IF_LOOPBACK && nl_attr(b,start,IFA_BROADCAST,&br,4))) return -LINUX_ENOBUFS; @@ -326,11 +332,12 @@ static int nl_route4(struct nl_builder *b, uint32_t seq, uint32_t destination, } /** @brief Copy the current address snapshot without retaining protocol pointers. + * @param ns Borrowed network, NULL for the initial network. * @param out Receives owned array or NULL. @param count Receives element count. * @return Zero or allocation/budget error. */ -static int nl_addresses(struct net_ipv6_address **out, uint32_t *count) +static int nl_addresses(struct net_namespace *ns, struct net_ipv6_address **out, uint32_t *count) { - *out = NULL; *count = net_ipv6_addresses(NULL,0); + *out = NULL; *count = ns ? 0 : net_ipv6_addresses(NULL,0); if (!*count) return 0; if (*count > NL_MESSAGE_MAX / sizeof(**out)) return -LINUX_ENOBUFS; *out = kernel_malloc((size_t)*count * sizeof(**out)); @@ -340,11 +347,12 @@ static int nl_addresses(struct net_ipv6_address **out, uint32_t *count) } /** @brief Copy the current route snapshot without retaining protocol pointers. + * @param ns Borrowed network, NULL for the initial network. * @param out Receives owned array or NULL. @param count Receives element count. * @return Zero or allocation/budget error. */ -static int nl_routes(struct net_ipv6_route **out, uint32_t *count) +static int nl_routes(struct net_namespace *ns, struct net_ipv6_route **out, uint32_t *count) { - *out = NULL; *count = net_ipv6_routes(NULL,0); + *out = NULL; *count = ns ? 0 : net_ipv6_routes(NULL,0); if (!*count) return 0; if (*count > NL_MESSAGE_MAX / sizeof(**out)) return -LINUX_ENOBUFS; *out = kernel_malloc((size_t)*count * sizeof(**out)); @@ -353,22 +361,26 @@ static int nl_routes(struct net_ipv6_route **out, uint32_t *count) return 0; } -/** @brief Copy every live link for dumps and subsequent change detection. */ -static int nl_links(struct nl_link_state **out, uint32_t *count) +/** @brief Copy every live link for dumps and subsequent change detection. + * @param ns Borrowed network, NULL for the initial network. + * @param out Required owned snapshot output. @param count Required element count. + * @return Zero or negative errno. Failure releases every candidate allocation. + */ +static int nl_links(struct net_namespace *ns, struct nl_link_state **out, uint32_t *count) { *out = NULL; *count = 0; - for (uint32_t index=net_interface_next(0);index;index=net_interface_next(index)) ++*count; + for (uint32_t index=net_interface_next(ns, 0);index;index=net_interface_next(ns, index)) ++*count; if (!*count) return 0; if (*count > NL_MESSAGE_MAX / sizeof(**out)) return -LINUX_ENOBUFS; struct nl_link_state *links=kernel_malloc((size_t)*count*sizeof(*links)); if (!links) return -LINUX_ENOMEM; uint32_t used=0; - for (uint32_t index=net_interface_next(0);index;index=net_interface_next(index)) { + for (uint32_t index=net_interface_next(ns, 0);index;index=net_interface_next(ns, index)) { if (used==*count) { kernel_free(links); return -LINUX_EAGAIN; } struct nl_link_state *link=&links[used++]; __builtin_memset(link,0,sizeof(*link)); link->index=index; - if (!net_interface_name(index,link->name)) { kernel_free(links); return -LINUX_EAGAIN; } - link->up=net_interface_is_up(index); + if (!net_interface_name(ns, index,link->name)) { kernel_free(links); return -LINUX_EAGAIN; } + link->up=net_interface_is_up(ns, index); if (index!=NET_IF_LOOPBACK) { struct e1000_info info={0}; netdev_get_info(index,&info); link->active=info.active!=0; __builtin_memcpy(link->mac,info.mac,sizeof(link->mac)); @@ -377,34 +389,66 @@ static int nl_links(struct nl_link_state **out, uint32_t *count) *out=links; *count=used; return 0; } -/** @brief Drop the owned change-detection baseline after the last subscriber leaves. */ -static void nl_forget_snapshot(void) +/** @brief Find a namespace's baseline under network execution ownership. + * @param ns Borrowed scope, NULL for the initial network. + * @return Borrowed snapshot, or NULL when no subscriber has established one. */ +static struct nl_snapshot *nl_find_snapshot(struct net_namespace *ns) { - kernel_free(nl_previous_addresses); kernel_free(nl_previous_routes); kernel_free(nl_previous_links); - nl_previous_addresses=NULL; nl_previous_routes=NULL; - nl_previous_links=NULL; - nl_previous_address_count=nl_previous_route_count=nl_previous_link_count=0; nl_snapshot_ready=false; + for (struct nl_snapshot *snapshot = nl_snapshots; snapshot; snapshot = snapshot->next) + if (snapshot->net_ns == ns) return snapshot; + return NULL; } -/** @brief Capture a baseline before admitting the first subscription. - * @return Zero or allocation error; no partial snapshot survives failure. */ -static int nl_initial_snapshot(void) +/** @brief Retire a namespace's owned baseline after its last subscriber leaves. + * @param ns Borrowed scope, still retained by the departing socket. */ +static void nl_forget_snapshot(struct net_namespace *ns) { - if (nl_snapshot_ready) return 0; - struct net_ipv6_address *addresses; struct net_ipv6_route *routes; - struct nl_link_state *links; - uint32_t acount, rcount, lcount; - int rc=nl_addresses(&addresses,&acount); if (rc) return rc; - rc=nl_routes(&routes,&rcount); if (rc) { kernel_free(addresses); return rc; } - rc=nl_links(&links,&lcount); if (rc) { kernel_free(addresses); kernel_free(routes); return rc; } - nl_previous_addresses=addresses; nl_previous_address_count=acount; - nl_previous_routes=routes; nl_previous_route_count=rcount; - nl_previous_links=links; nl_previous_link_count=lcount; - nl_snapshot_ready=true; return 0; + struct nl_snapshot **slot = &nl_snapshots; + while (*slot && (*slot)->net_ns != ns) slot = &(*slot)->next; + if (!*slot) return; + struct nl_snapshot *snapshot = *slot; + *slot = snapshot->next; + kernel_free(snapshot->addresses); + kernel_free(snapshot->routes); + kernel_free(snapshot->links); + kernel_free(snapshot); +} + +/** @brief Capture a complete baseline before admitting a scope's first subscriber. + * @param ns Borrowed creating network, retained by the prospective subscriber. + * @return Zero or allocation error. Failure leaves the registry unchanged. */ +static int nl_initial_snapshot(struct net_namespace *ns) +{ + if (nl_find_snapshot(ns)) return 0; + struct nl_snapshot *snapshot = kernel_malloc(sizeof(*snapshot)); + if (!snapshot) return -LINUX_ENOMEM; + *snapshot = (struct nl_snapshot){.net_ns = ns}; + int rc = nl_addresses(ns, &snapshot->addresses, &snapshot->address_count); + if (!rc) rc = nl_routes(ns, &snapshot->routes, &snapshot->route_count); + if (!rc) rc = nl_links(ns, &snapshot->links, &snapshot->link_count); + if (rc) { + kernel_free(snapshot->addresses); + kernel_free(snapshot->routes); + kernel_free(snapshot->links); + kernel_free(snapshot); + return rc; + } + snapshot->next = nl_snapshots; + nl_snapshots = snapshot; + return 0; +} + +/** @brief Release an unused baseline while a departing socket still pins its scope. + * @param ns Borrowed scope. Other namespaces' subscribers are independent. */ +static void nl_forget_unsubscribed(struct net_namespace *ns) +{ + for (struct netlink_socket *s = netlink_sockets; s; s = s->next) + if (s->net_ns == ns && s->protocol == NETLINK_ROUTE && s->groups) return; + nl_forget_snapshot(ns); } /** @brief Change membership transactionally, retaining an initialized query bitmap. - * Initial-network route subscribers own the current global interface baseline. + * Route subscribers share a baseline within their creating network. * @param s Subscriber. @param groups New Linux group mask. @return Zero or errno. */ static int nl_set_groups(struct netlink_socket *s, uint32_t groups) { @@ -416,23 +460,19 @@ static int nl_set_groups(struct netlink_socket *s, uint32_t groups) return 0; } if (groups & ~NL_SUPPORTED_GROUPS) return -LINUX_EOPNOTSUPP; - if (groups && !s->net_ns) { int rc=nl_initial_snapshot(); if (rc) return rc; } + if (groups) { int rc=nl_initial_snapshot(s->net_ns); if (rc) return rc; } s->groups=groups; s->memberships_initialized |= groups != 0; - if (!groups) { - for (struct netlink_socket *it=netlink_sockets;it;it=it->next) - if (!it->net_ns && it->protocol == NETLINK_ROUTE && it->groups) return 0; - nl_forget_snapshot(); - } + if (!groups) nl_forget_unsubscribed(s->net_ns); return 0; } -/** @brief Report initial-network notification loss to its interested subscribers. - * @param group Linux multicast group bit. */ -static void nl_overrun(uint32_t group) +/** @brief Report notification loss only to subscribers in the affected network. + * @param ns Borrowed network scope. @param group Linux multicast group bit. */ +static void nl_overrun(struct net_namespace *ns, uint32_t group) { for (struct netlink_socket *s=netlink_sockets;s;s=s->next) - if (!s->net_ns && s->protocol == NETLINK_ROUTE && (s->groups & group)) s->overrun=true; + if (s->net_ns == ns && s->protocol == NETLINK_ROUTE && (s->groups & group)) s->overrun=true; kernel_poll_readiness_notify(); } @@ -468,18 +508,18 @@ static int nl_queue_datagram(struct netlink_socket *s, uint32_t port, uint32_t g } /** @brief Fan out within the sender's retained scope, reporting queue overruns. - * Kernel route notifications describe the initial network. Untagged global - * device events reach networks owned by the initial user namespace. + * Untagged global device events reach networks owned by the initial user + * namespace. Route notifications use the explicit network scope. + * @param ns Borrowed destination scope, matching sender when provided. * @param protocol Netlink protocol. @param group Linux group bit. * @param data Validated datagram. @param length Datagram length. * @param sender Sending socket, excluded from fanout, or NULL for kernel. * @param credentials Sender's credential snapshot, or NULL for kernel. */ -static void nl_multicast(int protocol, uint32_t group, const void *data, uint32_t length, +static void nl_multicast(struct net_namespace *ns, int protocol, uint32_t group, const void *data, uint32_t length, const struct netlink_socket *sender, const struct ucred *credentials) { bool notified = false; - const struct net_namespace *scope = sender ? sender->net_ns : NULL; bool global_device_event = !sender && protocol == NETLINK_KOBJECT_UEVENT; for (struct netlink_socket *s = netlink_sockets; s; s = s->next) { if (s == sender || s->protocol != protocol || !(s->groups & group)) @@ -487,7 +527,7 @@ static void nl_multicast(int protocol, uint32_t group, const void *data, uint32_ if (global_device_event) { if (s->net_ns && s->net_ns->user_ns) continue; - } else if (s->net_ns != scope) { + } else if (s->net_ns != ns) { continue; } int result = nl_queue_datagram(s, sender ? sender->port : 0, group, data, length, credentials); @@ -520,7 +560,7 @@ void netlink_uevent_change(const char *devpath, const char *subsystem, text_unsigned(&stream, ++uevent_seqnum); text_bytes(&stream, "", 1); if (stream.position <= sizeof(payload)) - nl_multicast(NETLINK_KOBJECT_UEVENT, NL_UEVENT_KERNEL_GROUP, payload, stream.written, NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, NL_UEVENT_KERNEL_GROUP, payload, stream.written, NULL, NULL); } EXPORT_SYMBOL(netlink_uevent_change); @@ -551,82 +591,87 @@ static bool nl_same_route(const struct net_ipv6_route *a,const struct net_ipv6_r static bool nl_equal_route(const struct net_ipv6_route *a,const struct net_ipv6_route *b) { return nl_same_route(a,b) && a->metric==b->metric && a->flags==b->flags && a->valid_until==b->valid_until; } -/** @brief Queue a bounded initial-network event for its subscribed OFDs. +/** @brief Queue a bounded namespace-scoped event for its subscribed OFDs. + * @param ns Borrowed network, NULL for the initial network. * @param group Linux group bit. @param type Message type. @param value Copied address, - * route or Ethernet snapshot according to group. @param up Link readiness for link events. */ -static void nl_publish(uint32_t group,uint16_t type,const void *value,bool up) + * route or interface snapshot according to group. */ +static void nl_publish(struct net_namespace *ns, uint32_t group,uint16_t type,const void *value) { - (void)up; bool interested=false; for (struct netlink_socket *s=netlink_sockets;s;s=s->next) - if (!s->net_ns && s->protocol == NETLINK_ROUTE && (s->groups & group)) { interested=true; break; } + if (s->net_ns == ns && s->protocol == NETLINK_ROUTE && (s->groups & group)) { interested=true; break; } if (!interested) return; struct netlink_message *message=kernel_malloc(sizeof(*message)+NL_MESSAGE_MAX); - if (!message) { nl_overrun(group); return; } - struct nl_builder b={.message=message}; + if (!message) { nl_overrun(ns, group); return; } + struct nl_builder b={.message=message,.net_ns=ns}; int rc=group==RTMGRP_IPV6_IFADDR ? nl_address6(&b,0,value,type,false) : group==RTMGRP_IPV6_ROUTE ? nl_route6(&b,0,value,type,false) : nl_link_snapshot(&b,0,false,type,value); - if (rc) { kernel_free(message); nl_overrun(group); return; } - nl_multicast(NETLINK_ROUTE, group, message->data, b.used, NULL, NULL); + if (rc) { kernel_free(message); nl_overrun(ns, group); return; } + nl_multicast(ns, NETLINK_ROUTE, group, message->data, b.used, NULL, NULL); kernel_free(message); } -/** @brief Diff initial-network address, route and link snapshots into its events. - * Changes are detected under the existing execution owner; allocation failure - * is surfaced as ENOBUFS to subscribers and the previous baseline is retained. */ -void netlink_ipv6_changed(void) +/** @copydoc netlink_network_changed */ +void netlink_network_changed(struct net_namespace *ns) { - if (!nl_snapshot_ready) return; + struct nl_snapshot *snapshot = nl_find_snapshot(ns); + if (!snapshot) return; struct net_ipv6_address *addresses; struct net_ipv6_route *routes; struct nl_link_state *links; uint32_t acount, rcount, lcount; - int rc=nl_addresses(&addresses,&acount); - if (rc) { nl_overrun(NL_SUPPORTED_GROUPS); return; } - rc=nl_routes(&routes,&rcount); - if (rc) { kernel_free(addresses); nl_overrun(NL_SUPPORTED_GROUPS); return; } - rc=nl_links(&links,&lcount); - if (rc) { kernel_free(addresses); kernel_free(routes); nl_overrun(NL_SUPPORTED_GROUPS); return; } - for (uint32_t i=0;iaddress_count;++i) { bool found=false; - for (uint32_t j=0;jaddresses[i],&addresses[j])) { found=true; break; } + if (!found) nl_publish(ns, RTMGRP_IPV6_IFADDR,RTM_DELADDR,&snapshot->addresses[i]); } for (uint32_t i=0;iaddress_count;++j) + if (nl_equal_address(&addresses[i],&snapshot->addresses[j])) { same=true; break; } + if (!same) nl_publish(ns, RTMGRP_IPV6_IFADDR,RTM_NEWADDR,&addresses[i]); } - for (uint32_t i=0;iroute_count;++i) { bool found=false; - for (uint32_t j=0;jroutes[i],&routes[j])) { found=true; break; } + if (!found) nl_publish(ns, RTMGRP_IPV6_ROUTE,RTM_DELROUTE,&snapshot->routes[i]); } for (uint32_t i=0;iroute_count;++j) + if (nl_equal_route(&routes[i],&snapshot->routes[j])) { same=true; break; } + if (!same) nl_publish(ns, RTMGRP_IPV6_ROUTE,RTM_NEWROUTE,&routes[i]); } - for (uint32_t i=0;ilink_count;++i) { bool found=false; - for (uint32_t j=0;jlinks[i].index==links[j].index) { found=true; break; } + if (!found) nl_publish(ns, RTMGRP_LINK,RTM_DELLINK,&snapshot->links[i]); } for (uint32_t i=0;ilink_count;++j) + if (snapshot->links[j].index==links[i].index) { old=&snapshot->links[j]; break; } if (!old || old->up!=links[i].up || old->active!=links[i].active || __builtin_memcmp(old->mac,links[i].mac,sizeof(old->mac)) || __builtin_strcmp(old->name,links[i].name)) - nl_publish(RTMGRP_LINK,RTM_NEWLINK,&links[i],false); + nl_publish(ns, RTMGRP_LINK,RTM_NEWLINK,&links[i]); } - kernel_free(nl_previous_addresses); kernel_free(nl_previous_routes); kernel_free(nl_previous_links); - nl_previous_addresses=addresses; nl_previous_address_count=acount; - nl_previous_routes=routes; nl_previous_route_count=rcount; - nl_previous_links=links; nl_previous_link_count=lcount; + kernel_free(snapshot->addresses); kernel_free(snapshot->routes); kernel_free(snapshot->links); + snapshot->addresses=addresses; snapshot->address_count=acount; + snapshot->routes=routes; snapshot->route_count=rcount; + snapshot->links=links; snapshot->link_count=lcount; +} + +/** @copydoc netlink_ipv6_changed */ +void netlink_ipv6_changed(void) +{ + netlink_network_changed(NULL); } /** @brief Render a link, address or route dump from current network state. @@ -642,10 +687,10 @@ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) if (req.ifi_family != AF_UNSPEC && req.ifi_family != AF_PACKET && req.ifi_family != AF_INET && req.ifi_family != AF_INET6) return -LINUX_EAFNOSUPPORT; if (!multi) { - if (req.ifi_index <= 0 || !net_interface_exists((uint32_t)req.ifi_index)) return -LINUX_ENODEV; + if (req.ifi_index <= 0 || !net_interface_exists(b->net_ns, (uint32_t)req.ifi_index)) return -LINUX_ENODEV; return nl_link(b,h->nlmsg_seq,req.ifi_index,false); } - for (uint32_t index=net_interface_next(0);index;index=net_interface_next(index)) { + for (uint32_t index=net_interface_next(b->net_ns, 0);index;index=net_interface_next(b->net_ns, index)) { int rc=nl_link(b,h->nlmsg_seq,(int)index,true); if (rc) return rc; } return nl_done(b,h->nlmsg_seq); @@ -659,11 +704,11 @@ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) return -LINUX_EAFNOSUPPORT; int rc=0; if (req.ifa_family != AF_INET6) { - for (uint32_t index=net_interface_next(0);index;index=net_interface_next(index)) { + for (uint32_t index=net_interface_next(b->net_ns, 0);index;index=net_interface_next(b->net_ns, index)) { struct reliefos_net_config config; if ((req.ifa_index && req.ifa_index!=index) || - net_interface_get_config(index,&config) || !config.local_ip) continue; - struct net_interface *iface=net_interface_get(index); + net_interface_get_config(b->net_ns, index,&config) || !config.local_ip) continue; + struct net_interface *iface=net_interface_get(b->net_ns, index); uint32_t broadcast=iface ? iface->broadcast : 0; rc=nl_address4(b,h->nlmsg_seq,index,config.local_ip,nl_prefix4(config.subnet_mask),broadcast); if (rc) return rc; @@ -671,7 +716,7 @@ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) } if (req.ifa_family != AF_INET) { struct net_ipv6_address *entries; uint32_t count; - rc=nl_addresses(&entries,&count); if (rc) return rc; + rc=nl_addresses(b->net_ns, &entries,&count); if (rc) return rc; for (uint32_t i=0; inlmsg_seq,&entries[i],RTM_NEWADDR,true); @@ -686,11 +731,11 @@ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) return -LINUX_EAFNOSUPPORT; int rc=0; if (req.rtm_family != AF_INET6) { - uint32_t count=net_ipv4_routes(NULL,0); + uint32_t count=net_ipv4_routes(b->net_ns, NULL,0); if (count > NL_MESSAGE_MAX / sizeof(struct net_ipv4_route)) return -LINUX_ENOBUFS; struct net_ipv4_route *entries=count ? kernel_malloc((size_t)count*sizeof(*entries)) : NULL; if (count && !entries) return -LINUX_ENOMEM; - if (net_ipv4_routes(entries,count)>count) { kernel_free(entries); return -LINUX_EAGAIN; } + if (net_ipv4_routes(b->net_ns, entries,count)>count) { kernel_free(entries); return -LINUX_EAGAIN; } for (uint32_t i=0;inlmsg_seq,entries[i].destination,nl_prefix4(entries[i].mask), entries[i].gateway,entries[i].ifindex,entries[i].metric); @@ -698,7 +743,7 @@ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) } if (req.rtm_family != AF_INET) { struct net_ipv6_route *entries; uint32_t count; - rc=nl_routes(&entries,&count); if (rc) return rc; + rc=nl_routes(b->net_ns, &entries,&count); if (rc) return rc; for (uint32_t i=0; inlmsg_seq,&entries[i],RTM_NEWROUTE,true); kernel_free(entries); if (rc) return rc; } @@ -735,8 +780,12 @@ static int nl_copy_attr(const struct rtattr *a, void *out, uint32_t size) __builtin_memcpy(out,a+1,size); return 0; } -/** @brief Change administrative state on one existing interface. */ -static int nl_change_link(const struct nlmsghdr *h) +/** @brief Apply an authorized administrative change to one network's interface. + * @param ns Borrowed creating network, NULL for the initial network. + * @param h Validated request header and bounded attributes. + * @return Zero or negative errno. Changes notify this network's subscribers. + */ +static int nl_change_link(struct net_namespace *ns, const struct nlmsghdr *h) { if (h->nlmsg_len < sizeof(*h)+sizeof(struct ifinfomsg)) return -LINUX_EINVAL; struct ifinfomsg req; @@ -761,12 +810,12 @@ static int nl_change_link(const struct nlmsghdr *h) if (!terminated) return -LINUX_EINVAL; char name[NET_IF_NAME_LEN]={0}; __builtin_memcpy(name,input,n); - uint32_t named=net_interface_index(name); + uint32_t named=net_interface_index(ns, name); if (!index) index=named; else if (named!=index) return -LINUX_EOPNOTSUPP; } if (!index) return attrs[IFLA_IFNAME] ? -LINUX_ENODEV : -LINUX_EINVAL; - if (!net_interface_exists(index)) return -LINUX_ENODEV; + if (!net_interface_exists(ns, index)) return -LINUX_ENODEV; if (attrs[IFLA_MTU]) { uint32_t mtu; rc=nl_copy_attr(attrs[IFLA_MTU],&mtu,sizeof(mtu)); if (rc) return rc; @@ -774,20 +823,26 @@ static int nl_change_link(const struct nlmsghdr *h) } if (req.ifi_change & IFF_UP) { bool up=(req.ifi_flags & IFF_UP)!=0; - if (net_interface_is_up(index)!=up) { - rc=net_interface_set_up(index,up); if (rc) return rc; - if (index!=NET_IF_LOOPBACK) net_ipv6_link_changed_on(index,up); - netlink_ipv6_changed(); + if (net_interface_is_up(ns, index)!=up) { + rc=net_interface_set_up(ns, index,up); if (rc) return rc; + if (!ns && index!=NET_IF_LOOPBACK) net_ipv6_link_changed_on(index,up); + netlink_network_changed(ns); } } return 0; } -/** @brief Apply a primary IPv4 address request to its exact NIC. */ -static int nl_change_address4(const struct nlmsghdr *h, const struct ifaddrmsg *req, bool remove) +/** @brief Apply an authorized primary IPv4 address request within one network. + * @param ns Borrowed creating network, NULL for the initial network. + * @param h Validated request header and bounded attributes. + * @param req Copied address record selecting the interface. + * @param remove True to delete the matching address. + * @return Zero or negative errno. Validation failure preserves configuration. + */ +static int nl_change_address4(struct net_namespace *ns, const struct nlmsghdr *h, const struct ifaddrmsg *req, bool remove) { if (!req->ifa_index || req->ifa_prefixlen>32) return -LINUX_EINVAL; - struct net_interface *iface=net_interface_get(req->ifa_index); + struct net_interface *iface=net_interface_get(ns, req->ifa_index); if (!iface) return req->ifa_index==NET_IF_LOOPBACK ? -LINUX_EOPNOTSUPP : -LINUX_ENODEV; const struct rtattr *a[9]={0}; int rc=nl_parse_attrs((const uint8_t *)(h+1)+sizeof(*req), @@ -807,7 +862,7 @@ static int nl_change_address4(const struct nlmsghdr *h, const struct ifaddrmsg * if (flags & ~IFA_F_PERMANENT) return -LINUX_EOPNOTSUPP; if (a[IFA_LABEL]) { char name[NET_IF_NAME_LEN]; - if (!net_interface_name(req->ifa_index,name)) return -LINUX_ENODEV; + if (!net_interface_name(ns, req->ifa_index,name)) return -LINUX_ENODEV; uint32_t n=a[IFA_LABEL]->rta_len-sizeof(struct rtattr); if (n!=__builtin_strlen(name)+1 || __builtin_memcmp(a[IFA_LABEL]+1,name,n)) return -LINUX_EOPNOTSUPP; @@ -826,22 +881,24 @@ static int nl_change_address4(const struct nlmsghdr *h, const struct ifaddrmsg * bool found=iface->config.local_ip==ip && iface->config.subnet_mask==mask; if (remove) { if (!found) return -LINUX_EADDRNOTAVAIL; - return net_interface_configure_ipv4(req->ifa_index,0,0,0); + return net_interface_configure_ipv4(ns, req->ifa_index,0,0,0); } if (iface->config.local_ip && !(h->nlmsg_flags & NLM_F_REPLACE)) return -LINUX_EEXIST; if (!iface->config.local_ip && (h->nlmsg_flags & NLM_F_REPLACE) && !(h->nlmsg_flags & NLM_F_CREATE)) return -LINUX_EADDRNOTAVAIL; - return net_interface_configure_ipv4(req->ifa_index,ip,mask,broadcast); + return net_interface_configure_ipv4(ns, req->ifa_index,ip,mask,broadcast); } -/** @brief Apply an authorized IPv6 address request using copied snapshots. +/** @brief Dispatch an authorized IPv4 or IPv6 address request to its network. + * @param ns Borrowed creating network, NULL for the initial network. * @param h Checked request. @param remove True for delete. @return Zero or errno. */ -static int nl_change_address(const struct nlmsghdr *h, bool remove) +static int nl_change_address(struct net_namespace *ns, const struct nlmsghdr *h, bool remove) { if (h->nlmsg_len < sizeof(*h)+sizeof(struct ifaddrmsg)) return -LINUX_EINVAL; struct ifaddrmsg req; __builtin_memcpy(&req,h+1,sizeof(req)); - if (req.ifa_family == AF_INET) return nl_change_address4(h,&req,remove); + if (req.ifa_family == AF_INET) return nl_change_address4(ns, h,&req,remove); if (req.ifa_family != AF_INET6) return -LINUX_EAFNOSUPPORT; + if (ns) return -LINUX_EOPNOTSUPP; if (!req.ifa_index || req.ifa_prefixlen > 128) return -LINUX_EINVAL; const struct rtattr *a[9]={0}; int rc=nl_parse_attrs((const uint8_t *)(h+1)+sizeof(req), @@ -863,7 +920,7 @@ static int nl_change_address(const struct nlmsghdr *h, bool remove) const char *label=(const char *)(a[IFA_LABEL]+1); uint32_t n=a[IFA_LABEL]->rta_len-sizeof(struct rtattr); char expected[NET_IF_NAME_LEN]; - if (!net_interface_name(entry.ifindex,expected)) return -LINUX_ENODEV; + if (!net_interface_name(ns, entry.ifindex,expected)) return -LINUX_ENODEV; uint32_t expected_n=__builtin_strlen(expected)+1; if (n!=expected_n || __builtin_memcmp(label,expected,n)) return -LINUX_EOPNOTSUPP; } @@ -876,7 +933,7 @@ static int nl_change_address(const struct nlmsghdr *h, bool remove) } if (entry.valid_until==UINT64_MAX) entry.flags|=NET_IPV6_ADDR_PERMANENT; struct net_ipv6_address *existing; uint32_t count; - rc=nl_addresses(&existing,&count); if (rc) return rc; + rc=nl_addresses(ns, &existing,&count); if (rc) return rc; bool found=false; for (uint32_t i=0;irtm_dst_len>32 || req->rtm_src_len || req->rtm_tos || req->rtm_flags || (req->rtm_table && req->rtm_table!=RT_TABLE_MAIN) || @@ -917,41 +980,43 @@ static int nl_change_route4(const struct nlmsghdr *h, const struct rtmsg *req, b if (route.mask==UINT32_MAX) route.flags|=RTF_HOST; if (!route.ifindex) { struct net_ipv4_path path; - rc=net_ipv4_route_lookup(route.gateway ? route.gateway : route.destination,0,0,&path); + rc=net_ipv4_route_lookup(ns, route.gateway ? route.gateway : route.destination,0,0,&path); if (rc) return rc; route.ifindex=path.ifindex; } if (remove && !route.mask && !route.gateway) { - struct net_interface *iface=net_interface_get(route.ifindex); + struct net_interface *iface=net_interface_get(ns, route.ifindex); if (!iface || !iface->config.gateway_ip) return -LINUX_ESRCH; route.gateway=iface->config.gateway_ip; route.flags|=RTF_GATEWAY; } bool replace=(h->nlmsg_flags & NLM_F_REPLACE)!=0; if (!remove && replace && !(h->nlmsg_flags & NLM_F_CREATE)) { - uint32_t count=net_ipv4_routes(NULL,0); + uint32_t count=net_ipv4_routes(ns, NULL,0); if (count>NL_MESSAGE_MAX/sizeof(struct net_ipv4_route)) return -LINUX_ENOBUFS; struct net_ipv4_route *entries=count ? kernel_malloc((size_t)count*sizeof(*entries)) : NULL; if (count && !entries) return -LINUX_ENOMEM; - if (net_ipv4_routes(entries,count)>count) { kernel_free(entries); return -LINUX_EAGAIN; } + if (net_ipv4_routes(ns, entries,count)>count) { kernel_free(entries); return -LINUX_EAGAIN; } bool found=false; for (uint32_t i=0;inlmsg_len < sizeof(*h)+sizeof(struct rtmsg)) return -LINUX_EINVAL; struct rtmsg req; __builtin_memcpy(&req,h+1,sizeof(req)); - if (req.rtm_family == AF_INET) return nl_change_route4(h,&req,remove); + if (req.rtm_family == AF_INET) return nl_change_route4(ns, h,&req,remove); if (req.rtm_family != AF_INET6) return -LINUX_EAFNOSUPPORT; + if (ns) return -LINUX_EOPNOTSUPP; if (req.rtm_dst_len > 128 || req.rtm_src_len || req.rtm_tos || req.rtm_flags || (req.rtm_table && req.rtm_table!=RT_TABLE_MAIN) || (req.rtm_type && req.rtm_type!=RTN_UNICAST)) return -LINUX_EOPNOTSUPP; @@ -976,7 +1041,7 @@ static int nl_change_route(const struct nlmsghdr *h, bool remove) for (uint32_t bit=route.prefix_length;bit<128;++bit) route.destination.s6_addr[bit/8] &= (uint8_t)~(0x80u >> (bit%8)); struct net_ipv6_route *existing; uint32_t count; - rc=nl_routes(&existing,&count); if (rc) return rc; + rc=nl_routes(ns, &existing,&count); if (rc) return rc; bool found=false; for (uint32_t i=0;iused; + struct net_namespace *ns = b->net_ns; int rc; if (!(h->nlmsg_flags & NLM_F_REQUEST)) rc=-LINUX_EINVAL; else if (h->nlmsg_type==RTM_GETLINK || h->nlmsg_type==RTM_GETADDR || h->nlmsg_type==RTM_GETROUTE) @@ -1005,13 +1071,13 @@ static int nl_request(struct nl_builder *b, const struct nlmsghdr *h) h->nlmsg_type==RTM_NEWADDR || h->nlmsg_type==RTM_DELADDR || h->nlmsg_type==RTM_NEWROUTE || h->nlmsg_type==RTM_DELROUTE) { struct task *task=sched_current_task(); - if (!task || !(task_initial_capabilities(task) & (1ULL<user_ns : NULL, CAP_NET_ADMIN)) rc=-LINUX_EPERM; else if (h->nlmsg_flags & (NLM_F_ECHO|NLM_F_APPEND)) rc=-LINUX_EOPNOTSUPP; else if (h->nlmsg_type==RTM_NEWLINK || h->nlmsg_type==RTM_SETLINK) - rc=nl_change_link(h); + rc=nl_change_link(ns, h); else if (h->nlmsg_type==RTM_NEWADDR || h->nlmsg_type==RTM_DELADDR) - rc=nl_change_address(h,h->nlmsg_type==RTM_DELADDR); - else rc=nl_change_route(h,h->nlmsg_type==RTM_DELROUTE); + rc=nl_change_address(ns, h,h->nlmsg_type==RTM_DELADDR); + else rc=nl_change_route(ns, h,h->nlmsg_type==RTM_DELROUTE); } else rc=-LINUX_EOPNOTSUPP; if (rc) { b->used=original; return nl_error(b,h,rc); } bool dump=(h->nlmsg_type==RTM_GETLINK || h->nlmsg_type==RTM_GETADDR || h->nlmsg_type==RTM_GETROUTE) && @@ -1055,7 +1121,7 @@ static int nl_uevent_send(struct netlink_socket *sender, const void *data, uint3 return -LINUX_ENOBUFS; __builtin_memcpy(payload, data, length); if (dst.nl_groups) { - nl_multicast(NETLINK_KOBJECT_UEVENT, dst.nl_groups, payload, length, sender, &credentials); + nl_multicast(sender->net_ns, NETLINK_KOBJECT_UEVENT, dst.nl_groups, payload, length, sender, &credentials); rc = (int)length; } else { rc = -LINUX_ECONNREFUSED; @@ -1136,7 +1202,7 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui /* Reserve both slots before publishing any reply. The small terminator is * conservatively charged one full slot, as other queued datagrams are. */ s->queued_bytes+=reserved; - struct nl_builder builder={.message=message,.completion=completion,.port=s->port}; + struct nl_builder builder={.message=message,.completion=completion,.net_ns=s->net_ns,.port=s->port}; for (pos=0;poshead ? (int)s->head->length : 0; } +/** @copydoc task_netlink_ioctl */ +int task_netlink_ioctl(struct task_file *file, uint32_t request, uint64_t address) +{ + struct netlink_socket *s = nl_socket(file); + if (!s) return -LINUX_EBADF; + return net_interface_ioctl(s->net_ns, request, address); +} + /** @brief Free final socket ownership, its namespace, filter and queued datagrams. * @param file Final OFD. */ void task_netlink_release(struct task_file *file) @@ -1266,12 +1340,7 @@ void task_netlink_release(struct task_file *file) struct netlink_socket **link=&netlink_sockets; while (*link && *link!=s) link=&(*link)->next; if (*link) *link=s->next; - if (s->protocol == NETLINK_ROUTE && s->groups) { - bool subscribers=false; - for (struct netlink_socket *it=netlink_sockets;it;it=it->next) - if (!it->net_ns && it->protocol == NETLINK_ROUTE && it->groups) { subscribers=true; break; } - if (!subscribers) nl_forget_snapshot(); - } + if (s->protocol == NETLINK_ROUTE && s->groups) nl_forget_unsubscribed(s->net_ns); while (s->head) { struct netlink_message *m=s->head; s->head=m->next; kernel_free(m); } kernel_free(s->filter); net_namespace_put(s->net_ns); diff --git a/net/socket/packet.c b/net/socket/packet.c index be09da00..690b5ed8 100644 --- a/net/socket/packet.c +++ b/net/socket/packet.c @@ -261,9 +261,9 @@ int task_packet_send(struct task_file *file, const void *data, uint32_t length, __builtin_memcpy(&to, (void *)(uintptr_t)address, sizeof(to)); if (to.sll_family != AF_PACKET) return -LINUX_EINVAL; } - if (to.sll_ifindex <= 0 || !net_interface_exists((uint32_t)to.sll_ifindex)) return -LINUX_ENXIO; + if (to.sll_ifindex <= 0 || !net_interface_exists(NULL, (uint32_t)to.sll_ifindex)) return -LINUX_ENXIO; if (to.sll_ifindex == 1) return -LINUX_EOPNOTSUPP; - if (!net_interface_is_ready((uint32_t)to.sll_ifindex)) return -LINUX_ENETDOWN; + if (!net_interface_is_ready(NULL, (uint32_t)to.sll_ifindex)) return -LINUX_ENETDOWN; uint8_t frame[1514]; uint32_t total = length; if (s->type == SOCK_DGRAM) { @@ -476,7 +476,7 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin s->checksum_offset = value < 0 ? -1 : value; break; case IPV6_UNICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->unicast_hops = value; break; case IPV6_MULTICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->multicast_hops = value; break; - case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists((uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; + case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists(NULL, (uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; case IPV6_MULTICAST_LOOP: if (value != 0 && value != 1) return -LINUX_EINVAL; s->multicast_loop = value != 0; break; case IPV6_RECVPKTINFO: s->recv_pktinfo = value != 0; break; case IPV6_RECVHOPLIMIT: s->recv_hoplimit = value != 0; break; @@ -586,7 +586,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, a1 == SOL_SOCKET && a2 == SO_BINDTODEVICE) { uint32_t index = (uint32_t)s->ifindex; bool set = number == __NR_setsockopt; - int result = net_interface_device_option(set, a3, a4, &index); + int result = net_interface_device_option(NULL, set, a3, a4, &index); if (!result && set) s->ifindex = (int)index; return result; } @@ -600,7 +600,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, __builtin_memcpy(&address, (void *)(uintptr_t)a1, sizeof(address)); if (address.sll_family != AF_PACKET) return -LINUX_EINVAL; if (address.sll_ifindex < 0 || (address.sll_ifindex && - !net_interface_exists((uint32_t)address.sll_ifindex))) return -LINUX_ENODEV; + !net_interface_exists(NULL, (uint32_t)address.sll_ifindex))) return -LINUX_ENODEV; s->ifindex = address.sll_ifindex; s->protocol = address.sll_protocol; } else if (s->domain == AF_INET6) { @@ -609,7 +609,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (ret < 0) return ret; if (number == __NR_bind && !net_ipv6_needs_scope_id(&address.sin6_addr)) address.sin6_scope_id = 0; - if (address.sin6_scope_id && !net_interface_exists(address.sin6_scope_id)) return -LINUX_ENODEV; + if (address.sin6_scope_id && !net_interface_exists(NULL, address.sin6_scope_id)) return -LINUX_ENODEV; if (address.sin6_scope_id && s->ifindex && address.sin6_scope_id != (uint32_t)s->ifindex) return -LINUX_EINVAL; if (number == __NR_connect) { @@ -643,7 +643,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (address.sin_family != AF_INET) return -LINUX_EAFNOSUPPORT; if (number == __NR_connect) s->remote_ip = address.sin_addr.s_addr; else { - if (address.sin_addr.s_addr && !net_interface_for_ipv4(__builtin_bswap32(address.sin_addr.s_addr))) + if (address.sin_addr.s_addr && !net_interface_for_ipv4(NULL, __builtin_bswap32(address.sin_addr.s_addr))) return -LINUX_EADDRNOTAVAIL; s->local_ip = address.sin_addr.s_addr; } diff --git a/net/socket/udp.c b/net/socket/udp.c index 6dc6e89c..5268f3cf 100644 --- a/net/socket/udp.c +++ b/net/socket/udp.c @@ -127,7 +127,7 @@ static int bind_port(struct udp_socket *s, uint32_t ip, uint16_t port) if (s->bound) return -LINUX_EINVAL; struct reliefos_net_config config; net_get_config(&config); - if (ip && !net_interface_for_ipv4(ip)) return -LINUX_EADDRNOTAVAIL; + if (ip && !net_interface_for_ipv4(NULL, ip)) return -LINUX_EADDRNOTAVAIL; struct task *task = sched_current_task(); if (port && port < 1024 && !(task_initial_capabilities(task) & (1ULL << CAP_NET_BIND_SERVICE))) return -LINUX_EACCES; @@ -297,7 +297,7 @@ static int udp6_bind(struct udp_socket *s, const struct sockaddr_in6 *address) const struct in6_addr *ip = &address->sin6_addr; uint32_t scope = net_ipv6_needs_scope_id(ip) ? address->sin6_scope_id : 0; if (udp6_mapped(ip) && s->v6only) return -LINUX_EINVAL; - if (scope && !net_interface_exists(scope)) return -LINUX_ENODEV; + if (scope && !net_interface_exists(NULL, scope)) return -LINUX_ENODEV; if (scope && s->ifindex && scope != (uint32_t)s->ifindex) return -LINUX_EINVAL; if (ip->s6_addr[0] == 0xfe && (ip->s6_addr[1] & 0xc0) == 0x80 && !scope) @@ -340,8 +340,8 @@ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, if (!s->bound) { int ret = bind_port(s, 0, 0); if (ret) return ret; } struct reliefos_net_config config; net_get_config(&config); - if ((ip >> 24) == 127 || (ip && net_interface_for_ipv4(ip))) { - uint32_t local_index = net_interface_for_ipv4(ip); + if ((ip >> 24) == 127 || (ip && net_interface_for_ipv4(NULL, ip))) { + uint32_t local_index = net_interface_for_ipv4(NULL, ip); if (s->ifindex && (uint32_t)s->ifindex != local_index) return -LINUX_ENETUNREACH; loopback_bytes += length + 28; ++loopback_packets; net_udp_input(s->local ? s->local : ip, ip, s->port, port, data, length, (int)local_index); @@ -404,8 +404,8 @@ int task_udp_send(struct task_file *file, const void *data, uint32_t length, if (!s->bound) { int ret = bind_port(s, 0, 0); if (ret < 0) return ret; } struct reliefos_net_config config; net_get_config(&config); - if ((ip >> 24) == 127 || (ip && net_interface_for_ipv4(ip))) { - uint32_t local_index = net_interface_for_ipv4(ip); + if ((ip >> 24) == 127 || (ip && net_interface_for_ipv4(NULL, ip))) { + uint32_t local_index = net_interface_for_ipv4(NULL, ip); if (s->ifindex && (uint32_t)s->ifindex != local_index) return -LINUX_ENETUNREACH; loopback_bytes += length + 28; ++loopback_packets; @@ -614,7 +614,7 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, case IPV6_V6ONLY: if (s->bound) return -LINUX_EINVAL; s->v6only = value != 0; break; case IPV6_UNICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->unicast_hops = value; break; case IPV6_MULTICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->multicast_hops = value; break; - case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists((uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; + case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists(NULL, (uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; case IPV6_MULTICAST_LOOP: if (value != 0 && value != 1) return -LINUX_EINVAL; s->multicast_loop = value != 0; break; case IPV6_RECVPKTINFO: s->recv_pktinfo = value != 0; break; case IPV6_RECVHOPLIMIT: s->recv_hoplimit = value != 0; break; @@ -762,10 +762,10 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, net_get_config(&config); uint32_t local = s->local; if (!local && s->connected) { - if (net_interface_for_ipv4(s->remote)) local = s->remote; + if (net_interface_for_ipv4(NULL, s->remote)) local = s->remote; else { struct net_ipv4_path path; - if (!net_ipv4_route_lookup(s->remote, 0, (uint32_t)s->ifindex, &path)) local = path.source; + if (!net_ipv4_route_lookup(NULL, s->remote, 0, (uint32_t)s->ifindex, &path)) local = path.source; } } return export_address(a1, a2, number == __NR_getsockname ? local : s->remote, @@ -784,7 +784,7 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if ((int32_t)length < 0) return -LINUX_EINVAL; if (a2 == SO_BINDTODEVICE) { uint32_t index = (uint32_t)s->ifindex; - int result = net_interface_device_option(set, a3, a4, &index); + int result = net_interface_device_option(NULL, set, a3, a4, &index); if (!result && set) s->ifindex = (int)index; return result; } diff --git a/net/tcp/input.c b/net/tcp/input.c index 5144b38c..ff3a0d0a 100644 --- a/net/tcp/input.c +++ b/net/tcp/input.c @@ -211,7 +211,7 @@ void net_handle_tcp_on(uint32_t ifindex, const uint8_t *ip, uint32_t total_len, (void)net_send_tcp_socket(&reply, response_seq, response_ack, (flags & TCP_FLAG_ACK) ? TCP_FLAG_RST : TCP_FLAG_RST | TCP_FLAG_ACK, NULL, 0); } else if (!listening && !(flags & TCP_FLAG_RST) && - ((src_ip >> 24) == 127 || (src_ip && net_interface_for_ipv4(src_ip)))) { + ((src_ip >> 24) == 127 || (src_ip && net_interface_for_ipv4(NULL, src_ip)))) { struct net_socket reply = {.ifindex=ifindex,.local_ip=dst_ip,.remote_ip=src_ip,.local_port=dst_port,.remote_port=src_port}; uint32_t response_seq = (flags & TCP_FLAG_ACK) ? ack : 0; uint32_t response_ack = seq + payload_len + !!(flags & TCP_FLAG_SYN) + !!(flags & TCP_FLAG_FIN); diff --git a/net/tcp/output.c b/net/tcp/output.c index 7d5a6ccb..51857334 100644 --- a/net/tcp/output.c +++ b/net/tcp/output.c @@ -16,7 +16,7 @@ void net_tcp_loop_service(void) struct tcp_loop_frame frame = tcp_loop_frames[tcp_loop_head]; tcp_loop_head = (tcp_loop_head + 1u) % 32u; --tcp_loop_count; const uint8_t *ip = frame.bytes + 14; - if (net_interface_exists(frame.ifindex) && net_interface_is_up(frame.ifindex)) + if (net_interface_exists(NULL, frame.ifindex) && net_interface_is_up(NULL, frame.ifindex)) net_handle_tcp_on(frame.ifindex, ip, frame.length - 14u, 20u, net_get_u32(ip + 12), NULL, NULL); } @@ -140,14 +140,14 @@ static int net_send_tcp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint } net_put_u16(tcp + 16, net_tcp_checksum(src_ip, dst_ip, tcp, tcp_len)); int result; - if ((dst_ip >> 24) == 127 || (dst_ip && net_interface_for_ipv4(dst_ip))) { + if ((dst_ip >> 24) == 127 || (dst_ip && net_interface_for_ipv4(NULL, dst_ip))) { if (tcp_loop_count == 32) return -LINUX_ENOBUFS; struct tcp_loop_frame *queued = &tcp_loop_frames[(tcp_loop_head + tcp_loop_count) % 32u]; queued->length = 14u + total_len; queued->ifindex = ifindex; net_memcpy(queued->bytes, frame, queued->length); ++tcp_loop_count; result = (int)queued->length; - } else result = net_interface_is_ready(ifindex) ? netdev_send(ifindex, frame, 14u + total_len) : -LINUX_ENETDOWN; + } else result = net_interface_is_ready(NULL, ifindex) ? netdev_send(ifindex, frame, 14u + total_len) : -LINUX_ENETDOWN; if (result >= 0 && receiver && (flags & TCP_FLAG_ACK)) { receiver->rx_window_ack = ack; receiver->rx_window = window; @@ -179,10 +179,10 @@ int net_send_tcp_socket(struct net_socket *socket, uint32_t seq, uint32_t ack, { if (socket->resolving_neighbor) return -LINUX_EAGAIN; if (!socket->ipv6 || socket->mapped) { - bool local = net_interface_for_ipv4(socket->remote_ip) != 0; + bool local = net_interface_for_ipv4(NULL, socket->remote_ip) != 0; if (!local) { struct net_ipv4_path path; - int result = net_ipv4_route_lookup(socket->remote_ip, socket->local_ip, + int result = net_ipv4_route_lookup(NULL, socket->remote_ip, socket->local_ip, socket->bound_ifindex, &path); if (result < 0) return result; if (socket->ifindex != path.ifindex || socket->next_hop != path.next_hop || @@ -195,7 +195,7 @@ int net_send_tcp_socket(struct net_socket *socket, uint32_t seq, uint32_t ack, socket->ifindex = path.ifindex; socket->next_hop = path.next_hop; } - return net_send_tcp_to_mac_on(local ? net_interface_for_ipv4(socket->remote_ip) : socket->ifindex, socket->dst_mac, + return net_send_tcp_to_mac_on(local ? net_interface_for_ipv4(NULL, socket->remote_ip) : socket->ifindex, socket->dst_mac, socket->local_ip, socket->remote_ip, socket->local_port, socket->remote_port, seq, ack, flags, payload, length); } @@ -241,7 +241,7 @@ int net_send_tcp_to_mac(const uint8_t *mac, uint32_t source, uint32_t destinatio uint8_t flags, const uint8_t *data, uint32_t length) { struct net_ipv4_path path; - int result = net_ipv4_route_lookup(destination, source, 0, &path); + int result = net_ipv4_route_lookup(NULL, destination, source, 0, &path); if (result < 0) return result; return net_send_tcp_to_mac_on(path.ifindex, mac, source, destination, source_port, destination_port, seq, ack, flags, data, length); diff --git a/net/tcp/socket.c b/net/tcp/socket.c index 689fabd9..dfd96b05 100644 --- a/net/tcp/socket.c +++ b/net/tcp/socket.c @@ -761,14 +761,14 @@ static uint32_t net_socket_connect_ip(struct net_socket *socket, return RELIEFOS_NET_STATUS_BAD_ARGUMENT; } struct net_ipv4_path path; - ret = net_ipv4_route_lookup(remote_ip, socket->local_ip, socket->bound_ifindex, &path); + ret = net_ipv4_route_lookup(NULL, remote_ip, socket->local_ip, socket->bound_ifindex, &path); if (ret < 0) { socket->error = -ret; return RELIEFOS_NET_STATUS_NO_ADDRESS; } socket->ifindex = path.ifindex; socket->next_hop = path.next_hop; - if (net_interface_for_ipv4(remote_ip)) net_memzero(dst_mac, sizeof(dst_mac)); + if (net_interface_for_ipv4(NULL, remote_ip)) net_memzero(dst_mac, sizeof(dst_mac)); else { arp_ip = path.next_hop; ret = net_resolve_mac_on(path.ifindex, arp_ip, timeout_ms, dst_mac); @@ -1323,7 +1323,7 @@ int net_socket_connect_fd(int32_t handle, uint32_t ip, uint16_t port, bool nonbl if (s->state != RELIEFOS_NET_TCP_CLOSED) return -LINUX_EISCONN; if (!ip || !port) return -LINUX_EINVAL; struct net_ipv4_path path; - int route = net_ipv4_route_lookup(ip, s->local_ip, s->bound_ifindex, &path); + int route = net_ipv4_route_lookup(NULL, ip, s->local_ip, s->bound_ifindex, &path); if (route < 0) return route; s->error = 0; uint32_t status = net_socket_connect_ip(s, ip, port, 10000, nonblock); @@ -1362,7 +1362,7 @@ int net_socket_bind6_fd(int32_t handle, const struct sockaddr_in6 *address) if (!s) return -LINUX_EBADF; if (!address || s->bound || s->state != RELIEFOS_NET_TCP_CLOSED) return -LINUX_EINVAL; uint32_t scope = net_ipv6_needs_scope_id(&address->sin6_addr) ? address->sin6_scope_id : 0; - if (scope && !net_interface_exists(scope)) return -LINUX_ENODEV; + if (scope && !net_interface_exists(NULL, scope)) return -LINUX_ENODEV; if (scope && s->bound_ifindex && scope != s->bound_ifindex) return -LINUX_EINVAL; bool mapped = tcp6_mapped(&address->sin6_addr); @@ -1371,7 +1371,7 @@ int net_socket_bind6_fd(int32_t handle, const struct sockaddr_in6 *address) if (mapped) { struct reliefos_net_config config; net_get_config(&config); - if (ip && !net_interface_for_ipv4(ip)) return -LINUX_EADDRNOTAVAIL; + if (ip && !net_interface_for_ipv4(NULL, ip)) return -LINUX_EADDRNOTAVAIL; } else if (!tcp6_any(&address->sin6_addr)) { if (!s->ipv6) return -LINUX_EAFNOSUPPORT; if (address->sin6_addr.s6_addr[0] == 0xfe && (address->sin6_addr.s6_addr[1] & 0xc0) == 0x80 && !scope) @@ -1647,7 +1647,7 @@ struct net_socket *net_tcp_passive4_on(uint32_t ifindex, struct net_socket *list uint32_t seq,uint16_t window,uint16_t mss) { if (!listener || listener->state != NET_TCP_LISTEN || tcp_pending(listener, false) >= listener->backlog) return NULL; - if (!source_mac && !net_interface_for_ipv4(source)) return NULL; + if (!source_mac && !net_interface_for_ipv4(NULL, source)) return NULL; struct net_socket *s = net_socket_alloc(listener->owner_pid, listener->owner_uid); if (!s) return NULL; s->ifindex = ifindex; s->bound_ifindex = listener->bound_ifindex; @@ -1873,7 +1873,7 @@ struct net_socket *net_tcp_passive4(struct net_socket *listener, uint32_t source uint32_t destination, uint16_t source_port, const uint8_t *source_mac, uint32_t seq, uint16_t window, uint16_t mss) { - uint32_t index = source_mac ? net_interface_for_ipv4(destination) : 1; + uint32_t index = source_mac ? net_interface_for_ipv4(NULL, destination) : 1; return net_tcp_passive4_on(index, listener, source, destination, source_port, source_mac, seq, window, mss); } @@ -1894,7 +1894,7 @@ int net_socket_bound_device(int32_t handle, bool set, uint32_t *index) if (!socket) return -LINUX_EBADF; if (!index) return -LINUX_EINVAL; if (set) { - if (*index && !net_interface_exists(*index)) return -LINUX_ENODEV; + if (*index && !net_interface_exists(NULL, *index)) return -LINUX_ENODEV; socket->bound_ifindex = *index; } else *index = socket->bound_ifindex; return 0; diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 5edfbf8b..27402c34 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -541,7 +541,7 @@ static void check_uevent_userspace_delivery(void) (uintptr_t)&udev_address, sizeof(udev_address)) == sizeof(payload)); assert(receive(monitor, output, sizeof(output)) == sizeof(payload)); - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(task_netlink_recv_staged(&files[kernel], output, sizeof(output), MSG_DONTWAIT, &from, &from_size, &credentials) == sizeof(payload)); assert(!from.nl_pid && from.nl_groups == 1 && @@ -590,13 +590,13 @@ static void check_netlink_filter(void) uint8_t payload[] = {0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0xaa, 0xbb, 0xcc, 0xdd}; uint8_t output[64]; - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == 9); assert(!memcmp(output, payload, 9)); - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, 7, NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, 7, NULL, NULL); assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); payload[4] = 0x21; - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); payload[4] = 0x12; @@ -613,7 +613,7 @@ static void check_netlink_filter(void) }; struct sock_fprog expression = {.len = sizeof(arithmetic) / sizeof(arithmetic[0]), .filter = arithmetic}; assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&expression, sizeof(expression))); - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == 9); struct sock_filter invalid_path[] = { BPF_STMT(BPF_LD | BPF_W | BPF_IMM, 0), @@ -638,7 +638,7 @@ static void check_netlink_filter(void) }; struct sock_fprog zero_divisor = {.len = 4, .filter = divide}; assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&zero_divisor, sizeof(zero_divisor))); - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program))); @@ -650,10 +650,10 @@ static void check_netlink_filter(void) assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program)) == -LINUX_ENOMEM); allocation_fail_after = -1; } - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == 9); assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_DETACH_FILTER, (uintptr_t)&value, sizeof(value))); - nl_multicast(NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); assert(receive(monitor, output, sizeof(output)) == (int)sizeof(payload)); struct sock_filter reject[] = {BPF_STMT(BPF_RET | BPF_K, 0)}; @@ -691,6 +691,262 @@ static void check_netlink_filter(void) puts("PASS netlink socket filters: admission, multicast, unicast, rollback and release"); } +/** @brief Assert a route socket exports only its namespace's loopback. */ +static void check_scoped_loopback(int fd, bool up) +{ + struct { struct nlmsghdr header; struct ifinfomsg link; } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_GETLINK, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP}, + .link = {.ifi_family = AF_UNSPEC}, + }; + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + unsigned char output[8192]; + int count = receive_dump(fd, output, sizeof(output)); + unsigned links = 0; + for (unsigned pos = 0; pos < (unsigned)count;) { + struct nlmsghdr *header = (void *)(output + pos); + assert(header->nlmsg_type == RTM_NEWLINK); + struct ifinfomsg *link = (void *)(header + 1); + assert(link->ifi_index == 1); + assert(!!(link->ifi_flags & IFF_UP) == up); + ++links; + pos += NLMSG_ALIGN(header->nlmsg_len); + } + assert(links == 1); +} + +/** @brief Keep interface dumps and mutations in a transferred socket's scope. */ +static void check_netlink_interface_scopes(void) +{ + unsigned baseline = allocations; + struct net_namespace *first, *second; + assert(!net_namespace_create(NULL, &first)); + assert(!net_namespace_create(NULL, &second)); + current.net_ns = first; + int first_fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(first_fd >= 0); + current.net_ns = second; + int second_fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(second_fd >= 0); + check_scoped_loopback(first_fd, false); + check_scoped_loopback(second_fd, false); + struct { struct nlmsghdr header; struct ifinfomsg link; } change = { + .header = {.nlmsg_len = sizeof(change), .nlmsg_type = RTM_NEWLINK, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK}, + .link = {.ifi_family = AF_UNSPEC, .ifi_index = 1, + .ifi_change = IFF_UP, .ifi_flags = IFF_UP}, + }; + current.cap_effective = 1ULL << CAP_NET_ADMIN; + assert(send_req(first_fd, &change, sizeof(change)) == sizeof(change)); + unsigned char output[8192]; + assert(receive(first_fd, output, sizeof(output)) > 0); + assert(((struct nlmsgerr *)((struct nlmsghdr *)(void *)output + 1))->error == 0); + check_scoped_loopback(first_fd, true); + check_scoped_loopback(second_fd, false); + change.link.ifi_index = 2; + assert(send_req(first_fd, &change, sizeof(change)) == sizeof(change)); + assert(receive(first_fd, output, sizeof(output)) > 0); + assert(((struct nlmsgerr *)((struct nlmsghdr *)(void *)output + 1))->error == -LINUX_ENODEV); + struct { struct nlmsghdr header; struct rtmsg route; } routes = { + .header = {.nlmsg_len = sizeof(routes), .nlmsg_type = RTM_GETROUTE, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP}, + .route = {.rtm_family = AF_INET}, + }; + assert(send_req(second_fd, &routes, sizeof(routes)) == sizeof(routes)); + assert(receive(second_fd, output, sizeof(output)) == 20); + assert(((struct nlmsghdr *)(void *)output)->nlmsg_type == NLMSG_DONE); + assert(send_req(first_fd, &routes, sizeof(routes)) == sizeof(routes)); + int bytes = receive_dump(first_fd, output, sizeof(output)); + assert(bytes > 0); + struct nlmsghdr *header = (void *)output; + assert(header->nlmsg_type == RTM_NEWROUTE); + assert(((struct rtmsg *)(header + 1))->rtm_dst_len == 8); + assert(NLMSG_ALIGN(header->nlmsg_len) == (unsigned)bytes); + current = (struct task){0}; + task_netlink_release(&files[first_fd]); files[first_fd] = (struct task_file){0}; + task_netlink_release(&files[second_fd]); files[second_fd] = (struct task_file){0}; + net_namespace_put(first); net_namespace_put(second); + assert(allocations == baseline); + puts("PASS network-scoped interface dumps, loopback state, IPv4 routes and moved netlink FD"); +} + +/** @brief Authorize mutations against the socket network's immutable user owner. */ +static void check_netlink_interface_authority(void) +{ + unsigned baseline = allocations; + struct user_namespace *owner, *other_owner; + current.euid = 1000; + assert(!user_namespace_create(¤t, &owner)); + assert(!user_namespace_create(¤t, &other_owner)); + struct net_namespace *owned, *other; + assert(!net_namespace_create(owner, &owned)); + assert(!net_namespace_create(other_owner, &other)); + struct net_namespace *scopes[] = {owned, other, NULL}; + int sockets[3]; + for (unsigned i = 0; i < 3; ++i) { + current.net_ns = scopes[i]; + sockets[i] = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(sockets[i] >= 0); + } + current.user_ns = owner; + current.net_ns = other; + current.cap_effective = 1ULL << CAP_NET_ADMIN; + struct ifreq request = {.ifr_name = "lo", .data.flags = IFF_UP}; + assert(!task_netlink_ioctl(&files[sockets[0]], SIOCSIFFLAGS, (uintptr_t)&request)); + assert(task_netlink_ioctl(&files[sockets[1]], SIOCSIFFLAGS, (uintptr_t)&request) == -LINUX_EPERM); + assert(task_netlink_ioctl(&files[sockets[2]], SIOCSIFFLAGS, (uintptr_t)&request) == -LINUX_EPERM); + assert(!task_netlink_ioctl(&files[sockets[0]], SIOCGIFFLAGS, (uintptr_t)&request)); + assert(request.data.flags & IFF_UP); + assert(!task_netlink_ioctl(&files[sockets[1]], SIOCGIFFLAGS, (uintptr_t)&request)); + assert(!(request.data.flags & IFF_UP)); + struct { struct nlmsghdr header; struct ifinfomsg link; } change = { + .header = {.nlmsg_len = sizeof(change), .nlmsg_type = RTM_NEWLINK, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK}, + .link = {.ifi_index = 1, .ifi_change = IFF_UP}, + }; + unsigned char output[512]; + for (unsigned i = 0; i < 3; ++i) { + assert(send_req(sockets[i], &change, sizeof(change)) == sizeof(change)); + assert(receive(sockets[i], output, sizeof(output)) > 0); + assert(((struct nlmsghdr *)(void *)output)->nlmsg_type == NLMSG_ERROR); + assert(((struct nlmsgerr *)((struct nlmsghdr *)(void *)output + 1))->error == + (i ? -LINUX_EPERM : 0)); + } + current.cap_effective = 0; + assert(task_netlink_ioctl(&files[sockets[0]], SIOCSIFFLAGS, (uintptr_t)&request) == -LINUX_EPERM); + assert(send_req(sockets[0], &change, sizeof(change)) == sizeof(change)); + assert(receive(sockets[0], output, sizeof(output)) > 0); + assert(((struct nlmsgerr *)((struct nlmsghdr *)(void *)output + 1))->error == -LINUX_EPERM); + current = (struct task){.euid = 2000, .cap_effective = 1ULL << CAP_NET_ADMIN}; + request.data.flags = IFF_UP; + assert(!task_netlink_ioctl(&files[sockets[1]], SIOCSIFFLAGS, (uintptr_t)&request)); + current = (struct task){0}; + for (unsigned i = 0; i < 3; ++i) { + task_netlink_release(&files[sockets[i]]); + files[sockets[i]] = (struct task_file){0}; + } + net_namespace_put(owned); net_namespace_put(other); + user_namespace_put(owner); user_namespace_put(other_owner); + assert(allocations == baseline); + puts("PASS interface authority: creating scope, local and ancestor admin, cross-owner denial"); +} + +/** @brief Keep explicit IPv4 routes, allocation rollback and proc views scope-local. */ +static void check_scoped_ipv4_routes(void) +{ + unsigned baseline = allocations; + struct net_namespace *first, *second; + assert(!net_namespace_create(NULL, &first)); + assert(!net_namespace_create(NULL, &second)); + assert(!net_interface_set_up(first, NET_IF_LOOPBACK, true)); + assert(!net_interface_set_up(second, NET_IF_LOOPBACK, true)); + struct net_ipv4_route route = {.destination = 0xc6336400u, .mask = 0xffffff00u, + .ifindex = NET_IF_LOOPBACK, .metric = 10, .flags = RTF_UP}; + allocation_fail_after = 0; + assert(net_ipv4_route_update(first, &route, false, false) == -LINUX_ENOMEM); + allocation_fail_after = -1; + assert(!first->ipv4_routes && !second->ipv4_routes); + assert(!net_ipv4_route_update(first, &route, false, false)); + assert(net_ipv4_route_update(first, &route, false, false) == -LINUX_EEXIST); + struct net_ipv4_path path; + assert(!net_ipv4_route_lookup(first, 0xc6336401u, 0, 0, &path)); + assert(path.ifindex == NET_IF_LOOPBACK && path.source == 0x7f000001u); + assert(net_ipv4_route_lookup(second, 0xc6336401u, 0, 0, &path) == -LINUX_ENETUNREACH); + route.metric = 20; + allocation_fail_after = 0; + assert(!net_ipv4_route_update(first, &route, false, true)); + allocation_fail_after = -1; + assert(first->ipv4_routes->route.metric == 20); + char text[2048] = {0}; + struct text_stream stream = {.buffer = text, .capacity = sizeof(text) - 1}; + current.net_ns = first; + assert(!net_proc_emit(&stream, "route") && strstr(text, "006433c6")); + current.net_ns = second; + memset(text, 0, sizeof(text)); + stream = (struct text_stream){.buffer = text, .capacity = sizeof(text) - 1}; + assert(!net_proc_emit(&stream, "route") && !strstr(text, "006433c6")); + memset(text, 0, sizeof(text)); + stream = (struct text_stream){.buffer = text, .capacity = sizeof(text) - 1}; + assert(!net_proc_emit(&stream, "dev") && strstr(text, "lo:") && !strstr(text, "eth0")); + const char *empty_leaves[] = {"if_inet6", "ipv6_route"}; + for (unsigned i = 0; i < sizeof(empty_leaves) / sizeof(empty_leaves[0]); ++i) { + memset(text, 0, sizeof(text)); + stream = (struct text_stream){.buffer = text, .capacity = sizeof(text) - 1}; + assert(!net_proc_emit(&stream, empty_leaves[i]) && !stream.position); + } + assert(net_ipv4_route_update(second, &route, true, false) == -LINUX_ESRCH); + assert(!net_ipv4_route_update(first, &route, true, false) && !first->ipv4_routes); + assert(!net_ipv4_route_update(first, &route, false, false)); + current = (struct task){0}; + net_namespace_put(first); net_namespace_put(second); + assert(allocations == baseline); + puts("PASS scoped IPv4 routes and proc: isolation, OOM, replacement, removal and final cleanup"); +} + +/** @brief Isolate link baselines, failed capture, notifications and overrun recovery. */ +static void check_scoped_link_events(void) +{ + unsigned baseline = allocations; + struct net_namespace *first, *second; + assert(!net_namespace_create(NULL, &first)); + assert(!net_namespace_create(NULL, &second)); + struct net_namespace *scopes[] = {NULL, first, second}; + int sockets[3]; + struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_groups = RTMGRP_LINK}; + for (unsigned i = 0; i < 3; ++i) { + current.net_ns = scopes[i]; + sockets[i] = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(sockets[i] >= 0); + unsigned before = allocations; + int capture_allocations = scopes[i] ? 2 : 4; + for (int fail = 0; fail < capture_allocations; ++fail) { + allocation_fail_after = fail; + assert(call(__NR_bind, sockets[i], (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_ENOMEM); + allocation_fail_after = -1; + assert(!nl_socket(&files[sockets[i]])->bound && !nl_socket(&files[sockets[i]])->groups); + assert(!nl_find_snapshot(scopes[i]) && allocations == before); + } + assert(!call(__NR_bind, sockets[i], (uintptr_t)&address, sizeof(address), 0, 0)); + } + assert(!net_interface_set_up(first, NET_IF_LOOPBACK, true)); + netlink_network_changed(first); + unsigned char output[512]; + assert(receive(sockets[1], output, sizeof(output)) > 0); + struct nlmsghdr *header = (void *)output; + assert(header->nlmsg_type == RTM_NEWLINK && ((struct ifinfomsg *)(header + 1))->ifi_flags & IFF_UP); + assert(receive(sockets[0], output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(sockets[2], output, sizeof(output)) == -LINUX_EAGAIN); + assert(!net_interface_set_up(first, NET_IF_LOOPBACK, false)); + allocation_fail_after = 0; + netlink_network_changed(first); + allocation_fail_after = -1; + assert(receive(sockets[1], output, sizeof(output)) == -LINUX_ENOBUFS); + assert(receive(sockets[0], output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(sockets[2], output, sizeof(output)) == -LINUX_EAGAIN); + netlink_network_changed(first); + assert(receive(sockets[1], output, sizeof(output)) > 0); + header = (void *)output; + assert(header->nlmsg_type == RTM_NEWLINK && !(((struct ifinfomsg *)(header + 1))->ifi_flags & IFF_UP)); + current.net_ns = first; + int duplicate = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(duplicate >= 0); + assert(!call(__NR_bind, duplicate, (uintptr_t)&address, sizeof(address), 0, 0)); + task_netlink_release(&files[sockets[1]]); files[sockets[1]] = (struct task_file){0}; + assert(nl_find_snapshot(first)); + int group = RTNLGRP_LINK; + assert(!call(__NR_setsockopt, duplicate, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, + (uintptr_t)&group, sizeof(group))); + assert(!nl_find_snapshot(first) && nl_find_snapshot(second) && nl_find_snapshot(NULL)); + current = (struct task){0}; + task_netlink_release(&files[duplicate]); files[duplicate] = (struct task_file){0}; + for (unsigned i = 0; i < 3; i += 2) { + task_netlink_release(&files[sockets[i]]); files[sockets[i]] = (struct task_file){0}; + } + net_namespace_put(first); net_namespace_put(second); + assert(!nl_snapshots && allocations == baseline); + puts("PASS scoped link events: capture rollback, delivery, overrun, retry and last subscriber"); +} + int main(void) { check_netlink_namespace_ports(); @@ -700,6 +956,10 @@ int main(void) check_netlink_reuseaddr(); check_uevent_userspace_delivery(); assert(!net_interface_register(2)); + check_netlink_interface_scopes(); + check_netlink_interface_authority(); + check_scoped_ipv4_routes(); + check_scoped_link_events(); check_netlink_metadata_options(); check_netlink_filter(); net_config.local_ip=0x0a00020f; net_config.subnet_mask=0xffffff00; @@ -828,25 +1088,25 @@ int main(void) .rtmsg_flags=RTF_UP,.rtmsg_ifindex=2}; assert(net_ipv6_interface_ioctl(SIOCADDRT,(uintptr_t)&in6route)==0 && updates==4); struct ifreq ifr={.ifr_name="lo"}; - assert(net_interface_ioctl(SIOCGIFINDEX,(uintptr_t)&ifr)==0 && ifr.data.value==1); + assert(net_interface_ioctl(NULL, SIOCGIFINDEX,(uintptr_t)&ifr)==0 && ifr.data.value==1); memset(&ifr,0,sizeof(ifr)); ifr.data.value=1; - assert(net_interface_ioctl(SIOCGIFNAME,(uintptr_t)&ifr)==0 && !strcmp(ifr.ifr_name,"lo")); + assert(net_interface_ioctl(NULL, SIOCGIFNAME,(uintptr_t)&ifr)==0 && !strcmp(ifr.ifr_name,"lo")); nic_ready=nic_present=false; net_interface_remove(2); strcpy(ifr.ifr_name,"lo"); - assert(net_interface_ioctl(SIOCGIFINDEX,(uintptr_t)&ifr)==0 && ifr.data.value==1); + assert(net_interface_ioctl(NULL, SIOCGIFINDEX,(uintptr_t)&ifr)==0 && ifr.data.value==1); memset(&ifr,0,sizeof(ifr)); ifr.data.value=1; - assert(net_interface_ioctl(SIOCGIFNAME,(uintptr_t)&ifr)==0 && !strcmp(ifr.ifr_name,"lo")); + assert(net_interface_ioctl(NULL, SIOCGIFNAME,(uintptr_t)&ifr)==0 && !strcmp(ifr.ifr_name,"lo")); strcpy(ifr.ifr_name,"eth0"); - assert(net_interface_ioctl(SIOCGIFINDEX,(uintptr_t)&ifr)==-LINUX_ENODEV); + assert(net_interface_ioctl(NULL, SIOCGIFINDEX,(uintptr_t)&ifr)==-LINUX_ENODEV); nic_ready=nic_present=true; assert(!net_interface_register(2)); memset(&ifr,0,sizeof(ifr)); ifr.data.value=2; - assert(net_interface_ioctl(SIOCGIFNAME,(uintptr_t)&ifr)==0 && !strcmp(ifr.ifr_name,"eth0")); + assert(net_interface_ioctl(NULL, SIOCGIFNAME,(uintptr_t)&ifr)==0 && !strcmp(ifr.ifr_name,"eth0")); strcpy(ifr.ifr_name,"eth0"); ifr.data.flags=0; - assert(net_interface_ioctl(SIOCSIFFLAGS,(uintptr_t)&ifr)==0 && link_changes==1); - assert(net_interface_ioctl(SIOCSIFFLAGS,(uintptr_t)&ifr)==0 && link_changes==1); + assert(net_interface_ioctl(NULL, SIOCSIFFLAGS,(uintptr_t)&ifr)==0 && link_changes==1); + assert(net_interface_ioctl(NULL, SIOCSIFFLAGS,(uintptr_t)&ifr)==0 && link_changes==1); char text[2048]={0}; struct text_stream stream={.buffer=text,.capacity=sizeof(text)-1}; assert(net_proc_emit(&stream,"if_inet6")==0); assert(strstr(text,"00000000000000000000000000000001 01 80 10 80 lo\n")); diff --git a/tools/tests/ipv6_protocol_test.c b/tools/tests/ipv6_protocol_test.c index 375d0fcd..9bde9830 100644 --- a/tools/tests/ipv6_protocol_test.c +++ b/tools/tests/ipv6_protocol_test.c @@ -65,10 +65,10 @@ const uint8_t *netdev_mac(uint32_t index) { return index==second_index?second_ma int netdev_send(uint32_t index,const void *frame,uint32_t len) { assert(index==2 || (index==second_index && second_nic));assert(sent_count<128); sent_ifindex[sent_count]=index;return e1000_send(frame,len); } -bool net_interface_exists(uint32_t index) +bool net_interface_exists(struct net_namespace *ns, uint32_t index) { return index==1 || (index==2 && first_nic) || (index==second_index && second_nic) || (index>=100 && index-100>24)==127?1:0; } +bool net_interface_exists(struct net_namespace *ns, uint32_t index) { return index==1; } +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return index==1; } +uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip) { return (ip>>24)==127?1:0; } uint32_t netdev_next(uint32_t after) { (void)after;return 0; } int netdev_send(uint32_t index,const void *data,uint32_t length) { (void)index;(void)data;(void)length;return -LINUX_ENETDOWN; } -int net_ipv4_route_lookup(uint32_t destination,uint32_t source,uint32_t scope,struct net_ipv4_path *out) +int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination,uint32_t source,uint32_t scope,struct net_ipv4_path *out) { if((destination>>24)!=127 || (scope && scope!=1))return -LINUX_ENETUNREACH; *out=(struct net_ipv4_path){.source=source?source:0x7f000001u,.destination=destination, @@ -202,4 +202,4 @@ int main(void) puts("PASS IPv6 and IPv4-mapped TCP deferred loopback handshake, accept, payload and FIN"); } -bool net_interface_is_up(uint32_t index) { return net_interface_is_ready(index); } +bool net_interface_is_up(struct net_namespace *ns, uint32_t index) { return net_interface_is_ready(NULL, index); } diff --git a/tools/tests/ipv6_transport_test.c b/tools/tests/ipv6_transport_test.c index 6514acb9..a061baf5 100644 --- a/tools/tests/ipv6_transport_test.c +++ b/tools/tests/ipv6_transport_test.c @@ -237,7 +237,7 @@ int main(void) return ipv4_udp_regression_main(); } -bool net_interface_is_ready(uint32_t index) { return index >= 1 && index <= 3; } +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return index >= 1 && index <= 3; } const uint8_t *netdev_mac(uint32_t index) { (void)index; return e1000_mac(); } int netdev_send(uint32_t index, const void *frame, uint32_t length) { (void)index; return e1000_send(frame, length); } diff --git a/tools/tests/net_interface_test.c b/tools/tests/net_interface_test.c index 3e26f718..7fffc1e0 100644 --- a/tools/tests/net_interface_test.c +++ b/tools/tests/net_interface_test.c @@ -16,7 +16,7 @@ void e1000_get_info(struct e1000_info *info) { *info=(struct e1000_info){.present=nic_present,.active=nic_present && nic_carrier}; } void net_ipv6_link_changed(bool up) { (void)up; } int net_ipv6_link_changed_on(uint32_t index, bool up) { (void)index; (void)up; return 0; } -void netlink_ipv6_changed(void) { } +void netlink_network_changed(struct net_namespace *ns) { (void)ns; } const uint8_t *e1000_mac(void) { static const uint8_t mac[6] = {2,3,4,5,6,7}; return mac; } uint32_t netdev_next(uint32_t after) { return nic_present && after < 2 ? 2 : 0; } int netdev_is_ready(uint32_t index) { return index == 2 && e1000_is_ready(); } @@ -25,7 +25,7 @@ void netdev_get_info(uint32_t index, struct e1000_info *info) { if (index == 2) { e1000_get_info(info); memcpy(info->mac,e1000_mac(),6); } else memset(info,0,sizeof(*info)); } bool user_range_ok(uint64_t address, uint64_t size) { return address >= 4096 && size <= 4096; } bool user_range_writable(uint64_t address, uint64_t size) { return user_range_ok(address, size); } -static int call(unsigned command, struct ifreq *req) { return net_interface_ioctl(command, (uintptr_t)req); } +static int call(unsigned command, struct ifreq *req) { return net_interface_ioctl(NULL, command, (uintptr_t)req); } int main(void) { assert(!net_interface_register(2)); @@ -46,14 +46,14 @@ int main(void) struct rtentry rt = {.rt_dst.sa_family = AF_INET, .rt_gateway.sa_family = AF_INET, .rt_genmask.sa_family = 0, .rt_flags = 3}; net_put_u32((uint8_t *)&rt.rt_gateway + 4, 0x0a000202); - assert(net_interface_ioctl(SIOCADDRT, (uintptr_t)&rt) == 0); + assert(net_interface_ioctl(NULL, SIOCADDRT, (uintptr_t)&rt) == 0); assert(net_config.gateway_ip == 0x0a000202); - assert(net_interface_ioctl(SIOCADDRT, (uintptr_t)&rt) == -LINUX_EEXIST); - assert(net_interface_ioctl(SIOCDELRT, (uintptr_t)&rt) == 0); - assert(net_interface_ioctl(SIOCDELRT, (uintptr_t)&rt) == -LINUX_ESRCH); + assert(net_interface_ioctl(NULL, SIOCADDRT, (uintptr_t)&rt) == -LINUX_EEXIST); + assert(net_interface_ioctl(NULL, SIOCDELRT, (uintptr_t)&rt) == 0); + assert(net_interface_ioctl(NULL, SIOCDELRT, (uintptr_t)&rt) == -LINUX_ESRCH); struct ifreq output[2]; struct ifconf conf = {.ifc_len = sizeof(output), .ifc_buf = (uintptr_t)&output}; - assert(net_interface_ioctl(SIOCGIFCONF, (uintptr_t)&conf) == 0); + assert(net_interface_ioctl(NULL, SIOCGIFCONF, (uintptr_t)&conf) == 0); assert(conf.ifc_len == sizeof(output) && !strcmp(output[0].ifr_name, "lo") && !strcmp(output[1].ifr_name, "eth0")); assert(net_get_u32((uint8_t *)&output[1].data.addr + 4) == 0x0a00020f); @@ -72,16 +72,16 @@ int main(void) assert(call(SIOCSIFFLAGS,&req)==0); assert(call(SIOCGIFMTU,&req)==0 && req.data.value==1500); conf.ifc_len=sizeof(output); - assert(!net_interface_ioctl(SIOCGIFCONF,(uintptr_t)&conf) && conf.ifc_len==sizeof(output)); + assert(!net_interface_ioctl(NULL, SIOCGIFCONF,(uintptr_t)&conf) && conf.ifc_len==sizeof(output)); nic_present=false; net_interface_remove(2); assert(call(SIOCGIFINDEX,&req)==-LINUX_ENODEV); conf.ifc_len=sizeof(output); - assert(!net_interface_ioctl(SIOCGIFCONF,(uintptr_t)&conf) && conf.ifc_len==sizeof(struct ifreq)); + assert(!net_interface_ioctl(NULL, SIOCGIFCONF,(uintptr_t)&conf) && conf.ifc_len==sizeof(struct ifreq)); nic_present=nic_carrier=true; assert(!net_interface_register(2)); strcpy(req.ifr_name, "absent"); assert(call(SIOCGIFINDEX, &req) == -LINUX_ENODEV); - assert(net_interface_ioctl(SIOCGIFINDEX, 0) == -LINUX_EFAULT); + assert(net_interface_ioctl(NULL, SIOCGIFINDEX, 0) == -LINUX_EFAULT); puts("PASS real kernel interface ioctl permissions, address/mask, route, enumeration, up/down"); } diff --git a/tools/tests/net_multi_interface_test.c b/tools/tests/net_multi_interface_test.c index 2f003a05..26274dbb 100644 --- a/tools/tests/net_multi_interface_test.c +++ b/tools/tests/net_multi_interface_test.c @@ -38,7 +38,7 @@ int net_ipv6_route_update(const struct net_ipv6_route *route, bool remove) void net_arp_cache_clear_on(uint32_t index) { (void)index; } static int call(unsigned command, struct ifreq *req) -{ return net_interface_ioctl(command, (uintptr_t)req); } +{ return net_interface_ioctl(NULL, command, (uintptr_t)req); } static int netlink_request_error(const struct nlmsghdr *request) { struct netlink_message *message=kernel_malloc(sizeof(*message)+NL_MESSAGE_MAX); @@ -64,7 +64,7 @@ static void set_address(const char *name, unsigned command, uint32_t ip) int main(void) { struct ifconf conf = {0}; - assert(net_interface_ioctl(SIOCGIFCONF, (uintptr_t)&conf) == 0); + assert(net_interface_ioctl(NULL, SIOCGIFCONF, (uintptr_t)&conf) == 0); assert(conf.ifc_len == sizeof(struct ifreq)); assert(!net_interface_register(2) && !net_interface_register(3)); struct { struct nlmsghdr header; struct ifinfomsg info; } link={ @@ -72,10 +72,10 @@ int main(void) .nlmsg_flags=NLM_F_REQUEST|NLM_F_ACK}, .info={.ifi_family=AF_UNSPEC,.ifi_index=3,.ifi_change=IFF_UP}}; assert(netlink_request_error(&link.header)==-LINUX_EPERM); - assert(net_interface_is_up(2) && net_interface_is_up(3)); + assert(net_interface_is_up(NULL, 2) && net_interface_is_up(NULL, 3)); current.cap_effective=1ULL << CAP_NET_ADMIN; assert(!netlink_request_error(&link.header)); - assert(net_interface_is_up(2) && !net_interface_is_up(3)); + assert(net_interface_is_up(NULL, 2) && !net_interface_is_up(NULL, 3)); struct { struct nlmsghdr header; struct ifinfomsg info; struct rtattr name; char value[8]; struct rtattr mtu; uint32_t size; } named_link={ .header={.nlmsg_len=sizeof(named_link),.nlmsg_type=19, @@ -84,15 +84,15 @@ int main(void) .name={.rta_len=RTA_LENGTH(5),.rta_type=IFLA_IFNAME},.value="eth1", .mtu={.rta_len=RTA_LENGTH(4),.rta_type=IFLA_MTU},.size=1500}; assert(!netlink_request_error(&named_link.header)); - assert(net_interface_is_up(3)); + assert(net_interface_is_up(NULL, 3)); named_link.size=1400; named_link.info.ifi_flags=0; assert(netlink_request_error(&named_link.header)==-LINUX_EOPNOTSUPP); - assert(net_interface_is_up(3)); + assert(net_interface_is_up(NULL, 3)); named_link.size=1500; named_link.mtu.rta_type=IFLA_ADDRESS; assert(netlink_request_error(&named_link.header)==-LINUX_EOPNOTSUPP); - assert(net_interface_is_up(3)); + assert(net_interface_is_up(NULL, 3)); current.cap_effective=0; struct ifreq req = {.ifr_name = "eth1"}; assert(!call(SIOCGIFINDEX, &req) && req.data.value == 3); @@ -108,7 +108,7 @@ int main(void) .address={.ifa_family=AF_INET6,.ifa_prefixlen=64,.ifa_index=3}, .local={.rta_len=RTA_LENGTH(16),.rta_type=IFA_LOCAL},.ip={0x20,1,0xdb,8}, .label={.rta_len=RTA_LENGTH(5),.rta_type=IFA_LABEL},.name="eth1"}; - assert(!nl_change_address(&address6.header,false)); + assert(!nl_change_address(NULL, &address6.header,false)); strcpy(req.ifr_name, "eth01"); assert(call(SIOCGIFINDEX, &req) == -LINUX_ENODEV); @@ -124,28 +124,28 @@ int main(void) set_address("eth1", SIOCSIFNETMASK, 0xffffff00u); struct ifreq list[3]; conf = (struct ifconf){.ifc_len = sizeof(list), .ifc_buf = (uintptr_t)list}; - assert(!net_interface_ioctl(SIOCGIFCONF, (uintptr_t)&conf)); + assert(!net_interface_ioctl(NULL, SIOCGIFCONF, (uintptr_t)&conf)); assert(conf.ifc_len == sizeof(list)); assert(!strcmp(list[0].ifr_name, "lo") && !strcmp(list[1].ifr_name, "eth0") && !strcmp(list[2].ifr_name, "eth1")); assert(net_get_u32((uint8_t *)&list[1].data.addr + 4) == 0x0a00020fu); assert(net_get_u32((uint8_t *)&list[2].data.addr + 4) == 0xc0a8070fu); conf.ifc_len = 2 * sizeof(struct ifreq) + 1; - assert(!net_interface_ioctl(SIOCGIFCONF, (uintptr_t)&conf)); + assert(!net_interface_ioctl(NULL, SIOCGIFCONF, (uintptr_t)&conf)); assert(conf.ifc_len == 2 * sizeof(struct ifreq)); struct net_ipv4_path path; - assert(!net_ipv4_route_lookup(0xc0a80732u, 0x0a00020fu, 0, &path)); + assert(!net_ipv4_route_lookup(NULL, 0xc0a80732u, 0x0a00020fu, 0, &path)); assert(path.ifindex == 3 && path.source == 0x0a00020fu && path.next_hop == 0xc0a80732u); char eth1[] = "eth1"; struct rtentry route = {.rt_dst.sa_family = AF_INET, .rt_gateway.sa_family = AF_INET, .rt_flags = RTF_UP | RTF_GATEWAY, .rt_dev = (uintptr_t)eth1}; net_put_u32((uint8_t *)&route.rt_gateway + 4, 0xc0a80701u); - assert(!net_interface_ioctl(SIOCADDRT, (uintptr_t)&route)); - assert(!net_ipv4_route_lookup(0x08080808u, 0, 0, &path)); + assert(!net_interface_ioctl(NULL, SIOCADDRT, (uintptr_t)&route)); + assert(!net_ipv4_route_lookup(NULL, 0x08080808u, 0, 0, &path)); assert(path.ifindex == 3 && path.source == 0xc0a8070fu && path.next_hop == 0xc0a80701u); - assert(!net_interface_ioctl(SIOCDELRT, (uintptr_t)&route)); - assert(net_ipv4_route_lookup(0x08080808u, 0, 0, &path) == -LINUX_ENETUNREACH); + assert(!net_interface_ioctl(NULL, SIOCDELRT, (uintptr_t)&route)); + assert(net_ipv4_route_lookup(NULL, 0x08080808u, 0, 0, &path) == -LINUX_ENETUNREACH); struct { struct nlmsghdr header; @@ -156,9 +156,9 @@ int main(void) .address={.ifa_family=AF_INET,.ifa_prefixlen=24,.ifa_index=3}, .local={.rta_len=RTA_LENGTH(4),.rta_type=IFA_LOCAL}, .ip=__builtin_bswap32(0xc0a8080fu)}; - assert(!nl_change_address(&change.header, false)); - assert(net_interface_get(3)->config.local_ip == 0xc0a8080fu); - assert(net_interface_get(3)->config.subnet_mask == 0xffffff00u); + assert(!nl_change_address(NULL, &change.header, false)); + assert(net_interface_get(NULL, 3)->config.local_ip == 0xc0a8080fu); + assert(net_interface_get(NULL, 3)->config.subnet_mask == 0xffffff00u); struct { struct nlmsghdr header; struct rtmsg route; @@ -173,25 +173,25 @@ int main(void) .destination={.rta_len=RTA_LENGTH(4),.rta_type=RTA_DST},.dst=__builtin_bswap32(0xc6330000u), .gateway={.rta_len=RTA_LENGTH(4),.rta_type=RTA_GATEWAY},.gw=__builtin_bswap32(0xc0a80801u), .output={.rta_len=RTA_LENGTH(4),.rta_type=RTA_OIF},.ifindex=3}; - assert(!nl_change_route(&route_change.header,false)); - assert(!net_ipv4_route_lookup(0xc6336409u,0,0,&path)); + assert(!nl_change_route(NULL, &route_change.header,false)); + assert(!net_ipv4_route_lookup(NULL, 0xc6336409u,0,0,&path)); assert(path.ifindex==3 && path.next_hop==0xc0a80801u); - net_interface_get(2)->config.local_ip = 0; - assert(!net_ipv4_route_lookup(UINT32_MAX, 0, 2, &path)); + net_interface_get(NULL, 2)->config.local_ip = 0; + assert(!net_ipv4_route_lookup(NULL, UINT32_MAX, 0, 2, &path)); assert(path.ifindex == 2 && path.source == 0); struct netlink_socket listener={.groups=RTMGRP_LINK}; netlink_sockets=&listener; - assert(!nl_initial_snapshot()); + assert(!nl_initial_snapshot(NULL)); net_interface_remove(3); netlink_ipv6_changed(); assert(listener.head && ((struct nlmsghdr *)(void *)listener.head->data)->nlmsg_type==RTM_DELLINK); struct ifinfomsg *event=(void *)(listener.head->data+sizeof(struct nlmsghdr)); assert(event->ifi_index==3); kernel_free(listener.head); listener.head=listener.tail=NULL; - nl_forget_snapshot(); netlink_sockets=NULL; + nl_forget_snapshot(NULL); netlink_sockets=NULL; net_interface_remove(2); - assert(net_interface_next(1) == 0 && net_interface_index("eth0") == 0); + assert(net_interface_next(NULL, 1) == 0 && net_interface_index(NULL, "eth0") == 0); puts("PASS multi-interface IPv4 configuration, enumeration, routes, weak-host source and broadcast"); return 0; } diff --git a/tools/tests/net_multinic_data_test.c b/tools/tests/net_multinic_data_test.c index f1e48033..81ca27dd 100644 --- a/tools/tests/net_multinic_data_test.c +++ b/tools/tests/net_multinic_data_test.c @@ -23,28 +23,28 @@ static uint32_t wire_length, wire_index, transmissions; uint64_t time_uptime_ms(void) { return clock_ms; } uint32_t netdev_next(uint32_t after) { return after < 2 ? 2 : after == 2 ? 3 : 0; } const uint8_t *netdev_mac(uint32_t index) { assert(index==2 || index==3); return device_macs[index-2]; } -bool net_interface_is_ready(uint32_t index) { return index>=2 && index<=3 && ready[index-2]; } -struct net_interface *net_interface_get(uint32_t index) { return index>=2 && index<=3 ? &devices[index-2] : NULL; } -int net_interface_get_config(uint32_t index, struct reliefos_net_config *out) +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return index>=2 && index<=3 && ready[index-2]; } +struct net_interface *net_interface_get(struct net_namespace *ns, uint32_t index) { return index>=2 && index<=3 ? &devices[index-2] : NULL; } +int net_interface_get_config(struct net_namespace *ns, uint32_t index, struct reliefos_net_config *out) { - struct net_interface *device=net_interface_get(index); + struct net_interface *device=net_interface_get(NULL, index); if (!device) return -LINUX_ENODEV; *out=device->config; return 0; } -bool net_interface_name(uint32_t index, char out[16]) +bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[16]) { if (index<2 || index>3) return false; strcpy(out,index==2 ? "eth0" : "eth1"); return true; } int netdev_send(uint32_t index, const void *frame, uint32_t length) { - assert(net_interface_is_ready(index) && length<=sizeof(wire)); + assert(net_interface_is_ready(NULL, index) && length<=sizeof(wire)); wire_index=index; wire_length=length; ++transmissions; memcpy(wire,frame,length); return 0; } -int net_ipv4_route_lookup(uint32_t destination, uint32_t source, uint32_t scope, struct net_ipv4_path *out) +int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32_t source, uint32_t scope, struct net_ipv4_path *out) { uint32_t index=scope ? scope : (destination & 0xffffff00)==0x0a000300 ? 3 : 2; - if (!net_interface_is_ready(index)) return -LINUX_ENETDOWN; + if (!net_interface_is_ready(NULL, index)) return -LINUX_ENETDOWN; *out=(struct net_ipv4_path){.ifindex=index,.source=source ? source : devices[index-2].config.local_ip, .destination=destination,.next_hop=destination}; return 0; diff --git a/tools/tests/net_packet_test.c b/tools/tests/net_packet_test.c index 680cbd63..c81b98c8 100644 --- a/tools/tests/net_packet_test.c +++ b/tools/tests/net_packet_test.c @@ -42,13 +42,13 @@ int e1000_send(const void *p, uint32_t n) { assert(n <= sizeof(sent)); memcpy(se int net_get_config(struct reliefos_net_config *c) { *c=(struct reliefos_net_config){0}; return 0; } int net_ipv4_send_raw(uint32_t d, uint32_t s, uint8_t p, bool h, const void *b, uint32_t n) { (void)d; (void)s; (void)p; (void)h; (void)b; return n; } -bool net_interface_exists(uint32_t index) { return index >= 1 && index <= 3; } -bool net_interface_is_ready(uint32_t index) { return index >= 2 && index <= 3; } -uint32_t net_interface_index(const char *name) +bool net_interface_exists(struct net_namespace *ns, uint32_t index) { return index >= 1 && index <= 3; } +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return index >= 2 && index <= 3; } +uint32_t net_interface_index(struct net_namespace *ns, const char *name) { return !strcmp(name,"lo") ? 1 : !strcmp(name,"eth0") ? 2 : !strcmp(name,"eth1") ? 3 : 0; } -bool net_interface_name(uint32_t index, char out[16]) -{ if (!net_interface_exists(index)) return false; strcpy(out,index == 1 ? "lo" : index == 2 ? "eth0" : "eth1"); return true; } -uint32_t net_interface_for_ipv4(uint32_t ip) { return (ip >> 24) == 127 ? 1 : 0; } +bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[16]) +{ if (!net_interface_exists(NULL, index)) return false; strcpy(out,index == 1 ? "lo" : index == 2 ? "eth0" : "eth1"); return true; } +uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip) { return (ip >> 24) == 127 ? 1 : 0; } uint32_t netdev_next(uint32_t after) { return after < 2 ? 2 : after == 2 ? 3 : 0; } const uint8_t *netdev_mac(uint32_t index) { static const uint8_t macs[2][6] = {{2,3,4,5,6,7},{2,3,4,5,6,8}}; return macs[index == 3]; } diff --git a/tools/tests/net_rx_budget_test.c b/tools/tests/net_rx_budget_test.c index d5e8e868..b75bcfc9 100644 --- a/tools/tests/net_rx_budget_test.c +++ b/tools/tests/net_rx_budget_test.c @@ -18,7 +18,7 @@ uint32_t netdev_rx_take(uint32_t after) } void netdev_rx_notify(uint32_t id) { assert(id>=2 && id<=3); pending[id-2]=1; } uint32_t netdev_next(uint32_t after) { return after<2 ? 2 : after==2 ? 3 : 0; } -bool net_interface_is_up(uint32_t id) { return id>=2 && id<=3 && !down; } +bool net_interface_is_up(struct net_namespace *ns, uint32_t id) { return id>=2 && id<=3 && !down; } int netdev_poll(uint32_t id,void *frame,uint32_t capacity,uint32_t *length) { assert(id>=2 && id<=3 && capacity>=64); ++attempts; *length=0; diff --git a/tools/tests/socket_batch_unix_test.c b/tools/tests/socket_batch_unix_test.c index d39e13d1..1868fc4b 100644 --- a/tools/tests/socket_batch_unix_test.c +++ b/tools/tests/socket_batch_unix_test.c @@ -2,6 +2,7 @@ #include #include #include +#include #include #include "../../kernel/syscall/ipc/socket.c" #include "../../kernel/syscall/ipc/socket_batch.c" @@ -22,6 +23,18 @@ static bool netlink_credentials_fixture; static bool netlink_pktinfo_fixture; static unsigned netlink_receive_calls; static const struct ucred netlink_sender = {41, 1002, 3003}; +static bool interface_ioctl_expected; +static struct net_namespace *interface_ioctl_scope; +static uint32_t interface_ioctl_request; +static uint64_t interface_ioctl_address; +/** @brief Check UNIX ioctl dispatch without substituting interface policy. */ +int net_interface_ioctl(struct net_namespace *ns, uint32_t request, uint64_t address) +{ + assert(interface_ioctl_expected && ns == interface_ioctl_scope); + assert(request == interface_ioctl_request && address == interface_ioctl_address); + interface_ioctl_expected = false; + return -LINUX_EOPNOTSUPP; +} /* AF_UNIX cases must not cross into another socket family's backend. */ int task_udp_recv(struct task_file *f, void *b, uint32_t n, uint32_t flags, uint64_t a, uint64_t l) { (void)f; (void)b; (void)n; (void)flags; (void)a; (void)l; abort(); } @@ -535,6 +548,35 @@ static void check_netlink_packet_info(void) puts("PASS netlink packet info: group indices, optional source, credentials, truncation and output faults"); } +/** @brief Keep interface ioctl dispatch in the socket's retained creating scope. */ +static void check_interface_ioctl_scope(void) +{ + assert(!allocations); + struct net_namespace *creating, *receiving; + assert(!net_namespace_create(NULL, &creating)); + assert(!net_namespace_create(NULL, &receiving)); + peers[0].net_ns = net_namespace_get(creating); + net_namespace_put(creating); + current.net_ns = receiving; + struct ifreq request = {0}; + for (unsigned i = 0; i < 2; ++i) { + interface_ioctl_scope = i ? NULL : creating; + interface_ioctl_request = SIOCGIFINDEX; + interface_ioctl_address = (uintptr_t)&request; + interface_ioctl_expected = true; + assert(task_socket_ioctl(&endpoints[i], SIOCGIFINDEX, (uintptr_t)&request) == + -LINUX_EOPNOTSUPP); + assert(!interface_ioctl_expected); + } + net_namespace_put(peers[0].net_ns); + peers[0].net_ns = NULL; + current.net_ns = NULL; + net_namespace_put(receiving); + interface_ioctl_scope = NULL; + assert(!allocations); + puts("PASS UNIX interface ioctl dispatch: moved caller and retained socket network scope"); +} + int main(void) { current.kind = TASK_KIND_USER; @@ -548,6 +590,7 @@ int main(void) endpoints[i] = (struct task_file){.used = 1, .references = 1, .aux = i + 1, .flags = TASK_FILE_FLAG_SOCKET | TASK_FILE_FLAG_SOCKET_UNIX | RELIEFOS_O_RDWR}; } + check_interface_ioctl_scope(); check_unix_reuseaddr(); check_unix_timestamps(); /* Linux imports the outgoing header before blocking. A changed user diff --git a/tools/tests/udp_socket_test.c b/tools/tests/udp_socket_test.c index fb028dad..124373fb 100644 --- a/tools/tests/udp_socket_test.c +++ b/tools/tests/udp_socket_test.c @@ -52,15 +52,15 @@ int net_ipv4_send_udp(uint32_t source, uint32_t destination, uint16_t source_por uint16_t destination_port, const void *data, uint32_t length) { (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; return -LINUX_ENETDOWN; } -uint32_t net_interface_for_ipv4(uint32_t ip) +uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip) { return (ip >> 24) == 127 ? 1 : ip == 0x0a00020f ? 2 : ip == 0x0a00030f ? 3 : 0; } -bool net_interface_exists(uint32_t index) { return index >= 1 && index <= 3; } -uint32_t net_interface_index(const char *name) +bool net_interface_exists(struct net_namespace *ns, uint32_t index) { return index >= 1 && index <= 3; } +uint32_t net_interface_index(struct net_namespace *ns, const char *name) { return !strcmp(name,"lo") ? 1 : !strcmp(name,"eth0") ? 2 : !strcmp(name,"eth1") ? 3 : 0; } -bool net_interface_name(uint32_t index, char out[16]) -{ if (!net_interface_exists(index)) return false; strcpy(out, index == 1 ? "lo" : index == 2 ? "eth0" : "eth1"); return true; } +bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[16]) +{ if (!net_interface_exists(NULL, index)) return false; strcpy(out, index == 1 ? "lo" : index == 2 ? "eth0" : "eth1"); return true; } uint32_t netdev_next(uint32_t after) { return after < 2 ? 2 : after == 2 ? 3 : 0; } -int net_ipv4_route_lookup(uint32_t destination, uint32_t source, uint32_t scope, struct net_ipv4_path *path) +int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32_t source, uint32_t scope, struct net_ipv4_path *path) { uint32_t index=scope ? scope : 2; *path=(struct net_ipv4_path){.ifindex=index, .source=source ? source : index==3 ? 0x0a00030f : 0x0a00020f,.destination=destination,.next_hop=destination}; return 0; } int net_ipv4_send_udp_on(uint32_t index, uint32_t source, uint32_t destination, From bbfc6cb22a708ba8d822f589768addb32c4a0fe5 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 05:42:35 +0800 Subject: [PATCH 73/97] feat(net): isolate IPv6 protocol state by network namespace --- Documentation/core-api/mount-namespaces.rst | 8 +- Documentation/core-api/network-devices.rst | 5 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 50 +- .../LC_MESSAGES/core-api/network-devices.po | 18 +- .../en/LC_MESSAGES/userspace-api/ipv6.po | 43 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 44 +- .../LC_MESSAGES/core-api/network-devices.po | 12 +- .../ja/LC_MESSAGES/userspace-api/ipv6.po | 37 +- Documentation/userspace-api/ipv6.rst | 6 +- include/reliefnt/net_interface.h | 6 +- include/reliefnt/net_ipv6.h | 82 +- include/reliefnt/net_namespace.h | 6 +- kernel/syscall/device/legacy_ioctl.c | 2 +- net/core.c | 12 +- net/input.c | 2 +- net/interface/config.c | 14 +- net/interface/ioctl.c | 1 - net/interface/state.c | 3 + net/ipv6/Kbuild | 2 +- net/ipv6/core.c | 917 ++++++++++-------- net/ipv6/internal.h | 102 ++ net/ipv6/state.c | 50 + net/namespace/namespace.c | 8 + net/proc.c | 22 +- net/socket/netlink.c | 19 +- net/socket/packet.c | 24 +- net/socket/udp.c | 18 +- net/tcp/input.c | 4 +- net/tcp/output.c | 4 +- net/tcp/socket.c | 6 +- tools/test_eevdf.py | 3 +- tools/test_ipv6_control.py | 2 +- tools/test_ipv6_protocol.py | 4 +- tools/test_ipv6_transport.py | 2 +- tools/test_linux_socket_batches.py | 2 +- tools/test_network.py | 2 +- tools/test_poll_wakeup.py | 2 +- tools/test_sched_resume.py | 6 +- tools/tests/ipv6_control_test.c | 262 ++++- tools/tests/ipv6_protocol_test.c | 390 +++++--- tools/tests/ipv6_tcp_test.c | 12 +- tools/tests/ipv6_transport_test.c | 17 +- tools/tests/ipv6_vector_test.c | 16 +- tools/tests/modules/scheduler.h | 1 + tools/tests/net_interface_test.c | 4 +- tools/tests/net_multi_interface_test.c | 20 +- tools/tests/net_packet_test.c | 16 +- tools/tests/net_rx_budget_test.c | 4 +- tools/tests/task8_block_ioctl_user_test.c | 1 + ...date-1-block-ioctl-user-candidate-1.stub.c | 18 +- ...didate-3-net-ioctl-user-candidate-3.stub.c | 54 +- tools/tests/tcp_state_test.c | 26 +- tools/tests/udp_socket_test.c | 16 +- 53 files changed, 1636 insertions(+), 771 deletions(-) create mode 100644 net/ipv6/internal.h create mode 100644 net/ipv6/state.c diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 68675eba..33edbcb3 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -160,13 +160,13 @@ hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护 ``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。 -每个网络空间独立持有 loopback、接口列表和显式 IPv4 路由。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时分配 ``127.0.0.1/8``。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由和 owner 引用。 +每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 ``127.0.0.1/8``、``::1/128`` 和 IPv6 host route。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由、IPv6 协议资源和 owner 引用。 -网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口和 IPv4 路由查询、修改及 netlink 控制面使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。IPv6 和 transport 状态隔离仍待完成。 +网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用,允许 transport 回调释放最后一个外部引用。初始网络重新初始化保留其他活跃空间。transport registry 的网络隔离仍待完成。 -``/proc/net/dev`` 和 ``route`` 按调用者当前网络 scope 输出。非初始空间的 ``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``if_inet6`` 和 ``ipv6_route`` 为空,``unix`` 按真实 socket scope 枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。 +``/proc/net/dev``、``route``、``if_inet6`` 和 ``ipv6_route`` 按调用者当前网络 scope 输出。非初始空间的 ``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``unix`` 按真实 socket scope 枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。 -用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 IPv6 与 transport 隔离完成后接通。 +用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 transport 隔离完成后接通。 netlink 端口与事件 ================== diff --git a/Documentation/core-api/network-devices.rst b/Documentation/core-api/network-devices.rst index 81756c44..b278af0c 100644 --- a/Documentation/core-api/network-devices.rst +++ b/Documentation/core-api/network-devices.rst @@ -32,10 +32,7 @@ IPv4 路由优先使用最长前缀,再比较 metric 和接口索引。绑定 区分。TCP 路由变化时重新检查下一跳 MAC,向本机 NIC 地址发送的 TCP、UDP 保留目标接口身份。 -IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 携带 ifindex。 -逐链路状态通过动态分配管理,RA、RS、DAD、MLD 和发现定时分别推进。 -不同链路可以使用相同 link-local 地址,socket 的作用域与设备绑定须一致。 -现有 IPv6 地址、路由和邻居等共享表仍有各自的资源容量,耗尽时返回错误。 +IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 按网络空间隔离,并携带该空间的 ifindex。逐链路状态通过动态分配管理,RA、RS、DAD、MLD 和发现定时分别推进。不同链路可以使用相同 link-local 地址,socket 的作用域与设备绑定须一致。IPv6 表和队列的容量按网络空间分别计量,耗尽时返回错误。 Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及 行政状态开关。接口配置修改需要 ``CAP_NET_ADMIN``。首次设置 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 78faff45..4c6feb20 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -433,17 +433,49 @@ msgstr "Network namespace lifetime" msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" msgstr "``net_namespace_create()`` creates a reference-counted network namespace with an immutable user owner. ``NULL`` denotes the permanent initial network namespace. Tasks share the namespace on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix and netlink socket independently retains its creating network namespace until its final reference closes. Unix server connections inherit the listener namespace." -msgid "每个网络空间独立持有 loopback、接口列表和显式 IPv4 路由。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时分配 ``127.0.0.1/8``。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由和 owner 引用。" -msgstr "Each network namespace owns independent loopback state, an interface list and explicit IPv4 routes. A new namespace starts with ``lo`` down and unaddressed. Bringing it up for the first time assigns ``127.0.0.1/8``. Physical NIC registration and ingress remain in the initial network namespace. The final namespace reference releases its interface list, explicit IPv4 routes and owner reference." +msgid "" +"每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 " +"``127.0.0.1/8``、``::1/128`` 和 IPv6 host route。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 " +"IPv4 路由、IPv6 协议资源和 owner 引用。" +msgstr "" +"Each network owns its loopback, interface list, explicit IPv4 routes and IPv6 protocol state." +" A new network's ``lo`` starts down without addresses, and the first up transition configures" +" ``127.0.0.1/8``, ``::1/128`` and an IPv6 host route. Physical NIC registration and ingress " +"remain in the initial network. The final namespace reference releases interfaces, explicit " +"IPv4 routes, IPv6 resources and the owner reference." -msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口和 IPv4 路由查询、修改及 netlink 控制面使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。IPv6 和 transport 状态隔离仍待完成。" -msgstr "Network namespaces scope Unix abstract addresses, proc enumeration, netlink ports and message delivery. Interface and IPv4 route queries and mutations, together with the netlink control plane, use the network scope retained when the socket was created. Mutations require ``CAP_NET_ADMIN`` in that scope’s user owner. IPv6 address and route dumps are empty in non-initial namespaces, and IPv6 mutations that pass authorization return ``EOPNOTSUPP``. IPv6 and transport state isolation remain pending." +msgid "" +"网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket " +"创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 " +"地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用,允许 transport " +"回调释放最后一个外部引用。初始网络重新初始化保留其他活跃空间。transport registry 的网络隔离仍待完成。" +msgstr "" +"Network namespaces scope Unix abstract addresses, proc enumeration, netlink ports and message" +" delivery. Netlink interface, IPv4/IPv6 address and route queries and changes use the " +"socket's retained creating network, with changes requiring ``CAP_NET_ADMIN`` in its user " +"owner. IPv6 addresses, routes, neighbors, multicast, pending packets, reassembly, PMTU, " +"fragment identifiers and ICMP error rate limits are isolated by network. Maintenance visits " +"live protocol states and retains the serviced namespace across transport callbacks that can " +"release its final external reference. Reinitializing the initial network preserves other live" +" scopes. Transport registry network isolation remains pending." -msgid "``/proc/net/dev`` 和 ``route`` 按调用者当前网络 scope 输出。非初始空间的 ``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``if_inet6`` 和 ``ipv6_route`` 为空,``unix`` 按真实 socket scope 枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。" -msgstr "``/proc/net/dev`` and ``route`` use the caller’s current network scope. In non-initial namespaces, ``arp``, ``udp``, ``tcp``, ``tcp6``, ``udp6`` and ``raw6`` contain only headers, while ``if_inet6`` and ``ipv6_route`` are empty. ``unix`` enumerates sockets by their actual scope. The ``lo`` counters in ``dev`` currently report zero in non-initial namespaces." +msgid "" +"``/proc/net/dev``、``route``、``if_inet6`` 和 ``ipv6_route`` 按调用者当前网络 scope 输出。非初始空间的 " +"``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``unix`` 按真实 socket scope " +"枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。" +msgstr "" +"``/proc/net/dev``, ``route``, ``if_inet6`` and ``ipv6_route`` follow the caller's current " +"network scope. In other networks, ``arp``, ``udp``, ``tcp``, ``tcp6``, ``udp6`` and ``raw6`` " +"contain only headers. ``unix`` enumerates actual socket scopes. Noninitial ``dev`` currently " +"reports zero ``lo`` counters." -msgid "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 IPv6 与 transport 隔离完成后接通。" -msgstr "Userspace network namespace entry points through ``CLONE_NEWNET``, ``unshare()`` and ``setns()`` remain disabled. Clone requests using ``CLONE_NEWNET`` return ``EPERM`` or ``EINVAL`` according to authority. Unshare requests return ``EINVAL``. Userspace creation and switching will be connected after IPv6 and transport isolation is complete." +msgid "" +"用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " +"``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 transport 隔离完成后接通。" +msgstr "" +"Userspace network ``CLONE_NEWNET``, ``unshare()`` and ``setns()`` entry points remain closed." +" Clone requests with ``CLONE_NEWNET`` return ``EPERM`` or ``EINVAL`` according to authority, " +"and unshare returns ``EINVAL``. Creation and switching will open after transport isolation." msgid "netlink 端口与事件" msgstr "Netlink ports and events" @@ -458,4 +490,4 @@ msgid "每个网络空间的首个路由订阅者建立独立快照基线,IPv6 msgstr "The first route subscriber in each network namespace establishes an independent snapshot baseline. The baseline and subscription are published only after IPv6 address, IPv6 route and link snapshots have all been captured successfully. State changes likewise publish notifications and replace the baseline after a complete capture. Capture failures report overruns within the affected scope. Notifications and ``ENOBUFS`` loss reports are delivered by scope. Closing or unsubscribing the final subscriber in that namespace releases its baseline." msgid "路由多播组当前支持 ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR`` 和 ``RTMGRP_IPV6_ROUTE``。IPv4 地址和 IPv4 路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。" -msgstr "The supported route multicast groups are ``RTMGRP_LINK``, ``RTMGRP_IPV6_IFADDR`` and ``RTMGRP_IPV6_ROUTE``. IPv4 address and IPv4 route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``." \ No newline at end of file +msgstr "The supported route multicast groups are ``RTMGRP_LINK``, ``RTMGRP_IPV6_IFADDR`` and ``RTMGRP_IPV6_ROUTE``. IPv4 address and IPv4 route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``." diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po index a6fe2baa..95dd7e9c 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po @@ -82,17 +82,15 @@ msgstr "" "to local NIC addresses retain the destination interface identity." msgid "" -"IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 携带 ifindex。 逐链路状态通过动态分配管理,RA、RS、DAD、MLD " -"和发现定时分别推进。 不同链路可以使用相同 link-local 地址,socket 的作用域与设备绑定须一致。 现有 IPv6 " -"地址、路由和邻居等共享表仍有各自的资源容量,耗尽时返回错误。" +"IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 按网络空间隔离,并携带该空间的 ifindex。逐链路状态通过动态分配管理,RA、RS、DAD、MLD " +"和发现定时分别推进。不同链路可以使用相同 link-local 地址,socket 的作用域与设备绑定须一致。IPv6 表和队列的容量按网络空间分别计量,耗尽时返回错误。" msgstr "" -"IPv6 addresses, routes, neighbors, multicast memberships, pending packets, " -"reassembly, and PMTU carry ifindex. Per-link state is managed through " -"dynamic allocation, with RA, RS, DAD, MLD, and discovery timers advanced " -"separately. Different links can use the same link-local address, and socket " -"scope must agree with device binding. Existing shared tables for IPv6 " -"addresses, routes, neighbors, and other state still have their own resource " -"capacities and return errors on exhaustion." +"IPv6 addresses, routes, neighbors, multicast memberships, pending packets, reassembly and " +"PMTU are isolated by network namespace and carry that network's ifindex. Per-link state is " +"dynamically allocated, with independent RA, RS, DAD, MLD and discovery timing. Different " +"links may use the same link-local address, and socket scope must agree with device binding. " +"IPv6 tables and queues account capacity independently per network and return errors on " +"exhaustion." msgid "" "Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及 行政状态开关。接口配置修改需要 " diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po index e5872098..6d4dc0a2 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po @@ -57,8 +57,19 @@ msgstr "" msgid "配置与观测" msgstr "Configuration and Observation" -msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。``getifaddrs()`` 可以通过标准查询获取初始空间的 IPv6 地址。保留 Linux IPv6 地址、路由 ioctl,并根据 socket family 选择相应参数布局。" -msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` provides link, address and route queries and mutations within the network scope captured at socket creation. That scope is retained after FD transfer. Mutations require ``CAP_NET_ADMIN`` in the network scope’s user owner. IPv6 address and route dumps are empty in non-initial namespaces, and IPv6 mutations that pass authorization return ``EOPNOTSUPP``. ``getifaddrs()`` can obtain IPv6 addresses in the initial namespace through standard queries. Linux IPv6 address and route ioctls are retained, with argument layouts selected by socket family." +msgid "" +"``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD " +"后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 " +"IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。当前 INET socket 的 ioctl " +"仍使用初始网络,随 transport 隔离接通创建网络。" +msgstr "" +"``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 addresses and routes " +"in the network scope retained when the socket was created, including after FD transfer. " +"Changes require ``CAP_NET_ADMIN`` in that network owner's user namespace. ``getifaddrs()`` " +"obtains that scope's IPv6 addresses through standard queries. IPv6 address and route ioctls " +"use the selected network's state and owner authority, with argument layouts selected by " +"socket family. INET socket ioctls currently select the initial network and will retain the " +"creating network with transport isolation." msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" msgstr "Route multicast supports link, IPv6 address and IPv6 route groups. IPv4 address and route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``. Each network namespace maintains its own subscription snapshots, published after all captures succeed and released when its final subscriber closes or unsubscribes. Change notifications and overruns are delivered by network scope. Receive queue overflow reports ``ENOBUFS``, and callers should query again." @@ -72,11 +83,31 @@ msgstr "" "empty query result. Receivers must still iterate all messages in each datagram until the matching " "``NLMSG_DONE`` or an error arrives." -msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。快照复制出内部状态,跨等待仅保留副本。按调用者当前网络 scope 读取时,非初始空间的 IPv6 地址和路由表为空,``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text layouts. Address scope encoding differs from rtnetlink scope values. Snapshots copy internal state and retain only copies across waits. Reads use the caller’s current network scope. In non-initial namespaces, IPv6 address and route tables are empty, while ``tcp6``, ``udp6`` and ``raw6`` contain only headers." +msgid "" +"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope " +"的编码与 rtnetlink 的 scope 值不同。地址和路由按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。transport " +"表仍属于初始网络,非初始空间的 ``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。" +msgstr "" +"``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text " +"layouts. Address scope encodings differ from rtnetlink scope values. Addresses and routes " +"follow the caller's current network scope. Snapshots copy internal state and retain only " +"copies across waits. Transport tables currently belong to the initial network, and ``tcp6``, " +"``udp6`` and ``raw6`` in other networks contain only their headers." -msgid "接口、loopback 和显式 IPv4 路由已有独立网络空间状态,物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 IPv6 与 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。" -msgstr "Interfaces, loopback and explicit IPv4 routes already have independent network namespace state. Physical NIC registration and ingress remain in the initial namespace. Userspace network namespace entry points through ``CLONE_NEWNET``, ``unshare()`` and ``setns()`` will be connected after IPv6 and transport isolation is complete. See :doc:`../core-api/mount-namespaces` for internal lifetime and proc scope details." +msgid "" +"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" +" 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 " +"ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 transport " +"隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。" +msgstr "" +"Each network namespace owns its interfaces, loopback, IPv4 routes, and IPv6 addresses, " +"routes, neighbors, multicast state, pending packets, fragment reassembly, PMTU, fragment " +"identifiers and ICMP error rate limits. A new network's ``lo`` starts down without IPv6 " +"addresses. Its first up transition configures ``::1/128`` and a host route. Tables and queues" +" have independent capacities, and namespace destruction releases protocol resources. Physical" +" NIC registration and ingress remain in the initial network. Userspace network " +"``CLONE_NEWNET``, ``unshare()`` and ``setns()`` entry points will open after transport " +"isolation. See :doc:`../core-api/mount-namespaces` for internal lifetime and proc scope." msgid "范围与标准" msgstr "Scope and Standards" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 978a2280..bac8efff 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -383,17 +383,43 @@ msgstr "ネットワーク名前空間の寿命" msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク名前空間を作成します。``NULL`` は永続的な初期ネットワーク名前空間を表します。タスクは fork 時にこの空間を共有し、exec と ID の消去を通じて参照を保持し、wait による回収時またはスロットの再利用時に解放します。各 Unix および netlink ソケットは作成時のネットワーク名前空間を個別に保持し、最後の参照が閉じられると解放します。Unix のサーバー側接続はリスナーの名前空間を継承します。" -msgid "每个网络空间独立持有 loopback、接口列表和显式 IPv4 路由。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时分配 ``127.0.0.1/8``。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由和 owner 引用。" -msgstr "各ネットワーク名前空間は独立した loopback 状態、インターフェース一覧、明示的な IPv4 ルートを保持します。新しい空間の ``lo`` は初期状態で down かつアドレス未設定で、最初に up にすると ``127.0.0.1/8`` が設定されます。物理 NIC の登録と ingress は引き続き初期ネットワーク名前空間に属します。空間の最後の参照が解放されると、インターフェース一覧、明示的な IPv4 ルート、owner 参照も解放されます。" +msgid "" +"每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 " +"``127.0.0.1/8``、``::1/128`` 和 IPv6 host route。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 " +"IPv4 路由、IPv6 协议资源和 owner 引用。" +msgstr "" +"各ネットワーク空間は loopback、インターフェース一覧、明示的な IPv4 経路、IPv6 プロトコル状態を個別に保持します。新しい空間の ``lo`` は down " +"でアドレスを持たず、最初の up で ``127.0.0.1/8``、``::1/128``、IPv6 host route を設定します。物理 NIC 登録と ingress " +"は初期空間に属します。最後の空間参照を解放すると、インターフェース、明示的な IPv4 経路、IPv6 資源、owner 参照も解放します。" -msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口和 IPv4 路由查询、修改及 netlink 控制面使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。IPv6 和 transport 状态隔离仍待完成。" -msgstr "ネットワーク名前空間は Unix 抽象アドレス、proc 列挙、netlink ポートとメッセージ配信の適用範囲を定めます。インターフェースと IPv4 ルートの照会・変更、および netlink 制御面は、ソケット作成時に保持したネットワーク scope を使用します。変更にはその scope の user owner に対する ``CAP_NET_ADMIN`` が必要です。非初期空間の IPv6 アドレスとルートの dump は空で、認可を通過した IPv6 変更は ``EOPNOTSUPP`` を返します。IPv6 と transport の状態分離は今後の対応です。" +msgid "" +"网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket " +"创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 " +"地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用,允许 transport " +"回调释放最后一个外部引用。初始网络重新初始化保留其他活跃空间。transport registry 的网络隔离仍待完成。" +msgstr "" +"ネットワーク名前空間は Unix 抽象アドレス、proc 列挙、netlink ポート、メッセージ配送の範囲を定めます。netlink のインターフェース、IPv4/IPv6 " +"アドレス、経路の照会と変更は socket が保持する作成時のネットワークを使用し、変更には user owner の ``CAP_NET_ADMIN`` が必要です。IPv6 " +"アドレス、経路、近隣、多播、送信待ち、再構成、PMTU、断片番号、ICMP " +"エラーレート制限は空間ごとに分離します。保守処理は活性プロトコル状態を巡回し、処理中の空間を参照で保持するため、transport " +"コールバックは最後の外部参照を解放できます。初期ネットワークの再初期化は他の活性空間を保持します。transport registry のネットワーク分離は今後実装します。" -msgid "``/proc/net/dev`` 和 ``route`` 按调用者当前网络 scope 输出。非初始空间的 ``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``if_inet6`` 和 ``ipv6_route`` 为空,``unix`` 按真实 socket scope 枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。" -msgstr "``/proc/net/dev`` と ``route`` は呼び出し元の現在のネットワーク scope を使用します。非初期空間では ``arp``、``udp``、``tcp``、``tcp6``、``udp6``、``raw6`` は表ヘッダーのみを出力し、``if_inet6`` と ``ipv6_route`` は空になります。``unix`` は実際の socket scope に従って列挙します。非初期空間の ``dev`` における ``lo`` のカウンターは現在ゼロです。" +msgid "" +"``/proc/net/dev``、``route``、``if_inet6`` 和 ``ipv6_route`` 按调用者当前网络 scope 输出。非初始空间的 " +"``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``unix`` 按真实 socket scope " +"枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。" +msgstr "" +"``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route`` は呼び出し元の現在のネットワーク scope に従います。非初期空間の " +"``arp``、``udp``、``tcp``、``tcp6``、``udp6``、``raw6`` はヘッダーだけを出力し、``unix`` は実際の socket scope " +"を列挙します。非初期空間の ``dev`` の ``lo`` カウンターは現在ゼロです。" -msgid "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 IPv6 与 transport 隔离完成后接通。" -msgstr "``CLONE_NEWNET``、``unshare()``、``setns()`` によるユーザー空間のネットワーク名前空間操作は引き続き無効です。``CLONE_NEWNET`` を指定した clone は権限に応じて ``EPERM`` または ``EINVAL`` を返し、unshare は ``EINVAL`` を返します。ユーザー空間からの作成と切り替えは IPv6 と transport の分離完了後に接続します。" +msgid "" +"用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " +"``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 transport 隔离完成后接通。" +msgstr "" +"ユーザー空間のネットワーク ``CLONE_NEWNET``、``unshare()``、``setns()`` は現在無効です。``CLONE_NEWNET`` の clone " +"要求は権限に応じて ``EPERM`` または ``EINVAL``、unshare は ``EINVAL`` を返します。作成と切り替えは transport " +"分離の完了後に有効になります。" msgid "netlink 端口与事件" msgstr "netlink のポートとイベント" @@ -408,4 +434,4 @@ msgid "每个网络空间的首个路由订阅者建立独立快照基线,IPv6 msgstr "各ネットワーク名前空間の最初のルート購読者が独立したスナップショット基準を作成します。IPv6 アドレス、IPv6 ルート、リンクの全スナップショットの取得が成功してから、基準と購読を公開します。状態変更時も完全な取得後に通知を公開し、基準を置き換えます。取得失敗時の overrun は影響を受けた scope 内に報告します。通知と ``ENOBUFS`` による損失報告は scope ごとに配信します。その空間の最後の購読者が閉じるか購読を解除すると、基準を解放します。" msgid "路由多播组当前支持 ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR`` 和 ``RTMGRP_IPV6_ROUTE``。IPv4 地址和 IPv4 路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。" -msgstr "現在対応するルートマルチキャストグループは ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR``、``RTMGRP_IPV6_ROUTE`` です。IPv4 アドレスと IPv4 ルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。" \ No newline at end of file +msgstr "現在対応するルートマルチキャストグループは ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR``、``RTMGRP_IPV6_ROUTE`` です。IPv4 アドレスと IPv4 ルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po index bef6ac12..6fe9345d 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po @@ -71,14 +71,12 @@ msgstr "" "TCP、UDP は宛先インターフェースの識別情報を保持します。" msgid "" -"IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 携带 ifindex。 逐链路状态通过动态分配管理,RA、RS、DAD、MLD " -"和发现定时分别推进。 不同链路可以使用相同 link-local 地址,socket 的作用域与设备绑定须一致。 现有 IPv6 " -"地址、路由和邻居等共享表仍有各自的资源容量,耗尽时返回错误。" +"IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 按网络空间隔离,并携带该空间的 ifindex。逐链路状态通过动态分配管理,RA、RS、DAD、MLD " +"和发现定时分别推进。不同链路可以使用相同 link-local 地址,socket 的作用域与设备绑定须一致。IPv6 表和队列的容量按网络空间分别计量,耗尽时返回错误。" msgstr "" -"IPv6 のアドレス、経路、近隣、多播メンバー、送信待ちパケット、再構成、PMTU は ifindex " -"を持ちます。リンクごとの状態は動的割り当てで管理し、RA、RS、DAD、MLD、探索タイマーをそれぞれ進めます。異なるリンクでは同じ link-" -"local アドレスを使用でき、socket のスコープとデバイスのバインドは一致する必要があります。IPv6 " -"アドレス、経路、近隣などの既存の共有テーブルには引き続き個別のリソース上限があり、使い切るとエラーを返します。" +"IPv6 アドレス、経路、近隣、多播メンバー、送信待ちパケット、再構成、PMTU はネットワーク名前空間ごとに分離し、その空間の ifindex " +"を保持します。リンクごとの状態は動的に確保し、RA、RS、DAD、MLD、探索の時刻を個別に進めます。異なるリンクは同じ link-local アドレスを使用でき、socket の " +"scope とデバイス束縛は一致する必要があります。IPv6 テーブルとキューの容量はネットワークごとに計量し、枯渇時にはエラーを返します。" msgid "" "Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及 行政状态开关。接口配置修改需要 " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po index 0cbb8185..f976478e 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po @@ -52,8 +52,17 @@ msgstr "" msgid "配置与观测" msgstr "設定と観測" -msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。``getifaddrs()`` 可以通过标准查询获取初始空间的 IPv6 地址。保留 Linux IPv6 地址、路由 ioctl,并根据 socket family 选择相应参数布局。" -msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` は socket 作成時のネットワーク scope 内でリンク、アドレス、ルートの照会と変更を提供し、FD 転送後もその scope を保持します。変更にはネットワーク scope の user owner に対する ``CAP_NET_ADMIN`` が必要です。非初期空間の IPv6 アドレスとルートの dump は空で、認可を通過した IPv6 変更は ``EOPNOTSUPP`` を返します。``getifaddrs()`` は標準の照会を通じて初期空間の IPv6 アドレスを取得できます。Linux の IPv6 アドレスとルートの ioctl を維持し、socket family に応じた引数レイアウトを選択します。" +msgid "" +"``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD " +"后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 " +"IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。当前 INET socket 的 ioctl " +"仍使用初始网络,随 transport 隔离接通创建网络。" +msgstr "" +"``AF_NETLINK`` / ``NETLINK_ROUTE`` は socket 作成時に保持したネットワーク scope のリンク、IPv4/IPv6 " +"アドレス、経路を照会・変更し、FD 転送後も同じ scope を使用します。変更にはネットワーク owner のユーザー名前空間の ``CAP_NET_ADMIN`` " +"が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 アドレスを取得します。IPv6 アドレス・経路 ioctl は選択したネットワークの状態と owner " +"権限を使用し、socket family に応じた引数配置を選びます。現在の INET socket ioctl は初期ネットワークを選択し、transport " +"分離とともに作成時のネットワークを使用するようになります。" msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" msgstr "ルートマルチキャストはリンク、IPv6 アドレス、IPv6 ルートのグループに対応します。IPv4 アドレスとルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。各ネットワーク名前空間は独立した購読スナップショットを保持し、すべての取得が成功してから公開します。最後の購読者が閉じるか購読を解除すると解放します。変更通知と overrun はネットワーク scope ごとに配信し、受信キューのオーバーフローは ``ENOBUFS`` を報告するため、呼び出し元は再照会してください。" @@ -65,11 +74,27 @@ msgstr "" "複数部分からなる問い合わせでは、データと終端の ``NLMSG_DONE`` を別々のデータグラムとして送信します。終端マーカーは要求のシーケンス番号と受信ポート ID " "を保持し、結果が空でも送信します。受信側は引き続き各データグラム内の全メッセージを走査し、対応する番号の ``NLMSG_DONE`` またはエラーを待つ必要があります。" -msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。快照复制出内部状态,跨等待仅保留副本。按调用者当前网络 scope 读取时,非初始空间的 IPv6 地址和路由表为空,``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキストレイアウトを使用します。アドレス scope の符号化は rtnetlink の scope 値と異なります。スナップショットは内部状態をコピーし、待機をまたいで保持するのはコピーのみです。読み取りには呼び出し元の現在のネットワーク scope を使用します。非初期空間では IPv6 アドレス表とルート表は空で、``tcp6``、``udp6``、``raw6`` は表ヘッダーのみを出力します。" +msgid "" +"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope " +"的编码与 rtnetlink 的 scope 值不同。地址和路由按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。transport " +"表仍属于初始网络,非初始空间的 ``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。" +msgstr "" +"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト配置を使用し、アドレス " +"scope の符号化は rtnetlink の scope 値と異なります。アドレスと経路は呼び出し元の現在のネットワーク scope " +"に従います。スナップショットは内部状態を複写し、待機をまたいで複写だけを保持します。transport テーブルは現在初期ネットワークに属し、他の空間の " +"``tcp6``、``udp6``、``raw6`` はヘッダーだけを出力します。" -msgid "接口、loopback 和显式 IPv4 路由已有独立网络空间状态,物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 IPv6 与 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。" -msgstr "インターフェース、loopback、明示的な IPv4 ルートは独立したネットワーク名前空間の状態を持ちます。物理 NIC の登録と ingress は引き続き初期空間に属します。``CLONE_NEWNET``、``unshare()``、``setns()`` によるユーザー空間のネットワーク名前空間操作は IPv6 と transport の分離完了後に接続します。内部のライフサイクルと proc の適用範囲は :doc:`../core-api/mount-namespaces` を参照してください。" +msgid "" +"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" +" 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 " +"ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 transport " +"隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。" +msgstr "" +"各ネットワーク名前空間はインターフェース、loopback、IPv4 経路と、IPv6 のアドレス、経路、近隣、多播、送信待ちパケット、断片再構成、PMTU、断片番号、ICMP " +"エラーのレート制限を個別に保持します。新しい空間の ``lo`` は down で IPv6 アドレスを持たず、最初の up で ``::1/128`` と host route " +"を設定します。テーブルとキューの容量は個別に計量し、空間破棄時にプロトコル資源を解放します。物理 NIC 登録と ingress は初期空間に属します。ユーザー空間のネットワーク " +"``CLONE_NEWNET``、``unshare()``、``setns()`` は transport 分離の完了後に有効になります。内部ライフサイクルと proc の範囲は " +":doc:`../core-api/mount-namespaces` を参照してください。" msgid "范围与标准" msgstr "範囲と標準" diff --git a/Documentation/userspace-api/ipv6.rst b/Documentation/userspace-api/ipv6.rst index f9ada916..b3b48b46 100644 --- a/Documentation/userspace-api/ipv6.rst +++ b/Documentation/userspace-api/ipv6.rst @@ -32,7 +32,7 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 配置与观测 ========== -``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。非初始空间的 IPv6 地址和路由 dump 为空,通过权限检查的 IPv6 修改返回 ``EOPNOTSUPP``。``getifaddrs()`` 可以通过标准查询获取初始空间的 IPv6 地址。保留 Linux IPv6 地址、路由 ioctl,并根据 socket family 选择相应参数布局。 +``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。当前 INET socket 的 ioctl 仍使用初始网络,随 transport 隔离接通创建网络。 路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。 @@ -40,9 +40,9 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。 -``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。快照复制出内部状态,跨等待仅保留副本。按调用者当前网络 scope 读取时,非初始空间的 IPv6 地址和路由表为空,``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。 +``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址和路由按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。transport 表仍属于初始网络,非初始空间的 ``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。 -接口、loopback 和显式 IPv4 路由已有独立网络空间状态,物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 IPv6 与 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。 +每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。 范围与标准 ========== diff --git a/include/reliefnt/net_interface.h b/include/reliefnt/net_interface.h index 5c6d4520..2717455b 100644 --- a/include/reliefnt/net_interface.h +++ b/include/reliefnt/net_interface.h @@ -83,8 +83,10 @@ bool net_interface_is_up(struct net_namespace *ns, uint32_t index); /** @brief Set administrative state after the caller authorizes the operation. * @param ns Borrowed network, NULL for the initial network. * @param index Interface index. @param up Requested administrative state. - * @return Zero or -ENODEV. First enabling an unconfigured loopback assigns - * 127.0.0.1/8. The caller publishes notifications after dependent state changes. + * @return Zero or a negative interface/protocol allocation or capacity error. + * First enabling an unconfigured loopback assigns 127.0.0.1/8 and ::1/128. + * IPv6 setup failure preserves administrative state and loopback tables. + * The caller publishes notifications after dependent state changes. */ int net_interface_set_up(struct net_namespace *ns, uint32_t index, bool up); /** @brief Resolve a local IPv4 address within one network. diff --git a/include/reliefnt/net_ipv6.h b/include/reliefnt/net_ipv6.h index 3e1005c6..bffd8e4c 100644 --- a/include/reliefnt/net_ipv6.h +++ b/include/reliefnt/net_ipv6.h @@ -4,6 +4,19 @@ #include #include struct text_stream; +struct net_namespace; +struct net_ipv6_state; + +/** @brief Allocate empty IPv6 tables and publish their namespace maintenance link. + * @param ns Borrowed, unpublished owning network under execution ownership. + * @return Owned state, or NULL on allocation failure. Retains no namespace reference. + */ +struct net_ipv6_state *net_ipv6_state_create(struct net_namespace *ns); + +/** @brief Unlink and release all IPv6 state during final namespace destruction. + * @param state Owned noninitial state, with no servicing poll reference remaining. + */ +void net_ipv6_state_destroy(struct net_ipv6_state *state); #define NET_IPV6_IF_LOOPBACK 1u #define NET_IPV6_IF_ETHERNET 2u /* Legacy default when no NIC is registered. */ #define NET_IPV6_ADDR_TENTATIVE 0x40u @@ -45,22 +58,29 @@ struct net_ipv6_path { struct in6_addr source, destination, next_hop; uint32_t ifindex, mtu; }; -/** @brief Initialize loopback and Ethernet IPv6 host state without blocking. */ +/** @brief Reset initial-network IPv6 state and configure its active interfaces. + * Preserves all other network namespaces and requires network execution ownership. + */ void net_ipv6_init(void); /** @brief Retire state of the first live NIC, or the legacy default when none exists. */ void net_ipv6_detached(void); /** @brief Retire state owned by the specified NIC, including after registry removal. + * @param ns Borrowed network, NULL for the permanent initial network. * @param ifindex Stable interface index. */ -void net_ipv6_detached_on(uint32_t ifindex); +void net_ipv6_detached_on(struct net_namespace *ns, uint32_t ifindex); /** @brief Apply Ethernet state to the first live NIC or the legacy default. * @param up New administrative state. */ void net_ipv6_link_changed(bool up); -/** @brief Apply administrative state to one NIC under network execution ownership. +/** @brief Apply administrative state to one network's loopback or Ethernet link. + * @param ns Borrowed network, NULL for the permanent initial network. * @param ifindex Stable interface index. @param up New administrative state. - * @return Zero, -ENOMEM when link state cannot be allocated, or -ENODEV for an invalid interface. + * @return Zero, -ENOMEM for link allocation, -ENOBUFS for full loopback tables, + * or -ENODEV for an invalid interface. Loopback capacity failure preserves both tables. * Before initialization, state is applied later by the initialization scan. */ -int net_ipv6_link_changed_on(uint32_t ifindex,bool up); -/** @brief Advance bounded DAD, router/neighbor discovery and queued loopback work. */ +int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t ifindex,bool up); +/** @brief Advance protocol timers and deferred loopback work in every live network. + * Pins the servicing network across transport callbacks under execution ownership. + */ void net_ipv6_poll(void); /** @brief Indicate receive/timer work requiring the task-context network pump. * @return True when bounded maintenance should remain enabled. */ @@ -69,23 +89,26 @@ bool net_ipv6_maintenance_pending(void); * @param frame Borrowed complete Ethernet frame. @param length Available bytes. */ void net_ipv6_input(const uint8_t *frame,uint32_t length); /** @brief Validate and dispatch a frame received on the specified NIC. + * @param ns Borrowed network, NULL for the permanent initial network. * @param ifindex Stable receiving interface index. @param frame Borrowed Ethernet frame. * @param length Available bytes. */ -void net_ipv6_input_on(uint32_t ifindex,const uint8_t *frame,uint32_t length); +void net_ipv6_input_on(struct net_namespace *ns, uint32_t ifindex,const uint8_t *frame,uint32_t length); /** @brief Select a route and usable source without borrowing mutable state. + * @param ns Borrowed network, NULL for the permanent initial network. * @param destination Required destination. @param scope Explicit interface or zero. * @param bound Optional local source, zero-address means automatic. @param out_path Output. * @return Zero or negative Linux errno, including ENETUNREACH/EADDRNOTAVAIL. */ -int net_ipv6_route(const struct in6_addr *destination,uint32_t scope, +int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination,uint32_t scope, const struct in6_addr *bound,struct net_ipv6_path *out_path); /** @brief Send or retain a checked transport message for resolved IPv6 output. + * @param ns Borrowed network, NULL for the permanent initial network. * @param path Selected route copy. @param protocol Next-header protocol. * @param data Borrowed transport message including header and checksum. @param length Bytes. * @param hops Hop limit, -1 selects default. @param flowinfo Network-order flow information. * @param dont_fragment Reject oversize payload instead of source fragmentation. * @param multicast_loop Also deliver locally to joined multicast groups when true. * @return Accepted payload bytes or negative Linux errno. Loopback is deferred to poll. */ -int net_ipv6_output(const struct net_ipv6_path *path,uint8_t protocol, +int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,uint8_t protocol, const void *data,uint32_t length,int hops,uint32_t flowinfo, bool dont_fragment,bool multicast_loop); /** @brief Compute an IPv6 upper-layer pseudo-header checksum. @@ -95,49 +118,59 @@ int net_ipv6_output(const struct net_ipv6_path *path,uint8_t protocol, uint16_t net_ipv6_checksum(const struct in6_addr *source,const struct in6_addr *destination, uint8_t protocol,const void *data,uint32_t length); /** @brief Copy address entries and return the total live count. + * @param ns Borrowed network, NULL for the permanent initial network. * @param out Optional output. @param capacity Entry capacity. @return Total count. */ -uint32_t net_ipv6_addresses(struct net_ipv6_address *out,uint32_t capacity); +uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out,uint32_t capacity); /** @brief Copy routes and return their total live count. + * @param ns Borrowed network, NULL for the permanent initial network. * @param out Optional output. @param capacity Entry capacity. @return Total count. */ -uint32_t net_ipv6_routes(struct net_ipv6_route *out,uint32_t capacity); +uint32_t net_ipv6_routes(struct net_namespace *ns, struct net_ipv6_route *out,uint32_t capacity); /** @brief Copy neighbor entries and return their total live count. + * @param ns Borrowed network, NULL for the permanent initial network. * @param out Optional output. @param capacity Entry capacity. @return Total count. */ -uint32_t net_ipv6_neighbors(struct net_ipv6_neighbor *out,uint32_t capacity); +uint32_t net_ipv6_neighbors(struct net_namespace *ns, struct net_ipv6_neighbor *out,uint32_t capacity); /** @brief Add/update or remove an address with DAD and lifetime handling. + * @param ns Borrowed network, NULL for the permanent initial network. * @param address Checked native configuration. @param remove Remove when true. * @return Zero or negative Linux errno; authorization belongs to caller. */ -int net_ipv6_address_update(const struct net_ipv6_address *address,bool remove); +int net_ipv6_address_update(struct net_namespace *ns, const struct net_ipv6_address *address,bool remove); /** @brief Add/update or remove a route. + * @param ns Borrowed network, NULL for the permanent initial network. * @param route Checked native route. @param remove Remove when true. * @return Zero or negative Linux errno; authorization belongs to caller. */ -int net_ipv6_route_update(const struct net_ipv6_route *route,bool remove); +int net_ipv6_route_update(struct net_namespace *ns, const struct net_ipv6_route *route,bool remove); /** @brief Retain/release multicast membership and update MLD host state. + * @param ns Borrowed network, NULL for the permanent initial network. * @param address Multicast group. @param ifindex Selected interface. @param delta +1/-1. * @return Zero or negative Linux errno. */ -int net_ipv6_multicast_change(const struct in6_addr *address,uint32_t ifindex,int delta); +int net_ipv6_multicast_change(struct net_namespace *ns, const struct in6_addr *address,uint32_t ifindex,int delta); /** @brief Apply IPv6 address/route socket ioctls using checked user memory. + * @param ns Borrowed network, NULL for the permanent initial network. * @param request Linux ioctl. @param address User argument. @return Zero/negative errno. */ -int net_ipv6_interface_ioctl(uint32_t request,uint64_t address); +int net_ipv6_interface_ioctl(struct net_namespace *ns, uint32_t request,uint64_t address); /* Transport callbacks consume only validated, reassembled packets under execution ownership. */ /** @brief Deliver one checksummed UDP payload to matching sockets. + * @param ns Borrowed network, NULL for the permanent initial network. * @param source Peer. @param destination Local. @param source_port Peer host-order port. * @param destination_port Local host-order port. @param data Borrowed payload. * @param length Payload bytes. @param ifindex Interface. @param hops Received hop limit. * @return True when delivered; false permits ICMPv6 port-unreachable. */ -bool net_udp6_input(const struct in6_addr *source,const struct in6_addr *destination, +bool net_udp6_input(struct net_namespace *ns, const struct in6_addr *source,const struct in6_addr *destination, uint16_t source_port,uint16_t destination_port,const void *data, uint32_t length,uint32_t ifindex,uint8_t hops); /** @brief Deliver a checked TCP segment to the shared TCP engine. + * @param ns Borrowed network, NULL for the permanent initial network. * @param source Peer. @param destination Local. @param data TCP bytes. * @param length TCP length. @param ifindex Receiving interface. */ -void net_tcp6_input(const struct in6_addr *source,const struct in6_addr *destination, +void net_tcp6_input(struct net_namespace *ns, const struct in6_addr *source,const struct in6_addr *destination, const void *data,uint32_t length,uint32_t ifindex); /** @brief Deliver an IPv6 upper-layer message to matching raw sockets. + * @param ns Borrowed network, NULL for the permanent initial network. * @param source Peer. @param destination Local. @param protocol Next header. * @param data Borrowed bytes. @param length Length. @param ifindex Interface. * @param hops Received hop limit. */ -void net_raw6_input(const struct in6_addr *source,const struct in6_addr *destination, +void net_raw6_input(struct net_namespace *ns, const struct in6_addr *source,const struct in6_addr *destination, uint8_t protocol,const void *data,uint32_t length, uint32_t ifindex,uint8_t hops); /** @brief Associate a validated ICMPv6 error quote with transport state. @@ -145,13 +178,16 @@ void net_raw6_input(const struct in6_addr *source,const struct in6_addr *destina * @param error Positive Linux errno. @param mtu Reported MTU or zero. */ void net_ipv6_socket_error(const uint8_t *packet,uint32_t length,int error,uint32_t mtu); /** @brief Deliver an asynchronous error for a specific receiving or transmitting interface. + * @param ns Borrowed network, NULL for the permanent initial network. * @param ifindex Interface index, zero to skip interface filtering. @param packet Quoted packet. * @param length Available quote bytes. @param error Positive Linux errno. @param mtu MTU or zero. */ -void net_ipv6_socket_error_on(uint32_t ifindex,const uint8_t *packet,uint32_t length,int error,uint32_t mtu); +void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex,const uint8_t *packet,uint32_t length,int error,uint32_t mtu); /** @brief Render tcp6/udp6/raw6 socket state without driving I/O. * @param stream Slice output. @param leaf Requested standard proc basename. */ void net_ipv6_transport_proc_emit(struct text_stream *stream,const char *leaf); -/** @brief Notify initial-network route subscribers of protocol state changes. - * Runs under execution ownership and retains the previous baseline on OOM. */ -void netlink_ipv6_changed(void); +/** @brief Notify the selected network's route subscribers of protocol state changes. + * Runs under execution ownership and retains the previous baseline on OOM. + * @param ns Borrowed network, NULL for the permanent initial network. + */ +void netlink_ipv6_changed(struct net_namespace *ns); #endif diff --git a/include/reliefnt/net_namespace.h b/include/reliefnt/net_namespace.h index ed630195..0b50da0c 100644 --- a/include/reliefnt/net_namespace.h +++ b/include/reliefnt/net_namespace.h @@ -6,6 +6,7 @@ #include struct user_namespace; +struct net_ipv6_state; /** @brief Reference-counted network identity with an immutable user owner. * NULL denotes the permanent initial network namespace. Tasks and sockets own @@ -17,6 +18,7 @@ struct net_namespace { struct net_interface *interfaces; struct net_interface loopback; struct net_ipv4_route_node *ipv4_routes; + struct net_ipv6_state *ipv6; }; /** @brief Allocate an empty network identity and retain its user owner. @@ -24,7 +26,7 @@ struct net_namespace { * @param out Required output, cleared on failure, owning one reference on success. * @return Zero, -EINVAL or -ENOMEM. Caller supplies execution ownership and * authorization. The namespace starts with its own down, unconfigured loopback - * and empty IPv4 routing table. Hardware interfaces stay in the initial network. + * and empty IPv4 and IPv6 protocol tables. Hardware interfaces stay in the initial network. */ int net_namespace_create(struct user_namespace *owner, struct net_namespace **out); @@ -34,7 +36,7 @@ int net_namespace_create(struct user_namespace *owner, struct net_namespace **ou */ struct net_namespace *net_namespace_get(struct net_namespace *ns); -/** @brief Release a network identity, owned interfaces, IPv4 routes and user owner. +/** @brief Release a network identity, protocol state, interfaces and user owner. * @param ns Owned reference, nullable for the permanent initial namespace. * Does not acquire scheduler or network locks or access task state. */ diff --git a/kernel/syscall/device/legacy_ioctl.c b/kernel/syscall/device/legacy_ioctl.c index 5df629e3..6b6a2c7a 100644 --- a/kernel/syscall/device/legacy_ioctl.c +++ b/kernel/syscall/device/legacy_ioctl.c @@ -350,7 +350,7 @@ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t return task_socket_ioctl(file, a1, a2); if (file && (file->flags & TASK_FILE_FLAG_SOCKET_INET) && task_inet_family(file) == AF_INET6 && (a1 == SIOCSIFADDR || a1 == SIOCDIFADDR || a1 == SIOCADDRT || a1 == SIOCDELRT)) - return net_ipv6_interface_ioctl((uint32_t)a1, a2); + return net_ipv6_interface_ioctl(NULL, (uint32_t)a1, a2); if (file && (file->flags & TASK_FILE_FLAG_SOCKET_INET)) return task_net_control(file, (uint32_t)a1, a2); if (file && (file->node.flags & STORAGE_NODE_FLAG_DEV_NODE) && diff --git a/net/core.c b/net/core.c index 0cd3a931..c6bc08fd 100644 --- a/net/core.c +++ b/net/core.c @@ -89,8 +89,8 @@ void net_device_attached(uint32_t ifindex) console_error("[reliefnt] network interface %u registration failed: %d\n", ifindex, result); return; } - net_ipv6_link_changed_on(ifindex, net_interface_is_up(NULL, ifindex)); - netlink_ipv6_changed(); + net_ipv6_link_changed_on(NULL, ifindex, net_interface_is_up(NULL, ifindex)); + netlink_ipv6_changed(NULL); } /** @brief Retire sockets and discovery state belonging to one removed device. @@ -106,10 +106,10 @@ void net_device_detached(uint32_t ifindex) } net_udp_device_detached(ifindex); net_packet_device_detached(ifindex); - net_ipv6_detached_on(ifindex); + net_ipv6_detached_on(NULL, ifindex); net_arp_cache_clear_on(ifindex); net_interface_remove(ifindex); - netlink_ipv6_changed(); + netlink_ipv6_changed(NULL); } /** @brief Report whether a failed device-state allocation needs another pass. @@ -127,8 +127,8 @@ void net_device_retry_registration(void) for (uint32_t index = netdev_next(0); index; index = netdev_next(index)) { if (net_interface_get(NULL, index)) continue; if (!net_interface_register(index)) { - net_ipv6_link_changed_on(index, net_interface_is_up(NULL, index)); - netlink_ipv6_changed(); + net_ipv6_link_changed_on(NULL, index, net_interface_is_up(NULL, index)); + netlink_ipv6_changed(NULL); } return; } diff --git a/net/input.c b/net/input.c index 1dae5769..2edc9108 100644 --- a/net/input.c +++ b/net/input.c @@ -47,7 +47,7 @@ static void net_process_frame(uint32_t ifindex, const uint8_t *frame, uint32_t l } else if (type == ETH_TYPE_IPV4) { net_handle_ipv4_on(ifindex, frame, len, ping_wait, udp_wait, tcp_wait); } else if (type == 0x86dd) { - net_ipv6_input_on(ifindex, frame, len); + net_ipv6_input_on(NULL, ifindex, frame, len); } } diff --git a/net/interface/config.c b/net/interface/config.c index a47fad4a..3505fd53 100644 --- a/net/interface/config.c +++ b/net/interface/config.c @@ -1,6 +1,7 @@ #include #include #include +#include #include #include "../internal.h" @@ -450,19 +451,20 @@ void net_device_info(uint32_t *flags, uint64_t *mac_value, uint32_t *local_ip) } /** @brief Apply Linux IPv6 address and route ioctls for an IPv6 socket. + * @param ns Borrowed socket network, NULL for the initial network. * @param request Supported address or route mutation command. * @param address User pointer to a native in6_ifreq or in6_rtmsg. * @return Zero or negative errno. The current task must hold CAP_NET_ADMIN; * imported bytes are owned locally and no user reference crosses a wait. - * The shared network namespace is owned by the initial user namespace. + * Authority is checked against the creating network's user namespace. */ -int net_ipv6_interface_ioctl(uint32_t request, uint64_t address) +int net_ipv6_interface_ioctl(struct net_namespace *ns, uint32_t request, uint64_t address) { struct task *task = sched_current_task(); if (request != SIOCSIFADDR && request != SIOCDIFADDR && request != SIOCADDRT && request != SIOCDELRT) - return net_interface_ioctl(NULL, request, address); - if (!task || !(task_initial_capabilities(task) & (1ULL << CAP_NET_ADMIN))) return -LINUX_EPERM; + return net_interface_ioctl(ns, request, address); + if (!task || !task_ns_capable(task, ns ? ns->user_ns : NULL, CAP_NET_ADMIN)) return -LINUX_EPERM; if (request == SIOCSIFADDR || request == SIOCDIFADDR) { struct in6_ifreq input; int rc = socket_user_import(task, address, &input, sizeof(input)); @@ -477,7 +479,7 @@ int net_ipv6_interface_ioctl(uint32_t request, uint64_t address) else if (!__builtin_memcmp(entry.address.s6_addr, (const uint8_t[16]){0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},16)) entry.scope = 254; - return net_ipv6_address_update(&entry, request == SIOCDIFADDR); + return net_ipv6_address_update(ns, &entry, request == SIOCDIFADDR); } struct in6_rtmsg input; int rc = socket_user_import(task, address, &input, sizeof(input)); @@ -492,5 +494,5 @@ int net_ipv6_interface_ioctl(uint32_t request, uint64_t address) struct net_ipv6_route route = {.destination = input.rtmsg_dst, .gateway = input.rtmsg_gateway, .prefix_length = input.rtmsg_dst_len, .ifindex = (uint32_t)input.rtmsg_ifindex, .metric = input.rtmsg_metric, .flags = input.rtmsg_flags, .valid_until = UINT64_MAX}; - return net_ipv6_route_update(&route, request == SIOCDELRT); + return net_ipv6_route_update(ns, &route, request == SIOCDELRT); } diff --git a/net/interface/ioctl.c b/net/interface/ioctl.c index 81be86b6..b7c92d96 100644 --- a/net/interface/ioctl.c +++ b/net/interface/ioctl.c @@ -219,7 +219,6 @@ int net_interface_ioctl(struct net_namespace *ns, uint32_t request, uint64_t add if (net_interface_is_up(ns, index) != up) { rc = net_interface_set_up(ns, index, up); if (rc) return rc; - if (!ns && !loop) net_ipv6_link_changed_on(index, up); netlink_network_changed(ns); } break; diff --git a/net/interface/state.c b/net/interface/state.c index 60f1377c..95db581b 100644 --- a/net/interface/state.c +++ b/net/interface/state.c @@ -3,6 +3,7 @@ #include #include #include +#include #include /* All state is serialized by the existing network execution owner. */ @@ -115,6 +116,8 @@ int net_interface_set_up(struct net_namespace *ns, uint32_t index, bool up) { struct net_interface *iface = net_interface_get(ns, index); if (!iface) return -LINUX_ENODEV; + int rc = net_ipv6_link_changed_on(ns, index, up); + if (rc) return rc; if (index == NET_IF_LOOPBACK && up && !iface->config.local_ip) { iface->config.local_ip = 0x7f000001u; iface->config.subnet_mask = 0xff000000u; diff --git a/net/ipv6/Kbuild b/net/ipv6/Kbuild index 159ace7a..4ee533bf 100644 --- a/net/ipv6/Kbuild +++ b/net/ipv6/Kbuild @@ -1,2 +1,2 @@ # IPv6 host protocol and bounded state machines. -obj-y += core.o +obj-y += core.o state.o diff --git a/net/ipv6/core.c b/net/ipv6/core.c index 97828e51..be522436 100644 --- a/net/ipv6/core.c +++ b/net/ipv6/core.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: Apache-2.0 */ /** @file IPv6 host, neighbor discovery, bounded reassembly and MLD. */ #include "../internal.h" +#include "internal.h" #include #include #include @@ -10,13 +11,6 @@ #define IPV6_ETHERTYPE 0x86ddu #define IPV6_LINK_MTU 1500u #define IPV6_MIN_MTU 1280u -#define IPV6_ADDR_MAX 16u -#define IPV6_ROUTE_MAX 24u -#define IPV6_NEIGH_MAX 16u -#define IPV6_GROUP_MAX 32u -#define IPV6_PENDING_MAX 8u -#define IPV6_REASM_MAX 4u -#define IPV6_PMTU_MAX 8u #define IPV6_HEADER_LIMIT 2048u #define IPV6_HEADER_COUNT 8u #define IPV6_REASM_TIMEOUT 60000u @@ -31,96 +25,37 @@ #define IPV6_SCOPE_LINK 253u #define IPV6_SCOPE_HOST 254u -struct ipv6_address_slot { - struct net_ipv6_address value; - uint64_t dad_at; - bool used, autonomous, dad_sent, dad_wait_mld; -}; -struct ipv6_route_slot { - struct net_ipv6_route value; - uint64_t address_until, ra_until; - bool used, automatic; -}; -struct ipv6_neighbor_slot { - struct net_ipv6_neighbor value; - uint64_t deadline; - uint8_t probes; - bool used; -}; -struct ipv6_group_slot { - struct in6_addr address; - uint32_t ifindex, refs; - uint64_t report_at, query_at; - uint8_t reports; - bool used, query_pending; -}; -struct ipv6_pending { - struct net_ipv6_path path; - uint8_t *data; - uint32_t length, flowinfo; - int hops; - uint8_t protocol; - bool used, loopback, dont_fragment; -}; -struct ipv6_reassembly { - struct in6_addr source, destination; - uint8_t *data, *bitmap, *prefix; - uint32_t identification, ifindex, covered, total, highwater, prefix_len, prev_next; - uint64_t deadline; - uint8_t next; - bool used, poisoned, have_first, have_last; -}; -struct ipv6_pmtu { - struct in6_addr destination; - uint64_t deadline; - uint32_t ifindex, mtu; - bool used; -}; - -static struct ipv6_address_slot ipv6_addrs[IPV6_ADDR_MAX]; -static struct ipv6_route_slot ipv6_routes[IPV6_ROUTE_MAX]; -static struct ipv6_neighbor_slot ipv6_neighbors[IPV6_NEIGH_MAX]; -static struct ipv6_group_slot ipv6_groups[IPV6_GROUP_MAX]; -static struct ipv6_pending ipv6_pending[IPV6_PENDING_MAX]; -static struct ipv6_reassembly ipv6_reassembly[IPV6_REASM_MAX]; -static struct ipv6_pmtu ipv6_pmtu[IPV6_PMTU_MAX]; -/* Indexes are stable identifiers, not dense array positions. */ -struct ipv6_link { - struct ipv6_link *next; - uint32_t ifindex, mtu, rng_state, base_reachable_ms, retrans_ms; - uint64_t reachable_ms, reachable_refresh, rs_at, mld_v1_until; - uint8_t rs_sent; - bool up; -}; -static struct ipv6_link *ipv6_links; -static bool ipv6_initialized; -/* Fragment IDs must not collide when the same endpoints use different NICs. */ -static uint32_t ipv6_frag_id; -static uint64_t ipv6_error_at; -static uint8_t ipv6_error_count; static const struct in6_addr ipv6_zero = {0}; static const struct in6_addr ipv6_loop = {.s6_addr={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; static const struct in6_addr ipv6_all_nodes = {.s6_addr={0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; static const struct in6_addr ipv6_all_routers = {.s6_addr={0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2}}; static const struct in6_addr ipv6_mld_routers = {.s6_addr={0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0x16}}; -/** @brief Look up link state by stable interface index, optionally allocating it. */ -static struct ipv6_link *ipv6_link(uint32_t ifindex,bool create) +/** @brief Look up link state by stable interface index, optionally allocating it. + * @param state Borrowed protocol owner under network execution ownership. + * @param ifindex Stable interface index within this network. + * @param create Allocate and link an absent entry when true. + * @return Borrowed link entry, or NULL when absent or allocation fails. + */ +static struct ipv6_link *ipv6_link(struct net_ipv6_state *state, uint32_t ifindex,bool create) { - for(struct ipv6_link *link=ipv6_links;link;link=link->next) + for(struct ipv6_link *link=state->links;link;link=link->next) if(link->ifindex==ifindex)return link; if(!create)return 0; struct ipv6_link *link=kernel_malloc(sizeof(*link));if(!link)return 0; net_memzero(link,sizeof(*link));link->ifindex=ifindex; link->mtu=IPV6_LINK_MTU;link->base_reachable_ms=30000;link->retrans_ms=1000; - link->next=ipv6_links;ipv6_links=link; + link->next=state->links;state->links=link; return link; } -/** @brief Select the historical default NIC, including in legacy white-box fixtures. */ -static uint32_t ipv6_default_interface(void) +/** @brief Select the historical default NIC, including in legacy white-box fixtures. + * @param state Borrowed protocol owner under network execution ownership. + * @return First non-loopback index, the initial-network fallback, or zero. + */ +static uint32_t ipv6_default_interface(struct net_ipv6_state *state) { - uint32_t ifindex=netdev_next(0); - return ifindex?ifindex:NET_IPV6_IF_ETHERNET; + uint32_t ifindex=net_interface_next(state->net_ns, NET_IPV6_IF_LOOPBACK); + return ifindex?ifindex:(state->net_ns?0:NET_IPV6_IF_ETHERNET); } /** @brief Obtain per-interface discovery jitter without requiring hardware RNG. */ static uint32_t ipv6_jitter_word(struct ipv6_link *link) @@ -202,29 +137,32 @@ static void ipv6_solicited(struct in6_addr *out,const struct in6_addr *a) *out=ipv6_zero;out->s6_addr[0]=0xff;out->s6_addr[1]=2;out->s6_addr[11]=1;out->s6_addr[12]=0xff; net_memcpy(out->s6_addr+13,a->s6_addr+13,3); } -/** @brief Find a configured address. @param a Address. @param ifindex Interface or zero. +/** @brief Find a configured address. @param state Borrowed protocol owner under network execution ownership. + * @param a Address. @param ifindex Interface or zero. * @return Matching private entry or NULL. */ -static struct ipv6_address_slot *ipv6_find_address(const struct in6_addr *a,uint32_t ifindex) +static struct ipv6_address_slot *ipv6_find_address(struct net_ipv6_state *state, const struct in6_addr *a,uint32_t ifindex) { - for(uint32_t i=0;iaddresses[i].used && + (!ifindex || state->addresses[i].value.ifindex==ifindex) && ipv6_equal(&state->addresses[i].value.address,a))return &state->addresses[i]; return 0; } -/** @brief Find a multicast membership. @param a Group. @param ifindex Interface. +/** @brief Find a multicast membership. @param state Borrowed protocol owner under network execution ownership. + * @param a Group. @param ifindex Interface. * @return Matching private entry or NULL. */ -static struct ipv6_group_slot *ipv6_find_group(const struct in6_addr *a,uint32_t ifindex) +static struct ipv6_group_slot *ipv6_find_group(struct net_ipv6_state *state, const struct in6_addr *a,uint32_t ifindex) { - for(uint32_t i=0;igroups[i].used && state->groups[i].ifindex==ifindex && + ipv6_equal(&state->groups[i].address,a))return &state->groups[i]; return 0; } /** @brief Check whether a destination is local on the receiving interface. + * @param state Borrowed protocol owner under network execution ownership. * @param a Destination. @param ifindex Interface. @return True if accepted. */ -static bool ipv6_destination_local(const struct in6_addr *a,uint32_t ifindex) +static bool ipv6_destination_local(struct net_ipv6_state *state, const struct in6_addr *a,uint32_t ifindex) { - if(ipv6_multicast(a)){struct ipv6_group_slot *g=ipv6_find_group(a,ifindex); + if(ipv6_multicast(a)){struct ipv6_group_slot *g=ipv6_find_group(state,a,ifindex); return ipv6_equal(a,&ipv6_all_nodes) || (g && g->refs);} - struct ipv6_address_slot *slot=ipv6_find_address(a,ifindex); + struct ipv6_address_slot *slot=ipv6_find_address(state,a,ifindex); return slot && !(slot->value.flags & (NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED)); } /** @brief Compute a transport pseudo-header checksum. @param source Source address. @@ -239,82 +177,95 @@ uint16_t net_ipv6_checksum(const struct in6_addr *source,const struct in6_addr * sum=net_checksum_partial(sum,trailer,8); return net_checksum_finish(net_checksum_partial(sum,data,length)); } -/** @brief Copy live address snapshots. @param out Optional output. @param capacity Entries available. +/** @brief Copy live address snapshots. @param ns Borrowed network, NULL for the permanent initial network. + * @param out Optional output. @param capacity Entries available. * @return Total entry count. */ -uint32_t net_ipv6_addresses(struct net_ipv6_address *out,uint32_t capacity) +uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out,uint32_t capacity) { - uint32_t n=0;for(uint32_t i=0;iaddresses[i].used){ + if(out && naddresses[i].value; ++n;} return n; } -/** @brief Copy live route snapshots. @param out Optional output. @param capacity Entries available. +/** @brief Copy live route snapshots. @param ns Borrowed network, NULL for the permanent initial network. + * @param out Optional output. @param capacity Entries available. * @return Total entry count. */ -uint32_t net_ipv6_routes(struct net_ipv6_route *out,uint32_t capacity) +uint32_t net_ipv6_routes(struct net_namespace *ns, struct net_ipv6_route *out,uint32_t capacity) { - uint32_t n=0;for(uint32_t i=0;iroutes[i].used){ + if(out && nroutes[i].value; ++n;} return n; } -/** @brief Copy neighbor snapshots. @param out Optional output. @param capacity Entries available. +/** @brief Copy neighbor snapshots. @param ns Borrowed network, NULL for the permanent initial network. + * @param out Optional output. @param capacity Entries available. * @return Total entry count. */ -uint32_t net_ipv6_neighbors(struct net_ipv6_neighbor *out,uint32_t capacity) +uint32_t net_ipv6_neighbors(struct net_namespace *ns, struct net_ipv6_neighbor *out,uint32_t capacity) { - uint32_t n=0;for(uint32_t i=0;ineighbors[i].used){ + if(out && nneighbors[i].value; ++n;} return n; } -/** @brief Retain or release one host multicast membership. @param address Multicast group. +/** @brief Retain or release one host multicast membership. @param ns Borrowed network, NULL for the permanent initial network. + * @param address Multicast group. * @param ifindex Interface. @param delta One to join or minus one to leave. @return Zero or errno. */ -int net_ipv6_multicast_change(const struct in6_addr *address,uint32_t ifindex,int delta) +int net_ipv6_multicast_change(struct net_namespace *ns, const struct in6_addr *address,uint32_t ifindex,int delta) { - if(!address || !ipv6_multicast(address) || !net_interface_exists(NULL, ifindex) || (delta!=1 && delta!=-1))return -LINUX_EINVAL; - struct ipv6_group_slot *g=ipv6_find_group(address,ifindex); + struct net_ipv6_state *state = net_ipv6_state_get(ns); + if(!address || !ipv6_multicast(address) || !net_interface_exists(state->net_ns, ifindex) || (delta!=1 && delta!=-1))return -LINUX_EINVAL; + struct ipv6_group_slot *g=ipv6_find_group(state,address,ifindex); if(delta<0){if(!g)return -LINUX_EADDRNOTAVAIL;if(--g->refs==0){ /* Keep the group briefly to send an MLD state-change record. */ g->reports=2;g->query_pending=false;g->report_at=time_uptime_ms();}return 0;} if(g){if(g->refs==UINT32_MAX)return -LINUX_ENOBUFS;if(!g->refs){g->reports=2;g->query_pending=false;g->report_at=time_uptime_ms();}++g->refs;return 0;} - for(uint32_t i=0;iused=true;g->address=*address;g->ifindex=ifindex;g->refs=1; + for(uint32_t i=0;igroups[i].used){ + g=&state->groups[i];g->used=true;g->address=*address;g->ifindex=ifindex;g->refs=1; g->reports=2;g->query_pending=false;g->report_at=time_uptime_ms();return 0;} return -LINUX_ENOBUFS; } -/** @brief Add, replace or remove a route. @param route Checked route in network byte order. +/** @brief Add, replace or remove a route. @param ns Borrowed network, NULL for the permanent initial network. + * @param route Checked route in network byte order. * @param remove Remove rather than add. @return Zero or negative errno. */ -int net_ipv6_route_update(const struct net_ipv6_route *route,bool remove) +int net_ipv6_route_update(struct net_namespace *ns, const struct net_ipv6_route *route,bool remove) { - if(!route || route->prefix_length>128 || !net_interface_exists(NULL, route->ifindex) || + struct net_ipv6_state *state = net_ipv6_state_get(ns); + if(!route || route->prefix_length>128 || !net_interface_exists(state->net_ns, route->ifindex) || ipv6_multicast(&route->gateway))return -LINUX_EINVAL; struct net_ipv6_route normalized=*route;ipv6_mask(&normalized.destination,normalized.prefix_length); struct ipv6_route_slot *free_slot=0; for(uint32_t i=0;iused){if(!free_slot)free_slot=s;continue;} + struct ipv6_route_slot *s=&state->routes[i];if(!s->used){if(!free_slot)free_slot=s;continue;} if(s->value.ifindex==normalized.ifindex && s->value.prefix_length==normalized.prefix_length && ipv6_equal(&s->value.destination,&normalized.destination) && ipv6_equal(&s->value.gateway,&normalized.gateway)){ if(remove)s->used=false;else{s->value=normalized;s->automatic=false;s->address_until=s->ra_until=0;} - netlink_ipv6_changed();return 0;} + netlink_ipv6_changed(state->net_ns);return 0;} } if(remove)return -LINUX_ESRCH; if(!free_slot)return -LINUX_ENOBUFS; - free_slot->value=normalized;free_slot->used=true;free_slot->automatic=false;netlink_ipv6_changed();return 0; + free_slot->value=normalized;free_slot->used=true;free_slot->automatic=false;netlink_ipv6_changed(state->net_ns);return 0; } /** @brief Recompute an automatic connected route from manually assigned addresses. + * @param state Borrowed protocol owner under network execution ownership. * @param address An address in the prefix. @param bits Prefix width. - * @return Zero or negative capacity errno. */ -static int ipv6_connected_route(const struct in6_addr *address,uint32_t bits,uint32_t ifindex) + * @return Zero or negative capacity errno. + * @param ifindex Stable interface index within this network. + */ +static int ipv6_connected_route(struct net_ipv6_state *state, const struct in6_addr *address,uint32_t bits,uint32_t ifindex) { struct in6_addr prefix=*address;ipv6_mask(&prefix,bits);uint64_t deadline=0,now=time_uptime_ms(); for(uint32_t i=0;iaddresses[i]; if(a->used && !a->autonomous && a->value.ifindex==ifindex && a->value.prefix_length==bits && ipv6_prefix_equal(&a->value.address,&prefix,bits) && !ipv6_expired(a->value.valid_until,now) && a->value.valid_until>deadline)deadline=a->value.valid_until; } struct ipv6_route_slot *slot=0,*empty=0; for(uint32_t i=0;iroutes[i]; if(!r->used){if(!empty)empty=r;continue;} if(r->value.ifindex==ifindex && r->value.prefix_length==bits && ipv6_unspecified(&r->value.gateway) && ipv6_equal(&r->value.destination,&prefix)){slot=r;break;} @@ -328,88 +279,95 @@ static int ipv6_connected_route(const struct in6_addr *address,uint32_t bits,uin if(slot->ra_until && ipv6_expired(slot->ra_until,now))slot->ra_until=0; slot->value.valid_until=slot->address_until>slot->ra_until?slot->address_until:slot->ra_until; if(!slot->value.valid_until)slot->used=false; - netlink_ipv6_changed();return 0; + netlink_ipv6_changed(state->net_ns);return 0; } /** @brief Apply a manual or SLAAC address and associated membership. + * @param state Borrowed protocol owner under network execution ownership. * @param address Configuration and absolute lifetimes. @param remove Remove when true. * @param autonomous True for router-derived addresses. @return Zero or negative errno. */ -static int ipv6_address_set(const struct net_ipv6_address *address,bool remove,bool autonomous) +static int ipv6_address_set(struct net_ipv6_state *state, const struct net_ipv6_address *address,bool remove,bool autonomous) { - if(!address || address->prefix_length>128 || !net_interface_exists(NULL, address->ifindex) || + if(!address || address->prefix_length>128 || !net_interface_exists(state->net_ns, address->ifindex) || ipv6_multicast(&address->address) || ipv6_unspecified(&address->address) || address->preferred_until>address->valid_until)return -LINUX_EINVAL; - struct ipv6_address_slot *slot=ipv6_find_address(&address->address,address->ifindex); + struct ipv6_address_slot *slot=ipv6_find_address(state,&address->address,address->ifindex); if(remove){if(!slot)return -LINUX_EADDRNOTAVAIL; if(slot->value.ifindex==1 && ipv6_equal(&slot->value.address,&ipv6_loop))return -LINUX_EPERM; struct in6_addr group;ipv6_solicited(&group,&slot->value.address); - if(slot->value.ifindex!=1)(void)net_ipv6_multicast_change(&group,slot->value.ifindex,-1); + if(slot->value.ifindex!=1)(void)net_ipv6_multicast_change(state->net_ns, &group,slot->value.ifindex,-1); bool connected=slot->value.ifindex!=1 && !slot->autonomous; struct net_ipv6_address old=slot->value;slot->used=false; - if(connected)(void)ipv6_connected_route(&old.address,old.prefix_length,old.ifindex); - netlink_ipv6_changed();return 0;} + if(connected)(void)ipv6_connected_route(state,&old.address,old.prefix_length,old.ifindex); + netlink_ipv6_changed(state->net_ns);return 0;} if(slot){struct net_ipv6_address old=slot->value;bool old_auto=slot->autonomous; - uint32_t state=slot->value.flags & (NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED); - slot->value=*address;slot->value.flags|=state;slot->value.scope=ipv6_scope(&address->address); + uint32_t flags=slot->value.flags & (NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED); + slot->value=*address;slot->value.flags|=flags;slot->value.scope=ipv6_scope(&address->address); slot->autonomous=autonomous; - if(old.ifindex!=1 && !old_auto)(void)ipv6_connected_route(&old.address,old.prefix_length,old.ifindex); - if(address->ifindex!=1 && !autonomous){int rc=ipv6_connected_route(&address->address,address->prefix_length,address->ifindex); + if(old.ifindex!=1 && !old_auto)(void)ipv6_connected_route(state,&old.address,old.prefix_length,old.ifindex); + if(address->ifindex!=1 && !autonomous){int rc=ipv6_connected_route(state,&address->address,address->prefix_length,address->ifindex); if(rc<0){slot->value=old;slot->autonomous=old_auto; - if(old.ifindex!=1 && !old_auto)(void)ipv6_connected_route(&old.address,old.prefix_length,old.ifindex); + if(old.ifindex!=1 && !old_auto)(void)ipv6_connected_route(state,&old.address,old.prefix_length,old.ifindex); return rc;}} - netlink_ipv6_changed();return 0;} - for(uint32_t i=0;inet_ns);return 0;} + for(uint32_t i=0;iaddresses[i].used){slot=&state->addresses[i];break;} if(!slot)return -LINUX_ENOBUFS; struct in6_addr group;ipv6_solicited(&group,&address->address); - if(address->ifindex!=1){int ret=net_ipv6_multicast_change(&group,address->ifindex,1);if(ret<0)return ret;} + if(address->ifindex!=1){int ret=net_ipv6_multicast_change(state->net_ns, &group,address->ifindex,1);if(ret<0)return ret;} slot->used=true;slot->value=*address;slot->value.scope=ipv6_scope(&address->address); slot->autonomous=autonomous;slot->dad_sent=false;slot->dad_wait_mld=false;slot->dad_at=time_uptime_ms(); if(address->ifindex!=1 && !(address->flags&NET_IPV6_ADDR_NODAD)){ - slot->value.flags|=NET_IPV6_ADDR_TENTATIVE;struct ipv6_link *link=ipv6_link(address->ifindex,true); - if(!link){slot->used=false;(void)net_ipv6_multicast_change(&group,address->ifindex,-1);return -LINUX_ENOMEM;} + slot->value.flags|=NET_IPV6_ADDR_TENTATIVE;struct ipv6_link *link=ipv6_link(state,address->ifindex,true); + if(!link){slot->used=false;(void)net_ipv6_multicast_change(state->net_ns, &group,address->ifindex,-1);return -LINUX_ENOMEM;} slot->dad_at+=ipv6_jitter(link,1000); - struct ipv6_group_slot *g=ipv6_find_group(&group,address->ifindex); + struct ipv6_group_slot *g=ipv6_find_group(state,&group,address->ifindex); if(g && g->refs==1 && g->reports==2){g->report_at=slot->dad_at;slot->dad_wait_mld=true;} } - if(address->ifindex!=1 && !autonomous){int ret=ipv6_connected_route(&address->address,address->prefix_length,address->ifindex); - if(ret<0){slot->used=false;(void)net_ipv6_multicast_change(&group,address->ifindex,-1);return ret;}} - netlink_ipv6_changed();return 0; + if(address->ifindex!=1 && !autonomous){int ret=ipv6_connected_route(state,&address->address,address->prefix_length,address->ifindex); + if(ret<0){slot->used=false;(void)net_ipv6_multicast_change(state->net_ns, &group,address->ifindex,-1);return ret;}} + netlink_ipv6_changed(state->net_ns);return 0; } /** @brief Add or remove a local address and its solicited-node membership. + * @param ns Borrowed network, NULL for the permanent initial network. * @param address Checked address, interface and absolute lifetimes. @param remove Remove when true. * @return Zero or negative errno; caller has already authorized configuration. */ -int net_ipv6_address_update(const struct net_ipv6_address *address,bool remove) -{ return ipv6_address_set(address,remove,false); } +int net_ipv6_address_update(struct net_namespace *ns, const struct net_ipv6_address *address,bool remove) +{ + struct net_ipv6_state *state = net_ipv6_state_get(ns); + return ipv6_address_set(state,address,remove,false); +} -/** @brief Select a live source and route for an IPv6 destination. @param destination Destination. +/** @brief Select a live source and route for an IPv6 destination. @param ns Borrowed network, NULL for the permanent initial network. + * @param destination Destination. * @param scope Interface index or zero. @param bound Optional bound source. @param out_path Snapshot. * @return Zero or negative errno. */ -int net_ipv6_route(const struct in6_addr *destination,uint32_t scope, +int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination,uint32_t scope, const struct in6_addr *bound,struct net_ipv6_path *out_path) { - if(!destination || !out_path || ipv6_unspecified(destination) || (scope && !net_interface_exists(NULL, scope)))return -LINUX_EINVAL; + struct net_ipv6_state *state = net_ipv6_state_get(ns); + if(!destination || !out_path || ipv6_unspecified(destination) || (scope && !net_interface_exists(state->net_ns, scope)))return -LINUX_EINVAL; uint64_t now=time_uptime_ms();uint32_t ifindex=0,mtu=IPV6_LINK_MTU; struct in6_addr next=*destination; - struct ipv6_address_slot *local=ipv6_find_address(destination,scope); + struct ipv6_address_slot *local=ipv6_find_address(state,destination,scope); if(ipv6_equal(destination,&ipv6_loop)){ifindex=1;mtu=65575;} else if(local && !(local->value.flags&(NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED))){ ifindex=local->value.ifindex;mtu=65575; } else if(ipv6_multicast(destination)){ uint8_t ms=destination->s6_addr[1]&15; if(ms==0)return -LINUX_EINVAL; - ifindex=scope?scope:(ms==1?1:ipv6_default_interface()); + ifindex=scope?scope:(ms==1?1:ipv6_default_interface(state)); if(!scope && bound && !ipv6_unspecified(bound)){ - struct ipv6_address_slot *binding=ipv6_find_address(bound,0); + struct ipv6_address_slot *binding=ipv6_find_address(state,bound,0); if(binding)ifindex=binding->value.ifindex; } } else { struct ipv6_route_slot *best=0;bool matched_route=false; for(uint32_t i=0;iroutes[i]; if(!r->used || ipv6_expired(r->value.valid_until,now) || (scope && r->value.ifindex!=scope) || !ipv6_prefix_equal(destination,&r->value.destination,r->value.prefix_length))continue; matched_route=true; if(bound && !ipv6_unspecified(bound)){ - struct ipv6_address_slot *binding=ipv6_find_address(bound,r->value.ifindex); + struct ipv6_address_slot *binding=ipv6_find_address(state,bound,r->value.ifindex); if(!binding || binding->value.flags&(NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED) || ipv6_expired(binding->value.valid_until,now))continue; } @@ -421,15 +379,16 @@ int net_ipv6_route(const struct in6_addr *destination,uint32_t scope, if(!ipv6_unspecified(&best->value.gateway))next=best->value.gateway; } if(scope && scope!=ifindex)return -LINUX_ENETUNREACH; + if(!net_interface_is_ready(ns, ifindex))return -LINUX_ENETDOWN; if(ifindex!=1){ - struct ipv6_link *link=ipv6_link(ifindex,false); - if(!link || !link->up || !net_interface_is_ready(NULL, ifindex))return -LINUX_ENETDOWN; + struct ipv6_link *link=ipv6_link(state,ifindex,false); + if(!link || !link->up || !net_interface_is_ready(state->net_ns, ifindex))return -LINUX_ENETDOWN; if(mtu!=65575)mtu=link->mtu; if(ipv6_equal(destination,&ipv6_loop))return -LINUX_ENETUNREACH; } struct ipv6_address_slot *source=0;uint32_t best_score=0; for(uint32_t i=0;iaddresses[i]; if(!a->used || a->value.ifindex!=ifindex || a->value.flags&(NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED) || ipv6_expired(a->value.valid_until,now))continue; if(bound && !ipv6_unspecified(bound) && !ipv6_equal(bound,&a->value.address))continue; @@ -443,22 +402,25 @@ int net_ipv6_route(const struct in6_addr *destination,uint32_t scope, if(!source || score>best_score){source=a;best_score=score;} } if(!source)return -LINUX_EADDRNOTAVAIL; - for(uint32_t i=0;ipmtu[i].used && state->pmtu[i].ifindex==ifindex && + !ipv6_expired(state->pmtu[i].deadline,now) && ipv6_equal(&state->pmtu[i].destination,destination) && state->pmtu[i].mtupmtu[i].mtu; out_path->source=source->value.address;out_path->destination=*destination;out_path->next_hop=next; out_path->ifindex=ifindex;out_path->mtu=mtu;return 0; } -/** @brief Transmit a complete IPv6 packet using a known Ethernet address. @param mac Destination MAC. +/** @brief Transmit a complete IPv6 packet using a known Ethernet address. @param state Borrowed protocol owner under network execution ownership. + * @param mac Destination MAC. * @param source IPv6 source. @param destination IPv6 destination. @param next Next header. * @param hops Hop limit. @param flowinfo Network-order flow bits. @param payload Bytes. - * @param length Payload length no greater than Ethernet MTU minus IPv6 header. @return Driver status. */ -static int ipv6_send_frame(uint32_t ifindex,const uint8_t mac[6],const struct in6_addr *source, + * @param length Payload length no greater than Ethernet MTU minus IPv6 header. @return Driver status. + * @param ifindex Stable interface index within this network. + */ +static int ipv6_send_frame(struct net_ipv6_state *state, uint32_t ifindex,const uint8_t mac[6],const struct in6_addr *source, const struct in6_addr *destination,uint8_t next,uint8_t hops, uint32_t flowinfo,const uint8_t *payload,uint32_t length) { - struct ipv6_link *link=ipv6_link(ifindex,false); - if(!link || !link->up || !net_interface_is_ready(NULL, ifindex))return -LINUX_ENETDOWN; + struct ipv6_link *link=ipv6_link(state,ifindex,false); + if(!link || !link->up || !net_interface_is_ready(state->net_ns, ifindex))return -LINUX_ENETDOWN; if(length>IPV6_LINK_MTU-40)return -LINUX_EMSGSIZE; uint8_t frame[14+IPV6_LINK_MTU];uint8_t *ip=frame+14;const uint8_t *flow=(const uint8_t *)&flowinfo; net_memcpy(frame,mac,6);net_memcpy(frame+6,netdev_mac(ifindex),6);net_put_u16(frame+12,IPV6_ETHERTYPE);ip[0]=(uint8_t)(0x60|(flow[0]&15)); @@ -471,81 +433,95 @@ static int ipv6_send_frame(uint32_t ifindex,const uint8_t mac[6],const struct in * @param address Multicast destination. */ static void ipv6_multicast_mac(uint8_t mac[6],const struct in6_addr *address) { mac[0]=0x33;mac[1]=0x33;net_memcpy(mac+2,address->s6_addr+12,4); } -/** @brief Find one neighbor. @param address Neighbor address. @return Entry or NULL. */ -static struct ipv6_neighbor_slot *ipv6_find_neighbor(uint32_t ifindex,const struct in6_addr *address) +/** @brief Find one neighbor. @param state Borrowed protocol owner under network execution ownership. + * @param address Neighbor address. @return Entry or NULL. + * @param ifindex Stable interface index within this network. + */ +static struct ipv6_neighbor_slot *ipv6_find_neighbor(struct net_ipv6_state *state, uint32_t ifindex,const struct in6_addr *address) { - for(uint32_t i=0;ineighbors[i].used && state->neighbors[i].value.ifindex==ifindex && + ipv6_equal(&state->neighbors[i].value.address,address))return &state->neighbors[i]; return 0; } -/** @brief Create a bounded neighbor entry. @param address Neighbor address. - * @return Entry or NULL when every slot is active. */ -static struct ipv6_neighbor_slot *ipv6_create_neighbor(uint32_t ifindex,const struct in6_addr *address) +/** @brief Create a bounded neighbor entry. @param state Borrowed protocol owner under network execution ownership. + * @param address Neighbor address. + * @return Entry or NULL when every slot is active. + * @param ifindex Stable interface index within this network. + */ +static struct ipv6_neighbor_slot *ipv6_create_neighbor(struct net_ipv6_state *state, uint32_t ifindex,const struct in6_addr *address) { - struct ipv6_neighbor_slot *slot=ipv6_find_neighbor(ifindex,address); + struct ipv6_neighbor_slot *slot=ipv6_find_neighbor(state,ifindex,address); if(slot && slot->value.state!=IPV6_NUD_FAILED)return slot; if(slot){net_memzero(slot->value.mac,6);slot->value.state=IPV6_NUD_INCOMPLETE; - slot->deadline=time_uptime_ms();slot->probes=0;netlink_ipv6_changed();return slot;} - for(uint32_t i=0;ideadline=time_uptime_ms();slot->probes=0;netlink_ipv6_changed(state->net_ns);return slot;} + for(uint32_t i=0;ineighbors[i].used || + state->neighbors[i].value.state==IPV6_NUD_FAILED){slot=&state->neighbors[i];break;} if(!slot)return 0; net_memzero(slot,sizeof(*slot));slot->used=true;slot->value.address=*address; slot->value.ifindex=ifindex;slot->value.state=IPV6_NUD_INCOMPLETE;slot->deadline=time_uptime_ms(); - netlink_ipv6_changed();return slot; + netlink_ipv6_changed(state->net_ns);return slot; } -/** @brief Send a Neighbor Solicitation for DAD or address resolution. @param target Target. +/** @brief Send a Neighbor Solicitation for DAD or address resolution. @param state Borrowed protocol owner under network execution ownership. + * @param target Target. * @param source Usable source or unspecified for DAD. @param unicast Optional neighbor MAC. - * @return Driver status. */ -static int ipv6_send_ns(uint32_t ifindex,const struct in6_addr *target,const struct in6_addr *source,const uint8_t *unicast) + * @return Driver status. + * @param ifindex Stable interface index within this network. + */ +static int ipv6_send_ns(struct net_ipv6_state *state, uint32_t ifindex,const struct in6_addr *target,const struct in6_addr *source,const uint8_t *unicast) { struct in6_addr dest;uint8_t mac[6],ns[32]={0};uint32_t len=24; if(unicast){dest=*target;net_memcpy(mac,unicast,6);}else{ipv6_solicited(&dest,target);ipv6_multicast_mac(mac,&dest);} ns[0]=135;net_memcpy(ns+8,target->s6_addr,16); if(!ipv6_unspecified(source)){ns[24]=1;ns[25]=1;net_memcpy(ns+26,netdev_mac(ifindex),6);len=32;} net_put_u16(ns+2,net_ipv6_checksum(source,&dest,58,ns,len)); - return ipv6_send_frame(ifindex,mac,source,&dest,58,255,0,ns,len); + return ipv6_send_frame(state,ifindex,mac,source,&dest,58,255,0,ns,len); } -/** @brief Send a Router Solicitation after link-local DAD. @param source Link-local source. - * @return Driver status. */ -static int ipv6_send_rs(uint32_t ifindex,const struct in6_addr *source) +/** @brief Send a Router Solicitation after link-local DAD. @param state Borrowed protocol owner under network execution ownership. + * @param source Link-local source. + * @return Driver status. + * @param ifindex Stable interface index within this network. + */ +static int ipv6_send_rs(struct net_ipv6_state *state, uint32_t ifindex,const struct in6_addr *source) { uint8_t mac[6],rs[16]={133,0,0,0,0,0,0,0,1,1};ipv6_multicast_mac(mac,&ipv6_all_routers); net_memcpy(rs+10,netdev_mac(ifindex),6);net_put_u16(rs+2,net_ipv6_checksum(source,&ipv6_all_routers,58,rs,16)); - return ipv6_send_frame(ifindex,mac,source,&ipv6_all_routers,58,255,0,rs,16); + return ipv6_send_frame(state,ifindex,mac,source,&ipv6_all_routers,58,255,0,rs,16); } -/** @brief Transmit one datagram, fragmenting at the source when necessary. @param path Route snapshot. +/** @brief Transmit one datagram, fragmenting at the source when necessary. @param state Borrowed protocol owner under network execution ownership. + * @param path Route snapshot. * @param protocol Upper next-header. @param data Borrowed bytes. @param length Length. * @param hops Hop limit. @param flowinfo Network-order flow bits. @param dont_fragment Forbid fragments. * @param mac Resolved Ethernet destination. @return Accepted bytes or negative errno. */ -static int ipv6_transmit(const struct net_ipv6_path *path,uint8_t protocol,const uint8_t *data, +static int ipv6_transmit(struct net_ipv6_state *state, const struct net_ipv6_path *path,uint8_t protocol,const uint8_t *data, uint32_t length,int hops,uint32_t flowinfo,bool dont_fragment,const uint8_t mac[6]) { - struct ipv6_link *link=ipv6_link(path->ifindex,false); + struct ipv6_link *link=ipv6_link(state,path->ifindex,false); if(!link || !link->up)return -LINUX_ENETDOWN; uint32_t mtu=path->mtu;if(mtu>link->mtu)mtu=link->mtu; if(mtuifindex,mac,&path->source,&path->destination,protocol,hop,flowinfo,data,length); + if(length+40<=mtu){int rc=ipv6_send_frame(state,path->ifindex,mac,&path->source,&path->destination,protocol,hop,flowinfo,data,length); return rc<0?rc:(int)length;} if(dont_fragment)return -LINUX_EMSGSIZE; - uint32_t chunk=(mtu-48)&~7u,ident=++ipv6_frag_id,offset=0;uint8_t fragment[IPV6_LINK_MTU-40]; + uint32_t chunk=(mtu-48)&~7u,ident=++state->frag_id,offset=0;uint8_t fragment[IPV6_LINK_MTU-40]; while(offsetchunk)n=chunk; fragment[0]=protocol;fragment[1]=0;net_put_u16(fragment+2,(uint16_t)(offset|(offset+nifindex,mac,&path->source,&path->destination,44,hop,flowinfo,fragment,n+8); + int rc=ipv6_send_frame(state,path->ifindex,mac,&path->source,&path->destination,44,hop,flowinfo,fragment,n+8); if(rc<0)return rc; offset+=n;} return (int)length; } -/** @brief Own a payload until a neighbor resolves or loopback is polled. @param path Route snapshot. +/** @brief Own a payload until a neighbor resolves or loopback is polled. @param state Borrowed protocol owner under network execution ownership. + * @param path Route snapshot. * @param protocol Upper protocol. @param data Borrowed bytes. @param length Length. * @param hops Hop limit. @param flowinfo Network-order flow bits. @param dont_fragment Forbid fragments. * @param loopback Deferred local delivery. @return Accepted bytes or negative errno. */ -static int ipv6_queue(const struct net_ipv6_path *path,uint8_t protocol,const void *data,uint32_t length, +static int ipv6_queue(struct net_ipv6_state *state, const struct net_ipv6_path *path,uint8_t protocol,const void *data,uint32_t length, int hops,uint32_t flowinfo,bool dont_fragment,bool loopback) { struct ipv6_pending *slot=0; - for(uint32_t i=0;ipending[i].used){slot=&state->pending[i];break;} if(!slot)return -LINUX_ENOBUFS; uint8_t *copy=kernel_malloc(length?length:1);if(!copy)return -LINUX_ENOMEM; if(length)net_memcpy(copy,data,length); @@ -553,85 +529,93 @@ static int ipv6_queue(const struct net_ipv6_path *path,uint8_t protocol,const vo slot->length=length;slot->hops=hops;slot->flowinfo=flowinfo;slot->dont_fragment=dont_fragment; slot->loopback=loopback;slot->used=true;return (int)length; } -/** @brief Send or retain an IPv6 transport message. @param path Selected route. +/** @brief Send or retain an IPv6 transport message. @param ns Borrowed network, NULL for the permanent initial network. + * @param path Selected route. * @param protocol Next header. @param data Borrowed payload. @param length Payload bytes. * @param hops Hop limit or -1. @param flowinfo Network-order flow information. * @param dont_fragment Reject packets larger than MTU. @param multicast_loop Deliver to local members. * @return Accepted bytes or negative errno. */ -int net_ipv6_output(const struct net_ipv6_path *path,uint8_t protocol,const void *data,uint32_t length, +int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,uint8_t protocol,const void *data,uint32_t length, int hops,uint32_t flowinfo,bool dont_fragment,bool multicast_loop) { + struct net_ipv6_state *state = net_ipv6_state_get(ns); if(length>65535)return -LINUX_EMSGSIZE; if(!path || (!data && length) || hops < -1 || hops>255 || - !net_interface_exists(NULL, path->ifindex))return -LINUX_EINVAL; - struct ipv6_link *link=path->ifindex==1?0:ipv6_link(path->ifindex,false); - if(path->ifindex!=1 && (!link || !link->up || !net_interface_is_ready(NULL, path->ifindex)))return -LINUX_ENETDOWN; + !net_interface_exists(state->net_ns, path->ifindex))return -LINUX_EINVAL; + if(!net_interface_is_ready(ns, path->ifindex))return -LINUX_ENETDOWN; + struct ipv6_link *link=path->ifindex==1?0:ipv6_link(state,path->ifindex,false); + if(path->ifindex!=1 && (!link || !link->up || !net_interface_is_ready(state->net_ns, path->ifindex)))return -LINUX_ENETDOWN; if(dont_fragment && length+40>path->mtu)return -LINUX_EMSGSIZE; - struct ipv6_address_slot *dst=ipv6_find_address(&path->destination,path->ifindex); + struct ipv6_address_slot *dst=ipv6_find_address(state,&path->destination,path->ifindex); if(path->ifindex==1 || (dst && !(dst->value.flags&(NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED)))) - return ipv6_queue(path,protocol,data,length,hops,flowinfo,dont_fragment,true); + return ipv6_queue(state,path,protocol,data,length,hops,flowinfo,dont_fragment,true); if(ipv6_multicast(&path->destination)){ - struct ipv6_group_slot *group=ipv6_find_group(&path->destination,path->ifindex); + struct ipv6_group_slot *group=ipv6_find_group(state,&path->destination,path->ifindex); /* Interface-local multicast is delivered only inside this host. */ if((path->destination.s6_addr[1]&15)==1){ if(multicast_loop && group && group->refs) - return ipv6_queue(path,protocol,data,length,hops,flowinfo,dont_fragment,true); + return ipv6_queue(state,path,protocol,data,length,hops,flowinfo,dont_fragment,true); return (int)length; } struct ipv6_pending *queued=0; if(multicast_loop && (ipv6_equal(&path->destination,&ipv6_all_nodes) || (group && group->refs))){ - for(uint32_t i=0;ipending[i].used){queued=&state->pending[i];break;} + int rc=ipv6_queue(state,path,protocol,data,length,hops,flowinfo,dont_fragment,true); if(rc<0)return rc; } uint8_t mac[6];ipv6_multicast_mac(mac,&path->destination); - int rc=ipv6_transmit(path,protocol,data,length,hops,flowinfo,dont_fragment,mac); + int rc=ipv6_transmit(state,path,protocol,data,length,hops,flowinfo,dont_fragment,mac); if(rc<0 && queued){kernel_free(queued->data);queued->used=false;} return rc; } - struct ipv6_neighbor_slot *neighbor=ipv6_create_neighbor(path->ifindex,&path->next_hop); + struct ipv6_neighbor_slot *neighbor=ipv6_create_neighbor(state,path->ifindex,&path->next_hop); if(!neighbor)return -LINUX_ENOBUFS; if(neighbor->value.state!=IPV6_NUD_INCOMPLETE && neighbor->value.state!=IPV6_NUD_FAILED){ if(neighbor->value.state==IPV6_NUD_STALE){neighbor->value.state=IPV6_NUD_DELAY;neighbor->deadline=time_uptime_ms()+5000;} - return ipv6_transmit(path,protocol,data,length,hops,flowinfo,dont_fragment,neighbor->value.mac); + return ipv6_transmit(state,path,protocol,data,length,hops,flowinfo,dont_fragment,neighbor->value.mac); } - int rc=ipv6_queue(path,protocol,data,length,hops,flowinfo,dont_fragment,false); - if(rc>=0 && neighbor->probes==0){(void)ipv6_send_ns(path->ifindex,&path->next_hop,&path->source,0); + int rc=ipv6_queue(state,path,protocol,data,length,hops,flowinfo,dont_fragment,false); + if(rc>=0 && neighbor->probes==0){(void)ipv6_send_ns(state,path->ifindex,&path->next_hop,&path->source,0); neighbor->probes=1;neighbor->deadline=time_uptime_ms()+link->retrans_ms;} return rc; } /** @brief Inform matching transport of an asynchronous neighbor or transmit failure. + * @param state Borrowed protocol owner under network execution ownership. * @param pending Owned pending packet. @param error Positive Linux errno. */ -static void ipv6_pending_error(const struct ipv6_pending *pending,int error) +static void ipv6_pending_error(struct net_ipv6_state *state, const struct ipv6_pending *pending,int error) { uint8_t quote[128]={0};uint32_t n=pending->length;if(n>sizeof(quote)-40)n=sizeof(quote)-40; quote[0]=0x60;net_put_u16(quote+4,(uint16_t)pending->length);quote[6]=pending->protocol; net_memcpy(quote+8,pending->path.source.s6_addr,16);net_memcpy(quote+24,pending->path.destination.s6_addr,16); - net_memcpy(quote+40,pending->data,n);net_ipv6_socket_error_on(pending->path.ifindex,quote,n+40,error,0); + net_memcpy(quote+40,pending->data,n);net_ipv6_socket_error_on(state->net_ns, pending->path.ifindex,quote,n+40,error,0); } -/** @brief Release queued packets for a newly resolved neighbor. @param neighbor Resolved entry. */ -static void ipv6_flush_neighbor(struct ipv6_neighbor_slot *neighbor) +/** @brief Release queued packets for a newly resolved neighbor. @param state Borrowed protocol owner under network execution ownership. + * @param neighbor Resolved entry. */ +static void ipv6_flush_neighbor(struct net_ipv6_state *state, struct ipv6_neighbor_slot *neighbor) { for(uint32_t i=0;iused || p->loopback || + struct ipv6_pending *p=&state->pending[i];if(!p->used || p->loopback || p->path.ifindex!=neighbor->value.ifindex || !ipv6_equal(&p->path.next_hop,&neighbor->value.address))continue; - int rc=ipv6_transmit(&p->path,p->protocol,p->data,p->length,p->hops,p->flowinfo,p->dont_fragment,neighbor->value.mac); - if(rc<0)ipv6_pending_error(p,-rc); + int rc=ipv6_transmit(state,&p->path,p->protocol,p->data,p->length,p->hops,p->flowinfo,p->dont_fragment,neighbor->value.mac); + if(rc<0)ipv6_pending_error(state,p,-rc); kernel_free(p->data);p->used=false; } } -/** @brief Update neighbor state from a validated link-layer option. @param address Neighbor address. - * @param mac Link address. @param solicited Valid solicited advertisement. @param override Replace changed address. */ -static void ipv6_learn_neighbor(uint32_t ifindex,const struct in6_addr *address,const uint8_t mac[6],bool solicited,bool override) +/** @brief Update neighbor state from a validated link-layer option. @param state Borrowed protocol owner under network execution ownership. + * @param address Neighbor address. + * @param mac Link address. @param solicited Valid solicited advertisement. @param override Replace changed address. + * @param ifindex Stable interface index within this network. + */ +static void ipv6_learn_neighbor(struct net_ipv6_state *state, uint32_t ifindex,const struct in6_addr *address,const uint8_t mac[6],bool solicited,bool override) { if(ipv6_unspecified(address) || ipv6_multicast(address) || (mac[0]&1))return; - struct ipv6_neighbor_slot *n=ipv6_create_neighbor(ifindex,address);if(!n)return; + struct ipv6_neighbor_slot *n=ipv6_create_neighbor(state,ifindex,address);if(!n)return; bool changed=n->value.state!=IPV6_NUD_INCOMPLETE && !net_memeq(n->value.mac,mac,6); if(changed && !override){if(n->value.state==IPV6_NUD_REACHABLE)n->value.state=IPV6_NUD_STALE;return;} net_memcpy(n->value.mac,mac,6);n->value.state=solicited?IPV6_NUD_REACHABLE:IPV6_NUD_STALE; - struct ipv6_link *link=ipv6_link(ifindex,false);if(!link)return; - n->deadline=time_uptime_ms()+link->reachable_ms;n->probes=0;netlink_ipv6_changed();ipv6_flush_neighbor(n); + struct ipv6_link *link=ipv6_link(state,ifindex,false);if(!link)return; + n->deadline=time_uptime_ms()+link->reachable_ms;n->probes=0;netlink_ipv6_changed(state->net_ns);ipv6_flush_neighbor(state,n); } /** @brief Find and validate an ND link-layer option. @param options Option bytes. @param length Byte length. * @param kind Wanted option type. @param mac Output pointer into input or NULL. @return False for malformed options. */ @@ -644,32 +628,39 @@ static bool ipv6_nd_options(const uint8_t *options,uint32_t length,uint8_t kind, options+=n;length-=n;} return true; } -/** @brief Respond to a valid solicitation for one of our addresses. @param target Local address. - * @param destination Recipient address. @param mac Ethernet recipient. @param solicited Solicited response. */ -static void ipv6_send_na(uint32_t ifindex,const struct in6_addr *target,const struct in6_addr *destination, +/** @brief Respond to a valid solicitation for one of our addresses. @param state Borrowed protocol owner under network execution ownership. + * @param target Local address. + * @param destination Recipient address. @param mac Ethernet recipient. @param solicited Solicited response. + * @param ifindex Stable interface index within this network. + */ +static void ipv6_send_na(struct net_ipv6_state *state, uint32_t ifindex,const struct in6_addr *target,const struct in6_addr *destination, const uint8_t mac[6],bool solicited) { uint8_t na[32]={136,0,0,0,0,0,0,0};na[4]=(uint8_t)(0x20|(solicited?0x40:0)); net_memcpy(na+8,target->s6_addr,16);na[24]=2;na[25]=1;net_memcpy(na+26,netdev_mac(ifindex),6); net_put_u16(na+2,net_ipv6_checksum(target,destination,58,na,32)); - (void)ipv6_send_frame(ifindex,mac,target,destination,58,255,0,na,32); + (void)ipv6_send_frame(state,ifindex,mac,target,destination,58,255,0,na,32); } -/** @brief Mark an address as a failed duplicate. @param slot Tentative local address. */ -static void ipv6_dad_failed(struct ipv6_address_slot *slot) +/** @brief Mark an address as a failed duplicate. @param state Borrowed protocol owner under network execution ownership. + * @param slot Tentative local address. */ +static void ipv6_dad_failed(struct net_ipv6_state *state, struct ipv6_address_slot *slot) { slot->value.flags&=~NET_IPV6_ADDR_TENTATIVE;slot->value.flags|=NET_IPV6_ADDR_DADFAILED; - netlink_ipv6_changed(); + netlink_ipv6_changed(state->net_ns); } -/** @brief Install or refresh an automatically learned prefix route. @param prefix Prefix address. +/** @brief Install or refresh an automatically learned prefix route. @param state Borrowed protocol owner under network execution ownership. + * @param prefix Prefix address. * @param bits Prefix width. @param gateway Gateway or unspecified. @param deadline Lifetime. - * @param metric Selection metric. @param addrconf True for an RA-derived route. */ -static void ipv6_auto_route(uint32_t ifindex,const struct in6_addr *prefix,uint32_t bits,const struct in6_addr *gateway, + * @param metric Selection metric. @param addrconf True for an RA-derived route. + * @param ifindex Stable interface index within this network. + */ +static void ipv6_auto_route(struct net_ipv6_state *state, uint32_t ifindex,const struct in6_addr *prefix,uint32_t bits,const struct in6_addr *gateway, uint64_t deadline,uint32_t metric,bool addrconf) { struct in6_addr network=*prefix;ipv6_mask(&network,bits);uint64_t now=time_uptime_ms(); struct ipv6_route_slot *slot=0,*empty=0; for(uint32_t i=0;iused){if(!empty)empty=r;continue;} + struct ipv6_route_slot *r=&state->routes[i];if(!r->used){if(!empty)empty=r;continue;} if(r->value.ifindex==ifindex && r->value.prefix_length==bits && ipv6_equal(&r->value.destination,&network) && ipv6_equal(&r->value.gateway,gateway)){slot=r;break;} } @@ -683,17 +674,20 @@ static void ipv6_auto_route(uint32_t ifindex,const struct in6_addr *prefix,uint3 if(slot->address_until && ipv6_expired(slot->address_until,now))slot->address_until=0; slot->value.valid_until=slot->ra_until>slot->address_until?slot->ra_until:slot->address_until; if(!slot->value.valid_until)slot->used=false; - netlink_ipv6_changed(); + netlink_ipv6_changed(state->net_ns); } /** @brief Apply a validated autonomous /64 prefix with RFC 4862 lifetime protection. + * @param state Borrowed protocol owner under network execution ownership. * @param prefix Prefix information option. @param valid Valid lifetime seconds. - * @param preferred Preferred lifetime seconds. */ -static void ipv6_slaac(uint32_t ifindex,const uint8_t *prefix,uint32_t valid,uint32_t preferred) + * @param preferred Preferred lifetime seconds. + * @param ifindex Stable interface index within this network. + */ +static void ipv6_slaac(struct net_ipv6_state *state, uint32_t ifindex,const uint8_t *prefix,uint32_t valid,uint32_t preferred) { struct in6_addr address;net_memcpy(address.s6_addr,prefix,8); const uint8_t *mac=netdev_mac(ifindex);address.s6_addr[8]=mac[0]^2;address.s6_addr[9]=mac[1];address.s6_addr[10]=mac[2]; address.s6_addr[11]=0xff;address.s6_addr[12]=0xfe;address.s6_addr[13]=mac[3];address.s6_addr[14]=mac[4];address.s6_addr[15]=mac[5]; - struct ipv6_address_slot *slot=ipv6_find_address(&address,ifindex);uint64_t now=time_uptime_ms(); + struct ipv6_address_slot *slot=ipv6_find_address(state,&address,ifindex);uint64_t now=time_uptime_ms(); uint64_t valid_until=ipv6_deadline(valid),preferred_until=ipv6_deadline(preferred); if(slot){if(!slot->autonomous)return; uint64_t remaining=slot->value.valid_until==IPV6_FOREVER?IPV6_FOREVER: @@ -706,19 +700,22 @@ static void ipv6_slaac(uint32_t ifindex,const uint8_t *prefix,uint32_t valid,uin slot->value.valid_until=valid_until;slot->value.preferred_until=preferred_until; if(preferred==0)slot->value.flags|=NET_IPV6_ADDR_DEPRECATED; else slot->value.flags&=~NET_IPV6_ADDR_DEPRECATED; - netlink_ipv6_changed();return; + netlink_ipv6_changed(state->net_ns);return; } if(!valid)return; struct net_ipv6_address entry={0};entry.address=address;entry.ifindex=ifindex;entry.prefix_length=64; entry.preferred_until=preferred_until;entry.valid_until=valid_until; if(preferred==0)entry.flags|=NET_IPV6_ADDR_DEPRECATED; - (void)ipv6_address_set(&entry,false,true); + (void)ipv6_address_set(state,&entry,false,true); } /** @brief Process a validated router advertisement and its bounded options. - * @param source Link-local router. @param icmp Message. @param length Bytes. */ -static void ipv6_router_advertisement(uint32_t ifindex,const struct in6_addr *source,const uint8_t *icmp,uint32_t length) + * @param state Borrowed protocol owner under network execution ownership. + * @param source Link-local router. @param icmp Message. @param length Bytes. + * @param ifindex Stable interface index within this network. + */ +static void ipv6_router_advertisement(struct net_ipv6_state *state, uint32_t ifindex,const struct in6_addr *source,const uint8_t *icmp,uint32_t length) { - struct ipv6_link *link=ipv6_link(ifindex,false); + struct ipv6_link *link=ipv6_link(state,ifindex,false); if(!link || !ipv6_linklocal(source) || length<16 || icmp[1])return; /* Validate the entire option sequence before applying any changes. */ for(uint32_t off=16;offbase_reachable_ms){link->base_reachable_ms=reachable;ipv6_refresh_reachable(link);} if(retrans)link->retrans_ms=retrans; link->rs_sent=3; - uint16_t life=net_get_u16(icmp+6);ipv6_auto_route(ifindex,&ipv6_zero,0,source,ipv6_deadline(life),1024,true); + uint16_t life=net_get_u16(icmp+6);ipv6_auto_route(state,ifindex,&ipv6_zero,0,source,ipv6_deadline(life),1024,true); for(uint32_t off=16;off=IPV6_MIN_MTU && mtu<=IPV6_LINK_MTU)link->mtu=mtu;} else if(kind==3 && n==32){uint8_t bits=p[2],flags=p[3];uint32_t valid=net_get_u32(p+4),preferred=net_get_u32(p+8); struct in6_addr prefix;net_memcpy(prefix.s6_addr,p+16,16); if(bits<=128 && !ipv6_linklocal(&prefix) && !ipv6_multicast(&prefix)){ - if(flags&0x80)ipv6_auto_route(ifindex,&prefix,bits,&ipv6_zero,ipv6_deadline(valid),256,true); - if((flags&0x40) && bits==64 && preferred<=valid)ipv6_slaac(ifindex,prefix.s6_addr,valid,preferred); + if(flags&0x80)ipv6_auto_route(state,ifindex,&prefix,bits,&ipv6_zero,ipv6_deadline(valid),256,true); + if((flags&0x40) && bits==64 && preferred<=valid)ipv6_slaac(state,ifindex,prefix.s6_addr,valid,preferred); }} off+=n; } } -/** @brief Remember a validated path MTU update from an ICMPv6 quote. @param quote IPv6 header. - * @param length Quote length. @param mtu Reported MTU. */ -static void ipv6_update_pmtu(uint32_t ifindex,const uint8_t *quote,uint32_t length,uint32_t mtu) +/** @brief Remember a validated path MTU update from an ICMPv6 quote. @param state Borrowed protocol owner under network execution ownership. + * @param quote IPv6 header. + * @param length Quote length. @param mtu Reported MTU. + * @param ifindex Stable interface index within this network. + */ +static void ipv6_update_pmtu(struct net_ipv6_state *state, uint32_t ifindex,const uint8_t *quote,uint32_t length,uint32_t mtu) { if(length<40 || quote[0]>>4!=6)return; struct in6_addr src,dst;net_memcpy(src.s6_addr,quote+8,16);net_memcpy(dst.s6_addr,quote+24,16); - struct ipv6_address_slot *a=ipv6_find_address(&src,ifindex);if(!a || ipv6_multicast(&dst))return; + struct ipv6_address_slot *a=ipv6_find_address(state,&src,ifindex);if(!a || ipv6_multicast(&dst))return; if(mtuIPV6_LINK_MTU)return; struct ipv6_pmtu *slot=0; for(uint32_t i=0;ivalue.ifindex && ipv6_equal(&ipv6_pmtu[i].destination,&dst)){ - slot=&ipv6_pmtu[i];break;}if(!slot && (!ipv6_pmtu[i].used || ipv6_expired(ipv6_pmtu[i].deadline,time_uptime_ms())))slot=&ipv6_pmtu[i];} + if(state->pmtu[i].used && state->pmtu[i].ifindex==a->value.ifindex && ipv6_equal(&state->pmtu[i].destination,&dst)){ + slot=&state->pmtu[i];break;}if(!slot && (!state->pmtu[i].used || ipv6_expired(state->pmtu[i].deadline,time_uptime_ms())))slot=&state->pmtu[i];} if(!slot)return; if(!slot->used || ipv6_expired(slot->deadline,time_uptime_ms()) || mtumtu)slot->mtu=mtu; slot->used=true;slot->destination=dst;slot->ifindex=a->value.ifindex;slot->deadline=time_uptime_ms()+600000; @@ -773,66 +773,70 @@ static bool ipv6_error_suppressed(const uint8_t *ip,uint32_t length) return next==58 && (off>=length || ip[off]<128); } /** @brief Generate a rate-limited ICMPv6 error for a locally received packet. + * @param state Borrowed protocol owner under network execution ownership. * @param ip Original IPv6 packet. @param length Available bytes. @param type Error type. - * @param code Error code. @param word Type-specific field. @param allow_multicast Permit RFC option exception. */ -static void ipv6_error(const uint8_t *ip,uint32_t length,uint8_t type,uint8_t code,uint32_t word,bool allow_multicast,uint32_t ifindex) + * @param code Error code. @param word Type-specific field. @param allow_multicast Permit RFC option exception. + * @param ifindex Stable interface index within this network. + */ +static void ipv6_error(struct net_ipv6_state *state, const uint8_t *ip,uint32_t length,uint8_t type,uint8_t code,uint32_t word,bool allow_multicast,uint32_t ifindex) { if(length<40)return; struct in6_addr src,dst;net_memcpy(src.s6_addr,ip+8,16);net_memcpy(dst.s6_addr,ip+24,16); if(ipv6_unspecified(&src) || ipv6_multicast(&src) || (!allow_multicast && ipv6_multicast(&dst)))return; if(ipv6_error_suppressed(ip,length))return; - uint64_t now=time_uptime_ms();if(now-ipv6_error_at>=1000){ipv6_error_at=now;ipv6_error_count=0;} - if(ipv6_error_count>=10)return; - struct net_ipv6_path path;if(net_ipv6_route(&src,ipv6_linklocal(&src)?ifindex:0, + uint64_t now=time_uptime_ms();if(now-state->error_at>=1000){state->error_at=now;state->error_count=0;} + if(state->error_count>=10)return; + struct net_ipv6_path path;if(net_ipv6_route(state->net_ns, &src,ipv6_linklocal(&src)?ifindex:0, ipv6_multicast(&dst)?0:&dst,&path)<0)return; uint8_t error[1240]={0};uint32_t n=length;if(n>1232)n=1232; error[0]=type;error[1]=code;net_put_u32(error+4,word);net_memcpy(error+8,ip,n); net_put_u16(error+2,net_ipv6_checksum(&path.source,&path.destination,58,error,n+8)); - if(net_ipv6_output(&path,58,error,n+8,64,0,false,false)>=0)++ipv6_error_count; + if(net_ipv6_output(state->net_ns, &path,58,error,n+8,64,0,false,false)>=0)++state->error_count; } -/** @brief Process a validated ICMPv6 message. @param ip Original packet. +/** @brief Process a validated ICMPv6 message. @param state Borrowed protocol owner under network execution ownership. + * @param ip Original packet. * @param ip_length IPv6 bytes. @param icmp Message. @param length Message bytes. * @param ifindex Receiving interface. @param ethernet_mac Source Ethernet MAC or NULL for loopback. * @param fragmented True when any fragment header was present. */ -static void ipv6_icmp(const uint8_t *ip,uint32_t ip_length,const uint8_t *icmp,uint32_t length, +static void ipv6_icmp(struct net_ipv6_state *state, const uint8_t *ip,uint32_t ip_length,const uint8_t *icmp,uint32_t length, uint32_t ifindex,const uint8_t *ethernet_mac,bool fragmented) { struct in6_addr src,dst;net_memcpy(src.s6_addr,ip+8,16);net_memcpy(dst.s6_addr,ip+24,16); if(length<8)return; if(icmp[0]==128 && icmp[1]==0 && !ipv6_unspecified(&src) && !ipv6_multicast(&src)){ struct net_ipv6_path path;const struct in6_addr *bound=ipv6_multicast(&dst)?0:&dst; - if(net_ipv6_route(&src,ipv6_linklocal(&src)?ifindex:0,bound,&path)<0)return; + if(net_ipv6_route(state->net_ns, &src,ipv6_linklocal(&src)?ifindex:0,bound,&path)<0)return; uint8_t *reply=kernel_malloc(length);if(!reply)return;net_memcpy(reply,icmp,length);reply[0]=129; reply[2]=reply[3]=0;net_put_u16(reply+2,net_ipv6_checksum(&path.source,&path.destination,58,reply,length)); - (void)net_ipv6_output(&path,58,reply,length,64,0,false,false);kernel_free(reply);return; + (void)net_ipv6_output(state->net_ns, &path,58,reply,length,64,0,false,false);kernel_free(reply);return; } if(icmp[0]>=1 && icmp[0]<=4 && icmp[1]<=4 && length>=48){ int error=icmp[0]==1?(icmp[1]==4?LINUX_ECONNREFUSED:LINUX_EHOSTUNREACH): (icmp[0]==2?LINUX_EMSGSIZE:(icmp[0]==3?LINUX_ETIMEDOUT:LINUX_EPROTO)); uint32_t mtu=icmp[0]==2?net_get_u32(icmp+4):0; - if(icmp[0]==2)ipv6_update_pmtu(ifindex,icmp+8,length-8,mtu); - net_ipv6_socket_error_on(ifindex,icmp+8,length-8,error,mtu);return; + if(icmp[0]==2)ipv6_update_pmtu(state,ifindex,icmp+8,length-8,mtu); + net_ipv6_socket_error_on(state->net_ns, ifindex,icmp+8,length-8,error,mtu);return; } if(ifindex==1 || fragmented || ip[7]!=255 || icmp[1]!=0 || !ethernet_mac)return; - if(icmp[0]==134){ipv6_router_advertisement(ifindex,&src,icmp,length);return;} + if(icmp[0]==134){ipv6_router_advertisement(state,ifindex,&src,icmp,length);return;} if((icmp[0]==135 || icmp[0]==136) && length>=24){ struct in6_addr target;net_memcpy(target.s6_addr,icmp+8,16);if(ipv6_multicast(&target))return; const uint8_t *mac=0;if(!ipv6_nd_options(icmp+24,length-24,icmp[0]==135?1:2,&mac))return; if(icmp[0]==135){ if(ipv6_unspecified(&src)){struct in6_addr group;ipv6_solicited(&group,&target); if(mac || !ipv6_equal(&dst,&group))return;} - else if(mac)ipv6_learn_neighbor(ifindex,&src,mac,false,true); - struct ipv6_address_slot *slot=ipv6_find_address(&target,ifindex);if(!slot)return; - if(slot->value.flags&NET_IPV6_ADDR_TENTATIVE){if(!net_memeq(ethernet_mac,netdev_mac(ifindex),6))ipv6_dad_failed(slot);return;} + else if(mac)ipv6_learn_neighbor(state,ifindex,&src,mac,false,true); + struct ipv6_address_slot *slot=ipv6_find_address(state,&target,ifindex);if(!slot)return; + if(slot->value.flags&NET_IPV6_ADDR_TENTATIVE){if(!net_memeq(ethernet_mac,netdev_mac(ifindex),6))ipv6_dad_failed(state,slot);return;} if(slot->value.flags&NET_IPV6_ADDR_DADFAILED)return; if(ipv6_unspecified(&src)){uint8_t allmac[6];ipv6_multicast_mac(allmac,&ipv6_all_nodes); - ipv6_send_na(ifindex,&target,&ipv6_all_nodes,allmac,false);} - else ipv6_send_na(ifindex,&target,&src,ethernet_mac,true); + ipv6_send_na(state,ifindex,&target,&ipv6_all_nodes,allmac,false);} + else ipv6_send_na(state,ifindex,&target,&src,ethernet_mac,true); }else{ if(ipv6_unspecified(&src) || (ipv6_multicast(&dst) && (icmp[4]&0x40)))return; - struct ipv6_address_slot *slot=ipv6_find_address(&target,ifindex); - if(slot && slot->value.flags&NET_IPV6_ADDR_TENTATIVE){if(!net_memeq(ethernet_mac,netdev_mac(ifindex),6))ipv6_dad_failed(slot);return;} - if(mac && ipv6_find_neighbor(ifindex,&target))ipv6_learn_neighbor(ifindex,&target,mac,(icmp[4]&0x40)!=0,(icmp[4]&0x20)!=0); + struct ipv6_address_slot *slot=ipv6_find_address(state,&target,ifindex); + if(slot && slot->value.flags&NET_IPV6_ADDR_TENTATIVE){if(!net_memeq(ethernet_mac,netdev_mac(ifindex),6))ipv6_dad_failed(state,slot);return;} + if(mac && ipv6_find_neighbor(state,ifindex,&target))ipv6_learn_neighbor(state,ifindex,&target,mac,(icmp[4]&0x40)!=0,(icmp[4]&0x20)!=0); } } (void)ip_length; @@ -860,8 +864,9 @@ static void ipv6_reassembly_clear(struct ipv6_reassembly *r) kernel_free(r->data);kernel_free(r->bitmap);kernel_free(r->prefix);net_memzero(r,sizeof(*r)); } /** @brief Expire a reassembly and quote its first fragment when available. + * @param state Borrowed protocol owner under network execution ownership. * @param r Expired entry; released before return. */ -static void ipv6_reassembly_expire(struct ipv6_reassembly *r) +static void ipv6_reassembly_expire(struct net_ipv6_state *state, struct ipv6_reassembly *r) { if(r->have_first && !r->poisoned && r->prefix){ uint8_t quote[1232]={0};uint32_t n=r->prefix_len; @@ -874,7 +879,7 @@ static void ipv6_reassembly_expire(struct ipv6_reassembly *r) quote[n++]=r->data[i]; } } - ipv6_error(quote,n,3,1,0,false,r->ifindex); + ipv6_error(state,quote,n,3,1,0,false,r->ifindex); } ipv6_reassembly_clear(r); } @@ -884,25 +889,27 @@ static void ipv6_reassembly_poison(struct ipv6_reassembly *r) kernel_free(r->data);kernel_free(r->bitmap);kernel_free(r->prefix); r->data=0;r->bitmap=0;r->prefix=0;r->poisoned=true; } -/** @brief Validate and dispatch an IPv6 packet. @param ip Borrowed packet. @param length Bytes. +/** @brief Validate and dispatch an IPv6 packet. @param state Borrowed protocol owner under network execution ownership. + * @param ip Borrowed packet. @param length Bytes. * @param ifindex Receiving interface. @param mac Ethernet source or NULL. @param reassembled Reassembly guard. */ -static void ipv6_receive_ip(const uint8_t *ip,uint32_t length,uint32_t ifindex,const uint8_t *mac,bool reassembled); +static void ipv6_receive_ip(struct net_ipv6_state *state, const uint8_t *ip,uint32_t length,uint32_t ifindex,const uint8_t *mac,bool reassembled); -/** @brief Insert a fragment into bounded storage, rejecting any overlap. @param ip Original packet. +/** @brief Insert a fragment into bounded storage, rejecting any overlap. @param state Borrowed protocol owner under network execution ownership. + * @param ip Original packet. * @param ip_length Packet bytes. @param off Fragment header offset. @param previous Previous next-header offset. * @param ifindex Receiving interface. */ -static void ipv6_fragment(const uint8_t *ip,uint32_t ip_length,uint32_t off,uint32_t previous,uint32_t ifindex) +static void ipv6_fragment(struct net_ipv6_state *state, const uint8_t *ip,uint32_t ip_length,uint32_t off,uint32_t previous,uint32_t ifindex) { const uint8_t *fragment=ip+off;uint16_t field=net_get_u16(fragment+2); uint32_t offset=field&0xfff8u,n=ip_length-off-8u,ident=net_get_u32(fragment+4); bool more=(field&1)!=0;if((more && (!n || (n&7u))) || offset+n>65535u || off-40u+offset+n>65535u)return; if(offset==0 && !ipv6_first_complete(fragment[0],fragment+8,n)){ - ipv6_error(ip,ip_length,4,3,0,false,ifindex);return;} + ipv6_error(state,ip,ip_length,4,3,0,false,ifindex);return;} struct in6_addr src,dst;net_memcpy(src.s6_addr,ip+8,16);net_memcpy(dst.s6_addr,ip+24,16); struct ipv6_reassembly *r=0,*free_slot=0; for(uint32_t i=0;iused && ipv6_expired(e->deadline,time_uptime_ms()))ipv6_reassembly_expire(e); + struct ipv6_reassembly *e=&state->reassembly[i]; + if(e->used && ipv6_expired(e->deadline,time_uptime_ms()))ipv6_reassembly_expire(state,e); if(e->used && e->ifindex==ifindex && e->identification==ident && ipv6_equal(&e->source,&src) && ipv6_equal(&e->destination,&dst)){ r=e;break;}if(!e->used && !free_slot)free_slot=e; } @@ -928,21 +935,24 @@ static void ipv6_fragment(const uint8_t *ip,uint32_t ip_length,uint32_t off,uint if(!packet){ipv6_reassembly_clear(r);return;} net_memcpy(packet,r->prefix,r->prefix_len);packet[r->prev_next]=r->next; net_put_u16(packet+4,(uint16_t)(total-40));net_memcpy(packet+r->prefix_len,r->data,r->total); - ipv6_reassembly_clear(r);ipv6_receive_ip(packet,total,ifindex,0,true);kernel_free(packet); + ipv6_reassembly_clear(r);ipv6_receive_ip(state,packet,total,ifindex,0,true);kernel_free(packet); } /** @brief Parse hop-by-hop or destination options with RFC unknown-option actions. + * @param state Borrowed protocol owner under network execution ownership. * @param ip Packet. @param total Packet bytes. @param off Extension offset. * @param length Extension length. @param router_alert Set when the MLD router alert is present. - * @return True when processing may continue. */ -static bool ipv6_options(const uint8_t *ip,uint32_t total,uint32_t off,uint32_t length,bool *router_alert,uint32_t ifindex) + * @return True when processing may continue. + * @param ifindex Stable interface index within this network. + */ +static bool ipv6_options(struct net_ipv6_state *state, const uint8_t *ip,uint32_t total,uint32_t off,uint32_t length,bool *router_alert,uint32_t ifindex) { uint32_t pos=off+2,end=off+length; while(posend-pos){ipv6_error(ip,total,4,0,pos,false,ifindex);return false;} + if(end-pos<2 || (uint32_t)ip[pos+1]+2u>end-pos){ipv6_error(state,ip,total,4,0,pos,false,ifindex);return false;} uint32_t n=(uint32_t)ip[pos+1]+2u; if(type==5 && n==4 && ip[pos+2]==0 && ip[pos+3]==0)*router_alert=true; else if(type!=1){uint8_t action=type>>6;if(action){ - if(action==2 || action==3){ipv6_error(ip,total,4,2,pos,action==2,ifindex);} + if(action==2 || action==3){ipv6_error(state,ip,total,4,2,pos,action==2,ifindex);} return false;}} pos+=n; } @@ -955,49 +965,53 @@ static uint32_t ipv6_mld_response_ms(uint16_t code,bool v2) if(!v2 || code<32768)return code; return (uint32_t)((code&0x0fffu)|0x1000u)<<(((code>>12)&7u)+3u); } -/** @brief Schedule listener reports in response to a valid MLD query. @param ip IPv6 packet. - * @param icmp Query. @param length Bytes. @param router_alert Hop-by-hop router alert was present. */ -static void ipv6_mld_query(uint32_t ifindex,const uint8_t *ip,const uint8_t *icmp,uint32_t length,bool router_alert) +/** @brief Schedule listener reports in response to a valid MLD query. @param state Borrowed protocol owner under network execution ownership. + * @param ip IPv6 packet. + * @param icmp Query. @param length Bytes. @param router_alert Hop-by-hop router alert was present. + * @param ifindex Stable interface index within this network. + */ +static void ipv6_mld_query(struct net_ipv6_state *state, uint32_t ifindex,const uint8_t *ip,const uint8_t *icmp,uint32_t length,bool router_alert) { if(ip[7]!=1 || !router_alert || length<24 || icmp[1])return; struct in6_addr source,group;net_memcpy(source.s6_addr,ip+8,16);net_memcpy(group.s6_addr,icmp+8,16); if(!ipv6_unspecified(&source) && !ipv6_linklocal(&source))return; if(!ipv6_unspecified(&group) && !ipv6_multicast(&group))return; bool v2=length!=24; - struct ipv6_link *link=ipv6_link(ifindex,false);if(!link)return; + struct ipv6_link *link=ipv6_link(state,ifindex,false);if(!link)return; if(!v2)link->mld_v1_until=time_uptime_ms()+260000; else if(length<28 || (uint32_t)net_get_u16(icmp+26)*16u>length-28)return; uint32_t maximum=ipv6_mld_response_ms(net_get_u16(icmp+4),v2); - for(uint32_t i=0;igroups[i].used && state->groups[i].refs && + state->groups[i].ifindex==ifindex && (ipv6_unspecified(&group) || ipv6_equal(&group,&state->groups[i].address))){ uint64_t deadline=time_uptime_ms()+ipv6_jitter(link,maximum); - if(!ipv6_groups[i].query_pending || deadlinegroups[i].query_pending || deadlinegroups[i].query_at)state->groups[i].query_at=deadline; + state->groups[i].query_pending=true;} } /** @brief Validate extension headers and transport checksums before delivery. + * @param state Borrowed protocol owner under network execution ownership. * @param ip Borrowed packet. @param length Available bytes. @param ifindex Interface. * @param mac Ethernet source or NULL. @param reassembled True for a reconstructed packet. */ -static void ipv6_receive_ip(const uint8_t *ip,uint32_t length,uint32_t ifindex,const uint8_t *mac,bool reassembled) +static void ipv6_receive_ip(struct net_ipv6_state *state, const uint8_t *ip,uint32_t length,uint32_t ifindex,const uint8_t *mac,bool reassembled) { if(length<40 || ip[0]>>4!=6)return; uint32_t total=40u+net_get_u16(ip+4);if(total>length)return; struct in6_addr src,dst;net_memcpy(src.s6_addr,ip+8,16);net_memcpy(dst.s6_addr,ip+24,16); if(ipv6_multicast(&src) || (ifindex!=1 && (ipv6_equal(&src,&ipv6_loop) || ipv6_equal(&dst,&ipv6_loop))) || (ifindex!=1 && mac && ipv6_multicast(&dst) && (dst.s6_addr[1]&15)<2) || - !ipv6_destination_local(&dst,ifindex))return; + !ipv6_destination_local(state,&dst,ifindex))return; uint32_t off=40,previous=6,count=0;uint8_t next=ip[6];bool fragmented=reassembled,router_alert=false; while(next==0 || next==43 || next==44 || next==60){ if(++count>IPV6_HEADER_COUNT || off>IPV6_HEADER_LIMIT || total-off<8)return; if(next==44){ if(fragmented)return; uint16_t field=net_get_u16(ip+off+2);fragmented=true; - if((field&0xfff9u)!=0){ipv6_fragment(ip,total,off,previous,ifindex);return;} + if((field&0xfff9u)!=0){ipv6_fragment(state,ip,total,off,previous,ifindex);return;} next=ip[off];previous=off;off+=8;continue; } - if(next==0 && off!=40){ipv6_error(ip,total,4,1,previous,false,ifindex);return;} + if(next==0 && off!=40){ipv6_error(state,ip,total,4,1,previous,false,ifindex);return;} uint32_t n=((uint32_t)ip[off+1]+1u)*8u;if(n>total-off || off+n>IPV6_HEADER_LIMIT)return; - if(next==43 && ip[off+3]){ipv6_error(ip,total,4,0,off+2,false,ifindex);return;} - if((next==0 || next==60) && !ipv6_options(ip,total,off,n,&router_alert,ifindex))return; + if(next==43 && ip[off+3]){ipv6_error(state,ip,total,4,0,off+2,false,ifindex);return;} + if((next==0 || next==60) && !ipv6_options(state,ip,total,off,n,&router_alert,ifindex))return; next=ip[off];previous=off;off+=n; } uint32_t payload=total-off;const uint8_t *data=ip+off; @@ -1006,51 +1020,63 @@ static void ipv6_receive_ip(const uint8_t *ip,uint32_t length,uint32_t ifindex,c if(next==17){ if(payload<8 || net_get_u16(data+4)!=payload || !net_get_u16(data+6) || net_ipv6_checksum(&src,&dst,17,data,payload))return; - net_raw6_input(&src,&dst,next,data,payload,ifindex,ip[7]); - if(!net_udp6_input(&src,&dst,net_get_u16(data),net_get_u16(data+2),data+8,payload-8,ifindex,ip[7])) - ipv6_error(ip,total,1,4,0,false,ifindex); + net_raw6_input(state->net_ns, &src,&dst,next,data,payload,ifindex,ip[7]); + if(!net_udp6_input(state->net_ns, &src,&dst,net_get_u16(data),net_get_u16(data+2),data+8,payload-8,ifindex,ip[7])) + ipv6_error(state,ip,total,1,4,0,false,ifindex); }else if(next==6){ if(payload<20 || (data[12]>>4)<5 || (uint32_t)(data[12]>>4)*4u>payload || net_ipv6_checksum(&src,&dst,6,data,payload))return; - net_raw6_input(&src,&dst,next,data,payload,ifindex,ip[7]);net_tcp6_input(&src,&dst,data,payload,ifindex); + net_raw6_input(state->net_ns, &src,&dst,next,data,payload,ifindex,ip[7]);net_tcp6_input(state->net_ns, &src,&dst,data,payload,ifindex); }else if(next==58){ if(payload<8 || net_ipv6_checksum(&src,&dst,58,data,payload))return; /* RFC 6980: fragmented Neighbor Discovery must not reach raw consumers either. */ if(fragmented && data[0]>=133 && data[0]<=137)return; - net_raw6_input(&src,&dst,next,data,payload,ifindex,ip[7]); - if(data[0]==130 && ifindex!=1 && !fragmented)ipv6_mld_query(ifindex,ip,data,payload,router_alert); - ipv6_icmp(ip,total,data,payload,ifindex,mac,fragmented); + net_raw6_input(state->net_ns, &src,&dst,next,data,payload,ifindex,ip[7]); + if(data[0]==130 && ifindex!=1 && !fragmented)ipv6_mld_query(state,ifindex,ip,data,payload,router_alert); + ipv6_icmp(state,ip,total,data,payload,ifindex,mac,fragmented); }else{ - net_raw6_input(&src,&dst,next,data,payload,ifindex,ip[7]);ipv6_error(ip,total,4,1,previous,false,ifindex); + net_raw6_input(state->net_ns, &src,&dst,next,data,payload,ifindex,ip[7]);ipv6_error(state,ip,total,4,1,previous,false,ifindex); } } -/** @brief Process one complete IPv6 Ethernet frame on its receiving interface. */ -void net_ipv6_input_on(uint32_t ifindex,const uint8_t *frame,uint32_t length) +/** @brief Process one complete IPv6 Ethernet frame on its receiving interface. + * @param ns Borrowed network, NULL for the permanent initial network. + */ +void net_ipv6_input_on(struct net_namespace *ns, uint32_t ifindex,const uint8_t *frame,uint32_t length) { - struct ipv6_link *link=ipv6_link(ifindex,false); + struct net_ipv6_state *state = net_ipv6_state_get(ns); + struct ipv6_link *link=ipv6_link(state,ifindex,false); if(!frame || length<54 || net_get_u16(frame+12)!=IPV6_ETHERTYPE || - !link || !link->up || !net_interface_is_ready(NULL, ifindex))return; - ipv6_receive_ip(frame+14,length-14,ifindex,frame+6,false); + !link || !link->up || !net_interface_is_ready(state->net_ns, ifindex))return; + ipv6_receive_ip(state,frame+14,length-14,ifindex,frame+6,false); } void net_ipv6_input(const uint8_t *frame,uint32_t length) -{ net_ipv6_input_on(ipv6_default_interface(),frame,length); } +{ net_ipv6_input_on(NULL, ipv6_default_interface(net_ipv6_state_get(NULL)),frame,length); } -/** @brief Return a usable link-local source on one Ethernet interface. */ -static const struct in6_addr *ipv6_link_source(uint32_t ifindex) +/** @brief Return a usable link-local source on one Ethernet interface. + * @param state Borrowed protocol owner under network execution ownership. + * @param ifindex Stable interface index within this network. + * @return Borrowed usable address, or NULL when none is assigned. + */ +static const struct in6_addr *ipv6_link_source(struct net_ipv6_state *state, uint32_t ifindex) { - for(uint32_t i=0;iaddresses[i].used && state->addresses[i].value.ifindex==ifindex && + ipv6_linklocal(&state->addresses[i].value.address) && + !(state->addresses[i].value.flags&(NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED)))return &state->addresses[i].value.address; return 0; } -/** @brief Send one MLDv1/v2 group-state report with the mandatory Router Alert. */ -static bool ipv6_send_mld(struct ipv6_group_slot *group,bool query) +/** @brief Send one MLDv1/v2 group-state report with the mandatory Router Alert. + * @param state Borrowed protocol owner under network execution ownership. + * @param group Borrowed group state owned by this network. + * @param query Emit a current-state response when true, otherwise a membership transition. + * @return True when the report was sent or no report is required. + */ +static bool ipv6_send_mld(struct net_ipv6_state *state, struct ipv6_group_slot *group,bool query) { if(group->ifindex==1 || (group->address.s6_addr[1]&15)<=1 || ipv6_equal(&group->address,&ipv6_all_nodes))return true; - struct ipv6_link *link=ipv6_link(group->ifindex,false); + struct ipv6_link *link=ipv6_link(state,group->ifindex,false); if(!link || !link->up)return false; - const struct in6_addr *source=ipv6_link_source(group->ifindex);if(!source)source=&ipv6_zero; + const struct in6_addr *source=ipv6_link_source(state,group->ifindex);if(!source)source=&ipv6_zero; bool v1=time_uptime_ms()mld_v1_until; struct in6_addr dest=v1?(group->refs?group->address:ipv6_all_routers):ipv6_mld_routers; uint8_t payload[36]={58,0,5,2,0,0,1,0};uint8_t *icmp=payload+8;uint32_t n; @@ -1058,33 +1084,73 @@ static bool ipv6_send_mld(struct ipv6_group_slot *group,bool query) else{n=28;icmp[0]=143;net_put_u16(icmp+6,1);icmp[8]=(uint8_t)(group->refs?(query?2:4):3); net_memcpy(icmp+12,group->address.s6_addr,16);} net_put_u16(icmp+2,net_ipv6_checksum(source,&dest,58,icmp,n));uint8_t mac[6];ipv6_multicast_mac(mac,&dest); - return ipv6_send_frame(group->ifindex,mac,source,&dest,0,1,0,payload,n+8)>=0; -} -/** @brief Tear down only the state owned by one link. */ -static void ipv6_clear_link_state(uint32_t ifindex) -{ - for(uint32_t i=0;iifindex,mac,source,&dest,0,1,0,payload,n+8)>=0; +} +/** @brief Tear down only the state owned by one link. + * @param state Borrowed protocol owner under network execution ownership. + * @param ifindex Stable interface index within this network. + */ +static void ipv6_clear_link_state(struct net_ipv6_state *state, uint32_t ifindex) +{ + for(uint32_t i=0;ipending[i].used && state->pending[i].path.ifindex==ifindex){ + ipv6_pending_error(state,&state->pending[i],LINUX_ENETDOWN);kernel_free(state->pending[i].data);state->pending[i].used=false;} + for(uint32_t i=0;ireassembly[i].used && state->reassembly[i].ifindex==ifindex) + ipv6_reassembly_clear(&state->reassembly[i]); + for(uint32_t i=0;iaddresses[i].used && state->addresses[i].value.ifindex==ifindex)state->addresses[i].used=false; + for(uint32_t i=0;iroutes[i].used && state->routes[i].value.ifindex==ifindex)state->routes[i].used=false; + for(uint32_t i=0;igroups[i].used && state->groups[i].ifindex==ifindex)state->groups[i].used=false; + for(uint32_t i=0;ineighbors[i].used && state->neighbors[i].value.ifindex==ifindex)state->neighbors[i].used=false; + for(uint32_t i=0;ipmtu[i].used && state->pmtu[i].ifindex==ifindex)state->pmtu[i].used=false; + netlink_ipv6_changed(state->net_ns); +} +/** @brief Configure the loopback address and route after checking both table capacities. + * @param state Borrowed protocol owner under execution ownership. + * @return Zero or ENOBUFS, preserving both tables on capacity failure. + */ +static int ipv6_loopback_up(struct net_ipv6_state *state) +{ + bool address_room = false, route_room = false; + for (uint32_t i = 0; i < IPV6_ADDR_MAX; ++i) + if (!state->addresses[i].used || + (state->addresses[i].value.ifindex == NET_IPV6_IF_LOOPBACK && + ipv6_equal(&state->addresses[i].value.address, &ipv6_loop))) address_room = true; + for (uint32_t i = 0; i < IPV6_ROUTE_MAX; ++i) + if (!state->routes[i].used || + (state->routes[i].value.ifindex == NET_IPV6_IF_LOOPBACK && + state->routes[i].value.prefix_length == 128 && + ipv6_equal(&state->routes[i].value.destination, &ipv6_loop) && + ipv6_unspecified(&state->routes[i].value.gateway))) route_room = true; + if (!address_room || !route_room) return -LINUX_ENOBUFS; + struct net_ipv6_address loop = {.address = ipv6_loop, .ifindex = NET_IPV6_IF_LOOPBACK, + .prefix_length = 128, .flags = NET_IPV6_ADDR_PERMANENT | NET_IPV6_ADDR_NODAD, + .preferred_until = IPV6_FOREVER, .valid_until = IPV6_FOREVER}; + struct net_ipv6_route route = {.destination = ipv6_loop, .ifindex = NET_IPV6_IF_LOOPBACK, + .prefix_length = 128, .valid_until = IPV6_FOREVER, .flags = RTF_UP | RTF_HOST}; + (void)net_ipv6_address_update(state->net_ns, &loop, false); + return net_ipv6_route_update(state->net_ns, &route, false); +} + +/** @brief Apply administrative/carrier state to this network's loopback or Ethernet link. + * @param ns Borrowed network, NULL for the permanent initial network. + * @param ifindex Stable index in this network. @param up New administrative state. + * @return Zero or negative errno, leaving loopback tables intact on capacity failure. + */ +int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t ifindex,bool up) +{ + struct net_ipv6_state *state = net_ipv6_state_get(ns); + if(!state->initialized)return 0; + if(!net_interface_exists(state->net_ns, ifindex))return -LINUX_ENODEV; + if (ifindex == NET_IPV6_IF_LOOPBACK) { + if (up) return ipv6_loopback_up(state); + ipv6_clear_link_state(state, ifindex); + return 0; + } bool enabled=up && netdev_is_ready(ifindex); - struct ipv6_link *link=ipv6_link(ifindex,enabled); + struct ipv6_link *link=ipv6_link(state,ifindex,enabled); if(!link)return enabled?-LINUX_ENOMEM:0; if(enabled==link->up)return 0; link->up=enabled; - if(!enabled){ipv6_clear_link_state(ifindex);return 0;} + if(!enabled){ipv6_clear_link_state(state,ifindex);return 0;} link->mtu=IPV6_LINK_MTU;link->rng_state=0;link->mld_v1_until=0; ipv6_reset_timing(link); const uint8_t *mac=netdev_mac(ifindex);struct net_ipv6_address a={0};a.address.s6_addr[0]=0xfe;a.address.s6_addr[1]=0x80; @@ -1092,130 +1158,145 @@ int net_ipv6_link_changed_on(uint32_t ifindex,bool up) a.address.s6_addr[11]=0xff;a.address.s6_addr[12]=0xfe;a.address.s6_addr[13]=mac[3]; a.address.s6_addr[14]=mac[4];a.address.s6_addr[15]=mac[5];a.ifindex=ifindex;a.prefix_length=64; a.flags=NET_IPV6_ADDR_PERMANENT;a.preferred_until=a.valid_until=IPV6_FOREVER; - (void)net_ipv6_address_update(&a,false); + (void)net_ipv6_address_update(state->net_ns, &a,false); struct in6_addr prefix={.s6_addr={0xfe,0x80}}; - ipv6_auto_route(ifindex,&prefix,64,&ipv6_zero,IPV6_FOREVER,256,false); + ipv6_auto_route(state,ifindex,&prefix,64,&ipv6_zero,IPV6_FOREVER,256,false); link->rs_at=IPV6_FOREVER;link->rs_sent=0; return 0; } +/** @copydoc net_ipv6_link_changed */ void net_ipv6_link_changed(bool up) -{ (void)net_ipv6_link_changed_on(ipv6_default_interface(),up); } -/** @brief Retire all state for the detached interface, even after registry removal. */ -void net_ipv6_detached_on(uint32_t ifindex) +{ (void)net_ipv6_link_changed_on(NULL, ipv6_default_interface(net_ipv6_state_get(NULL)),up); } +/** @brief Retire all state for the detached interface, even after registry removal. + * @param ns Borrowed network, NULL for the permanent initial network. + * @param ifindex Stable interface index, including after registry removal. + */ +void net_ipv6_detached_on(struct net_namespace *ns, uint32_t ifindex) { - if(!ipv6_initialized || ifindex==1)return; - ipv6_clear_link_state(ifindex); - struct ipv6_link **link=&ipv6_links; + struct net_ipv6_state *state = net_ipv6_state_get(ns); + if(!state->initialized || ifindex==1)return; + ipv6_clear_link_state(state,ifindex); + struct ipv6_link **link=&state->links; while(*link && (*link)->ifindex!=ifindex)link=&(*link)->next; if(*link){struct ipv6_link *removed=*link;*link=removed->next;kernel_free(removed);} } +/** @copydoc net_ipv6_detached */ void net_ipv6_detached(void) -{ net_ipv6_detached_on(ipv6_default_interface()); } -/** @brief Initialize loopback and every currently published Ethernet interface. */ +{ net_ipv6_detached_on(NULL, ipv6_default_interface(net_ipv6_state_get(NULL))); } +/** @copydoc net_ipv6_init */ void net_ipv6_init(void) { - if(ipv6_initialized){ - for(uint32_t i=0;inext;kernel_free(old);} - net_memzero(ipv6_addrs,sizeof(ipv6_addrs));net_memzero(ipv6_routes,sizeof(ipv6_routes)); - net_memzero(ipv6_neighbors,sizeof(ipv6_neighbors));net_memzero(ipv6_groups,sizeof(ipv6_groups)); - net_memzero(ipv6_pending,sizeof(ipv6_pending));net_memzero(ipv6_reassembly,sizeof(ipv6_reassembly)); - net_memzero(ipv6_pmtu,sizeof(ipv6_pmtu)); - ipv6_initialized=true;ipv6_frag_id=0;ipv6_error_at=0;ipv6_error_count=0; - struct net_ipv6_address loop={0};loop.address=ipv6_loop;loop.ifindex=1;loop.prefix_length=128; - loop.flags=NET_IPV6_ADDR_PERMANENT|NET_IPV6_ADDR_NODAD;loop.preferred_until=loop.valid_until=IPV6_FOREVER; - (void)net_ipv6_address_update(&loop,false); - struct net_ipv6_route route={0};route.destination=ipv6_loop;route.ifindex=1;route.prefix_length=128; - route.valid_until=IPV6_FOREVER;route.flags=RTF_UP|RTF_HOST;(void)net_ipv6_route_update(&route,false); - for(uint32_t i=netdev_next(0);i;i=netdev_next(i))(void)net_ipv6_link_changed_on(i,net_interface_is_up(NULL, i)); -} -/** @brief Check if task-context receive or timer service should continue. */ + struct net_ipv6_state *state = net_ipv6_state_get(NULL); + net_ipv6_state_reset(state); + state->initialized = true; + if (net_interface_is_up(NULL, NET_IPV6_IF_LOOPBACK)) (void)ipv6_loopback_up(state); + for(uint32_t i=netdev_next(0);i;i=netdev_next(i))(void)net_ipv6_link_changed_on(state->net_ns, i,net_interface_is_up(NULL, i)); +} +/** @copydoc net_ipv6_maintenance_pending */ bool net_ipv6_maintenance_pending(void) { - if(ipv6_initialized)for(uint32_t i=netdev_next(0);i;i=netdev_next(i)) - if(net_interface_is_ready(NULL, i))return true; - for(uint32_t i=0;iinitialized) for (uint32_t i=netdev_next(0);i;i=netdev_next(i)) + if (net_interface_is_ready(NULL, i)) return true; + for (struct net_ipv6_state *state=initial;state;state=state->next) + for (uint32_t i=0;ipending[i].used && state->pending[i].loopback) return true; return false; } /** @brief Deliver a retained packet locally without recursing into a socket send call. + * @param state Borrowed protocol owner under network execution ownership. * @param p Owned pending packet, detached from the queue before transport delivery. */ -static void ipv6_loop_deliver(struct ipv6_pending *p) +static void ipv6_loop_deliver(struct net_ipv6_state *state, struct ipv6_pending *p) { - uint8_t *packet=kernel_malloc(40u+p->length);if(!packet){ipv6_pending_error(p,LINUX_ENOMEM);return;} + uint8_t *packet=kernel_malloc(40u+p->length);if(!packet){ipv6_pending_error(state,p,LINUX_ENOMEM);return;} net_memzero(packet,40);packet[0]=0x60;net_put_u16(packet+4,(uint16_t)p->length);packet[6]=p->protocol; packet[7]=(uint8_t)(p->hops<0?64:p->hops);net_memcpy(packet+8,p->path.source.s6_addr,16); net_memcpy(packet+24,p->path.destination.s6_addr,16);if(p->length)net_memcpy(packet+40,p->data,p->length); - ipv6_receive_ip(packet,40u+p->length,p->path.ifindex,0,false);kernel_free(packet); + ipv6_receive_ip(state,packet,40u+p->length,p->path.ifindex,0,false);kernel_free(packet); } -/** @brief Advance bounded address, neighbor, listener, reassembly and deferred-loopback work. */ -void net_ipv6_poll(void) +/** @brief Advance bounded address, neighbor, listener, reassembly and deferred-loopback work. + * @param state Borrowed protocol owner under network execution ownership. + */ +static void ipv6_poll_state(struct net_ipv6_state *state) { - if(!ipv6_initialized)return; - for(uint32_t i=netdev_next(0);i;i=netdev_next(i)){ - struct ipv6_link *link=ipv6_link(i,false); - bool up=net_interface_is_ready(NULL, i); - if((link && link->up)!=up)(void)net_ipv6_link_changed_on(i,up); + if(!state->initialized)return; + for(uint32_t i=state->net_ns?0:netdev_next(0);i;i=netdev_next(i)){ + struct ipv6_link *link=ipv6_link(state,i,false); + bool up=net_interface_is_ready(state->net_ns, i); + if((link && link->up)!=up)(void)net_ipv6_link_changed_on(state->net_ns, i,up); } uint64_t now=time_uptime_ms(); - for(uint32_t i=0;inext) + for(uint32_t i=0;ipending[i].used && state->pending[i].loopback){ + struct ipv6_pending p=state->pending[i];state->pending[i].used=false;ipv6_loop_deliver(state,&p);kernel_free(p.data);} + for(struct ipv6_link *link=state->links;link;link=link->next) if(link->up && now>=link->reachable_refresh)ipv6_refresh_reachable(link); /* Report a new solicited-node membership before sending its DAD probe. */ for(uint32_t i=0;iused)continue; - struct ipv6_link *link=ipv6_link(g->ifindex,false); + struct ipv6_group_slot *g=&state->groups[i];if(!g->used)continue; + struct ipv6_link *link=ipv6_link(state,g->ifindex,false); if(g->ifindex!=1 && (!link || !link->up))continue; - if(g->query_pending && now>=g->query_at && ipv6_send_mld(g,true))g->query_pending=false; - if(g->reports && now>=g->report_at && ipv6_send_mld(g,false)){ + if(g->query_pending && now>=g->query_at && ipv6_send_mld(state,g,true))g->query_pending=false; + if(g->reports && now>=g->report_at && ipv6_send_mld(state,g,false)){ --g->reports;g->report_at=now+(link?ipv6_jitter(link,1000):0); if(!g->reports && !g->refs)g->used=false; } } for(uint32_t i=0;iused)continue; + struct ipv6_address_slot *a=&state->addresses[i];if(!a->used)continue; if(ipv6_expired(a->value.valid_until,now)){struct net_ipv6_address old=a->value; - (void)net_ipv6_address_update(&old,true);continue;} + (void)net_ipv6_address_update(state->net_ns, &old,true);continue;} if(!(a->value.flags&NET_IPV6_ADDR_DEPRECATED) && ipv6_expired(a->value.preferred_until,now)){ - a->value.flags|=NET_IPV6_ADDR_DEPRECATED;netlink_ipv6_changed();} - struct ipv6_link *link=ipv6_link(a->value.ifindex,false); + a->value.flags|=NET_IPV6_ADDR_DEPRECATED;netlink_ipv6_changed(state->net_ns);} + struct ipv6_link *link=ipv6_link(state,a->value.ifindex,false); if(link && link->up && (a->value.flags&NET_IPV6_ADDR_TENTATIVE) && now>=a->dad_at){ if(!a->dad_sent && a->dad_wait_mld){struct in6_addr group;ipv6_solicited(&group,&a->value.address); - struct ipv6_group_slot *g=ipv6_find_group(&group,a->value.ifindex); + struct ipv6_group_slot *g=ipv6_find_group(state,&group,a->value.ifindex); if(g && g->reports==2)continue; a->dad_wait_mld=false;} - if(!a->dad_sent){if(ipv6_send_ns(a->value.ifindex,&a->value.address,&ipv6_zero,0)>=0){ + if(!a->dad_sent){if(ipv6_send_ns(state,a->value.ifindex,&a->value.address,&ipv6_zero,0)>=0){ a->dad_sent=true;a->dad_at=now+link->retrans_ms;}} - else{a->value.flags&=~NET_IPV6_ADDR_TENTATIVE;netlink_ipv6_changed();} + else{a->value.flags&=~NET_IPV6_ADDR_TENTATIVE;netlink_ipv6_changed(state->net_ns);} } } - for(uint32_t i=0;inext){ + for(uint32_t i=0;iroutes[i].used && ipv6_expired(state->routes[i].value.valid_until,now)){ + state->routes[i].used=false;netlink_ipv6_changed(state->net_ns);} + for(uint32_t i=0;ireassembly[i].used && ipv6_expired(state->reassembly[i].deadline,now)) + ipv6_reassembly_expire(state,&state->reassembly[i]); + for(struct ipv6_link *link=state->links;link;link=link->next){ if(!link->up)continue; - const struct in6_addr *source=ipv6_link_source(link->ifindex); + const struct in6_addr *source=ipv6_link_source(state,link->ifindex); if(source && !link->rs_sent && link->rs_at==IPV6_FOREVER)link->rs_at=now+ipv6_jitter(link,1000); - if(source && link->rs_sent<3 && now>=link->rs_at && ipv6_send_rs(link->ifindex,source)>=0){ + if(source && link->rs_sent<3 && now>=link->rs_at && ipv6_send_rs(state,link->ifindex,source)>=0){ ++link->rs_sent;link->rs_at=now+4000;} } for(uint32_t i=0;iused || nowdeadline)continue; - struct ipv6_link *link=ipv6_link(n->value.ifindex,false);if(!link || !link->up)continue; - const struct in6_addr *source=ipv6_link_source(n->value.ifindex); - if(n->value.state==IPV6_NUD_REACHABLE){n->value.state=IPV6_NUD_STALE;netlink_ipv6_changed();} + struct ipv6_neighbor_slot *n=&state->neighbors[i];if(!n->used || nowdeadline)continue; + struct ipv6_link *link=ipv6_link(state,n->value.ifindex,false);if(!link || !link->up)continue; + const struct in6_addr *source=ipv6_link_source(state,n->value.ifindex); + if(n->value.state==IPV6_NUD_REACHABLE){n->value.state=IPV6_NUD_STALE;netlink_ipv6_changed(state->net_ns);} else if(n->value.state==IPV6_NUD_DELAY){n->value.state=IPV6_NUD_PROBE;n->probes=0;n->deadline=now;} if(n->value.state==IPV6_NUD_INCOMPLETE || n->value.state==IPV6_NUD_PROBE){ - if(n->probes>=3){n->value.state=IPV6_NUD_FAILED;netlink_ipv6_changed(); - for(uint32_t j=0;jvalue.ifindex && - ipv6_equal(&ipv6_pending[j].path.next_hop,&n->value.address)){ - ipv6_pending_error(&ipv6_pending[j],LINUX_EHOSTUNREACH);kernel_free(ipv6_pending[j].data);ipv6_pending[j].used=false;} - }else if(source){(void)ipv6_send_ns(n->value.ifindex,&n->value.address,source, + if(n->probes>=3){n->value.state=IPV6_NUD_FAILED;netlink_ipv6_changed(state->net_ns); + for(uint32_t j=0;jpending[j].used && !state->pending[j].loopback && + state->pending[j].path.ifindex==n->value.ifindex && + ipv6_equal(&state->pending[j].path.next_hop,&n->value.address)){ + ipv6_pending_error(state,&state->pending[j],LINUX_EHOSTUNREACH);kernel_free(state->pending[j].data);state->pending[j].used=false;} + }else if(source){(void)ipv6_send_ns(state,n->value.ifindex,&n->value.address,source, n->value.state==IPV6_NUD_PROBE?n->value.mac:0);++n->probes;n->deadline=now+link->retrans_ms;} } } } + +/** @copydoc net_ipv6_poll */ +void net_ipv6_poll(void) +{ + struct net_ipv6_state *state = net_ipv6_state_get(NULL); + while (state) { + struct net_namespace *ns = net_namespace_get(state->net_ns); + ipv6_poll_state(state); + struct net_ipv6_state *next = state->next; + /* Read the successor before final put can unlink this state. */ + net_namespace_put(ns); + state = next; + } +} diff --git a/net/ipv6/internal.h b/net/ipv6/internal.h new file mode 100644 index 00000000..921719a8 --- /dev/null +++ b/net/ipv6/internal.h @@ -0,0 +1,102 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_NET_IPV6_INTERNAL_H +#define RELIEFNT_NET_IPV6_INTERNAL_H + +#include +#include + +#define IPV6_ADDR_MAX 16u +#define IPV6_ROUTE_MAX 24u +#define IPV6_NEIGH_MAX 16u +#define IPV6_GROUP_MAX 32u +#define IPV6_PENDING_MAX 8u +#define IPV6_REASM_MAX 4u +#define IPV6_PMTU_MAX 8u + +struct ipv6_address_slot { + struct net_ipv6_address value; + uint64_t dad_at; + bool used, autonomous, dad_sent, dad_wait_mld; +}; +struct ipv6_route_slot { + struct net_ipv6_route value; + uint64_t address_until, ra_until; + bool used, automatic; +}; +struct ipv6_neighbor_slot { + struct net_ipv6_neighbor value; + uint64_t deadline; + uint8_t probes; + bool used; +}; +struct ipv6_group_slot { + struct in6_addr address; + uint32_t ifindex, refs; + uint64_t report_at, query_at; + uint8_t reports; + bool used, query_pending; +}; +struct ipv6_pending { + struct net_ipv6_path path; + uint8_t *data; + uint32_t length, flowinfo; + int hops; + uint8_t protocol; + bool used, loopback, dont_fragment; +}; +struct ipv6_reassembly { + struct in6_addr source, destination; + uint8_t *data, *bitmap, *prefix; + uint32_t identification, ifindex, covered, total, highwater, prefix_len, prev_next; + uint64_t deadline; + uint8_t next; + bool used, poisoned, have_first, have_last; +}; +struct ipv6_pmtu { + struct in6_addr destination; + uint64_t deadline; + uint32_t ifindex, mtu; + bool used; +}; + +/* Indexes are stable identifiers, not dense array positions. */ +struct ipv6_link { + struct ipv6_link *next; + uint32_t ifindex, mtu, rng_state, base_reachable_ms, retrans_ms; + uint64_t reachable_ms, reachable_refresh, rs_at, mld_v1_until; + uint8_t rs_sent; + bool up; +}; +/** @brief Protocol tables and deferred work owned by one network namespace. + * Execution ownership serializes the borrowed namespace and maintenance links. + * A servicing poll owns a namespace reference across transport callbacks. + */ +struct net_ipv6_state { + struct net_ipv6_state *next; + struct net_namespace *net_ns; + struct ipv6_address_slot addresses[IPV6_ADDR_MAX]; + struct ipv6_route_slot routes[IPV6_ROUTE_MAX]; + struct ipv6_neighbor_slot neighbors[IPV6_NEIGH_MAX]; + struct ipv6_group_slot groups[IPV6_GROUP_MAX]; + struct ipv6_pending pending[IPV6_PENDING_MAX]; + struct ipv6_reassembly reassembly[IPV6_REASM_MAX]; + struct ipv6_pmtu pmtu[IPV6_PMTU_MAX]; + struct ipv6_link *links; + uint64_t error_at; + uint32_t frag_id; + uint8_t error_count; + bool initialized; +}; + +/** @brief Borrow a network's protocol state under execution ownership. + * @param ns Live network, NULL for the permanent initial network. + * @return Borrowed state, valid while the namespace remains retained. + */ +struct net_ipv6_state *net_ipv6_state_get(struct net_namespace *ns); + +/** @brief Release protocol-owned allocations while preserving identity and list links. + * @param state Borrowed state under execution ownership, with no callback in flight. + */ +void net_ipv6_state_reset(struct net_ipv6_state *state); + +#endif diff --git a/net/ipv6/state.c b/net/ipv6/state.c new file mode 100644 index 00000000..4609ffb4 --- /dev/null +++ b/net/ipv6/state.c @@ -0,0 +1,50 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "internal.h" +#include + +static struct net_ipv6_state initial_state; + +/** @copydoc net_ipv6_state_get */ +struct net_ipv6_state *net_ipv6_state_get(struct net_namespace *ns) +{ + return ns ? ns->ipv6 : &initial_state; +} + +/** @copydoc net_ipv6_state_create */ +struct net_ipv6_state *net_ipv6_state_create(struct net_namespace *ns) +{ + struct net_ipv6_state *state = kernel_malloc(sizeof(*state)); + if (!state) return NULL; + *state = (struct net_ipv6_state){.net_ns = ns, .initialized = true, + .next = initial_state.next}; + initial_state.next = state; + return state; +} + +/** @copydoc net_ipv6_state_reset */ +void net_ipv6_state_reset(struct net_ipv6_state *state) +{ + for (uint32_t i = 0; i < IPV6_PENDING_MAX; ++i) + if (state->pending[i].used) kernel_free(state->pending[i].data); + for (uint32_t i = 0; i < IPV6_REASM_MAX; ++i) { + kernel_free(state->reassembly[i].data); + kernel_free(state->reassembly[i].bitmap); + kernel_free(state->reassembly[i].prefix); + } + while (state->links) { + struct ipv6_link *link = state->links; + state->links = link->next; + kernel_free(link); + } + *state = (struct net_ipv6_state){.net_ns = state->net_ns, .next = state->next}; +} + +/** @copydoc net_ipv6_state_destroy */ +void net_ipv6_state_destroy(struct net_ipv6_state *state) +{ + struct net_ipv6_state **slot = &initial_state.next; + while (*slot && *slot != state) slot = &(*slot)->next; + if (*slot) *slot = state->next; + net_ipv6_state_reset(state); + kernel_free(state); +} diff --git a/net/namespace/namespace.c b/net/namespace/namespace.c index 7cc46ad8..f5e77601 100644 --- a/net/namespace/namespace.c +++ b/net/namespace/namespace.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include +#include #include #include #include @@ -13,6 +14,12 @@ int net_namespace_create(struct user_namespace *owner, struct net_namespace **ou if (!ns) return -LINUX_ENOMEM; *ns = (struct net_namespace){.references = 1, .user_ns = user_namespace_get(owner), .loopback = {.index = NET_IF_LOOPBACK}}; + ns->ipv6 = net_ipv6_state_create(ns); + if (!ns->ipv6) { + user_namespace_put(ns->user_ns); + kernel_free(ns); + return -LINUX_ENOMEM; + } *out = ns; return 0; } @@ -28,6 +35,7 @@ struct net_namespace *net_namespace_get(struct net_namespace *ns) void net_namespace_put(struct net_namespace *ns) { if (!ns || __atomic_sub_fetch(&ns->references, 1, __ATOMIC_ACQ_REL)) return; + net_ipv6_state_destroy(ns->ipv6); while (ns->interfaces) { struct net_interface *iface = ns->interfaces; ns->interfaces = iface->next; diff --git a/net/proc.c b/net/proc.c index d20f0092..ce8c7dab 100644 --- a/net/proc.c +++ b/net/proc.c @@ -22,19 +22,20 @@ static uint32_t proc_ipv6_scope(uint32_t scope) } /** @brief Render a snapshot of the currently assigned IPv6 addresses. + * @param ns Borrowed network, NULL for the initial network. * @param s Output stream. @return Zero or a memory allocation error. */ -static int proc_ipv6_addresses(struct text_stream *s) +static int proc_ipv6_addresses(struct net_namespace *ns, struct text_stream *s) { - uint32_t count=net_ipv6_addresses(NULL,0); + uint32_t count=net_ipv6_addresses(ns, NULL,0); if (!count) return 0; if (count > UINT32_MAX / sizeof(struct net_ipv6_address)) return -LINUX_ENOMEM; struct net_ipv6_address *entries=kernel_malloc((size_t)count*sizeof(*entries)); if (!entries) return -LINUX_ENOMEM; - if (net_ipv6_addresses(entries,count)>count) { kernel_free(entries); return -LINUX_EAGAIN; } + if (net_ipv6_addresses(ns, entries,count)>count) { kernel_free(entries); return -LINUX_EAGAIN; } for (uint32_t i=0;iifindex,name)) continue; + if (!net_interface_name(ns, a->ifindex,name)) continue; proc_ipv6(s,&a->address); text_string(s," "); text_hex(s,a->ifindex,2); text_string(s," "); text_hex(s,a->prefix_length,2); text_string(s," "); text_hex(s,proc_ipv6_scope(a->scope),2); @@ -45,20 +46,21 @@ static int proc_ipv6_addresses(struct text_stream *s) } /** @brief Render the current IPv6 routes in Linux's hexadecimal proc format. + * @param ns Borrowed network, NULL for the initial network. * @param s Output stream. @return Zero or a memory allocation error. */ -static int proc_ipv6_routes(struct text_stream *s) +static int proc_ipv6_routes(struct net_namespace *ns, struct text_stream *s) { - uint32_t count=net_ipv6_routes(NULL,0); + uint32_t count=net_ipv6_routes(ns, NULL,0); if (!count) return 0; if (count > UINT32_MAX / sizeof(struct net_ipv6_route)) return -LINUX_ENOMEM; struct net_ipv6_route *entries=kernel_malloc((size_t)count*sizeof(*entries)); if (!entries) return -LINUX_ENOMEM; - if (net_ipv6_routes(entries,count)>count) { kernel_free(entries); return -LINUX_EAGAIN; } + if (net_ipv6_routes(ns, entries,count)>count) { kernel_free(entries); return -LINUX_EAGAIN; } static const struct in6_addr zero; for (uint32_t i=0;iifindex,name)) continue; + if (!net_interface_name(ns, r->ifindex,name)) continue; proc_ipv6(s,&r->destination); text_string(s," "); text_hex(s,r->prefix_length,2); text_string(s," "); proc_ipv6(s,&zero); text_string(s," 00 "); proc_ipv6(s,&r->gateway); text_string(s," "); text_hex(s,r->metric,8); @@ -84,9 +86,9 @@ int net_proc_emit(struct text_stream *s, const char *leaf) struct task *task = sched_current_task(); struct net_namespace *ns = task ? task->net_ns : NULL; if (!__builtin_strcmp(leaf, "if_inet6")) - return ns ? 0 : proc_ipv6_addresses(s); + return proc_ipv6_addresses(ns, s); if (!__builtin_strcmp(leaf, "ipv6_route")) - return ns ? 0 : proc_ipv6_routes(s); + return proc_ipv6_routes(ns, s); if (!__builtin_strcmp(leaf, "tcp6") || !__builtin_strcmp(leaf, "udp6") || !__builtin_strcmp(leaf, "raw6")) { if (!ns) net_ipv6_transport_proc_emit(s,leaf); diff --git a/net/socket/netlink.c b/net/socket/netlink.c index 57e392b2..76d8b1ec 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -337,12 +337,12 @@ static int nl_route4(struct nl_builder *b, uint32_t seq, uint32_t destination, * @return Zero or allocation/budget error. */ static int nl_addresses(struct net_namespace *ns, struct net_ipv6_address **out, uint32_t *count) { - *out = NULL; *count = ns ? 0 : net_ipv6_addresses(NULL,0); + *out = NULL; *count = net_ipv6_addresses(ns, NULL,0); if (!*count) return 0; if (*count > NL_MESSAGE_MAX / sizeof(**out)) return -LINUX_ENOBUFS; *out = kernel_malloc((size_t)*count * sizeof(**out)); if (!*out) return -LINUX_ENOMEM; - if (net_ipv6_addresses(*out,*count) > *count) { kernel_free(*out); *out=NULL; return -LINUX_EAGAIN; } + if (net_ipv6_addresses(ns, *out,*count) > *count) { kernel_free(*out); *out=NULL; return -LINUX_EAGAIN; } return 0; } @@ -352,12 +352,12 @@ static int nl_addresses(struct net_namespace *ns, struct net_ipv6_address **out, * @return Zero or allocation/budget error. */ static int nl_routes(struct net_namespace *ns, struct net_ipv6_route **out, uint32_t *count) { - *out = NULL; *count = ns ? 0 : net_ipv6_routes(NULL,0); + *out = NULL; *count = net_ipv6_routes(ns, NULL,0); if (!*count) return 0; if (*count > NL_MESSAGE_MAX / sizeof(**out)) return -LINUX_ENOBUFS; *out = kernel_malloc((size_t)*count * sizeof(**out)); if (!*out) return -LINUX_ENOMEM; - if (net_ipv6_routes(*out,*count) > *count) { kernel_free(*out); *out=NULL; return -LINUX_EAGAIN; } + if (net_ipv6_routes(ns, *out,*count) > *count) { kernel_free(*out); *out=NULL; return -LINUX_EAGAIN; } return 0; } @@ -669,9 +669,9 @@ void netlink_network_changed(struct net_namespace *ns) } /** @copydoc netlink_ipv6_changed */ -void netlink_ipv6_changed(void) +void netlink_ipv6_changed(struct net_namespace *ns) { - netlink_network_changed(NULL); + netlink_network_changed(ns); } /** @brief Render a link, address or route dump from current network state. @@ -825,7 +825,6 @@ static int nl_change_link(struct net_namespace *ns, const struct nlmsghdr *h) bool up=(req.ifi_flags & IFF_UP)!=0; if (net_interface_is_up(ns, index)!=up) { rc=net_interface_set_up(ns, index,up); if (rc) return rc; - if (!ns && index!=NET_IF_LOOPBACK) net_ipv6_link_changed_on(index,up); netlink_network_changed(ns); } } @@ -898,7 +897,6 @@ static int nl_change_address(struct net_namespace *ns, const struct nlmsghdr *h, struct ifaddrmsg req; __builtin_memcpy(&req,h+1,sizeof(req)); if (req.ifa_family == AF_INET) return nl_change_address4(ns, h,&req,remove); if (req.ifa_family != AF_INET6) return -LINUX_EAFNOSUPPORT; - if (ns) return -LINUX_EOPNOTSUPP; if (!req.ifa_index || req.ifa_prefixlen > 128) return -LINUX_EINVAL; const struct rtattr *a[9]={0}; int rc=nl_parse_attrs((const uint8_t *)(h+1)+sizeof(req), @@ -943,7 +941,7 @@ static int nl_change_address(struct net_namespace *ns, const struct nlmsghdr *h, if (!remove && !found && (h->nlmsg_flags & NLM_F_REPLACE) && !(h->nlmsg_flags & NLM_F_CREATE)) return -LINUX_EADDRNOTAVAIL; if (remove && !found) return -LINUX_EADDRNOTAVAIL; - return net_ipv6_address_update(&entry,remove); + return net_ipv6_address_update(ns, &entry,remove); } /** @brief Apply an authorized IPv4 route request to its network's route table. @@ -1016,7 +1014,6 @@ static int nl_change_route(struct net_namespace *ns, const struct nlmsghdr *h, b struct rtmsg req; __builtin_memcpy(&req,h+1,sizeof(req)); if (req.rtm_family == AF_INET) return nl_change_route4(ns, h,&req,remove); if (req.rtm_family != AF_INET6) return -LINUX_EAFNOSUPPORT; - if (ns) return -LINUX_EOPNOTSUPP; if (req.rtm_dst_len > 128 || req.rtm_src_len || req.rtm_tos || req.rtm_flags || (req.rtm_table && req.rtm_table!=RT_TABLE_MAIN) || (req.rtm_type && req.rtm_type!=RTN_UNICAST)) return -LINUX_EOPNOTSUPP; @@ -1052,7 +1049,7 @@ static int nl_change_route(struct net_namespace *ns, const struct nlmsghdr *h, b if (!remove && !found && (h->nlmsg_flags & NLM_F_REPLACE) && !(h->nlmsg_flags & NLM_F_CREATE)) return -LINUX_ESRCH; if (remove && !found) return -LINUX_ESRCH; - return net_ipv6_route_update(&route,remove); + return net_ipv6_route_update(ns, &route,remove); } /** @brief Process one checked request and append its response or error. diff --git a/net/socket/packet.c b/net/socket/packet.c index 690b5ed8..a60a63fc 100644 --- a/net/socket/packet.c +++ b/net/socket/packet.c @@ -128,13 +128,15 @@ void net_packet_input_on(uint32_t ifindex, const void *input, uint32_t length) } /** @brief Queue a validated IPv6 upper-layer message for matching raw sockets. + * @param ns Borrowed network, NULL for the permanent initial network. * @param source Peer address. @param destination Local address. @param protocol Next header. * @param data Borrowed upper-layer bytes. @param length Byte count. @param ifindex Interface. * @param hops Received hop limit. */ -void net_raw6_input(const struct in6_addr *source, const struct in6_addr *destination, +void net_raw6_input(struct net_namespace *ns, const struct in6_addr *source, const struct in6_addr *destination, uint8_t protocol, const void *data, uint32_t length, uint32_t ifindex, uint8_t hops) { + if (ns) return; if (length > 65535) return; for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *s = sockets[i]; @@ -195,7 +197,7 @@ static int packet6_send(struct packet_socket *s, const void *data, uint32_t leng uint32_t scope = to.sin6_scope_id ? to.sin6_scope_id : (uint32_t)s->ifindex; if (!scope && to.sin6_addr.s6_addr[0] == 0xff) scope = s->multicast_if; struct net_ipv6_path path; - int ret = net_ipv6_route(&to.sin6_addr, scope, &s->local6, &path); + int ret = net_ipv6_route(NULL, &to.sin6_addr, scope, &s->local6, &path); if (ret < 0) return ret; uint8_t *copy = kernel_malloc(length ? length : 1); if (!copy) return -LINUX_ENOMEM; @@ -212,7 +214,7 @@ static int packet6_send(struct packet_socket *s, const void *data, uint32_t leng copy[offset] = (uint8_t)(checksum >> 8); copy[offset + 1] = (uint8_t)checksum; } int hops = to.sin6_addr.s6_addr[0] == 0xff ? s->multicast_hops : s->unicast_hops; - ret = net_ipv6_output(&path, (uint8_t)s->protocol, copy, length, hops, to.sin6_flowinfo, + ret = net_ipv6_output(NULL, &path, (uint8_t)s->protocol, copy, length, hops, to.sin6_flowinfo, s->dont_fragment || s->mtu_discover == IPV6_PMTUDISC_DO, s->multicast_loop); kernel_free(copy); return ret < 0 ? ret : (int)length; @@ -421,7 +423,7 @@ void task_packet_release(struct task_file *file) for (unsigned i = 0; i < PACKET_LIMIT; ++i) if (sockets[i] == s) sockets[i] = NULL; for (unsigned i = 0; i < 16; ++i) if (s->groups[i].used) - (void)net_ipv6_multicast_change(&s->groups[i].address, s->groups[i].ifindex, -1); + (void)net_ipv6_multicast_change(NULL, &s->groups[i].address, s->groups[i].ifindex, -1); while (s->head) { struct packet_message *m = s->head; s->head = m->next; kernel_free(m); } kernel_free(s); file->aux = 0; @@ -458,7 +460,7 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin if (join && slot != 16) return -LINUX_EADDRINUSE; if (!join && slot == 16) return -LINUX_EADDRNOTAVAIL; if (join && empty == 16) return -LINUX_ENOBUFS; - ret = net_ipv6_multicast_change(&group.ipv6mr_multiaddr, ifindex, join ? 1 : -1); + ret = net_ipv6_multicast_change(NULL, &group.ipv6mr_multiaddr, ifindex, join ? 1 : -1); if (ret < 0) return ret; if (join) { s->groups[empty].address = group.ipv6mr_multiaddr; s->groups[empty].ifindex = ifindex; s->groups[empty].used = true; } else s->groups[slot].used = false; @@ -503,7 +505,7 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin case IPV6_MTU: { if (!s->connected6) return -LINUX_ENOTCONN; struct net_ipv6_path path; - int ret = net_ipv6_route(&s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path); + int ret = net_ipv6_route(NULL, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path); if (ret < 0) return ret; value = (int)path.mtu; break; } @@ -625,7 +627,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, s->ping_id = id; } if (!packet6_any(&address.sin6_addr) && address.sin6_addr.s6_addr[0] != 0xff) { - struct net_ipv6_address entries[32]; uint32_t count = net_ipv6_addresses(entries, 32); bool found = false; + struct net_ipv6_address entries[32]; uint32_t count = net_ipv6_addresses(NULL, entries, 32); bool found = false; for (uint32_t i = 0; i < count && i < 32; ++i) if (!__builtin_memcmp(&entries[i].address, &address.sin6_addr, sizeof(address.sin6_addr)) && !(entries[i].flags & (NET_IPV6_ADDR_TENTATIVE | NET_IPV6_ADDR_DADFAILED)) && @@ -660,7 +662,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (number == __NR_getsockname && s->type == SOCK_DGRAM) address.sin6_port = __builtin_bswap16(s->ping_id); if (number == __NR_getsockname && s->connected6 && packet6_any(&address.sin6_addr)) { struct net_ipv6_path path; - if (!net_ipv6_route(&s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path)) address.sin6_addr = path.source; + if (!net_ipv6_route(NULL, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path)) address.sin6_addr = path.source; } if (length > sizeof(address)) length = sizeof(address); ret = socket_user_prepare(task, a1, length, true); if (ret) return ret; @@ -751,10 +753,12 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, } /** @brief Report ICMPv6 errors to the socket owning the quoted protocol tuple. + * @param ns Borrowed network, NULL for the permanent initial network. * @param packet Quoted original IPv6 packet. @param length Quote size. * @param error Positive Linux errno. @param mtu Reported path MTU or zero. */ -void net_ipv6_socket_error_on(uint32_t ifindex, const uint8_t *packet, uint32_t length, int error, uint32_t mtu) +void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex, const uint8_t *packet, uint32_t length, int error, uint32_t mtu) { + if (ns) return; if (!packet || length < 40 || packet[0] >> 4 != 6) return; struct in6_addr source, destination; __builtin_memcpy(&source, packet + 8, 16); __builtin_memcpy(&destination, packet + 24, 16); @@ -818,7 +822,7 @@ void net_packet_input(const void *input, uint32_t length) * @param packet Quote. @param length Bytes. @param error Errno. @param mtu MTU. */ void net_ipv6_socket_error(const uint8_t *packet, uint32_t length, int error, uint32_t mtu) { - net_ipv6_socket_error_on(0, packet, length, error, mtu); + net_ipv6_socket_error_on(NULL, 0, packet, length, error, mtu); } /** @brief Wake raw endpoints explicitly bound to a removed NIC. * @param ifindex Removed interface index. */ diff --git a/net/socket/udp.c b/net/socket/udp.c index 5268f3cf..124814d9 100644 --- a/net/socket/udp.c +++ b/net/socket/udp.c @@ -191,14 +191,16 @@ void net_udp_input(uint32_t source, uint32_t destination, uint16_t source_port, } /** @brief Queue a validated native IPv6 UDP datagram for a matching endpoint. + * @param ns Borrowed network, NULL for the permanent initial network. * @param source Network-order source. @param destination Network-order destination. * @param source_port Host-order source port. @param destination_port Host-order local port. * @param data Borrowed datagram bytes. @param length Byte count. @param ifindex Ingress interface. * @param hops Received hop limit. @return True if at least one socket accepted the datagram. */ -bool net_udp6_input(const struct in6_addr *source, const struct in6_addr *destination, +bool net_udp6_input(struct net_namespace *ns, const struct in6_addr *source, const struct in6_addr *destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length, uint32_t ifindex, uint8_t hops) { + if (ns) return false; if (length > UDP6_MAX_PAYLOAD) return false; bool delivered = false; for (struct udp_socket *s = sockets; s; s = s->registry_next) { @@ -304,7 +306,7 @@ static int udp6_bind(struct udp_socket *s, const struct sockaddr_in6 *address) return -LINUX_EINVAL; if (!udp6_any(ip) && !udp6_mapped(ip) && ip->s6_addr[0] != 0xff) { struct net_ipv6_address entries[32]; - uint32_t count = net_ipv6_addresses(entries, 32); + uint32_t count = net_ipv6_addresses(NULL, entries, 32); bool found = false; for (uint32_t i = 0; i < count && i < 32; ++i) if (!__builtin_memcmp(&entries[i].address, ip, sizeof(*ip)) && @@ -357,7 +359,7 @@ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, uint32_t scope = to.sin6_scope_id ? to.sin6_scope_id : (uint32_t)s->ifindex; if (!scope && to.sin6_addr.s6_addr[0] == 0xff) scope = s->multicast_if; struct net_ipv6_path path; - int ret = net_ipv6_route(&to.sin6_addr, scope, &s->local6, &path); + int ret = net_ipv6_route(NULL, &to.sin6_addr, scope, &s->local6, &path); if (ret < 0) return ret; if (!s->bound) { ret = bind_port(s, 0, 0); if (ret < 0) return ret; } uint8_t *packet = kernel_malloc(length + 8); @@ -371,7 +373,7 @@ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, if (!checksum) checksum = 0xffff; packet[6] = (uint8_t)(checksum >> 8); packet[7] = (uint8_t)checksum; int hops = to.sin6_addr.s6_addr[0] == 0xff ? s->multicast_hops : s->unicast_hops; - ret = net_ipv6_output(&path, 17, packet, length + 8, hops, to.sin6_flowinfo, + ret = net_ipv6_output(NULL, &path, 17, packet, length + 8, hops, to.sin6_flowinfo, s->dont_fragment || s->mtu_discover == IPV6_PMTUDISC_DO, s->multicast_loop); kernel_free(packet); return ret < 0 ? ret : (int)length; @@ -558,7 +560,7 @@ void task_udp_release(struct task_file *file) if (*link == s) *link = s->registry_next; for (unsigned i = 0; i < UDP6_GROUP_LIMIT; ++i) if (s->groups[i].used) - (void)net_ipv6_multicast_change(&s->groups[i].address, s->groups[i].ifindex, -1); + (void)net_ipv6_multicast_change(NULL, &s->groups[i].address, s->groups[i].ifindex, -1); while (s->head) { struct udp_packet *p = s->head; s->head = p->next; @@ -598,7 +600,7 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, if (join && slot != UDP6_GROUP_LIMIT) return -LINUX_EADDRINUSE; if (!join && slot == UDP6_GROUP_LIMIT) return -LINUX_EADDRNOTAVAIL; if (join && empty == UDP6_GROUP_LIMIT) return -LINUX_ENOBUFS; - ret = net_ipv6_multicast_change(&group.ipv6mr_multiaddr, ifindex, join ? 1 : -1); + ret = net_ipv6_multicast_change(NULL, &group.ipv6mr_multiaddr, ifindex, join ? 1 : -1); if (ret < 0) return ret; if (join) { s->groups[empty].address = group.ipv6mr_multiaddr; s->groups[empty].ifindex = ifindex; s->groups[empty].used = true; } else s->groups[slot].used = false; @@ -642,7 +644,7 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, case IPV6_MTU: { struct net_ipv6_path path; if (!s->connected || udp6_mapped(&s->remote6)) return -LINUX_ENOTCONN; - int ret = net_ipv6_route(&s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path); + int ret = net_ipv6_route(NULL, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path); if (ret < 0) return ret; value = (int)path.mtu; break; @@ -753,7 +755,7 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, address.sin6_addr = udp6_map(s->remote >> 24 == 127 ? 0x7f000001 : config.local_ip); } else { struct net_ipv6_path path; - if (!net_ipv6_route(&s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path)) address.sin6_addr = path.source; + if (!net_ipv6_route(NULL, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path)) address.sin6_addr = path.source; } } return udp6_export(a1, a2, &address); diff --git a/net/tcp/input.c b/net/tcp/input.c index ff3a0d0a..faa45a34 100644 --- a/net/tcp/input.c +++ b/net/tcp/input.c @@ -60,11 +60,13 @@ static uint16_t net_tcp6_syn_mss(const uint8_t *tcp, uint32_t header) } /** @brief Match and deliver a validated IPv6 TCP segment to the shared state machine. + * @param ns Borrowed network, NULL for the permanent initial network. * @param source Network-order peer. @param destination Network-order local address. * @param data Borrowed TCP bytes. @param length Segment bytes. @param ifindex Ingress interface. */ -void net_tcp6_input(const struct in6_addr *source, const struct in6_addr *destination, +void net_tcp6_input(struct net_namespace *ns, const struct in6_addr *source, const struct in6_addr *destination, const void *data, uint32_t length, uint32_t ifindex) { + if (ns) return; const uint8_t *tcp = data; if (length < 20) return; uint32_t header = (uint32_t)(tcp[12] >> 4) * 4u; diff --git a/net/tcp/output.c b/net/tcp/output.c index 51857334..bee35b62 100644 --- a/net/tcp/output.c +++ b/net/tcp/output.c @@ -202,7 +202,7 @@ int net_send_tcp_socket(struct net_socket *socket, uint32_t seq, uint32_t ack, if (socket->remote_scope6 && socket->bound_ifindex && socket->remote_scope6 != socket->bound_ifindex) return -LINUX_EINVAL; struct net_ipv6_path path; - int ret = net_ipv6_route(&socket->remote6, socket->remote_scope6 ? socket->remote_scope6 : socket->bound_ifindex, &socket->local6, &path); + int ret = net_ipv6_route(NULL, &socket->remote6, socket->remote_scope6 ? socket->remote_scope6 : socket->bound_ifindex, &socket->local6, &path); if (ret < 0) return ret; socket->mtu6 = path.mtu; socket->ifindex = path.ifindex; @@ -223,7 +223,7 @@ int net_send_tcp_socket(struct net_socket *socket, uint32_t seq, uint32_t ack, } if (length) net_memcpy(tcp + header, payload, length); net_put_u16(tcp + 16, net_ipv6_checksum(&path.source, &path.destination, 6, tcp, header + length)); - ret = net_ipv6_output(&path, 6, tcp, header + length, socket->unicast_hops, 0, + ret = net_ipv6_output(NULL, &path, 6, tcp, header + length, socket->unicast_hops, 0, socket->dont_fragment || socket->mtu_discover == IPV6_PMTUDISC_DO, true); if (ret >= 0 && (flags & TCP_FLAG_ACK)) { socket->rx_window_ack = ack; socket->rx_window = window; socket->rx_window_valid = true; diff --git a/net/tcp/socket.c b/net/tcp/socket.c index dfd96b05..2d416614 100644 --- a/net/tcp/socket.c +++ b/net/tcp/socket.c @@ -1376,7 +1376,7 @@ int net_socket_bind6_fd(int32_t handle, const struct sockaddr_in6 *address) if (!s->ipv6) return -LINUX_EAFNOSUPPORT; if (address->sin6_addr.s6_addr[0] == 0xfe && (address->sin6_addr.s6_addr[1] & 0xc0) == 0x80 && !scope) return -LINUX_EINVAL; - struct net_ipv6_address entries[32]; uint32_t count = net_ipv6_addresses(entries, 32); bool found = false; + struct net_ipv6_address entries[32]; uint32_t count = net_ipv6_addresses(NULL, entries, 32); bool found = false; for (uint32_t i = 0; i < count && i < 32; ++i) if (!__builtin_memcmp(&entries[i].address, &address->sin6_addr, sizeof(address->sin6_addr)) && !(entries[i].flags & (NET_IPV6_ADDR_TENTATIVE | NET_IPV6_ADDR_DADFAILED)) && @@ -1417,7 +1417,7 @@ int net_socket_connect6_fd(int32_t handle, const struct sockaddr_in6 *address, b return -LINUX_EINVAL; if (tcp6_mapped(&s->local6)) return -LINUX_ENETUNREACH; struct net_ipv6_path path; - int ret = net_ipv6_route(&address->sin6_addr, address->sin6_scope_id ? address->sin6_scope_id : s->bound_ifindex, &s->local6, &path); + int ret = net_ipv6_route(NULL, &address->sin6_addr, address->sin6_scope_id ? address->sin6_scope_id : s->bound_ifindex, &s->local6, &path); if (ret < 0) return ret; if (!s->bound) { ret = tcp_bind_port(s, 0, 0); if (ret < 0) return ret; } s->ifindex = path.ifindex; s->local6 = path.source; s->remote6 = address->sin6_addr; s->remote_scope6 = address->sin6_scope_id; @@ -1617,7 +1617,7 @@ struct net_socket *net_tcp_passive6(struct net_socket *listener,const struct in6 if (!listener || listener->state != NET_TCP_LISTEN || tcp_pending(listener, false) >= listener->backlog) return NULL; struct net_ipv6_path path; uint32_t scope = source->s6_addr[0] == 0xfe && (source->s6_addr[1] & 0xc0) == 0x80 ? ifindex : 0; - if (net_ipv6_route(source, scope, destination, &path) < 0) return NULL; + if (net_ipv6_route(NULL, source, scope, destination, &path) < 0) return NULL; struct net_socket *s = net_socket_alloc(listener->owner_pid, listener->owner_uid); if (!s) return NULL; s->ifindex = ifindex; s->bound_ifindex = listener->bound_ifindex; diff --git a/tools/test_eevdf.py b/tools/test_eevdf.py index f77e0b99..a9b666f9 100644 --- a/tools/test_eevdf.py +++ b/tools/test_eevdf.py @@ -1,11 +1,12 @@ #!/usr/bin/env python3 """Deterministic EEVDF tests using the kernel's actual integer policy.""" from pathlib import Path +import os import subprocess import tempfile ROOT = Path(__file__).resolve().parents[1] -tmp_root = ROOT / "out" / "tmp" +tmp_root = Path(os.environ.get("TMPDIR", ROOT / "out" / "tmp")) tmp_root.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix="reliefos-eevdf-", dir=tmp_root) as tmp: for name in ("eevdf", "eevdf_scheduler", "eevdf_rbtree"): diff --git a/tools/test_ipv6_control.py b/tools/test_ipv6_control.py index 53f21f1b..7b19a467 100644 --- a/tools/test_ipv6_control.py +++ b/tools/test_ipv6_control.py @@ -13,6 +13,6 @@ "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", "tools/tests/ipv6_control_test.c", "net/socket/filter.c", - "net/namespace/namespace.c", "kernel/sched/user_namespace.c", + "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) diff --git a/tools/test_ipv6_protocol.py b/tools/test_ipv6_protocol.py index b20ddc8c..d7c395f3 100644 --- a/tools/test_ipv6_protocol.py +++ b/tools/test_ipv6_protocol.py @@ -9,10 +9,12 @@ output.mkdir(parents=True, exist_ok=True) source = root / "net" / "ipv6" / "core.c" cmd = [os.environ.get("CC", "cc"), "-std=c11", "-Wall", "-Wextra", "-Werror", + "-g", "-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-fno-pie", "-no-pie", "-I" + str(root / "include"), "-I" + str(root / "include/uapi"), str(root / "tools/tests/ipv6_protocol_test.c")] if source.exists(): - cmd += [str(source), str(root / "net/link/ethernet.c"), str(root / "net/input.c")] + cmd += [str(source), str(root / "net/link/ethernet.c"), str(root / "net/input.c"), + str(root / "net/namespace/namespace.c"), str(root / "net/ipv6/state.c")] else: cmd += ["-DIPV6_NO_IMPLEMENTATION"] cmd += ["-o", str(output / "ipv6_protocol_test")] diff --git a/tools/test_ipv6_transport.py b/tools/test_ipv6_transport.py index 72caf7ad..94b8fa75 100644 --- a/tools/test_ipv6_transport.py +++ b/tools/test_ipv6_transport.py @@ -21,7 +21,7 @@ "tools/tests/ipv6_vector_test.c", "tools/tests/ipv6_vector_stubs.c", "kernel/syscall/io/vector.c", "kernel/syscall/ipc/socket.c", "kernel/sched/user_namespace.c", - "net/namespace/namespace.c", + "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/syscall/fs/lookup_state.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) binary = out / "ipv6_tcp_test" diff --git a/tools/test_linux_socket_batches.py b/tools/test_linux_socket_batches.py index 30dfe5e4..c834c457 100644 --- a/tools/test_linux_socket_batches.py +++ b/tools/test_linux_socket_batches.py @@ -17,7 +17,7 @@ subprocess.run(["cc", "-std=c11", "-g", "-O1", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude", "-Iinclude/uapi", - "-Iinclude", "tools/tests/socket_batch_unix_test.c", "kernel/sched/user_namespace.c", "net/namespace/namespace.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "-o", output], + "-Iinclude", "tools/tests/socket_batch_unix_test.c", "kernel/sched/user_namespace.c", "net/namespace/namespace.c", "net/ipv6/state.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "-o", output], cwd=root, check=True) subprocess.run([output], cwd=root, check=True, timeout=20) output = str(Path(directory) / "socket_batch_abi") diff --git a/tools/test_network.py b/tools/test_network.py index 2ae1894a..0a58ceb3 100644 --- a/tools/test_network.py +++ b/tools/test_network.py @@ -11,7 +11,7 @@ "-fsanitize=address,undefined", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", - f"tools/tests/{name}_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", + f"tools/tests/{name}_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=20) binary = Path(work) / "tcp_nodelay_probe" diff --git a/tools/test_poll_wakeup.py b/tools/test_poll_wakeup.py index 6e17fcc8..c6864eda 100644 --- a/tools/test_poll_wakeup.py +++ b/tools/test_poll_wakeup.py @@ -17,7 +17,7 @@ "-Iinclude", "tools/tests/poll_wakeup_test.c", *kernel_sources("syscall_dispatch"), "kernel/sched/identity.c", "kernel/syscall/process/pidfd.c", - "kernel/sched/user_namespace.c", "net/namespace/namespace.c", + "kernel/sched/user_namespace.c", "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/sync/wait.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "-o", str(binary), ], cwd=ROOT, check=True) subprocess.run([str(binary)], cwd=ROOT, check=True, timeout=20) diff --git a/tools/test_sched_resume.py b/tools/test_sched_resume.py index 00430e39..2f7ce843 100644 --- a/tools/test_sched_resume.py +++ b/tools/test_sched_resume.py @@ -14,11 +14,13 @@ def run_host_fixture() -> None: compiler = shutil.which("clang") or shutil.which("cc") if compiler is None: raise RuntimeError("a C compiler is required for the scheduler host fixture") + temporary = Path(os.environ.get("TMPDIR", ROOT / "out" / "tmp")) + temporary.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix="reliefos-sched-resume-", - dir=ROOT / "out" / "tmp") as directory: + dir=temporary) as directory: executable = str(Path(directory) / "sched-resume") env = os.environ.copy() - env["TMPDIR"] = str(ROOT / "out" / "tmp") + env["TMPDIR"] = str(temporary) subprocess.run([ compiler, "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-ffunction-sections", "-fdata-sections", diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 27402c34..3d80e0c8 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -20,6 +20,14 @@ static int allocation_fail_after = -1; static bool additional_address; static bool nic_ready=true; static bool nic_present=true; +/* Enabled only by the scoped control regression. */ +static struct { + struct net_namespace *ns; + struct net_ipv6_address address; + struct net_ipv6_route route; + bool has_address, has_route; + unsigned mutations; +} scoped_ipv6[2]; struct net_socket *net_sockets; struct task *sched_current_task(void) { return ¤t; } void *kernel_malloc(size_t bytes) @@ -64,7 +72,7 @@ void net_put_u32(uint8_t *p,uint32_t value) { p[0]=value>>24;p[1]=value>>16;p[2] void net_arp_cache_clear(void) {} void net_arp_cache_clear_on(uint32_t index) { (void)index; } void net_ipv6_link_changed(bool up) { (void)up; ++link_changes; } -int net_ipv6_link_changed_on(uint32_t index,bool up) { (void)index; (void)up; ++link_changes; return 0; } +int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index,bool up) { (void)ns; (void)index; (void)up; ++link_changes; return 0; } void net_device_counters(struct net_proc_counters *out) { memset(out,0,sizeof(*out)); } void net_loopback_proc_emit(struct text_stream *stream) { (void)stream; } void net_arp_proc_emit(struct text_stream *stream) { (void)stream; } @@ -72,8 +80,14 @@ void net_udp_proc_emit(struct text_stream *stream) { (void)stream; } void unix_proc_emit(struct text_stream *stream) { (void)stream; } void net_ipv6_transport_proc_emit(struct text_stream *stream,const char *leaf) { text_string(stream,leaf); text_string(stream,"\n"); } -uint32_t net_ipv6_addresses(struct net_ipv6_address *out, uint32_t capacity) +uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out, uint32_t capacity) { + for (unsigned i = 0; ns && i < 2; ++i) { + if (scoped_ipv6[i].ns != ns) continue; + if (capacity && scoped_ipv6[i].has_address) *out = scoped_ipv6[i].address; + return scoped_ipv6[i].has_address; + } + if (ns) return 0; struct net_ipv6_address a = {.address.s6_addr={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, .ifindex=1,.prefix_length=128,.flags=NET_IPV6_ADDR_PERMANENT,.scope=RT_SCOPE_HOST, .preferred_until=UINT64_MAX,.valid_until=UINT64_MAX}; @@ -85,17 +99,48 @@ uint32_t net_ipv6_addresses(struct net_ipv6_address *out, uint32_t capacity) } return 1+additional_address; } -uint32_t net_ipv6_routes(struct net_ipv6_route *out, uint32_t capacity) +uint32_t net_ipv6_routes(struct net_namespace *ns, struct net_ipv6_route *out, uint32_t capacity) { + for (unsigned i = 0; ns && i < 2; ++i) { + if (scoped_ipv6[i].ns != ns) continue; + if (capacity && scoped_ipv6[i].has_route) *out = scoped_ipv6[i].route; + return scoped_ipv6[i].has_route; + } + if (ns) return 0; struct net_ipv6_route r = {.destination.s6_addr={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, .prefix_length=128,.ifindex=1,.metric=256,.valid_until=UINT64_MAX}; if (capacity) *out = r; return 1; } -int net_ipv6_address_update(const struct net_ipv6_address *address, bool remove) -{ (void)remove; assert(address->ifindex == 2 && address->prefix_length == 64); ++updates; return 0; } -int net_ipv6_route_update(const struct net_ipv6_route *route, bool remove) -{ (void)route; (void)remove; ++updates; return 0; } +int net_ipv6_address_update(struct net_namespace *ns, const struct net_ipv6_address *address, bool remove) +{ + for (unsigned i = 0; ns && i < 2; ++i) { + if (scoped_ipv6[i].ns != ns) continue; + assert(address->ifindex == 1 && address->prefix_length == 64); + scoped_ipv6[i].address = *address; + scoped_ipv6[i].has_address = !remove; + ++scoped_ipv6[i].mutations; + netlink_ipv6_changed(ns); + return 0; + } + assert(address->ifindex == 2 && address->prefix_length == 64); + ++updates; + return 0; +} +int net_ipv6_route_update(struct net_namespace *ns, const struct net_ipv6_route *route, bool remove) +{ + for (unsigned i = 0; ns && i < 2; ++i) { + if (scoped_ipv6[i].ns != ns) continue; + assert(route->ifindex == 1 && route->prefix_length == 64); + scoped_ipv6[i].route = *route; + scoped_ipv6[i].has_route = !remove; + ++scoped_ipv6[i].mutations; + netlink_ipv6_changed(ns); + return 0; + } + ++updates; + return 0; +} static long call(uint64_t nr, uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { return syscall_netlink(nr,a,b,c,d,e,0); } @@ -313,12 +358,12 @@ static void check_netlink_namespace_events(void) assert(!call(__NR_bind, subscribers[i], (uintptr_t)&route_group, sizeof(route_group), 0, 0)); } additional_address = true; - netlink_ipv6_changed(); + netlink_ipv6_changed(NULL); assert(receive(subscribers[0], output, sizeof(output)) > 0); assert(receive(subscribers[1], output, sizeof(output)) == -LINUX_EAGAIN); assert(receive(subscribers[2], output, sizeof(output)) == -LINUX_EAGAIN); allocation_fail_after = 0; - netlink_ipv6_changed(); + netlink_ipv6_changed(NULL); allocation_fail_after = -1; assert(receive(subscribers[0], output, sizeof(output)) == -LINUX_ENOBUFS); assert(receive(subscribers[1], output, sizeof(output)) == -LINUX_EAGAIN); @@ -668,7 +713,7 @@ static void check_netlink_filter(void) assert(!call(__NR_bind, route, (uintptr_t)&address, sizeof(address), 0, 0)); assert(!call(__NR_setsockopt, route, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&route_filter, sizeof(route_filter))); additional_address = true; - netlink_ipv6_changed(); + netlink_ipv6_changed(NULL); assert(receive(route, output, sizeof(output)) == -LINUX_EAGAIN); assert(send_req(route, &request, sizeof(request)) == sizeof(request)); assert(receive(route, output, sizeof(output)) == -LINUX_EAGAIN); @@ -680,7 +725,7 @@ static void check_netlink_filter(void) route_filter.filter = truncate; assert(!call(__NR_setsockopt, route, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&route_filter, sizeof(route_filter))); additional_address = false; - netlink_ipv6_changed(); + netlink_ipv6_changed(NULL); assert(receive(route, output, sizeof(output)) == 4); assert(send_req(route, &request, sizeof(request)) == sizeof(request)); route_filter.filter = reject; @@ -947,6 +992,187 @@ static void check_scoped_link_events(void) puts("PASS scoped link events: capture rollback, delivery, overrun, retry and last subscriber"); } +/* Check the actual serialized address in both dumps and multicast messages. */ +static void check_ipv6_record(const void *buffer, unsigned bytes, uint16_t type, + const struct in6_addr *expected) +{ + const struct nlmsghdr *header = buffer; + assert(bytes >= sizeof(*header) && header->nlmsg_type == type); + assert(header->nlmsg_len == bytes); + bool address = type == RTM_NEWADDR || type == RTM_DELADDR; + unsigned payload = address ? sizeof(struct ifaddrmsg) : sizeof(struct rtmsg); + assert(bytes >= sizeof(*header) + payload); + if (address) { + const struct ifaddrmsg *message = (const void *)(header + 1); + assert(message->ifa_family == AF_INET6 && message->ifa_index == 1); + assert(message->ifa_prefixlen == 64); + } else { + const struct rtmsg *message = (const void *)(header + 1); + assert(message->rtm_family == AF_INET6 && message->rtm_dst_len == 64); + } + const struct rtattr *attrs[16] = {0}; + assert(!nl_parse_attrs((const uint8_t *)(header + 1) + payload, + bytes - sizeof(*header) - payload, attrs, 16)); + struct in6_addr actual = {0}; + unsigned kind = address ? IFA_ADDRESS : RTA_DST; + assert(attrs[kind] && !nl_copy_attr(attrs[kind], &actual, sizeof(actual))); + assert(!memcmp(&actual, expected, sizeof(actual))); +} + +static void check_ipv6_ack(int fd, const void *request, unsigned bytes, int error) +{ + unsigned char output[512]; + assert(send_req(fd, request, bytes) == (int)bytes); + assert(receive(fd, output, sizeof(output)) >= (int)(sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr))); + const struct nlmsghdr *header = (const void *)output; + assert(header->nlmsg_type == NLMSG_ERROR); + assert(((const struct nlmsgerr *)(header + 1))->error == error); + assert(receive(fd, output, sizeof(output)) == -LINUX_EAGAIN); +} + +static void check_ipv6_event(int *listeners, uint16_t type, const struct in6_addr *expected) +{ + unsigned char output[512]; + int bytes = receive(listeners[0], output, sizeof(output)); + assert(bytes > 0); + check_ipv6_record(output, (unsigned)bytes, type, expected); + assert(!((struct nlmsghdr *)(void *)output)->nlmsg_seq); + for (unsigned i = 0; i < 3; ++i) + assert(receive(listeners[i], output, sizeof(output)) == -LINUX_EAGAIN); +} + +/** @brief Preserve IPv6 control scope across task moves with observable stub state. */ +static void check_scoped_ipv6_control(void) +{ + unsigned baseline = allocations; + struct user_namespace *owners[2]; + current.euid = 1000; + for (unsigned i = 0; i < 2; ++i) { + assert(!user_namespace_create(¤t, &owners[i])); + assert(!net_namespace_create(owners[i], &scoped_ipv6[i].ns)); + scoped_ipv6[i].address = (struct net_ipv6_address){ + .address.s6_addr = {0x20, 1, 0x0d, 0xb8, 0, i + 1}, + .ifindex = 1, .prefix_length = 64, .flags = NET_IPV6_ADDR_PERMANENT, + .preferred_until = UINT64_MAX, .valid_until = UINT64_MAX}; + scoped_ipv6[i].route = (struct net_ipv6_route){ + .destination = scoped_ipv6[i].address.address, + .ifindex = 1, .prefix_length = 64, .metric = 1024, + .flags = RTF_UP, .valid_until = UINT64_MAX}; + scoped_ipv6[i].has_address = scoped_ipv6[i].has_route = true; + } + struct net_namespace *scopes[] = {scoped_ipv6[0].ns, scoped_ipv6[1].ns, NULL}; + int listeners[3]; + const struct sockaddr_nl subscription = {.nl_family = AF_NETLINK, + .nl_groups = RTMGRP_IPV6_IFADDR | RTMGRP_IPV6_ROUTE}; + for (unsigned i = 0; i < 3; ++i) { + current.net_ns = scopes[i]; + listeners[i] = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(listeners[i] >= 0); + assert(!call(__NR_bind, listeners[i], (uintptr_t)&subscription, sizeof(subscription), 0, 0)); + } + current.net_ns = scopes[0]; + int command = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(command >= 0); + current.net_ns = scopes[1]; + current.user_ns = owners[0]; + current.cap_effective = 1ULL << CAP_NET_ADMIN; + unsigned char output[2048]; + struct { struct nlmsghdr h; struct ifaddrmsg m; } addresses = { + .h = {.nlmsg_len = sizeof(addresses), .nlmsg_type = RTM_GETADDR, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP}, .m = {.ifa_family = AF_INET6}}; + struct { struct nlmsghdr h; struct rtmsg m; } routes = { + .h = {.nlmsg_len = sizeof(routes), .nlmsg_type = RTM_GETROUTE, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP}, .m = {.rtm_family = AF_INET6}}; + for (unsigned i = 0; i < 2; ++i) { + assert(send_req(listeners[i], &addresses, sizeof(addresses)) == sizeof(addresses)); + int bytes = receive_dump(listeners[i], output, sizeof(output)); + check_ipv6_record(output, bytes, RTM_NEWADDR, &scoped_ipv6[i].address.address); + assert(send_req(listeners[i], &routes, sizeof(routes)) == sizeof(routes)); + bytes = receive_dump(listeners[i], output, sizeof(output)); + check_ipv6_record(output, bytes, RTM_NEWROUTE, &scoped_ipv6[i].route.destination); + } + const char *leaves[] = {"if_inet6", "ipv6_route"}; + const char *markers[] = {"20010db8000100000000000000000000", "20010db8000200000000000000000000"}; + for (unsigned i = 0; i < 2; ++i) { + current.net_ns = scopes[i]; + for (unsigned j = 0; j < 2; ++j) { + char text[2048] = {0}; + struct text_stream stream = {.buffer = text, .capacity = sizeof(text) - 1}; + assert(!net_proc_emit(&stream, leaves[j])); + assert(strstr(text, markers[i]) && !strstr(text, markers[1 - i])); + } + } + current.net_ns = scopes[1]; + struct { struct nlmsghdr h; struct ifaddrmsg m; struct rtattr a; struct in6_addr ip; } address = { + .h = {.nlmsg_len = sizeof(address), .nlmsg_type = RTM_DELADDR, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK}, + .m = {.ifa_family = AF_INET6, .ifa_prefixlen = 64, .ifa_index = 1}, + .a = {.rta_len = 20, .rta_type = IFA_LOCAL}, .ip = scoped_ipv6[0].address.address}; + struct { struct nlmsghdr h; struct rtmsg m; struct rtattr dst; struct in6_addr ip; + struct rtattr oif; uint32_t index; } route = { + .h = {.nlmsg_len = sizeof(route), .nlmsg_type = RTM_DELROUTE, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK}, + .m = {.rtm_family = AF_INET6, .rtm_dst_len = 64, + .rtm_table = RT_TABLE_MAIN, .rtm_type = RTN_UNICAST}, + .dst = {.rta_len = 20, .rta_type = RTA_DST}, .ip = scoped_ipv6[0].route.destination, + .oif = {.rta_len = 8, .rta_type = RTA_OIF}, .index = 1}; + /* The current task owns the first socket's network while living in its sibling. */ + for (unsigned i = 1; i < 3; ++i) { + check_ipv6_ack(listeners[i], &address, sizeof(address), -LINUX_EPERM); + check_ipv6_ack(listeners[i], &route, sizeof(route), -LINUX_EPERM); + } + struct in6_ifreq in6 = {.ifr6_addr = address.ip, .ifr6_prefixlen = 64, .ifr6_ifindex = 1}; + struct in6_rtmsg in6route = {.rtmsg_dst = route.ip, .rtmsg_dst_len = 64, + .rtmsg_ifindex = 1, .rtmsg_metric = 1024, .rtmsg_flags = RTF_UP}; + for (unsigned i = 1; i < 3; ++i) { + assert(net_ipv6_interface_ioctl(scopes[i], SIOCDIFADDR, (uintptr_t)&in6) == -LINUX_EPERM); + assert(net_ipv6_interface_ioctl(scopes[i], SIOCDELRT, (uintptr_t)&in6route) == -LINUX_EPERM); + } + current.cap_effective = 0; + check_ipv6_ack(command, &address, sizeof(address), -LINUX_EPERM); + check_ipv6_ack(command, &route, sizeof(route), -LINUX_EPERM); + assert(net_ipv6_interface_ioctl(scopes[0], SIOCDIFADDR, (uintptr_t)&in6) == -LINUX_EPERM); + assert(net_ipv6_interface_ioctl(scopes[0], SIOCDELRT, (uintptr_t)&in6route) == -LINUX_EPERM); + assert(!scoped_ipv6[0].mutations && !scoped_ipv6[1].mutations && !updates); + current.cap_effective = 1ULL << CAP_NET_ADMIN; + check_ipv6_ack(command, &address, sizeof(address), 0); + assert(!scoped_ipv6[0].has_address && scoped_ipv6[1].has_address); + check_ipv6_event(listeners, RTM_DELADDR, &address.ip); + check_ipv6_ack(command, &route, sizeof(route), 0); + assert(!scoped_ipv6[0].has_route && scoped_ipv6[1].has_route); + check_ipv6_event(listeners, RTM_DELROUTE, &route.ip); + address.h.nlmsg_type = RTM_NEWADDR; + address.h.nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL; + route.h.nlmsg_type = RTM_NEWROUTE; + route.h.nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL; + check_ipv6_ack(command, &address, sizeof(address), 0); + check_ipv6_event(listeners, RTM_NEWADDR, &address.ip); + check_ipv6_ack(command, &route, sizeof(route), 0); + check_ipv6_event(listeners, RTM_NEWROUTE, &route.ip); + assert(!net_ipv6_interface_ioctl(scopes[0], SIOCDIFADDR, (uintptr_t)&in6)); + check_ipv6_event(listeners, RTM_DELADDR, &address.ip); + assert(!net_ipv6_interface_ioctl(scopes[0], SIOCDELRT, (uintptr_t)&in6route)); + check_ipv6_event(listeners, RTM_DELROUTE, &route.ip); + assert(!net_ipv6_interface_ioctl(scopes[0], SIOCSIFADDR, (uintptr_t)&in6)); + check_ipv6_event(listeners, RTM_NEWADDR, &address.ip); + assert(!net_ipv6_interface_ioctl(scopes[0], SIOCADDRT, (uintptr_t)&in6route)); + check_ipv6_event(listeners, RTM_NEWROUTE, &route.ip); + assert(scoped_ipv6[0].mutations == 8 && !scoped_ipv6[1].mutations && !updates); + current = (struct task){0}; + task_netlink_release(&files[command]); files[command] = (struct task_file){0}; + for (unsigned i = 0; i < 3; ++i) { + task_netlink_release(&files[listeners[i]]); + files[listeners[i]] = (struct task_file){0}; + } + for (unsigned i = 0; i < 2; ++i) { + net_namespace_put(scopes[i]); + user_namespace_put(owners[i]); + } + memset(scoped_ipv6, 0, sizeof(scoped_ipv6)); + assert(!nl_snapshots && allocations == baseline); + puts("PASS scoped IPv6 control dumps, mutations, notifications, proc and owner authority"); +} + int main(void) { check_netlink_namespace_ports(); @@ -960,6 +1186,7 @@ int main(void) check_netlink_interface_authority(); check_scoped_ipv4_routes(); check_scoped_link_events(); + check_scoped_ipv6_control(); check_netlink_metadata_options(); check_netlink_filter(); net_config.local_ip=0x0a00020f; net_config.subnet_mask=0xffffff00; @@ -1065,28 +1292,28 @@ int main(void) assert(listener>=0 && files[listener].socket_ino!=files[fd].socket_ino); struct sockaddr_nl bind_address={.nl_family=AF_NETLINK,.nl_groups=RTMGRP_IPV6_IFADDR}; assert(call(__NR_bind,listener,(uintptr_t)&bind_address,sizeof(bind_address),0,0)==0); - additional_address=true; netlink_ipv6_changed(); + additional_address=true; netlink_ipv6_changed(NULL); struct sockaddr_nl source={0}; uint32_t source_size=sizeof(source); count=task_netlink_recv(&files[listener],output,sizeof(output),0,(uintptr_t)&source,(uintptr_t)&source_size); assert(count>0 && ((struct nlmsghdr *)output)->nlmsg_type==RTM_NEWADDR && ((struct nlmsghdr *)output)->nlmsg_seq==0 && source.nl_pid==0 && source.nl_groups==RTMGRP_IPV6_IFADDR && source_size==sizeof(source)); - additional_address=false; netlink_ipv6_changed(); + additional_address=false; netlink_ipv6_changed(NULL); count=receive(listener,output,sizeof(output)); assert(count>0 && ((struct nlmsghdr *)output)->nlmsg_type==RTM_DELADDR); - for (unsigned i=0;i<10;++i) { additional_address=!additional_address; netlink_ipv6_changed(); } + for (unsigned i=0;i<10;++i) { additional_address=!additional_address; netlink_ipv6_changed(NULL); } assert(task_netlink_poll(&files[listener],POLLIN)&POLLERR); assert(receive(listener,output,sizeof(output))==-LINUX_ENOBUFS); while (receive(listener,output,sizeof(output))>0) {} task_netlink_release(&files[listener]); struct in6_ifreq in6={.ifr6_addr.s6_addr={0x20,1,0x0d,0xb8},.ifr6_prefixlen=64,.ifr6_ifindex=2}; current.cap_effective=0; - assert(net_ipv6_interface_ioctl(SIOCSIFADDR,(uintptr_t)&in6)==-LINUX_EPERM && updates==2); + assert(net_ipv6_interface_ioctl(NULL, SIOCSIFADDR,(uintptr_t)&in6)==-LINUX_EPERM && updates==2); current.cap_effective=1ULL< #include #include +#include #include #include "../../net/internal.h" #include +#include #include #include #include @@ -23,6 +25,10 @@ static bool second_nic; static uint32_t second_index=3; static uint32_t extra_nics; static unsigned failed_allocations; +static int64_t allocation_budget = -1; +static size_t live_allocations; +static struct net_namespace *last_udp_ns, *last_raw_ns, *last_error_ns, *last_change_ns; +static struct net_namespace *release_on_udp; static uint8_t second_mac[6] = {0x52,0x54,0x00,0x12,0x34,0x57}; static uint8_t sent[128][1536]; static uint32_t sent_len[128]; @@ -36,6 +42,9 @@ const uint8_t net_broadcast_mac[6]={255,255,255,255,255,255}; static uint8_t received[65536]; static uint32_t received_len; +struct user_namespace *user_namespace_get(struct user_namespace *ns) { assert(!ns); return ns; } +void user_namespace_put(struct user_namespace *ns) { assert(!ns); } + /** @brief Return the fake monotonic clock. @return Uptime in milliseconds. */ uint64_t time_uptime_ms(void) { return now_ms; } /** @brief Supply controlled random words or model an absent hardware generator. @@ -66,39 +75,52 @@ int netdev_send(uint32_t index,const void *frame,uint32_t len) { assert(index==2 || (index==second_index && second_nic));assert(sent_count<128); sent_ifindex[sent_count]=index;return e1000_send(frame,len); } bool net_interface_exists(struct net_namespace *ns, uint32_t index) -{ return index==1 || (index==2 && first_nic) || (index==second_index && second_nic) || (index>=100 && index-100=100 && index-100loopback.up : index==1 || (net_interface_exists(NULL, index) && net_interface_up); } +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) +{ return net_interface_is_up(ns, index) && (index==1 || netdev_is_ready(index)); } bool net_device_registration_pending(void) { return false; } void net_device_retry_registration(void) { } /** @brief Allocate kernel fixture memory. @param size Requested bytes. @return Owned memory. */ void *kernel_malloc(size_t size) -{ if(failed_allocations){--failed_allocations;return NULL;}return calloc(1,size); } +{ + if (failed_allocations) { --failed_allocations; return NULL; } + if (!allocation_budget) return NULL; + if (allocation_budget > 0) --allocation_budget; + void *memory = calloc(1, size); + if (memory) ++live_allocations; + return memory; +} /** @brief Free fixture memory. @param memory Owned allocation or NULL. */ -void kernel_free(void *memory) { free(memory); } +void kernel_free(void *memory) { if (memory) { assert(live_allocations); --live_allocations; } free(memory); } /** @brief Announce a state change to the fixture. */ -void netlink_ipv6_changed(void) { } +void netlink_ipv6_changed(struct net_namespace *ns) { last_change_ns=ns; } /** @brief Capture UDP delivery. @param s Source. @param d Destination. @param sp Source port. * @param dp Destination port. @param data Borrowed bytes. @param len Length. * @param ifindex Interface. @param hops Hop limit. @return True for a listening port. */ -bool net_udp6_input(const struct in6_addr *s,const struct in6_addr *d,uint16_t sp, +bool net_udp6_input(struct net_namespace *ns,const struct in6_addr *s,const struct in6_addr *d,uint16_t sp, uint16_t dp,const void *data,uint32_t len,uint32_t ifindex,uint8_t hops) -{ (void)s;(void)d;(void)sp;(void)hops; if(dp!=9000)return false; - assert(len<=sizeof(received));memcpy(received,data,len);received_len=len;last_udp_ifindex=ifindex;++udp_count;return true; } +{ last_udp_ns=ns;(void)s;(void)d;(void)sp;(void)hops; if(dp!=9000)return false; + assert(len<=sizeof(received));memcpy(received,data,len);received_len=len;last_udp_ifindex=ifindex;++udp_count; + if (release_on_udp) { struct net_namespace *release=release_on_udp; release_on_udp=NULL; net_namespace_put(release); } + return true; } /** @brief Ignore checked TCP. @param s Source. @param d Destination. @param p Bytes. * @param n Length. @param i Interface. */ -void net_tcp6_input(const struct in6_addr *s,const struct in6_addr *d,const void *p,uint32_t n,uint32_t i) -{ (void)s;(void)d;(void)p;(void)n;(void)i; } +void net_tcp6_input(struct net_namespace *ns,const struct in6_addr *s,const struct in6_addr *d,const void *p,uint32_t n,uint32_t i) +{ (void)ns;(void)s;(void)d;(void)p;(void)n;(void)i; } /** @brief Count checked raw delivery. @param s Source. @param d Destination. @param p Protocol. * @param b Bytes. @param n Length. @param i Interface. @param h Hop limit. */ -void net_raw6_input(const struct in6_addr *s,const struct in6_addr *d,uint8_t p,const void *b, +void net_raw6_input(struct net_namespace *ns,const struct in6_addr *s,const struct in6_addr *d,uint8_t p,const void *b, uint32_t n,uint32_t i,uint8_t h) -{ (void)s;(void)d;(void)p;(void)b;(void)n;(void)i;(void)h;++raw_count; } +{ last_raw_ns=ns;(void)s;(void)d;(void)p;(void)b;(void)n;(void)i;(void)h;++raw_count; } /** @brief Ignore socket errors. @param p Quote. @param n Length. @param e Error. @param m MTU. */ void net_ipv6_socket_error(const uint8_t *p,uint32_t n,int e,uint32_t m) { (void)p;(void)n;(void)e;(void)m; } -void net_ipv6_socket_error_on(uint32_t i,const uint8_t *p,uint32_t n,int e,uint32_t m) -{ last_error_ifindex=i;++socket_error_count;net_ipv6_socket_error(p,n,e,m); } +void net_ipv6_socket_error_on(struct net_namespace *ns,uint32_t i,const uint8_t *p,uint32_t n,int e,uint32_t m) +{ last_error_ns=ns;last_error_ifindex=i;++socket_error_count;net_ipv6_socket_error(p,n,e,m); } /** @brief Copy bytes. @param d Destination. @param s Source. @param n Length. */ void net_memcpy(void *d,const void *s,uint32_t n) { memcpy(d,s,n); } /** @brief Clear bytes. @param d Destination. @param n Length. */ @@ -160,7 +182,7 @@ void net_tcp_service_sockets(void) { } /** @brief Exercise the expected absent implementation failure. */ void net_ipv6_init(void) { } /** @brief Return no configured addresses. @param out Optional output. @param n Capacity. @return Zero. */ -uint32_t net_ipv6_addresses(struct net_ipv6_address *out,uint32_t n) { (void)out;(void)n;return 0; } +uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out,uint32_t n) { (void)ns;(void)out;(void)n;return 0; } #endif #ifndef IPV6_NO_IMPLEMENTATION @@ -194,7 +216,7 @@ static int mld_record(unsigned first,const struct in6_addr *group,uint8_t type) return -1; } /** @brief Find a neighbor's published NUD state. @param target Address. @return Linux NUD state or zero. */ static uint32_t neighbor_state(const struct in6_addr *target) -{ struct net_ipv6_neighbor neighbors[16];uint32_t n=net_ipv6_neighbors(neighbors,16); +{ struct net_ipv6_neighbor neighbors[16];uint32_t n=net_ipv6_neighbors(NULL, neighbors,16); for(uint32_t i=0;iloopback.up = true; + assert(last_change_ns == first); + assert(!net_ipv6_link_changed_on(second, 1, true)); + second->loopback.up = true; + assert(net_ipv6_addresses(first, NULL, 0) == 1); + assert(net_ipv6_routes(first, NULL, 0) == 1); + struct net_ipv6_address local = {.address = loop, .ifindex = 1, + .prefix_length = 128, .flags = NET_IPV6_ADDR_NODAD, + .preferred_until = UINT64_MAX, .valid_until = UINT64_MAX}; + local.address.s6_addr[15] = 42; + assert(!net_ipv6_address_update(first, &local, false)); + assert(net_ipv6_addresses(first, NULL, 0) == 2); + assert(net_ipv6_addresses(second, NULL, 0) == 1); + struct net_ipv6_route route = {.destination = local.address, .prefix_length = 128, + .ifindex = 1, .metric = 42, .flags = RTF_UP | RTF_HOST, .valid_until = UINT64_MAX}; + assert(!net_ipv6_route_update(first, &route, false)); + assert(net_ipv6_routes(first, NULL, 0) == 2); + assert(net_ipv6_routes(second, NULL, 0) == 1); + local.ifindex = 2; + assert(net_ipv6_address_update(first, &local, false) == -LINUX_EINVAL); + assert(net_ipv6_link_changed_on(first, 2, true) == -LINUX_ENODEV); + + /* Initial-network initialization must preserve other live protocol tables. */ + net_ipv6_init(); + assert(net_ipv6_addresses(first, NULL, 0) == 2); + assert(net_ipv6_routes(first, NULL, 0) == 2); + assert(!net_ipv6_route(first, &loop, 0, NULL, &path)); + uint8_t message[13]; + udp(message, &loop, &loop, 9000, (const uint8_t *)"first", 5); + unsigned delivered = udp_count; + assert(net_ipv6_output(first, &path, 17, message, 13, 64, 0, false, false) == 13); + assert(net_ipv6_maintenance_pending()); + net_ipv6_poll(); + assert(udp_count == delivered + 1 && last_udp_ns == first && last_raw_ns == first); + for (unsigned i = 0; i < 8; ++i) + assert(net_ipv6_output(first, &path, 17, message, 13, 64, 0, false, false) == 13); + assert(net_ipv6_output(first, &path, 17, message, 13, 64, 0, false, false) == -LINUX_ENOBUFS); + assert(net_ipv6_output(second, &path, 17, message, 13, 64, 0, false, false) == 13); + net_ipv6_poll(); + assert(udp_count == delivered + 10); + + struct in6_addr group = {.s6_addr = {0xff,1,0,0,0,0,0,0,0,0,0,0,0,0,0,42}}; + assert(!net_ipv6_multicast_change(second, &group, 1, 1)); + assert(!net_ipv6_route(first, &group, 1, NULL, &path)); + udp(message, &loop, &group, 9000, (const uint8_t *)"group", 5); + delivered = udp_count; + assert(net_ipv6_output(first, &path, 17, message, 13, 1, 0, false, true) == 13); + net_ipv6_poll(); + assert(udp_count == delivered); + assert(net_ipv6_output(second, &path, 17, message, 13, 1, 0, false, true) == 13); + net_ipv6_poll(); + assert(udp_count == delivered + 1 && last_udp_ns == second); + + /* Equal fragment identities in different networks must reassemble separately. */ + assert(!net_ipv6_route(first, &loop, 0, NULL, &path)); + udp(message, &loop, &loop, 9000, (const uint8_t *)"first", 5); + uint8_t fragment[16] = {17}; + net_put_u16(fragment + 2, 1); + net_put_u32(fragment + 4, 123); + memcpy(fragment + 8, message, 8); + delivered = udp_count; + assert(net_ipv6_output(first, &path, 44, fragment, 16, 64, 0, false, false) == 16); + net_ipv6_poll(); + net_put_u16(fragment + 2, 8); + memcpy(fragment + 8, message + 8, 5); + assert(net_ipv6_output(second, &path, 44, fragment, 13, 64, 0, false, false) == 13); + net_ipv6_poll(); + assert(udp_count == delivered); + assert(net_ipv6_output(first, &path, 44, fragment, 13, 64, 0, false, false) == 13); + net_ipv6_poll(); + assert(udp_count == delivered + 1 && last_udp_ns == first); + net_put_u16(fragment + 2, 1); + memcpy(fragment + 8, message, 8); + assert(net_ipv6_output(second, &path, 44, fragment, 16, 64, 0, false, false) == 16); + net_ipv6_poll(); + assert(udp_count == delivered + 2 && last_udp_ns == second); + + /* A validated Packet Too Big changes only the receiving network's PMTU. */ + uint8_t too_big[56] = {2}; + net_put_u32(too_big + 4, 1280); + too_big[8] = 0x60; + too_big[14] = 17; + memcpy(too_big + 16, &loop, 16); + memcpy(too_big + 32, &loop, 16); + net_put_u16(too_big + 2, net_ipv6_checksum(&loop, &loop, 58, too_big, sizeof(too_big))); + assert(net_ipv6_output(first, &path, 58, too_big, sizeof(too_big), 64, 0, false, false) == (int)sizeof(too_big)); + net_ipv6_poll(); + assert(last_error_ns == first); + assert(!net_ipv6_route(first, &loop, 0, NULL, &path) && path.mtu == 1280); + assert(!net_ipv6_route(second, &loop, 0, NULL, &path) && path.mtu == 65575); + + assert(net_ipv6_output(first, &path, 17, message, 13, 64, 0, false, false) == 13); + failed_allocations = 1; + unsigned errors = socket_error_count; + net_ipv6_poll(); + assert(socket_error_count == errors + 1 && last_error_ns == first); + assert(!net_ipv6_link_changed_on(first, 1, false)); + first->loopback.up = false; + assert(!net_ipv6_addresses(first, NULL, 0) && !net_ipv6_routes(first, NULL, 0)); + assert(net_ipv6_output(first, &path, 17, message, 13, 64, 0, false, false) == -LINUX_ENETDOWN); + assert(net_ipv6_addresses(second, NULL, 0) == 1); + + /* Poll pins its current network while a callback drops the last external owner. */ + assert(net_ipv6_output(second, &path, 17, message, 13, 64, 0, false, false) == 13); + release_on_udp = second; + net_ipv6_poll(); + assert(!release_on_udp); + net_namespace_put(first); + assert(live_allocations == baseline); + assert(!net_ipv6_maintenance_pending()); } #endif @@ -461,7 +618,7 @@ int main(void) { struct net_ipv6_address entries[16]; net_ipv6_init(); - uint32_t count=net_ipv6_addresses(entries,16); + uint32_t count=net_ipv6_addresses(NULL, entries,16); bool loop=false; for(uint32_t i=0;i=0); assert(sent[dad][21]==255 && !memcmp(sent[dad]+22,(uint8_t[16]){0},16)); assert(sent[dad][38]==0xff && sent[dad][39]==2 && sent[dad][49]==1 && sent[dad][50]==0xff); now_ms=1000;net_ipv6_poll(); - count=net_ipv6_addresses(entries,16);bool found=false; + count=net_ipv6_addresses(NULL, entries,16);bool found=false; for(uint32_t i=0;ibefore && last_icmp(135)>=0); uint8_t na[32]={136,0,0,0,0x60},frame[4096];const uint8_t remote_mac[6]={2,0,0,0,0,1}; memcpy(na+8,peer.s6_addr,16);na[24]=2;na[25]=1;memcpy(na+26,remote_mac,6); @@ -496,10 +653,10 @@ int main(void) unsigned delivered=udp_count;net_ipv6_input(frame,len);assert(udp_count==delivered+1); frame[60]=0;frame[61]=0;net_ipv6_input(frame,len);assert(udp_count==delivered+1); uint8_t large[2408];memset(large+8,0xa5,2400);udp(large,&local,&peer,9000,large+8,2400); - before=sent_count;assert(net_ipv6_output(&path,17,large,sizeof(large),64,0,false,false)==(int)sizeof(large)); + before=sent_count;assert(net_ipv6_output(NULL, &path,17,large,sizeof(large),64,0,false,false)==(int)sizeof(large)); assert(sent_count==before+2 && sent[before][20]==44 && sent[before+1][20]==44); assert(sent_len[before]<=1514 && sent_len[before+1]<=1514); - assert(net_ipv6_output(&path,17,large,sizeof(large),64,0,true,false)==-LINUX_EMSGSIZE); + assert(net_ipv6_output(NULL, &path,17,large,sizeof(large),64,0,true,false)==-LINUX_EMSGSIZE); /* Reassembly accepts out-of-order fragments and discards all overlapping pieces. */ udp(large,&peer,&local,9000,large+8,2400); @@ -525,7 +682,7 @@ int main(void) net_put_u16(ra+2,net_ipv6_checksum(&peer,&all,58,ra,sizeof(ra))); queued_length=packet(queued_frame,&peer,&all,58,255,ra,sizeof(ra)); unsigned raw_before=raw_count;now_ms=1010;net_tcp_maintenance();assert(!queued_length && raw_count>raw_before); - count=net_ipv6_addresses(entries,16);struct in6_addr global={0};bool have_global=false; + count=net_ipv6_addresses(NULL, entries,16);struct in6_addr global={0};bool have_global=false; for(uint32_t i=0;i=now_ms+7200000); /* A manually configured /64 supplies its own connected route. */ struct net_ipv6_address manual={0};manual.address=global;manual.address.s6_addr[7]=0x22; manual.ifindex=2;manual.prefix_length=64;manual.flags=NET_IPV6_ADDR_NODAD; manual.preferred_until=manual.valid_until=UINT64_MAX; - assert(net_ipv6_address_update(&manual,false)==0); + assert(net_ipv6_address_update(NULL, &manual,false)==0); struct in6_addr direct=manual.address;direct.s6_addr[15]^=3; - assert(net_ipv6_route(&direct,2,NULL,&path)==0 && !memcmp(&path.next_hop,&direct,16)); - assert(net_ipv6_address_update(&manual,true)==0); + assert(net_ipv6_route(NULL, &direct,2,NULL,&path)==0 && !memcmp(&path.next_hop,&direct,16)); + assert(net_ipv6_address_update(NULL, &manual,true)==0); /* Multicast is Ethernet-filtered then IPv6-membership-filtered and loop policy is per send. */ const uint8_t groupbytes[16]={0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0xfb}; - struct in6_addr group;address(&group,groupbytes);assert(net_ipv6_multicast_change(&group,2,1)==0); - assert(net_ipv6_route(&group,2,NULL,&path)==0);udp(msg,&path.source,&group,9000,hello,5); - delivered=udp_count;assert(net_ipv6_output(&path,17,msg,13,1,0,false,false)==13); + struct in6_addr group;address(&group,groupbytes);assert(net_ipv6_multicast_change(NULL, &group,2,1)==0); + assert(net_ipv6_route(NULL, &group,2,NULL,&path)==0);udp(msg,&path.source,&group,9000,hello,5); + delivered=udp_count;assert(net_ipv6_output(NULL, &path,17,msg,13,1,0,false,false)==13); net_ipv6_poll();assert(udp_count==delivered); - assert(net_ipv6_output(&path,17,msg,13,1,0,false,true)==13);net_ipv6_poll();assert(udp_count==delivered+1); + assert(net_ipv6_output(NULL, &path,17,msg,13,1,0,false,true)==13);net_ipv6_poll();assert(udp_count==delivered+1); /* Option action 10 sends an error even for multicast; 11 suppresses that error. */ uint8_t option_packet[21]={17,0,0x80,0,1,2,0,0};udp(option_packet+8,&peer,&all,9000,hello,5); len=packet(frame,&peer,&all,0,64,option_packet,sizeof(option_packet));before=sent_count; @@ -593,21 +750,21 @@ int main(void) assert(sent_count>before && timeout>=(int)before && sent[timeout][55]==1); /* ::1 and a full 65535-byte IPv6 payload work without a NIC. */ - net_ipv6_detached();nic_ready=false;assert(net_ipv6_route(&one,0,NULL,&path)==0); + net_ipv6_detached();nic_ready=false;assert(net_ipv6_route(NULL, &one,0,NULL,&path)==0); uint8_t *maximum=malloc(65535);assert(maximum);memset(maximum+8,0x7b,65527); udp(maximum,&one,&one,9000,maximum+8,65527);delivered=udp_count; - assert(net_ipv6_output(&path,17,maximum,65535,64,0,false,false)==65535); + assert(net_ipv6_output(NULL, &path,17,maximum,65535,64,0,false,false)==65535); maximum[8]=0;free(maximum);assert(udp_count==delivered);now_ms+=10;net_tcp_maintenance(); assert(udp_count==delivered+1 && received_len==65527 && received[0]==0x7b); - nic_ready=true;now_ms+=10;net_tcp_maintenance();count=net_ipv6_addresses(entries,16);found=false; + nic_ready=true;now_ms+=10;net_tcp_maintenance();count=net_ipv6_addresses(NULL, entries,16);found=false; for(uint32_t i=0;ibefore && last_icmp(135)>=(int)before); /* Randomized DAD, first RS and MLD delays must be bounded, and DAD sends its MLD report first. */ random_word=UINT32_MAX;now_ms+=10000;net_ipv6_init();sent_count=0; @@ -617,11 +774,11 @@ int main(void) uint64_t dad_time=now_ms;struct in6_addr solicited={0}; memcpy(solicited.s6_addr,sent[dad]+38,16);int joined=mld_record(0,&solicited,4); assert(joined>=0 && joined=0 && now_ms-ready>0 && now_ms-ready<=1000); - local=path.source;before=sent_count;assert(net_ipv6_multicast_change(&group,2,1)==0);net_ipv6_poll(); + local=path.source;before=sent_count;assert(net_ipv6_multicast_change(NULL, &group,2,1)==0);net_ipv6_poll(); assert(mld_record(before,&group,4)>=0);before=sent_count;start=now_ms; net_ipv6_poll();assert(mld_record(before,&group,4)<0); while(mld_record(before,&group,4)<0 && now_ms-start<1000){now_ms+=10;net_ipv6_poll();} @@ -650,8 +807,8 @@ int main(void) memset(timing_ra+8,0,8);timing_ra[2]=timing_ra[3]=0; net_put_u16(timing_ra+2,net_ipv6_checksum(&peer,&all,58,timing_ra,16)); len=packet(frame,&peer,&all,58,255,timing_ra,16);net_ipv6_input(frame,len); - assert(net_ipv6_route(&peer2,2,NULL,&path)==0);udp(msg,&local,&peer2,9000,hello,5); - assert(net_ipv6_output(&path,17,msg,13,64,0,false,false)==13);before=sent_count; + assert(net_ipv6_route(NULL, &peer2,2,NULL,&path)==0);udp(msg,&local,&peer2,9000,hello,5); + assert(net_ipv6_output(NULL, &path,17,msg,13,64,0,false,false)==13);before=sent_count; now_ms+=2499;net_ipv6_poll();assert(last_icmp(135)<(int)before); now_ms++;net_ipv6_poll();assert(last_icmp(135)>=(int)before); memcpy(na+8,peer2.s6_addr,16);na[2]=na[3]=0;net_put_u16(na+2,net_ipv6_checksum(&peer2,&local,58,na,32)); @@ -662,11 +819,11 @@ int main(void) /* Link reset restores default retransmission and hardware-RNG failure still progresses. */ net_ipv6_detached();random_word=0;nic_ready=true;net_ipv6_link_changed(true);net_ipv6_poll(); - now_ms+=1000;net_ipv6_poll();assert(net_ipv6_route(&peer2,2,NULL,&path)==0); + now_ms+=1000;net_ipv6_poll();assert(net_ipv6_route(NULL, &peer2,2,NULL,&path)==0); net_put_u32(timing_ra+8,4000);net_put_u32(timing_ra+12,2500);timing_ra[2]=timing_ra[3]=0; net_put_u16(timing_ra+2,net_ipv6_checksum(&peer,&all,58,timing_ra,16)); len=packet(frame,&peer,&all,58,64,timing_ra,16);net_ipv6_input(frame,len); - udp(msg,&path.source,&peer2,9000,hello,5);assert(net_ipv6_output(&path,17,msg,13,64,0,false,false)==13); + udp(msg,&path.source,&peer2,9000,hello,5);assert(net_ipv6_output(NULL, &path,17,msg,13,64,0,false,false)==13); before=sent_count;now_ms+=999;net_ipv6_poll();assert(last_icmp(135)<(int)before); now_ms++;net_ipv6_poll();assert(last_icmp(135)>=(int)before); memcpy(na+8,peer2.s6_addr,16);na[2]=na[3]=0; @@ -681,6 +838,7 @@ int main(void) test_multiple_interfaces(); test_many_interfaces(); test_link_allocation_retry(); + test_namespace_addresses(); puts("PASS IPv6 protocol: loopback, DAD/NDP, checksums, fragments, RA/SLAAC, MLD and timer pump"); #endif return 0; diff --git a/tools/tests/ipv6_tcp_test.c b/tools/tests/ipv6_tcp_test.c index 28bd57aa..c74bf68a 100644 --- a/tools/tests/ipv6_tcp_test.c +++ b/tools/tests/ipv6_tcp_test.c @@ -58,11 +58,12 @@ void net_write_eth(uint8_t *frame, const uint8_t *mac, uint16_t type) { (void)frame; (void)mac; (void)type; } void net_write_eth_on(uint32_t index,uint8_t *frame,const uint8_t *mac,uint16_t type) { (void)index;net_write_eth(frame,mac,type); } -uint32_t net_ipv6_addresses(struct net_ipv6_address *out,uint32_t cap) -{ if (cap) out[0] = (struct net_ipv6_address){.address=loop6,.ifindex=1}; return 1; } -int net_ipv6_route(const struct in6_addr *destination,uint32_t scope, +uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out,uint32_t cap) +{ (void)ns; if (cap) out[0] = (struct net_ipv6_address){.address=loop6,.ifindex=1}; return 1; } +int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination,uint32_t scope, const struct in6_addr *bound,struct net_ipv6_path *path) { + (void)ns; static const struct in6_addr zero = {0}; if (memcmp(destination,&loop6,16) || (scope && scope != 1)) return -LINUX_ENETUNREACH; *path = (struct net_ipv6_path){.source=memcmp(bound,&zero,16) ? *bound : loop6, @@ -78,9 +79,10 @@ uint16_t net_ipv6_checksum(const struct in6_addr *source,const struct in6_addr * sum = net_checksum_partial(sum,trailer,8); return net_checksum_finish(net_checksum_partial(sum,data,length)); } -int net_ipv6_output(const struct net_ipv6_path *path,uint8_t protocol,const void *data, +int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,uint8_t protocol,const void *data, uint32_t length,int hops,uint32_t flowinfo,bool df,bool multicast_loop) { + (void)ns; (void)hops; (void)flowinfo; (void)df; (void)multicast_loop; assert(protocol == 6 && length <= sizeof(queue[0].data)); assert(!net_ipv6_checksum(&path->source,&path->destination,protocol,data,length)); @@ -94,7 +96,7 @@ void net_poll_packets(void) net_tcp_service_sockets(); while (head < tail) { struct queued q = queue[head++ % 32]; - net_tcp6_input(&q.path.source,&q.path.destination,q.data,q.length,q.path.ifindex); + net_tcp6_input(NULL, &q.path.source,&q.path.destination,q.data,q.length,q.path.ifindex); assert(head <= tail && tail - head < 32); } } diff --git a/tools/tests/ipv6_transport_test.c b/tools/tests/ipv6_transport_test.c index a061baf5..a39d130b 100644 --- a/tools/tests/ipv6_transport_test.c +++ b/tools/tests/ipv6_transport_test.c @@ -11,14 +11,16 @@ void kernel_poll_readiness_notify(void) {} static const struct in6_addr loop6 = {.s6_addr = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; -uint32_t net_ipv6_addresses(struct net_ipv6_address *out, uint32_t capacity) +uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out, uint32_t capacity) { + (void)ns; if (capacity) out[0] = (struct net_ipv6_address){.address = loop6, .ifindex = 1}; return 1; } -int net_ipv6_route(const struct in6_addr *destination, uint32_t scope, +int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination, uint32_t scope, const struct in6_addr *bound, struct net_ipv6_path *path) { + (void)ns; if (memcmp(destination, &loop6, sizeof(loop6)) || (scope && scope != 1)) return -LINUX_ENETUNREACH; *path = (struct net_ipv6_path){.source = udp6_any(bound) ? loop6 : *bound, .destination = *destination, .ifindex = 1, .mtu = 65536}; @@ -37,24 +39,25 @@ uint16_t net_ipv6_checksum(const struct in6_addr *source, const struct in6_addr while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16); return (uint16_t)~sum; } -int net_ipv6_output(const struct net_ipv6_path *path, uint8_t protocol, +int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path, uint8_t protocol, const void *data, uint32_t length, int hops, uint32_t flowinfo, bool dont_fragment, bool multicast_loop) { + (void)ns; const uint8_t *p = data; (void)flowinfo; (void)dont_fragment; (void)multicast_loop; assert(!net_ipv6_checksum(&path->source, &path->destination, protocol, data, length)); if (protocol == 17) { assert(length >= 8); - assert(net_udp6_input(&path->source, &path->destination, (p[0] << 8) | p[1], + assert(net_udp6_input(NULL, &path->source, &path->destination, (p[0] << 8) | p[1], (p[2] << 8) | p[3], p + 8, length - 8, path->ifindex, hops < 0 ? 64 : (uint8_t)hops)); - } else net_raw6_input(&path->source, &path->destination, protocol, data, length, + } else net_raw6_input(NULL, &path->source, &path->destination, protocol, data, length, path->ifindex, hops < 0 ? 64 : (uint8_t)hops); return (int)length; } -int net_ipv6_multicast_change(const struct in6_addr *address, uint32_t ifindex, int delta) -{ (void)address; (void)ifindex; (void)delta; return 0; } +int net_ipv6_multicast_change(struct net_namespace *ns, const struct in6_addr *address, uint32_t ifindex, int delta) +{ (void)ns; (void)address; (void)ifindex; (void)delta; return 0; } bool net_interface_ready(void) { return true; } const uint8_t *e1000_mac(void) { static uint8_t mac[6]; return mac; } int e1000_send(const void *frame, uint32_t length) { (void)frame; return (int)length; } diff --git a/tools/tests/ipv6_vector_test.c b/tools/tests/ipv6_vector_test.c index 9bf8edf7..3cf68a0a 100644 --- a/tools/tests/ipv6_vector_test.c +++ b/tools/tests/ipv6_vector_test.c @@ -6,11 +6,12 @@ static const struct in6_addr loop6={.s6_addr={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; void kernel_poll_readiness_notify(void) {} -uint32_t net_ipv6_addresses(struct net_ipv6_address *out,uint32_t capacity) -{ if(capacity)out[0]=(struct net_ipv6_address){.address=loop6,.ifindex=1};return 1; } -int net_ipv6_route(const struct in6_addr *destination,uint32_t scope, +uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out,uint32_t capacity) +{ (void)ns; if(capacity)out[0]=(struct net_ipv6_address){.address=loop6,.ifindex=1};return 1; } +int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination,uint32_t scope, const struct in6_addr *bound,struct net_ipv6_path *path) { + (void)ns; if(memcmp(destination,&loop6,16) || (scope && scope!=1))return -LINUX_ENETUNREACH; *path=(struct net_ipv6_path){.source=udp6_any(bound) ? loop6 : *bound, .destination=*destination,.ifindex=1,.mtu=65536};return 0; @@ -26,17 +27,18 @@ uint16_t net_ipv6_checksum(const struct in6_addr *source,const struct in6_addr * while(sum>>16)sum=(sum&0xffff)+(sum>>16); return (uint16_t)~sum; } -int net_ipv6_output(const struct net_ipv6_path *path,uint8_t protocol,const void *data, +int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,uint8_t protocol,const void *data, uint32_t length,int hops,uint32_t flowinfo,bool df,bool multicast_loop) { + (void)ns; (void)flowinfo;(void)df;(void)multicast_loop;const uint8_t *p=data; assert(protocol==17 && length>=8 && !net_ipv6_checksum(&path->source,&path->destination,protocol,data,length)); - assert(net_udp6_input(&path->source,&path->destination,(p[0]<<8)|p[1],(p[2]<<8)|p[3], + assert(net_udp6_input(NULL, &path->source,&path->destination,(p[0]<<8)|p[1],(p[2]<<8)|p[3], p+8,length-8,path->ifindex,hops<0 ? 64 : (uint8_t)hops)); return (int)length; } -int net_ipv6_multicast_change(const struct in6_addr *address,uint32_t ifindex,int delta) -{ (void)address;(void)ifindex;(void)delta;return 0; } +int net_ipv6_multicast_change(struct net_namespace *ns, const struct in6_addr *address,uint32_t ifindex,int delta) +{ (void)ns; (void)address;(void)ifindex;(void)delta;return 0; } int file_can_read(const struct task_file *file) { return file != NULL; } int file_can_write(const struct task_file *file) { return file != NULL; } diff --git a/tools/tests/modules/scheduler.h b/tools/tests/modules/scheduler.h index 15aeed47..de3cdff4 100644 --- a/tools/tests/modules/scheduler.h +++ b/tools/tests/modules/scheduler.h @@ -28,6 +28,7 @@ static void fixture_exec_other_exit(uint32_t pid, uint64_t code); #include "../../../kernel/sched/user_namespace.c" #include "../../../kernel/init/uts.c" #include "../../../net/namespace/namespace.c" +#include "../../../net/ipv6/state.c" #include "../../../kernel/sched/user_namespace_task.c" #include "../../../kernel/sched/tables.c" #include "../../../kernel/sched/lookup.c" diff --git a/tools/tests/net_interface_test.c b/tools/tests/net_interface_test.c index 7fffc1e0..de988ae3 100644 --- a/tools/tests/net_interface_test.c +++ b/tools/tests/net_interface_test.c @@ -15,8 +15,9 @@ int e1000_is_ready(void) { return nic_present && nic_carrier; } void e1000_get_info(struct e1000_info *info) { *info=(struct e1000_info){.present=nic_present,.active=nic_present && nic_carrier}; } void net_ipv6_link_changed(bool up) { (void)up; } -int net_ipv6_link_changed_on(uint32_t index, bool up) { (void)index; (void)up; return 0; } +int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index, bool up) { (void)ns; (void)index; (void)up; return 0; } void netlink_network_changed(struct net_namespace *ns) { (void)ns; } +void netlink_ipv6_changed(struct net_namespace *ns) { (void)ns; } const uint8_t *e1000_mac(void) { static const uint8_t mac[6] = {2,3,4,5,6,7}; return mac; } uint32_t netdev_next(uint32_t after) { return nic_present && after < 2 ? 2 : 0; } int netdev_is_ready(uint32_t index) { return index == 2 && e1000_is_ready(); } @@ -25,6 +26,7 @@ void netdev_get_info(uint32_t index, struct e1000_info *info) { if (index == 2) { e1000_get_info(info); memcpy(info->mac,e1000_mac(),6); } else memset(info,0,sizeof(*info)); } bool user_range_ok(uint64_t address, uint64_t size) { return address >= 4096 && size <= 4096; } bool user_range_writable(uint64_t address, uint64_t size) { return user_range_ok(address, size); } +int user_range_readable(uint64_t address, uint64_t size) { return user_range_ok(address, size) ? 0 : -LINUX_EFAULT; } static int call(unsigned command, struct ifreq *req) { return net_interface_ioctl(NULL, command, (uintptr_t)req); } int main(void) { diff --git a/tools/tests/net_multi_interface_test.c b/tools/tests/net_multi_interface_test.c index 26274dbb..9b073fe7 100644 --- a/tools/tests/net_multi_interface_test.c +++ b/tools/tests/net_multi_interface_test.c @@ -24,17 +24,17 @@ void netdev_get_info(uint32_t index, struct e1000_info *out) .active = index < 4 && carrier[index]}; memcpy(out->mac, netdev_mac(index), 6); } -int net_ipv6_link_changed_on(uint32_t index, bool up) { (void)index; (void)up; return 0; } +int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index, bool up) { (void)ns; (void)index; (void)up; return 0; } uint64_t time_uptime_ms(void) { return 1000; } void kernel_poll_readiness_notify(void) { } -uint32_t net_ipv6_addresses(struct net_ipv6_address *out, uint32_t capacity) -{ (void)out; (void)capacity; return 0; } -uint32_t net_ipv6_routes(struct net_ipv6_route *out, uint32_t capacity) -{ (void)out; (void)capacity; return 0; } -int net_ipv6_address_update(const struct net_ipv6_address *address, bool remove) -{ (void)address; (void)remove; return 0; } -int net_ipv6_route_update(const struct net_ipv6_route *route, bool remove) -{ (void)route; (void)remove; return 0; } +uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out, uint32_t capacity) +{ (void)ns; (void)out; (void)capacity; return 0; } +uint32_t net_ipv6_routes(struct net_namespace *ns, struct net_ipv6_route *out, uint32_t capacity) +{ (void)ns; (void)out; (void)capacity; return 0; } +int net_ipv6_address_update(struct net_namespace *ns, const struct net_ipv6_address *address, bool remove) +{ (void)ns; (void)address; (void)remove; return 0; } +int net_ipv6_route_update(struct net_namespace *ns, const struct net_ipv6_route *route, bool remove) +{ (void)ns; (void)route; (void)remove; return 0; } void net_arp_cache_clear_on(uint32_t index) { (void)index; } static int call(unsigned command, struct ifreq *req) @@ -184,7 +184,7 @@ int main(void) netlink_sockets=&listener; assert(!nl_initial_snapshot(NULL)); net_interface_remove(3); - netlink_ipv6_changed(); + netlink_ipv6_changed(NULL); assert(listener.head && ((struct nlmsghdr *)(void *)listener.head->data)->nlmsg_type==RTM_DELLINK); struct ifinfomsg *event=(void *)(listener.head->data+sizeof(struct nlmsghdr)); assert(event->ifi_index==3); diff --git a/tools/tests/net_packet_test.c b/tools/tests/net_packet_test.c index c81b98c8..95504afd 100644 --- a/tools/tests/net_packet_test.c +++ b/tools/tests/net_packet_test.c @@ -21,17 +21,17 @@ uint64_t time_ticks(void) { return 1; } void sched_sleep_current_until(uint64_t deadline) { (void)deadline; } void net_poll_packets(void) {} void kernel_poll_readiness_notify(void) {} -uint32_t net_ipv6_addresses(struct net_ipv6_address *out, uint32_t capacity) -{ (void)out; (void)capacity; return 0; } -int net_ipv6_multicast_change(const struct in6_addr *address, uint32_t index, int delta) -{ (void)address; (void)index; (void)delta; return 0; } -int net_ipv6_route(const struct in6_addr *destination, uint32_t scope, +uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out, uint32_t capacity) +{ (void)ns; (void)out; (void)capacity; return 0; } +int net_ipv6_multicast_change(struct net_namespace *ns, const struct in6_addr *address, uint32_t index, int delta) +{ (void)ns; (void)address; (void)index; (void)delta; return 0; } +int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination, uint32_t scope, const struct in6_addr *source, struct net_ipv6_path *path) -{ (void)destination; (void)scope; (void)source; (void)path; return -LINUX_ENETUNREACH; } -int net_ipv6_output(const struct net_ipv6_path *path, uint8_t protocol, +{ (void)ns; (void)destination; (void)scope; (void)source; (void)path; return -LINUX_ENETUNREACH; } +int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path, uint8_t protocol, const void *data, uint32_t length, int hops, uint32_t flow, bool dont_fragment, bool multicast_loop) -{ (void)path; (void)protocol; (void)data; (void)length; (void)hops; (void)flow; +{ (void)ns; (void)path; (void)protocol; (void)data; (void)length; (void)hops; (void)flow; (void)dont_fragment; (void)multicast_loop; return -LINUX_ENETUNREACH; } uint16_t net_ipv6_checksum(const struct in6_addr *source, const struct in6_addr *destination, uint8_t protocol, const void *data, uint32_t length) diff --git a/tools/tests/net_rx_budget_test.c b/tools/tests/net_rx_budget_test.c index b75bcfc9..3ff9d9c3 100644 --- a/tools/tests/net_rx_budget_test.c +++ b/tools/tests/net_rx_budget_test.c @@ -18,7 +18,7 @@ uint32_t netdev_rx_take(uint32_t after) } void netdev_rx_notify(uint32_t id) { assert(id>=2 && id<=3); pending[id-2]=1; } uint32_t netdev_next(uint32_t after) { return after<2 ? 2 : after==2 ? 3 : 0; } -bool net_interface_is_up(struct net_namespace *ns, uint32_t id) { return id>=2 && id<=3 && !down; } +bool net_interface_is_up(struct net_namespace *ns, uint32_t id) { (void)ns; return id>=2 && id<=3 && !down; } int netdev_poll(uint32_t id,void *frame,uint32_t capacity,uint32_t *length) { assert(id>=2 && id<=3 && capacity>=64); ++attempts; *length=0; @@ -37,7 +37,7 @@ void net_handle_arp_on(uint32_t id,const uint8_t *p,uint32_t n,struct net_arp_wa { (void)id;(void)p;(void)n;(void)w; } void net_handle_ipv4_on(uint32_t id,const uint8_t *p,uint32_t n,struct net_ping_wait *a, struct net_udp_wait *b,struct net_tcp_wait *c) { (void)id;(void)p;(void)n;(void)a;(void)b;(void)c; } -void net_ipv6_input_on(uint32_t id,const uint8_t *p,uint32_t n) { (void)id;(void)p;(void)n; } +void net_ipv6_input_on(struct net_namespace *ns, uint32_t id,const uint8_t *p,uint32_t n) { (void)ns; (void)id;(void)p;(void)n; } void net_tcp_service_sockets(void) { ++timers; } void net_ipv6_poll(void) {} void net_device_retry_registration(void) {} diff --git a/tools/tests/task8_block_ioctl_user_test.c b/tools/tests/task8_block_ioctl_user_test.c index 4044f8f6..bd743ceb 100644 --- a/tools/tests/task8_block_ioctl_user_test.c +++ b/tools/tests/task8_block_ioctl_user_test.c @@ -29,6 +29,7 @@ void kernel_free(void *p) { if (p) { assert(allocations); --allocations; free(p) bool user_range_ok(uint64_t address, uint64_t length) { return address == (uintptr_t)&result && length == sizeof(result) && !foreign_contention; } bool user_range_writable(uint64_t address, uint64_t length) { return user_range_ok(address, length); } +int user_range_readable(uint64_t address, uint64_t length) { return user_range_ok(address, length) ? 0 : -EFAULT; } int swap_prepare_user_range(struct task *task, uint64_t address, uint64_t length, bool writing) { assert(task == ¤t && address == (uintptr_t)&result && length == sizeof(result)); if (pending_owner) return -EBUSY; diff --git a/tools/tests/task8_host_stubs/block-ioctl-user-candidate-1-block-ioctl-user-candidate-1.stub.c b/tools/tests/task8_host_stubs/block-ioctl-user-candidate-1-block-ioctl-user-candidate-1.stub.c index 656b8011..8ce71be5 100644 --- a/tools/tests/task8_host_stubs/block-ioctl-user-candidate-1-block-ioctl-user-candidate-1.stub.c +++ b/tools/tests/task8_host_stubs/block-ioctl-user-candidate-1-block-ioctl-user-candidate-1.stub.c @@ -1,5 +1,14 @@ /* SPDX-License-Identifier: Apache-2.0 */ /* Unreached host-fixture dependencies trap if invoked. */ +#include + +struct net_namespace; +/** @brief Trap if the block-only fixture reaches PTY number lookup. */ +__attribute__((noreturn)) uint32_t pty_number(uint32_t pty_id) +{ + (void)pty_id; + __builtin_trap(); +} /** @brief Trap if the block-only fixture reaches pipe byte accounting. */ __attribute__((noreturn)) void task_pipe_available(void) { __builtin_trap(); } /** @brief Trap if the block-only fixture reaches network interface control. */ @@ -7,7 +16,14 @@ __attribute__((noreturn)) void net_interface_ioctl(void) { __builtin_trap(); } /** @brief Trap if the block-only fixture reaches Internet socket family lookup. */ __attribute__((noreturn)) void task_inet_family(void) { __builtin_trap(); } /** @brief Trap if the block-only fixture reaches IPv6 interface control. */ -__attribute__((noreturn)) void net_ipv6_interface_ioctl(void) { __builtin_trap(); } +__attribute__((noreturn)) int net_ipv6_interface_ioctl(struct net_namespace *ns, + uint32_t request, uint64_t address) +{ + (void)ns; + (void)request; + (void)address; + __builtin_trap(); +} /** @brief Trap if the size-only fixture reaches registered block geometry. */ __attribute__((noreturn)) void block_device_info(void) { __builtin_trap(); } /** @brief Trap if the size-only fixture reaches block sequence querying. */ diff --git a/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c b/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c index 1ba0b794..8dd22160 100644 --- a/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c +++ b/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c @@ -1,5 +1,20 @@ /* SPDX-License-Identifier: Apache-2.0 */ /* Unreached host-fixture dependencies trap if invoked. */ +#include + +struct net_namespace; +struct in6_addr; +struct net_ipv6_path; +struct task_file; +/** @brief Trap if the INET ioctl fixture reaches netlink interface control. */ +__attribute__((noreturn)) int task_netlink_ioctl(struct task_file *file, + uint32_t request, uint64_t address) +{ + (void)file; + (void)request; + (void)address; + __builtin_trap(); +} /** @brief Trap if the fixture reaches unmodeled console_log. */ __attribute__((noreturn)) void console_log(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled copy_user_path. */ @@ -29,15 +44,48 @@ __attribute__((noreturn)) void netdev_poll(void) { __builtin_trap(); } /** @brief Trap if the ioctl-only fixture delivers a received packet frame. */ __attribute__((noreturn)) void net_packet_input_on(void) { __builtin_trap(); } /** @brief Trap if the ioctl-only fixture delivers an IPv6 frame. */ -__attribute__((noreturn)) void net_ipv6_input_on(void) { __builtin_trap(); } +__attribute__((noreturn)) void net_ipv6_input_on(struct net_namespace *ns, uint32_t ifindex, + const uint8_t *frame, uint32_t length) +{ + (void)ns; + (void)ifindex; + (void)frame; + (void)length; + __builtin_trap(); +} /** @brief Trap if the ioctl-only fixture runs IPv6 discovery maintenance. */ __attribute__((noreturn)) void net_ipv6_poll(void) { __builtin_trap(); } /** @brief Trap if the ioctl-only fixture selects an IPv6 transport route. */ -__attribute__((noreturn)) void net_ipv6_route(void) { __builtin_trap(); } +__attribute__((noreturn)) int net_ipv6_route(struct net_namespace *ns, + const struct in6_addr *destination, uint32_t scope, + const struct in6_addr *bound, struct net_ipv6_path *path) +{ + (void)ns; + (void)destination; + (void)scope; + (void)bound; + (void)path; + __builtin_trap(); +} /** @brief Trap if the ioctl-only fixture computes an IPv6 transport checksum. */ __attribute__((noreturn)) void net_ipv6_checksum(void) { __builtin_trap(); } /** @brief Trap if the ioctl-only fixture transmits an IPv6 packet. */ -__attribute__((noreturn)) void net_ipv6_output(void) { __builtin_trap(); } +__attribute__((noreturn)) int net_ipv6_output(struct net_namespace *ns, + const struct net_ipv6_path *path, uint8_t protocol, + const void *data, uint32_t length, int hops, + uint32_t flowinfo, bool dont_fragment, bool multicast_loop) +{ + (void)ns; + (void)path; + (void)protocol; + (void)data; + (void)length; + (void)hops; + (void)flowinfo; + (void)dont_fragment; + (void)multicast_loop; + __builtin_trap(); +} /** @brief Trap if the fixture reaches unmodeled net_udp_input. */ __attribute__((noreturn)) void net_udp_input(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled sched_sleep_current_until. */ diff --git a/tools/tests/tcp_state_test.c b/tools/tests/tcp_state_test.c index 14cbe405..a3250536 100644 --- a/tools/tests/tcp_state_test.c +++ b/tools/tests/tcp_state_test.c @@ -8,19 +8,19 @@ #include "../../net/proc.c" /* IPv4-only legacy state fixture: native IPv6 transport has its own link model. */ -__attribute__((weak)) uint32_t net_ipv6_addresses(struct net_ipv6_address *out,uint32_t cap) -{ (void)out; (void)cap; return 0; } -__attribute__((weak)) uint32_t net_ipv6_routes(struct net_ipv6_route *out,uint32_t cap) -{ (void)out; (void)cap; return 0; } -__attribute__((weak)) int net_ipv6_route(const struct in6_addr *dst,uint32_t scope, +__attribute__((weak)) uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out,uint32_t cap) +{ (void)ns; (void)out; (void)cap; return 0; } +__attribute__((weak)) uint32_t net_ipv6_routes(struct net_namespace *ns, struct net_ipv6_route *out,uint32_t cap) +{ (void)ns; (void)out; (void)cap; return 0; } +__attribute__((weak)) int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *dst,uint32_t scope, const struct in6_addr *bound,struct net_ipv6_path *path) -{ (void)dst; (void)scope; (void)bound; (void)path; return -LINUX_ENETUNREACH; } +{ (void)ns; (void)dst; (void)scope; (void)bound; (void)path; return -LINUX_ENETUNREACH; } __attribute__((weak)) uint16_t net_ipv6_checksum(const struct in6_addr *src,const struct in6_addr *dst, uint8_t protocol,const void *data,uint32_t length) { (void)src; (void)dst; (void)protocol; (void)data; (void)length; return 0; } -__attribute__((weak)) int net_ipv6_output(const struct net_ipv6_path *path,uint8_t protocol,const void *data, +__attribute__((weak)) int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,uint8_t protocol,const void *data, uint32_t length,int hops,uint32_t flowinfo,bool df,bool loop) -{ (void)path; (void)protocol; (void)data; (void)length; (void)hops; (void)flowinfo; (void)df; (void)loop; return -LINUX_ENETUNREACH; } +{ (void)ns; (void)path; (void)protocol; (void)data; (void)length; (void)hops; (void)flowinfo; (void)df; (void)loop; return -LINUX_ENETUNREACH; } __attribute__((weak)) bool net_ipv6_maintenance_pending(void) { return false; } __attribute__((weak)) void net_ipv6_poll(void) {} __attribute__((weak)) void net_ipv6_input(const uint8_t *frame,uint32_t length) { (void)frame; (void)length; } @@ -1262,10 +1262,10 @@ int netdev_poll(uint32_t index, void *frame, uint32_t capacity, uint32_t *length { (void)index; return e1000_poll(frame, capacity, length); } void netdev_counters(uint32_t index, struct net_proc_counters *out) { (void)index; *out = (struct net_proc_counters){0}; } -void net_ipv6_input_on(uint32_t index, const uint8_t *frame, uint32_t length) -{ (void)index; net_ipv6_input(frame,length); } +void net_ipv6_input_on(struct net_namespace *ns, uint32_t index, const uint8_t *frame, uint32_t length) +{ (void)ns; (void)index; net_ipv6_input(frame,length); } void net_packet_input_on(uint32_t index, const void *frame, uint32_t length) { (void)index; net_packet_input(frame,length); } -int net_ipv6_link_changed_on(uint32_t index, bool up) { (void)index; (void)up; return 0; } -void net_ipv6_detached_on(uint32_t index) { (void)index; } -void netlink_ipv6_changed(void) {} +int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index, bool up) { (void)ns; (void)index; (void)up; return 0; } +void net_ipv6_detached_on(struct net_namespace *ns, uint32_t index) { (void)ns; (void)index; } +void netlink_ipv6_changed(struct net_namespace *ns) { (void)ns; } diff --git a/tools/tests/udp_socket_test.c b/tools/tests/udp_socket_test.c index 124373fb..b23ab315 100644 --- a/tools/tests/udp_socket_test.c +++ b/tools/tests/udp_socket_test.c @@ -34,19 +34,19 @@ void net_poll_packets(void) {} /* This legacy fixture exercises IPv4 only; IPv6 dependencies are supplied by * the dedicated IPv6 transport fixture with an actual deferred link model. */ __attribute__((weak)) void kernel_poll_readiness_notify(void) {} -__attribute__((weak)) uint32_t net_ipv6_addresses(struct net_ipv6_address *out,uint32_t capacity) -{ (void)out; (void)capacity; return 0; } -__attribute__((weak)) int net_ipv6_route(const struct in6_addr *destination,uint32_t scope, +__attribute__((weak)) uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out,uint32_t capacity) +{ (void)ns; (void)out; (void)capacity; return 0; } +__attribute__((weak)) int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination,uint32_t scope, const struct in6_addr *bound,struct net_ipv6_path *path) -{ (void)destination; (void)scope; (void)bound; (void)path; return -LINUX_ENETUNREACH; } +{ (void)ns; (void)destination; (void)scope; (void)bound; (void)path; return -LINUX_ENETUNREACH; } __attribute__((weak)) uint16_t net_ipv6_checksum(const struct in6_addr *source,const struct in6_addr *destination, uint8_t protocol,const void *data,uint32_t length) { (void)source; (void)destination; (void)protocol; (void)data; (void)length; return 0; } -__attribute__((weak)) int net_ipv6_output(const struct net_ipv6_path *path,uint8_t protocol,const void *data, +__attribute__((weak)) int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,uint8_t protocol,const void *data, uint32_t length,int hops,uint32_t flowinfo,bool df,bool multicast_loop) -{ (void)path; (void)protocol; (void)data; (void)length; (void)hops; (void)flowinfo; (void)df; (void)multicast_loop; return -LINUX_ENETUNREACH; } -__attribute__((weak)) int net_ipv6_multicast_change(const struct in6_addr *address,uint32_t ifindex,int delta) -{ (void)address; (void)ifindex; (void)delta; return -LINUX_ENETUNREACH; } +{ (void)ns; (void)path; (void)protocol; (void)data; (void)length; (void)hops; (void)flowinfo; (void)df; (void)multicast_loop; return -LINUX_ENETUNREACH; } +__attribute__((weak)) int net_ipv6_multicast_change(struct net_namespace *ns, const struct in6_addr *address,uint32_t ifindex,int delta) +{ (void)ns; (void)address; (void)ifindex; (void)delta; return -LINUX_ENETUNREACH; } #endif int net_ipv4_send_udp(uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length) From 2dc010198f8f0f547ee3cee19b8c921881ad7639 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 06:02:54 +0800 Subject: [PATCH 74/97] feat(net): isolate UDP transport by creating network namespace --- Documentation/core-api/mount-namespaces.rst | 6 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 31 +- .../en/LC_MESSAGES/userspace-api/ipv6.po | 27 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 27 +- .../ja/LC_MESSAGES/userspace-api/ipv6.po | 24 +- Documentation/userspace-api/ipv6.rst | 4 +- include/reliefnt/net.h | 4 +- include/reliefnt/net_namespace.h | 2 + include/reliefnt/net_udp.h | 33 +- include/reliefnt/proc_stats.h | 10 +- kernel/syscall/device/legacy_ioctl.c | 5 +- net/core.c | 2 +- net/ipv4/udp.c | 14 +- net/proc.c | 14 +- net/socket/control.c | 8 +- net/socket/packet.c | 9 +- net/socket/udp.c | 182 ++++++----- tools/test_ipv6_transport.py | 3 +- tools/test_network.py | 5 +- tools/tests/ipv6_control_test.c | 6 +- tools/tests/ipv6_transport_test.c | 101 +++++- tools/tests/ipv6_vector_test.c | 5 +- tools/tests/net_multinic_data_test.c | 8 +- tools/tests/task8_host_fixtures.json | 8 + ...ate-3-inet-message-user-candidate-3.stub.c | 52 ++- ...didate-3-net-ioctl-user-candidate-3.stub.c | 9 +- tools/tests/task8_net_ioctl_user_test.c | 33 ++ tools/tests/tcp_state_test.c | 12 +- tools/tests/udp_socket_test.c | 300 +++++++++++++++++- 29 files changed, 701 insertions(+), 243 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 33edbcb3..302c1d81 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -158,13 +158,13 @@ hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护 网络空间生命周期 ================ -``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。 +``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink 和 UDP 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。 每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 ``127.0.0.1/8``、``::1/128`` 和 IPv6 host route。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由、IPv6 协议资源和 owner 引用。 -网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用,允许 transport 回调释放最后一个外部引用。初始网络重新初始化保留其他活跃空间。transport registry 的网络隔离仍待完成。 +网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。TCP 和 raw transport 的网络隔离仍待完成。 -``/proc/net/dev``、``route``、``if_inet6`` 和 ``ipv6_route`` 按调用者当前网络 scope 输出。非初始空间的 ``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``unix`` 按真实 socket scope 枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。 +``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp``、``tcp``、``tcp6`` 和 ``raw6`` 仅输出表头。 用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 transport 隔离完成后接通。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 4c6feb20..67a19654 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -430,8 +430,8 @@ msgstr "``struct uts_namespace`` uses atomic reference counting. Tasks and nsfs msgid "网络空间生命周期" msgstr "Network namespace lifetime" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" -msgstr "``net_namespace_create()`` creates a reference-counted network namespace with an immutable user owner. ``NULL`` denotes the permanent initial network namespace. Tasks share the namespace on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix and netlink socket independently retains its creating network namespace until its final reference closes. Unix server connections inherit the listener namespace." +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink 和 UDP 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。" +msgstr "``net_namespace_create()`` creates a reference-counted network namespace with an immutable user owner. ``NULL`` denotes the permanent initial network namespace. Tasks share it on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix, netlink and UDP socket independently retains its creating network until its final reference closes. Unix server connections inherit the listener network. Failed UDP allocation or FD installation releases the candidate object. Final close removes the registry entry before releasing multicast memberships, received datagrams and the network reference." msgid "" "每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 " @@ -444,30 +444,11 @@ msgstr "" "remain in the initial network. The final namespace reference releases interfaces, explicit " "IPv4 routes, IPv6 resources and the owner reference." -msgid "" -"网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket " -"创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 " -"地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用,允许 transport " -"回调释放最后一个外部引用。初始网络重新初始化保留其他活跃空间。transport registry 的网络隔离仍待完成。" -msgstr "" -"Network namespaces scope Unix abstract addresses, proc enumeration, netlink ports and message" -" delivery. Netlink interface, IPv4/IPv6 address and route queries and changes use the " -"socket's retained creating network, with changes requiring ``CAP_NET_ADMIN`` in its user " -"owner. IPv6 addresses, routes, neighbors, multicast, pending packets, reassembly, PMTU, " -"fragment identifiers and ICMP error rate limits are isolated by network. Maintenance visits " -"live protocol states and retains the serviced namespace across transport callbacks that can " -"release its final external reference. Reinitializing the initial network preserves other live" -" scopes. Transport registry network isolation remains pending." +msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。TCP 和 raw transport 的网络隔离仍待完成。" +msgstr "Network namespaces scope Unix abstract addresses, proc enumeration, netlink ports and message delivery. Netlink interface, IPv4/IPv6 address and route queries and changes use the socket's retained creating network, with changes requiring ``CAP_NET_ADMIN`` in its user owner. IPv6 addresses, routes, neighbors, multicast, pending packets, reassembly, PMTU, fragment identifiers and ICMP error rate limits are isolated by network. Maintenance visits live protocol states while retaining the serviced network. Reinitializing the initial network preserves other live networks. UDP port conflicts, IPv4/IPv6 and mapped-address delivery, ICMPv6 errors, multicast and device options match the creating network across OFD transfer or task network changes. Privileged ports require ``CAP_NET_BIND_SERVICE`` in that network's user owner. Local sends check the network's route and interface readiness. ReliefOS private global network control on noninitial UDP sockets returns ``EOPNOTSUPP``. TCP and raw transport network isolation remains pending." -msgid "" -"``/proc/net/dev``、``route``、``if_inet6`` 和 ``ipv6_route`` 按调用者当前网络 scope 输出。非初始空间的 " -"``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``unix`` 按真实 socket scope " -"枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。" -msgstr "" -"``/proc/net/dev``, ``route``, ``if_inet6`` and ``ipv6_route`` follow the caller's current " -"network scope. In other networks, ``arp``, ``udp``, ``tcp``, ``tcp6``, ``udp6`` and ``raw6`` " -"contain only headers. ``unix`` enumerates actual socket scopes. Noninitial ``dev`` currently " -"reports zero ``lo`` counters." +msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp``、``tcp``、``tcp6`` 和 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/dev``, ``route``, ``if_inet6``, ``ipv6_route``, ``udp``, ``udp6`` and ``unix`` follow the caller's current network scope. UDP rows report actual receive queues and numeric inodes. IPv4 local UDP delivery counters belong to the corresponding network. Noninitial ``arp``, ``tcp``, ``tcp6`` and ``raw6`` views contain only headers." msgid "" "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po index 6d4dc0a2..0950f9c4 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po @@ -57,19 +57,8 @@ msgstr "" msgid "配置与观测" msgstr "Configuration and Observation" -msgid "" -"``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD " -"后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 " -"IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。当前 INET socket 的 ioctl " -"仍使用初始网络,随 transport 隔离接通创建网络。" -msgstr "" -"``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 addresses and routes " -"in the network scope retained when the socket was created, including after FD transfer. " -"Changes require ``CAP_NET_ADMIN`` in that network owner's user namespace. ``getifaddrs()`` " -"obtains that scope's IPv6 addresses through standard queries. IPv6 address and route ioctls " -"use the selected network's state and owner authority, with argument layouts selected by " -"socket family. INET socket ioctls currently select the initial network and will retain the " -"creating network with transport isolation." +msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。TCP 和 raw socket 的 ioctl 随其 transport 隔离接通。" +msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 addresses and routes in the network scope retained when the socket was created, including after FD transfer. Changes require ``CAP_NET_ADMIN`` in the network owner's user namespace. ``getifaddrs()`` obtains that scope's IPv6 addresses through standard queries. IPv6 address and route ioctls use the selected network's state and owner authority, with layouts selected by socket family. UDP interface, IPv6 address and route ioctls use the creating network. TCP and raw socket ioctls will follow their transport isolation." msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" msgstr "Route multicast supports link, IPv6 address and IPv6 route groups. IPv4 address and route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``. Each network namespace maintains its own subscription snapshots, published after all captures succeed and released when its final subscriber closes or unsubscribes. Change notifications and overruns are delivered by network scope. Receive queue overflow reports ``ENOBUFS``, and callers should query again." @@ -83,16 +72,8 @@ msgstr "" "empty query result. Receivers must still iterate all messages in each datagram until the matching " "``NLMSG_DONE`` or an error arrives." -msgid "" -"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope " -"的编码与 rtnetlink 的 scope 值不同。地址和路由按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。transport " -"表仍属于初始网络,非初始空间的 ``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。" -msgstr "" -"``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text " -"layouts. Address scope encodings differ from rtnetlink scope values. Addresses and routes " -"follow the caller's current network scope. Snapshots copy internal state and retain only " -"copies across waits. Transport tables currently belong to the initial network, and ``tcp6``, " -"``udp6`` and ``raw6`` in other networks contain only their headers." +msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由和 UDP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。TCP 和 raw transport 的网络隔离仍待完成,非初始空间的 ``tcp6`` 和 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text layouts. Address scope encodings differ from rtnetlink scope values. Addresses, routes and UDP tables follow the caller's current network scope. Snapshots copy internal state and retain only copies across waits. TCP and raw transport isolation remains pending, and their ``tcp6`` and ``raw6`` views in noninitial networks contain only headers." msgid "" "每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index bac8efff..964780a4 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -380,8 +380,8 @@ msgstr "``struct uts_namespace`` はアトミックな参照カウントを使 msgid "网络空间生命周期" msgstr "ネットワーク名前空間の寿命" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix 和 netlink 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。" -msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク名前空間を作成します。``NULL`` は永続的な初期ネットワーク名前空間を表します。タスクは fork 時にこの空間を共有し、exec と ID の消去を通じて参照を保持し、wait による回収時またはスロットの再利用時に解放します。各 Unix および netlink ソケットは作成時のネットワーク名前空間を個別に保持し、最後の参照が閉じられると解放します。Unix のサーバー側接続はリスナーの名前空間を継承します。" +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink 和 UDP 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。" +msgstr "``net_namespace_create()`` は不変の user owner を持つ参照カウント付きネットワーク空間を作成し、``NULL`` は永続的な初期ネットワーク空間を表します。タスクは fork で空間を共有し、exec と識別情報の整理を通じて参照を保持し、wait による回収やスロット再利用時に解放します。Unix、netlink、UDP の各ソケットは作成元ネットワークを独立して保持し、最後の参照を閉じる際に解放します。Unix のサーバー接続はリスナーの空間を継承します。UDP のメモリ確保または FD 登録に失敗すると候補オブジェクトを解放します。最後の close は registry から削除した後、多播メンバーシップ、受信キュー、ネットワーク参照を解放します。" msgid "" "每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 " @@ -392,26 +392,11 @@ msgstr "" "でアドレスを持たず、最初の up で ``127.0.0.1/8``、``::1/128``、IPv6 host route を設定します。物理 NIC 登録と ingress " "は初期空間に属します。最後の空間参照を解放すると、インターフェース、明示的な IPv4 経路、IPv6 資源、owner 参照も解放します。" -msgid "" -"网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket " -"创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 " -"地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用,允许 transport " -"回调释放最后一个外部引用。初始网络重新初始化保留其他活跃空间。transport registry 的网络隔离仍待完成。" -msgstr "" -"ネットワーク名前空間は Unix 抽象アドレス、proc 列挙、netlink ポート、メッセージ配送の範囲を定めます。netlink のインターフェース、IPv4/IPv6 " -"アドレス、経路の照会と変更は socket が保持する作成時のネットワークを使用し、変更には user owner の ``CAP_NET_ADMIN`` が必要です。IPv6 " -"アドレス、経路、近隣、多播、送信待ち、再構成、PMTU、断片番号、ICMP " -"エラーレート制限は空間ごとに分離します。保守処理は活性プロトコル状態を巡回し、処理中の空間を参照で保持するため、transport " -"コールバックは最後の外部参照を解放できます。初期ネットワークの再初期化は他の活性空間を保持します。transport registry のネットワーク分離は今後実装します。" +msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。TCP 和 raw transport 的网络隔离仍待完成。" +msgstr "ネットワーク空間は Unix 抽象アドレス、proc 列挙、netlink ポート、メッセージ配送に scope を与えます。netlink のインターフェース、IPv4/IPv6 アドレス、経路の照会と変更はソケットが保持する作成元ネットワークを使用し、変更にはその user owner の ``CAP_NET_ADMIN`` が必要です。IPv6 アドレス、経路、近隣、多播、送信待ちパケット、再構成、PMTU、フラグメント ID、ICMP エラー制限はネットワークごとに隔離します。保守処理は対象空間の参照を保持して稼働中のプロトコル状態を巡回します。初期ネットワークの再初期化は他の稼働中空間を保持します。UDP のポート競合、IPv4/IPv6 とマップアドレスの送受信、ICMPv6 エラー、多播、デバイスオプションは OFD 転送やタスクのネットワーク変更後も作成元空間で照合します。特権ポートにはそのネットワークの user owner における ``CAP_NET_BIND_SERVICE`` が必要です。ローカル送信は対象空間の経路とインターフェースの準備状態を確認します。非初期 UDP ソケットの ReliefOS 独自グローバルネットワーク制御は ``EOPNOTSUPP`` を返します。TCP と raw transport のネットワーク隔離は今後の実装対象です。" -msgid "" -"``/proc/net/dev``、``route``、``if_inet6`` 和 ``ipv6_route`` 按调用者当前网络 scope 输出。非初始空间的 " -"``arp``、``udp``、``tcp``、``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头,``unix`` 按真实 socket scope " -"枚举。非初始空间的 ``dev`` 中 ``lo`` 计数当前为零。" -msgstr "" -"``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route`` は呼び出し元の現在のネットワーク scope に従います。非初期空間の " -"``arp``、``udp``、``tcp``、``tcp6``、``udp6``、``raw6`` はヘッダーだけを出力し、``unix`` は実際の socket scope " -"を列挙します。非初期空間の ``dev`` の ``lo`` カウンターは現在ゼロです。" +msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp``、``tcp``、``tcp6`` 和 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``unix`` は呼び出し元の現在のネットワーク scope に従います。UDP の行は実際の受信キューと数値 inode を表示し、IPv4 のローカル UDP 配送カウンターは対応するネットワークに属します。非初期空間の ``arp``、``tcp``、``tcp6``、``raw6`` はヘッダーだけを出力します。" msgid "" "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po index f976478e..2e696cf3 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po @@ -52,17 +52,8 @@ msgstr "" msgid "配置与观测" msgstr "設定と観測" -msgid "" -"``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD " -"后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 " -"IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。当前 INET socket 的 ioctl " -"仍使用初始网络,随 transport 隔离接通创建网络。" -msgstr "" -"``AF_NETLINK`` / ``NETLINK_ROUTE`` は socket 作成時に保持したネットワーク scope のリンク、IPv4/IPv6 " -"アドレス、経路を照会・変更し、FD 転送後も同じ scope を使用します。変更にはネットワーク owner のユーザー名前空間の ``CAP_NET_ADMIN`` " -"が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 アドレスを取得します。IPv6 アドレス・経路 ioctl は選択したネットワークの状態と owner " -"権限を使用し、socket family に応じた引数配置を選びます。現在の INET socket ioctl は初期ネットワークを選択し、transport " -"分離とともに作成時のネットワークを使用するようになります。" +msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。TCP 和 raw socket 的 ioctl 随其 transport 隔离接通。" +msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` はソケット作成時に保持したネットワーク scope のリンク、IPv4/IPv6 アドレス、経路を照会・変更し、FD 転送後もその scope を使用します。変更にはネットワークの user owner における ``CAP_NET_ADMIN`` が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 アドレスを取得します。IPv6 アドレスと経路の ioctl は対象ネットワークの状態と owner 権限を使用し、引数形式は socket family で選択します。UDP のインターフェース、IPv6 アドレス、経路 ioctl は作成元ネットワークを使用します。TCP と raw socket の ioctl は各 transport の隔離に合わせて対応します。" msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" msgstr "ルートマルチキャストはリンク、IPv6 アドレス、IPv6 ルートのグループに対応します。IPv4 アドレスとルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。各ネットワーク名前空間は独立した購読スナップショットを保持し、すべての取得が成功してから公開します。最後の購読者が閉じるか購読を解除すると解放します。変更通知と overrun はネットワーク scope ごとに配信し、受信キューのオーバーフローは ``ENOBUFS`` を報告するため、呼び出し元は再照会してください。" @@ -74,15 +65,8 @@ msgstr "" "複数部分からなる問い合わせでは、データと終端の ``NLMSG_DONE`` を別々のデータグラムとして送信します。終端マーカーは要求のシーケンス番号と受信ポート ID " "を保持し、結果が空でも送信します。受信側は引き続き各データグラム内の全メッセージを走査し、対応する番号の ``NLMSG_DONE`` またはエラーを待つ必要があります。" -msgid "" -"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope " -"的编码与 rtnetlink 的 scope 值不同。地址和路由按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。transport " -"表仍属于初始网络,非初始空间的 ``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。" -msgstr "" -"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト配置を使用し、アドレス " -"scope の符号化は rtnetlink の scope 値と異なります。アドレスと経路は呼び出し元の現在のネットワーク scope " -"に従います。スナップショットは内部状態を複写し、待機をまたいで複写だけを保持します。transport テーブルは現在初期ネットワークに属し、他の空間の " -"``tcp6``、``udp6``、``raw6`` はヘッダーだけを出力します。" +msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由和 UDP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。TCP 和 raw transport 的网络隔离仍待完成,非初始空间的 ``tcp6`` 和 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト形式を使用します。アドレス scope の符号化は rtnetlink の scope 値と異なります。アドレス、経路、UDP 表は呼び出し元の現在のネットワーク scope に従います。スナップショットは内部状態をコピーし、待機をまたいでコピーを保持します。TCP と raw transport のネットワーク隔離は今後の実装対象で、非初期ネットワークの ``tcp6`` と ``raw6`` はヘッダーだけを出力します。" msgid "" "每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" diff --git a/Documentation/userspace-api/ipv6.rst b/Documentation/userspace-api/ipv6.rst index b3b48b46..102c8873 100644 --- a/Documentation/userspace-api/ipv6.rst +++ b/Documentation/userspace-api/ipv6.rst @@ -32,7 +32,7 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 配置与观测 ========== -``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。当前 INET socket 的 ioctl 仍使用初始网络,随 transport 隔离接通创建网络。 +``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。TCP 和 raw socket 的 ioctl 随其 transport 隔离接通。 路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。 @@ -40,7 +40,7 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。 -``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址和路由按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。transport 表仍属于初始网络,非初始空间的 ``tcp6``、``udp6`` 和 ``raw6`` 仅输出表头。 +``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由和 UDP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。TCP 和 raw transport 的网络隔离仍待完成,非初始空间的 ``tcp6`` 和 ``raw6`` 仅输出表头。 每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。 diff --git a/include/reliefnt/net.h b/include/reliefnt/net.h index 71727077..0bfc55ec 100644 --- a/include/reliefnt/net.h +++ b/include/reliefnt/net.h @@ -334,10 +334,12 @@ bool net_interface_admin_up(void); int net_ipv4_send_raw_on(uint32_t ifindex, uint32_t destination, uint32_t source, uint8_t protocol, bool header_included, const void *data, uint32_t length); /** @brief Transmit a UDP message through the selected interface and route. + * @param ns Borrowed network, NULL for the initial network. Hardware output + * requires the initial network and a physical route. * @param ifindex Bound output device or zero. @param source Optional bound source. * @param destination Peer IPv4. @param source_port Local port. @param destination_port Peer port. * @param data Borrowed payload. @param length Byte count. @return Zero or negative errno. */ -int net_ipv4_send_udp_on(uint32_t ifindex, uint32_t source, uint32_t destination, +int net_ipv4_send_udp_on(struct net_namespace *ns, uint32_t ifindex, uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length); diff --git a/include/reliefnt/net_namespace.h b/include/reliefnt/net_namespace.h index 0b50da0c..e91894d1 100644 --- a/include/reliefnt/net_namespace.h +++ b/include/reliefnt/net_namespace.h @@ -19,6 +19,8 @@ struct net_namespace { struct net_interface loopback; struct net_ipv4_route_node *ipv4_routes; struct net_ipv6_state *ipv6; + uint64_t udp_loopback_bytes; + uint64_t udp_loopback_packets; }; /** @brief Allocate an empty network identity and retain its user owner. diff --git a/include/reliefnt/net_udp.h b/include/reliefnt/net_udp.h index 26bc0a77..05af6576 100644 --- a/include/reliefnt/net_udp.h +++ b/include/reliefnt/net_udp.h @@ -3,6 +3,7 @@ #include #include struct task_file; +struct net_namespace; #define TASK_FILE_KIND_UDP 2u int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5); @@ -19,6 +20,11 @@ struct net_udp_rx_info { /** @brief Determine the socket's native source-address size. * @param file Pinned UDP OFD. @return Address size, or zero for invalid OFD. */ uint32_t task_udp_address_size(const struct task_file *file); +/** @brief Borrow the UDP open description's retained creation network. + * @param file Pinned canonical UDP OFD. @return Borrowed network, or NULL for + * the initial network or an invalid description. No reference is transferred. + */ +struct net_namespace *task_udp_namespace(const struct task_file *file); /** @brief Receive into owned buffers, including source and IPv6 packet metadata. * @param file Pinned UDP OFD. @param data Kernel output. @param length Capacity. * @param flags Receive flags. @param source Optional native sockaddr storage. @@ -45,20 +51,31 @@ struct text_stream; * @param destination_port Peer port. @param error Positive errno. @param mtu Reported MTU. */ void net_udp6_error(const struct in6_addr *source,const struct in6_addr *destination, uint16_t source_port,uint16_t destination_port,int error,uint32_t mtu); -/** @brief Render live IPv6 UDP endpoints into a proc slice. - * @param stream Caller-owned proc output. */ -void net_udp6_proc_emit(struct text_stream *stream); -void net_udp_input(uint32_t source, uint32_t destination, uint16_t source_port, +/** @brief Render live IPv6 UDP endpoints in the selected network. + * @param ns Borrowed network, NULL for the initial network. + * @param stream Caller-owned proc output under execution ownership. */ +void net_udp6_proc_emit(struct net_namespace *ns, struct text_stream *stream); +/** @brief Deliver a checked IPv4 datagram to endpoints in its ingress network. + * @param ns Borrowed network, NULL for the initial network. + * @param source Source IPv4. @param destination Destination IPv4. + * @param source_port Peer port. @param destination_port Local port. + * @param data Borrowed payload. @param length Bytes. @param ifindex Ingress link. + * Caller holds execution ownership and retains the network across delivery. + */ +void net_udp_input(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length, int ifindex); -/** @brief Deliver a checked ICMPv6 error only to UDP state on the matching link. +/** @brief Deliver a checked ICMPv6 error to UDP state in its network and link. + * @param ns Borrowed network, NULL for the initial network. * @param ifindex Link or zero. @param source Local. @param destination Peer. * @param source_port Local port. @param destination_port Peer port. * @param error Positive errno. @param mtu Reported MTU. */ -void net_udp6_error_on(uint32_t ifindex, const struct in6_addr *source, +void net_udp6_error_on(struct net_namespace *ns, uint32_t ifindex, const struct in6_addr *source, const struct in6_addr *destination, uint16_t source_port, uint16_t destination_port, int error, uint32_t mtu); -/** @brief Wake UDP sockets bound to a disappearing device. @param ifindex Device. */ -void net_udp_device_detached(uint32_t ifindex); +/** @brief Wake UDP sockets bound to a disappearing device in its network. + * @param ns Borrowed network, NULL for the initial network. @param ifindex Device. + * Caller holds execution ownership. No references escape. */ +void net_udp_device_detached(struct net_namespace *ns, uint32_t ifindex); #endif diff --git a/include/reliefnt/proc_stats.h b/include/reliefnt/proc_stats.h index 07e948eb..328aff28 100644 --- a/include/reliefnt/proc_stats.h +++ b/include/reliefnt/proc_stats.h @@ -5,6 +5,7 @@ #include struct task; struct task_file; +struct net_namespace; struct linux_timespec; /** @brief Emit specialized eventfd/timerfd/epoll details without consuming events. * @param file Borrowed canonical OFD. @param s Required output. @@ -63,14 +64,17 @@ void sched_proc_snapshot(struct sched_proc_stats *out); * @return Zero or ENOENT. Caller holds kernel execution ownership. */ int net_proc_emit(struct text_stream *s, const char *leaf); -/** @brief Emit IPv4 UDP rows under caller execution ownership, without pointers. +/** @brief Emit IPv4 UDP rows in the selected network, without pointers. + * @param ns Borrowed network, NULL for the initial network. * @param s Required stream; no references escape or hardware is polled. + * Caller holds execution ownership. */ -void net_udp_proc_emit(struct text_stream *s); +void net_udp_proc_emit(struct net_namespace *ns, struct text_stream *s); /** @brief Emit successful local UDP delivery counters without polling devices. + * @param ns Borrowed network, NULL for the initial network. * @param s Required output stream; caller holds execution ownership. */ -void net_loopback_proc_emit(struct text_stream *s); +void net_loopback_proc_emit(struct net_namespace *ns, struct text_stream *s); /** @brief Emit UNIX sockets from the caller's network namespace without pointers. * @param s Required output stream; abstract names use the Linux @ convention. */ diff --git a/kernel/syscall/device/legacy_ioctl.c b/kernel/syscall/device/legacy_ioctl.c index 6b6a2c7a..eb180953 100644 --- a/kernel/syscall/device/legacy_ioctl.c +++ b/kernel/syscall/device/legacy_ioctl.c @@ -3,6 +3,7 @@ extern int64_t task_inotify_fionread(struct task *, const struct task_file *, uint64_t) __attribute__((weak)); #include #include +#include #include #include @@ -320,6 +321,7 @@ static int64_t fb_user_blit(struct task *task,const struct framebuffer *fb,uint6 * @note The caller retains the kernel execution transaction and descriptor pins. * TIOCGPTN returns the master session's instance-local devpts index. * Privileged device and console controls require capabilities in the initial user namespace. + * UDP IPv6 network controls select the pinned socket's creation network and user owner. */ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) { @@ -350,7 +352,8 @@ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t return task_socket_ioctl(file, a1, a2); if (file && (file->flags & TASK_FILE_FLAG_SOCKET_INET) && task_inet_family(file) == AF_INET6 && (a1 == SIOCSIFADDR || a1 == SIOCDIFADDR || a1 == SIOCADDRT || a1 == SIOCDELRT)) - return net_ipv6_interface_ioctl(NULL, (uint32_t)a1, a2); + return net_ipv6_interface_ioctl(file->kind == TASK_FILE_KIND_UDP ? + task_udp_namespace(file) : NULL, (uint32_t)a1, a2); if (file && (file->flags & TASK_FILE_FLAG_SOCKET_INET)) return task_net_control(file, (uint32_t)a1, a2); if (file && (file->node.flags & STORAGE_NODE_FLAG_DEV_NODE) && diff --git a/net/core.c b/net/core.c index c6bc08fd..2f9ac9e5 100644 --- a/net/core.c +++ b/net/core.c @@ -104,7 +104,7 @@ void net_device_detached(uint32_t ifindex) net_socket_mark_closed(s, RELIEFOS_NET_STATUS_NO_DEVICE); } } - net_udp_device_detached(ifindex); + net_udp_device_detached(NULL, ifindex); net_packet_device_detached(ifindex); net_ipv6_detached_on(NULL, ifindex); net_arp_cache_clear_on(ifindex); diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c index 0c5fecf2..f9bfe74c 100644 --- a/net/ipv4/udp.c +++ b/net/ipv4/udp.c @@ -80,7 +80,7 @@ void net_handle_udp_on(uint32_t ifindex, const uint8_t *ip, uint32_t total_len, sum += IPV4_PROTO_UDP + udp_len; if (net_checksum_finish(net_checksum_partial(sum, udp, udp_len))) return; } - net_udp_input(src_ip, net_get_u32(ip + 16), src_port, dst_port, udp + 8, udp_len - 8, (int)ifindex); + net_udp_input(NULL, src_ip, net_get_u32(ip + 16), src_port, dst_port, udp + 8, udp_len - 8, (int)ifindex); if (!udp_wait || udp_wait->done || (udp_wait->ifindex && udp_wait->ifindex != ifindex)) return; if (udp_wait->src_port && src_port != udp_wait->src_port) { return; @@ -110,19 +110,21 @@ void net_handle_udp(const uint8_t *ip, uint32_t total_len, uint32_t ihl, } /** @brief Send an IPv4 datagram with an explicit bound interface or route selection. + * @param ns Borrowed route network. Hardware output belongs to the initial network. * @param ifindex Bound device or zero. @param source Optional source address. * @param destination Peer address. @param source_port Local port. @param destination_port Peer port. * @param data Borrowed payload. @param length Bytes. @return Zero or negative errno. */ -int net_ipv4_send_udp_on(uint32_t ifindex, uint32_t source, uint32_t destination, +int net_ipv4_send_udp_on(struct net_namespace *ns, uint32_t ifindex, uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length) { if (length > 1472 || (length && !data)) return -LINUX_EMSGSIZE; struct net_ipv4_path path; - int result = net_ipv4_route_lookup(NULL, destination, source, ifindex, &path); + int result = net_ipv4_route_lookup(ns, destination, source, ifindex, &path); if (result < 0) return result; + if (ns || path.ifindex == NET_IF_LOOPBACK) return -LINUX_ENETUNREACH; uint8_t mac[6]; - struct net_interface *interface = net_interface_get(NULL, path.ifindex); + struct net_interface *interface = net_interface_get(ns, path.ifindex); if (destination == UINT32_MAX || (interface && destination == interface->broadcast)) net_memcpy(mac, net_broadcast_mac, 6); else if (net_resolve_mac_on(path.ifindex, path.next_hop, 1000, mac) < 0) @@ -132,14 +134,14 @@ int net_ipv4_send_udp_on(uint32_t ifindex, uint32_t source, uint32_t destination return result < 0 ? result : 0; } -/** @brief Send UDP with automatic output device selection. +/** @brief Send initial-network UDP with automatic output device selection. * @param source Optional source. @param destination Peer. @param source_port Local port. * @param destination_port Peer port. @param data Payload. @param length Bytes. * @return Zero or negative errno. */ int net_ipv4_send_udp(uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length) { - return net_ipv4_send_udp_on(0, source, destination, source_port, destination_port, data, length); + return net_ipv4_send_udp_on(NULL, 0, source, destination, source_port, destination_port, data, length); } /** @brief Build a legacy UDP frame using destination-based route selection. diff --git a/net/proc.c b/net/proc.c index ce8c7dab..4bba51de 100644 --- a/net/proc.c +++ b/net/proc.c @@ -2,6 +2,7 @@ #include "internal.h" #include #include +#include #include /** @brief Emit the 16 address octets in Linux proc's contiguous hexadecimal form. @@ -89,7 +90,11 @@ int net_proc_emit(struct text_stream *s, const char *leaf) return proc_ipv6_addresses(ns, s); if (!__builtin_strcmp(leaf, "ipv6_route")) return proc_ipv6_routes(ns, s); - if (!__builtin_strcmp(leaf, "tcp6") || !__builtin_strcmp(leaf, "udp6") || + if (!__builtin_strcmp(leaf, "udp6")) { + net_udp6_proc_emit(ns, s); + return 0; + } + if (!__builtin_strcmp(leaf, "tcp6") || !__builtin_strcmp(leaf, "raw6")) { if (!ns) net_ipv6_transport_proc_emit(s,leaf); else text_string(s, " sl local_address rem_address st tx_queue rx_queue tr tm->when " @@ -101,8 +106,7 @@ int net_proc_emit(struct text_stream *s, const char *leaf) "Transmit\n face |bytes packets errs drop fifo frame compressed " "multicast|bytes packets errs drop fifo colls carrier compressed\n"); /* Loopback datagrams are accounted by their owner rather than the NIC. */ - if (!ns) net_loopback_proc_emit(s); - else text_string(s, " lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n"); + net_loopback_proc_emit(ns, s); for (uint32_t index=net_interface_next(ns, NET_IF_LOOPBACK);index; index=net_interface_next(ns, index)) { struct net_proc_counters c; @@ -141,9 +145,7 @@ int net_proc_emit(struct text_stream *s, const char *leaf) if (!ns) net_arp_proc_emit(s); else text_string(s, "IP address HW type Flags HW address Mask Device\n"); } else if (!__builtin_strcmp(leaf, "udp")) { - if (!ns) net_udp_proc_emit(s); - else text_string(s, " sl local_address rem_address st tx_queue rx_queue tr tm->when " - "retrnsmt uid timeout inode\n"); + net_udp_proc_emit(ns, s); } else if (!__builtin_strcmp(leaf, "unix")) unix_proc_emit(s); else if (!__builtin_strcmp(leaf, "tcp")) { diff --git a/net/socket/control.c b/net/socket/control.c index 37415114..fa1663a3 100644 --- a/net/socket/control.c +++ b/net/socket/control.c @@ -16,8 +16,8 @@ * @param file Borrowed socket OFD under execution ownership. * @param request Native ioctl number. @param address User argument address. * @return Zero, negative errno, or a user-memory prerequisite wait marker. - * Netlink interface changes use the retained network's user owner. Internet - * transport and private control operations currently use the initial network. + * Netlink and UDP interface operations use the retained creation network and + * its user owner. Private global control on noninitial UDP returns EOPNOTSUPP. */ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) { @@ -43,9 +43,11 @@ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) if (request >= 0x8900 && request <= 0x89ff) { if (file->kind == TASK_FILE_KIND_NETLINK) return task_netlink_ioctl(file, request, address); - return net_interface_ioctl(NULL, request, address); + return net_interface_ioctl(file->kind == TASK_FILE_KIND_UDP ? + task_udp_namespace(file) : NULL, request, address); } if (request != RELIEFOS_NET_CONTROL_IOCTL) return -LINUX_ENOTTY; + if (file->kind == TASK_FILE_KIND_UDP && task_udp_namespace(file)) return -LINUX_EOPNOTSUPP; struct reliefos_net_control control; int rc=socket_user_import(task,address,&control,sizeof(control));if(rc)return rc; rc=socket_user_prepare(task,address,sizeof(control),true);if(rc)return rc; diff --git a/net/socket/packet.c b/net/socket/packet.c index a60a63fc..7177bd10 100644 --- a/net/socket/packet.c +++ b/net/socket/packet.c @@ -754,11 +754,11 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, /** @brief Report ICMPv6 errors to the socket owning the quoted protocol tuple. * @param ns Borrowed network, NULL for the permanent initial network. + * @param ifindex Ingress link or zero for no link filter. * @param packet Quoted original IPv6 packet. @param length Quote size. * @param error Positive Linux errno. @param mtu Reported path MTU or zero. */ void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex, const uint8_t *packet, uint32_t length, int error, uint32_t mtu) { - if (ns) return; if (!packet || length < 40 || packet[0] >> 4 != 6) return; struct in6_addr source, destination; __builtin_memcpy(&source, packet + 8, 16); __builtin_memcpy(&destination, packet + 24, 16); @@ -766,9 +766,10 @@ void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex, const if ((protocol == 6 || protocol == 17) && length >= 48) { uint16_t source_port = ((uint16_t)packet[40] << 8) | packet[41]; uint16_t destination_port = ((uint16_t)packet[42] << 8) | packet[43]; - if (protocol == 6) net_tcp6_error_on(ifindex, &source, &destination, source_port, destination_port, error, mtu); - else net_udp6_error_on(ifindex, &source, &destination, source_port, destination_port, error, mtu); + if (protocol == 6 && !ns) net_tcp6_error_on(ifindex, &source, &destination, source_port, destination_port, error, mtu); + else if (protocol == 17) net_udp6_error_on(ns, ifindex, &source, &destination, source_port, destination_port, error, mtu); } + if (ns) return; for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *s = sockets[i]; if (!s || s->domain != AF_INET6 || s->protocol != protocol || @@ -807,7 +808,7 @@ static void net_raw6_proc_emit(struct text_stream *stream) void net_ipv6_transport_proc_emit(struct text_stream *stream, const char *leaf) { if (!__builtin_strcmp(leaf,"tcp6")) net_tcp6_proc_emit(stream); - else if (!__builtin_strcmp(leaf,"udp6")) net_udp6_proc_emit(stream); + else if (!__builtin_strcmp(leaf,"udp6")) net_udp6_proc_emit(NULL, stream); else if (!__builtin_strcmp(leaf,"raw6")) net_raw6_proc_emit(stream); } diff --git a/net/socket/udp.c b/net/socket/udp.c index 124814d9..f73e38cd 100644 --- a/net/socket/udp.c +++ b/net/socket/udp.c @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include #include #include @@ -40,6 +42,7 @@ struct udp_packet { unsigned char data[]; }; struct udp_socket { + struct net_namespace *net_ns; uint32_t local, remote; struct in6_addr local6, remote6; uint32_t scope6, remote_scope6, multicast_if; @@ -66,6 +69,13 @@ static uint32_t swap32(uint32_t x) { return __builtin_bswap32(x); } static struct udp_socket *udp_from_file(struct task_file *file) { return file && file->kind == TASK_FILE_KIND_UDP ? (void *)(uintptr_t)file->aux : NULL; } +/** @copydoc task_udp_namespace */ +struct net_namespace *task_udp_namespace(const struct task_file *file) +{ + const struct udp_socket *s = udp_from_file((struct task_file *)file); + return s ? s->net_ns : NULL; +} + /** @brief Test whether an IPv6 address is unspecified. * @param address Network-order address. @return True for the all-zero address. */ static bool udp6_any(const struct in6_addr *address) @@ -120,16 +130,15 @@ static bool udp_ipv4_overlap(const struct udp_socket *s, uint32_t ip, * @param ip Requested local IPv4 address, or zero for any address. * @param port Requested local port, or zero for automatic allocation. * @return Zero on success or a negative errno. - * Binding a privileged port requires initial user namespace CAP_NET_BIND_SERVICE. + * Binding a privileged port requires CAP_NET_BIND_SERVICE in the network owner. */ static int bind_port(struct udp_socket *s, uint32_t ip, uint16_t port) { if (s->bound) return -LINUX_EINVAL; - struct reliefos_net_config config; - net_get_config(&config); - if (ip && !net_interface_for_ipv4(NULL, ip)) return -LINUX_EADDRNOTAVAIL; + if (ip && !net_interface_for_ipv4(s->net_ns, ip)) return -LINUX_EADDRNOTAVAIL; struct task *task = sched_current_task(); - if (port && port < 1024 && !(task_initial_capabilities(task) & (1ULL << CAP_NET_BIND_SERVICE))) + if (port && port < 1024 && + !task_ns_capable(task, s->net_ns ? s->net_ns->user_ns : NULL, CAP_NET_BIND_SERVICE)) return -LINUX_EACCES; for (unsigned attempt = 0; attempt < 16384; ++attempt) { uint16_t candidate = port ? port : next_port++; @@ -137,7 +146,7 @@ static int bind_port(struct udp_socket *s, uint32_t ip, uint16_t port) bool conflict = false; for (struct udp_socket *other = sockets; other; other = other->registry_next) { - if (other == s || !other->bound || other->port != candidate || + if (other == s || other->net_ns != s->net_ns || !other->bound || other->port != candidate || (s->reuse && other->reuse) || (s->ifindex && other->ifindex && s->ifindex != other->ifindex)) continue; if (udp_ipv4_overlap(s, ip, other)) conflict = true; @@ -156,6 +165,7 @@ static int bind_port(struct udp_socket *s, uint32_t ip, uint16_t port) /** * @brief Queue one received IPv4 datagram for each matching UDP endpoint. + * @param ns Borrowed ingress network, NULL for the initial network. * @param source Source IPv4 address. * @param destination Destination IPv4 address. * @param source_port Source transport port. @@ -164,11 +174,12 @@ static int bind_port(struct udp_socket *s, uint32_t ip, uint16_t port) * @param length Payload bytes. * @param ifindex Incoming interface index. */ -void net_udp_input(uint32_t source, uint32_t destination, uint16_t source_port, +void net_udp_input(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length, int ifindex) { if (length > UDP_MAX_PAYLOAD) return; for (struct udp_socket *s = sockets; s; s = s->registry_next) { + if (s->net_ns != ns) continue; if (s->ipv6 && (s->v6only || (!udp6_any(&s->local6) && !udp6_mapped(&s->local6)) || (s->connected && !udp6_mapped(&s->remote6)))) continue; @@ -200,11 +211,10 @@ bool net_udp6_input(struct net_namespace *ns, const struct in6_addr *source, con uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length, uint32_t ifindex, uint8_t hops) { - if (ns) return false; if (length > UDP6_MAX_PAYLOAD) return false; bool delivered = false; for (struct udp_socket *s = sockets; s; s = s->registry_next) { - if (!s->ipv6 || !s->bound || s->port != destination_port || + if (s->net_ns != ns || !s->ipv6 || !s->bound || s->port != destination_port || (s->ifindex && (uint32_t)s->ifindex != ifindex) || (s->scope6 && s->scope6 != ifindex) || (!udp6_any(&s->local6) && __builtin_memcmp(&s->local6, destination, sizeof(*destination))) || @@ -299,14 +309,14 @@ static int udp6_bind(struct udp_socket *s, const struct sockaddr_in6 *address) const struct in6_addr *ip = &address->sin6_addr; uint32_t scope = net_ipv6_needs_scope_id(ip) ? address->sin6_scope_id : 0; if (udp6_mapped(ip) && s->v6only) return -LINUX_EINVAL; - if (scope && !net_interface_exists(NULL, scope)) return -LINUX_ENODEV; + if (scope && !net_interface_exists(s->net_ns, scope)) return -LINUX_ENODEV; if (scope && s->ifindex && scope != (uint32_t)s->ifindex) return -LINUX_EINVAL; if (ip->s6_addr[0] == 0xfe && (ip->s6_addr[1] & 0xc0) == 0x80 && !scope) return -LINUX_EINVAL; if (!udp6_any(ip) && !udp6_mapped(ip) && ip->s6_addr[0] != 0xff) { struct net_ipv6_address entries[32]; - uint32_t count = net_ipv6_addresses(NULL, entries, 32); + uint32_t count = net_ipv6_addresses(s->net_ns, entries, 32); bool found = false; for (uint32_t i = 0; i < count && i < 32; ++i) if (!__builtin_memcmp(&entries[i].address, ip, sizeof(*ip)) && @@ -321,7 +331,42 @@ static int udp6_bind(struct udp_socket *s, const struct sockaddr_in6 *address) return ret; } -/** @brief Send native IPv6 UDP using the selected route and pseudo-header checksum. +/** @brief Send IPv4 UDP through the socket's retained network and route. + * @param s Owning socket. @param ip Host-order destination. @param port Peer port. + * @param data Borrowed payload. @param length Payload bytes. + * @return Accepted bytes or negative errno. Local delivery requires a ready + * interface and accounts traffic in the creating network under execution ownership. + */ +static int udp4_send(struct udp_socket *s, uint32_t ip, uint16_t port, + const void *data, uint32_t length) +{ + if (!port) return -LINUX_EINVAL; + if (ip == UINT32_MAX && !s->broadcast) return -LINUX_EACCES; + if (!s->bound) { + int ret = bind_port(s, 0, 0); + if (ret < 0) return ret; + } + struct net_ipv4_path path; + int ret = net_ipv4_route_lookup(s->net_ns, ip, s->local, (uint32_t)s->ifindex, &path); + if (ret < 0) return ret; + if (net_interface_for_ipv4(s->net_ns, ip)) { + if (!net_interface_is_ready(s->net_ns, path.ifindex)) return -LINUX_ENETDOWN; + if (s->net_ns) { + s->net_ns->udp_loopback_bytes += length + 28; + ++s->net_ns->udp_loopback_packets; + } else { + loopback_bytes += length + 28; + ++loopback_packets; + } + net_udp_input(s->net_ns, path.source, ip, s->port, port, data, length, (int)path.ifindex); + return (int)length; + } + ret = net_ipv4_send_udp_on(s->net_ns, path.ifindex, path.source, ip, + s->port, port, data, length); + return ret < 0 ? ret : (int)length; +} + +/** @brief Send native or mapped IPv6 UDP within the socket's creating network. * @param s Owning socket. @param data Borrowed payload. @param length Payload bytes. * @param address Optional user destination. @param address_length Destination bytes. * @return Accepted payload bytes or a negative errno. */ @@ -337,21 +382,7 @@ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, if (udp6_mapped(&to.sin6_addr)) { if (length > UDP_MAX_PAYLOAD) return -LINUX_EMSGSIZE; if (s->v6only || (!udp6_any(&s->local6) && !udp6_mapped(&s->local6))) return -LINUX_ENETUNREACH; - uint32_t ip = udp6_unmap(&to.sin6_addr); - if (ip == UINT32_MAX && !s->broadcast) return -LINUX_EACCES; - if (!s->bound) { int ret = bind_port(s, 0, 0); if (ret) return ret; } - struct reliefos_net_config config; - net_get_config(&config); - if ((ip >> 24) == 127 || (ip && net_interface_for_ipv4(NULL, ip))) { - uint32_t local_index = net_interface_for_ipv4(NULL, ip); - if (s->ifindex && (uint32_t)s->ifindex != local_index) return -LINUX_ENETUNREACH; - loopback_bytes += length + 28; ++loopback_packets; - net_udp_input(s->local ? s->local : ip, ip, s->port, port, data, length, (int)local_index); - return (int)length; - } - if (s->ifindex == 1) return -LINUX_ENETUNREACH; - int ret = net_ipv4_send_udp_on((uint32_t)s->ifindex, s->local, ip, s->port, port, data, length); - return ret < 0 ? ret : (int)length; + return udp4_send(s, udp6_unmap(&to.sin6_addr), port, data, length); } if (udp6_mapped(&s->local6)) return -LINUX_ENETUNREACH; if (to.sin6_scope_id && s->ifindex && to.sin6_scope_id != (uint32_t)s->ifindex) @@ -359,7 +390,7 @@ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, uint32_t scope = to.sin6_scope_id ? to.sin6_scope_id : (uint32_t)s->ifindex; if (!scope && to.sin6_addr.s6_addr[0] == 0xff) scope = s->multicast_if; struct net_ipv6_path path; - int ret = net_ipv6_route(NULL, &to.sin6_addr, scope, &s->local6, &path); + int ret = net_ipv6_route(s->net_ns, &to.sin6_addr, scope, &s->local6, &path); if (ret < 0) return ret; if (!s->bound) { ret = bind_port(s, 0, 0); if (ret < 0) return ret; } uint8_t *packet = kernel_malloc(length + 8); @@ -373,7 +404,7 @@ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, if (!checksum) checksum = 0xffff; packet[6] = (uint8_t)(checksum >> 8); packet[7] = (uint8_t)checksum; int hops = to.sin6_addr.s6_addr[0] == 0xff ? s->multicast_hops : s->unicast_hops; - ret = net_ipv6_output(NULL, &path, 17, packet, length + 8, hops, to.sin6_flowinfo, + ret = net_ipv6_output(s->net_ns, &path, 17, packet, length + 8, hops, to.sin6_flowinfo, s->dont_fragment || s->mtu_discover == IPV6_PMTUDISC_DO, s->multicast_loop); kernel_free(packet); return ret < 0 ? ret : (int)length; @@ -401,22 +432,7 @@ int task_udp_send(struct task_file *file, const void *data, uint32_t length, if (ret < 0) return ret; ip = swap32(to.sin_addr.s_addr); port = swap16(to.sin_port); } else if (!s->connected) return -LINUX_EDESTADDRREQ; - if (!port) return -LINUX_EINVAL; - if (ip == 0xffffffffu && !s->broadcast) return -LINUX_EACCES; - if (!s->bound) { int ret = bind_port(s, 0, 0); if (ret < 0) return ret; } - struct reliefos_net_config config; - net_get_config(&config); - if ((ip >> 24) == 127 || (ip && net_interface_for_ipv4(NULL, ip))) { - uint32_t local_index = net_interface_for_ipv4(NULL, ip); - if (s->ifindex && (uint32_t)s->ifindex != local_index) return -LINUX_ENETUNREACH; - loopback_bytes += length + 28; - ++loopback_packets; - net_udp_input(s->local ? s->local : ip, ip, s->port, port, data, length, (int)local_index); - return (int)length; - } - if (s->ifindex == 1) return -LINUX_ENETUNREACH; - int ret = net_ipv4_send_udp_on((uint32_t)s->ifindex, s->local, ip, s->port, port, data, length); - return ret < 0 ? ret : (int)length; + return udp4_send(s, ip, port, data, length); } /** @@ -548,7 +564,7 @@ int task_udp_available(struct task_file *file) } /** - * @brief Remove a final UDP socket description and release its queued datagrams. + * @brief Unregister a final UDP socket and release its memberships, queue and network. * @param file File description whose final reference is being released. */ void task_udp_release(struct task_file *file) @@ -560,12 +576,13 @@ void task_udp_release(struct task_file *file) if (*link == s) *link = s->registry_next; for (unsigned i = 0; i < UDP6_GROUP_LIMIT; ++i) if (s->groups[i].used) - (void)net_ipv6_multicast_change(NULL, &s->groups[i].address, s->groups[i].ifindex, -1); + (void)net_ipv6_multicast_change(s->net_ns, &s->groups[i].address, s->groups[i].ifindex, -1); while (s->head) { struct udp_packet *p = s->head; s->head = p->next; kernel_free(p); } + net_namespace_put(s->net_ns); kernel_free(s); file->aux = 0; } @@ -589,7 +606,8 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, __builtin_memcpy(&group, (void *)(uintptr_t)pointer, sizeof(group)); if (group.ipv6mr_multiaddr.s6_addr[0] != 0xff || group.ipv6mr_ifindex < 0) return -LINUX_EINVAL; uint32_t ifindex = group.ipv6mr_ifindex ? (uint32_t)group.ipv6mr_ifindex : s->multicast_if; - if (!ifindex) ifindex = s->ifindex ? (uint32_t)s->ifindex : netdev_next(0); + if (!ifindex) ifindex = s->ifindex ? (uint32_t)s->ifindex : + net_interface_next(s->net_ns, NET_IF_LOOPBACK); unsigned slot = UDP6_GROUP_LIMIT, empty = UDP6_GROUP_LIMIT; for (unsigned i = 0; i < UDP6_GROUP_LIMIT; ++i) { if (!s->groups[i].used && empty == UDP6_GROUP_LIMIT) empty = i; @@ -600,7 +618,7 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, if (join && slot != UDP6_GROUP_LIMIT) return -LINUX_EADDRINUSE; if (!join && slot == UDP6_GROUP_LIMIT) return -LINUX_EADDRNOTAVAIL; if (join && empty == UDP6_GROUP_LIMIT) return -LINUX_ENOBUFS; - ret = net_ipv6_multicast_change(NULL, &group.ipv6mr_multiaddr, ifindex, join ? 1 : -1); + ret = net_ipv6_multicast_change(s->net_ns, &group.ipv6mr_multiaddr, ifindex, join ? 1 : -1); if (ret < 0) return ret; if (join) { s->groups[empty].address = group.ipv6mr_multiaddr; s->groups[empty].ifindex = ifindex; s->groups[empty].used = true; } else s->groups[slot].used = false; @@ -616,7 +634,7 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, case IPV6_V6ONLY: if (s->bound) return -LINUX_EINVAL; s->v6only = value != 0; break; case IPV6_UNICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->unicast_hops = value; break; case IPV6_MULTICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->multicast_hops = value; break; - case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists(NULL, (uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; + case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists(s->net_ns, (uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; case IPV6_MULTICAST_LOOP: if (value != 0 && value != 1) return -LINUX_EINVAL; s->multicast_loop = value != 0; break; case IPV6_RECVPKTINFO: s->recv_pktinfo = value != 0; break; case IPV6_RECVHOPLIMIT: s->recv_hoplimit = value != 0; break; @@ -644,7 +662,7 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, case IPV6_MTU: { struct net_ipv6_path path; if (!s->connected || udp6_mapped(&s->remote6)) return -LINUX_ENOTCONN; - int ret = net_ipv6_route(NULL, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path); + int ret = net_ipv6_route(s->net_ns, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path); if (ret < 0) return ret; value = (int)path.mtu; break; @@ -660,7 +678,7 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, } /** - * @brief Dispatch IPv4 and IPv6 datagram syscalls against registered UDP sockets. + * @brief Create UDP sockets retaining their network and dispatch against that scope. * @param number Native syscall number. * @param a0 First syscall argument. * @param a1 Second syscall argument. @@ -684,7 +702,8 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, struct task_file *file; int fd = task_allocate_fd(task, 0, &file); if (fd < 0) { kernel_free(s); return fd; } - *s = (struct udp_socket){.uid = task->euid, .ino = (3ULL << 60) | ++proc_udp_ino, + *s = (struct udp_socket){.net_ns = net_namespace_get(task->net_ns), + .uid = task->euid, .ino = (3ULL << 60) | ++proc_udp_ino, .ipv6 = (int)a0 == AF_INET6, .unicast_hops = -1, .multicast_hops = 1, .mtu_discover = IPV6_PMTUDISC_WANT, .multicast_loop = true}; if (!sockets) sockets = s; @@ -751,24 +770,22 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, .sin6_scope_id = number == __NR_getsockname ? s->scope6 : s->remote_scope6}; if (number == __NR_getsockname && udp6_any(&address.sin6_addr) && s->connected) { if (udp6_mapped(&s->remote6)) { - struct reliefos_net_config config; net_get_config(&config); - address.sin6_addr = udp6_map(s->remote >> 24 == 127 ? 0x7f000001 : config.local_ip); + struct net_ipv4_path path; + if (!net_ipv4_route_lookup(s->net_ns, s->remote, s->local, + (uint32_t)s->ifindex, &path)) + address.sin6_addr = udp6_map(path.source); } else { struct net_ipv6_path path; - if (!net_ipv6_route(NULL, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path)) address.sin6_addr = path.source; + if (!net_ipv6_route(s->net_ns, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path)) address.sin6_addr = path.source; } } return udp6_export(a1, a2, &address); } - struct reliefos_net_config config; - net_get_config(&config); uint32_t local = s->local; if (!local && s->connected) { - if (net_interface_for_ipv4(NULL, s->remote)) local = s->remote; - else { - struct net_ipv4_path path; - if (!net_ipv4_route_lookup(NULL, s->remote, 0, (uint32_t)s->ifindex, &path)) local = path.source; - } + struct net_ipv4_path path; + if (!net_ipv4_route_lookup(s->net_ns, s->remote, 0, (uint32_t)s->ifindex, &path)) + local = path.source; } return export_address(a1, a2, number == __NR_getsockname ? local : s->remote, number == __NR_getsockname ? s->port : s->remote_port); @@ -786,7 +803,7 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if ((int32_t)length < 0) return -LINUX_EINVAL; if (a2 == SO_BINDTODEVICE) { uint32_t index = (uint32_t)s->ifindex; - int result = net_interface_device_option(NULL, set, a3, a4, &index); + int result = net_interface_device_option(s->net_ns, set, a3, a4, &index); if (!result && set) s->ifindex = (int)index; return result; } @@ -850,15 +867,17 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, } /** @brief Match a validated ICMPv6 quote to its originating UDP endpoint. + * @param ns Borrowed ingress network, NULL for the initial network. + * @param ifindex Ingress link or zero for no link filter. * @param source Original local address. @param destination Original peer address. * @param source_port Original local port. @param destination_port Original peer port. * @param error Positive errno. @param mtu Reported path MTU or zero. */ -void net_udp6_error_on(uint32_t ifindex, const struct in6_addr *source,const struct in6_addr *destination, +void net_udp6_error_on(struct net_namespace *ns, uint32_t ifindex, const struct in6_addr *source,const struct in6_addr *destination, uint16_t source_port,uint16_t destination_port,int error,uint32_t mtu) { (void)mtu; for (struct udp_socket *s = sockets; s; s = s->registry_next) { - if (!s->ipv6 || !s->bound || s->port != source_port || + if (s->net_ns != ns || !s->ipv6 || !s->bound || s->port != source_port || (ifindex && ((s->ifindex && (uint32_t)s->ifindex != ifindex) || (s->scope6 && s->scope6 != ifindex) || (s->remote_scope6 && s->remote_scope6 != ifindex))) || @@ -871,13 +890,14 @@ void net_udp6_error_on(uint32_t ifindex, const struct in6_addr *source,const str } /** @brief Render IPv6 UDP endpoints and their actual queued byte counts. + * @param ns Borrowed network, NULL for the initial network. * @param stream Caller-owned proc output slice. */ -void net_udp6_proc_emit(struct text_stream *stream) +void net_udp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) { text_string(stream," sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n"); uint32_t index = 0; for (struct udp_socket *u = sockets; u; u = u->registry_next) { - if (!u->ipv6 || !u->bound) continue; + if (u->net_ns != ns || !u->ipv6 || !u->bound) continue; uint64_t queued = 0; for (struct udp_packet *p = u->head; p; p = p->next) queued += p->length; text_unsigned(stream,index++); text_string(stream,": "); for (unsigned i = 0; i < 16; i += 4) { uint32_t word; __builtin_memcpy(&word,u->local6.s6_addr+i,4); text_hex(stream,word,8); } @@ -890,15 +910,16 @@ void net_udp6_proc_emit(struct text_stream *stream) } /** @brief Render registered UDP endpoints and their actual queued payloads. + * @param ns Borrowed network, NULL for the initial network. * @param s Output, execution-owned; stable numeric IDs never expose pointers. */ -void net_udp_proc_emit(struct text_stream *s) +void net_udp_proc_emit(struct net_namespace *ns, struct text_stream *s) { text_string(s, " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt " "uid timeout inode\n"); uint32_t index = 0; for (struct udp_socket *u = sockets; u; u = u->registry_next) { - if (!u->bound || u->ipv6) + if (u->net_ns != ns || !u->bound || u->ipv6) continue; uint64_t queued = 0; for (struct udp_packet *p = u->head; p; p = p->next) @@ -923,36 +944,41 @@ void net_udp_proc_emit(struct text_stream *s) } } /** @brief Emit loopback datagram packet/byte counters in net/dev format. + * @param ns Borrowed network, NULL for the initial network. * @param s Required output; execution ownership, no polling or allocation. */ -void net_loopback_proc_emit(struct text_stream *s) +void net_loopback_proc_emit(struct net_namespace *ns, struct text_stream *s) { + uint64_t bytes = ns ? ns->udp_loopback_bytes : loopback_bytes; + uint64_t packets = ns ? ns->udp_loopback_packets : loopback_packets; text_string(s, " lo: "); - text_unsigned(s, loopback_bytes); + text_unsigned(s, bytes); text_string(s, " "); - text_unsigned(s, loopback_packets); + text_unsigned(s, packets); text_string(s, " 0 0 0 0 0 0 "); - text_unsigned(s, loopback_bytes); + text_unsigned(s, bytes); text_string(s, " "); - text_unsigned(s, loopback_packets); + text_unsigned(s, packets); text_string(s, " 0 0 0 0 0 0\n"); } -/** @brief Deliver a compatibility ICMPv6 quote without an explicit ingress filter. +/** @brief Deliver an initial-network compatibility ICMPv6 quote without a link filter. * @param source Quoted local address. @param destination Quoted peer. * @param source_port Local port. @param destination_port Peer port. * @param error Positive errno. @param mtu Reported MTU. */ void net_udp6_error(const struct in6_addr *source, const struct in6_addr *destination, uint16_t source_port, uint16_t destination_port, int error, uint32_t mtu) { - net_udp6_error_on(0, source, destination, source_port, destination_port, error, mtu); + net_udp6_error_on(NULL, 0, source, destination, source_port, destination_port, error, mtu); } /** @brief Wake only UDP endpoints explicitly tied to a removed interface. + * @param ns Borrowed network, NULL for the initial network. * @param ifindex Removed non-reused interface index. */ -void net_udp_device_detached(uint32_t ifindex) +void net_udp_device_detached(struct net_namespace *ns, uint32_t ifindex) { for (struct udp_socket *s = sockets; s; s = s->registry_next) { + if (s->net_ns != ns) continue; if ((uint32_t)s->ifindex == ifindex || s->scope6 == ifindex || s->remote_scope6 == ifindex) s->error = LINUX_ENETDOWN; } diff --git a/tools/test_ipv6_transport.py b/tools/test_ipv6_transport.py index 94b8fa75..e388ee5a 100644 --- a/tools/test_ipv6_transport.py +++ b/tools/test_ipv6_transport.py @@ -11,7 +11,8 @@ subprocess.run(["cc", "-std=c11", "-g", "-O1", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", - "tools/tests/ipv6_transport_test.c", "-o", str(binary)], cwd=root, check=True) + "tools/tests/ipv6_transport_test.c", "net/proc.c", "net/namespace/namespace.c", + "net/ipv6/state.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) binary = out / "ipv6_vector_test" subprocess.run(["clang", "-std=c11", "-g", "-O1", "-DCONFIG_SWAP", diff --git a/tools/test_network.py b/tools/test_network.py index 0a58ceb3..4557aa04 100644 --- a/tools/test_network.py +++ b/tools/test_network.py @@ -11,7 +11,10 @@ "-fsanitize=address,undefined", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", - f"tools/tests/{name}_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "kernel/sched/user_namespace.c", + f"tools/tests/{name}_test.c", + *(["net/proc.c", "net/namespace/namespace.c", "net/ipv6/state.c"] + if name == "udp_socket" else []), + "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=20) binary = Path(work) / "tcp_nodelay_probe" diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 3d80e0c8..50cf7ffc 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -74,9 +74,11 @@ void net_arp_cache_clear_on(uint32_t index) { (void)index; } void net_ipv6_link_changed(bool up) { (void)up; ++link_changes; } int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index,bool up) { (void)ns; (void)index; (void)up; ++link_changes; return 0; } void net_device_counters(struct net_proc_counters *out) { memset(out,0,sizeof(*out)); } -void net_loopback_proc_emit(struct text_stream *stream) { (void)stream; } +void net_loopback_proc_emit(struct net_namespace *ns, struct text_stream *stream) +{ (void)ns; text_string(stream, " lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n"); } void net_arp_proc_emit(struct text_stream *stream) { (void)stream; } -void net_udp_proc_emit(struct text_stream *stream) { (void)stream; } +void net_udp_proc_emit(struct net_namespace *ns, struct text_stream *stream) { (void)ns; (void)stream; } +void net_udp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) { (void)ns; (void)stream; } void unix_proc_emit(struct text_stream *stream) { (void)stream; } void net_ipv6_transport_proc_emit(struct text_stream *stream,const char *leaf) { text_string(stream,leaf); text_string(stream,"\n"); } diff --git a/tools/tests/ipv6_transport_test.c b/tools/tests/ipv6_transport_test.c index a39d130b..89c765a1 100644 --- a/tools/tests/ipv6_transport_test.c +++ b/tools/tests/ipv6_transport_test.c @@ -10,17 +10,23 @@ #include void kernel_poll_readiness_notify(void) {} +void net_tcp6_proc_emit(struct text_stream *stream) { (void)stream; } +void net_tcp6_error_on(uint32_t index, const struct in6_addr *source, + const struct in6_addr *destination, uint16_t source_port, + uint16_t destination_port, int error, uint32_t mtu) +{ (void)index; (void)source; (void)destination; (void)source_port; + (void)destination_port; (void)error; (void)mtu; abort(); } static const struct in6_addr loop6 = {.s6_addr = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out, uint32_t capacity) { - (void)ns; + if (ns && !ns->loopback.config.local_ip) return 0; if (capacity) out[0] = (struct net_ipv6_address){.address = loop6, .ifindex = 1}; return 1; } int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination, uint32_t scope, const struct in6_addr *bound, struct net_ipv6_path *path) { - (void)ns; + if (!net_interface_is_ready(ns, NET_IF_LOOPBACK)) return -LINUX_ENETDOWN; if (memcmp(destination, &loop6, sizeof(loop6)) || (scope && scope != 1)) return -LINUX_ENETUNREACH; *path = (struct net_ipv6_path){.source = udp6_any(bound) ? loop6 : *bound, .destination = *destination, .ifindex = 1, .mtu = 65536}; @@ -43,16 +49,15 @@ int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path, const void *data, uint32_t length, int hops, uint32_t flowinfo, bool dont_fragment, bool multicast_loop) { - (void)ns; const uint8_t *p = data; (void)flowinfo; (void)dont_fragment; (void)multicast_loop; assert(!net_ipv6_checksum(&path->source, &path->destination, protocol, data, length)); if (protocol == 17) { assert(length >= 8); - assert(net_udp6_input(NULL, &path->source, &path->destination, (p[0] << 8) | p[1], + assert(net_udp6_input(ns, &path->source, &path->destination, (p[0] << 8) | p[1], (p[2] << 8) | p[3], p + 8, length - 8, path->ifindex, hops < 0 ? 64 : (uint8_t)hops)); - } else net_raw6_input(NULL, &path->source, &path->destination, protocol, data, length, + } else net_raw6_input(ns, &path->source, &path->destination, protocol, data, length, path->ifindex, hops < 0 ? 64 : (uint8_t)hops); return (int)length; } @@ -118,9 +123,94 @@ static void test_bind_scope(void) task_udp_release(&files[fd]); files[fd].used=0; } +static void test_udp6_namespace_bind(bool mapped) +{ + unsigned baseline = allocations; + struct net_namespace *first, *second; + assert(!net_namespace_create(NULL, &first)); + assert(!net_namespace_create(NULL, &second)); + enable_loopback(first); + enable_loopback(second); + current.net_ns = first; + int a = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + int sender = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + int conflict = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + current.net_ns = second; + int b = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + current.net_ns = NULL; + int initial = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + assert(a >= 0 && b >= 0 && sender >= 0 && conflict >= 0 && initial >= 0); + assert(first->references == 4 && second->references == 2); + assert(task_udp_namespace(&files[a]) == first); + struct sockaddr_in6 address = {.sin6_family = AF_INET6, .sin6_port = swap16(55111), + .sin6_addr = mapped ? udp6_map(0x7f000001) : loop6}; + assert(!call(__NR_bind, a, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(!call(__NR_bind, b, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(!call(__NR_bind, initial, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(call(__NR_bind, conflict, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EADDRINUSE); + current.net_ns = second; + assert(task_udp_send(&files[sender], "scope6", 6, 0, (uintptr_t)&address, sizeof(address)) == 6); + char data[16]; + assert(task_udp_recv(&files[b], data, sizeof(data), 0, 0, 0) == -LINUX_EAGAIN); + assert(task_udp_recv(&files[initial], data, sizeof(data), 0, 0, 0) == -LINUX_EAGAIN); + check_proc_socket("udp6", b, a); + current.net_ns = first; + check_proc_socket("udp6", a, b); + struct sockaddr_in6 source; + uint32_t size = sizeof(source); + assert(task_udp_recv(&files[a], data, sizeof(data), 0, (uintptr_t)&source, (uintptr_t)&size) == 6); + assert(!memcmp(data, "scope6", 6) && !memcmp(&source.sin6_addr, &address.sin6_addr, 16)); + first->loopback.up = false; + uint64_t counted = first->udp_loopback_packets; + assert(task_udp_send(&files[sender], "down", 4, 0, (uintptr_t)&address, sizeof(address)) == -LINUX_ENETDOWN); + assert(!task_udp_available(&files[a]) && first->udp_loopback_packets == counted); + first->loopback.up = true; + const char physical[] = "eth0"; + assert(call(__NR_setsockopt, a, SOL_SOCKET, SO_BINDTODEVICE, + (uintptr_t)physical, sizeof(physical)) == -LINUX_ENODEV); + if (!mapped) { + current.net_ns = NULL; + uint8_t quote[48] = {0}; + quote[0] = 0x60; + quote[6] = 17; + memcpy(quote + 8, &loop6, 16); + memcpy(quote + 24, &loop6, 16); + net_put_u16(quote + 40, 55111); + net_put_u16(quote + 42, 55112); + net_ipv6_socket_error_on(first, NET_IF_LOOPBACK, quote, sizeof(quote), LINUX_ECONNREFUSED, 0); + assert(udp_from_file(&files[a])->error == LINUX_ECONNREFUSED); + assert(!udp_from_file(&files[b])->error && !udp_from_file(&files[initial])->error); + udp_from_file(&files[a])->error = 0; + net_ipv6_socket_error(quote, sizeof(quote), LINUX_EMSGSIZE, 1280); + assert(udp_from_file(&files[initial])->error == LINUX_EMSGSIZE); + assert(!udp_from_file(&files[a])->error && !udp_from_file(&files[b])->error); + assert(net_udp6_input(second, &loop6, &loop6, 55112, 55111, "input6", 6, NET_IF_LOOPBACK, 64)); + assert(task_udp_recv(&files[b], data, sizeof(data), 0, 0, 0) == 6); + assert(!memcmp(data, "input6", 6)); + assert(!task_udp_available(&files[a])); + } + current.net_ns = NULL; + net_namespace_put(first); + net_namespace_put(second); + close_udp(sender); + close_udp(conflict); + assert(first->references == 1 && second->references == 1); + close_udp(a); + close_udp(b); + close_udp(initial); + assert(allocations == baseline); + /* The initial-network legacy regression checks exact accounting below. */ + loopback_bytes = loopback_packets = 0; + puts(mapped ? "PASS mapped UDP creating-net delivery, proc, down-lo and references" : + "PASS IPv6 UDP creating-net delivery, proc, down-lo, ICMPv6 errors and references"); +} + int main(void) { current.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; + test_udp6_namespace_bind(false); + test_udp6_namespace_bind(true); + test_udp_namespace_failures_and_owner(AF_INET6); test_bind_scope(); int fd = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); assert(fd >= 0); @@ -240,7 +330,6 @@ int main(void) return ipv4_udp_regression_main(); } -bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return index >= 1 && index <= 3; } const uint8_t *netdev_mac(uint32_t index) { (void)index; return e1000_mac(); } int netdev_send(uint32_t index, const void *frame, uint32_t length) { (void)index; return e1000_send(frame, length); } diff --git a/tools/tests/ipv6_vector_test.c b/tools/tests/ipv6_vector_test.c index 3cf68a0a..3d92f504 100644 --- a/tools/tests/ipv6_vector_test.c +++ b/tools/tests/ipv6_vector_test.c @@ -30,10 +30,9 @@ uint16_t net_ipv6_checksum(const struct in6_addr *source,const struct in6_addr * int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,uint8_t protocol,const void *data, uint32_t length,int hops,uint32_t flowinfo,bool df,bool multicast_loop) { - (void)ns; (void)flowinfo;(void)df;(void)multicast_loop;const uint8_t *p=data; assert(protocol==17 && length>=8 && !net_ipv6_checksum(&path->source,&path->destination,protocol,data,length)); - assert(net_udp6_input(NULL, &path->source,&path->destination,(p[0]<<8)|p[1],(p[2]<<8)|p[3], + assert(net_udp6_input(ns, &path->source,&path->destination,(p[0]<<8)|p[1],(p[2]<<8)|p[3], p+8,length-8,path->ifindex,hops<0 ? 64 : (uint8_t)hops)); return (int)length; } @@ -42,8 +41,6 @@ int net_ipv6_multicast_change(struct net_namespace *ns, const struct in6_addr *a int file_can_read(const struct task_file *file) { return file != NULL; } int file_can_write(const struct task_file *file) { return file != NULL; } -int user_range_readable(uint64_t address, uint64_t length) -{ return user_range_ok(address,length) ? 0 : -LINUX_EFAULT; } /* The scalar fallback is only reached by the old, incorrect vector path. */ int64_t syscall_io_write(uint64_t fd, uint64_t address, uint64_t length) diff --git a/tools/tests/net_multinic_data_test.c b/tools/tests/net_multinic_data_test.c index 81ca27dd..291a7b34 100644 --- a/tools/tests/net_multinic_data_test.c +++ b/tools/tests/net_multinic_data_test.c @@ -52,9 +52,9 @@ int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32 void net_poll_once(struct net_arp_wait *arp, struct net_ping_wait *ping, struct net_udp_wait *udp, struct net_tcp_wait *tcp) { (void)arp; (void)ping; (void)udp; (void)tcp; ++clock_ms; } -void net_udp_input(uint32_t source, uint32_t destination, uint16_t source_port, +void net_udp_input(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length, int index) -{ (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; (void)index; } +{ (void)ns; (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; (void)index; } static void neighbor(uint32_t index, uint32_t ip, const uint8_t mac[6], uint16_t operation) { @@ -84,13 +84,13 @@ int main(void) assert(!memcmp(wire+6,device_macs[1],6)); assert(net_get_u32(wire+28)==devices[1].config.local_ip); neighbor(3,0x0a000302,peer_macs[1],ARP_OPER_REPLY); - assert(!net_ipv4_send_udp_on(3,0,0x0a000302,55000,55001,"second",6)); + assert(!net_ipv4_send_udp_on(NULL,3,0,0x0a000302,55000,55001,"second",6)); assert(wire_index==3 && wire_length==48 && !memcmp(wire,peer_macs[1],6)); assert(!memcmp(wire+6,device_macs[1],6) && net_get_u32(wire+26)==devices[1].config.local_ip); uint32_t before=transmissions; ready[0]=false; assert(net_resolve_mac_on(2,peer,20,mac)==-LINUX_ENETDOWN); - assert(!net_ipv4_send_udp_on(3,0,0x0a000302,55000,55001,"ok",2)); + assert(!net_ipv4_send_udp_on(NULL,3,0,0x0a000302,55000,55001,"ok",2)); assert(transmissions==before+1 && wire_index==3); puts("PASS per-interface ARP neighbors, reply identity, UDP output and independent link failure"); return 0; diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index cf856f4e..f4ef8a7c 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -911,6 +911,8 @@ "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "kernel/sched/user_namespace.c", + "net/namespace/namespace.c", + "net/ipv6/state.c", "-o", "{tmp}/inet-message-user-candidate-3" ] @@ -1479,6 +1481,9 @@ "{tmp}/net-ioctl-user-candidate-3.2.o", "tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c", "tools/tests/task8_host_stubs/no_prlimit_identity.c", + "net/namespace/namespace.c", + "net/ipv6/state.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/net-ioctl-user-candidate-3" ] @@ -2598,6 +2603,9 @@ "{tmp}/udp-user-candidate-1.1.o", "tools/tests/task8_host_stubs/udp-user-candidate-1-udp-user-candidate-1.stub.c", "tools/tests/task8_host_stubs/no_prlimit_identity.c", + "net/namespace/namespace.c", + "net/ipv6/state.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/udp-user-candidate-1" ] diff --git a/tools/tests/task8_host_stubs/inet-message-user-candidate-3-inet-message-user-candidate-3.stub.c b/tools/tests/task8_host_stubs/inet-message-user-candidate-3-inet-message-user-candidate-3.stub.c index 02f58861..6535bdfe 100644 --- a/tools/tests/task8_host_stubs/inet-message-user-candidate-3-inet-message-user-candidate-3.stub.c +++ b/tools/tests/task8_host_stubs/inet-message-user-candidate-3-inet-message-user-candidate-3.stub.c @@ -16,8 +16,6 @@ __attribute__((noreturn)) void kernel_object_lookup(void) { __builtin_trap(); } __attribute__((noreturn)) void kernel_object_remove(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled kernel_objects. */ __attribute__((noreturn)) void kernel_objects(void) { __builtin_trap(); } -/** @brief Trap if the fixture reaches unmodeled kernel_poll_readiness_notify. */ -__attribute__((noreturn)) void kernel_poll_readiness_notify(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled kernel_wait_queue_add. */ __attribute__((noreturn)) void kernel_wait_queue_add(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled kernel_wait_queue_init. */ @@ -136,3 +134,53 @@ __attribute__((noreturn)) void vfs_path_node(void) { __builtin_trap(); } __attribute__((noreturn)) void vfs_path_same_inode(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled vfs_system_namespace. */ __attribute__((noreturn)) void vfs_system_namespace(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_accept_commit. */ +__attribute__((noreturn)) void net_socket_accept_commit(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_accept_peek. */ +__attribute__((noreturn)) void net_socket_accept_peek(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_address6. */ +__attribute__((noreturn)) void net_socket_address6(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_bind6_fd. */ +__attribute__((noreturn)) void net_socket_bind6_fd(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_bound_device. */ +__attribute__((noreturn)) void net_socket_bound_device(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_connect6_fd. */ +__attribute__((noreturn)) void net_socket_connect6_fd(void) { __builtin_trap(); } +/** @brief Resolve the controlled IPv4 TCP descriptor used for SO_ERROR. */ +int net_socket_family(int handle) +{ + if (handle != 44) __builtin_trap(); + return 2; /* AF_INET */ +} +/** @brief Trap if the fixture reaches unmodeled net_socket_ipv6_option. */ +__attribute__((noreturn)) void net_socket_ipv6_option(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_is_listening. */ +__attribute__((noreturn)) void net_socket_is_listening(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_listen_fd. */ +__attribute__((noreturn)) void net_socket_listen_fd(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_nodelay. */ +__attribute__((noreturn)) void net_socket_nodelay(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_reuse. */ +__attribute__((noreturn)) void net_socket_reuse(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled net_socket_set_ipv6. */ +__attribute__((noreturn)) void net_socket_set_ipv6(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled proc_account_file. */ +__attribute__((noreturn)) void proc_account_file(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled syscall_netlink. */ +__attribute__((noreturn)) void syscall_netlink(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled task_netlink_cancel_wait. */ +__attribute__((noreturn)) void task_netlink_cancel_wait(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled task_netlink_passcred. */ +__attribute__((noreturn)) void task_netlink_passcred(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled task_netlink_pktinfo. */ +__attribute__((noreturn)) void task_netlink_pktinfo(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled task_netlink_recv. */ +__attribute__((noreturn)) void task_netlink_recv(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled task_netlink_recv_staged. */ +__attribute__((noreturn)) void task_netlink_recv_staged(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled task_netlink_send. */ +__attribute__((noreturn)) void task_netlink_send(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled task_packet_recv_ex. */ +__attribute__((noreturn)) void task_packet_recv_ex(void) { __builtin_trap(); } +/** @brief Trap if the fixture reaches unmodeled time_clock_get. */ +__attribute__((noreturn)) void time_clock_get(void) { __builtin_trap(); } diff --git a/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c b/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c index 8dd22160..dfe817d0 100644 --- a/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c +++ b/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c @@ -87,7 +87,14 @@ __attribute__((noreturn)) int net_ipv6_output(struct net_namespace *ns, __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled net_udp_input. */ -__attribute__((noreturn)) void net_udp_input(void) { __builtin_trap(); } +__attribute__((noreturn)) void net_udp_input(struct net_namespace *ns, + uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, + const void *data, uint32_t length, int ifindex) +{ + (void)ns; (void)source; (void)destination; (void)source_port; + (void)destination_port; (void)data; (void)length; (void)ifindex; + __builtin_trap(); +} /** @brief Trap if the fixture reaches unmodeled sched_sleep_current_until. */ __attribute__((noreturn)) void sched_sleep_current_until(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled storage_inode_deny_write. */ diff --git a/tools/tests/task8_net_ioctl_user_test.c b/tools/tests/task8_net_ioctl_user_test.c index 598f5100..bc7ef5b6 100644 --- a/tools/tests/task8_net_ioctl_user_test.c +++ b/tools/tests/task8_net_ioctl_user_test.c @@ -12,6 +12,7 @@ #pragma clang diagnostic pop #undef main #include +#include #include #include #include @@ -19,6 +20,12 @@ static uint64_t blocked; static bool block_output; static struct task_file net_file={.used=1,.flags=TASK_FILE_FLAG_SOCKET_INET}; +static struct net_namespace *udp_creating_ns; +struct net_namespace *task_udp_namespace(const struct task_file *file) +{ + assert(file == &net_file); + return udp_creating_ns; +} void *kernel_malloc(size_t size) { return malloc(size); } void kernel_free(void *memory) { free(memory); } int swap_prepare_user_range(struct task *task,uint64_t address,uint64_t length,bool output) @@ -72,6 +79,32 @@ int main(void) assert(!scoped(SIOCADDRT,(uintptr_t)&route) && net_config.gateway_ip==0x0a000202); task_lookup_scope_cancel(¤t); assert(scoped(0x89fe,1)==-LINUX_ENOTTY);task_lookup_scope_cancel(¤t); + struct net_namespace *creating, *moved; + assert(!net_namespace_create(NULL, &creating)); + assert(!net_namespace_create(NULL, &moved)); + assert(!net_interface_set_up(creating, NET_IF_LOOPBACK, true)); + udp_creating_ns = creating; + net_file.kind = TASK_FILE_KIND_UDP; + current.net_ns = moved; + req = (struct ifreq){.ifr_name = "lo"}; + assert(!scoped(SIOCGIFFLAGS, (uintptr_t)&req) && (req.data.flags & IFF_UP)); + task_lookup_scope_cancel(¤t); + req = (struct ifreq){.ifr_name = "eth0"}; + assert(scoped(SIOCGIFINDEX, (uintptr_t)&req) == -LINUX_ENODEV); + task_lookup_scope_cancel(¤t); + ctrl = (struct reliefos_net_control){.version = RELIEFOS_NET_CONTROL_VERSION, + .operation = RELIEFOS_NET_CONTROL_CONFIG}; + assert(scoped(RELIEFOS_NET_CONTROL_IOCTL, (uintptr_t)&ctrl) == -LINUX_EOPNOTSUPP); + task_lookup_scope_cancel(¤t); + udp_creating_ns = NULL; + req = (struct ifreq){.ifr_name = "eth0"}; + assert(!scoped(SIOCGIFINDEX, (uintptr_t)&req) && req.data.value == 2); + task_lookup_scope_cancel(¤t); + current.net_ns = NULL; + net_file.kind = 0; + net_namespace_put(creating); + net_namespace_put(moved); + puts("PASS UDP creating-net ioctl after task movement and scoped private-control rejection"); puts("PASS INET ioctls: fixed and nested output waits, immutable inputs, ignored unknown operand"); return 0; } diff --git a/tools/tests/tcp_state_test.c b/tools/tests/tcp_state_test.c index a3250536..576c002a 100644 --- a/tools/tests/tcp_state_test.c +++ b/tools/tests/tcp_state_test.c @@ -94,9 +94,9 @@ int e1000_poll(void *frame, uint32_t capacity, uint32_t *length) *length = 42; return 1; } -void net_udp_input(uint32_t source, uint32_t destination, uint16_t source_port, +void net_udp_input(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length, int ifindex) -{ (void)ifindex; (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; } +{ (void)ns; (void)ifindex; (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; } void net_packet_input(const void *frame, uint32_t length) { (void)frame; (void)length; } void console_printf(const char *format, ...) { (void)format; } @@ -137,13 +137,17 @@ int task_udp_recv(struct task_file *file, void *buffer, uint32_t length, /* UDP and NIC counters are separate owners; this fixture only supplies their * boundaries. TCP, route, ARP and UNIX emitters execute production bodies. */ -void net_udp_proc_emit(struct text_stream *stream) +void net_udp_proc_emit(struct net_namespace *ns, struct text_stream *stream) { + (void)ns; (void)stream; abort(); } -void net_loopback_proc_emit(struct text_stream *stream) +void net_udp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) +{ (void)ns; (void)stream; abort(); } +void net_loopback_proc_emit(struct net_namespace *ns, struct text_stream *stream) { + (void)ns; (void)stream; abort(); } diff --git a/tools/tests/udp_socket_test.c b/tools/tests/udp_socket_test.c index b23ab315..74fa34ce 100644 --- a/tools/tests/udp_socket_test.c +++ b/tools/tests/udp_socket_test.c @@ -2,24 +2,44 @@ #include #include #include +#include #include "../../net/socket/udp.c" #include "../../net/interface/socket.c" +#include "../../net/utility.c" +/* Keep hardware receive parsing real alongside controlled transmit routing. */ +#define net_ipv4_send_udp_on fixture_hardware_send_udp_on +#define net_ipv4_send_udp fixture_hardware_send_udp +#include "../../net/ipv4/udp.c" +#undef net_ipv4_send_udp +#undef net_ipv4_send_udp_on static struct task current; static struct task_file files[80]; static unsigned allocations; +static int allocation_fail_after = -1; +static bool fail_fd; static unsigned sleeps; static uint64_t ticks = 100; struct task *sched_current_task(void) { return ¤t; } -void *kernel_malloc(size_t bytes) { ++allocations; return calloc(1, bytes); } +void *kernel_malloc(size_t bytes) +{ + if (allocation_fail_after == 0) return NULL; + if (allocation_fail_after > 0) --allocation_fail_after; + void *memory = calloc(1, bytes); + if (memory) ++allocations; + return memory; +} void kernel_free(void *p) { if (p) { assert(allocations); --allocations; free(p); } } uint64_t time_ticks(void) { return ticks; } void sched_sleep_current_until(uint64_t tick) { assert(tick == ticks + 1); ++sleeps; } bool user_range_ok(uint64_t address, uint64_t size) { (void)size; return address > 4096; } bool user_range_writable(uint64_t address, uint64_t size) { return user_range_ok(address, size); } +int user_range_readable(uint64_t address, uint64_t size) +{ return user_range_ok(address, size) ? 0 : -LINUX_EFAULT; } int task_allocate_fd(struct task *task, int minimum, struct task_file **out) { (void)task; + if (fail_fd) return -LINUX_EMFILE; for (unsigned i = minimum; i < 80; ++i) if (!files[i].used) { files[i].used = 1; *out = &files[i]; return (int)i; } @@ -52,21 +72,68 @@ int net_ipv4_send_udp(uint32_t source, uint32_t destination, uint16_t source_por uint16_t destination_port, const void *data, uint32_t length) { (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; return -LINUX_ENETDOWN; } +/* Namespace-owned loopback state follows the real interface provider contract. */ +static void enable_loopback(struct net_namespace *ns) +{ + ns->loopback.up = true; + ns->loopback.config.local_ip = 0x7f000001; + ns->loopback.config.subnet_mask = 0xff000000; +} uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip) -{ return (ip >> 24) == 127 ? 1 : ip == 0x0a00020f ? 2 : ip == 0x0a00030f ? 3 : 0; } -bool net_interface_exists(struct net_namespace *ns, uint32_t index) { return index >= 1 && index <= 3; } +{ + if ((ip >> 24) == 127) + return !ns || ns->loopback.config.local_ip ? NET_IF_LOOPBACK : 0; + if (ns) return 0; + return ip == 0x0a00020f ? 2 : ip == 0x0a00030f ? 3 : 0; +} +bool net_interface_exists(struct net_namespace *ns, uint32_t index) +{ return index == NET_IF_LOOPBACK || (!ns && index >= 2 && index <= 3); } +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) +{ return net_interface_exists(ns, index) && (!ns || ns->loopback.up); } uint32_t net_interface_index(struct net_namespace *ns, const char *name) -{ return !strcmp(name,"lo") ? 1 : !strcmp(name,"eth0") ? 2 : !strcmp(name,"eth1") ? 3 : 0; } +{ + if (!strcmp(name, "lo")) return NET_IF_LOOPBACK; + if (ns) return 0; + return !strcmp(name, "eth0") ? 2 : !strcmp(name, "eth1") ? 3 : 0; +} bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[16]) -{ if (!net_interface_exists(NULL, index)) return false; strcpy(out, index == 1 ? "lo" : index == 2 ? "eth0" : "eth1"); return true; } +{ + if (!net_interface_exists(ns, index)) return false; + strcpy(out, index == 1 ? "lo" : index == 2 ? "eth0" : "eth1"); + return true; +} uint32_t netdev_next(uint32_t after) { return after < 2 ? 2 : after == 2 ? 3 : 0; } -int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32_t source, uint32_t scope, struct net_ipv4_path *path) -{ uint32_t index=scope ? scope : 2; *path=(struct net_ipv4_path){.ifindex=index, - .source=source ? source : index==3 ? 0x0a00030f : 0x0a00020f,.destination=destination,.next_hop=destination}; return 0; } -int net_ipv4_send_udp_on(uint32_t index, uint32_t source, uint32_t destination, - uint16_t source_port, uint16_t destination_port, +uint32_t net_interface_next(struct net_namespace *ns, uint32_t after) +{ return after < NET_IF_LOOPBACK ? NET_IF_LOOPBACK : ns ? 0 : netdev_next(after); } +int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32_t source, + uint32_t scope, struct net_ipv4_path *path) +{ + if (scope && !net_interface_exists(ns, scope)) return -LINUX_ENODEV; + if (source && !net_interface_for_ipv4(ns, source)) return -LINUX_EADDRNOTAVAIL; + uint32_t index = net_interface_for_ipv4(ns, destination); + if (index) { + if (scope && scope != index) return -LINUX_ENETUNREACH; + if (!net_interface_is_ready(ns, index)) return -LINUX_ENETDOWN; + } else { + if (ns) return -LINUX_ENETUNREACH; + index = scope ? scope : 2; + if (index == NET_IF_LOOPBACK) return -LINUX_ENETUNREACH; + } + uint32_t local = index == NET_IF_LOOPBACK ? 0x7f000001 : + index == 3 ? 0x0a00030f : 0x0a00020f; + *path = (struct net_ipv4_path){.ifindex = index, .source = source ? source : local, + .destination = destination, .next_hop = destination}; + return 0; +} +int net_ipv4_send_udp_on(struct net_namespace *ns, uint32_t index, uint32_t source, + uint32_t destination, uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length) -{ (void)index; return net_ipv4_send_udp(source,destination,source_port,destination_port,data,length); } +{ + struct net_ipv4_path path; + int result = net_ipv4_route_lookup(ns, destination, source, index, &path); + if (result) return result; + return net_ipv4_send_udp(path.source, destination, source_port, destination_port, data, length); +} static long call(uint64_t nr, uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { return syscall_udp(nr, a, b, c, d, e, 0); } @@ -95,10 +162,216 @@ static void test_udp_device_local_delivery(void) loopback_bytes = loopback_packets = 0; } +static void close_udp(int fd) +{ + task_udp_release(&files[fd]); + files[fd] = (struct task_file){0}; +} + +/* Unrelated proc tables stay empty, while the real dispatcher selects scope. */ +struct net_socket; +struct net_socket *net_sockets; +void netdev_counters(uint32_t index, struct net_proc_counters *out) +{ (void)index; *out = (struct net_proc_counters){0}; } +void net_arp_proc_emit(struct text_stream *stream) { (void)stream; } +__attribute__((weak)) void unix_proc_emit(struct text_stream *stream) { (void)stream; } +uint32_t net_ipv4_routes(struct net_namespace *ns, struct net_ipv4_route *out, uint32_t capacity) +{ (void)ns; (void)out; (void)capacity; return 0; } +uint32_t net_ipv6_routes(struct net_namespace *ns, struct net_ipv6_route *out, uint32_t capacity) +{ (void)ns; (void)out; (void)capacity; return 0; } +#ifndef IPV6_TRANSPORT_FIXTURE +void net_ipv6_transport_proc_emit(struct text_stream *stream, const char *leaf) +{ (void)stream; (void)leaf; } +#endif + +static void check_proc_socket(const char *leaf, int visible, int hidden) +{ + char output[4096] = {0}, identity[64]; + struct text_stream stream = {.buffer = output, .capacity = sizeof(output) - 1}; + assert(!net_proc_emit(&stream, leaf)); + snprintf(identity, sizeof(identity), " 0 %llu\n", (unsigned long long)files[visible].socket_ino); + assert(strstr(output, identity)); + snprintf(identity, sizeof(identity), " 0 %llu\n", (unsigned long long)files[hidden].socket_ino); + assert(!strstr(output, identity)); +} + +static void test_udp_namespace_bind(void) +{ + unsigned baseline = allocations; + struct net_namespace *first, *second; + assert(!net_namespace_create(NULL, &first)); + assert(!net_namespace_create(NULL, &second)); + assert(!first->loopback.up && !first->loopback.config.local_ip); + enable_loopback(first); + enable_loopback(second); + current.net_ns = first; + int a = open_socket(), sender = open_socket(), conflict = open_socket(); + current.net_ns = second; + int b = open_socket(); + assert(a >= 0 && b >= 0 && sender >= 0 && conflict >= 0); + assert(first->references == 4 && second->references == 2); + assert(task_udp_namespace(&files[a]) == first); + assert(task_udp_namespace(&files[b]) == second); + assert(!task_udp_namespace(NULL)); + struct sockaddr_in address = {.sin_family = AF_INET, .sin_port = swap16(55110), + .sin_addr.s_addr = swap32(0x7f000001)}; + assert(!call(__NR_bind, a, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(!call(__NR_bind, b, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(call(__NR_bind, conflict, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EADDRINUSE); + assert(task_udp_send(&files[sender], "first", 5, 0, (uintptr_t)&address, sizeof(address)) == 5); + char data[16]; + struct sockaddr_in source; + uint32_t size = sizeof(source); + assert(task_udp_recv(&files[b], data, sizeof(data), 0, 0, 0) == -LINUX_EAGAIN); + check_proc_socket("udp", b, a); + current.net_ns = first; + check_proc_socket("udp", a, b); + assert(task_udp_recv(&files[a], data, sizeof(data), 0, (uintptr_t)&source, (uintptr_t)&size) == 5); + assert(!memcmp(data, "first", 5) && source.sin_addr.s_addr == swap32(0x7f000001)); + current.net_ns = NULL; + net_udp_input(second, 0x7f000001, 0x7f000001, 55112, 55110, "second", 6, NET_IF_LOOPBACK); + assert(task_udp_recv(&files[a], data, sizeof(data), 0, 0, 0) == -LINUX_EAGAIN); + assert(task_udp_recv(&files[b], data, sizeof(data), 0, 0, 0) == 6); + assert(!memcmp(data, "second", 6)); + const char physical[] = "eth0"; + assert(call(__NR_setsockopt, a, SOL_SOCKET, SO_BINDTODEVICE, + (uintptr_t)physical, sizeof(physical)) == -LINUX_ENODEV); + struct sockaddr_in hardware = address; + hardware.sin_addr.s_addr = swap32(0x0a00020f); + assert(call(__NR_bind, conflict, (uintptr_t)&hardware, sizeof(hardware), 0, 0) == -LINUX_EADDRNOTAVAIL); + assert(net_interface_next(first, NET_IF_LOOPBACK) == 0); + struct sockaddr_in alias = {.sin_family = AF_INET, .sin_port = swap16(55113), + .sin_addr.s_addr = swap32(0x7f000002)}; + assert(!call(__NR_bind, conflict, (uintptr_t)&alias, sizeof(alias), 0, 0)); + assert(task_udp_send(&files[sender], "alias", 5, 0, (uintptr_t)&alias, sizeof(alias)) == 5); + size = sizeof(source); + assert(task_udp_recv(&files[conflict], data, sizeof(data), 0, + (uintptr_t)&source, (uintptr_t)&size) == 5); + assert(!memcmp(data, "alias", 5) && source.sin_addr.s_addr == swap32(0x7f000001)); + assert(first->udp_loopback_packets == 2 && second->udp_loopback_packets == 0); + current.net_ns = first; + char counters[512] = {0}; + struct text_stream stream = {.buffer = counters, .capacity = sizeof(counters) - 1}; + assert(!net_proc_emit(&stream, "dev")); + assert(strstr(counters, " lo: 66 2 ") && !strstr(counters, "eth")); + first->loopback.up = false; + assert(task_udp_send(&files[sender], "down", 4, 0, (uintptr_t)&address, sizeof(address)) == -LINUX_ENETDOWN); + assert(task_udp_available(&files[a]) == 0 && first->udp_loopback_packets == 2); + first->loopback.up = true; + const char device[] = "lo"; + assert(!call(__NR_setsockopt, a, SOL_SOCKET, SO_BINDTODEVICE, (uintptr_t)device, sizeof(device))); + assert(!call(__NR_setsockopt, b, SOL_SOCKET, SO_BINDTODEVICE, (uintptr_t)device, sizeof(device))); + net_udp_device_detached(first, NET_IF_LOOPBACK); + assert(udp_from_file(&files[a])->error == LINUX_ENETDOWN); + assert(!udp_from_file(&files[b])->error); + current.net_ns = first; + int first_wildcard = open_socket(); + current.net_ns = second; + int second_wildcard = open_socket(); + current.net_ns = NULL; + int initial = open_socket(); + assert(first_wildcard >= 0 && second_wildcard >= 0 && initial >= 0); + address.sin_addr.s_addr = 0; + address.sin_port = swap16(55114); + /* Wildcard endpoints share the port while physical ingress stays initial. */ + assert(!call(__NR_bind, initial, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(!call(__NR_bind, first_wildcard, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(!call(__NR_bind, second_wildcard, (uintptr_t)&address, sizeof(address), 0, 0)); + uint8_t packet[32] = {0}; + net_put_u32(packet + 12, 0x0a000202); + net_put_u32(packet + 16, 0x0a00020f); + net_put_u16(packet + 20, 55112); + net_put_u16(packet + 22, 55114); + net_put_u16(packet + 24, 12); + memcpy(packet + 28, "wire", 4); + current.net_ns = first; + net_handle_udp_on(2, packet, sizeof(packet), 20, 0x0a000202, NULL); + assert(task_udp_recv(&files[initial], data, sizeof(data), 0, 0, 0) == 4); + assert(!memcmp(data, "wire", 4)); + assert(!task_udp_available(&files[first_wildcard]) && !task_udp_available(&files[second_wildcard])); + assert(!call(__NR_setsockopt, initial, SOL_SOCKET, SO_BINDTODEVICE, + (uintptr_t)physical, sizeof(physical))); + net_udp_device_detached(NULL, 2); + assert(udp_from_file(&files[initial])->error == LINUX_ENETDOWN); + assert(!udp_from_file(&files[first_wildcard])->error && !udp_from_file(&files[second_wildcard])->error); + close_udp(initial); + close_udp(first_wildcard); + close_udp(second_wildcard); + current.net_ns = NULL; + net_namespace_put(first); + net_namespace_put(second); + assert(first->references == 3 && second->references == 1); + close_udp(sender); + close_udp(conflict); + assert(first->references == 1); + close_udp(a); + close_udp(b); + assert(allocations == baseline); + puts("PASS UDP creating-net bind, delivery, OFD scope, proc, down-lo, detach and references"); +} + +static void test_udp_namespace_failures_and_owner(int domain) +{ + unsigned baseline = allocations; + struct task saved = current; + struct user_namespace *owner, *sibling; + assert(!user_namespace_create(¤t, &owner)); + assert(!user_namespace_create(¤t, &sibling)); + struct net_namespace *ns; + assert(!net_namespace_create(owner, &ns)); + enable_loopback(ns); + current.net_ns = ns; + current.user_ns = owner; + current.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; + unsigned before_socket = allocations; + allocation_fail_after = 0; + assert((int)call(__NR_socket, domain, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0) == -LINUX_ENOMEM); + allocation_fail_after = -1; + assert(ns->references == 1 && allocations == before_socket); + fail_fd = true; + assert((int)call(__NR_socket, domain, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0) == -LINUX_EMFILE); + fail_fd = false; + assert(ns->references == 1 && allocations == before_socket); + int local = (int)call(__NR_socket, domain, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + current.net_ns = NULL; + int initial = (int)call(__NR_socket, domain, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + current.net_ns = ns; + int denied = (int)call(__NR_socket, domain, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + int no_cap = (int)call(__NR_socket, domain, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + assert(local >= 0 && initial >= 0 && denied >= 0 && no_cap >= 0); + struct sockaddr_in address = {.sin_family = AF_INET, .sin_port = swap16(100), + .sin_addr.s_addr = swap32(0x7f000001)}; + struct sockaddr_in6 address6 = {.sin6_family = AF_INET6, .sin6_port = address.sin_port, + .sin6_addr = {.s6_addr = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}}; + void *bind_address = domain == AF_INET6 ? (void *)&address6 : (void *)&address; + uint32_t bind_length = domain == AF_INET6 ? sizeof(address6) : sizeof(address); + assert(!call(__NR_bind, local, (uintptr_t)bind_address, bind_length, 0, 0)); + assert(call(__NR_bind, initial, (uintptr_t)bind_address, bind_length, 0, 0) == -LINUX_EACCES); + current.user_ns = sibling; + address.sin_port = address6.sin6_port = swap16(101); + assert(call(__NR_bind, denied, (uintptr_t)bind_address, bind_length, 0, 0) == -LINUX_EACCES); + current.user_ns = owner; + current.cap_effective = 0; + assert(call(__NR_bind, no_cap, (uintptr_t)bind_address, bind_length, 0, 0) == -LINUX_EACCES); + current = saved; + close_udp(local); + close_udp(initial); + close_udp(denied); + close_udp(no_cap); + net_namespace_put(ns); + assert(owner->references == 1 && sibling->references == 1); + user_namespace_put(owner); + user_namespace_put(sibling); + assert(allocations == baseline); + printf("PASS UDP family %d owner CAP_NET_BIND_SERVICE and ENOMEM/EMFILE rollback\n", domain); +} + int main(void) { current.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; current.euid = 1234; + test_udp_namespace_bind(); + test_udp_namespace_failures_and_owner(AF_INET); test_udp_device_local_delivery(); int a = open_socket(), b = open_socket(); assert(a >= 0 && b >= 0 && a != b); @@ -124,13 +397,13 @@ int main(void) assert(task_udp_send(&files[a], "hello", 5, 0, 0, 0) == 5); char proc[2048] = {0}, identity[64]; struct text_stream stream = {.buffer = proc, .capacity = sizeof(proc) - 1}; - net_udp_proc_emit(&stream); + net_udp_proc_emit(NULL, &stream); snprintf(identity, sizeof(identity), " 1234 0 %llu\n", (unsigned long long)files[b].socket_ino); assert(strstr(proc, "0100007f:d6d8") && strstr(proc, "00000000:00000005")); assert(files[b].socket_ino && strstr(proc, identity)); memset(proc, 0, sizeof(proc)); stream = (struct text_stream){.buffer = proc, .capacity = sizeof(proc) - 1}; - net_loopback_proc_emit(&stream); + net_loopback_proc_emit(NULL, &stream); assert(!strcmp(proc, " lo: 33 1 0 0 0 0 0 0 33 1 0 0 0 0 0 0\n")); assert(task_udp_poll(&files[b], POLLIN | POLLOUT) == (POLLIN | POLLOUT)); assert(task_udp_recv(&files[b], text, 2, MSG_PEEK | MSG_TRUNC, 0, 0) == 5); @@ -187,4 +460,5 @@ int main(void) assert(!sockets); assert(!allocations); puts("PASS UDP bind, connect, datagram boundaries, source address, truncation/peek, zero length, options and cleanup"); + return 0; } From e7c1ea5c8c2bacdaa185a11d4dd8b2a2618f1416 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 06:14:07 +0800 Subject: [PATCH 75/97] feat(net): isolate TCP transport by creating network namespace --- Documentation/core-api/mount-namespaces.rst | 8 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 16 +- .../en/LC_MESSAGES/userspace-api/ipv6.po | 8 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 16 +- .../ja/LC_MESSAGES/userspace-api/ipv6.po | 8 +- Documentation/userspace-api/ipv6.rst | 4 +- include/reliefnt/net.h | 24 +- kernel/syscall/device/legacy_ioctl.c | 5 +- kernel/syscall/ipc/socket.c | 8 +- net/core.c | 4 +- net/internal.h | 12 +- net/ipv4/core.c | 2 +- net/proc.c | 11 +- net/socket/control.c | 13 +- net/socket/packet.c | 4 +- net/tcp/input.c | 33 +- net/tcp/output.c | 57 ++-- net/tcp/socket.c | 124 +++++--- tools/test_ipv6_transport.py | 4 +- tools/test_network.py | 4 +- tools/tests/ipv6_tcp_test.c | 222 +++++++++++++- tools/tests/ipv6_transport_test.c | 6 +- tools/tests/task8_host_fixtures.json | 2 + .../fix1-tcp-front-unreached.c | 15 +- tools/tests/task8_inet_tcp_probe_test.c | 34 +- tools/tests/tcp_state_test.c | 290 ++++++++++++++++-- tools/tests/udp_socket_test.c | 2 + 27 files changed, 750 insertions(+), 186 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 302c1d81..32c47441 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -158,13 +158,15 @@ hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护 网络空间生命周期 ================ -``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink 和 UDP 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。 +``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink、UDP 和 TCP 套接字独立持有创建时的网络空间,服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。TCP 分配或新建 FD 安装失败释放候选对象及网络引用,已绑定或协议活跃的端点在关闭描述并完成协议回收后释放网络。 每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 ``127.0.0.1/8``、``::1/128`` 和 IPv6 host route。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由、IPv6 协议资源和 owner 引用。 -网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。TCP 和 raw transport 的网络隔离仍待完成。 +网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。raw transport 的网络隔离仍待完成。 -``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp``、``tcp``、``tcp6`` 和 ``raw6`` 仅输出表头。 +TCP 的端口冲突、IPv4/IPv6 和映射地址握手、接收连接、收发、ICMPv6 错误与设备选项按创建网络隔离。接收连接保留监听端网络,IPv4 延迟回环队列持有网络引用,投递或丢弃后释放。发送先查询该空间的路由与接口状态,物理输出归初始网络。特权端口按网络 owner 的 ``CAP_NET_BIND_SERVICE`` 授权,接口 ioctl 与 ``SO_BINDTODEVICE`` 使用创建网络。非初始 TCP 的私有全局网络控制返回 ``EOPNOTSUPP``,旧连接入口接受数值 IPv4 目标,主机名解析限于初始网络。 + +``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 和 TCP 端点输出实际队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 和 ``raw6`` 仅输出表头。 用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 transport 隔离完成后接通。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 67a19654..018e2c93 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -430,8 +430,8 @@ msgstr "``struct uts_namespace`` uses atomic reference counting. Tasks and nsfs msgid "网络空间生命周期" msgstr "Network namespace lifetime" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink 和 UDP 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。" -msgstr "``net_namespace_create()`` creates a reference-counted network namespace with an immutable user owner. ``NULL`` denotes the permanent initial network namespace. Tasks share it on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix, netlink and UDP socket independently retains its creating network until its final reference closes. Unix server connections inherit the listener network. Failed UDP allocation or FD installation releases the candidate object. Final close removes the registry entry before releasing multicast memberships, received datagrams and the network reference." +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink、UDP 和 TCP 套接字独立持有创建时的网络空间,服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。TCP 分配或新建 FD 安装失败释放候选对象及网络引用,已绑定或协议活跃的端点在关闭描述并完成协议回收后释放网络。" +msgstr "``net_namespace_create()`` creates a reference-counted network namespace with an immutable user owner. ``NULL`` denotes the permanent initial network namespace. Tasks share it on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix, netlink, UDP and TCP socket independently retains its creating network. Server connections inherit the listener network. Failed UDP allocation or FD installation releases the candidate object. Final close removes the registry entry before releasing multicast memberships, received datagrams and the network reference. Failed TCP allocation or new FD installation releases the candidate and its network reference. Bound or protocol-active TCP endpoints release the network after description close and protocol collection." msgid "" "每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 " @@ -444,11 +444,11 @@ msgstr "" "remain in the initial network. The final namespace reference releases interfaces, explicit " "IPv4 routes, IPv6 resources and the owner reference." -msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。TCP 和 raw transport 的网络隔离仍待完成。" -msgstr "Network namespaces scope Unix abstract addresses, proc enumeration, netlink ports and message delivery. Netlink interface, IPv4/IPv6 address and route queries and changes use the socket's retained creating network, with changes requiring ``CAP_NET_ADMIN`` in its user owner. IPv6 addresses, routes, neighbors, multicast, pending packets, reassembly, PMTU, fragment identifiers and ICMP error rate limits are isolated by network. Maintenance visits live protocol states while retaining the serviced network. Reinitializing the initial network preserves other live networks. UDP port conflicts, IPv4/IPv6 and mapped-address delivery, ICMPv6 errors, multicast and device options match the creating network across OFD transfer or task network changes. Privileged ports require ``CAP_NET_BIND_SERVICE`` in that network's user owner. Local sends check the network's route and interface readiness. ReliefOS private global network control on noninitial UDP sockets returns ``EOPNOTSUPP``. TCP and raw transport network isolation remains pending." +msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。raw transport 的网络隔离仍待完成。" +msgstr "Network namespaces scope Unix abstract addresses, proc enumeration, netlink ports and message delivery. Netlink interface, IPv4/IPv6 address and route queries and changes use the socket's retained creating network, with changes requiring ``CAP_NET_ADMIN`` in its user owner. IPv6 addresses, routes, neighbors, multicast, pending packets, reassembly, PMTU, fragment identifiers and ICMP error rate limits are isolated by network. Maintenance visits live protocol states while retaining the serviced network. Reinitializing the initial network preserves other live networks. UDP port conflicts, IPv4/IPv6 and mapped-address delivery, ICMPv6 errors, multicast and device options match the creating network across OFD transfer or task network changes. Privileged ports require ``CAP_NET_BIND_SERVICE`` in that network's user owner. Local sends check the network's route and interface readiness. ReliefOS private global network control on noninitial UDP sockets returns ``EOPNOTSUPP``. Raw transport network isolation remains pending." -msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp``、``tcp``、``tcp6`` 和 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/dev``, ``route``, ``if_inet6``, ``ipv6_route``, ``udp``, ``udp6`` and ``unix`` follow the caller's current network scope. UDP rows report actual receive queues and numeric inodes. IPv4 local UDP delivery counters belong to the corresponding network. Noninitial ``arp``, ``tcp``, ``tcp6`` and ``raw6`` views contain only headers." +msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 和 TCP 端点输出实际队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 和 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/dev``, ``route``, ``if_inet6``, ``ipv6_route``, ``udp``, ``udp6``, ``tcp``, ``tcp6`` and ``unix`` follow the caller's current network scope. UDP and TCP rows report actual queues and numeric inodes. IPv4 local UDP delivery counters belong to the corresponding network. Noninitial ``arp`` and ``raw6`` views contain only headers." msgid "" "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " @@ -472,3 +472,7 @@ msgstr "The first route subscriber in each network namespace establishes an inde msgid "路由多播组当前支持 ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR`` 和 ``RTMGRP_IPV6_ROUTE``。IPv4 地址和 IPv4 路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。" msgstr "The supported route multicast groups are ``RTMGRP_LINK``, ``RTMGRP_IPV6_IFADDR`` and ``RTMGRP_IPV6_ROUTE``. IPv4 address and IPv4 route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``." + + +msgid "TCP 的端口冲突、IPv4/IPv6 和映射地址握手、接收连接、收发、ICMPv6 错误与设备选项按创建网络隔离。接收连接保留监听端网络,IPv4 延迟回环队列持有网络引用,投递或丢弃后释放。发送先查询该空间的路由与接口状态,物理输出归初始网络。特权端口按网络 owner 的 ``CAP_NET_BIND_SERVICE`` 授权,接口 ioctl 与 ``SO_BINDTODEVICE`` 使用创建网络。非初始 TCP 的私有全局网络控制返回 ``EOPNOTSUPP``,旧连接入口接受数值 IPv4 目标,主机名解析限于初始网络。" +msgstr "TCP port conflicts, IPv4/IPv6 and mapped-address handshakes, accepted connections, data, ICMPv6 errors and device options are isolated by the creating network. Accepted connections retain the listener network. The deferred IPv4 loopback queue owns a network reference until delivery or drop. Sends first query that network's route and interface state, with physical output owned by the initial network. Privileged ports require ``CAP_NET_BIND_SERVICE`` in the network owner. Interface ioctls and ``SO_BINDTODEVICE`` use the creating network. Private global control on noninitial TCP returns ``EOPNOTSUPP``. The legacy connect entry accepts numeric IPv4 targets, with hostname resolution confined to the initial network." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po index 0950f9c4..91619b5e 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po @@ -57,8 +57,8 @@ msgstr "" msgid "配置与观测" msgstr "Configuration and Observation" -msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。TCP 和 raw socket 的 ioctl 随其 transport 隔离接通。" -msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 addresses and routes in the network scope retained when the socket was created, including after FD transfer. Changes require ``CAP_NET_ADMIN`` in the network owner's user namespace. ``getifaddrs()`` obtains that scope's IPv6 addresses through standard queries. IPv6 address and route ioctls use the selected network's state and owner authority, with layouts selected by socket family. UDP interface, IPv6 address and route ioctls use the creating network. TCP and raw socket ioctls will follow their transport isolation." +msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP 和 TCP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。raw socket 的 ioctl 随其 transport 隔离接通。" +msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 addresses and routes in the network scope retained when the socket was created, including after FD transfer. Changes require ``CAP_NET_ADMIN`` in the network owner's user namespace. ``getifaddrs()`` obtains that scope's IPv6 addresses through standard queries. IPv6 address and route ioctls use the selected network's state and owner authority, with layouts selected by socket family. UDP and TCP interface, IPv6 address and route ioctls use the creating network. Raw socket ioctls will follow their transport isolation." msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" msgstr "Route multicast supports link, IPv6 address and IPv6 route groups. IPv4 address and route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``. Each network namespace maintains its own subscription snapshots, published after all captures succeed and released when its final subscriber closes or unsubscribes. Change notifications and overruns are delivered by network scope. Receive queue overflow reports ``ENOBUFS``, and callers should query again." @@ -72,8 +72,8 @@ msgstr "" "empty query result. Receivers must still iterate all messages in each datagram until the matching " "``NLMSG_DONE`` or an error arrives." -msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由和 UDP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。TCP 和 raw transport 的网络隔离仍待完成,非初始空间的 ``tcp6`` 和 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text layouts. Address scope encodings differ from rtnetlink scope values. Addresses, routes and UDP tables follow the caller's current network scope. Snapshots copy internal state and retain only copies across waits. TCP and raw transport isolation remains pending, and their ``tcp6`` and ``raw6`` views in noninitial networks contain only headers." +msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP 和 TCP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。raw transport 的网络隔离仍待完成,非初始空间的 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text layouts. Address scope encoding differs from rtnetlink scope values. Address, route, UDP and TCP tables follow the caller's current network scope. Snapshots copy internal state and retain only copies across waits. Raw transport network isolation remains pending, and noninitial ``raw6`` views contain only headers." msgid "" "每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index 964780a4..ab56887f 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -380,8 +380,8 @@ msgstr "``struct uts_namespace`` はアトミックな参照カウントを使 msgid "网络空间生命周期" msgstr "ネットワーク名前空間の寿命" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink 和 UDP 套接字独立持有创建时的网络空间,最后一个套接字引用关闭时释放它,Unix 监听端创建的服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。" -msgstr "``net_namespace_create()`` は不変の user owner を持つ参照カウント付きネットワーク空間を作成し、``NULL`` は永続的な初期ネットワーク空間を表します。タスクは fork で空間を共有し、exec と識別情報の整理を通じて参照を保持し、wait による回収やスロット再利用時に解放します。Unix、netlink、UDP の各ソケットは作成元ネットワークを独立して保持し、最後の参照を閉じる際に解放します。Unix のサーバー接続はリスナーの空間を継承します。UDP のメモリ確保または FD 登録に失敗すると候補オブジェクトを解放します。最後の close は registry から削除した後、多播メンバーシップ、受信キュー、ネットワーク参照を解放します。" +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink、UDP 和 TCP 套接字独立持有创建时的网络空间,服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。TCP 分配或新建 FD 安装失败释放候选对象及网络引用,已绑定或协议活跃的端点在关闭描述并完成协议回收后释放网络。" +msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク名前空間を作成します。``NULL`` は永続的な初期ネットワーク名前空間です。タスクは fork で共有し、exec と資格情報のクリーンアップで参照を保持し、wait による回収やスロット再利用で解放します。Unix、netlink、UDP、TCP ソケットはそれぞれ作成時のネットワークを独立して保持し、サーバー接続はリスナーのネットワークを継承します。UDP の割り当てや FD 設置が失敗すると候補を解放します。最後の close は registry から削除した後、マルチキャスト参加、受信キュー、ネットワーク参照を解放します。TCP の割り当てや新規 FD 設置の失敗は候補とネットワーク参照を解放します。バインド済みまたはプロトコルが動作中の TCP 端点は記述の close とプロトコル回収後にネットワークを解放します。" msgid "" "每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 " @@ -392,11 +392,11 @@ msgstr "" "でアドレスを持たず、最初の up で ``127.0.0.1/8``、``::1/128``、IPv6 host route を設定します。物理 NIC 登録と ingress " "は初期空間に属します。最後の空間参照を解放すると、インターフェース、明示的な IPv4 経路、IPv6 資源、owner 参照も解放します。" -msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。TCP 和 raw transport 的网络隔离仍待完成。" -msgstr "ネットワーク空間は Unix 抽象アドレス、proc 列挙、netlink ポート、メッセージ配送に scope を与えます。netlink のインターフェース、IPv4/IPv6 アドレス、経路の照会と変更はソケットが保持する作成元ネットワークを使用し、変更にはその user owner の ``CAP_NET_ADMIN`` が必要です。IPv6 アドレス、経路、近隣、多播、送信待ちパケット、再構成、PMTU、フラグメント ID、ICMP エラー制限はネットワークごとに隔離します。保守処理は対象空間の参照を保持して稼働中のプロトコル状態を巡回します。初期ネットワークの再初期化は他の稼働中空間を保持します。UDP のポート競合、IPv4/IPv6 とマップアドレスの送受信、ICMPv6 エラー、多播、デバイスオプションは OFD 転送やタスクのネットワーク変更後も作成元空間で照合します。特権ポートにはそのネットワークの user owner における ``CAP_NET_BIND_SERVICE`` が必要です。ローカル送信は対象空間の経路とインターフェースの準備状態を確認します。非初期 UDP ソケットの ReliefOS 独自グローバルネットワーク制御は ``EOPNOTSUPP`` を返します。TCP と raw transport のネットワーク隔離は今後の実装対象です。" +msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。raw transport 的网络隔离仍待完成。" +msgstr "ネットワーク空間は Unix 抽象アドレス、proc 列挙、netlink ポート、メッセージ配送に scope を与えます。netlink のインターフェース、IPv4/IPv6 アドレス、経路の照会と変更はソケットが保持する作成元ネットワークを使用し、変更にはその user owner の ``CAP_NET_ADMIN`` が必要です。IPv6 アドレス、経路、近隣、多播、送信待ちパケット、再構成、PMTU、フラグメント ID、ICMP エラー制限はネットワークごとに隔離します。保守処理は対象空間の参照を保持して稼働中のプロトコル状態を巡回します。初期ネットワークの再初期化は他の稼働中空間を保持します。UDP のポート競合、IPv4/IPv6 とマップアドレスの送受信、ICMPv6 エラー、多播、デバイスオプションは OFD 転送やタスクのネットワーク変更後も作成元空間で照合します。特権ポートにはそのネットワークの user owner における ``CAP_NET_BIND_SERVICE`` が必要です。ローカル送信は対象空間の経路とインターフェースの準備状態を確認します。非初期 UDP ソケットの ReliefOS 独自グローバルネットワーク制御は ``EOPNOTSUPP`` を返します。raw transport のネットワーク隔離は今後の実装対象です。" -msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp``、``tcp``、``tcp6`` 和 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``unix`` は呼び出し元の現在のネットワーク scope に従います。UDP の行は実際の受信キューと数値 inode を表示し、IPv4 のローカル UDP 配送カウンターは対応するネットワークに属します。非初期空間の ``arp``、``tcp``、``tcp6``、``raw6`` はヘッダーだけを出力します。" +msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 和 TCP 端点输出实际队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 和 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``unix`` は呼び出し元の現在のネットワーク scope を使用します。UDP と TCP の行は実際のキューと数値 inode を表示します。IPv4 ローカル UDP 配信のカウンターは対応するネットワークに属します。非初期空間の ``arp`` と ``raw6`` はヘッダーのみを出力します。" msgid "" "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " @@ -420,3 +420,7 @@ msgstr "各ネットワーク名前空間の最初のルート購読者が独立 msgid "路由多播组当前支持 ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR`` 和 ``RTMGRP_IPV6_ROUTE``。IPv4 地址和 IPv4 路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。" msgstr "現在対応するルートマルチキャストグループは ``RTMGRP_LINK``、``RTMGRP_IPV6_IFADDR``、``RTMGRP_IPV6_ROUTE`` です。IPv4 アドレスと IPv4 ルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。" + + +msgid "TCP 的端口冲突、IPv4/IPv6 和映射地址握手、接收连接、收发、ICMPv6 错误与设备选项按创建网络隔离。接收连接保留监听端网络,IPv4 延迟回环队列持有网络引用,投递或丢弃后释放。发送先查询该空间的路由与接口状态,物理输出归初始网络。特权端口按网络 owner 的 ``CAP_NET_BIND_SERVICE`` 授权,接口 ioctl 与 ``SO_BINDTODEVICE`` 使用创建网络。非初始 TCP 的私有全局网络控制返回 ``EOPNOTSUPP``,旧连接入口接受数值 IPv4 目标,主机名解析限于初始网络。" +msgstr "TCP のポート競合、IPv4/IPv6 とマップ形式のハンドシェイク、接続受け入れ、送受信、ICMPv6 エラー、デバイスオプションは作成時のネットワークで分離します。受け入れた接続はリスナーのネットワークを保持します。IPv4 遅延ループバックキューは配信または破棄までネットワーク参照を保持します。送信はそのネットワークの経路とインターフェース状態を確認し、物理出力は初期ネットワークに属します。特権ポートはネットワーク owner の ``CAP_NET_BIND_SERVICE`` で認可します。インターフェース ioctl と ``SO_BINDTODEVICE`` は作成時のネットワークを使用します。非初期 TCP の独自グローバル制御は ``EOPNOTSUPP`` を返します。旧接続入口は数値 IPv4 宛先を受け付け、ホスト名解決は初期ネットワークに限定します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po index 2e696cf3..857e22df 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po @@ -52,8 +52,8 @@ msgstr "" msgid "配置与观测" msgstr "設定と観測" -msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。TCP 和 raw socket 的 ioctl 随其 transport 隔离接通。" -msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` はソケット作成時に保持したネットワーク scope のリンク、IPv4/IPv6 アドレス、経路を照会・変更し、FD 転送後もその scope を使用します。変更にはネットワークの user owner における ``CAP_NET_ADMIN`` が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 アドレスを取得します。IPv6 アドレスと経路の ioctl は対象ネットワークの状態と owner 権限を使用し、引数形式は socket family で選択します。UDP のインターフェース、IPv6 アドレス、経路 ioctl は作成元ネットワークを使用します。TCP と raw socket の ioctl は各 transport の隔離に合わせて対応します。" +msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP 和 TCP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。raw socket 的 ioctl 随其 transport 隔离接通。" +msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` はソケット作成時に保持したネットワーク scope のリンク、IPv4/IPv6 アドレス、経路を照会・変更し、FD 転送後もその scope を使用します。変更にはネットワークの user owner における ``CAP_NET_ADMIN`` が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 アドレスを取得します。IPv6 アドレスと経路の ioctl は対象ネットワークの状態と owner 権限を使用し、引数形式は socket family で選択します。UDP と TCP のインターフェース、IPv6 アドレス、経路 ioctl は作成元ネットワークを使用します。raw socket の ioctl は transport の隔離に合わせて対応します。" msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" msgstr "ルートマルチキャストはリンク、IPv6 アドレス、IPv6 ルートのグループに対応します。IPv4 アドレスとルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。各ネットワーク名前空間は独立した購読スナップショットを保持し、すべての取得が成功してから公開します。最後の購読者が閉じるか購読を解除すると解放します。変更通知と overrun はネットワーク scope ごとに配信し、受信キューのオーバーフローは ``ENOBUFS`` を報告するため、呼び出し元は再照会してください。" @@ -65,8 +65,8 @@ msgstr "" "複数部分からなる問い合わせでは、データと終端の ``NLMSG_DONE`` を別々のデータグラムとして送信します。終端マーカーは要求のシーケンス番号と受信ポート ID " "を保持し、結果が空でも送信します。受信側は引き続き各データグラム内の全メッセージを走査し、対応する番号の ``NLMSG_DONE`` またはエラーを待つ必要があります。" -msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由和 UDP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。TCP 和 raw transport 的网络隔离仍待完成,非初始空间的 ``tcp6`` 和 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト形式を使用します。アドレス scope の符号化は rtnetlink の scope 値と異なります。アドレス、経路、UDP 表は呼び出し元の現在のネットワーク scope に従います。スナップショットは内部状態をコピーし、待機をまたいでコピーを保持します。TCP と raw transport のネットワーク隔離は今後の実装対象で、非初期ネットワークの ``tcp6`` と ``raw6`` はヘッダーだけを出力します。" +msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP 和 TCP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。raw transport 的网络隔离仍待完成,非初始空间的 ``raw6`` 仅输出表头。" +msgstr "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト形式を使用します。アドレス scope の符号化は rtnetlink の値と異なります。アドレス、経路、UDP、TCP の表は呼び出し元の現在のネットワーク scope に従います。スナップショットは内部状態をコピーし、待機をまたいでコピーだけを保持します。raw transport のネットワーク分離は今後の実装で、非初期空間の ``raw6`` はヘッダーのみを出力します。" msgid "" "每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" diff --git a/Documentation/userspace-api/ipv6.rst b/Documentation/userspace-api/ipv6.rst index 102c8873..6be61d0e 100644 --- a/Documentation/userspace-api/ipv6.rst +++ b/Documentation/userspace-api/ipv6.rst @@ -32,7 +32,7 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 配置与观测 ========== -``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。TCP 和 raw socket 的 ioctl 随其 transport 隔离接通。 +``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP 和 TCP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。raw socket 的 ioctl 随其 transport 隔离接通。 路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。 @@ -40,7 +40,7 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。 -``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由和 UDP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。TCP 和 raw transport 的网络隔离仍待完成,非初始空间的 ``tcp6`` 和 ``raw6`` 仅输出表头。 +``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP 和 TCP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。raw transport 的网络隔离仍待完成,非初始空间的 ``raw6`` 仅输出表头。 每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。 diff --git a/include/reliefnt/net.h b/include/reliefnt/net.h index 0bfc55ec..8b6b4ad1 100644 --- a/include/reliefnt/net.h +++ b/include/reliefnt/net.h @@ -86,7 +86,7 @@ int net_ntp_sync(struct reliefos_time_sync *request); */ int net_http_get(struct reliefos_net_http_get *request); /** - * @brief Allocate a TCP socket and return its internal network handle in request. + * @brief Allocate a TCP socket retaining the caller's current network namespace. * @param request Requested family/type/protocol and output handle/status. * @param owner_pid Owning process identifier. * @param owner_uid Owning user identifier used for connection visibility. @@ -95,10 +95,12 @@ int net_http_get(struct reliefos_net_http_get *request); int net_socket_open(struct reliefos_net_socket_open *request, uint32_t owner_pid, uint32_t owner_uid); /** - * @brief Resolve and connect the requested TCP socket, updating endpoint fields. + * @brief Connect through the creation network, updating endpoint fields. * @param request Socket handle, hostname/address, port, and output status/endpoints. * @param owner_pid Required socket owner process identifier. * @return Zero when the request was processed; inspect request->status for the result. + * Legacy hostname resolution uses the initial network's global resolver policy. + * A noninitial endpoint accepts numeric IPv4 targets through this entry point. */ int net_socket_connect(struct reliefos_net_socket_connect *request, uint32_t owner_pid); /** @@ -155,10 +157,18 @@ short net_socket_poll_fd(int32_t handle, uint32_t owner_pid, short events); */ void net_socket_pin_fd(int32_t handle); /** - * @brief Release an AF_INET file-description reference and permit later collection. + * @brief Close an AF_INET description, immediately releasing an unbound closed socket. * @param handle Internal socket handle. + * Bound or protocol-active endpoints retain their network until normal collection. */ void net_socket_release_fd(int32_t handle); +/** @brief Borrow a live TCP endpoint's creation network under execution ownership. + * @param handle Internal socket handle held by the caller's open description. + * @return Borrowed namespace, or NULL for the initial network or an unknown handle. + * The caller retains the socket lifetime across use and performs authorization + * against this network's user owner. No reference is transferred. + */ +struct net_namespace *net_socket_namespace(int32_t handle); /** * @brief Park a blocking stream writer until transmit queue space is available. * @param handle Internal socket handle. @@ -270,8 +280,9 @@ struct text_stream; void net_tcp6_error(const struct in6_addr *source,const struct in6_addr *destination, uint16_t source_port,uint16_t destination_port,int error,uint32_t mtu); /** @brief Render the live native IPv6 TCP registry. + * @param ns Borrowed network, NULL for the initial network. * @param stream Caller-owned proc output. */ -void net_tcp6_proc_emit(struct text_stream *stream); +void net_tcp6_proc_emit(struct net_namespace *ns, struct text_stream *stream); /** * @brief Shut down a TCP socket direction and queue a FIN after pending writes. * @param handle Internal socket handle. @@ -343,11 +354,12 @@ int net_ipv4_send_udp_on(struct net_namespace *ns, uint32_t ifindex, uint32_t so uint16_t source_port, uint16_t destination_port, const void *data, uint32_t length); -/** @brief Deliver a checked ICMPv6 error only to TCP state on the matching link. +/** @brief Deliver a checked ICMPv6 error to TCP state in its network and link. + * @param ns Borrowed ingress network, NULL for the initial network. * @param ifindex Link or zero. @param source Local. @param destination Peer. * @param source_port Local port. @param destination_port Peer port. * @param error Positive errno. @param mtu Reported MTU. */ -void net_tcp6_error_on(uint32_t ifindex, const struct in6_addr *source, +void net_tcp6_error_on(struct net_namespace *ns, uint32_t ifindex, const struct in6_addr *source, const struct in6_addr *destination, uint16_t source_port, uint16_t destination_port, int error, uint32_t mtu); diff --git a/kernel/syscall/device/legacy_ioctl.c b/kernel/syscall/device/legacy_ioctl.c index eb180953..4617d263 100644 --- a/kernel/syscall/device/legacy_ioctl.c +++ b/kernel/syscall/device/legacy_ioctl.c @@ -4,6 +4,7 @@ extern int64_t task_inotify_fionread(struct task *, const struct task_file *, ui #include #include #include +#include #include #include @@ -353,7 +354,9 @@ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t if (file && (file->flags & TASK_FILE_FLAG_SOCKET_INET) && task_inet_family(file) == AF_INET6 && (a1 == SIOCSIFADDR || a1 == SIOCDIFADDR || a1 == SIOCADDRT || a1 == SIOCDELRT)) return net_ipv6_interface_ioctl(file->kind == TASK_FILE_KIND_UDP ? - task_udp_namespace(file) : NULL, (uint32_t)a1, a2); + task_udp_namespace(file) : + file->kind == TASK_FILE_KIND_PACKET ? NULL : + net_socket_namespace((int32_t)file->aux), (uint32_t)a1, a2); if (file && (file->flags & TASK_FILE_FLAG_SOCKET_INET)) return task_net_control(file, (uint32_t)a1, a2); if (file && (file->node.flags & STORAGE_NODE_FLAG_DEV_NODE) && diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index cd91016d..21430409 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -1369,6 +1369,7 @@ void task_inet_release(struct task_file *file) * @note Linux SO_*TIMEO values are converted to scheduler ticks with ceiling * rounding. An all-zero timeval maps to an infinite wait; negative seconds map * to an immediate timeout and are reported by getsockopt as (0, 0). + * SO_BINDTODEVICE resolves and authorizes against the endpoint's creation network. */ static int inet_socket_option(bool setting, int level, int option, uint64_t address, uint64_t length, int32_t handle) @@ -1377,7 +1378,7 @@ static int inet_socket_option(bool setting, int level, int option, uint32_t index = 0; int result = net_socket_bound_device(handle, false, &index); if (result < 0) return result; - result = net_interface_device_option(NULL, setting, address, length, &index); + result = net_interface_device_option(net_socket_namespace(handle), setting, address, length, &index); if (result < 0) return result; return setting ? net_socket_bound_device(handle, true, &index) : 0; } @@ -1555,10 +1556,7 @@ static int64_t inet_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, net_socket_pin_fd(request.socket); return fd; } - { - struct reliefos_net_socket_close close = {.socket = request.socket}; - (void)net_socket_close(&close, task->pid); - } + net_socket_release_fd(request.socket); return fd; } file = task_file_for_io(task, (int)a0); diff --git a/net/core.c b/net/core.c index 2f9ac9e5..247ae9b8 100644 --- a/net/core.c +++ b/net/core.c @@ -93,13 +93,13 @@ void net_device_attached(uint32_t ifindex) netlink_ipv6_changed(NULL); } -/** @brief Retire sockets and discovery state belonging to one removed device. +/** @brief Retire initial-network sockets and discovery state of a removed device. * @param ifindex Non-reused hardware interface index. Other interfaces retain * their addresses, routes, neighbors and connections. Execution ownership held. */ void net_device_detached(uint32_t ifindex) { for (struct net_socket *s = net_sockets; s; s = s->registry_next) { - if (s->used && s->ifindex == ifindex) { + if (!s->net_ns && s->used && s->ifindex == ifindex) { s->error = LINUX_ENETDOWN; net_socket_mark_closed(s, RELIEFOS_NET_STATUS_NO_DEVICE); } diff --git a/net/internal.h b/net/internal.h index 4297595d..b0167d70 100644 --- a/net/internal.h +++ b/net/internal.h @@ -149,9 +149,11 @@ struct net_arp_cache_entry { * * The receive and transmit storage is allocated with this object. The network * registry never relocates sockets; collection detaches both embedded wait - * queues and the optional active-work queue before releasing the object. + * queues and the optional active-work queue before releasing the creation + * network reference and the object. Accepted children retain the listener's network. */ struct net_socket { + struct net_namespace *net_ns; uint32_t used; bool fd_owned; bool shutdown_read; @@ -965,7 +967,7 @@ int net_http_resolve_hosts(const char *host, uint32_t host_len, uint32_t *out_status); /** - * @brief Allocate and register one dynamically backed TCP socket. + * @brief Register a dynamically backed TCP socket retaining the caller's network. * @param request Requested domain/type/protocol and output handle/status. * @param owner_pid Owning process identifier. * @param owner_uid Owning user identifier. @@ -1036,8 +1038,9 @@ short net_socket_poll_fd(int32_t handle, uint32_t owner_pid, short events); void net_socket_pin_fd(int32_t handle); /** - * @brief Release a socket's AF_INET file-description reference. + * @brief Close a socket description and immediately free an unbound closed endpoint. * @param handle Internal socket handle. + * Bound or protocol-active endpoints retain their network until normal collection. */ void net_socket_release_fd(int32_t handle); @@ -1139,10 +1142,11 @@ void net_handle_udp_on(uint32_t ifindex, const uint8_t *ip, uint32_t total_len, /** @brief Process TCP with a stable ingress device identity. + * @param ns Borrowed ingress network, NULL for the initial network. * @param ifindex Ingress. @param ip IP packet. @param total_len Bytes. @param ihl Header size. * @param src_ip Peer address. @param source_mac Peer MAC or NULL for loopback. * @param wait Optional synchronous waiter. */ -void net_handle_tcp_on(uint32_t ifindex, const uint8_t *ip, uint32_t total_len, +void net_handle_tcp_on(struct net_namespace *ns, uint32_t ifindex, const uint8_t *ip, uint32_t total_len, uint32_t ihl, uint32_t src_ip, const uint8_t *source_mac, struct net_tcp_wait *wait); /** @brief Create an incoming IPv4 child associated with its ingress link. * @param ifindex Ingress. @param listener Parent. @param source Peer. @param destination Local. diff --git a/net/ipv4/core.c b/net/ipv4/core.c index e2d47a17..d54d93a6 100644 --- a/net/ipv4/core.c +++ b/net/ipv4/core.c @@ -68,7 +68,7 @@ void net_handle_ipv4_on(uint32_t ifindex, const uint8_t *frame, uint32_t len, return; } if (ip[9] == IPV4_PROTO_TCP) { - net_handle_tcp_on(ifindex, ip, total_len, ihl, src_ip, frame + 6, tcp_wait); + net_handle_tcp_on(NULL, ifindex, ip, total_len, ihl, src_ip, frame + 6, tcp_wait); return; } if (ip[9] != IPV4_PROTO_ICMP || total_len < ihl + 8u) { diff --git a/net/proc.c b/net/proc.c index 4bba51de..271a305c 100644 --- a/net/proc.c +++ b/net/proc.c @@ -94,8 +94,11 @@ int net_proc_emit(struct text_stream *s, const char *leaf) net_udp6_proc_emit(ns, s); return 0; } - if (!__builtin_strcmp(leaf, "tcp6") || - !__builtin_strcmp(leaf, "raw6")) { + if (!__builtin_strcmp(leaf, "tcp6")) { + net_tcp6_proc_emit(ns, s); + return 0; + } + if (!__builtin_strcmp(leaf, "raw6")) { if (!ns) net_ipv6_transport_proc_emit(s,leaf); else text_string(s, " sl local_address rem_address st tx_queue rx_queue tr tm->when " "retrnsmt uid timeout inode\n"); @@ -152,8 +155,8 @@ int net_proc_emit(struct text_stream *s, const char *leaf) text_string(s, " sl local_address rem_address st tx_queue rx_queue tr tm->when " "retrnsmt uid timeout inode\n"); uint32_t index = 0; - for (struct net_socket *n = ns ? NULL : net_sockets; n; n = n->registry_next) { - if (!n->used || !n->local_port || n->ipv6) + for (struct net_socket *n = net_sockets; n; n = n->registry_next) { + if (n->net_ns != ns || !n->used || !n->local_port || n->ipv6) continue; unsigned state = n->state == RELIEFOS_NET_TCP_SYN_SENT ? 2 : n->state == RELIEFOS_NET_TCP_ESTABLISHED diff --git a/net/socket/control.c b/net/socket/control.c index fa1663a3..5a6371eb 100644 --- a/net/socket/control.c +++ b/net/socket/control.c @@ -16,8 +16,8 @@ * @param file Borrowed socket OFD under execution ownership. * @param request Native ioctl number. @param address User argument address. * @return Zero, negative errno, or a user-memory prerequisite wait marker. - * Netlink and UDP interface operations use the retained creation network and - * its user owner. Private global control on noninitial UDP returns EOPNOTSUPP. + * Netlink, UDP and TCP interface operations use the retained creation network + * and its user owner. Private global control on noninitial UDP/TCP returns EOPNOTSUPP. */ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) { @@ -40,14 +40,17 @@ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) *(int *)(uintptr_t)address = bytes; return 0; } + struct net_namespace *ns = NULL; + if (file->kind == TASK_FILE_KIND_UDP) ns = task_udp_namespace(file); + else if (file->kind != TASK_FILE_KIND_PACKET && file->kind != TASK_FILE_KIND_NETLINK) + ns = net_socket_namespace((int32_t)file->aux); if (request >= 0x8900 && request <= 0x89ff) { if (file->kind == TASK_FILE_KIND_NETLINK) return task_netlink_ioctl(file, request, address); - return net_interface_ioctl(file->kind == TASK_FILE_KIND_UDP ? - task_udp_namespace(file) : NULL, request, address); + return net_interface_ioctl(ns, request, address); } if (request != RELIEFOS_NET_CONTROL_IOCTL) return -LINUX_ENOTTY; - if (file->kind == TASK_FILE_KIND_UDP && task_udp_namespace(file)) return -LINUX_EOPNOTSUPP; + if (ns) return -LINUX_EOPNOTSUPP; struct reliefos_net_control control; int rc=socket_user_import(task,address,&control,sizeof(control));if(rc)return rc; rc=socket_user_prepare(task,address,sizeof(control),true);if(rc)return rc; diff --git a/net/socket/packet.c b/net/socket/packet.c index 7177bd10..c569d8c3 100644 --- a/net/socket/packet.c +++ b/net/socket/packet.c @@ -766,7 +766,7 @@ void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex, const if ((protocol == 6 || protocol == 17) && length >= 48) { uint16_t source_port = ((uint16_t)packet[40] << 8) | packet[41]; uint16_t destination_port = ((uint16_t)packet[42] << 8) | packet[43]; - if (protocol == 6 && !ns) net_tcp6_error_on(ifindex, &source, &destination, source_port, destination_port, error, mtu); + if (protocol == 6) net_tcp6_error_on(ns, ifindex, &source, &destination, source_port, destination_port, error, mtu); else if (protocol == 17) net_udp6_error_on(ns, ifindex, &source, &destination, source_port, destination_port, error, mtu); } if (ns) return; @@ -807,7 +807,7 @@ static void net_raw6_proc_emit(struct text_stream *stream) * @param stream Caller-owned output slice. @param leaf Requested basename. */ void net_ipv6_transport_proc_emit(struct text_stream *stream, const char *leaf) { - if (!__builtin_strcmp(leaf,"tcp6")) net_tcp6_proc_emit(stream); + if (!__builtin_strcmp(leaf,"tcp6")) net_tcp6_proc_emit(NULL, stream); else if (!__builtin_strcmp(leaf,"udp6")) net_udp6_proc_emit(NULL, stream); else if (!__builtin_strcmp(leaf,"raw6")) net_raw6_proc_emit(stream); } diff --git a/net/tcp/input.c b/net/tcp/input.c index faa45a34..38543efe 100644 --- a/net/tcp/input.c +++ b/net/tcp/input.c @@ -2,13 +2,15 @@ /** * @brief Find a registered TCP socket by its peer and local port tuple. + * @param ns Borrowed ingress network, NULL for the initial network. + * @param ifindex Ingress interface index within that network. * @param src_ip Peer IPv4 source address in host byte order. * @param dst_ip Local IPv4 address in host byte order. * @param src_port Peer source port. * @param dst_port Local destination port. * @return Matching live socket, or null when the tuple is not registered. */ -static struct net_socket *net_socket_match(uint32_t ifindex, uint32_t src_ip, uint32_t dst_ip, uint16_t src_port, +static struct net_socket *net_socket_match(struct net_namespace *ns, uint32_t ifindex, uint32_t src_ip, uint32_t dst_ip, uint16_t src_port, uint16_t dst_port); /** @@ -66,7 +68,6 @@ static uint16_t net_tcp6_syn_mss(const uint8_t *tcp, uint32_t header) void net_tcp6_input(struct net_namespace *ns, const struct in6_addr *source, const struct in6_addr *destination, const void *data, uint32_t length, uint32_t ifindex) { - if (ns) return; const uint8_t *tcp = data; if (length < 20) return; uint32_t header = (uint32_t)(tcp[12] >> 4) * 4u; @@ -77,7 +78,7 @@ void net_tcp6_input(struct net_namespace *ns, const struct in6_addr *source, con uint8_t flags = tcp[13]; struct net_socket *match = NULL, *listener = NULL; for (struct net_socket *s = net_sockets; s; s = s->registry_next) { - if (!s->used || !s->ipv6 || s->mapped || s->local_port != destination_port || + if (s->net_ns != ns || !s->used || !s->ipv6 || s->mapped || s->local_port != destination_port || (s->bound_ifindex && s->bound_ifindex != ifindex)) continue; if (s->state == NET_TCP_LISTEN) { static const struct in6_addr zero = {0}; @@ -96,7 +97,7 @@ void net_tcp6_input(struct net_namespace *ns, const struct in6_addr *source, con } if (!match) { if (!(flags & TCP_FLAG_RST) && destination->s6_addr[0] != 0xff) { - struct net_socket reply = {.ifindex=ifindex,.ipv6=true,.local6=*destination,.remote6=*source, + struct net_socket reply = {.net_ns=ns,.ifindex=ifindex,.ipv6=true,.local6=*destination,.remote6=*source, .local_port=destination_port,.remote_port=source_port,.unicast_hops=-1, .remote_scope6=source->s6_addr[0] == 0xfe && (source->s6_addr[1] & 0xc0) == 0x80 ? ifindex : 0}; uint32_t reply_seq = (flags & TCP_FLAG_ACK) ? ack : 0; @@ -143,6 +144,8 @@ static bool net_tcp_segment_acceptable(const struct net_socket *socket, /** * @brief Validate and dispatch one IPv4 TCP segment, including its peer window. + * @param ns Borrowed ingress network, NULL for the initial network. + * @param ifindex Ingress interface index within that network. * @param ip Complete IPv4 packet containing the TCP segment. * @param total_len Packet length in bytes. * @param ihl IPv4 header length in bytes. @@ -151,7 +154,7 @@ static bool net_tcp_segment_acceptable(const struct net_socket *socket, * @param tcp_wait Optional synchronous legacy TCP exchange waiter. * @note Socket dispatch is serialized by the network execution transaction. */ -void net_handle_tcp_on(uint32_t ifindex, const uint8_t *ip, uint32_t total_len, +void net_handle_tcp_on(struct net_namespace *ns, uint32_t ifindex, const uint8_t *ip, uint32_t total_len, uint32_t ihl, uint32_t src_ip, const uint8_t *source_mac, struct net_tcp_wait *tcp_wait) @@ -184,13 +187,13 @@ void net_handle_tcp_on(uint32_t ifindex, const uint8_t *ip, uint32_t total_len, window = net_get_u16(tcp + 14); payload_len = tcp_len - hdr_len; uint32_t dst_ip = net_get_u32(ip + 16); - struct net_socket *matched = net_socket_match(ifindex, src_ip, dst_ip, src_port, dst_port); + struct net_socket *matched = net_socket_match(ns, ifindex, src_ip, dst_ip, src_port, dst_port); bool listening = false; if (!matched && (flags & (TCP_FLAG_SYN | TCP_FLAG_ACK | TCP_FLAG_RST)) == TCP_FLAG_SYN) { static const struct in6_addr any = {0}; static const uint8_t mapped_prefix[12] = {0,0,0,0,0,0,0,0,0,0,255,255}; for (struct net_socket *listener = net_sockets; listener; listener = listener->registry_next) { - if (!listener->used || listener->state != NET_TCP_LISTEN || listener->local_port != dst_port || + if (listener->net_ns != ns || !listener->used || listener->state != NET_TCP_LISTEN || listener->local_port != dst_port || (listener->local_ip && listener->local_ip != dst_ip) || (listener->bound_ifindex && listener->bound_ifindex != ifindex)) continue; if (listener->ipv6 && (listener->v6only || @@ -206,21 +209,21 @@ void net_handle_tcp_on(uint32_t ifindex, const uint8_t *ip, uint32_t total_len, if (matched && (flags & TCP_FLAG_SYN)) matched->peer_mss = net_tcp6_syn_mss(tcp, hdr_len); net_socket_handle_tcp(matched, seq, ack, window, flags, tcp + hdr_len, payload_len); } else if (!listening && !(flags & TCP_FLAG_RST) && source_mac) { - struct net_socket reply = {.ifindex=ifindex,.local_ip=dst_ip,.remote_ip=src_ip,.local_port=dst_port,.remote_port=src_port}; + struct net_socket reply = {.net_ns=ns,.ifindex=ifindex,.local_ip=dst_ip,.remote_ip=src_ip,.local_port=dst_port,.remote_port=src_port}; net_memcpy(reply.dst_mac, source_mac, 6); uint32_t response_seq = (flags & TCP_FLAG_ACK) ? ack : 0; uint32_t response_ack = seq + payload_len + !!(flags & TCP_FLAG_SYN) + !!(flags & TCP_FLAG_FIN); (void)net_send_tcp_socket(&reply, response_seq, response_ack, (flags & TCP_FLAG_ACK) ? TCP_FLAG_RST : TCP_FLAG_RST | TCP_FLAG_ACK, NULL, 0); } else if (!listening && !(flags & TCP_FLAG_RST) && - ((src_ip >> 24) == 127 || (src_ip && net_interface_for_ipv4(NULL, src_ip)))) { - struct net_socket reply = {.ifindex=ifindex,.local_ip=dst_ip,.remote_ip=src_ip,.local_port=dst_port,.remote_port=src_port}; + net_interface_for_ipv4(ns, src_ip)) { + struct net_socket reply = {.net_ns=ns,.ifindex=ifindex,.local_ip=dst_ip,.remote_ip=src_ip,.local_port=dst_port,.remote_port=src_port}; uint32_t response_seq = (flags & TCP_FLAG_ACK) ? ack : 0; uint32_t response_ack = seq + payload_len + !!(flags & TCP_FLAG_SYN) + !!(flags & TCP_FLAG_FIN); (void)net_send_tcp_socket(&reply, response_seq, response_ack, (flags & TCP_FLAG_ACK) ? TCP_FLAG_RST : TCP_FLAG_RST | TCP_FLAG_ACK, NULL, 0); } - if (!tcp_wait || (tcp_wait->ifindex && tcp_wait->ifindex != ifindex)) { + if (ns || !tcp_wait || (tcp_wait->ifindex && tcp_wait->ifindex != ifindex)) { return; } if (tcp_wait->src_port && src_port != tcp_wait->src_port) { @@ -278,18 +281,20 @@ void net_handle_tcp_on(uint32_t ifindex, const uint8_t *ip, uint32_t total_len, /** * @brief Find a registered TCP socket by its peer and local port tuple. + * @param ns Borrowed ingress network, NULL for the initial network. + * @param ifindex Ingress interface index within that network. * @param src_ip Peer IPv4 source address in host byte order. * @param dst_ip Local IPv4 destination in host byte order. * @param src_port Peer source port. * @param dst_port Local destination port. * @return Matching live socket, or null when the tuple is not registered. */ -static struct net_socket *net_socket_match(uint32_t ifindex, uint32_t src_ip, uint32_t dst_ip, uint16_t src_port, +static struct net_socket *net_socket_match(struct net_namespace *ns, uint32_t ifindex, uint32_t src_ip, uint32_t dst_ip, uint16_t src_port, uint16_t dst_port) { for (struct net_socket *socket = net_sockets; socket; socket = socket->registry_next) { - if (!socket->used || socket->state == RELIEFOS_NET_TCP_CLOSED || + if (socket->net_ns != ns || !socket->used || socket->state == RELIEFOS_NET_TCP_CLOSED || socket->state == NET_TCP_LISTEN || (socket->ipv6 && !socket->mapped) || (socket->bound_ifindex && socket->bound_ifindex != ifindex)) { continue; @@ -471,5 +476,5 @@ static void net_socket_handle_tcp(struct net_socket *socket, uint32_t seq, void net_handle_tcp(const uint8_t *ip, uint32_t total_len, uint32_t ihl, uint32_t src_ip, const uint8_t *source_mac, struct net_tcp_wait *wait) { - net_handle_tcp_on(source_mac ? netdev_next(0) : 1, ip, total_len, ihl, src_ip, source_mac, wait); + net_handle_tcp_on(NULL, source_mac ? netdev_next(0) : 1, ip, total_len, ihl, src_ip, source_mac, wait); } diff --git a/net/tcp/output.c b/net/tcp/output.c index bee35b62..4a0528dd 100644 --- a/net/tcp/output.c +++ b/net/tcp/output.c @@ -1,6 +1,11 @@ #include "../internal.h" +#include -struct tcp_loop_frame { uint32_t length, ifindex; uint8_t bytes[NET_FRAME_MAX]; }; +struct tcp_loop_frame { + struct net_namespace *net_ns; + uint32_t length, ifindex; + uint8_t bytes[NET_FRAME_MAX]; +}; static struct tcp_loop_frame tcp_loop_frames[32]; static uint32_t tcp_loop_head, tcp_loop_count; @@ -9,16 +14,18 @@ static uint32_t tcp_loop_head, tcp_loop_count; bool net_tcp_loop_pending(void) { return tcp_loop_count != 0; } /** @brief Deliver a bounded batch of deferred IPv4 TCP loopback frames. - * Frames are copied before dispatch so a reply may safely reuse a ring slot. */ + * Frames retain their creation network through dispatch or drop. Copying before + * dispatch lets replies reuse ring slots while the local copy owns the reference. */ void net_tcp_loop_service(void) { for (unsigned n = 0; n < 16 && tcp_loop_count; ++n) { struct tcp_loop_frame frame = tcp_loop_frames[tcp_loop_head]; tcp_loop_head = (tcp_loop_head + 1u) % 32u; --tcp_loop_count; const uint8_t *ip = frame.bytes + 14; - if (net_interface_exists(NULL, frame.ifindex) && net_interface_is_up(NULL, frame.ifindex)) - net_handle_tcp_on(frame.ifindex, ip, frame.length - 14u, 20u, + if (net_interface_is_ready(frame.net_ns, frame.ifindex)) + net_handle_tcp_on(frame.net_ns, frame.ifindex, ip, frame.length - 14u, 20u, net_get_u32(ip + 12), NULL, NULL); + net_namespace_put(frame.net_ns); } } @@ -65,6 +72,8 @@ uint32_t net_socket_select_window(const struct net_socket *socket) /** * @brief Build and transmit one TCP segment with a current local receive window. + * @param ns Borrowed creation network, retained by a queued local frame. + * @param ifindex Selected scoped output interface. * @param dst_mac Ethernet destination address. * @param src_ip Host-order local IPv4 source address. * @param dst_ip Host-order peer IPv4 destination address. @@ -79,7 +88,7 @@ uint32_t net_socket_select_window(const struct net_socket *socket) * @note The receiver window is read from the matching stable socket under the * network execution transaction, then published only after successful transmit. */ -static int net_send_tcp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint32_t src_ip, +static int net_send_tcp_to_mac_on(struct net_namespace *ns, uint32_t ifindex, const uint8_t *dst_mac, uint32_t src_ip, uint32_t dst_ip, uint16_t src_port, uint16_t dst_port, uint32_t seq, uint32_t ack, uint8_t flags, @@ -96,10 +105,14 @@ static int net_send_tcp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint (payload_len && !payload)) { return -1; } + bool local = net_interface_for_ipv4(ns, dst_ip) != 0; + if (!local && ns) return -LINUX_ENETUNREACH; + if (!net_interface_is_ready(ns, ifindex)) return -LINUX_ENETDOWN; tcp_len = (uint16_t)(tcp_header_len + payload_len); total_len = (uint16_t)(20u + tcp_len); net_memzero(frame, 34u + tcp_header_len + payload_len); - net_write_eth_on(ifindex, frame, dst_mac, ETH_TYPE_IPV4); + if (local) net_put_u16(frame + 12, ETH_TYPE_IPV4); + else net_write_eth_on(ifindex, frame, dst_mac, ETH_TYPE_IPV4); ip[0] = 0x45; ip[1] = 0; net_put_u16(ip + 2, total_len); @@ -120,7 +133,7 @@ static int net_send_tcp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint uint32_t window = 8192u; struct net_socket *receiver = 0; for (struct net_socket *s = net_sockets; s; s = s->registry_next) { - if (s->used && s->local_port == src_port && s->remote_port == dst_port && + if (s->net_ns == ns && s->used && s->local_port == src_port && s->remote_port == dst_port && s->remote_ip == dst_ip && s->local_ip == src_ip) { receiver = s; window = net_socket_select_window(s); @@ -140,14 +153,15 @@ static int net_send_tcp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint } net_put_u16(tcp + 16, net_tcp_checksum(src_ip, dst_ip, tcp, tcp_len)); int result; - if ((dst_ip >> 24) == 127 || (dst_ip && net_interface_for_ipv4(NULL, dst_ip))) { + if (local) { if (tcp_loop_count == 32) return -LINUX_ENOBUFS; struct tcp_loop_frame *queued = &tcp_loop_frames[(tcp_loop_head + tcp_loop_count) % 32u]; + queued->net_ns = net_namespace_get(ns); queued->length = 14u + total_len; queued->ifindex = ifindex; net_memcpy(queued->bytes, frame, queued->length); ++tcp_loop_count; result = (int)queued->length; - } else result = net_interface_is_ready(NULL, ifindex) ? netdev_send(ifindex, frame, 14u + total_len) : -LINUX_ENETDOWN; + } else result = netdev_send(ifindex, frame, 14u + total_len); if (result >= 0 && receiver && (flags & TCP_FLAG_ACK)) { receiver->rx_window_ack = ack; receiver->rx_window = window; @@ -170,7 +184,7 @@ uint32_t net_socket_mss(const struct net_socket *socket) return mss; } -/** @brief Emit one TCP segment for a stable socket, using IPv6 pseudo-header checksums. +/** @brief Emit TCP through the endpoint's creation network and scoped route. * @param socket Endpoint under execution ownership. @param seq Sequence number. * @param ack Acknowledgment. @param flags TCP control flags. @param payload Optional data. * @param length Payload bytes. @return Lower-layer result or negative errno. */ @@ -179,12 +193,13 @@ int net_send_tcp_socket(struct net_socket *socket, uint32_t seq, uint32_t ack, { if (socket->resolving_neighbor) return -LINUX_EAGAIN; if (!socket->ipv6 || socket->mapped) { - bool local = net_interface_for_ipv4(NULL, socket->remote_ip) != 0; + struct net_ipv4_path path; + int result = net_ipv4_route_lookup(socket->net_ns, socket->remote_ip, socket->local_ip, + socket->bound_ifindex, &path); + if (result < 0) return result; + bool local = net_interface_for_ipv4(socket->net_ns, socket->remote_ip) != 0; if (!local) { - struct net_ipv4_path path; - int result = net_ipv4_route_lookup(NULL, socket->remote_ip, socket->local_ip, - socket->bound_ifindex, &path); - if (result < 0) return result; + if (socket->net_ns) return -LINUX_ENETUNREACH; if (socket->ifindex != path.ifindex || socket->next_hop != path.next_hop || net_mac_is_zero(socket->dst_mac)) { socket->resolving_neighbor = true; @@ -192,17 +207,17 @@ int net_send_tcp_socket(struct net_socket *socket, uint32_t seq, uint32_t ack, socket->resolving_neighbor = false; if (result < 0) return result; } - socket->ifindex = path.ifindex; - socket->next_hop = path.next_hop; } - return net_send_tcp_to_mac_on(local ? net_interface_for_ipv4(NULL, socket->remote_ip) : socket->ifindex, socket->dst_mac, + socket->ifindex = path.ifindex; + socket->next_hop = path.next_hop; + return net_send_tcp_to_mac_on(socket->net_ns, path.ifindex, socket->dst_mac, socket->local_ip, socket->remote_ip, socket->local_port, socket->remote_port, seq, ack, flags, payload, length); } if (socket->remote_scope6 && socket->bound_ifindex && socket->remote_scope6 != socket->bound_ifindex) return -LINUX_EINVAL; struct net_ipv6_path path; - int ret = net_ipv6_route(NULL, &socket->remote6, socket->remote_scope6 ? socket->remote_scope6 : socket->bound_ifindex, &socket->local6, &path); + int ret = net_ipv6_route(socket->net_ns, &socket->remote6, socket->remote_scope6 ? socket->remote_scope6 : socket->bound_ifindex, &socket->local6, &path); if (ret < 0) return ret; socket->mtu6 = path.mtu; socket->ifindex = path.ifindex; @@ -223,7 +238,7 @@ int net_send_tcp_socket(struct net_socket *socket, uint32_t seq, uint32_t ack, } if (length) net_memcpy(tcp + header, payload, length); net_put_u16(tcp + 16, net_ipv6_checksum(&path.source, &path.destination, 6, tcp, header + length)); - ret = net_ipv6_output(NULL, &path, 6, tcp, header + length, socket->unicast_hops, 0, + ret = net_ipv6_output(socket->net_ns, &path, 6, tcp, header + length, socket->unicast_hops, 0, socket->dont_fragment || socket->mtu_discover == IPV6_PMTUDISC_DO, true); if (ret >= 0 && (flags & TCP_FLAG_ACK)) { socket->rx_window_ack = ack; socket->rx_window = window; socket->rx_window_valid = true; @@ -243,6 +258,6 @@ int net_send_tcp_to_mac(const uint8_t *mac, uint32_t source, uint32_t destinatio struct net_ipv4_path path; int result = net_ipv4_route_lookup(NULL, destination, source, 0, &path); if (result < 0) return result; - return net_send_tcp_to_mac_on(path.ifindex, mac, source, destination, source_port, + return net_send_tcp_to_mac_on(NULL, path.ifindex, mac, source, destination, source_port, destination_port, seq, ack, flags, data, length); } diff --git a/net/tcp/socket.c b/net/tcp/socket.c index 2d416614..3e5b218d 100644 --- a/net/tcp/socket.c +++ b/net/tcp/socket.c @@ -1,6 +1,8 @@ #include "../internal.h" #include #include +#include +#include #define NET_TCP_SOCKET_SERVICE_BUDGET 4u @@ -40,12 +42,13 @@ static struct net_socket *net_socket_find(int32_t handle, uint32_t owner_pid, int allow_closed); /** - * Net socket alloc. + * @brief Allocate a TCP endpoint retaining the selected creation network. + * @param ns Borrowed network, NULL for the initial network. * @param owner_pid Value supplied by the caller. * @param owner_uid Value supplied by the caller. * @return The value or status produced by the operation. */ -static struct net_socket *net_socket_alloc(uint32_t owner_pid, uint32_t owner_uid); +static struct net_socket *net_socket_alloc(struct net_namespace *ns, uint32_t owner_pid, uint32_t owner_uid); /** * Net socket clamp timeout. @@ -68,12 +71,9 @@ static uint32_t net_socket_connect_ip(struct net_socket *socket, uint32_t remote_ip, uint16_t remote_port, uint32_t timeout_ms, bool asynchronous); -/** - * Net connection visible. - * @param socket Value supplied by the caller. - * @param viewer Value supplied by the caller. - * @return The value or status produced by the operation. - */ +/** @brief Apply network scope followed by legacy role and UID connection visibility. + * @param socket Borrowed stable endpoint. @param viewer Snapshot caller. + * @return Nonzero when the viewer may enumerate this endpoint. */ static int net_connection_visible(const struct net_socket *socket, const struct task *viewer); @@ -172,7 +172,7 @@ static uint32_t net_now32(void) } /** - * @brief Unlink a socket after detaching its waiters and freeing owned buffers. + * @brief Unlink a socket, wake its waiters and release its buffers and network. * @param socket Stable socket object that is no longer externally reachable. */ static void net_socket_clear(struct net_socket *socket) @@ -188,6 +188,7 @@ static void net_socket_clear(struct net_socket *socket) (void)kernel_wait_queue_wake_all(&socket->wait_read); kernel_free(socket->rx); kernel_free(socket->tx); + net_namespace_put(socket->net_ns); kernel_free(socket); } } @@ -288,11 +289,12 @@ int net_socket_trace_tls(const struct net_socket *socket) /** * @brief Allocate and register a stable TCP socket object with dynamic buffers. + * @param ns Borrowed creation network, retained after buffer allocation succeeds. * @param owner_pid Process identifier that owns the socket. * @param owner_uid User identifier used for connection visibility. * @return New registered socket, or null when memory allocation fails. */ -static struct net_socket *net_socket_alloc(uint32_t owner_pid, uint32_t owner_uid) +static struct net_socket *net_socket_alloc(struct net_namespace *ns, uint32_t owner_pid, uint32_t owner_uid) { struct net_socket *slot; int32_t handle; @@ -317,6 +319,7 @@ static struct net_socket *net_socket_alloc(uint32_t owner_pid, uint32_t owner_ui if (handle > 0 && !net_socket_find(handle, 0, 1)) break; } slot->handle = handle; + slot->net_ns = net_namespace_get(ns); slot->owner_pid = owner_pid; slot->owner_uid = owner_uid; slot->state = RELIEFOS_NET_TCP_CLOSED; @@ -384,20 +387,22 @@ static bool tcp_uses_ipv4(const struct net_socket *socket) /** @brief Reserve one TCP port across native and mapped families. * @param socket Unbound endpoint. @param ip Host-order IPv4 address when applicable. * @param port Requested host-order port or zero. @return Zero or negative errno. - * Binding a privileged port requires initial user namespace CAP_NET_BIND_SERVICE. + * Binding a privileged port requires CAP_NET_BIND_SERVICE in the network owner. */ static int tcp_bind_port(struct net_socket *socket, uint32_t ip, uint16_t port) { static uint16_t next_port = 49152; struct task *task = sched_current_task(); if (socket->bound) return -LINUX_EINVAL; - if (port && port < 1024 && (!task || !(task_initial_capabilities(task) & (1ULL << CAP_NET_BIND_SERVICE)))) return -LINUX_EACCES; + if (port && port < 1024 && + !task_ns_capable(task, socket->net_ns ? socket->net_ns->user_ns : NULL, CAP_NET_BIND_SERVICE)) + return -LINUX_EACCES; for (unsigned attempt = 0; attempt < 16384; ++attempt) { uint16_t candidate = port ? port : next_port++; if (next_port < 49152) next_port = 49152; bool conflict = false; for (struct net_socket *other = net_sockets; other; other = other->registry_next) { - if (other == socket || !other->used || !other->bound || other->listener || other->local_port != candidate) continue; + if (other == socket || other->net_ns != socket->net_ns || !other->used || !other->bound || other->listener || other->local_port != candidate) continue; if (socket->reuse && other->reuse && other->state != NET_TCP_LISTEN) continue; if (socket->bound_ifindex && other->bound_ifindex && socket->bound_ifindex != other->bound_ifindex) continue; if (tcp_uses_ipv4(socket) && tcp_uses_ipv4(other) && (!ip || !other->local_ip || ip == other->local_ip)) conflict = true; @@ -703,7 +708,7 @@ void net_tcp_service_sockets(void) } /** - * @brief Allocate and register one dynamically backed TCP socket. + * @brief Register a dynamically backed TCP socket retaining the caller's network. * @param request Requested domain/type/protocol and output handle/status. * @param owner_pid Owning process identifier. * @param owner_uid Owning user identifier. @@ -725,7 +730,8 @@ int net_socket_open(struct reliefos_net_socket_open *request, uint32_t owner_pid request->protocol != RELIEFOS_NET_IPPROTO_TCP)) { return 0; } - socket = net_socket_alloc(owner_pid, owner_uid); + struct task *task = sched_current_task(); + socket = net_socket_alloc(task ? task->net_ns : NULL, owner_pid, owner_uid); if (!socket) { request->status = RELIEFOS_NET_STATUS_SOCKET_LIMIT; return 0; @@ -761,15 +767,19 @@ static uint32_t net_socket_connect_ip(struct net_socket *socket, return RELIEFOS_NET_STATUS_BAD_ARGUMENT; } struct net_ipv4_path path; - ret = net_ipv4_route_lookup(NULL, remote_ip, socket->local_ip, socket->bound_ifindex, &path); + ret = net_ipv4_route_lookup(socket->net_ns, remote_ip, socket->local_ip, socket->bound_ifindex, &path); if (ret < 0) { socket->error = -ret; return RELIEFOS_NET_STATUS_NO_ADDRESS; } socket->ifindex = path.ifindex; socket->next_hop = path.next_hop; - if (net_interface_for_ipv4(NULL, remote_ip)) net_memzero(dst_mac, sizeof(dst_mac)); + if (net_interface_for_ipv4(socket->net_ns, remote_ip)) net_memzero(dst_mac, sizeof(dst_mac)); else { + if (socket->net_ns) { + socket->error = LINUX_ENETUNREACH; + return RELIEFOS_NET_STATUS_NO_ADDRESS; + } arp_ip = path.next_hop; ret = net_resolve_mac_on(path.ifindex, arp_ip, timeout_ms, dst_mac); if (ret < 0) return ret == -1 ? RELIEFOS_NET_STATUS_TX_FAILED : RELIEFOS_NET_STATUS_ARP_TIMEOUT; @@ -862,6 +872,8 @@ static uint32_t net_socket_connect_ip(struct net_socket *socket, * @return Zero when processed; request->status carries connection outcome. * @note The legacy control ABI retains its explicit bounded timeout; Linux fd calls * use their connection path and are not governed by SO_RCVTIMEO/SO_SNDTIMEO. + * Numeric addresses use the creation network. Legacy hostname lookup requires + * the initial network, where the global resolver policy is maintained. */ int net_socket_connect(struct reliefos_net_socket_connect *request, uint32_t owner_pid) @@ -894,7 +906,7 @@ int net_socket_connect(struct reliefos_net_socket_connect *request, request->status = RELIEFOS_NET_STATUS_BAD_ARGUMENT; return 0; } - if (!e1000_is_ready()) { + if (!socket->net_ns && !e1000_is_ready()) { request->status = RELIEFOS_NET_STATUS_NO_DEVICE; return 0; } @@ -905,7 +917,12 @@ int net_socket_connect(struct reliefos_net_socket_connect *request, return 0; } literal = net_parse_ipv4_literal(request->host, host_len, &literal_ip) == 0; - { + if (socket->net_ns && !literal) { + socket->error = LINUX_ENETUNREACH; + request->status = RELIEFOS_NET_STATUS_NO_ADDRESS; + return 0; + } + if (!socket->net_ns) { uint32_t config_status = net_ensure_ipv4_config(timeout_ms, literal ? 0 : 1); if (config_status != RELIEFOS_NET_STATUS_OK) { request->status = config_status; @@ -1174,15 +1191,15 @@ int net_socket_close(struct reliefos_net_socket_close *request, } /** - * Net connection visible. - * @param socket Value supplied by the caller. - * @param viewer Value supplied by the caller. - * @return The value or status produced by the operation. + * @brief Apply the viewer's network scope and role/UID visibility rules. + * @param socket Borrowed stable TCP endpoint. + * @param viewer Task whose retained network selects the visible endpoint scope. + * @return Nonzero when the endpoint is visible to the viewer. */ static int net_connection_visible(const struct net_socket *socket, const struct task *viewer) { - if (!socket || !viewer) { + if (!socket || !viewer || socket->net_ns != viewer->net_ns) { return 0; } if (viewer->role == RELIEFOS_AUTH_ROLE_ADMIN) { @@ -1197,7 +1214,7 @@ static int net_connection_visible(const struct net_socket *socket, /** * @brief Count visible live TCP sockets and fill the caller's bounded snapshot. * @param request Snapshot capacity, optional entry array, and live-count output. - * @param viewer Task identity used to apply admin/service/user visibility rules. + * @param viewer Task identity and network for admin/service/user visibility rules. * @return Zero or a negative error for an invalid request. * @note request->count is not capped by the legacy fixed-size entry array capacity. */ @@ -1287,6 +1304,7 @@ void net_socket_pin_fd(int32_t handle) if (s) s->fd_owned = true; } +/** @copydoc net_socket_release_fd */ void net_socket_release_fd(int32_t handle) { struct net_socket *s = net_socket_find(handle, 0, 1); @@ -1294,6 +1312,14 @@ void net_socket_release_fd(int32_t handle) struct reliefos_net_socket_close request = {.socket = handle}; (void)net_socket_close(&request, 0); s->fd_owned = false; + if (!s->bound && s->state == RELIEFOS_NET_TCP_CLOSED) net_socket_clear(s); +} + +/** @copydoc net_socket_namespace */ +struct net_namespace *net_socket_namespace(int32_t handle) +{ + struct net_socket *socket = net_socket_find(handle, 0, 1); + return socket ? socket->net_ns : NULL; } int net_socket_error(int32_t handle, bool clear) @@ -1311,7 +1337,7 @@ int net_socket_available(int32_t handle) return s ? (int)s->rx_len : -LINUX_EBADF; } -/** @brief Start an IPv4 TCP connection, including deferred local loopback. +/** @brief Start an IPv4 TCP connection through the endpoint's creation network. * @param handle Stable TCP socket. @param ip Host-order peer IPv4 address. * @param port Peer port. @param nonblock Return EINPROGRESS for an unfinished handshake. * @return Zero or a negative Linux errno. */ @@ -1323,7 +1349,7 @@ int net_socket_connect_fd(int32_t handle, uint32_t ip, uint16_t port, bool nonbl if (s->state != RELIEFOS_NET_TCP_CLOSED) return -LINUX_EISCONN; if (!ip || !port) return -LINUX_EINVAL; struct net_ipv4_path path; - int route = net_ipv4_route_lookup(NULL, ip, s->local_ip, s->bound_ifindex, &path); + int route = net_ipv4_route_lookup(s->net_ns, ip, s->local_ip, s->bound_ifindex, &path); if (route < 0) return route; s->error = 0; uint32_t status = net_socket_connect_ip(s, ip, port, 10000, nonblock); @@ -1353,7 +1379,7 @@ int net_socket_family(int32_t handle) return !s ? -LINUX_EBADF : s->ipv6 ? AF_INET6 : AF_INET; } -/** @brief Bind a stream endpoint to a checked native or mapped address. +/** @brief Bind a native or mapped address and port in the endpoint's creation network. * @param handle Internal socket. @param address Kernel-owned native address. * @return Zero or negative errno with no partial binding. */ int net_socket_bind6_fd(int32_t handle, const struct sockaddr_in6 *address) @@ -1362,21 +1388,19 @@ int net_socket_bind6_fd(int32_t handle, const struct sockaddr_in6 *address) if (!s) return -LINUX_EBADF; if (!address || s->bound || s->state != RELIEFOS_NET_TCP_CLOSED) return -LINUX_EINVAL; uint32_t scope = net_ipv6_needs_scope_id(&address->sin6_addr) ? address->sin6_scope_id : 0; - if (scope && !net_interface_exists(NULL, scope)) return -LINUX_ENODEV; + if (scope && !net_interface_exists(s->net_ns, scope)) return -LINUX_ENODEV; if (scope && s->bound_ifindex && scope != s->bound_ifindex) return -LINUX_EINVAL; bool mapped = tcp6_mapped(&address->sin6_addr); if (mapped && s->ipv6 && s->v6only) return -LINUX_EINVAL; uint32_t ip = mapped ? tcp6_unmap(&address->sin6_addr) : 0; if (mapped) { - struct reliefos_net_config config; - net_get_config(&config); - if (ip && !net_interface_for_ipv4(NULL, ip)) return -LINUX_EADDRNOTAVAIL; + if (ip && !net_interface_for_ipv4(s->net_ns, ip)) return -LINUX_EADDRNOTAVAIL; } else if (!tcp6_any(&address->sin6_addr)) { if (!s->ipv6) return -LINUX_EAFNOSUPPORT; if (address->sin6_addr.s6_addr[0] == 0xfe && (address->sin6_addr.s6_addr[1] & 0xc0) == 0x80 && !scope) return -LINUX_EINVAL; - struct net_ipv6_address entries[32]; uint32_t count = net_ipv6_addresses(NULL, entries, 32); bool found = false; + struct net_ipv6_address entries[32]; uint32_t count = net_ipv6_addresses(s->net_ns, entries, 32); bool found = false; for (uint32_t i = 0; i < count && i < 32; ++i) if (!__builtin_memcmp(&entries[i].address, &address->sin6_addr, sizeof(address->sin6_addr)) && !(entries[i].flags & (NET_IPV6_ADDR_TENTATIVE | NET_IPV6_ADDR_DADFAILED)) && @@ -1389,7 +1413,7 @@ int net_socket_bind6_fd(int32_t handle, const struct sockaddr_in6 *address) return ret; } -/** @brief Start or resume a native IPv6 stream handshake without retaining user memory. +/** @brief Start or resume an IPv6 handshake through the endpoint's creation network. * @param handle Internal socket. @param address Kernel-owned peer address. * @param nonblock OFD nonblocking setting. @return Zero, errno or blocked marker. */ int net_socket_connect6_fd(int32_t handle, const struct sockaddr_in6 *address, bool nonblock) @@ -1417,7 +1441,7 @@ int net_socket_connect6_fd(int32_t handle, const struct sockaddr_in6 *address, b return -LINUX_EINVAL; if (tcp6_mapped(&s->local6)) return -LINUX_ENETUNREACH; struct net_ipv6_path path; - int ret = net_ipv6_route(NULL, &address->sin6_addr, address->sin6_scope_id ? address->sin6_scope_id : s->bound_ifindex, &s->local6, &path); + int ret = net_ipv6_route(s->net_ns, &address->sin6_addr, address->sin6_scope_id ? address->sin6_scope_id : s->bound_ifindex, &s->local6, &path); if (ret < 0) return ret; if (!s->bound) { ret = tcp_bind_port(s, 0, 0); if (ret < 0) return ret; } s->ifindex = path.ifindex; s->local6 = path.source; s->remote6 = address->sin6_addr; s->remote_scope6 = address->sin6_scope_id; @@ -1510,14 +1534,16 @@ int net_socket_reuse(int32_t handle, bool set, int *value) } /** @brief Associate a validated ICMPv6 quote with its native TCP connection. + * @param ns Borrowed ingress network, NULL for the initial network. + * @param ifindex Ingress link or zero for no link filter. * @param source Original local address. @param destination Original peer address. * @param source_port Local port. @param destination_port Peer port. * @param error Positive errno. @param mtu Reported path MTU or zero. */ -void net_tcp6_error_on(uint32_t ifindex, const struct in6_addr *source,const struct in6_addr *destination, +void net_tcp6_error_on(struct net_namespace *ns, uint32_t ifindex, const struct in6_addr *source,const struct in6_addr *destination, uint16_t source_port,uint16_t destination_port,int error,uint32_t mtu) { for (struct net_socket *s = net_sockets; s; s = s->registry_next) { - if (!s->used || !s->ipv6 || s->mapped || s->local_port != source_port || s->remote_port != destination_port || + if (s->net_ns != ns || !s->used || !s->ipv6 || s->mapped || s->local_port != source_port || s->remote_port != destination_port || (ifindex && s->ifindex && s->ifindex != ifindex) || __builtin_memcmp(&s->local6, source, sizeof(*source)) || __builtin_memcmp(&s->remote6, destination, sizeof(*destination))) continue; @@ -1533,13 +1559,14 @@ void net_tcp6_error_on(uint32_t ifindex, const struct in6_addr *source,const str } /** @brief Emit each IPv6 TCP endpoint and actual queue sizes using stable identifiers. + * @param ns Borrowed network, NULL for the initial network. * @param stream Caller-owned proc text slice under execution ownership. */ -void net_tcp6_proc_emit(struct text_stream *stream) +void net_tcp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) { text_string(stream, " sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n"); uint32_t index = 0; for (struct net_socket *s = net_sockets; s; s = s->registry_next) { - if (!s->used || !s->ipv6 || !s->bound) continue; + if (s->net_ns != ns || !s->used || !s->ipv6 || !s->bound) continue; struct in6_addr local = s->mapped ? tcp6_map(s->local_ip) : s->local6; struct in6_addr remote = s->mapped ? tcp6_map(s->remote_ip) : s->remote6; text_unsigned(stream,index++); text_string(stream, ": "); @@ -1605,7 +1632,7 @@ int net_socket_nodelay(int32_t handle, bool set, int *value) return 0; } -/** @brief Create a queued native IPv6 child and send its SYN/ACK. +/** @brief Retain a listener's creation network in an IPv6 child and send SYN/ACK. * @param listener Listening socket. @param source Peer address. @param destination Local address. * @param source_port Peer port. @param ifindex Interface. @param seq Peer sequence. * @param window Peer window. @param mss Advertised peer MSS or zero. @@ -1617,8 +1644,8 @@ struct net_socket *net_tcp_passive6(struct net_socket *listener,const struct in6 if (!listener || listener->state != NET_TCP_LISTEN || tcp_pending(listener, false) >= listener->backlog) return NULL; struct net_ipv6_path path; uint32_t scope = source->s6_addr[0] == 0xfe && (source->s6_addr[1] & 0xc0) == 0x80 ? ifindex : 0; - if (net_ipv6_route(NULL, source, scope, destination, &path) < 0) return NULL; - struct net_socket *s = net_socket_alloc(listener->owner_pid, listener->owner_uid); + if (net_ipv6_route(listener->net_ns, source, scope, destination, &path) < 0) return NULL; + struct net_socket *s = net_socket_alloc(listener->net_ns, listener->owner_pid, listener->owner_uid); if (!s) return NULL; s->ifindex = ifindex; s->bound_ifindex = listener->bound_ifindex; s->ipv6 = true; s->v6only = listener->v6only; s->bound = true; s->listener = listener; @@ -1637,7 +1664,8 @@ struct net_socket *net_tcp_passive6(struct net_socket *listener,const struct in6 return s; } -/** @brief Create a queued IPv4 or IPv4-mapped child from an incoming SYN. +/** @brief Create an IPv4 or mapped SYN child retaining its listener's network. + * @param ifindex Ingress interface within the listener's network. * @param listener Listening socket. @param source Peer IPv4 host order. * @param destination Local IPv4 host order. @param source_port Peer port. * @param source_mac Borrowed next-hop MAC, null for loopback. @param seq Peer sequence. @@ -1647,8 +1675,8 @@ struct net_socket *net_tcp_passive4_on(uint32_t ifindex, struct net_socket *list uint32_t seq,uint16_t window,uint16_t mss) { if (!listener || listener->state != NET_TCP_LISTEN || tcp_pending(listener, false) >= listener->backlog) return NULL; - if (!source_mac && !net_interface_for_ipv4(NULL, source)) return NULL; - struct net_socket *s = net_socket_alloc(listener->owner_pid, listener->owner_uid); + if (!source_mac && !net_interface_for_ipv4(listener->net_ns, source)) return NULL; + struct net_socket *s = net_socket_alloc(listener->net_ns, listener->owner_pid, listener->owner_uid); if (!s) return NULL; s->ifindex = ifindex; s->bound_ifindex = listener->bound_ifindex; s->ipv6 = listener->ipv6; s->mapped = listener->ipv6; s->v6only = listener->v6only; @@ -1873,7 +1901,7 @@ struct net_socket *net_tcp_passive4(struct net_socket *listener, uint32_t source uint32_t destination, uint16_t source_port, const uint8_t *source_mac, uint32_t seq, uint16_t window, uint16_t mss) { - uint32_t index = source_mac ? net_interface_for_ipv4(NULL, destination) : 1; + uint32_t index = source_mac ? net_interface_for_ipv4(listener ? listener->net_ns : NULL, destination) : 1; return net_tcp_passive4_on(index, listener, source, destination, source_port, source_mac, seq, window, mss); } @@ -1883,7 +1911,7 @@ struct net_socket *net_tcp_passive4(struct net_socket *listener, uint32_t source void net_tcp6_error(const struct in6_addr *source, const struct in6_addr *destination, uint16_t source_port, uint16_t destination_port, int error, uint32_t mtu) { - net_tcp6_error_on(0, source, destination, source_port, destination_port, error, mtu); + net_tcp6_error_on(NULL, 0, source, destination, source_port, destination_port, error, mtu); } /** @brief Read or change a stream endpoint's bound output device. * @param handle Socket handle. @param set Select update. @param index Input/output index. @@ -1894,7 +1922,7 @@ int net_socket_bound_device(int32_t handle, bool set, uint32_t *index) if (!socket) return -LINUX_EBADF; if (!index) return -LINUX_EINVAL; if (set) { - if (*index && !net_interface_exists(NULL, *index)) return -LINUX_ENODEV; + if (*index && !net_interface_exists(socket->net_ns, *index)) return -LINUX_ENODEV; socket->bound_ifindex = *index; } else *index = socket->bound_ifindex; return 0; diff --git a/tools/test_ipv6_transport.py b/tools/test_ipv6_transport.py index e388ee5a..f3b6f5da 100644 --- a/tools/test_ipv6_transport.py +++ b/tools/test_ipv6_transport.py @@ -30,5 +30,7 @@ "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", "tools/tests/ipv6_tcp_test.c", "net/tcp/input.c", "net/tcp/output.c", - "net/tcp/socket.c", "net/utility.c", "-o", str(binary)], cwd=root, check=True) + "net/tcp/socket.c", "net/utility.c", "net/proc.c", "net/socket/packet.c", + "net/namespace/namespace.c", + "net/ipv6/state.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) diff --git a/tools/test_network.py b/tools/test_network.py index 4557aa04..3fe4eb1c 100644 --- a/tools/test_network.py +++ b/tools/test_network.py @@ -12,8 +12,8 @@ "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", f"tools/tests/{name}_test.c", - *(["net/proc.c", "net/namespace/namespace.c", "net/ipv6/state.c"] - if name == "udp_socket" else []), + *(["net/proc.c"] if name == "udp_socket" else []), + "net/namespace/namespace.c", "net/ipv6/state.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/initial.c", "kernel/syscall/ipc/unix_name.c", "kernel/syscall/fs/lookup_state.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=20) diff --git a/tools/tests/ipv6_tcp_test.c b/tools/tests/ipv6_tcp_test.c index c74bf68a..7ba4f3a5 100644 --- a/tools/tests/ipv6_tcp_test.c +++ b/tools/tests/ipv6_tcp_test.c @@ -4,6 +4,9 @@ #include #include #include "../../net/internal.h" +#include +#include +#include struct net_socket *net_sockets; static struct reliefos_net_config fixture_config; @@ -13,12 +16,18 @@ uint16_t net_ipv4_id; static struct task current; static uint64_t now = 1000; static const struct in6_addr loop6 = {.s6_addr = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; -struct queued { struct net_ipv6_path path; uint32_t length; uint8_t data[1500]; }; +struct queued { struct net_namespace *ns; struct net_ipv6_path path; uint32_t length; uint8_t data[1500]; }; static struct queued queue[32]; static unsigned head, tail; -void *kernel_malloc(size_t n) { return calloc(1, n); } -void kernel_free(void *p) { free(p); } +static unsigned allocations; +void *kernel_malloc(size_t n) +{ + void *p = calloc(1, n); + if (p) ++allocations; + return p; +} +void kernel_free(void *p) { if (p) { assert(allocations); --allocations; free(p); } } struct task *sched_current_task(void) { return ¤t; } uint64_t time_uptime_ms(void) { return now; } uint64_t time_ticks(void) { return now; } @@ -32,15 +41,19 @@ void console_log(enum console_log_level level, const char *format, ...) { (void) int net_get_config(struct reliefos_net_config *out) { *out = net_config; return 0; } struct reliefos_net_config *net_interface_legacy_config(void) { return &fixture_config; } bool *net_interface_legacy_up(void) { return &fixture_interface_up; } -bool net_interface_exists(struct net_namespace *ns, uint32_t index) { return index==1; } -bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return index==1; } -uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip) { return (ip>>24)==127?1:0; } +bool net_interface_exists(struct net_namespace *ns, uint32_t index) +{ (void)ns; return index == NET_IF_LOOPBACK; } +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) +{ return net_interface_exists(ns, index) && (!ns || ns->loopback.up); } +uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip) { return (ip >> 24) == 127 && (!ns || ns->loopback.config.local_ip) ? 1 : 0; } uint32_t netdev_next(uint32_t after) { (void)after;return 0; } int netdev_send(uint32_t index,const void *data,uint32_t length) { (void)index;(void)data;(void)length;return -LINUX_ENETDOWN; } int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination,uint32_t source,uint32_t scope,struct net_ipv4_path *out) { - if((destination>>24)!=127 || (scope && scope!=1))return -LINUX_ENETUNREACH; + if ((destination >> 24) != 127 || (scope && scope != 1) || + (source && (source >> 24) != 127)) return -LINUX_ENETUNREACH; + if (!net_interface_is_ready(ns, 1)) return -LINUX_ENETDOWN; *out=(struct net_ipv4_path){.source=source?source:0x7f000001u,.destination=destination, .next_hop=destination,.ifindex=1}; return 0; @@ -59,11 +72,11 @@ void net_write_eth(uint8_t *frame, const uint8_t *mac, uint16_t type) void net_write_eth_on(uint32_t index,uint8_t *frame,const uint8_t *mac,uint16_t type) { (void)index;net_write_eth(frame,mac,type); } uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out,uint32_t cap) -{ (void)ns; if (cap) out[0] = (struct net_ipv6_address){.address=loop6,.ifindex=1}; return 1; } +{ if (ns && !ns->loopback.config.local_ip) return 0; if (cap) out[0] = (struct net_ipv6_address){.address=loop6,.ifindex=1}; return 1; } int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination,uint32_t scope, const struct in6_addr *bound,struct net_ipv6_path *path) { - (void)ns; + if (!net_interface_is_ready(ns, 1)) return -LINUX_ENETDOWN; static const struct in6_addr zero = {0}; if (memcmp(destination,&loop6,16) || (scope && scope != 1)) return -LINUX_ENETUNREACH; *path = (struct net_ipv6_path){.source=memcmp(bound,&zero,16) ? *bound : loop6, @@ -82,12 +95,12 @@ uint16_t net_ipv6_checksum(const struct in6_addr *source,const struct in6_addr * int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,uint8_t protocol,const void *data, uint32_t length,int hops,uint32_t flowinfo,bool df,bool multicast_loop) { - (void)ns; + if (!net_interface_is_ready(ns, path->ifindex)) return -LINUX_ENETDOWN; (void)hops; (void)flowinfo; (void)df; (void)multicast_loop; assert(protocol == 6 && length <= sizeof(queue[0].data)); assert(!net_ipv6_checksum(&path->source,&path->destination,protocol,data,length)); assert(tail - head < 32); - struct queued *q = &queue[tail++ % 32]; q->path = *path; q->length = length; + struct queued *q = &queue[tail++ % 32]; q->ns = net_namespace_get(ns); q->path = *path; q->length = length; memcpy(q->data,data,length); return (int)length; } @@ -96,7 +109,9 @@ void net_poll_packets(void) net_tcp_service_sockets(); while (head < tail) { struct queued q = queue[head++ % 32]; - net_tcp6_input(NULL, &q.path.source,&q.path.destination,q.data,q.length,q.path.ifindex); + if (net_interface_is_ready(q.ns, q.path.ifindex)) + net_tcp6_input(q.ns, &q.path.source,&q.path.destination,q.data,q.length,q.path.ifindex); + net_namespace_put(q.ns); assert(head <= tail && tail - head < 32); } } @@ -146,6 +161,157 @@ static void test_bind_scope(void) assert(!net_socket_bind6_fd(listener,&address)); } +/* Exercise real release and GC, including endpoint-owned namespace references. */ +static void cleanup_tcp(void) +{ + net_poll_packets(); + for (struct net_socket *s = net_sockets; s;) { + struct net_socket *next = s->registry_next; + net_socket_mark_closed(s, RELIEFOS_NET_STATUS_SOCKET_CLOSED); + net_socket_release_fd(s->handle); + s = next; + } + now += NET_SOCKET_CLOSE_HOLD_MS + 1; + struct reliefos_net_connection_list snapshot = {0}; + assert(!net_connections(&snapshot, ¤t)); + assert(!net_sockets); +} + +static void assert_tcp6_proc(struct net_namespace *ns, int present, int absent) +{ + current.net_ns = ns; + char text[4096] = {0}, identity[64]; + struct text_stream stream = {.buffer = text, .capacity = sizeof(text) - 1}; + assert(!net_proc_emit(&stream, "tcp6")); + snprintf(identity, sizeof(identity), " %llu\n", + (unsigned long long)((2ULL << 60) | (uint32_t)present)); + assert(strstr(text, identity)); + snprintf(identity, sizeof(identity), " %llu\n", + (unsigned long long)((2ULL << 60) | (uint32_t)absent)); + assert(!strstr(text, identity)); +} + +/* Losing scope in native input, mapped dispatch or accept inheritance makes + * identical tuples collide or deliver a payload to the other namespace. */ +static void test_tcp6_creating_network(bool mapped) +{ + struct net_namespace *spaces[2]; + int listeners[2], clients[2], children[2]; + struct sockaddr_in6 server = {.sin6_family = AF_INET6, + .sin6_port = __builtin_bswap16(55200), .sin6_addr = loop6}; + if (mapped) server.sin6_addr = (struct in6_addr){ + .s6_addr = {0,0,0,0,0,0,0,0,0,0,255,255,127,0,0,1}}; + struct sockaddr_in6 local = server; + local.sin6_port = __builtin_bswap16(55201); + for (unsigned i = 0; i < 2; ++i) { + assert(!net_namespace_create(NULL, &spaces[i])); + current.net_ns = spaces[i]; + int down = open6(); + unsigned queued_before = tail - head; + assert(net_socket_connect6_fd(down, &server, true) == -LINUX_ENETDOWN); + assert(tail - head == queued_before && !net_tcp_loop_pending()); + net_socket_release_fd(down); + assert(spaces[i]->references == 1); + spaces[i]->loopback.up = true; + spaces[i]->loopback.config.local_ip = 0x7f000001; + spaces[i]->loopback.config.subnet_mask = 0xff000000; + current.net_ns = spaces[i]; + listeners[i] = open6(); + clients[i] = open6(); + assert(!net_socket_bind6_fd(listeners[i], &server)); + assert(!net_socket_listen_fd(listeners[i], 2)); + assert(!net_socket_bind6_fd(clients[i], &local)); + uint32_t physical = 2; + assert(net_socket_bound_device(clients[i], true, &physical) == -LINUX_ENODEV); + } + current.net_ns = NULL; + for (unsigned i = 0; i < 2; ++i) + assert(net_socket_connect6_fd(clients[i], &server, true) == -LINUX_EINPROGRESS); + net_poll_packets(); + for (unsigned i = 0; i < 2; ++i) { + children[i] = net_socket_accept_peek(listeners[i]); + assert(children[i] > 0 && !net_socket_accept_commit(listeners[i], children[i])); + assert(net_socket_namespace(children[i]) == spaces[i]); + assert(spaces[i]->references == 4); + } + for (unsigned i = 0; i < 2; ++i) { + current.net_ns = spaces[1 - i]; + char payload = (char)('A' + i), data = 0; + struct reliefos_net_socket_io io = {.socket = clients[i], .buffer = &payload, .length = 1}; + assert(!net_socket_send(&io, 0) && io.transferred == 1); + net_poll_packets(); + assert(net_socket_available(children[1 - i]) == 0); + io = (struct reliefos_net_socket_io){.socket = children[i], .buffer = &data, .length = 1}; + assert(!net_socket_recv(&io, 0) && io.transferred == 1 && data == payload); + net_poll_packets(); + assert_tcp6_proc(spaces[i], children[i], children[1 - i]); + } + if (!mapped) { + uint8_t quote[48] = {0x60}; + quote[6] = IPV4_PROTO_TCP; + memcpy(quote + 8, &loop6, 16); + memcpy(quote + 24, &loop6, 16); + net_put_u16(quote + 40, 55201); + net_put_u16(quote + 42, 55200); + net_ipv6_socket_error_on(NULL, 1, quote, sizeof(quote), LINUX_EHOSTUNREACH, 0); + assert(!net_socket_error(clients[0], false) && !net_socket_error(clients[1], false)); + net_ipv6_socket_error_on(spaces[0], 1, quote, sizeof(quote), LINUX_EHOSTUNREACH, 0); + assert(net_socket_error(clients[0], true) == LINUX_EHOSTUNREACH); + assert(!net_socket_error(clients[1], false)); + net_ipv6_socket_error_on(spaces[1], 1, quote, sizeof(quote), LINUX_EMSGSIZE, 1280); + assert(!net_socket_error(clients[0], false) && !net_socket_error(clients[1], false)); + } + current.net_ns = NULL; + cleanup_tcp(); + for (unsigned i = 0; i < 2; ++i) { + assert(spaces[i]->references == 1); + net_namespace_put(spaces[i]); + } + assert(!allocations); + printf("PASS TCP %s creating-net same tuple, deferred handshake, accept, data, proc and error isolation\n", + mapped ? "mapped" : "native IPv6"); +} + +static void test_tcp6_owner_capability(bool mapped) +{ + struct task saved = current; + struct user_namespace *owner, *sibling; + assert(!user_namespace_create(¤t, &owner)); + assert(!user_namespace_create(¤t, &sibling)); + struct net_namespace *ns; + assert(!net_namespace_create(owner, &ns)); + ns->loopback.up = true; + ns->loopback.config.local_ip = 0x7f000001; + ns->loopback.config.subnet_mask = 0xff000000; + current.net_ns = ns; + current.user_ns = owner; + current.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; + int allowed = open6(), denied = open6(); + current.net_ns = NULL; + int initial = open6(); + struct sockaddr_in6 address = {.sin6_family = AF_INET6, + .sin6_port = __builtin_bswap16(100), .sin6_addr = loop6}; + if (mapped) address.sin6_addr = (struct in6_addr){ + .s6_addr = {0,0,0,0,0,0,0,0,0,0,255,255,127,0,0,1}}; + assert(!net_socket_bind6_fd(allowed, &address)); + assert(net_socket_bind6_fd(initial, &address) == -LINUX_EACCES); + address.sin6_port = __builtin_bswap16(101); + current.user_ns = sibling; + assert(net_socket_bind6_fd(denied, &address) == -LINUX_EACCES); + current.user_ns = owner; + current.cap_effective = 0; + assert(net_socket_bind6_fd(denied, &address) == -LINUX_EACCES); + cleanup_tcp(); + assert(ns->references == 1); + net_namespace_put(ns); + assert(owner->references == 1 && sibling->references == 1); + current = saved; + user_namespace_put(owner); + user_namespace_put(sibling); + assert(!allocations); + printf("PASS TCP %s owner CAP_NET_BIND_SERVICE after task movement\n", mapped ? "mapped" : "native IPv6"); +} + int main(void) { current.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; @@ -200,8 +366,36 @@ int main(void) assert(net_socket_connect_fd(v4request.socket,0x7f000001,55012,true) == -LINUX_EINPROGRESS); net_poll_packets(); assert(net_socket_error(v4request.socket,true) == LINUX_ECONNREFUSED); - while (net_sockets) { struct net_socket *s=net_sockets; net_sockets=s->registry_next; free(s->rx); free(s->tx); free(s); } + cleanup_tcp(); + test_tcp6_creating_network(false); + test_tcp6_creating_network(true); + test_tcp6_owner_capability(false); + test_tcp6_owner_capability(true); + assert(!allocations); puts("PASS IPv6 and IPv4-mapped TCP deferred loopback handshake, accept, payload and FIN"); } -bool net_interface_is_up(struct net_namespace *ns, uint32_t index) { return net_interface_is_ready(NULL, index); } +bool net_interface_is_up(struct net_namespace *ns, uint32_t index) { return net_interface_is_ready(ns, index); } + +/* Unrelated proc providers stay at the boundary of this TCP-only fixture. */ +uint32_t net_ipv6_routes(struct net_namespace *ns, struct net_ipv6_route *out, uint32_t cap) +{ (void)ns; (void)out; (void)cap; return 0; } +uint32_t net_ipv4_routes(struct net_namespace *ns, struct net_ipv4_route *out, uint32_t cap) +{ (void)ns; (void)out; (void)cap; return 0; } +uint32_t net_interface_next(struct net_namespace *ns, uint32_t after) +{ (void)ns; return after < 1 ? 1 : 0; } +bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[16]) +{ if (!net_interface_exists(ns, index)) return false; strcpy(out, "lo"); return true; } +void net_udp_proc_emit(struct net_namespace *ns, struct text_stream *s) { (void)ns; (void)s; abort(); } +void net_udp6_proc_emit(struct net_namespace *ns, struct text_stream *s) { (void)ns; (void)s; abort(); } +void net_loopback_proc_emit(struct net_namespace *ns, struct text_stream *s) { (void)ns; (void)s; abort(); } +void net_device_counters(struct net_proc_counters *out) { (void)out; abort(); } +void net_arp_proc_emit(struct text_stream *s) { (void)s; abort(); } +void unix_proc_emit(struct text_stream *s) { (void)s; abort(); } +void net_udp6_error_on(struct net_namespace *ns, uint32_t index, + const struct in6_addr *src, const struct in6_addr *dst, + uint16_t sport, uint16_t dport, int error, uint32_t mtu) +{ (void)ns; (void)index; (void)src; (void)dst; (void)sport; (void)dport; (void)error; (void)mtu; abort(); } + +void netdev_counters(uint32_t index, struct net_proc_counters *out) +{ (void)index; *out = (struct net_proc_counters){0}; } diff --git a/tools/tests/ipv6_transport_test.c b/tools/tests/ipv6_transport_test.c index 89c765a1..8f9aea46 100644 --- a/tools/tests/ipv6_transport_test.c +++ b/tools/tests/ipv6_transport_test.c @@ -10,11 +10,11 @@ #include void kernel_poll_readiness_notify(void) {} -void net_tcp6_proc_emit(struct text_stream *stream) { (void)stream; } -void net_tcp6_error_on(uint32_t index, const struct in6_addr *source, +void net_tcp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) { (void)ns; (void)stream; } +void net_tcp6_error_on(struct net_namespace *ns, uint32_t index, const struct in6_addr *source, const struct in6_addr *destination, uint16_t source_port, uint16_t destination_port, int error, uint32_t mtu) -{ (void)index; (void)source; (void)destination; (void)source_port; +{ (void)ns; (void)index; (void)source; (void)destination; (void)source_port; (void)destination_port; (void)error; (void)mtu; abort(); } static const struct in6_addr loop6 = {.s6_addr = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out, uint32_t capacity) diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index f4ef8a7c..37ea14d6 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -4527,6 +4527,8 @@ "-Iinclude", "-Iinclude/uapi", "tools/tests/task8_inet_tcp_probe_test.c", + "net/namespace/namespace.c", + "net/ipv6/state.c", "tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c", "kernel/sched/user_namespace.c", "-o", diff --git a/tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c b/tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c index b14a40a6..60656db2 100644 --- a/tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c +++ b/tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c @@ -11,8 +11,6 @@ __attribute__((noreturn)) void device_user_page_get(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void device_user_page_put(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ -__attribute__((noreturn)) void e1000_is_ready(void) { __builtin_trap(); } -/** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void kernel_object_insert(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void kernel_object_lookup(void) { __builtin_trap(); } @@ -59,8 +57,6 @@ __attribute__((noreturn)) void syscall_udp(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void syscall_unix_address(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ -__attribute__((noreturn)) void task_allocate_fd(void) { __builtin_trap(); } -/** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void task_descriptor_for_fd(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void task_file_for_fd(void) { __builtin_trap(); } @@ -88,3 +84,14 @@ __attribute__((noreturn)) void vfs_path_put(void) { __builtin_trap(); } __attribute__((noreturn)) void vfs_path_same_inode(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void vfs_system_namespace(void) { __builtin_trap(); } + +/* Unrelated branches retained by the real socket-creation rollback probe. */ +__attribute__((noreturn)) void time_clock_get(void) { __builtin_trap(); } +__attribute__((noreturn)) void task_netlink_passcred(void) { __builtin_trap(); } +__attribute__((noreturn)) void task_netlink_pktinfo(void) { __builtin_trap(); } +__attribute__((noreturn)) void task_udp_address_size(void) { __builtin_trap(); } +__attribute__((noreturn)) void task_netlink_recv_staged(void) { __builtin_trap(); } +__attribute__((noreturn)) void task_packet_recv_ex(void) { __builtin_trap(); } +__attribute__((noreturn)) void task_udp_recv_ex(void) { __builtin_trap(); } +__attribute__((noreturn)) void task_netlink_cancel_wait(void) { __builtin_trap(); } +__attribute__((noreturn)) void syscall_netlink(void) { __builtin_trap(); } diff --git a/tools/tests/task8_inet_tcp_probe_test.c b/tools/tests/task8_inet_tcp_probe_test.c index bad3d0be..55acd729 100644 --- a/tools/tests/task8_inet_tcp_probe_test.c +++ b/tools/tests/task8_inet_tcp_probe_test.c @@ -23,10 +23,42 @@ int task_udp_recv_staged(struct task_file *file,void *data,uint32_t length,uint3 int task_packet_recv_staged(struct task_file *file,void *data,uint32_t length,uint32_t flags,void *source,uint32_t *source_length) { (void)file;(void)data;(void)length;(void)flags;(void)source;(void)source_length;abort(); } +/* Drive the actual socket syscall rollback after endpoint creation. */ +int task_allocate_fd(struct task *task, int minimum, struct task_file **out) +{ + assert(task == ¤t_task && minimum == 0); + (void)out; + return -LINUX_EMFILE; +} + +static void test_tcp_fd_creation_rollback(void) +{ + struct net_namespace *ns; + assert(!net_namespace_create(NULL, &ns)); + current_task.net_ns = ns; + int baseline = buffers; + for (unsigned i = 0; i < 2; ++i) { + int family = i ? AF_INET6 : AF_INET; + assert(syscall_socket_dispatch(__NR_socket, family, SOCK_STREAM, 0, 0, 0, 0) == -LINUX_EMFILE); + assert(buffers == baseline && !net_sockets && ns->references == 1); + for (int failure = 0; failure < 3; ++failure) { + allocation_fail_after = failure; + assert(syscall_socket_dispatch(__NR_socket, family, SOCK_STREAM, 0, 0, 0, 0) == -LINUX_ENOMEM); + allocation_fail_after = -1; + assert(buffers == baseline && !net_sockets && ns->references == 1); + } + } + current_task.net_ns = NULL; + net_namespace_put(ns); + assert(!buffers); + puts("PASS TCP IPv4/IPv6 syscall ENOMEM and EMFILE immediately restore references, buffers and registry"); +} + int main(void) { current_task.kind=TASK_KIND_USER;current_task.pid=7; - struct net_socket *socket=net_socket_alloc(7,1000);assert(socket); + test_tcp_fd_creation_rollback(); + struct net_socket *socket=net_socket_alloc(NULL, 7,1000);assert(socket); socket->state=RELIEFOS_NET_TCP_ESTABLISHED; struct task_file *file=&tcp_file; *file=(struct task_file){.flags=TASK_FILE_FLAG_SOCKET|TASK_FILE_FLAG_SOCKET_INET|RELIEFOS_O_NONBLOCK, diff --git a/tools/tests/tcp_state_test.c b/tools/tests/tcp_state_test.c index 576c002a..45ac3b6d 100644 --- a/tools/tests/tcp_state_test.c +++ b/tools/tests/tcp_state_test.c @@ -3,6 +3,7 @@ #include #include #include +#include #include "modules/network.h" #include "../../kernel/syscall/ipc/socket.c" #include "../../net/proc.c" @@ -41,7 +42,9 @@ static uint32_t sent_length; static uint32_t sent_count; static int send_error; static bool arp_reply_pending; +static bool fixture_nic_ready = true; static int allocation_failure; +static int allocation_fail_after = -1; static int buffers; static bool advance_poll_clock; static struct task current_task; @@ -52,12 +55,15 @@ static unsigned sleep_deadlines; static unsigned network_poll_count; void *kernel_malloc(size_t size) { + if (allocation_fail_after == 0) return NULL; + if (allocation_fail_after > 0) --allocation_fail_after; void *p = allocation_failure ? NULL : malloc(size); if (p) ++buffers; return p; } void kernel_free(void *p) { if (p) { --buffers; free(p); } } uint64_t time_uptime_ms(void) { return now_ms; } +int e1000_is_ready(void) { return fixture_nic_ready; } const uint8_t *e1000_mac(void) { static const uint8_t mac[6] = {2, 3, 4, 5, 6, 7}; return mac; } void e1000_get_info(struct e1000_info *info) { *info = (struct e1000_info){.present=1, .active=1}; } int e1000_send(const void *data, uint32_t length) @@ -282,7 +288,7 @@ static void test_window_edges(struct net_socket *s) static void test_nonblocking_tcp_send_without_ack(void) { - struct net_socket *socket = net_socket_alloc(7, 1000); + struct net_socket *socket = net_socket_alloc(NULL, 7, 1000); struct task_file file = {0}; uint8_t payload[70000]; unsigned sent_before; @@ -381,7 +387,7 @@ static void test_nonblocking_tcp_send_without_ack(void) static void test_tcp_peer_window_and_persist(void) { - struct net_socket *socket = net_socket_alloc(8, 1000); + struct net_socket *socket = net_socket_alloc(NULL, 8, 1000); struct reliefos_net_socket_io request = {0}; uint8_t payload[5000]; unsigned before; @@ -421,7 +427,7 @@ static void test_tcp_peer_window_and_persist(void) assert(socket->peer_window == 0 && socket->tx_sent == 1900); net_socket_clear(socket); - socket = net_socket_alloc(8, 1000); + socket = net_socket_alloc(NULL, 8, 1000); assert(socket); assert(!net_socket_nodelay(socket->handle, true, &nodelay)); socket->state = RELIEFOS_NET_TCP_ESTABLISHED; @@ -485,7 +491,7 @@ static void test_tcp_peer_window_and_persist(void) */ static void test_tcp_nodelay(void) { - struct net_socket *socket = net_socket_alloc(36, 1000); + struct net_socket *socket = net_socket_alloc(NULL, 36, 1000); assert(socket); socket->state = RELIEFOS_NET_TCP_ESTABLISHED; socket->local_ip = 0x0a25000f; socket->remote_ip = 0x0a250002; @@ -554,7 +560,7 @@ static void test_tcp_nodelay(void) static void test_tcp_timeouts_and_read_errors(void) { - struct net_socket *socket = net_socket_alloc(9, 1000); + struct net_socket *socket = net_socket_alloc(NULL, 9, 1000); struct task_file file = {0}; struct linux_timeval timeout = {.tv_sec = 0, .tv_usec = 25000}; struct linux_timeval observed = {0}; @@ -630,7 +636,7 @@ static void test_tcp_timeouts_and_read_errors(void) static void test_negative_socket_timeout_seconds_clamp_to_immediate(void) { - struct net_socket *inet = net_socket_alloc(35, 1000); + struct net_socket *inet = net_socket_alloc(NULL, 35, 1000); struct kernel_wait_queue unix_wait = {0}; struct task_file unix_file = {0}; struct unix_socket unix = { @@ -722,7 +728,7 @@ static void test_socket_registry_growth_and_legacy_snapshot(void) }; struct task viewer = {.role = RELIEFOS_AUTH_ROLE_ADMIN}; for (unsigned i = 0; i < 24; ++i) { - sockets[i] = net_socket_alloc(100u + i, 1000u); + sockets[i] = net_socket_alloc(NULL, 100u + i, 1000u); assert(sockets[i]); for (unsigned j = 0; j < i; ++j) { assert(sockets[i] != sockets[j]); @@ -745,7 +751,7 @@ static void test_tcp_release_then_owner_exit_drains_queued_bytes(void) { const uint32_t owner_pid = 27; uint8_t payload[NET_TCP_MSS * 4u + 37u]; - struct net_socket *socket = net_socket_alloc(owner_pid, 1000); + struct net_socket *socket = net_socket_alloc(NULL, owner_pid, 1000); struct task_file file = {0}; struct reliefos_net_socket_io request = {0}; uint32_t initial_seq = 71000; @@ -827,7 +833,7 @@ static void test_tcp_release_then_owner_exit_drains_queued_bytes(void) static void test_tcp_fin_retransmit_ack_and_half_close(void) { - struct net_socket *socket = net_socket_alloc(31, 1000); + struct net_socket *socket = net_socket_alloc(NULL, 31, 1000); struct reliefos_net_socket_io request = {0}; uint8_t received[8] = {0}; uint8_t peer_data[] = {0x41, 0x42, 0x43}; @@ -926,7 +932,7 @@ static void test_tcp_fin_retransmit_ack_and_half_close(void) static void test_tcp_peer_half_close_allows_reply(void) { - struct net_socket *socket = net_socket_alloc(34, 1000); + struct net_socket *socket = net_socket_alloc(NULL, 34, 1000); struct reliefos_net_socket_io request = {0}; uint8_t reply[] = {0x51, 0x52, 0x53, 0x54}; uint8_t received = 0; @@ -1008,7 +1014,7 @@ static void test_tcp_peer_half_close_allows_reply(void) static void test_tcp_unacknowledged_fin_is_not_reclaimed(void) { - struct net_socket *socket = net_socket_alloc(32, 1000); + struct net_socket *socket = net_socket_alloc(NULL, 32, 1000); int32_t handle; assert(socket); socket->state = RELIEFOS_NET_TCP_ESTABLISHED; @@ -1044,7 +1050,7 @@ static void test_tcp_unacknowledged_fin_is_not_reclaimed(void) static void test_tcp_out_of_window_segment_cannot_ack_data(void) { - struct net_socket *socket = net_socket_alloc(33, 1000); + struct net_socket *socket = net_socket_alloc(NULL, 33, 1000); uint32_t original_seq; uint32_t original_ack; uint32_t original_window; @@ -1088,7 +1094,7 @@ static void test_tcp_route_gateway_change(void) net_config.gateway_ip = 0x0a250002; net_arp_store_on(2, 0x0a250002, first_mac); net_arp_store_on(2, 0x0a250003, second_mac); - struct net_socket *socket = net_socket_alloc(7, 1000); + struct net_socket *socket = net_socket_alloc(NULL, 7, 1000); assert(socket); socket->local_ip = net_config.local_ip; socket->remote_ip = 0x08080808; @@ -1107,8 +1113,8 @@ static void test_tcp_route_gateway_change(void) static void test_tcp_bound_device_local_delivery(void) { - struct net_socket *listener = net_socket_alloc(7, 1000); - struct net_socket *client = net_socket_alloc(7, 1000); + struct net_socket *listener = net_socket_alloc(NULL, 7, 1000); + struct net_socket *client = net_socket_alloc(NULL, 7, 1000); assert(listener && client); uint32_t index = 2; assert(!net_socket_bound_device(listener->handle, true, &index)); @@ -1129,8 +1135,8 @@ static void test_tcp_bound_device_local_delivery(void) static void test_tcp_matching_and_scope_isolation(void) { - struct net_socket *first = net_socket_alloc(7, 1000); - struct net_socket *second = net_socket_alloc(7, 1000); + struct net_socket *first = net_socket_alloc(NULL, 7, 1000); + struct net_socket *second = net_socket_alloc(NULL, 7, 1000); assert(first && second); first->state = second->state = RELIEFOS_NET_TCP_ESTABLISHED; first->local_ip = second->local_ip = 0x0a25000f; @@ -1139,8 +1145,8 @@ static void test_tcp_matching_and_scope_isolation(void) first->remote_port = second->remote_port = 80; first->bound_ifindex = 2; second->bound_ifindex = 3; - assert(net_socket_match(2,0x0a250002,0x0a25000f,80,55052) == first); - assert(net_socket_match(3,0x0a250002,0x0a25000f,80,55052) == second); + assert(net_socket_match(NULL, 2,0x0a250002,0x0a25000f,80,55052) == first); + assert(net_socket_match(NULL, 3,0x0a250002,0x0a25000f,80,55052) == second); first->resolving_neighbor = true; unsigned before = sent_count; assert(net_send_tcp_socket(first,1,1,TCP_FLAG_ACK,NULL,0) == -LINUX_EAGAIN); @@ -1148,7 +1154,7 @@ static void test_tcp_matching_and_scope_isolation(void) assert(sent_count == before); net_socket_clear(second); net_socket_clear(first); - first = net_socket_alloc(7,1000); + first = net_socket_alloc(NULL, 7,1000); assert(first && !net_socket_set_ipv6(first->handle,true)); uint32_t index=2; assert(!net_socket_bound_device(first->handle,true,&index)); @@ -1158,12 +1164,242 @@ static void test_tcp_matching_and_scope_isolation(void) net_socket_clear(first); } + +/* Removing the creating scope from tuple lookup, deferred input or proc must + * break these exchanges even when both namespaces use identical four-tuples. */ +static void drain_tcp_loop(void) +{ + for (unsigned pass = 0; pass < 32 && net_tcp_loop_pending(); ++pass) + net_tcp_loop_service(); + assert(!net_tcp_loop_pending()); +} + +static struct net_socket *open_scoped_tcp(struct net_namespace *ns) +{ + current_task.net_ns = ns; + struct reliefos_net_socket_open request = { + .domain = RELIEFOS_NET_AF_INET, .type = RELIEFOS_NET_SOCK_STREAM}; + assert(!net_socket_open(&request, 7, 1000)); + assert(request.status == RELIEFOS_NET_STATUS_OK); + net_socket_pin_fd(request.socket); + assert(net_socket_namespace(request.socket) == ns); + return net_socket_find(request.socket, 0, 1); +} + +static void assert_tcp_proc_scope(struct net_namespace *ns, int present, int absent) +{ + current_task.net_ns = ns; + char text[4096] = {0}, identity[64]; + struct text_stream stream = {.buffer = text, .capacity = sizeof(text) - 1}; + assert(!net_proc_emit(&stream, "tcp")); + snprintf(identity, sizeof(identity), " %llu\n", + (unsigned long long)((2ULL << 60) | (uint32_t)present)); + assert(strstr(text, identity)); + snprintf(identity, sizeof(identity), " %llu\n", + (unsigned long long)((2ULL << 60) | (uint32_t)absent)); + assert(!strstr(text, identity)); +} + +static void test_tcp_creating_network(void) +{ + int baseline = buffers; + struct task saved = current_task; + struct net_namespace *spaces[2]; + struct net_socket *listeners[2], *clients[2], *children[2]; + for (unsigned i = 0; i < 2; ++i) { + assert(!net_namespace_create(NULL, &spaces[i])); + assert(!net_interface_set_up(spaces[i], NET_IF_LOOPBACK, true)); + listeners[i] = open_scoped_tcp(spaces[i]); + clients[i] = open_scoped_tcp(spaces[i]); + assert(!tcp_bind_port(listeners[i], 0x7f000001, 55100)); + assert(!net_socket_listen_fd(listeners[i]->handle, 2)); + assert(!tcp_bind_port(clients[i], 0x7f000001, 55101)); + uint32_t physical = 2; + assert(net_socket_bound_device(clients[i]->handle, true, &physical) == -LINUX_ENODEV); + } + current_task.net_ns = NULL; + for (unsigned i = 0; i < 2; ++i) { + uint64_t references = spaces[i]->references; + assert(net_socket_connect_fd(clients[i]->handle, 0x7f000001, 55100, true) == -LINUX_EINPROGRESS); + assert(spaces[i]->references == references + 1); /* Queued SYN retains scope. */ + } + drain_tcp_loop(); + for (unsigned i = 0; i < 2; ++i) { + assert(clients[i]->state == RELIEFOS_NET_TCP_ESTABLISHED); + int handle = net_socket_accept_peek(listeners[i]->handle); + assert(handle > 0 && !net_socket_accept_commit(listeners[i]->handle, handle)); + children[i] = net_socket_find(handle, 0, 1); + assert(net_socket_namespace(handle) == spaces[i]); + assert(spaces[i]->references == 4); /* Caller, listener, client and child. */ + } + for (unsigned i = 0; i < 2; ++i) { + current_task.net_ns = spaces[1 - i]; + struct task_file file = {.flags = TASK_FILE_FLAG_SOCKET_INET | RELIEFOS_O_NONBLOCK, + .aux = clients[i]->handle}; + const char *payload = i ? "second" : "first"; + assert(task_inet_write(&file, payload, 6) == 6); + net_tcp_service_sockets(); + drain_tcp_loop(); + assert(!children[1 - i]->rx_len); + file.aux = children[i]->handle; + char data[6]; + assert(task_inet_read(&file, data, sizeof(data)) == 6); + assert(!memcmp(data, payload, 6)); + drain_tcp_loop(); + assert_tcp_proc_scope(spaces[i], children[i]->handle, children[1 - i]->handle); + } + uint8_t packet[40] = {0x45}, source_mac[6] = {2,9,8,7,6,5}; + net_put_u32(packet + 12, 0x7f000001); + net_put_u32(packet + 16, 0x7f000001); + net_put_u16(packet + 20, 55100); + net_put_u16(packet + 22, 55101); + net_put_u32(packet + 24, clients[0]->remote_seq); + packet[32] = 0x50; + packet[33] = TCP_FLAG_RST; + net_put_u16(packet + 36, net_tcp_checksum(0x7f000001, 0x7f000001, packet + 20, 20)); + net_handle_tcp_on(NULL, 2, packet, sizeof(packet), 20, 0x7f000001, source_mac, NULL); + /* Driver detach is initial ingress ownership, even for an equal ifindex. */ + net_device_detached(NET_IF_LOOPBACK); + for (unsigned i = 0; i < 2; ++i) { + assert(clients[i]->state == RELIEFOS_NET_TCP_ESTABLISHED); + assert(!net_socket_error(clients[i]->handle, false)); + net_socket_clear(children[i]); + net_socket_clear(clients[i]); + net_socket_clear(listeners[i]); + assert(spaces[i]->references == 1); + net_namespace_put(spaces[i]); + } + current_task = saved; + assert(buffers == baseline); + puts("PASS TCP creating-net IPv4 bind, handshake, accept, OFD data, proc, detach and queue references"); +} + +/* A queued frame must keep its namespace alive after both endpoints disappear, + * and a down-loopback drop must release that last queue ownership. */ +static void test_tcp_loopback_queue_lifetime(void) +{ + int baseline = buffers; + struct task saved = current_task; + struct net_namespace *ns; + assert(!net_namespace_create(NULL, &ns)); + assert(!net_interface_set_up(ns, NET_IF_LOOPBACK, true)); + struct net_socket *listener = open_scoped_tcp(ns); + struct net_socket *client = open_scoped_tcp(ns); + assert(!tcp_bind_port(listener, 0x7f000001, 55102)); + assert(!net_socket_listen_fd(listener->handle, 1)); + assert(net_socket_connect_fd(client->handle, 0x7f000001, 55102, true) == -LINUX_EINPROGRESS); + assert(ns->references == 4); + for (unsigned i = 1; i < 32; ++i) + assert(net_send_tcp_socket(client, 1, 1, TCP_FLAG_ACK, NULL, 0) >= 0); + assert(ns->references == 35); + assert(net_send_tcp_socket(client, 1, 1, TCP_FLAG_ACK, NULL, 0) == -LINUX_ENOBUFS); + assert(ns->references == 35); + net_socket_clear(client); + net_socket_clear(listener); + assert(ns->references == 33); + assert(!net_interface_set_up(ns, NET_IF_LOOPBACK, false)); + net_namespace_put(ns); + current_task = saved; + drain_tcp_loop(); + assert(buffers == baseline && !net_sockets); + puts("PASS TCP queued scope survives endpoints and queue-full failure and down-lo drop balance references"); +} + +static void test_tcp_legacy_scoped_connect(void) +{ + int baseline = buffers; + struct task saved = current_task; + struct net_namespace *ns; + assert(!net_namespace_create(NULL, &ns)); + assert(!net_interface_set_up(ns, NET_IF_LOOPBACK, true)); + struct net_socket *listener = open_scoped_tcp(ns); + struct net_socket *client = open_scoped_tcp(ns); + struct net_socket *hostname = open_scoped_tcp(ns); + assert(!tcp_bind_port(listener, 0x7f000001, 55103)); + assert(!net_socket_listen_fd(listener->handle, 1)); + current_task.net_ns = NULL; + fixture_nic_ready = false; + unsigned sends = sent_count, polls = network_poll_count; + struct reliefos_net_socket_connect request = { + .socket = hostname->handle, .host = "namespace.invalid", .port = 80, .timeout_ms = 10}; + assert(!net_socket_connect(&request, 7)); + assert(request.status == RELIEFOS_NET_STATUS_NO_ADDRESS); + assert(net_socket_error(hostname->handle, true) == LINUX_ENETUNREACH); + assert(sent_count == sends && network_poll_count == polls); + request = (struct reliefos_net_socket_connect){ + .socket = client->handle, .host = "127.0.0.1", .port = 55103, .timeout_ms = 10}; + assert(!net_socket_connect(&request, 7)); + assert(request.status == RELIEFOS_NET_STATUS_OK); + assert(request.local_ip == 0x7f000001 && request.remote_ip == 0x7f000001); + assert(client->ifindex == NET_IF_LOOPBACK && sent_count == sends); + int child = net_socket_accept_peek(listener->handle); + assert(child > 0 && net_socket_namespace(child) == ns); + net_socket_clear(net_socket_find(child, 0, 1)); + net_socket_clear(client); + net_socket_clear(hostname); + net_socket_clear(listener); + drain_tcp_loop(); + assert(ns->references == 1); + fixture_nic_ready = true; + current_task = saved; + net_namespace_put(ns); + assert(buffers == baseline); + puts("PASS legacy TCP uses creating-net numeric routes and rejects hostname without global resolver/NIC setup"); +} + +static void test_tcp_namespace_failures_and_owner(void) +{ + int baseline = buffers; + struct task saved = current_task; + struct user_namespace *owner, *sibling; + assert(!user_namespace_create(¤t_task, &owner)); + assert(!user_namespace_create(¤t_task, &sibling)); + struct net_namespace *ns; + assert(!net_namespace_create(owner, &ns)); + assert(!net_interface_set_up(ns, NET_IF_LOOPBACK, true)); + int before_socket = buffers; + for (int fail = 0; fail < 3; ++fail) { + allocation_fail_after = fail; + assert(!net_socket_alloc(ns, 7, 1000)); + allocation_fail_after = -1; + assert(ns->references == 1 && buffers == before_socket && !net_sockets); + } + current_task.user_ns = owner; + current_task.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; + struct net_socket *allowed = open_scoped_tcp(ns); + struct net_socket *denied = open_scoped_tcp(ns); + struct net_socket *initial = open_scoped_tcp(NULL); + current_task.net_ns = NULL; + assert(!tcp_bind_port(allowed, 0x7f000001, 100)); + assert(tcp_bind_port(initial, 0, 100) == -LINUX_EACCES); + current_task.user_ns = sibling; + assert(tcp_bind_port(denied, 0x7f000001, 101) == -LINUX_EACCES); + current_task.user_ns = owner; + current_task.cap_effective = 0; + assert(tcp_bind_port(denied, 0x7f000001, 101) == -LINUX_EACCES); + int handle = denied->handle; + net_socket_release_fd(handle); + assert(!net_socket_find(handle, 0, 1)); + net_socket_release_fd(initial->handle); + net_socket_release_fd(allowed->handle); + assert(net_socket_find(allowed->handle, 0, 1)); /* Bound endpoint uses existing GC. */ + now_ms += NET_SOCKET_CLOSE_HOLD_MS + 1; + net_socket_gc(); + assert(!net_sockets && ns->references == 1 && buffers == before_socket); + net_namespace_put(ns); + current_task = saved; + user_namespace_put(owner); + user_namespace_put(sibling); + assert(buffers == baseline); + puts("PASS TCP owner CAP_NET_BIND_SERVICE, staged ENOMEM and release/GC references"); +} + int main(void) { static struct net_interface test_interface = {.index=2, .up=true, .config={.local_ip=0x0a25000f,.subnet_mask=0xffffff00,.gateway_ip=0x0a250002}}; interfaces = &test_interface; - struct net_socket *s = net_socket_alloc(7, 1000); + struct net_socket *s = net_socket_alloc(NULL, 7, 1000); bool interface_was_up = net_interface_up; assert(s); net_interface_up = true; @@ -1223,9 +1459,9 @@ int main(void) net_socket_gc(); assert(buffers == 0); allocation_failure = 1; - assert(net_socket_alloc(7, 1000) == NULL && buffers == 0); + assert(net_socket_alloc(NULL, 7, 1000) == NULL && buffers == 0); allocation_failure = 0; - s = net_socket_alloc(7, 1000); + s = net_socket_alloc(NULL, 7, 1000); assert(s && buffers == 3); net_socket_clear(s); assert(buffers == 0); @@ -1244,6 +1480,10 @@ int main(void) test_tcp_peer_half_close_allows_reply(); test_tcp_unacknowledged_fin_is_not_reclaimed(); test_tcp_out_of_window_segment_cannot_ack_data(); + test_tcp_creating_network(); + test_tcp_loopback_queue_lifetime(); + test_tcp_legacy_scoped_connect(); + test_tcp_namespace_failures_and_owner(); puts("[tcp-state] PASS socket lifetime, queued TCP, congestion/window flow, retransmit and partial ACK"); return 0; } @@ -1273,3 +1513,7 @@ void net_packet_input_on(uint32_t index, const void *frame, uint32_t length) int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index, bool up) { (void)ns; (void)index; (void)up; return 0; } void net_ipv6_detached_on(struct net_namespace *ns, uint32_t index) { (void)ns; (void)index; } void netlink_ipv6_changed(struct net_namespace *ns) { (void)ns; } + +void net_udp_device_detached(struct net_namespace *ns, uint32_t index) +{ assert(!ns); (void)index; } +void net_packet_device_detached(uint32_t index) { (void)index; } diff --git a/tools/tests/udp_socket_test.c b/tools/tests/udp_socket_test.c index 74fa34ce..791a9e29 100644 --- a/tools/tests/udp_socket_test.c +++ b/tools/tests/udp_socket_test.c @@ -51,6 +51,8 @@ int net_get_config(struct reliefos_net_config *config) { *config = (struct reliefos_net_config){.local_ip = 0x0a00020f}; return 0; } void net_poll_packets(void) {} #ifndef IPV6_TRANSPORT_FIXTURE +__attribute__((weak)) void net_tcp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) +{ (void)ns; (void)stream; abort(); } /* This legacy fixture exercises IPv4 only; IPv6 dependencies are supplied by * the dedicated IPv6 transport fixture with an actual deferred link model. */ __attribute__((weak)) void kernel_poll_readiness_notify(void) {} From 9f184894e79d095b882438d60035e7122d804123 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 06:25:50 +0800 Subject: [PATCH 76/97] feat(net): isolate raw and packet sockets by creating network namespace --- Documentation/core-api/mount-namespaces.rst | 8 +- Documentation/core-api/network-devices.rst | 5 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 15 +- .../LC_MESSAGES/core-api/network-devices.po | 13 +- .../en/LC_MESSAGES/userspace-api/ipv6.po | 11 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 15 +- .../LC_MESSAGES/core-api/network-devices.po | 12 +- .../ja/LC_MESSAGES/userspace-api/ipv6.po | 11 +- Documentation/userspace-api/ipv6.rst | 6 +- include/reliefnt/net.h | 4 +- include/reliefnt/net_ipv6.h | 7 +- include/reliefnt/net_packet.h | 14 +- kernel/syscall/device/legacy_ioctl.c | 2 +- net/input.c | 4 +- net/ipv4/core.c | 12 +- net/proc.c | 4 +- net/socket/control.c | 5 +- net/socket/packet.c | 116 ++++++++----- tools/test_net_multinic_data.py | 2 + tools/test_openrc_network.py | 2 + tools/tests/ipv6_control_test.c | 4 + tools/tests/ipv6_protocol_test.c | 4 +- tools/tests/ipv6_transport_test.c | 115 +++++++++++- tools/tests/net_packet_test.c | 163 ++++++++++++++++-- tools/tests/net_rx_budget_test.c | 4 +- tools/tests/task8_host_fixtures.json | 5 + .../fix1-packet-front-unreached.c | 16 +- .../task8_host_stubs/packet_tcp_unreached.c | 15 ++ tools/tests/task8_net_ioctl_user_test.c | 20 ++- tools/tests/task8_packet_user_test.c | 2 + tools/tests/tcp_state_test.c | 6 +- tools/tests/udp_socket_test.c | 2 + 32 files changed, 488 insertions(+), 136 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 32c47441..7a4d826b 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -158,15 +158,17 @@ hostname 和 domainname 的复制、读取及更新由短时 UTS 自旋锁保护 网络空间生命周期 ================ -``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink、UDP 和 TCP 套接字独立持有创建时的网络空间,服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。TCP 分配或新建 FD 安装失败释放候选对象及网络引用,已绑定或协议活跃的端点在关闭描述并完成协议回收后释放网络。 +``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink、UDP、TCP、raw 和 AF_PACKET 套接字独立持有创建时的网络空间,服务端连接继承监听端空间。UDP、raw 和 AF_PACKET 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。TCP 分配或新建 FD 安装失败释放候选对象及网络引用,已绑定或协议活跃的端点在关闭描述并完成协议回收后释放网络。 每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 ``127.0.0.1/8``、``::1/128`` 和 IPv6 host route。物理 NIC 注册和 ingress 仍归初始网络空间。最后一个空间引用释放接口列表、显式 IPv4 路由、IPv6 协议资源和 owner 引用。 -网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。raw transport 的网络隔离仍待完成。 +网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。 + +raw 和 AF_PACKET 的创建按网络 user owner 的 ``CAP_NET_RAW`` 授权。收包、地址绑定、设备选项、接口 ioctl、IPv6 路由、多播、错误和 ICMPv6 ping ID 冲突按创建网络匹配。传递 OFD 或切换任务网络后仍使用创建网络,非初始 socket 的私有全局控制返回 ``EOPNOTSUPP``。物理 ingress 和设备移除只作用于初始网络。AF_PACKET 的 loopback 发送返回 ``EOPNOTSUPP``。raw IPv4 先查询创建网络的路由,非初始或 loopback 路由返回 ``ENETUNREACH``,其物理发送仅在初始网络执行。 TCP 的端口冲突、IPv4/IPv6 和映射地址握手、接收连接、收发、ICMPv6 错误与设备选项按创建网络隔离。接收连接保留监听端网络,IPv4 延迟回环队列持有网络引用,投递或丢弃后释放。发送先查询该空间的路由与接口状态,物理输出归初始网络。特权端口按网络 owner 的 ``CAP_NET_BIND_SERVICE`` 授权,接口 ioctl 与 ``SO_BINDTODEVICE`` 使用创建网络。非初始 TCP 的私有全局网络控制返回 ``EOPNOTSUPP``,旧连接入口接受数值 IPv4 目标,主机名解析限于初始网络。 -``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 和 TCP 端点输出实际队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 和 ``raw6`` 仅输出表头。 +``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``raw6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP、TCP 和 raw IPv6 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 仅输出表头。 用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 transport 隔离完成后接通。 diff --git a/Documentation/core-api/network-devices.rst b/Documentation/core-api/network-devices.rst index b278af0c..8c610a88 100644 --- a/Documentation/core-api/network-devices.rst +++ b/Documentation/core-api/network-devices.rst @@ -34,10 +34,7 @@ IPv4 路由优先使用最长前缀,再比较 metric 和接口索引。绑定 IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 按网络空间隔离,并携带该空间的 ifindex。逐链路状态通过动态分配管理,RA、RS、DAD、MLD 和发现定时分别推进。不同链路可以使用相同 link-local 地址,socket 的作用域与设备绑定须一致。IPv6 表和队列的容量按网络空间分别计量,耗尽时返回错误。 -Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及 -行政状态开关。接口配置修改需要 ``CAP_NET_ADMIN``。首次设置 -``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要 ``CAP_NET_RAW``。 -AF_PACKET 和 raw socket 的创建权限继续由对应协议入口检查。 +Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及行政状态开关。查询使用 socket 创建时保留的网络,接口配置修改需要该网络 user owner 的 ``CAP_NET_ADMIN``。首次设置 ``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要该 owner 的 ``CAP_NET_RAW``。AF_PACKET 和 raw socket 的创建同样要求该 owner 的 ``CAP_NET_RAW``。 设备直接接收软件提交的帧,发送队列交由各设备的有界 DMA 环管理。 ``SIOCGIFTXQLEN`` 报告的软件队列长度为 0。硬件 MTU 为 1500。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 018e2c93..736cdc8b 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -430,8 +430,8 @@ msgstr "``struct uts_namespace`` uses atomic reference counting. Tasks and nsfs msgid "网络空间生命周期" msgstr "Network namespace lifetime" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink、UDP 和 TCP 套接字独立持有创建时的网络空间,服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。TCP 分配或新建 FD 安装失败释放候选对象及网络引用,已绑定或协议活跃的端点在关闭描述并完成协议回收后释放网络。" -msgstr "``net_namespace_create()`` creates a reference-counted network namespace with an immutable user owner. ``NULL`` denotes the permanent initial network namespace. Tasks share it on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix, netlink, UDP and TCP socket independently retains its creating network. Server connections inherit the listener network. Failed UDP allocation or FD installation releases the candidate object. Final close removes the registry entry before releasing multicast memberships, received datagrams and the network reference. Failed TCP allocation or new FD installation releases the candidate and its network reference. Bound or protocol-active TCP endpoints release the network after description close and protocol collection." +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink、UDP、TCP、raw 和 AF_PACKET 套接字独立持有创建时的网络空间,服务端连接继承监听端空间。UDP、raw 和 AF_PACKET 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。TCP 分配或新建 FD 安装失败释放候选对象及网络引用,已绑定或协议活跃的端点在关闭描述并完成协议回收后释放网络。" +msgstr "``net_namespace_create()`` creates a reference-counted network namespace with an immutable user owner. ``NULL`` denotes the permanent initial network. Tasks share it on fork, retain it across exec and identity cleanup, and release it on wait reaping or slot reuse. Each Unix, netlink, UDP, TCP, raw and AF_PACKET socket independently retains its creating network. Server connections inherit the listener network. Failed UDP, raw and AF_PACKET allocation or FD installation releases the candidate object. Final close removes the registry entry before releasing multicast memberships, queued data and the network reference. Failed TCP allocation or new FD installation releases the candidate object and network reference. Bound or protocol-active TCP endpoints release their network after descriptor close and protocol reclamation." msgid "" "每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 " @@ -444,11 +444,11 @@ msgstr "" "remain in the initial network. The final namespace reference releases interfaces, explicit " "IPv4 routes, IPv6 resources and the owner reference." -msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。raw transport 的网络隔离仍待完成。" -msgstr "Network namespaces scope Unix abstract addresses, proc enumeration, netlink ports and message delivery. Netlink interface, IPv4/IPv6 address and route queries and changes use the socket's retained creating network, with changes requiring ``CAP_NET_ADMIN`` in its user owner. IPv6 addresses, routes, neighbors, multicast, pending packets, reassembly, PMTU, fragment identifiers and ICMP error rate limits are isolated by network. Maintenance visits live protocol states while retaining the serviced network. Reinitializing the initial network preserves other live networks. UDP port conflicts, IPv4/IPv6 and mapped-address delivery, ICMPv6 errors, multicast and device options match the creating network across OFD transfer or task network changes. Privileged ports require ``CAP_NET_BIND_SERVICE`` in that network's user owner. Local sends check the network's route and interface readiness. ReliefOS private global network control on noninitial UDP sockets returns ``EOPNOTSUPP``. Raw transport network isolation remains pending." +msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。" +msgstr "Network namespaces scope Unix abstract addresses, proc enumeration, netlink ports and message delivery. Netlink interface, IPv4/IPv6 address and route queries and changes use the socket's retained creating network, with changes requiring ``CAP_NET_ADMIN`` in its user owner. IPv6 addresses, routes, neighbors, multicast, pending packets, reassembly, PMTU, fragment identifiers and ICMP error rate limits are isolated by network. Maintenance visits live protocol states while retaining the serviced network. Reinitializing the initial network preserves other live networks. UDP port conflicts, IPv4/IPv6 and mapped-address delivery, ICMPv6 errors, multicast and device options match the creating network across OFD transfer or task network changes. Privileged ports require ``CAP_NET_BIND_SERVICE`` in that network's user owner. Local sends check the network's route and interface readiness. ReliefOS private global network control on noninitial UDP sockets returns ``EOPNOTSUPP``." -msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 和 TCP 端点输出实际队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 和 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/dev``, ``route``, ``if_inet6``, ``ipv6_route``, ``udp``, ``udp6``, ``tcp``, ``tcp6`` and ``unix`` follow the caller's current network scope. UDP and TCP rows report actual queues and numeric inodes. IPv4 local UDP delivery counters belong to the corresponding network. Noninitial ``arp`` and ``raw6`` views contain only headers." +msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``raw6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP、TCP 和 raw IPv6 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 仅输出表头。" +msgstr "``/proc/net/dev``, ``route``, ``if_inet6``, ``ipv6_route``, ``udp``, ``udp6``, ``tcp``, ``tcp6``, ``raw6`` and ``unix`` follow the caller's current network scope. UDP, TCP and raw IPv6 endpoints report actual receive queues and numeric inodes. IPv4 local UDP delivery counters belong to the corresponding network. Noninitial ``arp`` views contain only headers." msgid "" "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " @@ -476,3 +476,6 @@ msgstr "The supported route multicast groups are ``RTMGRP_LINK``, ``RTMGRP_IPV6_ msgid "TCP 的端口冲突、IPv4/IPv6 和映射地址握手、接收连接、收发、ICMPv6 错误与设备选项按创建网络隔离。接收连接保留监听端网络,IPv4 延迟回环队列持有网络引用,投递或丢弃后释放。发送先查询该空间的路由与接口状态,物理输出归初始网络。特权端口按网络 owner 的 ``CAP_NET_BIND_SERVICE`` 授权,接口 ioctl 与 ``SO_BINDTODEVICE`` 使用创建网络。非初始 TCP 的私有全局网络控制返回 ``EOPNOTSUPP``,旧连接入口接受数值 IPv4 目标,主机名解析限于初始网络。" msgstr "TCP port conflicts, IPv4/IPv6 and mapped-address handshakes, accepted connections, data, ICMPv6 errors and device options are isolated by the creating network. Accepted connections retain the listener network. The deferred IPv4 loopback queue owns a network reference until delivery or drop. Sends first query that network's route and interface state, with physical output owned by the initial network. Privileged ports require ``CAP_NET_BIND_SERVICE`` in the network owner. Interface ioctls and ``SO_BINDTODEVICE`` use the creating network. Private global control on noninitial TCP returns ``EOPNOTSUPP``. The legacy connect entry accepts numeric IPv4 targets, with hostname resolution confined to the initial network." + +msgid "raw 和 AF_PACKET 的创建按网络 user owner 的 ``CAP_NET_RAW`` 授权。收包、地址绑定、设备选项、接口 ioctl、IPv6 路由、多播、错误和 ICMPv6 ping ID 冲突按创建网络匹配。传递 OFD 或切换任务网络后仍使用创建网络,非初始 socket 的私有全局控制返回 ``EOPNOTSUPP``。物理 ingress 和设备移除只作用于初始网络。AF_PACKET 的 loopback 发送返回 ``EOPNOTSUPP``。raw IPv4 先查询创建网络的路由,非初始或 loopback 路由返回 ``ENETUNREACH``,其物理发送仅在初始网络执行。" +msgstr "Raw and AF_PACKET creation requires ``CAP_NET_RAW`` in the network's user owner. Receive delivery, address binding, device options, interface ioctls, IPv6 routing, multicast, errors and ICMPv6 ping ID conflicts match the creating network. OFD transfer or task network changes preserve that network. Private global control on noninitial sockets returns ``EOPNOTSUPP``. Physical ingress and device removal affect only the initial network. AF_PACKET loopback sends return ``EOPNOTSUPP``. Raw IPv4 first looks up routes in its creating network. Noninitial or loopback routes return ``ENETUNREACH``, and physical transmission runs only in the initial network." diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po index 95dd7e9c..ee099196 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po @@ -92,17 +92,8 @@ msgstr "" "IPv6 tables and queues account capacity independently per network and return errors on " "exhaustion." -msgid "" -"Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及 行政状态开关。接口配置修改需要 " -"``CAP_NET_ADMIN``。首次设置 ``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要 " -"``CAP_NET_RAW``。 AF_PACKET 和 raw socket 的创建权限继续由对应协议入口检查。" -msgstr "" -"Linux network-management entry points cover queries by name/index, IPv4/IPv6" -" address and route operations, and administrative state changes. Changing " -"interface configuration requires ``CAP_NET_ADMIN``. Ordinary processes may " -"set ``SO_BINDTODEVICE`` initially; changing an existing device binding " -"requires ``CAP_NET_RAW``. Permissions to create AF_PACKET and raw sockets " -"remain checked at the respective protocol entry points." +msgid "Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及行政状态开关。查询使用 socket 创建时保留的网络,接口配置修改需要该网络 user owner 的 ``CAP_NET_ADMIN``。首次设置 ``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要该 owner 的 ``CAP_NET_RAW``。AF_PACKET 和 raw socket 的创建同样要求该 owner 的 ``CAP_NET_RAW``。" +msgstr "Linux network management supports name and index queries, IPv4/IPv6 address and route operations, and administrative state changes. Queries use the socket's retained creating network. Interface changes require ``CAP_NET_ADMIN`` in that network's user owner. Initial ``SO_BINDTODEVICE`` is allowed for ordinary processes. Changing an existing device binding requires ``CAP_NET_RAW`` in that owner. AF_PACKET and raw socket creation also requires ``CAP_NET_RAW`` in that owner." msgid "" "设备直接接收软件提交的帧,发送队列交由各设备的有界 DMA 环管理。 ``SIOCGIFTXQLEN`` 报告的软件队列长度为 0。硬件 MTU 为 " diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po index 91619b5e..b7b60e7e 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po @@ -57,8 +57,8 @@ msgstr "" msgid "配置与观测" msgstr "Configuration and Observation" -msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP 和 TCP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。raw socket 的 ioctl 随其 transport 隔离接通。" -msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 addresses and routes in the network scope retained when the socket was created, including after FD transfer. Changes require ``CAP_NET_ADMIN`` in the network owner's user namespace. ``getifaddrs()`` obtains that scope's IPv6 addresses through standard queries. IPv6 address and route ioctls use the selected network's state and owner authority, with layouts selected by socket family. UDP and TCP interface, IPv6 address and route ioctls use the creating network. Raw socket ioctls will follow their transport isolation." +msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。" +msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 addresses and routes in the network scope retained when the socket was created, including after FD transfer. Changes require ``CAP_NET_ADMIN`` in the network owner's user namespace. ``getifaddrs()`` obtains that scope's IPv6 addresses through standard queries. IPv6 address and route ioctls use the selected network's state and owner authority, with layouts selected by socket family. Interface ioctls on UDP, TCP, raw and AF_PACKET sockets, and address and route ioctls on IPv6 sockets, all use the creating network." msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" msgstr "Route multicast supports link, IPv6 address and IPv6 route groups. IPv4 address and route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``. Each network namespace maintains its own subscription snapshots, published after all captures succeed and released when its final subscriber closes or unsubscribes. Change notifications and overruns are delivered by network scope. Receive queue overflow reports ``ENOBUFS``, and callers should query again." @@ -72,8 +72,8 @@ msgstr "" "empty query result. Receivers must still iterate all messages in each datagram until the matching " "``NLMSG_DONE`` or an error arrives." -msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP 和 TCP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。raw transport 的网络隔离仍待完成,非初始空间的 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text layouts. Address scope encoding differs from rtnetlink scope values. Address, route, UDP and TCP tables follow the caller's current network scope. Snapshots copy internal state and retain only copies across waits. Raw transport network isolation remains pending, and noninitial ``raw6`` views contain only headers." +msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP、TCP 和 raw 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。" +msgstr "``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text layouts. Address scope encoding differs from rtnetlink scope values. Address, route, UDP, TCP and raw tables follow the caller's current network scope. Snapshots copy internal state and retain only copies across waits." msgid "" "每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" @@ -114,3 +114,6 @@ msgstr "" msgid "TCP、UDP 和 raw socket 的 ``bind`` 与 Linux 一样,只对需要区域标识的地址 使用 ``sin6_scope_id``。绑定 ``::``、``::1``、IPv4 映射地址或其他无此需求的 地址时忽略该字段,避免将旧版 Netty 留下的未初始化值误判为不存在的网卡。 链路本地地址及接口/链路本地多播地址仍校验接口;``SO_BINDTODEVICE`` 指定的设备绑定继续生效。" msgstr "As on Linux, bind on TCP, UDP, and raw sockets uses sin6_scope_id only for addresses that require a scope identifier. For ::, ::1, IPv4-mapped addresses, and other addresses without that requirement, the field is ignored so that an uninitialized value left by older Netty versions is not mistaken for a nonexistent interface. Link-local addresses and interface-local or link-local multicast addresses still require a valid interface. Device binding selected with SO_BINDTODEVICE remains effective." + +msgid "raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 ``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD 后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。" +msgstr "Raw IPv6 sockets independently retain their creating network. Creation requires ``CAP_NET_RAW`` in that network's user owner. Address binding, routing, delivery, multicast memberships, ICMPv6 errors, ping ID conflicts and device options are isolated by creating network, including after FD transfer. Final close leaves multicast in the original network and releases references. Physical device removal reports errors only to affected sockets in the initial network." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index ab56887f..b1aaf1d4 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -380,8 +380,8 @@ msgstr "``struct uts_namespace`` はアトミックな参照カウントを使 msgid "网络空间生命周期" msgstr "ネットワーク名前空間の寿命" -msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink、UDP 和 TCP 套接字独立持有创建时的网络空间,服务端连接继承监听端空间。UDP 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。TCP 分配或新建 FD 安装失败释放候选对象及网络引用,已绑定或协议活跃的端点在关闭描述并完成协议回收后释放网络。" -msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク名前空間を作成します。``NULL`` は永続的な初期ネットワーク名前空間です。タスクは fork で共有し、exec と資格情報のクリーンアップで参照を保持し、wait による回収やスロット再利用で解放します。Unix、netlink、UDP、TCP ソケットはそれぞれ作成時のネットワークを独立して保持し、サーバー接続はリスナーのネットワークを継承します。UDP の割り当てや FD 設置が失敗すると候補を解放します。最後の close は registry から削除した後、マルチキャスト参加、受信キュー、ネットワーク参照を解放します。TCP の割り当てや新規 FD 設置の失敗は候補とネットワーク参照を解放します。バインド済みまたはプロトコルが動作中の TCP 端点は記述の close とプロトコル回収後にネットワークを解放します。" +msgid "``net_namespace_create()`` 创建带不可变用户 owner 的引用计数网络空间,``NULL`` 表示永久初始网络空间。任务在 fork 时共享该空间,exec 和身份清理保留引用,wait 回收或槽位重用时释放引用。每个 Unix、netlink、UDP、TCP、raw 和 AF_PACKET 套接字独立持有创建时的网络空间,服务端连接继承监听端空间。UDP、raw 和 AF_PACKET 分配内存或安装 FD 失败时释放候选对象,最后关闭时先移除 registry,再释放多播成员、接收队列和网络引用。TCP 分配或新建 FD 安装失败释放候选对象及网络引用,已绑定或协议活跃的端点在关闭描述并完成协议回收后释放网络。" +msgstr "``net_namespace_create()`` は不変のユーザー owner を持つ参照カウント付きネットワーク名前空間を作成します。``NULL`` は永続的な初期ネットワーク名前空間です。タスクは fork で共有し、exec と資格情報のクリーンアップで参照を保持し、wait による回収やスロット再利用で解放します。Unix、netlink、UDP、TCP、raw、AF_PACKET ソケットはそれぞれ作成時のネットワークを独立して保持し、サーバー接続はリスナーのネットワークを継承します。UDP、raw、AF_PACKET の割り当てや FD 設置が失敗すると候補を解放します。最後の close は registry から削除した後、マルチキャスト参加、受信キュー、ネットワーク参照を解放します。TCP の割り当てや新規 FD 設置の失敗は候補とネットワーク参照を解放します。バインド済みまたはプロトコルが動作中の TCP 端点は記述の close とプロトコル回収後にネットワークを解放します。" msgid "" "每个网络空间独立持有 loopback、接口列表、显式 IPv4 路由及 IPv6 协议状态。新空间的 ``lo`` 默认 down 且无地址,首次置为 up 时配置 " @@ -392,11 +392,11 @@ msgstr "" "でアドレスを持たず、最初の up で ``127.0.0.1/8``、``::1/128``、IPv6 host route を設定します。物理 NIC 登録と ingress " "は初期空間に属します。最後の空間参照を解放すると、インターフェース、明示的な IPv4 経路、IPv6 資源、owner 参照も解放します。" -msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。raw transport 的网络隔离仍待完成。" -msgstr "ネットワーク空間は Unix 抽象アドレス、proc 列挙、netlink ポート、メッセージ配送に scope を与えます。netlink のインターフェース、IPv4/IPv6 アドレス、経路の照会と変更はソケットが保持する作成元ネットワークを使用し、変更にはその user owner の ``CAP_NET_ADMIN`` が必要です。IPv6 アドレス、経路、近隣、多播、送信待ちパケット、再構成、PMTU、フラグメント ID、ICMP エラー制限はネットワークごとに隔離します。保守処理は対象空間の参照を保持して稼働中のプロトコル状態を巡回します。初期ネットワークの再初期化は他の稼働中空間を保持します。UDP のポート競合、IPv4/IPv6 とマップアドレスの送受信、ICMPv6 エラー、多播、デバイスオプションは OFD 転送やタスクのネットワーク変更後も作成元空間で照合します。特権ポートにはそのネットワークの user owner における ``CAP_NET_BIND_SERVICE`` が必要です。ローカル送信は対象空間の経路とインターフェースの準備状態を確認します。非初期 UDP ソケットの ReliefOS 独自グローバルネットワーク制御は ``EOPNOTSUPP`` を返します。raw transport のネットワーク隔離は今後の実装対象です。" +msgid "网络空间为 Unix 抽象地址、proc 枚举、netlink 端口及消息投递提供作用域。接口、IPv4/IPv6 地址和路由的 netlink 查询与修改使用 socket 创建时保留的网络 scope,修改要求该 scope 的 user owner 的 ``CAP_NET_ADMIN``。IPv6 地址、路由、邻居、多播、待发包、重组、PMTU、分片编号和 ICMP 错误限速按网络隔离。网络维护遍历活跃协议状态,执行期间持有被服务空间的引用。初始网络重新初始化保留其他活跃空间。UDP 的端口冲突、IPv4/IPv6 与映射地址收发、ICMPv6 错误、多播和设备选项按创建网络匹配,传递 OFD 或切换任务网络后继续使用创建网络。特权端口需要该网络 owner 的 ``CAP_NET_BIND_SERVICE``,本地发送检查该空间的路由及接口就绪状态。非初始 UDP socket 的 ReliefOS 私有全局网络控制返回 ``EOPNOTSUPP``。" +msgstr "ネットワーク空間は Unix 抽象アドレス、proc 列挙、netlink ポート、メッセージ配送に scope を与えます。netlink のインターフェース、IPv4/IPv6 アドレス、経路の照会と変更はソケットが保持する作成元ネットワークを使用し、変更にはその user owner の ``CAP_NET_ADMIN`` が必要です。IPv6 アドレス、経路、近隣、多播、送信待ちパケット、再構成、PMTU、フラグメント ID、ICMP エラー制限はネットワークごとに隔離します。保守処理は対象空間の参照を保持して稼働中のプロトコル状態を巡回します。初期ネットワークの再初期化は他の稼働中空間を保持します。UDP のポート競合、IPv4/IPv6 とマップアドレスの送受信、ICMPv6 エラー、多播、デバイスオプションは OFD 転送やタスクのネットワーク変更後も作成元空間で照合します。特権ポートにはそのネットワークの user owner における ``CAP_NET_BIND_SERVICE`` が必要です。ローカル送信は対象空間の経路とインターフェースの準備状態を確認します。非初期 UDP ソケットの ReliefOS 独自グローバルネットワーク制御は ``EOPNOTSUPP`` を返します。" -msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP 和 TCP 端点输出实际队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 和 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``unix`` は呼び出し元の現在のネットワーク scope を使用します。UDP と TCP の行は実際のキューと数値 inode を表示します。IPv4 ローカル UDP 配信のカウンターは対応するネットワークに属します。非初期空間の ``arp`` と ``raw6`` はヘッダーのみを出力します。" +msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``raw6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP、TCP 和 raw IPv6 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 仅输出表头。" +msgstr "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``raw6``、``unix`` は呼び出し元の現在のネットワーク scope を使用します。UDP、TCP、raw IPv6 の端点は実際の受信キューと数値 inode を表示します。IPv4 ローカル UDP 配信のカウンターは対応するネットワークに属します。非初期空間の ``arp`` はヘッダーのみを出力します。" msgid "" "用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " @@ -424,3 +424,6 @@ msgstr "現在対応するルートマルチキャストグループは ``RTMGRP msgid "TCP 的端口冲突、IPv4/IPv6 和映射地址握手、接收连接、收发、ICMPv6 错误与设备选项按创建网络隔离。接收连接保留监听端网络,IPv4 延迟回环队列持有网络引用,投递或丢弃后释放。发送先查询该空间的路由与接口状态,物理输出归初始网络。特权端口按网络 owner 的 ``CAP_NET_BIND_SERVICE`` 授权,接口 ioctl 与 ``SO_BINDTODEVICE`` 使用创建网络。非初始 TCP 的私有全局网络控制返回 ``EOPNOTSUPP``,旧连接入口接受数值 IPv4 目标,主机名解析限于初始网络。" msgstr "TCP のポート競合、IPv4/IPv6 とマップ形式のハンドシェイク、接続受け入れ、送受信、ICMPv6 エラー、デバイスオプションは作成時のネットワークで分離します。受け入れた接続はリスナーのネットワークを保持します。IPv4 遅延ループバックキューは配信または破棄までネットワーク参照を保持します。送信はそのネットワークの経路とインターフェース状態を確認し、物理出力は初期ネットワークに属します。特権ポートはネットワーク owner の ``CAP_NET_BIND_SERVICE`` で認可します。インターフェース ioctl と ``SO_BINDTODEVICE`` は作成時のネットワークを使用します。非初期 TCP の独自グローバル制御は ``EOPNOTSUPP`` を返します。旧接続入口は数値 IPv4 宛先を受け付け、ホスト名解決は初期ネットワークに限定します。" + +msgid "raw 和 AF_PACKET 的创建按网络 user owner 的 ``CAP_NET_RAW`` 授权。收包、地址绑定、设备选项、接口 ioctl、IPv6 路由、多播、错误和 ICMPv6 ping ID 冲突按创建网络匹配。传递 OFD 或切换任务网络后仍使用创建网络,非初始 socket 的私有全局控制返回 ``EOPNOTSUPP``。物理 ingress 和设备移除只作用于初始网络。AF_PACKET 的 loopback 发送返回 ``EOPNOTSUPP``。raw IPv4 先查询创建网络的路由,非初始或 loopback 路由返回 ``ENETUNREACH``,其物理发送仅在初始网络执行。" +msgstr "raw と AF_PACKET の作成にはネットワークの user owner における ``CAP_NET_RAW`` が必要です。受信、アドレス bind、デバイスオプション、インターフェース ioctl、IPv6 経路、マルチキャスト、エラー、ICMPv6 ping ID の競合を作成元ネットワークで照合します。OFD 転送やタスクのネットワーク変更後も同じネットワークを使用します。非初期ソケットの独自グローバル制御は ``EOPNOTSUPP`` を返します。物理 ingress とデバイス削除は初期ネットワークだけに作用します。AF_PACKET のループバック送信は ``EOPNOTSUPP`` を返します。raw IPv4 は作成元ネットワークの経路を先に検索し、非初期またはループバック経路には ``ENETUNREACH`` を返します。物理送信は初期ネットワークで実行します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po index 6fe9345d..c30a0014 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po @@ -78,16 +78,8 @@ msgstr "" "を保持します。リンクごとの状態は動的に確保し、RA、RS、DAD、MLD、探索の時刻を個別に進めます。異なるリンクは同じ link-local アドレスを使用でき、socket の " "scope とデバイス束縛は一致する必要があります。IPv6 テーブルとキューの容量はネットワークごとに計量し、枯渇時にはエラーを返します。" -msgid "" -"Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及 行政状态开关。接口配置修改需要 " -"``CAP_NET_ADMIN``。首次设置 ``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要 " -"``CAP_NET_RAW``。 AF_PACKET 和 raw socket 的创建权限继续由对应协议入口检查。" -msgstr "" -"Linux のネットワーク管理エントリーは、名前・インデックスによる照会、IPv4/IPv6 " -"アドレスと経路の操作、管理状態の切り替えに対応します。インターフェース構成の変更には ``CAP_NET_ADMIN`` " -"が必要です。``SO_BINDTODEVICE`` の初回設定は通常プロセスにも許可しますが、既存のデバイスバインドの変更には " -"``CAP_NET_RAW`` が必要です。AF_PACKET と raw socket " -"の作成権限は、引き続き対応するプロトコルエントリーで確認します。" +msgid "Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及行政状态开关。查询使用 socket 创建时保留的网络,接口配置修改需要该网络 user owner 的 ``CAP_NET_ADMIN``。首次设置 ``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要该 owner 的 ``CAP_NET_RAW``。AF_PACKET 和 raw socket 的创建同样要求该 owner 的 ``CAP_NET_RAW``。" +msgstr "Linux のネットワーク管理は名前・索引の照会、IPv4/IPv6 アドレスと経路の操作、管理状態の変更を提供します。照会はソケットが保持する作成元ネットワークを使用し、インターフェースの変更にはその user owner における ``CAP_NET_ADMIN`` が必要です。最初の ``SO_BINDTODEVICE`` は通常のプロセスにも許可され、既存のデバイス bind の変更には同じ owner における ``CAP_NET_RAW`` が必要です。AF_PACKET と raw socket の作成にも同じ owner における ``CAP_NET_RAW`` が必要です。" msgid "" "设备直接接收软件提交的帧,发送队列交由各设备的有界 DMA 环管理。 ``SIOCGIFTXQLEN`` 报告的软件队列长度为 0。硬件 MTU 为 " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po index 857e22df..338ef941 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po @@ -52,8 +52,8 @@ msgstr "" msgid "配置与观测" msgstr "設定と観測" -msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP 和 TCP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。raw socket 的 ioctl 随其 transport 隔离接通。" -msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` はソケット作成時に保持したネットワーク scope のリンク、IPv4/IPv6 アドレス、経路を照会・変更し、FD 転送後もその scope を使用します。変更にはネットワークの user owner における ``CAP_NET_ADMIN`` が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 アドレスを取得します。IPv6 アドレスと経路の ioctl は対象ネットワークの状態と owner 権限を使用し、引数形式は socket family で選択します。UDP と TCP のインターフェース、IPv6 アドレス、経路 ioctl は作成元ネットワークを使用します。raw socket の ioctl は transport の隔離に合わせて対応します。" +msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。" +msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` はソケット作成時に保持したネットワーク scope のリンク、IPv4/IPv6 アドレス、経路を照会・変更し、FD 転送後もその scope を使用します。変更にはネットワークの user owner における ``CAP_NET_ADMIN`` が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 アドレスを取得します。IPv6 アドレスと経路の ioctl は対象ネットワークの状態と owner 権限を使用し、引数形式は socket family で選択します。UDP、TCP、raw、AF_PACKET のインターフェース ioctl と、IPv6 ソケットのアドレスおよび経路 ioctl は、すべて作成元ネットワークを使用します。" msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" msgstr "ルートマルチキャストはリンク、IPv6 アドレス、IPv6 ルートのグループに対応します。IPv4 アドレスとルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。各ネットワーク名前空間は独立した購読スナップショットを保持し、すべての取得が成功してから公開します。最後の購読者が閉じるか購読を解除すると解放します。変更通知と overrun はネットワーク scope ごとに配信し、受信キューのオーバーフローは ``ENOBUFS`` を報告するため、呼び出し元は再照会してください。" @@ -65,8 +65,8 @@ msgstr "" "複数部分からなる問い合わせでは、データと終端の ``NLMSG_DONE`` を別々のデータグラムとして送信します。終端マーカーは要求のシーケンス番号と受信ポート ID " "を保持し、結果が空でも送信します。受信側は引き続き各データグラム内の全メッセージを走査し、対応する番号の ``NLMSG_DONE`` またはエラーを待つ必要があります。" -msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP 和 TCP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。raw transport 的网络隔离仍待完成,非初始空间的 ``raw6`` 仅输出表头。" -msgstr "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト形式を使用します。アドレス scope の符号化は rtnetlink の値と異なります。アドレス、経路、UDP、TCP の表は呼び出し元の現在のネットワーク scope に従います。スナップショットは内部状態をコピーし、待機をまたいでコピーだけを保持します。raw transport のネットワーク分離は今後の実装で、非初期空間の ``raw6`` はヘッダーのみを出力します。" +msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP、TCP 和 raw 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。" +msgstr "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト形式を使用します。アドレス scope の符号化は rtnetlink の値と異なります。アドレス、経路、UDP、TCP、raw の表は呼び出し元の現在のネットワーク scope に従います。スナップショットは内部状態をコピーし、待機をまたいでコピーだけを保持します。" msgid "" "每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" @@ -101,3 +101,6 @@ msgstr "" msgid "TCP、UDP 和 raw socket 的 ``bind`` 与 Linux 一样,只对需要区域标识的地址 使用 ``sin6_scope_id``。绑定 ``::``、``::1``、IPv4 映射地址或其他无此需求的 地址时忽略该字段,避免将旧版 Netty 留下的未初始化值误判为不存在的网卡。 链路本地地址及接口/链路本地多播地址仍校验接口;``SO_BINDTODEVICE`` 指定的设备绑定继续生效。" msgstr "Linux と同様に、TCP、UDP、および raw socket の bind はスコープ識別子が必要なアドレスに限って sin6_scope_id を使用します。::、::1、IPv4 マップアドレスなど、識別子が不要なアドレスではこのフィールドを無視し、旧版 Netty が残した未初期化の値を存在しないインターフェースとして誤判定することを防ぎます。リンクローカルアドレスとインターフェースローカルまたはリンクローカルのマルチキャストアドレスでは、引き続き有効なインターフェースを検証します。SO_BINDTODEVICE で指定したデバイスへのバインドも維持します。" + +msgid "raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 ``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD 后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。" +msgstr "raw IPv6 ソケットは作成元ネットワークを独立して保持し、作成にはその user owner における ``CAP_NET_RAW`` が必要です。アドレス bind、経路、送受信、マルチキャスト所属、ICMPv6 エラー、ping ID の競合、デバイスオプションを作成元ネットワークで隔離し、FD 転送後も同じネットワークを使います。最終 close で元のネットワークのマルチキャストから脱退し、参照を解放します。物理デバイス削除は初期ネットワークの該当ソケットだけにエラーを通知します。" diff --git a/Documentation/userspace-api/ipv6.rst b/Documentation/userspace-api/ipv6.rst index 6be61d0e..9c0440a2 100644 --- a/Documentation/userspace-api/ipv6.rst +++ b/Documentation/userspace-api/ipv6.rst @@ -32,7 +32,7 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 配置与观测 ========== -``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP 和 TCP socket 的接口、IPv6 地址和路由 ioctl 使用创建网络。raw socket 的 ioctl 随其 transport 隔离接通。 +``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。 路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。 @@ -40,7 +40,9 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。 -``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP 和 TCP 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。raw transport 的网络隔离仍待完成,非初始空间的 ``raw6`` 仅输出表头。 +``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP、TCP 和 raw 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。 + +raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 ``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD 后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。 每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。 diff --git a/include/reliefnt/net.h b/include/reliefnt/net.h index 8b6b4ad1..3c3e6acb 100644 --- a/include/reliefnt/net.h +++ b/include/reliefnt/net.h @@ -338,11 +338,13 @@ bool net_interface_present(void); bool net_interface_admin_up(void); /** @brief Transmit raw IPv4 with an optional bound output device. + * @param ns Borrowed network, NULL for the initial network. Hardware output + * requires the initial network and a physical route. * @param ifindex Bound device or zero for route selection. @param destination Peer IPv4. * @param source Bound source or zero. @param protocol IP protocol. * @param header_included Payload contains an IPv4 header. @param data Borrowed bytes. * @param length Byte count. @return Bytes accepted or negative Linux errno. */ -int net_ipv4_send_raw_on(uint32_t ifindex, uint32_t destination, uint32_t source, +int net_ipv4_send_raw_on(struct net_namespace *ns, uint32_t ifindex, uint32_t destination, uint32_t source, uint8_t protocol, bool header_included, const void *data, uint32_t length); /** @brief Transmit a UDP message through the selected interface and route. * @param ns Borrowed network, NULL for the initial network. Hardware output diff --git a/include/reliefnt/net_ipv6.h b/include/reliefnt/net_ipv6.h index bffd8e4c..8ff44dd1 100644 --- a/include/reliefnt/net_ipv6.h +++ b/include/reliefnt/net_ipv6.h @@ -182,9 +182,14 @@ void net_ipv6_socket_error(const uint8_t *packet,uint32_t length,int error,uint3 * @param ifindex Interface index, zero to skip interface filtering. @param packet Quoted packet. * @param length Available quote bytes. @param error Positive Linux errno. @param mtu MTU or zero. */ void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex,const uint8_t *packet,uint32_t length,int error,uint32_t mtu); -/** @brief Render tcp6/udp6/raw6 socket state without driving I/O. +/** @brief Render the initial network's tcp6/udp6/raw6 state without driving I/O. * @param stream Slice output. @param leaf Requested standard proc basename. */ void net_ipv6_transport_proc_emit(struct text_stream *stream,const char *leaf); +/** @brief Render a network's tcp6/udp6/raw6 state without driving I/O. + * @param ns Borrowed network, NULL for the permanent initial network. + * @param stream Caller-owned output slice. @param leaf Standard proc basename. + */ +void net_ipv6_transport_proc_emit_on(struct net_namespace *ns, struct text_stream *stream, const char *leaf); /** @brief Notify the selected network's route subscribers of protocol state changes. * Runs under execution ownership and retains the previous baseline on OOM. * @param ns Borrowed network, NULL for the permanent initial network. diff --git a/include/reliefnt/net_packet.h b/include/reliefnt/net_packet.h index 75f7c480..da79b72d 100644 --- a/include/reliefnt/net_packet.h +++ b/include/reliefnt/net_packet.h @@ -2,7 +2,13 @@ #define RELIEFNT_NET_PACKET_H #include struct task_file; +struct net_namespace; #define TASK_FILE_KIND_PACKET 3u +/** @brief Borrow the network retained by a raw/packet socket description. + * @param file Pinned description under execution ownership, or NULL. + * @return Borrowed creating network, NULL for the initial network or another kind. + */ +struct net_namespace *task_packet_namespace(const struct task_file *file); /** @brief Dispatch raw IPv4 and Ethernet socket operations under the execution lock. * @param number Native syscall number. * @param a0 First native argument. @@ -69,7 +75,7 @@ int task_packet_recv_staged(struct task_file *file,void *data,uint32_t length, * @return Ready event bits. */ short task_packet_poll(struct task_file *file, short events); -/** @brief Release the final raw/packet description and queued messages. +/** @brief Release the final raw/packet description, queue, multicast and network. * @param file Owned description under the execution lock. */ void task_packet_release(struct task_file *file); @@ -79,12 +85,14 @@ void task_packet_release(struct task_file *file); */ int task_packet_available(struct task_file *file); /** @brief Deliver one Ethernet frame while retaining its original ingress link. + * @param ns Borrowed network, NULL for the permanent initial network. * @param ifindex Stable ingress interface. @param frame Borrowed frame. * @param length Complete Ethernet frame length. */ -void net_packet_input_on(uint32_t ifindex, const void *frame, uint32_t length); +void net_packet_input_on(struct net_namespace *ns, uint32_t ifindex, const void *frame, uint32_t length); -/** @brief Wake raw sockets bound to a disappearing device. @param ifindex Device. */ +/** @brief Wake initial-network raw sockets bound to a removed physical device. + * @param ifindex Removed initial-network device. */ void net_packet_device_detached(uint32_t ifindex); #endif diff --git a/kernel/syscall/device/legacy_ioctl.c b/kernel/syscall/device/legacy_ioctl.c index 4617d263..cba8f17e 100644 --- a/kernel/syscall/device/legacy_ioctl.c +++ b/kernel/syscall/device/legacy_ioctl.c @@ -355,7 +355,7 @@ int64_t syscall_legacy_ioctl(uint64_t number, uint64_t a0, uint64_t a1, uint64_t (a1 == SIOCSIFADDR || a1 == SIOCDIFADDR || a1 == SIOCADDRT || a1 == SIOCDELRT)) return net_ipv6_interface_ioctl(file->kind == TASK_FILE_KIND_UDP ? task_udp_namespace(file) : - file->kind == TASK_FILE_KIND_PACKET ? NULL : + file->kind == TASK_FILE_KIND_PACKET ? task_packet_namespace(file) : net_socket_namespace((int32_t)file->aux), (uint32_t)a1, a2); if (file && (file->flags & TASK_FILE_FLAG_SOCKET_INET)) return task_net_control(file, (uint32_t)a1, a2); diff --git a/net/input.c b/net/input.c index 2edc9108..03de5d24 100644 --- a/net/input.c +++ b/net/input.c @@ -75,7 +75,7 @@ void net_poll_once(struct net_arp_wait *arp_wait, if (ifindex && net_interface_is_up(NULL, ifindex)) { int ret = netdev_poll(ifindex, frame, sizeof(frame), &len); if (ret > 0 && len) { - net_packet_input_on(ifindex, frame, len); + net_packet_input_on(NULL, ifindex, frame, len); net_process_frame(ifindex, frame, len, arp_wait, ping_wait, udp_wait, tcp_wait); } } @@ -113,7 +113,7 @@ void net_poll_rx_budget(uint32_t budget) int result=netdev_poll_notified(id,frame,sizeof(frame),&length); more=result>0 || result==-90 || result==-74; if (result>0 && length && net_interface_is_up(NULL, id)) { - net_packet_input_on(id,frame,length); + net_packet_input_on(NULL,id,frame,length); net_process_frame(id,frame,length,NULL,NULL,NULL,NULL); } if (!more) break; diff --git a/net/ipv4/core.c b/net/ipv4/core.c index d54d93a6..5ef524da 100644 --- a/net/ipv4/core.c +++ b/net/ipv4/core.c @@ -90,15 +90,18 @@ void net_handle_ipv4_on(uint32_t ifindex, const uint8_t *frame, uint32_t len, /** * @brief Send raw IPv4 using the configured route and Ethernet transport. + * @param ns Borrowed network, NULL for the permanent initial network. + * @param ifindex Bound output interface or zero for route selection. * @param destination Host-order destination IPv4 address. * @param source Host-order bound source, zero selects the interface address. * @param protocol IPv4 protocol used when constructing a header. * @param header_included True when data already contains an IPv4 header. * @param data Borrowed validated message payload under the execution lock. * @param length Payload bytes. - * @return Bytes accepted or negative errno; no fragmentation is implemented. + * @return Bytes accepted or negative errno. Noninitial and loopback routes + * return ENETUNREACH before any physical I/O. No fragmentation is implemented. */ -int net_ipv4_send_raw_on(uint32_t ifindex, uint32_t destination, uint32_t source, uint8_t protocol, +int net_ipv4_send_raw_on(struct net_namespace *ns, uint32_t ifindex, uint32_t destination, uint32_t source, uint8_t protocol, bool header_included, const void *data, uint32_t length) { uint32_t header = header_included ? 0 : 20; @@ -107,8 +110,9 @@ int net_ipv4_send_raw_on(uint32_t ifindex, uint32_t destination, uint32_t source uint8_t frame[1514] = {0}; uint8_t *ip = frame + 14; struct net_ipv4_path path; - int route = net_ipv4_route_lookup(NULL, destination, source, ifindex, &path); + int route = net_ipv4_route_lookup(ns, destination, source, ifindex, &path); if (route < 0) return route; + if (ns || path.ifindex == NET_IF_LOOPBACK) return -LINUX_ENETUNREACH; ifindex = path.ifindex; source = path.source; if (header_included) { @@ -151,5 +155,5 @@ void net_handle_ipv4(const uint8_t *frame, uint32_t length, struct net_ping_wait int net_ipv4_send_raw(uint32_t destination, uint32_t source, uint8_t protocol, bool header_included, const void *data, uint32_t length) { - return net_ipv4_send_raw_on(0, destination, source, protocol, header_included, data, length); + return net_ipv4_send_raw_on(NULL, 0, destination, source, protocol, header_included, data, length); } diff --git a/net/proc.c b/net/proc.c index 271a305c..f23e5260 100644 --- a/net/proc.c +++ b/net/proc.c @@ -99,9 +99,7 @@ int net_proc_emit(struct text_stream *s, const char *leaf) return 0; } if (!__builtin_strcmp(leaf, "raw6")) { - if (!ns) net_ipv6_transport_proc_emit(s,leaf); - else text_string(s, " sl local_address rem_address st tx_queue rx_queue tr tm->when " - "retrnsmt uid timeout inode\n"); + net_ipv6_transport_proc_emit_on(ns, s, leaf); return 0; } if (!__builtin_strcmp(leaf, "dev")) { diff --git a/net/socket/control.c b/net/socket/control.c index 5a6371eb..24f24e53 100644 --- a/net/socket/control.c +++ b/net/socket/control.c @@ -16,8 +16,8 @@ * @param file Borrowed socket OFD under execution ownership. * @param request Native ioctl number. @param address User argument address. * @return Zero, negative errno, or a user-memory prerequisite wait marker. - * Netlink, UDP and TCP interface operations use the retained creation network - * and its user owner. Private global control on noninitial UDP/TCP returns EOPNOTSUPP. + * Netlink, UDP, TCP and raw/packet interface operations use the retained creation + * network and its user owner. Private global control in other networks returns EOPNOTSUPP. */ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) { @@ -42,6 +42,7 @@ int task_net_control(struct task_file *file, uint32_t request, uint64_t address) } struct net_namespace *ns = NULL; if (file->kind == TASK_FILE_KIND_UDP) ns = task_udp_namespace(file); + else if (file->kind == TASK_FILE_KIND_PACKET) ns = task_packet_namespace(file); else if (file->kind != TASK_FILE_KIND_PACKET && file->kind != TASK_FILE_KIND_NETLINK) ns = net_socket_namespace((int32_t)file->aux); if (request >= 0x8900 && request <= 0x89ff) { diff --git a/net/socket/packet.c b/net/socket/packet.c index c569d8c3..c89194a1 100644 --- a/net/socket/packet.c +++ b/net/socket/packet.c @@ -7,6 +7,8 @@ #include #include #include +#include +#include #include #include #include @@ -41,6 +43,7 @@ struct packet_message { uint8_t data[]; }; struct packet_socket { + struct net_namespace *net_ns; int domain, type, protocol, ifindex; uint32_t local_ip, remote_ip; uint32_t uid; @@ -79,11 +82,20 @@ static struct packet_socket *packet_of(const struct task_file *file) return file && file->kind == TASK_FILE_KIND_PACKET ? (void *)(uintptr_t)file->aux : NULL; } -/** @brief Queue a bounded copy of each matching ingress packet. +/** @copydoc task_packet_namespace */ +struct net_namespace *task_packet_namespace(const struct task_file *file) +{ + const struct packet_socket *s = packet_of(file); + return s ? s->net_ns : NULL; +} + +/** @brief Queue bounded copies for sockets in the ingress network. + * @param ns Borrowed network, NULL for the permanent initial network. + * @param ifindex Interface index within the ingress network. * @param input Ethernet frame under the execution lock. * @param length Complete frame length. */ -void net_packet_input_on(uint32_t ifindex, const void *input, uint32_t length) +void net_packet_input_on(struct net_namespace *ns, uint32_t ifindex, const void *input, uint32_t length) { if (length < 14 || length > 1514) return; const uint8_t *frame = input; @@ -91,13 +103,13 @@ void net_packet_input_on(uint32_t ifindex, const void *input, uint32_t length) __builtin_memcpy(&protocol, frame + 12, 2); for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *s = sockets[i]; - if (!s || s->queued >= PACKET_QUEUE_LIMIT) continue; + if (!s || s->net_ns != ns || s->queued >= PACKET_QUEUE_LIMIT || + (s->ifindex && (uint32_t)s->ifindex != ifindex)) continue; uint32_t offset = s->domain == AF_PACKET && s->type == SOCK_RAW ? 0 : 14; uint32_t size = length - offset; uint32_t source = 0, destination = 0; if (s->domain == AF_PACKET) { if (!s->protocol || (s->protocol != (int)__builtin_bswap16(3) && s->protocol != protocol)) continue; - if (s->ifindex && (uint32_t)s->ifindex != ifindex) continue; } else { if (s->domain != AF_INET) continue; if (protocol != __builtin_bswap16(0x0800) || length < 34 || frame[14] >> 4 != 4 || @@ -136,11 +148,10 @@ void net_raw6_input(struct net_namespace *ns, const struct in6_addr *source, con uint8_t protocol, const void *data, uint32_t length, uint32_t ifindex, uint8_t hops) { - if (ns) return; if (length > 65535) return; for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *s = sockets[i]; - if (!s || s->domain != AF_INET6 || s->protocol != protocol || s->queued >= PACKET_QUEUE_LIMIT || + if (!s || s->net_ns != ns || s->domain != AF_INET6 || s->protocol != protocol || s->queued >= PACKET_QUEUE_LIMIT || (s->ifindex && (uint32_t)s->ifindex != ifindex) || (s->scope6 && s->scope6 != ifindex) || (!packet6_any(&s->local6) && __builtin_memcmp(&s->local6, destination, sizeof(*destination))) || (s->connected6 && __builtin_memcmp(&s->remote6, source, sizeof(*source)))) continue; @@ -180,8 +191,8 @@ static int packet6_import(uint64_t pointer, uint32_t length, struct sockaddr_in6 return out->sin6_family == AF_INET6 ? 0 : -LINUX_EAFNOSUPPORT; } -/** @brief Send a raw IPv6 upper-layer message through the selected native route. - * @param s Socket. @param data Borrowed bytes. @param length Byte count. +/** @brief Send raw IPv6 through the socket's retained network. + * @param s Socket owning its creation network. @param data Borrowed bytes. @param length Byte count. * @param address Optional user sockaddr. @param address_length Supplied sockaddr length. * @return Accepted bytes or negative errno. */ static int packet6_send(struct packet_socket *s, const void *data, uint32_t length, @@ -197,7 +208,7 @@ static int packet6_send(struct packet_socket *s, const void *data, uint32_t leng uint32_t scope = to.sin6_scope_id ? to.sin6_scope_id : (uint32_t)s->ifindex; if (!scope && to.sin6_addr.s6_addr[0] == 0xff) scope = s->multicast_if; struct net_ipv6_path path; - int ret = net_ipv6_route(NULL, &to.sin6_addr, scope, &s->local6, &path); + int ret = net_ipv6_route(s->net_ns, &to.sin6_addr, scope, &s->local6, &path); if (ret < 0) return ret; uint8_t *copy = kernel_malloc(length ? length : 1); if (!copy) return -LINUX_ENOMEM; @@ -214,13 +225,13 @@ static int packet6_send(struct packet_socket *s, const void *data, uint32_t leng copy[offset] = (uint8_t)(checksum >> 8); copy[offset + 1] = (uint8_t)checksum; } int hops = to.sin6_addr.s6_addr[0] == 0xff ? s->multicast_hops : s->unicast_hops; - ret = net_ipv6_output(NULL, &path, (uint8_t)s->protocol, copy, length, hops, to.sin6_flowinfo, + ret = net_ipv6_output(s->net_ns, &path, (uint8_t)s->protocol, copy, length, hops, to.sin6_flowinfo, s->dont_fragment || s->mtu_discover == IPV6_PMTUDISC_DO, s->multicast_loop); kernel_free(copy); return ret < 0 ? ret : (int)length; } -/** @brief Send a complete packet with native address validation. +/** @brief Send a complete packet using the OFD's retained network. * @param file Pinned socket description. * @param data Validated packet payload. * @param length Payload bytes. @@ -251,7 +262,7 @@ int task_packet_send(struct task_file *file, const void *data, uint32_t length, } if (!destination) return -LINUX_EDESTADDRREQ; if (destination == UINT32_MAX && !s->broadcast) return -LINUX_EACCES; - return net_ipv4_send_raw_on((uint32_t)s->ifindex, __builtin_bswap32(destination), __builtin_bswap32(s->local_ip), + return net_ipv4_send_raw_on(s->net_ns, (uint32_t)s->ifindex, __builtin_bswap32(destination), __builtin_bswap32(s->local_ip), (uint8_t)s->protocol, s->hdrincl, data, length); } struct sockaddr_ll to = {.sll_family = AF_PACKET, .sll_protocol = (uint16_t)s->protocol, .sll_ifindex = s->ifindex}; @@ -263,9 +274,9 @@ int task_packet_send(struct task_file *file, const void *data, uint32_t length, __builtin_memcpy(&to, (void *)(uintptr_t)address, sizeof(to)); if (to.sll_family != AF_PACKET) return -LINUX_EINVAL; } - if (to.sll_ifindex <= 0 || !net_interface_exists(NULL, (uint32_t)to.sll_ifindex)) return -LINUX_ENXIO; - if (to.sll_ifindex == 1) return -LINUX_EOPNOTSUPP; - if (!net_interface_is_ready(NULL, (uint32_t)to.sll_ifindex)) return -LINUX_ENETDOWN; + if (to.sll_ifindex <= 0 || !net_interface_exists(s->net_ns, (uint32_t)to.sll_ifindex)) return -LINUX_ENXIO; + if (to.sll_ifindex == NET_IF_LOOPBACK) return -LINUX_EOPNOTSUPP; + if (!net_interface_is_ready(s->net_ns, (uint32_t)to.sll_ifindex)) return -LINUX_ENETDOWN; uint8_t frame[1514]; uint32_t total = length; if (s->type == SOCK_DGRAM) { @@ -413,7 +424,7 @@ int task_packet_available(struct task_file *file) return !s ? -LINUX_EBADF : s->head ? (int)s->head->length : 0; } -/** @brief Free a final socket description and its bounded receive queue. +/** @brief Remove a final socket, release its multicast groups, queue and network. * @param file Owned description under the execution lock. */ void task_packet_release(struct task_file *file) @@ -423,14 +434,15 @@ void task_packet_release(struct task_file *file) for (unsigned i = 0; i < PACKET_LIMIT; ++i) if (sockets[i] == s) sockets[i] = NULL; for (unsigned i = 0; i < 16; ++i) if (s->groups[i].used) - (void)net_ipv6_multicast_change(NULL, &s->groups[i].address, s->groups[i].ifindex, -1); + (void)net_ipv6_multicast_change(s->net_ns, &s->groups[i].address, s->groups[i].ifindex, -1); while (s->head) { struct packet_message *m = s->head; s->head = m->next; kernel_free(m); } + net_namespace_put(s->net_ns); kernel_free(s); file->aux = 0; } -/** @brief Read or update a supported IPv6 raw-socket option. - * @param s Raw socket. @param set True for a setter. @param level Native option level. +/** @brief Read or update an IPv6 raw option in the retained creation network. + * @param s Raw socket owning its network. @param set True for a setter. @param level Native option level. * @param option Native option. * @param pointer User value. @param length_or_pointer Length or user socklen pointer. * @return Zero or negative errno. */ @@ -449,7 +461,8 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin __builtin_memcpy(&group, (void *)(uintptr_t)pointer, sizeof(group)); if (group.ipv6mr_multiaddr.s6_addr[0] != 0xff || group.ipv6mr_ifindex < 0) return -LINUX_EINVAL; uint32_t ifindex = group.ipv6mr_ifindex ? (uint32_t)group.ipv6mr_ifindex : s->multicast_if; - if (!ifindex) ifindex = s->ifindex ? (uint32_t)s->ifindex : netdev_next(0); + if (!ifindex) ifindex = s->ifindex ? (uint32_t)s->ifindex : + net_interface_next(s->net_ns, NET_IF_LOOPBACK); unsigned slot = 16, empty = 16; for (unsigned i = 0; i < 16; ++i) { if (!s->groups[i].used && empty == 16) empty = i; @@ -460,7 +473,7 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin if (join && slot != 16) return -LINUX_EADDRINUSE; if (!join && slot == 16) return -LINUX_EADDRNOTAVAIL; if (join && empty == 16) return -LINUX_ENOBUFS; - ret = net_ipv6_multicast_change(NULL, &group.ipv6mr_multiaddr, ifindex, join ? 1 : -1); + ret = net_ipv6_multicast_change(s->net_ns, &group.ipv6mr_multiaddr, ifindex, join ? 1 : -1); if (ret < 0) return ret; if (join) { s->groups[empty].address = group.ipv6mr_multiaddr; s->groups[empty].ifindex = ifindex; s->groups[empty].used = true; } else s->groups[slot].used = false; @@ -478,7 +491,7 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin s->checksum_offset = value < 0 ? -1 : value; break; case IPV6_UNICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->unicast_hops = value; break; case IPV6_MULTICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->multicast_hops = value; break; - case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists(NULL, (uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; + case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists(s->net_ns, (uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; case IPV6_MULTICAST_LOOP: if (value != 0 && value != 1) return -LINUX_EINVAL; s->multicast_loop = value != 0; break; case IPV6_RECVPKTINFO: s->recv_pktinfo = value != 0; break; case IPV6_RECVHOPLIMIT: s->recv_hoplimit = value != 0; break; @@ -505,7 +518,7 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin case IPV6_MTU: { if (!s->connected6) return -LINUX_ENOTCONN; struct net_ipv6_path path; - int ret = net_ipv6_route(NULL, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path); + int ret = net_ipv6_route(s->net_ns, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path); if (ret < 0) return ret; value = (int)path.mtu; break; } @@ -528,7 +541,8 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin * @param a4 Fifth native argument. * @param a5 Sixth native argument. * @return Native result or negative errno; unsupported options are not accepted. - * Packet socket creation requires CAP_NET_RAW in the initial user namespace. + * Creation checks CAP_NET_RAW in the creating network's user owner. Installed + * OFDs retain that network for address, option and data operations after transfer. */ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) @@ -542,7 +556,8 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (type != SOCK_RAW && !((int)a0 == AF_PACKET && type == SOCK_DGRAM) && !((int)a0 == AF_INET6 && type == SOCK_DGRAM && (int)a2 == IPPROTO_ICMPV6)) return -LINUX_ESOCKTNOSUPPORT; if (((int)a0 == AF_INET || (int)a0 == AF_INET6) && ((int)a2 <= 0 || (int)a2 > 255)) return -LINUX_EPROTONOSUPPORT; - if (!(task_initial_capabilities(task) & (1ULL << CAP_NET_RAW))) return -LINUX_EPERM; + if (!task_ns_capable(task, task->net_ns ? task->net_ns->user_ns : NULL, CAP_NET_RAW)) + return -LINUX_EPERM; unsigned index = 0; while (index < PACKET_LIMIT && sockets[index]) ++index; if (index == PACKET_LIMIT) return -LINUX_ENFILE; @@ -551,7 +566,8 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, struct task_file *file; int fd = task_allocate_fd(task, 0, &file); if (fd < 0) { kernel_free(s); return fd; } - *s = (struct packet_socket){.domain = (int)a0, .type = type, .protocol = (int)a2, + *s = (struct packet_socket){.net_ns = net_namespace_get(task->net_ns), + .domain = (int)a0, .type = type, .protocol = (int)a2, .uid = task->euid, .ino = (4ULL << 60) | ++packet_ino, .hdrincl = (int)a0 == AF_INET && (int)a2 == 255, .checksum_offset = ((int)a0 == AF_INET6 && (int)a2 == IPPROTO_ICMPV6) ? 2 : -1, @@ -562,7 +578,8 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, for (unsigned tries = 0; tries < 65535; ++tries) { bool used = false; for (unsigned i = 0; i < PACKET_LIMIT; ++i) - if (sockets[i] && sockets[i]->domain == AF_INET6 && sockets[i]->type == SOCK_DGRAM && sockets[i]->ping_id == id) used = true; + if (sockets[i] && sockets[i]->net_ns == s->net_ns && sockets[i]->domain == AF_INET6 && + sockets[i]->type == SOCK_DGRAM && sockets[i]->ping_id == id) used = true; if (!used) break; if (++id == 0) id = 1; } @@ -588,7 +605,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, a1 == SOL_SOCKET && a2 == SO_BINDTODEVICE) { uint32_t index = (uint32_t)s->ifindex; bool set = number == __NR_setsockopt; - int result = net_interface_device_option(NULL, set, a3, a4, &index); + int result = net_interface_device_option(s->net_ns, set, a3, a4, &index); if (!result && set) s->ifindex = (int)index; return result; } @@ -602,7 +619,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, __builtin_memcpy(&address, (void *)(uintptr_t)a1, sizeof(address)); if (address.sll_family != AF_PACKET) return -LINUX_EINVAL; if (address.sll_ifindex < 0 || (address.sll_ifindex && - !net_interface_exists(NULL, (uint32_t)address.sll_ifindex))) return -LINUX_ENODEV; + !net_interface_exists(s->net_ns, (uint32_t)address.sll_ifindex))) return -LINUX_ENODEV; s->ifindex = address.sll_ifindex; s->protocol = address.sll_protocol; } else if (s->domain == AF_INET6) { @@ -611,7 +628,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (ret < 0) return ret; if (number == __NR_bind && !net_ipv6_needs_scope_id(&address.sin6_addr)) address.sin6_scope_id = 0; - if (address.sin6_scope_id && !net_interface_exists(NULL, address.sin6_scope_id)) return -LINUX_ENODEV; + if (address.sin6_scope_id && !net_interface_exists(s->net_ns, address.sin6_scope_id)) return -LINUX_ENODEV; if (address.sin6_scope_id && s->ifindex && address.sin6_scope_id != (uint32_t)s->ifindex) return -LINUX_EINVAL; if (number == __NR_connect) { @@ -622,12 +639,12 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (s->type == SOCK_DGRAM && address.sin6_port) { uint16_t id = __builtin_bswap16(address.sin6_port); for (unsigned i = 0; i < PACKET_LIMIT; ++i) - if (sockets[i] && sockets[i] != s && sockets[i]->domain == AF_INET6 && + if (sockets[i] && sockets[i] != s && sockets[i]->net_ns == s->net_ns && sockets[i]->domain == AF_INET6 && sockets[i]->type == SOCK_DGRAM && sockets[i]->ping_id == id) return -LINUX_EADDRINUSE; s->ping_id = id; } if (!packet6_any(&address.sin6_addr) && address.sin6_addr.s6_addr[0] != 0xff) { - struct net_ipv6_address entries[32]; uint32_t count = net_ipv6_addresses(NULL, entries, 32); bool found = false; + struct net_ipv6_address entries[32]; uint32_t count = net_ipv6_addresses(s->net_ns, entries, 32); bool found = false; for (uint32_t i = 0; i < count && i < 32; ++i) if (!__builtin_memcmp(&entries[i].address, &address.sin6_addr, sizeof(address.sin6_addr)) && !(entries[i].flags & (NET_IPV6_ADDR_TENTATIVE | NET_IPV6_ADDR_DADFAILED)) && @@ -645,7 +662,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (address.sin_family != AF_INET) return -LINUX_EAFNOSUPPORT; if (number == __NR_connect) s->remote_ip = address.sin_addr.s_addr; else { - if (address.sin_addr.s_addr && !net_interface_for_ipv4(NULL, __builtin_bswap32(address.sin_addr.s_addr))) + if (address.sin_addr.s_addr && !net_interface_for_ipv4(s->net_ns, __builtin_bswap32(address.sin_addr.s_addr))) return -LINUX_EADDRNOTAVAIL; s->local_ip = address.sin_addr.s_addr; } @@ -662,7 +679,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (number == __NR_getsockname && s->type == SOCK_DGRAM) address.sin6_port = __builtin_bswap16(s->ping_id); if (number == __NR_getsockname && s->connected6 && packet6_any(&address.sin6_addr)) { struct net_ipv6_path path; - if (!net_ipv6_route(NULL, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path)) address.sin6_addr = path.source; + if (!net_ipv6_route(s->net_ns, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path)) address.sin6_addr = path.source; } if (length > sizeof(address)) length = sizeof(address); ret = socket_user_prepare(task, a1, length, true); if (ret) return ret; @@ -769,10 +786,9 @@ void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex, const if (protocol == 6) net_tcp6_error_on(ns, ifindex, &source, &destination, source_port, destination_port, error, mtu); else if (protocol == 17) net_udp6_error_on(ns, ifindex, &source, &destination, source_port, destination_port, error, mtu); } - if (ns) return; for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *s = sockets[i]; - if (!s || s->domain != AF_INET6 || s->protocol != protocol || + if (!s || s->net_ns != ns || s->domain != AF_INET6 || s->protocol != protocol || (ifindex && ((s->ifindex && (uint32_t)s->ifindex != ifindex) || (s->scope6 && s->scope6 != ifindex) || (s->remote_scope6 && s->remote_scope6 != ifindex))) || @@ -783,15 +799,16 @@ void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex, const kernel_poll_readiness_notify(); } -/** @brief Render raw IPv6 endpoints with their actual receive queue sizes. +/** @brief Render one network's raw IPv6 endpoints and receive queue sizes. + * @param ns Borrowed network, NULL for the permanent initial network. * @param stream Caller-owned proc output. */ -static void net_raw6_proc_emit(struct text_stream *stream) +static void net_raw6_proc_emit(struct net_namespace *ns, struct text_stream *stream) { text_string(stream," sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n"); unsigned index = 0; for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *s = sockets[i]; - if (!s || s->domain != AF_INET6) continue; + if (!s || s->net_ns != ns || s->domain != AF_INET6) continue; uint64_t queued = 0; for (struct packet_message *m = s->head; m; m = m->next) queued += m->length; text_unsigned(stream,index++); text_string(stream,": "); for (unsigned j = 0; j < 16; j += 4) { uint32_t word; __builtin_memcpy(&word,s->local6.s6_addr+j,4); text_hex(stream,word,8); } @@ -803,20 +820,25 @@ static void net_raw6_proc_emit(struct text_stream *stream) } } -/** @brief Emit the selected standard proc IPv6 transport view. - * @param stream Caller-owned output slice. @param leaf Requested basename. */ +/** @copydoc net_ipv6_transport_proc_emit_on */ +void net_ipv6_transport_proc_emit_on(struct net_namespace *ns, struct text_stream *stream, const char *leaf) +{ + if (!__builtin_strcmp(leaf,"tcp6")) net_tcp6_proc_emit(ns, stream); + else if (!__builtin_strcmp(leaf,"udp6")) net_udp6_proc_emit(ns, stream); + else if (!__builtin_strcmp(leaf,"raw6")) net_raw6_proc_emit(ns, stream); +} + +/** @copydoc net_ipv6_transport_proc_emit */ void net_ipv6_transport_proc_emit(struct text_stream *stream, const char *leaf) { - if (!__builtin_strcmp(leaf,"tcp6")) net_tcp6_proc_emit(NULL, stream); - else if (!__builtin_strcmp(leaf,"udp6")) net_udp6_proc_emit(NULL, stream); - else if (!__builtin_strcmp(leaf,"raw6")) net_raw6_proc_emit(stream); + net_ipv6_transport_proc_emit_on(NULL, stream, leaf); } /** @brief Deliver a frame for the primary compatibility interface. * @param input Borrowed Ethernet frame. @param length Complete frame length. */ void net_packet_input(const void *input, uint32_t length) { - net_packet_input_on(netdev_next(0), input, length); + net_packet_input_on(NULL, netdev_next(0), input, length); } /** @brief Forward a compatibility ICMPv6 error without a link filter. @@ -825,13 +847,13 @@ void net_ipv6_socket_error(const uint8_t *packet, uint32_t length, int error, ui { net_ipv6_socket_error_on(NULL, 0, packet, length, error, mtu); } -/** @brief Wake raw endpoints explicitly bound to a removed NIC. +/** @brief Wake initial-network raw endpoints bound to a removed physical NIC. * @param ifindex Removed interface index. */ void net_packet_device_detached(uint32_t ifindex) { for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *socket = sockets[i]; - if (socket && ((uint32_t)socket->ifindex == ifindex || socket->scope6 == ifindex || + if (socket && !socket->net_ns && ((uint32_t)socket->ifindex == ifindex || socket->scope6 == ifindex || socket->remote_scope6 == ifindex)) socket->error = LINUX_ENETDOWN; } kernel_poll_readiness_notify(); diff --git a/tools/test_net_multinic_data.py b/tools/test_net_multinic_data.py index 89ec33c6..a538fb41 100644 --- a/tools/test_net_multinic_data.py +++ b/tools/test_net_multinic_data.py @@ -18,6 +18,8 @@ def main(): "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude/uapi", f"tools/tests/{name}_test.c", + *(["net/namespace/namespace.c", "net/ipv6/state.c", + "kernel/sched/user_namespace.c"] if name == "net_packet" else []), "-o", str(binary)], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=15) diff --git a/tools/test_openrc_network.py b/tools/test_openrc_network.py index 42ad5ba1..bdd64ef0 100644 --- a/tools/test_openrc_network.py +++ b/tools/test_openrc_network.py @@ -14,6 +14,8 @@ def main(): "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", f"tools/tests/{name}_test.c", + *(["net/namespace/namespace.c", "net/ipv6/state.c", + "kernel/sched/user_namespace.c"] if name == "net_packet" else []), *(["kernel/time/time_discipline.c"] if name == "timekeeper_discipline" else []), "-o", str(binary)], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=15) diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 50cf7ffc..d100234c 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -79,9 +79,13 @@ void net_loopback_proc_emit(struct net_namespace *ns, struct text_stream *stream void net_arp_proc_emit(struct text_stream *stream) { (void)stream; } void net_udp_proc_emit(struct net_namespace *ns, struct text_stream *stream) { (void)ns; (void)stream; } void net_udp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) { (void)ns; (void)stream; } +void net_tcp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) +{ (void)ns; text_string(stream,"tcp6\n"); } void unix_proc_emit(struct text_stream *stream) { (void)stream; } void net_ipv6_transport_proc_emit(struct text_stream *stream,const char *leaf) { text_string(stream,leaf); text_string(stream,"\n"); } +void net_ipv6_transport_proc_emit_on(struct net_namespace *ns, struct text_stream *stream,const char *leaf) +{ (void)ns; text_string(stream,leaf); text_string(stream,"\n"); } uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out, uint32_t capacity) { for (unsigned i = 0; ns && i < 2; ++i) { diff --git a/tools/tests/ipv6_protocol_test.c b/tools/tests/ipv6_protocol_test.c index 1805d1f8..fd008a17 100644 --- a/tools/tests/ipv6_protocol_test.c +++ b/tools/tests/ipv6_protocol_test.c @@ -158,8 +158,8 @@ int netdev_poll_notified(uint32_t index,void *frame,uint32_t capacity,uint32_t * { return netdev_poll(index,frame,capacity,len); } /** @brief Ignore packet socket mirroring. @param frame Bytes. @param length Byte length. */ void net_packet_input(const void *frame,uint32_t length) { (void)frame;(void)length; } -void net_packet_input_on(uint32_t index,const void *frame,uint32_t length) -{ (void)index;net_packet_input(frame,length); } +void net_packet_input_on(struct net_namespace *ns,uint32_t index,const void *frame,uint32_t length) +{ (void)ns;(void)index;net_packet_input(frame,length); } /** @brief Ignore ARP for this fixture. @param frame Bytes. @param length Length. @param wait Waiter. */ void net_handle_arp(const uint8_t *frame,uint32_t length,struct net_arp_wait *wait) { (void)frame;(void)length;(void)wait; } diff --git a/tools/tests/ipv6_transport_test.c b/tools/tests/ipv6_transport_test.c index 8f9aea46..605a2d14 100644 --- a/tools/tests/ipv6_transport_test.c +++ b/tools/tests/ipv6_transport_test.c @@ -205,9 +205,120 @@ static void test_udp6_namespace_bind(bool mapped) "PASS IPv6 UDP creating-net delivery, proc, down-lo, ICMPv6 errors and references"); } +static void close_packet(int fd) +{ + task_packet_release(&files[fd]); + files[fd].used = 0; +} + +static void test_raw6_creating_network(void) +{ + struct task saved = current; + unsigned baseline = allocations; + struct net_namespace *spaces[2]; + int raw[3], ping[3]; + struct sockaddr_in6 address = {.sin6_family = AF_INET6, .sin6_addr = loop6}; + current.cap_effective |= 1ULL << CAP_NET_RAW; + for (unsigned i = 0; i < 3; ++i) { + if (i < 2) { + assert(!net_namespace_create(NULL, &spaces[i])); + enable_loopback(spaces[i]); + } + current.net_ns = i < 2 ? spaces[i] : NULL; + raw[i] = (int)syscall_packet(__NR_socket, AF_INET6, SOCK_RAW | SOCK_NONBLOCK, + IPPROTO_ICMPV6, 0, 0, 0); + ping[i] = (int)syscall_packet(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, + IPPROTO_ICMPV6, 0, 0, 0); + assert(raw[i] >= 0 && ping[i] >= 0); + assert(task_packet_namespace(&files[raw[i]]) == current.net_ns); + assert(task_packet_namespace(&files[ping[i]]) == current.net_ns); + address.sin6_port = 0; + assert(!syscall_packet(__NR_bind, raw[i], (uintptr_t)&address, sizeof(address), 0, 0, 0)); + address.sin6_port = swap16(55300); + assert(!syscall_packet(__NR_bind, ping[i], (uintptr_t)&address, sizeof(address), 0, 0, 0)); + assert(!syscall_packet(__NR_connect, raw[i], (uintptr_t)&address, sizeof(address), 0, 0, 0)); + assert(!syscall_packet(__NR_connect, ping[i], (uintptr_t)&address, sizeof(address), 0, 0, 0)); + } + current.net_ns = spaces[0]; + int conflict = (int)syscall_packet(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, + IPPROTO_ICMPV6, 0, 0, 0); + assert(conflict >= 0); + assert(syscall_packet(__NR_bind, conflict, (uintptr_t)&address, sizeof(address), 0, 0, 0) == -LINUX_EADDRINUSE); + close_packet(conflict); + for (unsigned i = 0; i < 2; ++i) { + current.net_ns = spaces[1 - i]; + const char physical[] = "eth0", loopback[] = "lo"; + assert(syscall_packet(__NR_setsockopt, raw[i], SOL_SOCKET, SO_BINDTODEVICE, + (uintptr_t)physical, sizeof(physical), 0) == -LINUX_ENODEV); + assert(!syscall_packet(__NR_setsockopt, raw[i], SOL_SOCKET, SO_BINDTODEVICE, + (uintptr_t)loopback, sizeof(loopback), 0)); + uint8_t echo[8] = {128}; + assert(task_packet_send(&files[raw[i]], echo, sizeof(echo), 0, 0, 0) == 8); + assert(task_packet_available(&files[raw[i]]) == 8); + assert(!task_packet_available(&files[raw[1 - i]]) && !task_packet_available(&files[raw[2]])); + char data[16]; + assert(task_packet_recv(&files[raw[i]], data, sizeof(data), 0, 0, 0) == 8); + assert(task_packet_send(&files[ping[i]], echo, sizeof(echo), 0, 0, 0) == 8); + assert(task_packet_recv(&files[raw[i]], data, sizeof(data), 0, 0, 0) == 8); + assert((unsigned char)data[4] == (55300 >> 8) && (unsigned char)data[5] == (55300 & 255)); + uint8_t reply[8] = {129, 0, 0, 0, 55300 >> 8, 55300 & 255}; + net_raw6_input(spaces[i], &loop6, &loop6, IPPROTO_ICMPV6, reply, sizeof(reply), 1, 64); + assert(task_packet_available(&files[ping[i]]) == 8); + assert(!task_packet_available(&files[ping[1 - i]]) && !task_packet_available(&files[ping[2]])); + assert(task_packet_recv(&files[ping[i]], data, sizeof(data), 0, 0, 0) == 8); + assert(task_packet_recv(&files[raw[i]], data, sizeof(data), 0, 0, 0) == 8); + current.net_ns = spaces[i]; + check_proc_socket("raw6", raw[i], raw[1 - i]); + check_proc_socket("raw6", ping[i], ping[1 - i]); + spaces[i]->loopback.up = false; + assert(task_packet_send(&files[raw[i]], echo, sizeof(echo), 0, 0, 0) == -LINUX_ENETDOWN); + assert(!task_packet_available(&files[raw[i]])); + spaces[i]->loopback.up = true; + } + uint8_t quote[48] = {0x60}; + quote[6] = IPPROTO_ICMPV6; + memcpy(quote + 8, &loop6, 16); + memcpy(quote + 24, &loop6, 16); + quote[40] = 128; + quote[44] = 55300 >> 8; + quote[45] = 55300 & 255; + current.net_ns = spaces[1]; + net_ipv6_socket_error_on(spaces[0], 1, quote, sizeof(quote), LINUX_EHOSTUNREACH, 0); + char data[16]; + assert(task_packet_recv(&files[raw[0]], data, sizeof(data), 0, 0, 0) == -LINUX_EHOSTUNREACH); + assert(task_packet_recv(&files[ping[0]], data, sizeof(data), 0, 0, 0) == -LINUX_EHOSTUNREACH); + assert(task_packet_recv(&files[raw[1]], data, sizeof(data), 0, 0, 0) == -LINUX_EAGAIN); + assert(task_packet_recv(&files[ping[1]], data, sizeof(data), 0, 0, 0) == -LINUX_EAGAIN); + net_packet_device_detached(1); + assert(task_packet_recv(&files[raw[0]], data, sizeof(data), 0, 0, 0) == -LINUX_EAGAIN); + current.net_ns = NULL; + char output[4096] = {0}, identity[64]; + struct text_stream stream = {.buffer = output, .capacity = sizeof(output) - 1}; + net_ipv6_transport_proc_emit(&stream, "raw6"); + snprintf(identity, sizeof(identity), " 0 %llu\n", (unsigned long long)files[raw[2]].socket_ino); + assert(strstr(output, identity)); + snprintf(identity, sizeof(identity), " 0 %llu\n", (unsigned long long)files[raw[0]].socket_ino); + assert(!strstr(output, identity)); + for (unsigned i = 0; i < 3; ++i) { + struct net_namespace *ns = i < 2 ? spaces[i] : NULL; + uint8_t reply[8] = {129, 0, 0, 0, 55300 >> 8, 55300 & 255}; + net_raw6_input(ns, &loop6, &loop6, IPPROTO_ICMPV6, reply, sizeof(reply), 1, 64); + if (ns) { + assert(ns->references == 3); + net_namespace_put(ns); + } + close_packet(raw[i]); + close_packet(ping[i]); + } + current = saved; + assert(allocations == baseline); + puts("PASS raw IPv6/ping creating-net same ID, OFD output, input, proc, errors and retained release"); +} + int main(void) { current.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; + test_raw6_creating_network(); test_udp6_namespace_bind(false); test_udp6_namespace_bind(true); test_udp_namespace_failures_and_owner(AF_INET6); @@ -333,6 +444,6 @@ int main(void) const uint8_t *netdev_mac(uint32_t index) { (void)index; return e1000_mac(); } int netdev_send(uint32_t index, const void *frame, uint32_t length) { (void)index; return e1000_send(frame, length); } -int net_ipv4_send_raw_on(uint32_t index, uint32_t destination, uint32_t source, +int net_ipv4_send_raw_on(struct net_namespace *ns, uint32_t index, uint32_t destination, uint32_t source, uint8_t protocol, bool hdrincl, const void *data, uint32_t length) -{ (void)index; return net_ipv4_send_raw(destination,source,protocol,hdrincl,data,length); } +{ (void)index; if (ns) return -LINUX_ENETUNREACH; return net_ipv4_send_raw(destination,source,protocol,hdrincl,data,length); } diff --git a/tools/tests/net_packet_test.c b/tools/tests/net_packet_test.c index 95504afd..c7bc93cf 100644 --- a/tools/tests/net_packet_test.c +++ b/tools/tests/net_packet_test.c @@ -2,17 +2,32 @@ #include #include #include +#include +#include #include "../../net/socket/packet.c" #include "../../net/interface/socket.c" static struct task current; static struct task_file description; static uint8_t sent[1514]; static uint32_t sent_length; +static unsigned allocations; +static int allocation_fail_after = -1; +static bool fail_fd; struct task *sched_current_task(void) { return ¤t; } -void *kernel_malloc(size_t n) { return malloc(n); } -void kernel_free(void *p) { free(p); } +void *kernel_malloc(size_t n) +{ + if (allocation_fail_after == 0) return NULL; + if (allocation_fail_after > 0) --allocation_fail_after; + void *p = calloc(1, n); + if (p) ++allocations; + return p; +} +void kernel_free(void *p) +{ + if (p) { assert(allocations); --allocations; free(p); } +} int task_allocate_fd(struct task *t, int minimum, struct task_file **f) -{ (void)t; (void)minimum; *f = &description; return 3; } +{ (void)t; (void)minimum; if (fail_fd) return -LINUX_EMFILE; *f = &description; return 3; } struct task_file *task_file_for_fd(struct task *t, int fd) { (void)t; return fd == 3 ? &description : NULL; } bool user_range_ok(uint64_t p, uint64_t n) { return p >= 4096 && n < 65536; } @@ -42,24 +57,150 @@ int e1000_send(const void *p, uint32_t n) { assert(n <= sizeof(sent)); memcpy(se int net_get_config(struct reliefos_net_config *c) { *c=(struct reliefos_net_config){0}; return 0; } int net_ipv4_send_raw(uint32_t d, uint32_t s, uint8_t p, bool h, const void *b, uint32_t n) { (void)d; (void)s; (void)p; (void)h; (void)b; return n; } -bool net_interface_exists(struct net_namespace *ns, uint32_t index) { return index >= 1 && index <= 3; } -bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return index >= 2 && index <= 3; } +bool net_interface_exists(struct net_namespace *ns, uint32_t index) { return index == 1 || (!ns && index >= 2 && index <= 3); } +bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return net_interface_exists(ns, index) && (ns ? ns->loopback.up : index >= 2); } uint32_t net_interface_index(struct net_namespace *ns, const char *name) -{ return !strcmp(name,"lo") ? 1 : !strcmp(name,"eth0") ? 2 : !strcmp(name,"eth1") ? 3 : 0; } +{ return !strcmp(name,"lo") ? 1 : ns ? 0 : !strcmp(name,"eth0") ? 2 : !strcmp(name,"eth1") ? 3 : 0; } bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[16]) -{ if (!net_interface_exists(NULL, index)) return false; strcpy(out,index == 1 ? "lo" : index == 2 ? "eth0" : "eth1"); return true; } +{ if (!net_interface_exists(ns, index)) return false; strcpy(out,index == 1 ? "lo" : index == 2 ? "eth0" : "eth1"); return true; } uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip) { return (ip >> 24) == 127 ? 1 : 0; } uint32_t netdev_next(uint32_t after) { return after < 2 ? 2 : after == 2 ? 3 : 0; } +uint32_t net_interface_next(struct net_namespace *ns, uint32_t after) +{ return after < NET_IF_LOOPBACK ? NET_IF_LOOPBACK : ns ? 0 : netdev_next(after); } const uint8_t *netdev_mac(uint32_t index) { static const uint8_t macs[2][6] = {{2,3,4,5,6,7},{2,3,4,5,6,8}}; return macs[index == 3]; } static uint32_t sent_interface; int netdev_send(uint32_t index, const void *data, uint32_t length) { sent_interface = index; return e1000_send(data, length); } -int net_ipv4_send_raw_on(uint32_t index, uint32_t d, uint32_t s, uint8_t p, +int net_ipv4_send_raw_on(struct net_namespace *ns, uint32_t index, uint32_t d, uint32_t s, uint8_t p, bool h, const void *data, uint32_t length) -{ (void)index; return net_ipv4_send_raw(d,s,p,h,data,length); } +{ (void)index; if (ns) return -LINUX_ENETUNREACH; return net_ipv4_send_raw(d,s,p,h,data,length); } +static void test_packet_namespace_owner(void) +{ + struct task saved = current; + unsigned baseline = allocations; + struct user_namespace *owner, *sibling; + struct net_namespace *ns; + assert(!user_namespace_create(¤t, &owner)); + assert(!user_namespace_create(¤t, &sibling)); + assert(!net_namespace_create(owner, &ns)); + const int families[] = {AF_INET, AF_INET6, AF_PACKET, AF_INET6}; + for (unsigned i = 0; i < 4; ++i) { + int type = i == 3 ? SOCK_DGRAM : SOCK_RAW; + int protocol = i == 3 ? IPPROTO_ICMPV6 : 1; + current.user_ns = owner; + current.net_ns = ns; + current.cap_effective = 1ULL << CAP_NET_RAW; + unsigned before = allocations; + allocation_fail_after = 0; + assert(syscall_packet(__NR_socket, families[i], type, protocol, 0, 0, 0) == -LINUX_ENOMEM); + allocation_fail_after = -1; + assert(allocations == before && ns->references == 1); + fail_fd = true; + assert(syscall_packet(__NR_socket, families[i], type, protocol, 0, 0, 0) == -LINUX_EMFILE); + fail_fd = false; + assert(allocations == before && ns->references == 1); + assert(syscall_packet(__NR_socket, families[i], type, protocol, 0, 0, 0) == 3); + assert(task_packet_namespace(&description) == ns && ns->references == 2); + task_packet_release(&description); + assert(ns->references == 1 && allocations == before); + current.user_ns = sibling; + assert(syscall_packet(__NR_socket, families[i], type, protocol, 0, 0, 0) == -LINUX_EPERM); + current.user_ns = owner; + current.cap_effective = 0; + assert(syscall_packet(__NR_socket, families[i], type, protocol, 0, 0, 0) == -LINUX_EPERM); + current.cap_effective = 1ULL << CAP_NET_RAW; + current.net_ns = NULL; + assert(syscall_packet(__NR_socket, families[i], type, protocol, 0, 0, 0) == -LINUX_EPERM); + } + current = saved; + net_namespace_put(ns); + user_namespace_put(owner); + user_namespace_put(sibling); + assert(allocations == baseline); + puts("PASS raw/AF_PACKET owner CAP_NET_RAW, ENOMEM/EMFILE and namespace release"); +} + +static void test_packet_creating_network(int family) +{ + struct task saved = current; + unsigned baseline = allocations; + struct net_namespace *spaces[2]; + struct task_file endpoints[3]; + current.cap_effective = 1ULL << CAP_NET_RAW; + for (unsigned i = 0; i < 3; ++i) { + if (i < 2) { + assert(!net_namespace_create(NULL, &spaces[i])); + spaces[i]->loopback.up = true; + } + current.net_ns = i < 2 ? spaces[i] : NULL; + assert(syscall_packet(__NR_socket, family, SOCK_RAW | SOCK_NONBLOCK, + family == AF_PACKET ? 8 : 1, 0, 0, 0) == 3); + endpoints[i] = description; + assert(task_packet_namespace(&endpoints[i]) == current.net_ns); + } + uint8_t frame[42] = {0}; + frame[12] = 8; + frame[14] = 0x45; + frame[17] = 28; + frame[23] = 1; + frame[26] = frame[30] = 127; + frame[29] = frame[33] = 1; + frame[34] = 8; + current.net_ns = NULL; + net_packet_input(frame, sizeof(frame)); + assert(!task_packet_available(&endpoints[0]) && !task_packet_available(&endpoints[1])); + assert(task_packet_available(&endpoints[2]) == (int)(family == AF_PACKET ? 42 : 28)); + uint8_t received[64]; + assert(task_packet_recv(&endpoints[2], received, sizeof(received), 0, 0, 0) > 0); + for (unsigned i = 0; i < 2; ++i) { + description = endpoints[i]; + current.net_ns = spaces[1 - i]; + const char physical[] = "eth0", loopback[] = "lo"; + assert(syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_BINDTODEVICE, + (uintptr_t)physical, sizeof(physical), 0) == -LINUX_ENODEV); + assert(!syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_BINDTODEVICE, + (uintptr_t)loopback, sizeof(loopback), 0)); + assert(packet_of(&description)->ifindex == 1); + net_packet_device_detached(1); + assert(!packet_of(&description)->error); + allocation_fail_after = 0; + net_packet_input_on(spaces[i], 1, frame, sizeof(frame)); + allocation_fail_after = -1; + assert(!task_packet_available(&description) && spaces[i]->references == 2); + net_packet_input_on(spaces[i], 1, frame, sizeof(frame)); + assert(task_packet_available(&description) == (int)(family == AF_PACKET ? 42 : 28)); + assert(!task_packet_available(&endpoints[1 - i]) && !task_packet_available(&endpoints[2])); + assert(task_packet_recv(&description, received, sizeof(received), 0, 0, 0) > 0); + assert(!task_packet_available(&description)); + if (family == AF_PACKET) { + struct sockaddr_ll destination = {.sll_family = AF_PACKET, .sll_ifindex = 1}; + assert(task_packet_send(&description, frame, sizeof(frame), 0, + (uintptr_t)&destination, sizeof(destination)) == -LINUX_EOPNOTSUPP); + } else { + struct sockaddr_in destination = {.sin_family = AF_INET, + .sin_addr.s_addr = __builtin_bswap32(0x7f000001)}; + assert(task_packet_send(&description, "raw", 3, 0, + (uintptr_t)&destination, sizeof(destination)) == -LINUX_ENETUNREACH); + } + } + for (unsigned i = 0; i < 2; ++i) { + net_packet_input_on(spaces[i], 1, frame, sizeof(frame)); + assert(task_packet_available(&endpoints[i]) > 0); + net_namespace_put(spaces[i]); + task_packet_release(&endpoints[i]); + } + task_packet_release(&endpoints[2]); + current = saved; + assert(allocations == baseline); + puts("PASS IPv4 raw/AF_PACKET creating-net ingress, OFD device scope, detach and queued release"); +} + int main(void) { + test_packet_namespace_owner(); + test_packet_creating_network(AF_INET); + test_packet_creating_network(AF_PACKET); assert(syscall_packet(__NR_socket, AF_PACKET, SOCK_DGRAM, 8,0,0,0) == -LINUX_EPERM); current.cap_effective = 1ULL << CAP_NET_RAW; assert(syscall_packet(__NR_socket, AF_PACKET, SOCK_DGRAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 8,0,0,0) == 3); @@ -73,9 +214,9 @@ int main(void) const char second[] = "second link"; assert(task_packet_send(&description,second,sizeof(second),0,(uintptr_t)&dest,sizeof(dest)) == sizeof(second)); assert(sent_interface == 3 && !memcmp(sent+6,netdev_mac(3),6)); - net_packet_input_on(2,sent,sent_length); + net_packet_input_on(NULL,2,sent,sent_length); assert(task_packet_available(&description) == 0); - net_packet_input_on(3,sent,sent_length); + net_packet_input_on(NULL,3,sent,sent_length); struct sockaddr_ll ingress; uint32_t ingress_length=sizeof(ingress); char second_out[sizeof(second)]; assert(task_packet_recv(&description,second_out,sizeof(second_out),0,(uintptr_t)&ingress,(uintptr_t)&ingress_length) == sizeof(second)); assert(ingress.sll_ifindex == 3 && !memcmp(second_out,second,sizeof(second))); diff --git a/tools/tests/net_rx_budget_test.c b/tools/tests/net_rx_budget_test.c index 3ff9d9c3..2830ff66 100644 --- a/tools/tests/net_rx_budget_test.c +++ b/tools/tests/net_rx_budget_test.c @@ -29,8 +29,8 @@ int netdev_poll(uint32_t id,void *frame,uint32_t capacity,uint32_t *length) } int netdev_poll_notified(uint32_t id,void *frame,uint32_t capacity,uint32_t *length) { return netdev_poll(id,frame,capacity,length); } -void net_packet_input_on(uint32_t id,const void *frame,uint32_t length) -{ assert(frame && length==64); ++delivered[id-2]; } +void net_packet_input_on(struct net_namespace *ns, uint32_t id,const void *frame,uint32_t length) +{ assert(!ns); assert(frame && length==64); ++delivered[id-2]; } int net_frame_for_us_on(uint32_t id,const uint8_t *frame) { (void)id;(void)frame;return 0; } uint16_t net_get_u16(const uint8_t *data) { return (uint16_t)data[0]<<8|data[1]; } void net_handle_arp_on(uint32_t id,const uint8_t *p,uint32_t n,struct net_arp_wait *w) diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 37ea14d6..3265d2a1 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -1547,6 +1547,9 @@ "{tmp}/packet-user-candidate-1.1.o", "tools/tests/task8_host_stubs/packet-user-candidate-1-packet-user-candidate-1.stub.c", "tools/tests/task8_host_stubs/no_prlimit_identity.c", + "net/namespace/namespace.c", + "net/ipv6/state.c", + "kernel/sched/user_namespace.c", "-o", "{tmp}/packet-user-candidate-1" ] @@ -4597,6 +4600,8 @@ "tools/tests/task8_host_stubs/packet_tcp_unreached.c", "tools/tests/task8_host_stubs/fix1-packet-front-unreached.c", "kernel/sched/user_namespace.c", + "net/namespace/namespace.c", + "net/ipv6/state.c", "-o", "{tmp}/fix1-inet-packet-probe" ] diff --git a/tools/tests/task8_host_stubs/fix1-packet-front-unreached.c b/tools/tests/task8_host_stubs/fix1-packet-front-unreached.c index e61e8dc6..01d230d7 100644 --- a/tools/tests/task8_host_stubs/fix1-packet-front-unreached.c +++ b/tools/tests/task8_host_stubs/fix1-packet-front-unreached.c @@ -17,8 +17,6 @@ __attribute__((noreturn)) void kernel_object_remove(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void kernel_objects(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ -__attribute__((noreturn)) void kernel_poll_readiness_notify(void) { __builtin_trap(); } -/** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void kernel_wait_queue_add(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void kernel_wait_queue_init(void) { __builtin_trap(); } @@ -102,3 +100,17 @@ __attribute__((noreturn)) void task_pty_release_entry(void) { __builtin_trap(); __attribute__((noreturn)) void task_udp_send(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void vfs_system_namespace(void) { __builtin_trap(); } + +#define UNREACHED(name) __attribute__((noreturn)) void name(void) { __builtin_trap(); } +UNREACHED(clear_task_file) +UNREACHED(proc_account_file) +UNREACHED(syscall_netlink) +UNREACHED(task_netlink_cancel_wait) +UNREACHED(task_netlink_passcred) +UNREACHED(task_netlink_pktinfo) +UNREACHED(task_netlink_recv) +UNREACHED(task_netlink_recv_staged) +UNREACHED(task_netlink_send) +UNREACHED(task_udp_address_size) +UNREACHED(task_udp_recv_ex) +UNREACHED(time_clock_get) diff --git a/tools/tests/task8_host_stubs/packet_tcp_unreached.c b/tools/tests/task8_host_stubs/packet_tcp_unreached.c index 6039d37b..17cd4d52 100644 --- a/tools/tests/task8_host_stubs/packet_tcp_unreached.c +++ b/tools/tests/task8_host_stubs/packet_tcp_unreached.c @@ -7,3 +7,18 @@ UNREACHED(net_socket_recv) UNREACHED(net_socket_wait_readable) UNREACHED(net_socket_peek) UNREACHED(net_socket_available) +UNREACHED(net_socket_accept_commit) +UNREACHED(net_socket_accept_peek) +UNREACHED(net_socket_address6) +UNREACHED(net_socket_bind6_fd) +UNREACHED(net_socket_bound_device) +UNREACHED(net_socket_connect6_fd) +UNREACHED(net_socket_family) +UNREACHED(net_socket_ipv6_option) +UNREACHED(net_socket_is_listening) +UNREACHED(net_socket_listen_fd) +UNREACHED(net_socket_namespace) +UNREACHED(net_socket_nodelay) +UNREACHED(net_socket_release_fd) +UNREACHED(net_socket_reuse) +UNREACHED(net_socket_set_ipv6) diff --git a/tools/tests/task8_net_ioctl_user_test.c b/tools/tests/task8_net_ioctl_user_test.c index bc7ef5b6..a7aeb5e5 100644 --- a/tools/tests/task8_net_ioctl_user_test.c +++ b/tools/tests/task8_net_ioctl_user_test.c @@ -21,6 +21,12 @@ static uint64_t blocked; static bool block_output; static struct task_file net_file={.used=1,.flags=TASK_FILE_FLAG_SOCKET_INET}; static struct net_namespace *udp_creating_ns; +static struct net_namespace *packet_creating_ns; +struct net_namespace *task_packet_namespace(const struct task_file *file) +{ + assert(file == &net_file); + return packet_creating_ns; +} struct net_namespace *task_udp_namespace(const struct task_file *file) { assert(file == &net_file); @@ -96,6 +102,18 @@ int main(void) .operation = RELIEFOS_NET_CONTROL_CONFIG}; assert(scoped(RELIEFOS_NET_CONTROL_IOCTL, (uintptr_t)&ctrl) == -LINUX_EOPNOTSUPP); task_lookup_scope_cancel(¤t); + packet_creating_ns = creating; + net_file.kind = TASK_FILE_KIND_PACKET; + req = (struct ifreq){.ifr_name = "lo"}; + assert(!scoped(SIOCGIFFLAGS, (uintptr_t)&req) && (req.data.flags & IFF_UP)); + task_lookup_scope_cancel(¤t); + req = (struct ifreq){.ifr_name = "eth0"}; + assert(scoped(SIOCGIFINDEX, (uintptr_t)&req) == -LINUX_ENODEV); + task_lookup_scope_cancel(¤t); + assert(scoped(RELIEFOS_NET_CONTROL_IOCTL, (uintptr_t)&ctrl) == -LINUX_EOPNOTSUPP); + task_lookup_scope_cancel(¤t); + packet_creating_ns = NULL; + net_file.kind = TASK_FILE_KIND_UDP; udp_creating_ns = NULL; req = (struct ifreq){.ifr_name = "eth0"}; assert(!scoped(SIOCGIFINDEX, (uintptr_t)&req) && req.data.value == 2); @@ -104,7 +122,7 @@ int main(void) net_file.kind = 0; net_namespace_put(creating); net_namespace_put(moved); - puts("PASS UDP creating-net ioctl after task movement and scoped private-control rejection"); + puts("PASS UDP/raw/AF_PACKET creating-net ioctl after task movement and scoped private-control rejection"); puts("PASS INET ioctls: fixed and nested output waits, immutable inputs, ignored unknown operand"); return 0; } diff --git a/tools/tests/task8_packet_user_test.c b/tools/tests/task8_packet_user_test.c index 6763ff8e..dd920678 100644 --- a/tools/tests/task8_packet_user_test.c +++ b/tools/tests/task8_packet_user_test.c @@ -14,6 +14,8 @@ static uint64_t blocked; static bool contended; +int user_range_readable(uint64_t address, uint64_t length) +{ return user_range_ok(address, length) ? 0 : -LINUX_EFAULT; } struct task_file *task_file_for_io(struct task *task, int fd) { return task->syscall_file && task->syscall_fd == fd ? task->syscall_file : task_file_for_fd(task, fd); } int swap_prepare_user_range(struct task *task, uint64_t address, uint64_t length, bool output) diff --git a/tools/tests/tcp_state_test.c b/tools/tests/tcp_state_test.c index 45ac3b6d..c2db0d7c 100644 --- a/tools/tests/tcp_state_test.c +++ b/tools/tests/tcp_state_test.c @@ -27,6 +27,8 @@ __attribute__((weak)) void net_ipv6_poll(void) {} __attribute__((weak)) void net_ipv6_input(const uint8_t *frame,uint32_t length) { (void)frame; (void)length; } __attribute__((weak)) void net_ipv6_transport_proc_emit(struct text_stream *stream,const char *leaf) { (void)stream; (void)leaf; } +__attribute__((weak)) void net_ipv6_transport_proc_emit_on(struct net_namespace *ns, struct text_stream *stream,const char *leaf) +{ (void)ns; (void)stream; (void)leaf; } __attribute__((weak)) int task_netlink_send(struct task_file *file,const void *data,uint32_t length, uint32_t flags,uint64_t address,uint32_t size) { (void)file; (void)data; (void)length; (void)flags; (void)address; (void)size; return -LINUX_EBADF; } @@ -1508,8 +1510,8 @@ void netdev_counters(uint32_t index, struct net_proc_counters *out) { (void)index; *out = (struct net_proc_counters){0}; } void net_ipv6_input_on(struct net_namespace *ns, uint32_t index, const uint8_t *frame, uint32_t length) { (void)ns; (void)index; net_ipv6_input(frame,length); } -void net_packet_input_on(uint32_t index, const void *frame, uint32_t length) -{ (void)index; net_packet_input(frame,length); } +void net_packet_input_on(struct net_namespace *ns, uint32_t index, const void *frame, uint32_t length) +{ assert(!ns); (void)index; net_packet_input(frame,length); } int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index, bool up) { (void)ns; (void)index; (void)up; return 0; } void net_ipv6_detached_on(struct net_namespace *ns, uint32_t index) { (void)ns; (void)index; } void netlink_ipv6_changed(struct net_namespace *ns) { (void)ns; } diff --git a/tools/tests/udp_socket_test.c b/tools/tests/udp_socket_test.c index 791a9e29..c4e9eb17 100644 --- a/tools/tests/udp_socket_test.c +++ b/tools/tests/udp_socket_test.c @@ -184,6 +184,8 @@ uint32_t net_ipv6_routes(struct net_namespace *ns, struct net_ipv6_route *out, u #ifndef IPV6_TRANSPORT_FIXTURE void net_ipv6_transport_proc_emit(struct text_stream *stream, const char *leaf) { (void)stream; (void)leaf; } +void net_ipv6_transport_proc_emit_on(struct net_namespace *ns, struct text_stream *stream, const char *leaf) +{ (void)ns; (void)stream; (void)leaf; } #endif static void check_proc_socket(const char *leaf, int visible, int hidden) From faafcef452f8a8cad4921864130fc07b3d741e2c Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 07:04:17 +0800 Subject: [PATCH 77/97] feat(namespace): support systemd network isolation through Linux entry points --- Documentation/core-api/mount-namespaces.rst | 17 +- .../LC_MESSAGES/core-api/mount-namespaces.po | 72 +++++-- .../en/LC_MESSAGES/userspace-api/abi.po | 114 ++++++++++- .../en/LC_MESSAGES/userspace-api/ipv6.po | 52 +++-- .../en/LC_MESSAGES/userspace-api/procfs.po | 29 ++- .../LC_MESSAGES/core-api/mount-namespaces.po | 61 ++++-- .../ja/LC_MESSAGES/userspace-api/abi.po | 98 +++++++++- .../ja/LC_MESSAGES/userspace-api/ipv6.po | 41 ++-- .../ja/LC_MESSAGES/userspace-api/procfs.po | 25 ++- Documentation/userspace-api/abi.rst | 40 +++- Documentation/userspace-api/ipv6.rst | 17 +- Documentation/userspace-api/procfs.rst | 8 +- fs/nsfs/namespace.c | 35 +++- fs/proc/procfs.c | 18 +- fs/vfs/pseudo.c | 36 ++-- include/reliefnt/net_namespace.h | 1 + include/reliefnt/nsfs.h | 27 ++- include/reliefnt/task/accessors.h | 5 +- include/reliefnt/user_namespace.h | 6 +- include/uapi/linux/socket.h | 2 + kernel/sched/clone.c | 25 ++- kernel/sched/user_namespace_task.c | 12 +- kernel/syscall/dispatch.c | 2 +- kernel/syscall/fs/locks.c | 30 ++- kernel/syscall/fs/mount.c | 8 +- kernel/syscall/fs/mount_api.c | 36 +++- kernel/syscall/process/clone.c | 6 +- kernel/syscall/process/setns.c | 17 +- net/socket/netlink.c | 74 +++++-- tools/test_linux_inventory.py | 2 +- tools/test_lock_profile.py | 4 +- tools/test_memory_reporting.py | 2 +- tools/test_mount_backend.py | 2 +- tools/test_procfs.py | 3 +- tools/test_rootfs.py | 2 +- tools/tests/descriptor_table_test.c | 97 ++++++++++ tools/tests/ipv6_control_test.c | 171 +++++++++++++++- tools/tests/linux_inventory_test.c | 8 + tools/tests/mount_backend_test.c | 182 ++++++++++++++++++ tools/tests/mount_namespace_task_test.c | 159 ++++++++++++++- tools/tests/procfs_directories_test.c | 57 +++++- tools/tests/test-version.sh | 3 +- 42 files changed, 1424 insertions(+), 182 deletions(-) diff --git a/Documentation/core-api/mount-namespaces.rst b/Documentation/core-api/mount-namespaces.rst index 7a4d826b..1a48e756 100644 --- a/Documentation/core-api/mount-namespaces.rst +++ b/Documentation/core-api/mount-namespaces.rst @@ -114,15 +114,17 @@ bind 和挂载图快照保留该引用,最后一个挂载在后端成功退役 句柄与切换 ========== -``/proc//ns/mnt``、``/proc//ns/user`` 与 ``/proc//ns/uts`` +``/proc//ns/mnt``、``/proc//ns/user``、``/proc//ns/uts`` 与 +``/proc//ns/net`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 -PID 身份,每次成功跟随则取得目标当时的挂载图、用户空间或 UTS 空间。 +PID 身份,每次成功跟随则取得目标当时的挂载图、用户、UTS 或网络空间。 -跟随链接得到分离的 nsfs inode。mount、user 与 UTS 空间使用同一单调递增序列,首次 +跟随链接得到分离的 nsfs inode。mount、user、UTS 与 network 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 -返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]``、``user:[inode]`` 或 ``uts:[inode]``。 +返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]``、``user:[inode]``、``uts:[inode]`` 或 +``net:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。 ``setns()`` 通过实际后端、inode 和后端 pin 认证句柄,再按类型取得目标空间。 @@ -140,6 +142,11 @@ UTS 切换要求当前用户空间和目标 UTS owner 用户空间两侧的 ``CA 允许共享文件系统状态。成功时替换任务的 UTS 引用并释放旧引用。 ``NS_GET_NSTYPE`` 对 UTS 句柄返回 ``CLONE_NEWUTS``。 +network 切换要求当前用户空间和目标网络 owner 用户空间两侧的 +``CAP_SYS_ADMIN``,允许共享文件系统状态。成功时取得目标引用再释放旧引用, +已有套接字继续保留各自的创建网络。``NS_GET_NSTYPE`` 返回 ``CLONE_NEWNET``。 +初始网络由空指针表示,布尔查询接口区分有效初始网络句柄与无效路径。 + 引用释放 ======== @@ -170,7 +177,7 @@ TCP 的端口冲突、IPv4/IPv6 和映射地址握手、接收连接、收发、 ``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``raw6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP、TCP 和 raw IPv6 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 仅输出表头。 -用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 ``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 transport 隔离完成后接通。 +``clone()``、``clone3()`` 和 ``unshare()`` 接受 ``CLONE_NEWNET``。单独创建要求当前用户空间的 ``CAP_SYS_ADMIN``,与 ``CLONE_NEWUSER`` 组合时由候选用户空间拥有新网络。候选网络在 scheduler lock 外准备,失败时与其他候选状态一同释放,成功时将一个引用交给任务。单独 unshare 网络保留文件系统共享状态。``setns()`` 通过真实 nsfs 句柄认证类型并检查当前与目标 owner 两侧权限,成功时切换任务引用。接口与套接字继续遵循各自的网络归属。 netlink 端口与事件 ================== diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po index 736cdc8b..001ea8f7 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/mount-namespaces.po @@ -323,9 +323,6 @@ msgstr "Message queue, semaphore and shared-memory registries, permission checks msgid "``IPC_SET`` 先执行现有对象所有权与资源限制检查,再将输入的 UID/GID 全部 转换为全局 ID。任一输入未映射或为 ``UINT32_MAX`` 时返回 ``EINVAL``,对象的 身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 用户空间检查。" msgstr "``IPC_SET`` first performs the existing object ownership and resource-limit checks, then translates both input UID/GID values into global IDs. An unmapped input or ``UINT32_MAX`` returns ``EINVAL``, preserving the object identities, permissions, capacity and modification time. Success updates the owner and low 0777 permission bits while preserving creator identities and shared-memory lock and deletion flags. Global IPC administration and resource privileges are still checked in the initial user namespace." -msgid "``/proc//ns/mnt``、``/proc//ns/user`` 与 ``/proc//ns/uts`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图、用户空间或 UTS 空间。" -msgstr "``/proc//ns/mnt``, ``/proc//ns/user`` and ``/proc//ns/uts`` are proc magic links. Reading or following them requires the same ``PTRACE_MODE_READ_FSCREDS`` check as ``/proc//fd``. Link keys retain PID identity. Each successful follow captures the target task current mount graph, user namespace or UTS namespace." - msgid "" "``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare " "同时准备独立的文件系统 状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 no_new_privs,并初始化新空间的能力集合及 " @@ -356,9 +353,6 @@ msgstr "" msgid "user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。" msgstr "A user namespace switch requires a single thread, exclusive filesystem state and ``CAP_SYS_ADMIN`` in the target namespace, and rejects reentry into the current namespace. Success preserves root, cwd and global identities and reuses namespace installation to reset capability sets and securebits. Increased scoped authority restricts dumpability and clears the parent-death signal. A NULL pointer represents the initial user namespace. Authenticated handle types and the boolean query distinguish that valid identity from an invalid path." -msgid "跟随链接得到分离的 nsfs inode。mount、user 与 UTS 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]``、``user:[inode]`` 或 ``uts:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" -msgstr "Following a link obtains a detached nsfs inode. Mount, user and UTS namespaces share one monotonically increasing sequence. The first display or handle creation assigns an inode, and every handle for that namespace shares this identity. Exhausting the 64-bit sequence returns ``EOVERFLOW``. Labels are ``mnt:[inode]``, ``user:[inode]`` or ``uts:[inode]``. Each typed backend retains its namespace. Final path release reclaims the backend and drops the namespace reference." - msgid "" "每个挂载图持有不可变的 user owner 引用,空指针表示初始用户空间。 ``vfs_namespace_snapshot()`` 和 " "``vfs_namespace_clone()`` 保留原 owner; ``vfs_namespace_clone_owned()`` 显式选择新图的 owner。owner " @@ -450,14 +444,6 @@ msgstr "Network namespaces scope Unix abstract addresses, proc enumeration, netl msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``raw6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP、TCP 和 raw IPv6 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 仅输出表头。" msgstr "``/proc/net/dev``, ``route``, ``if_inet6``, ``ipv6_route``, ``udp``, ``udp6``, ``tcp``, ``tcp6``, ``raw6`` and ``unix`` follow the caller's current network scope. UDP, TCP and raw IPv6 endpoints report actual receive queues and numeric inodes. IPv4 local UDP delivery counters belong to the corresponding network. Noninitial ``arp`` views contain only headers." -msgid "" -"用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " -"``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 transport 隔离完成后接通。" -msgstr "" -"Userspace network ``CLONE_NEWNET``, ``unshare()`` and ``setns()`` entry points remain closed." -" Clone requests with ``CLONE_NEWNET`` return ``EPERM`` or ``EINVAL`` according to authority, " -"and unshare returns ``EINVAL``. Creation and switching will open after transport isolation." - msgid "netlink 端口与事件" msgstr "Netlink ports and events" @@ -479,3 +465,61 @@ msgstr "TCP port conflicts, IPv4/IPv6 and mapped-address handshakes, accepted co msgid "raw 和 AF_PACKET 的创建按网络 user owner 的 ``CAP_NET_RAW`` 授权。收包、地址绑定、设备选项、接口 ioctl、IPv6 路由、多播、错误和 ICMPv6 ping ID 冲突按创建网络匹配。传递 OFD 或切换任务网络后仍使用创建网络,非初始 socket 的私有全局控制返回 ``EOPNOTSUPP``。物理 ingress 和设备移除只作用于初始网络。AF_PACKET 的 loopback 发送返回 ``EOPNOTSUPP``。raw IPv4 先查询创建网络的路由,非初始或 loopback 路由返回 ``ENETUNREACH``,其物理发送仅在初始网络执行。" msgstr "Raw and AF_PACKET creation requires ``CAP_NET_RAW`` in the network's user owner. Receive delivery, address binding, device options, interface ioctls, IPv6 routing, multicast, errors and ICMPv6 ping ID conflicts match the creating network. OFD transfer or task network changes preserve that network. Private global control on noninitial sockets returns ``EOPNOTSUPP``. Physical ingress and device removal affect only the initial network. AF_PACKET loopback sends return ``EOPNOTSUPP``. Raw IPv4 first looks up routes in its creating network. Noninitial or loopback routes return ``ENETUNREACH``, and physical transmission runs only in the initial network." + +msgid "" +"``/proc//ns/mnt``、``/proc//ns/user``、``/proc//ns/uts`` 与 " +"``/proc//ns/net`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` " +"相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图、用户、UTS" +" 或网络空间。" +msgstr "" +"``/proc//ns/mnt``, ``/proc//ns/user``, ``/proc//ns/uts`` and" +" ``/proc//ns/net`` are proc magic links. Reading or following them " +"requires the same ``PTRACE_MODE_READ_FSCREDS`` permission check as " +"``/proc//fd``. Link keys retain PID identity. Each successful follow " +"captures the target’s current mount graph, user, UTS or network namespace." + +msgid "" +"跟随链接得到分离的 nsfs inode。mount、user、UTS 与 network 空间使用同一单调递增序列,首次 显示或创建句柄时分配 " +"inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 " +"``mnt:[inode]``、``user:[inode]``、``uts:[inode]`` 或 ``net:[inode]``。 " +"每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" +msgstr "" +"Following a link produces a detached nsfs inode. Mount, user, UTS and " +"network namespaces use one monotonically increasing sequence. An inode is " +"assigned on first display or handle creation, and every handle for that " +"namespace shares the identity. Exhausting the 64-bit sequence returns " +"``EOVERFLOW``. Labels are ``mnt:[inode]``, ``user:[inode]``, " +"``uts:[inode]`` and ``net:[inode]``. Each typed backend retains its " +"namespace and releases both the backend and namespace when the final path " +"is released." + +msgid "" +"network 切换要求当前用户空间和目标网络 owner 用户空间两侧的 " +"``CAP_SYS_ADMIN``,允许共享文件系统状态。成功时取得目标引用再释放旧引用, " +"已有套接字继续保留各自的创建网络。``NS_GET_NSTYPE`` 返回 ``CLONE_NEWNET``。 " +"初始网络由空指针表示,布尔查询接口区分有效初始网络句柄与无效路径。" +msgstr "" +"Network switching requires ``CAP_SYS_ADMIN`` in both the current user " +"namespace and the target network owner’s user namespace. Filesystem sharing" +" is allowed. Success acquires the target reference before releasing the old" +" one. Existing sockets retain their creating networks. ``NS_GET_NSTYPE`` " +"returns ``CLONE_NEWNET``. The initial network is represented by a null " +"pointer, and a boolean query distinguishes its valid handle from an invalid" +" path." + +msgid "" +"``clone()``、``clone3()`` 和 ``unshare()`` 接受 ``CLONE_NEWNET``。单独创建要求当前用户空间的 " +"``CAP_SYS_ADMIN``,与 ``CLONE_NEWUSER`` 组合时由候选用户空间拥有新网络。候选网络在 scheduler lock " +"外准备,失败时与其他候选状态一同释放,成功时将一个引用交给任务。单独 unshare 网络保留文件系统共享状态。``setns()`` 通过真实 " +"nsfs 句柄认证类型并检查当前与目标 owner 两侧权限,成功时切换任务引用。接口与套接字继续遵循各自的网络归属。" +msgstr "" +"``clone()``, ``clone3()`` and ``unshare()`` accept ``CLONE_NEWNET``. " +"Creation on its own requires ``CAP_SYS_ADMIN`` in the current user " +"namespace. Combined with ``CLONE_NEWUSER``, the candidate user namespace " +"owns the new network. The candidate network is prepared outside the " +"scheduler lock and released with other candidates on failure. Success " +"transfers one reference to the task. Network-only unshare preserves " +"filesystem sharing. ``setns()`` authenticates an actual nsfs handle and " +"checks authority in both the current and target-owner user namespaces " +"before replacing the task reference. Interfaces and sockets continue to use" +" their respective network ownership." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 61f063c6..de545279 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -373,8 +373,35 @@ msgstr "" "owner. CREATE requires ``CAP_SYS_ADMIN`` in that owner. See :doc:`procfs` " "for policy and reconfiguration semantics." -msgid "tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 ``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo 中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" -msgstr "Both tmpfs and proc contexts accept the ``source`` parameter with ``FSCONFIG_SET_STRING``. Its value may be empty or contain commas and is limited to 255 bytes. If unset, the source is displayed as ``none``. Setting it twice in the same configuration phase returns ``EINVAL``. Setting parameters after successful creation and before successful ``fsmount`` returns ``EBUSY``. After a successful ``fsmount`` and each successful reconfiguration, a new ``source`` may be set for the next configuration phase. Reconfiguration does not change the existing mount's source in mountinfo. If creation or reconfiguration fails, the pending source remains available for retry." +msgid "" +"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 捕获当前网络空间的 user owner,并要求其 ``CAP_SYS_ADMIN``。传统 sysfs " +"mount 使用同一 owner。CREATE 再次检查捕获的 owner,调用者随后切换网络不会改变该权限作用域。sysfs 上下文接受通用 ``source``、``ro`` 和 " +"``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的 只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读 " +"属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" +msgstr "" +"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` captures the current network namespace's user owner and" +" requires its ``CAP_SYS_ADMIN``. Legacy sysfs mount uses the same owner. CREATE checks the " +"captured owner again. A later network switch preserves this authority scope. sysfs contexts " +"accept the generic ``source``, ``ro`` and ``rw`` parameters. Unknown private options return " +"``EINVAL``. The shared backend retains the CREATE readonly setting, and RECONFIGURE can " +"update that state. An independent ``fsmount`` readonly attribute continues to restrict its " +"attachment. Allocation, descriptor installation and creation failures release candidate " +"references and allow retry." + +msgid "" +"tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 " +"字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 " +"``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo " +"中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" +msgstr "" +"The tmpfs, proc and sysfs contexts accept the ``source`` parameter with " +"``FSCONFIG_SET_STRING``. Its value may be empty or contain commas and is limited to 255 " +"bytes. If unset, the source is displayed as ``none``. Setting it twice in the same " +"configuration phase returns ``EINVAL``. Setting parameters after successful creation and " +"before successful ``fsmount`` returns ``EBUSY``. After a successful ``fsmount`` and each " +"successful reconfiguration, a new ``source`` may be set for the next configuration phase. " +"Reconfiguration preserves the existing mount's source in mountinfo. If creation or " +"reconfiguration fails, the pending source remains available for retry." msgid "" "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` " @@ -458,9 +485,6 @@ msgstr "" msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUSER)`` accept an ordinary read-only ``/proc//ns/user`` handle. Joining the current user namespace, having another live thread in the group, or sharing filesystem state with another task returns ``EINVAL``. The caller needs ``CAP_SYS_ADMIN`` in the target user namespace or receives ``EPERM``. Ancestors of the current namespace fail this authority check." -msgid "nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS``、``CLONE_NEWUSER`` 或 ``CLONE_NEWUTS``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" -msgstr "An nsfs handle provides metadata and ioctls. Opening it for writing or with ``O_TRUNC`` returns ``EPERM``. ``O_PATH`` ignores these open flags. Scalar, positioned and vectored reads on an ordinary FD return ``EINVAL``, writes return ``EBADF``, and ``lseek()`` with a valid ``whence`` returns ``ESPIPE``. ``NS_GET_NSTYPE`` returns ``CLONE_NEWNS``, ``CLONE_NEWUSER`` or ``CLONE_NEWUTS`` according to the handle type. ``FIONREAD`` writes zero. Unsupported namespace ioctls return ``ENOTTY``. An ``O_PATH`` FD supports metadata queries but cannot read, write, seek or issue ioctls." - msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" msgstr "After switching, root and cwd both point to the visible root of the target mount graph. Existing FDs and umask are preserved. Handles remain usable after the original process exits or changes namespaces." @@ -470,9 +494,6 @@ msgstr "Joining namespaces" msgid "成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask 保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" msgstr "A successful user namespace join preserves global UID/GID, supplementary groups, no_new_privs, root, cwd and umask. The permitted, effective and bounding sets contain all supported capabilities. Inheritable, ambient and securebits are cleared. An increase in scoped authority clears the parent-death signal and restricts dumpability. Rejection preserves the original credentials and filesystem state." -msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount、user 与 UTS 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" -msgstr "Invalid or ``O_PATH`` FDs return ``EBADF``. A non-nsfs FD, type mismatch or unsupported type returns ``EINVAL``. Mount, user and UTS handles are supported. Pidfds and bind mounts of nsfs handles remain pending. See :doc:`../core-api/mount-namespaces`." - msgid "" "bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 owner " "的覆盖挂载不能单独移动或卸载,普通与 lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 ``EINVAL``, 递归 bind 剪除锁定的 " @@ -532,3 +553,80 @@ msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUTS)`` accept an ordinary read msgid "当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 文件 I/O 规则推进。此处尚未实现 Linux strict sysctl 对忽略写入保留偏移的行为。" msgstr "When the current position is beyond the name end, a write preserves the name and reports the accepted input byte count. The file position still advances under ordinary file I/O rules. Preserving the offset for ignored writes as Linux strict sysctl does remains pending." + +msgid "创建网络命名空间" +msgstr "Creating network namespaces" + +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNET`` 为子任务建立独立网络空间, " +"``unshare(CLONE_NEWNET)`` 为调用任务建立独立网络空间。单独创建要求当前用户 空间的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。同时指定 ``CLONE_NEWUSER`` 时,新网络由候选用户空间拥有。普通 " +"fork 及未指定该标志的 clone 共享原网络。" +msgstr "" +"``CLONE_NEWNET`` in ``clone()`` and ``clone3()`` creates an independent " +"network for the child. ``unshare(CLONE_NEWNET)`` creates one for the " +"caller. Creation on its own requires ``CAP_SYS_ADMIN`` in the current user " +"namespace and returns ``EPERM`` when it is absent. When combined with " +"``CLONE_NEWUSER``, the candidate user namespace owns the new network. " +"Ordinary fork and clone without this flag share the original network." + +msgid "" +"新网络仅包含默认 down 的 ``lo``,置为 up 时配置回环地址。接口、路由、IPv6 " +"协议状态和套接字匹配按网络隔离。已有套接字保留创建时的网络,任务切换后也 继续使用该网络。单独创建或切换网络保留文件系统共享状态。组合创建先准备全部 " +"候选状态,准备失败保留原空间、凭据、路径和进程发布状态。内部生命周期和已 实现网络范围见 " +":doc:`../core-api/mount-namespaces`。" +msgstr "" +"A new network contains only ``lo``, initially down. Bringing it up " +"configures loopback addresses. Interfaces, routes, IPv6 protocol state and " +"socket matching are network-scoped. Existing sockets retain their creating " +"network after task movement. Creating or joining only a network preserves " +"filesystem sharing. Combined creation prepares all candidates first. " +"Preparation failure preserves the original namespaces, credentials, paths " +"and process publication state. See :doc:`../core-api/mount-namespaces` for " +"lifetimes and implemented networking scope." + +msgid "" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNET)`` 接受普通只读的 " +"``/proc//ns/net`` 句柄。调用者需要当前用户空间和目标网络 owner 用户 空间两侧的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。成功后替换任务网络 引用,root、cwd、umask " +"和已有套接字的创建网络保留。允许共享 ``CLONE_FS``, 句柄继续保留目标网络,权限或类型检查失败时保留调用者原网络。" +msgstr "" +"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNET)`` accept an ordinary " +"readonly ``/proc//ns/net`` handle. The caller needs ``CAP_SYS_ADMIN`` " +"in both its current user namespace and the target network owner’s user " +"namespace. Missing authority returns ``EPERM``. Success replaces the task’s" +" network reference while retaining root, cwd, umask and the creating " +"networks of existing sockets. Shared ``CLONE_FS`` is allowed. The handle " +"retains the target network. Failed permission or type checks preserve the " +"caller’s original network." + +msgid "" +"无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 " +"``EINVAL``。当前支持 mount、user、UTS 与 network 句柄,pidfd 和 nsfs 句柄的 bind mount " +"仍未接通。参见 :doc:`../core-api/mount-namespaces`。" +msgstr "" +"Invalid FDs and ``O_PATH`` FDs return ``EBADF``. Non-nsfs FDs, mismatched " +"types and unsupported types return ``EINVAL``. Mount, user, UTS and network" +" handles are supported. Pidfds and bind mounting nsfs handles remain " +"unimplemented. See :doc:`../core-api/mount-namespaces`." + +msgid "" +"nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` " +"忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 " +"``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 " +"``CLONE_NEWNS``、``CLONE_NEWUSER``、 ``CLONE_NEWUTS`` 或 ``CLONE_NEWNET``。 " +"``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD " +"可用于元数据查询,但不能 读写、定位或执行 ioctl。" +msgstr "" +"Nsfs handles provide metadata and ioctls. Opening for writing or with " +"``O_TRUNC`` returns ``EPERM``. ``O_PATH`` ignores those flags. Scalar, " +"positioned and vector reads on ordinary FDs return ``EINVAL``, writes " +"return ``EBADF``, and ``lseek()`` with a valid ``whence`` returns " +"``ESPIPE``. ``NS_GET_NSTYPE`` returns ``CLONE_NEWNS``, ``CLONE_NEWUSER``, " +"``CLONE_NEWUTS`` or ``CLONE_NEWNET`` according to the handle. ``FIONREAD`` " +"stores zero. Unsupported namespace ioctls return ``ENOTTY``. ``O_PATH`` FDs" +" support metadata queries, while read, write, seek and ioctl operations are" +" rejected." + +msgid "普通文件和 socket 均可使用这些锁命令。socket 按完整的匿名 inode 编号识别, 同一端点的别名共享冲突范围,不同端点的锁独立。socket 的 ``SEEK_END`` 基准 为零,``O_PATH`` 描述符返回 ``EBADF``。关闭 socket 的 POSIX 锁释放规则与 普通文件相同,OFD 锁持续到最后一个引用释放。" +msgstr "Regular files and sockets support these lock commands. Socket identity uses the complete anonymous inode number. Aliases of one endpoint share conflict ranges, while separate endpoints have independent locks. A socket uses zero as the ``SEEK_END`` base, and an ``O_PATH`` descriptor returns ``EBADF``. Closing a socket follows the regular-file POSIX lock release rules. OFD locks remain until the final reference is released." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po index b7b60e7e..74c4db61 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po @@ -75,21 +75,6 @@ msgstr "" msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP、TCP 和 raw 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。" msgstr "``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text layouts. Address scope encoding differs from rtnetlink scope values. Address, route, UDP, TCP and raw tables follow the caller's current network scope. Snapshots copy internal state and retain only copies across waits." -msgid "" -"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" -" 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 " -"ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 transport " -"隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。" -msgstr "" -"Each network namespace owns its interfaces, loopback, IPv4 routes, and IPv6 addresses, " -"routes, neighbors, multicast state, pending packets, fragment reassembly, PMTU, fragment " -"identifiers and ICMP error rate limits. A new network's ``lo`` starts down without IPv6 " -"addresses. Its first up transition configures ``::1/128`` and a host route. Tables and queues" -" have independent capacities, and namespace destruction releases protocol resources. Physical" -" NIC registration and ingress remain in the initial network. Userspace network " -"``CLONE_NEWNET``, ``unshare()`` and ``setns()`` entry points will open after transport " -"isolation. See :doc:`../core-api/mount-namespaces` for internal lifetime and proc scope." - msgid "范围与标准" msgstr "Scope and Standards" @@ -117,3 +102,40 @@ msgstr "As on Linux, bind on TCP, UDP, and raw sockets uses sin6_scope_id only f msgid "raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 ``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD 后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。" msgstr "Raw IPv6 sockets independently retain their creating network. Creation requires ``CAP_NET_RAW`` in that network's user owner. Address binding, routing, delivery, multicast memberships, ICMPv6 errors, ping ID conflicts and device options are isolated by creating network, including after FD transfer. Final close leaves multicast in the original network and releases references. Physical device removal reports errors only to affected sockets in the initial network." + +msgid "" +"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP " +"错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host " +"route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态通过 " +"``clone()``、``clone3()`` 或 ``unshare()`` 的 ``CLONE_NEWNET`` 创建网络,通过 " +"``/proc//ns/net`` 句柄和 ``setns()`` 切换网络。授权与失败语义见 :doc:`abi`,内部生命周期与 " +"proc 范围见 :doc:`../core-api/mount-namespaces`。" +msgstr "" +"Each network namespace owns its interfaces, loopback, IPv4 routes, IPv6 " +"addresses and routes, neighbors, multicast state, pending packets, fragment" +" reassembly, PMTU, fragment IDs and ICMP error rate limits. A new namespace" +" starts with ``lo`` down and no IPv6 address. Its first transition up " +"configures ``::1/128`` and a host route. Tables and queues account for " +"capacity independently, and namespace destruction releases protocol " +"resources. Physical NIC registration and ingress remain in the initial " +"namespace. Userspace creates networks with ``CLONE_NEWNET`` in ``clone()``," +" ``clone3()`` or ``unshare()`` and switches through ``/proc//ns/net`` " +"handles and ``setns()``. See :doc:`abi` for authorization and failure " +"semantics and :doc:`../core-api/mount-namespaces` for lifetimes and proc " +"scope." + +msgid "netlink socket 的 ``SO_SNDBUF`` 和 ``SO_RCVBUF`` 默认有效大小均为 65536 字节。 设置值按无符号整数裁剪到 65536 后乘二,发送和接收的最小有效值分别为 4608 和 2304 字节,查询返回有效大小。发送数据报同时受 8192 字节硬上限及有效发送 缓冲区减 32 字节的限制,超过时返回 ``EMSGSIZE``。短设置值、错误用户指针和 负长度返回错误并保留原设置。" +msgstr "A netlink socket defaults to effective ``SO_SNDBUF`` and ``SO_RCVBUF`` sizes of 65536 bytes each. Setters clamp the unsigned request to 65536 before doubling it, with effective send and receive minima of 4608 and 2304 bytes. Getters return the effective size. A sent datagram must fit both the 8192-byte hard limit and the effective send buffer minus 32 bytes, otherwise it returns ``EMSGSIZE``. Short setter values, invalid user pointers, and negative lengths return errors while preserving the previous setting." + +msgid "接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 位置。预留失败时返回 ``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 属于实际 socket,传递 FD 或切换网络后继续保留。" +msgstr "The receive queue conservatively charges 8192 bytes per datagram. Multipart queries reserve two slots for data and the terminator. Failed reservation returns ``ENOBUFS`` before the request changes network state. Shrinking the receive buffer preserves queued messages and new messages wait for available capacity. Reading releases capacity, and growing the buffer updates writability. Buffer settings belong to the actual socket and survive FD transfer or a network switch." + +msgid "" +"路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含 " +"被忽略的尾部;全部消息无效时不生成回复。预扫描和实际处理使用同一前缀边界。" +msgstr "" +"Route requests process the valid message prefix of a datagram in order, ignoring the first " +"malformed or incomplete message and all subsequent bytes. The last complete message may omit " +"alignment padding. A successful send returns the entire datagram length, including the " +"ignored tail. A datagram with no valid messages generates no replies. Prescanning and " +"processing use the same prefix boundary." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po index 1ecc20ea..9ffcd14b 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/procfs.po @@ -443,11 +443,28 @@ msgstr "" msgid "``status`` 的四个 ``Uid``、四个 ``Gid`` 和 ``Groups`` 中的补充组按生成视图时 调用者的用户命名空间输出。未映射的 ID 显示为 65534,目标任务的内部凭据保持 全局 ID。成功打开的文件保存已渲染字节,之后切换空间或转交描述符继续读取 原视图,重新打开时使用新调用者的空间。" msgstr "The four ``Uid`` fields, four ``Gid`` fields and supplementary ``Groups`` in ``status`` use the user namespace of the caller generating the view. Unmapped IDs appear as 65534. The target task retains kernel-global credentials. A successfully opened file retains the rendered bytes across namespace changes or descriptor transfers. Reopening uses the new caller namespace." -msgid "``ns/mnt``、``ns/user``" -msgstr "``ns/mnt``, ``ns/user``" +msgid "``ns/mnt``、``ns/user``、``ns/uts``、``ns/net``" +msgstr "``ns/mnt``, ``ns/user``, ``ns/uts``, ``ns/net``" -msgid "``ns`` 目录枚举 ``mnt`` 和 ``user``。读取或跟随链接须通过现有 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接保留 PID 身份,每次跟随取得目标 当时的空间。nsfs 句柄在原进程退出或切换空间后继续保留原空间,链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。同一空间的句柄共享稳定 inode,不同空间 在共同的 nsfs 设备上使用独立 inode。切换接口见 :doc:`abi`。" -msgstr "The ``ns`` directory lists ``mnt`` and ``user``. Reading or following a link requires the existing ``PTRACE_MODE_READ_FSCREDS`` check. Links retain PID identity and capture the target namespace at each follow. An nsfs handle retains its original namespace after the process exits or changes namespaces. Link labels are ``mnt:[inode]`` or ``user:[inode]``. Handles for the same namespace share a stable inode, while distinct namespaces have distinct inodes on the common nsfs device. See :doc:`abi` for switching." +msgid "目标任务的挂载、用户、UTS 和网络命名空间 magic link,跟随时取得保留空间的 nsfs 句柄。" +msgstr "" +"Magic links for the target task’s mount, user, UTS and network namespaces. " +"Following one yields an nsfs handle that retains the namespace." -msgid "目标任务的挂载与用户命名空间 magic link,跟随时取得保留空间的 nsfs 句柄。" -msgstr "Magic links for the target task mount and user namespaces. Following a link obtains an nsfs handle retaining that namespace." +msgid "" +"``ns`` 目录枚举 ``mnt``、``user``、``uts`` 和 ``net``。读取或跟随链接须通过现有 " +"``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接保留 PID 身份,每次跟随取得目标 当时的空间。nsfs " +"句柄在原进程退出或切换空间后继续保留原空间,链接显示为 " +"``mnt:[inode]``、``user:[inode]``、``uts:[inode]`` 或 " +"``net:[inode]``。同一空间的句柄共享稳定 inode,不同空间 在共同的 nsfs 设备上使用独立 inode。切换接口见 " +":doc:`abi`。" +msgstr "" +"The ``ns`` directory enumerates ``mnt``, ``user``, ``uts`` and ``net``. " +"Reading or following a link requires the existing " +"``PTRACE_MODE_READ_FSCREDS`` permission check. Links retain PID identity " +"and capture the target’s current namespace whenever followed. An nsfs " +"handle retains the original namespace after the target exits or switches " +"namespaces. Labels are ``mnt:[inode]``, ``user:[inode]``, ``uts:[inode]`` " +"and ``net:[inode]``. Handles for one namespace share a stable inode. " +"Different namespaces use distinct inodes on the common nsfs device. See " +":doc:`abi` for switching interfaces." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po index b1aaf1d4..63aa3d94 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/mount-namespaces.po @@ -286,9 +286,6 @@ msgstr "メッセージキュー、セマフォ、共有メモリの登録表、 msgid "``IPC_SET`` 先执行现有对象所有权与资源限制检查,再将输入的 UID/GID 全部 转换为全局 ID。任一输入未映射或为 ``UINT32_MAX`` 时返回 ``EINVAL``,对象的 身份、权限、容量与修改时间均保留。成功时更新所有者及低 0777 权限位,保留 创建者身份和共享内存的锁定、删除标志。全局 IPC 管理与资源特权继续按初始 用户空间检查。" msgstr "``IPC_SET`` は既存のオブジェクト所有権とリソース制限を確認してから、入力 UID/GID の両方をグローバル ID に変換します。未マッピングの入力または ``UINT32_MAX`` には ``EINVAL`` を返し、オブジェクトの ID、権限、容量、変更時刻を保持します。成功時は所有者と下位 0777 の権限ビットを更新し、作成者の ID と共有メモリのロックおよび削除フラグを保持します。グローバル IPC 管理とリソース特権は引き続き初期ユーザー名前空間で確認します。" -msgid "``/proc//ns/mnt``、``/proc//ns/user`` 与 ``/proc//ns/uts`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` 相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图、用户空间或 UTS 空间。" -msgstr "``/proc//ns/mnt``、``/proc//ns/user``、``/proc//ns/uts`` は proc magic link です。読み取りと追跡には ``/proc//fd`` と同じ ``PTRACE_MODE_READ_FSCREDS`` 検査が必要です。リンクキーは PID の同一性を保持します。追跡が成功するたびに対象タスクの現在のマウントグラフ、ユーザー名前空間または UTS 名前空間を取得します。" - msgid "" "``CLONE_NEWUSER`` 为 clone 子任务或 unshare 调用者创建用户空间,安装前完成 有效 UID/GID 映射、chroot、线程组与分配检查。unshare " "同时准备独立的文件系统 状态。任一准备失败都回滚候选空间和路径。创建保留全局身份、补充组与 no_new_privs,并初始化新空间的能力集合及 " @@ -315,9 +312,6 @@ msgstr "" msgid "user 切换要求单线程、独占文件系统状态及目标空间的 ``CAP_SYS_ADMIN``,并拒绝 重入当前空间。成功时保留 root、cwd 和全局身份,复用用户空间安装逻辑重置能力 集合与 securebits。权限作用域增加时限制可转储状态并清除父死亡信号。初始用户 空间由空指针表示,句柄类型认证和布尔查询接口区分该有效身份与无效路径。" msgstr "user の切り替えには単一スレッド、ファイルシステム状態の独占、対象名前空間の ``CAP_SYS_ADMIN`` が必要で、現在の名前空間への再参加は拒否します。成功時は root、cwd、グローバル ID を保持し、ユーザー名前空間の設定処理を再利用して能力集合と securebits をリセットします。作用域内の権限が増加するとダンプ可能性を制限し、親死亡シグナルを解除します。初期ユーザー名前空間は空ポインタで表し、ハンドル型の認証と真偽値の照会でこの有効な ID と無効なパスを区別します。" -msgid "跟随链接得到分离的 nsfs inode。mount、user 与 UTS 空间使用同一单调递增序列,首次 显示或创建句柄时分配 inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 ``mnt:[inode]``、``user:[inode]`` 或 ``uts:[inode]``。 每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" -msgstr "リンクをたどると独立した nsfs inode を取得します。mount、user、UTS の名前空間は単調増加する共通の採番列を使います。最初の表示またはハンドル作成時に inode を割り当て、同じ名前空間のすべてのハンドルがその ID を共有します。64 ビットの採番列を使い切ると ``EOVERFLOW`` を返します。表示は ``mnt:[inode]``、``user:[inode]`` または ``uts:[inode]`` です。各バックエンドは型に応じた名前空間の参照を持ち、最後のパス解放時にバックエンドを回収して名前空間の参照を解放します。" - msgid "" "每个挂载图持有不可变的 user owner 引用,空指针表示初始用户空间。 ``vfs_namespace_snapshot()`` 和 " "``vfs_namespace_clone()`` 保留原 owner; ``vfs_namespace_clone_owned()`` 显式选择新图的 owner。owner " @@ -398,14 +392,6 @@ msgstr "ネットワーク空間は Unix 抽象アドレス、proc 列挙、netl msgid "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``raw6`` 和 ``unix`` 按调用者当前网络 scope 输出。UDP、TCP 和 raw IPv6 端点输出实际接收队列和数值 inode,IPv4 本地 UDP 投递计数属于对应网络。非初始空间的 ``arp`` 仅输出表头。" msgstr "``/proc/net/dev``、``route``、``if_inet6``、``ipv6_route``、``udp``、``udp6``、``tcp``、``tcp6``、``raw6``、``unix`` は呼び出し元の現在のネットワーク scope を使用します。UDP、TCP、raw IPv6 の端点は実際の受信キューと数値 inode を表示します。IPv4 ローカル UDP 配信のカウンターは対応するネットワークに属します。非初期空間の ``arp`` はヘッダーのみを出力します。" -msgid "" -"用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口仍关闭。``CLONE_NEWNET`` 的 clone 请求按权限返回 " -"``EPERM`` 或 ``EINVAL``,unshare 请求返回 ``EINVAL``。用户态创建和切换将在 transport 隔离完成后接通。" -msgstr "" -"ユーザー空間のネットワーク ``CLONE_NEWNET``、``unshare()``、``setns()`` は現在無効です。``CLONE_NEWNET`` の clone " -"要求は権限に応じて ``EPERM`` または ``EINVAL``、unshare は ``EINVAL`` を返します。作成と切り替えは transport " -"分離の完了後に有効になります。" - msgid "netlink 端口与事件" msgstr "netlink のポートとイベント" @@ -427,3 +413,50 @@ msgstr "TCP のポート競合、IPv4/IPv6 とマップ形式のハンドシェ msgid "raw 和 AF_PACKET 的创建按网络 user owner 的 ``CAP_NET_RAW`` 授权。收包、地址绑定、设备选项、接口 ioctl、IPv6 路由、多播、错误和 ICMPv6 ping ID 冲突按创建网络匹配。传递 OFD 或切换任务网络后仍使用创建网络,非初始 socket 的私有全局控制返回 ``EOPNOTSUPP``。物理 ingress 和设备移除只作用于初始网络。AF_PACKET 的 loopback 发送返回 ``EOPNOTSUPP``。raw IPv4 先查询创建网络的路由,非初始或 loopback 路由返回 ``ENETUNREACH``,其物理发送仅在初始网络执行。" msgstr "raw と AF_PACKET の作成にはネットワークの user owner における ``CAP_NET_RAW`` が必要です。受信、アドレス bind、デバイスオプション、インターフェース ioctl、IPv6 経路、マルチキャスト、エラー、ICMPv6 ping ID の競合を作成元ネットワークで照合します。OFD 転送やタスクのネットワーク変更後も同じネットワークを使用します。非初期ソケットの独自グローバル制御は ``EOPNOTSUPP`` を返します。物理 ingress とデバイス削除は初期ネットワークだけに作用します。AF_PACKET のループバック送信は ``EOPNOTSUPP`` を返します。raw IPv4 は作成元ネットワークの経路を先に検索し、非初期またはループバック経路には ``ENETUNREACH`` を返します。物理送信は初期ネットワークで実行します。" + +msgid "" +"``/proc//ns/mnt``、``/proc//ns/user``、``/proc//ns/uts`` 与 " +"``/proc//ns/net`` 是 proc magic link。 读取链接或跟随它需要通过与 ``/proc//fd`` " +"相同的 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接键保留 PID 身份,每次成功跟随则取得目标当时的挂载图、用户、UTS" +" 或网络空间。" +msgstr "" +"``/proc//ns/mnt``、``/proc//ns/user``、``/proc//ns/uts``、``/proc//ns/net``" +" は proc magic link です。読み取りや追跡には、``/proc//fd`` と同じ " +"``PTRACE_MODE_READ_FSCREDS`` 権限検査が必要です。リンクのキーは PID " +"の識別情報を保持し、追跡が成功するたびに対象の現在のマウントグラフ、ユーザー、UTS、ネットワーク名前空間を取得します。" + +msgid "" +"跟随链接得到分离的 nsfs inode。mount、user、UTS 与 network 空间使用同一单调递增序列,首次 显示或创建句柄时分配 " +"inode,此后同一空间的全部句柄共享该身份。64 位序列耗尽 返回 ``EOVERFLOW``。链接显示为 " +"``mnt:[inode]``、``user:[inode]``、``uts:[inode]`` 或 ``net:[inode]``。 " +"每个后端按类型持有空间引用,最后一个路径释放时回收后端并释放空间。" +msgstr "" +"リンクを追跡すると、切り離された nsfs inode を取得します。mount、user、UTS、network " +"名前空間は共通の単調増加シーケンスを使います。最初の表示またはハンドル作成時に inode " +"を割り当て、同じ名前空間の全ハンドルがその識別情報を共有します。64 ビットのシーケンスが尽きると ``EOVERFLOW`` を返します。ラベルは " +"``mnt:[inode]``、``user:[inode]``、``uts:[inode]``、``net:[inode]`` " +"です。各型のバックエンドは名前空間を保持し、最後のパスの解放時にバックエンドと名前空間を解放します。" + +msgid "" +"network 切换要求当前用户空间和目标网络 owner 用户空间两侧的 " +"``CAP_SYS_ADMIN``,允许共享文件系统状态。成功时取得目标引用再释放旧引用, " +"已有套接字继续保留各自的创建网络。``NS_GET_NSTYPE`` 返回 ``CLONE_NEWNET``。 " +"初始网络由空指针表示,布尔查询接口区分有效初始网络句柄与无效路径。" +msgstr "" +"network の切り替えには、現在のユーザー名前空間と対象ネットワーク owner のユーザー名前空間の両方で ``CAP_SYS_ADMIN`` " +"が必要です。ファイルシステム状態の共有を許可します。成功時は、古い参照を解放する前に対象の参照を取得します。既存ソケットは作成時のネットワークを保持し、``NS_GET_NSTYPE``" +" は ``CLONE_NEWNET`` を返します。初期ネットワークは null " +"ポインターで表され、真偽値を返す照会インターフェースで有効な初期ネットワークハンドルと無効なパスを区別します。" + +msgid "" +"``clone()``、``clone3()`` 和 ``unshare()`` 接受 ``CLONE_NEWNET``。单独创建要求当前用户空间的 " +"``CAP_SYS_ADMIN``,与 ``CLONE_NEWUSER`` 组合时由候选用户空间拥有新网络。候选网络在 scheduler lock " +"外准备,失败时与其他候选状态一同释放,成功时将一个引用交给任务。单独 unshare 网络保留文件系统共享状态。``setns()`` 通过真实 " +"nsfs 句柄认证类型并检查当前与目标 owner 两侧权限,成功时切换任务引用。接口与套接字继续遵循各自的网络归属。" +msgstr "" +"``clone()``、``clone3()``、``unshare()`` は ``CLONE_NEWNET`` " +"を受け付けます。単独での作成には現在のユーザー名前空間の ``CAP_SYS_ADMIN`` が必要です。``CLONE_NEWUSER`` " +"と組み合わせると、候補ユーザー名前空間が新しいネットワークを所有します。候補ネットワークは scheduler lock " +"の外で準備し、失敗時には他の候補とともに解放します。成功時は一つの参照をタスクへ渡します。ネットワークだけの unshare " +"はファイルシステム状態の共有を維持します。``setns()`` は実際の nsfs ハンドルを認証し、現在と対象 owner " +"の両ユーザー名前空間の権限を検査してからタスク参照を置き換えます。インターフェースとソケットは、それぞれのネットワーク所有関係を引き続き使用します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 5750eff3..d16b4598 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -328,8 +328,30 @@ msgstr "" "として保持し、CREATE にはその owner における ``CAP_SYS_ADMIN`` が必要です。ポリシーと再構成の意味は " ":doc:`procfs` を参照してください。" -msgid "tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 ``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo 中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" -msgstr "tmpfs と proc のコンテキストはどちらも ``FSCONFIG_SET_STRING`` の ``source`` パラメーターを受け付けます。値は最大 255 バイトで、空文字列やカンマを含む文字列も使用できます。未設定の場合、ソースは ``none`` と表示されます。同じ設定段階で重複して設定すると ``EINVAL`` を返します。作成が成功した後、``fsmount`` が成功する前にパラメーターを設定すると ``EBUSY`` を返します。``fsmount`` の成功後と各再設定の成功後には、次の設定段階で新しい ``source`` を設定できます。再設定は既存マウントの mountinfo に表示されるソースを変更しません。作成または再設定に失敗した場合、保留中のソースは保持され、再試行できます。" +msgid "" +"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 捕获当前网络空间的 user owner,并要求其 ``CAP_SYS_ADMIN``。传统 sysfs " +"mount 使用同一 owner。CREATE 再次检查捕获的 owner,调用者随后切换网络不会改变该权限作用域。sysfs 上下文接受通用 ``source``、``ro`` 和 " +"``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的 只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读 " +"属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" +msgstr "" +"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` は現在のネットワーク名前空間の user owner を保持し、その ``CAP_SYS_ADMIN`` " +"を要求します。従来の sysfs mount も同じ owner を使用します。CREATE は保持した owner " +"の権限を再確認します。その後ネットワークを切り替えても、この権限スコープは維持されます。sysfs コンテキストは汎用の ``source``、``ro``、``rw`` " +"パラメーターを受け付け、未知の固有オプションには ``EINVAL`` を返します。CREATE の読み取り専用設定は共有バックエンドに保持され、RECONFIGURE " +"で更新できます。``fsmount`` " +"の独立した読み取り専用属性は、そのマウントを引き続き制限します。メモリー割り当て、記述子の登録、作成に失敗した場合は候補の参照を解放し、再試行できます。" + +msgid "" +"tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 " +"字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 " +"``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo " +"中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" +msgstr "" +"tmpfs、proc、sysfs のコンテキストは ``FSCONFIG_SET_STRING`` の ``source`` パラメーターを受け付けます。値は最大 255 " +"バイトで、空文字列やカンマを含む文字列も使用できます。未設定の場合、ソースは ``none`` と表示されます。同じ設定段階で重複して設定すると ``EINVAL`` " +"を返します。作成が成功した後、``fsmount`` が成功する前にパラメーターを設定すると ``EBUSY`` を返します。``fsmount`` " +"の成功後と各再設定の成功後には、次の設定段階で新しい ``source`` を設定できます。再設定は既存マウントの mountinfo " +"に表示されるソースを保持します。作成または再設定に失敗した場合、保留中のソースは保持され、再試行できます。" msgid "" "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` " @@ -407,9 +429,6 @@ msgstr "" msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUSER)`` は通常の読み取り専用 ``/proc//ns/user`` ハンドルを受け付けます。現在のユーザー名前空間への再参加、同じグループの別の活動中スレッド、他のタスクとのファイルシステム状態の共有は ``EINVAL`` になります。対象ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。現在の名前空間の祖先はこの権限検査を通過できません。" -msgid "nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS``、``CLONE_NEWUSER`` 或 ``CLONE_NEWUTS``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。" -msgstr "nsfs ハンドルはメタデータと ioctl を提供します。書き込みモードまたは ``O_TRUNC`` で開くと ``EPERM`` を返し、``O_PATH`` はこれらのフラグを無視します。通常 FD のスカラー、位置指定、ベクトル読み取りは ``EINVAL``、書き込みは ``EBADF``、有効な ``whence`` の ``lseek()`` は ``ESPIPE`` を返します。``NS_GET_NSTYPE`` は実際の型に応じて ``CLONE_NEWNS``、``CLONE_NEWUSER`` または ``CLONE_NEWUTS`` を返し、``FIONREAD`` はゼロを書き込みます。未対応の namespace ioctl は ``ENOTTY`` を返します。``O_PATH`` FD はメタデータ照会に使えますが、読み書き、シーク、ioctl は実行できません。" - msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" msgstr "切り替え後の root と cwd は対象マウントグラフの可視ルートを指します。既存の FD と umask は保持されます。元のプロセスが終了した後や名前空間を切り替えた後もハンドルを使用できます。" @@ -419,9 +438,6 @@ msgstr "名前空間への参加" msgid "成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask 保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" msgstr "ユーザー名前空間への参加が成功すると、グローバル UID/GID、補助グループ、no_new_privs、root、cwd、umask を保持します。permitted、effective、bounding にはサポートする全能力を設定し、inheritable、ambient、securebits をクリアします。作用域内の権限が増加すると親死亡シグナルを解除してダンプ可能性を制限します。検査失敗時は元の資格情報とファイルシステム状態を保持します。" -msgid "无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 ``EINVAL``。当前支持 mount、user 与 UTS 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。" -msgstr "無効な FD と ``O_PATH`` FD は ``EBADF`` を返します。nsfs 以外の FD、型の不一致、未対応の型は ``EINVAL`` を返します。mount、user、UTS のハンドルに対応します。pidfd と nsfs ハンドルの bind mount は未接続です。:doc:`../core-api/mount-namespaces` を参照してください。" - msgid "" "bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 owner " "的覆盖挂载不能单独移动或卸载,普通与 lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 ``EINVAL``, 递归 bind 剪除锁定的 " @@ -475,3 +491,69 @@ msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUTS)`` は、通常の読み msgid "当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 文件 I/O 规则推进。此处尚未实现 Linux strict sysctl 对忽略写入保留偏移的行为。" msgstr "現在位置が名前の末尾を超える書き込みは名前を保持し、受け付けた入力バイト数を返します。ファイル位置は通常のファイル I/O 規則に従って進みます。Linux strict sysctl のように無視した書き込みの位置を保持する動作は未実装です。" + +msgid "创建网络命名空间" +msgstr "ネットワーク名前空間の作成" + +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNET`` 为子任务建立独立网络空间, " +"``unshare(CLONE_NEWNET)`` 为调用任务建立独立网络空间。单独创建要求当前用户 空间的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。同时指定 ``CLONE_NEWUSER`` 时,新网络由候选用户空间拥有。普通 " +"fork 及未指定该标志的 clone 共享原网络。" +msgstr "" +"``clone()`` と ``clone3()`` の ``CLONE_NEWNET`` " +"は、子タスク用の独立したネットワークを作成します。``unshare(CLONE_NEWNET)`` " +"は呼び出し元用に作成します。単独での作成には現在のユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、不足時は ``EPERM`` " +"を返します。``CLONE_NEWUSER`` と組み合わせると、候補ユーザー名前空間が新しいネットワークを所有します。通常の fork " +"と、このフラグを指定しない clone は元のネットワークを共有します。" + +msgid "" +"新网络仅包含默认 down 的 ``lo``,置为 up 时配置回环地址。接口、路由、IPv6 " +"协议状态和套接字匹配按网络隔离。已有套接字保留创建时的网络,任务切换后也 继续使用该网络。单独创建或切换网络保留文件系统共享状态。组合创建先准备全部 " +"候选状态,准备失败保留原空间、凭据、路径和进程发布状态。内部生命周期和已 实现网络范围见 " +":doc:`../core-api/mount-namespaces`。" +msgstr "" +"新しいネットワークには、初期状態が down の ``lo`` だけが存在します。up " +"にするとループバックアドレスを設定します。インターフェース、経路、IPv6 " +"プロトコル状態、ソケットの照合はネットワークごとに分離されます。既存ソケットはタスクの移動後も作成時のネットワークを保持します。ネットワークだけの作成や切り替えは、ファイルシステム状態の共有を維持します。組み合わせた作成では、すべての候補を先に準備します。準備に失敗すると、元の名前空間、資格情報、パス、プロセスの公開状態を保持します。ライフタイムと実装済みのネットワーク範囲は" +" :doc:`../core-api/mount-namespaces` を参照してください。" + +msgid "" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNET)`` 接受普通只读的 " +"``/proc//ns/net`` 句柄。调用者需要当前用户空间和目标网络 owner 用户 空间两侧的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。成功后替换任务网络 引用,root、cwd、umask " +"和已有套接字的创建网络保留。允许共享 ``CLONE_FS``, 句柄继续保留目标网络,权限或类型检查失败时保留调用者原网络。" +msgstr "" +"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNET)`` は、通常の読み取り専用 " +"``/proc//ns/net`` ハンドルを受け付けます。呼び出し元には、現在のユーザー名前空間と、対象ネットワーク owner " +"のユーザー名前空間の両方で ``CAP_SYS_ADMIN`` が必要です。不足時は ``EPERM`` " +"を返します。成功時はタスクのネットワーク参照を置き換え、root、cwd、umask、既存ソケットの作成時ネットワークを維持します。``CLONE_FS``" +" の共有を許可します。ハンドルは対象ネットワークを保持し、権限や型の検査に失敗すると呼び出し元の元のネットワークを維持します。" + +msgid "" +"无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 " +"``EINVAL``。当前支持 mount、user、UTS 与 network 句柄,pidfd 和 nsfs 句柄的 bind mount " +"仍未接通。参见 :doc:`../core-api/mount-namespaces`。" +msgstr "" +"無効な FD と ``O_PATH`` FD は ``EBADF`` を返します。nsfs 以外の FD、型の不一致、未対応の型は " +"``EINVAL`` を返します。mount、user、UTS、network ハンドルに対応します。pidfd と nsfs ハンドルの bind " +"mount は未実装です。:doc:`../core-api/mount-namespaces` を参照してください。" + +msgid "" +"nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` " +"忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 " +"``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 " +"``CLONE_NEWNS``、``CLONE_NEWUSER``、 ``CLONE_NEWUTS`` 或 ``CLONE_NEWNET``。 " +"``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD " +"可用于元数据查询,但不能 读写、定位或执行 ioctl。" +msgstr "" +"nsfs ハンドルはメタデータと ioctl を提供します。書き込み用または ``O_TRUNC`` を指定したオープンは ``EPERM`` " +"を返します。``O_PATH`` はこれらのフラグを無視します。通常の FD のスカラー読み取り、位置指定読み取り、ベクトル読み取りは " +"``EINVAL``、書き込みは ``EBADF``、有効な ``whence`` での ``lseek()`` は ``ESPIPE`` " +"を返します。``NS_GET_NSTYPE`` はハンドルに応じて " +"``CLONE_NEWNS``、``CLONE_NEWUSER``、``CLONE_NEWUTS``、``CLONE_NEWNET`` " +"を返します。``FIONREAD`` はゼロを書き戻し、未対応の namespace ioctl は ``ENOTTY`` " +"を返します。``O_PATH`` FD はメタデータ照会に対応し、読み書き、シーク、ioctl は拒否します。" + +msgid "普通文件和 socket 均可使用这些锁命令。socket 按完整的匿名 inode 编号识别, 同一端点的别名共享冲突范围,不同端点的锁独立。socket 的 ``SEEK_END`` 基准 为零,``O_PATH`` 描述符返回 ``EBADF``。关闭 socket 的 POSIX 锁释放规则与 普通文件相同,OFD 锁持续到最后一个引用释放。" +msgstr "通常ファイルと socket はこれらのロックコマンドを使用できます。socket は匿名 inode 番号全体で識別し、同じエンドポイントの別名は競合範囲を共有します。異なるエンドポイントのロックは独立します。socket の ``SEEK_END`` 基準はゼロで、``O_PATH`` 記述子は ``EBADF`` を返します。socket を閉じた際の POSIX ロック解放規則は通常ファイルと同じです。OFD ロックは最後の参照が解放されるまで保持されます。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po index 338ef941..796f4215 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po @@ -68,18 +68,6 @@ msgstr "" msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP、TCP 和 raw 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。" msgstr "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト形式を使用します。アドレス scope の符号化は rtnetlink の値と異なります。アドレス、経路、UDP、TCP、raw の表は呼び出し元の現在のネットワーク scope に従います。スナップショットは内部状態をコピーし、待機をまたいでコピーだけを保持します。" -msgid "" -"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo``" -" 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 " -"ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 transport " -"隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。" -msgstr "" -"各ネットワーク名前空間はインターフェース、loopback、IPv4 経路と、IPv6 のアドレス、経路、近隣、多播、送信待ちパケット、断片再構成、PMTU、断片番号、ICMP " -"エラーのレート制限を個別に保持します。新しい空間の ``lo`` は down で IPv6 アドレスを持たず、最初の up で ``::1/128`` と host route " -"を設定します。テーブルとキューの容量は個別に計量し、空間破棄時にプロトコル資源を解放します。物理 NIC 登録と ingress は初期空間に属します。ユーザー空間のネットワーク " -"``CLONE_NEWNET``、``unshare()``、``setns()`` は transport 分離の完了後に有効になります。内部ライフサイクルと proc の範囲は " -":doc:`../core-api/mount-namespaces` を参照してください。" - msgid "范围与标准" msgstr "範囲と標準" @@ -104,3 +92,32 @@ msgstr "Linux と同様に、TCP、UDP、および raw socket の bind はスコ msgid "raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 ``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD 后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。" msgstr "raw IPv6 ソケットは作成元ネットワークを独立して保持し、作成にはその user owner における ``CAP_NET_RAW`` が必要です。アドレス bind、経路、送受信、マルチキャスト所属、ICMPv6 エラー、ping ID の競合、デバイスオプションを作成元ネットワークで隔離し、FD 転送後も同じネットワークを使います。最終 close で元のネットワークのマルチキャストから脱退し、参照を解放します。物理デバイス削除は初期ネットワークの該当ソケットだけにエラーを通知します。" + +msgid "" +"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP " +"错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host " +"route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态通过 " +"``clone()``、``clone3()`` 或 ``unshare()`` 的 ``CLONE_NEWNET`` 创建网络,通过 " +"``/proc//ns/net`` 句柄和 ``setns()`` 切换网络。授权与失败语义见 :doc:`abi`,内部生命周期与 " +"proc 范围见 :doc:`../core-api/mount-namespaces`。" +msgstr "" +"各ネットワーク名前空間は、インターフェース、loopback、IPv4 経路、IPv6 " +"アドレスと経路、近隣、多播、送信待ちパケット、フラグメント再構成、PMTU、フラグメント ID、ICMP " +"エラーのレート制限を個別に所有します。新しい名前空間の ``lo`` は初期状態が down で、IPv6 アドレスを持ちません。最初に up " +"にすると ``::1/128`` と host route " +"を設定します。各テーブルとキューは容量を独立して計数し、名前空間の破棄時にプロトコル資源を解放します。物理 NIC の登録と ingress " +"は初期名前空間に属します。ユーザー空間は ``clone()``、``clone3()``、``unshare()`` の " +"``CLONE_NEWNET`` でネットワークを作成し、``/proc//ns/net`` ハンドルと ``setns()`` " +"で切り替えます。権限と失敗時の動作は :doc:`abi`、ライフタイムと proc の範囲は " +":doc:`../core-api/mount-namespaces` を参照してください。" + +msgid "netlink socket 的 ``SO_SNDBUF`` 和 ``SO_RCVBUF`` 默认有效大小均为 65536 字节。 设置值按无符号整数裁剪到 65536 后乘二,发送和接收的最小有效值分别为 4608 和 2304 字节,查询返回有效大小。发送数据报同时受 8192 字节硬上限及有效发送 缓冲区减 32 字节的限制,超过时返回 ``EMSGSIZE``。短设置值、错误用户指针和 负长度返回错误并保留原设置。" +msgstr "netlink socket の ``SO_SNDBUF`` と ``SO_RCVBUF`` のデフォルト実効サイズはそれぞれ 65536 バイトです。設定値を符号なし整数として 65536 に制限してから 2 倍にし、送信と受信の最小実効値をそれぞれ 4608 バイトと 2304 バイトにします。取得時は実効サイズを返します。送信データグラムには 8192 バイトの上限と実効送信バッファから 32 バイトを引いた制限を適用し、超過時は ``EMSGSIZE`` を返します。短い設定値、不正なユーザーポインター、負の長さはエラーとなり、元の設定を保持します。" + +msgid "接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 位置。预留失败时返回 ``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 属于实际 socket,传递 FD 或切换网络后继续保留。" +msgstr "受信キューは各データグラムを 8192 バイトとして保守的に計上します。複数部分の照会ではデータと終了メッセージ用に 2 枠を予約します。予約失敗時はネットワーク状態を変更する前に ``ENOBUFS`` を返します。受信バッファを縮小しても既存のメッセージを保持し、新規メッセージは容量の回復を待ちます。読み取りで容量を解放し、拡張時は書き込み可能状態を更新します。バッファ設定は実際の socket に属し、FD の受け渡しやネットワークの切り替え後も保持します。" + +msgid "" +"路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含 " +"被忽略的尾部;全部消息无效时不生成回复。预扫描和实际处理使用同一前缀边界。" +msgstr "ルート要求はデータグラム内の有効なメッセージの先頭部分を順番に処理し、最初の不正または不完全なメッセージとそれ以降のバイトを無視します。最後の完全なメッセージではアラインメントのパディングを省略できます。送信が成功すると、無視した末尾を含むデータグラム全体のバイト数を返します。有効なメッセージがない場合は返信を生成しません。事前走査と実際の処理は同じ先頭部分の境界を使用します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po index 383387c4..f26dddd1 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/procfs.po @@ -388,11 +388,24 @@ msgstr "" msgid "``status`` 的四个 ``Uid``、四个 ``Gid`` 和 ``Groups`` 中的补充组按生成视图时 调用者的用户命名空间输出。未映射的 ID 显示为 65534,目标任务的内部凭据保持 全局 ID。成功打开的文件保存已渲染字节,之后切换空间或转交描述符继续读取 原视图,重新打开时使用新调用者的空间。" msgstr "``status`` の四つの ``Uid``、四つの ``Gid`` と補助 ``Groups`` は、ビューを生成する呼び出し元のユーザー名前空間で表示します。未マップの ID は 65534 となり、対象タスクの内部資格情報はグローバル ID を保持します。正常にオープンしたファイルは描画済みバイト列を保存するため、名前空間の切り替えや記述子の転送後も元のビューを読みます。再オープンでは新しい呼び出し元の空間を使用します。" -msgid "``ns/mnt``、``ns/user``" -msgstr "``ns/mnt``、``ns/user``" +msgid "``ns/mnt``、``ns/user``、``ns/uts``、``ns/net``" +msgstr "``ns/mnt``、``ns/user``、``ns/uts``、``ns/net``" -msgid "``ns`` 目录枚举 ``mnt`` 和 ``user``。读取或跟随链接须通过现有 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接保留 PID 身份,每次跟随取得目标 当时的空间。nsfs 句柄在原进程退出或切换空间后继续保留原空间,链接显示为 ``mnt:[inode]`` 或 ``user:[inode]``。同一空间的句柄共享稳定 inode,不同空间 在共同的 nsfs 设备上使用独立 inode。切换接口见 :doc:`abi`。" -msgstr "``ns`` ディレクトリは ``mnt`` と ``user`` を列挙します。リンクの読み取りと追跡には既存の ``PTRACE_MODE_READ_FSCREDS`` 検査が必要です。リンクは PID の同一性を保持し、追跡するたびに対象の現在の名前空間を取得します。nsfs ハンドルは元のプロセスの終了や名前空間の切り替え後も元の名前空間を保持します。リンク表示は ``mnt:[inode]`` または ``user:[inode]`` です。同じ名前空間のハンドルは安定した inode を共有し、異なる名前空間は共通の nsfs デバイス上で別々の inode を使います。切り替えは :doc:`abi` を参照してください。" +msgid "目标任务的挂载、用户、UTS 和网络命名空间 magic link,跟随时取得保留空间的 nsfs 句柄。" +msgstr "対象タスクのマウント、ユーザー、UTS、ネットワーク名前空間の magic link。追跡すると名前空間を保持する nsfs ハンドルを取得します。" -msgid "目标任务的挂载与用户命名空间 magic link,跟随时取得保留空间的 nsfs 句柄。" -msgstr "対象タスクのマウントおよびユーザー名前空間の magic link です。リンクをたどると、その名前空間を保持する nsfs ハンドルを取得します。" +msgid "" +"``ns`` 目录枚举 ``mnt``、``user``、``uts`` 和 ``net``。读取或跟随链接须通过现有 " +"``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接保留 PID 身份,每次跟随取得目标 当时的空间。nsfs " +"句柄在原进程退出或切换空间后继续保留原空间,链接显示为 " +"``mnt:[inode]``、``user:[inode]``、``uts:[inode]`` 或 " +"``net:[inode]``。同一空间的句柄共享稳定 inode,不同空间 在共同的 nsfs 设备上使用独立 inode。切换接口见 " +":doc:`abi`。" +msgstr "" +"``ns`` ディレクトリは ``mnt``、``user``、``uts``、``net`` を列挙します。リンクの読み取りや追跡には、既存の " +"``PTRACE_MODE_READ_FSCREDS`` 権限検査が必要です。リンクは PID " +"の識別情報を保持し、追跡するたびに対象の現在の名前空間を取得します。nsfs " +"ハンドルは、対象が終了または名前空間を切り替えた後も元の名前空間を保持します。ラベルは " +"``mnt:[inode]``、``user:[inode]``、``uts:[inode]``、``net:[inode]`` " +"です。同じ名前空間のハンドルは安定した inode を共有し、異なる名前空間は共通の nsfs デバイス上で個別の inode " +"を使用します。切り替えインターフェースは :doc:`abi` を参照してください。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 58175751..5ea412b0 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -116,6 +116,20 @@ bind 挂载上的写入返回 ``EROFS``。 当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 文件 I/O 规则推进。此处尚未实现 Linux strict sysctl 对忽略写入保留偏移的行为。 +创建网络命名空间 +================ + +``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNET`` 为子任务建立独立网络空间, +``unshare(CLONE_NEWNET)`` 为调用任务建立独立网络空间。单独创建要求当前用户 +空间的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。同时指定 ``CLONE_NEWUSER`` +时,新网络由候选用户空间拥有。普通 fork 及未指定该标志的 clone 共享原网络。 + +新网络仅包含默认 down 的 ``lo``,置为 up 时配置回环地址。接口、路由、IPv6 +协议状态和套接字匹配按网络隔离。已有套接字保留创建时的网络,任务切换后也 +继续使用该网络。单独创建或切换网络保留文件系统共享状态。组合创建先准备全部 +候选状态,准备失败保留原空间、凭据、路径和进程发布状态。内部生命周期和已 +实现网络范围见 :doc:`../core-api/mount-namespaces`。 + 加入命名空间 ============ @@ -144,15 +158,21 @@ ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并 ``CLONE_FS`` 状态,root、cwd 和 umask 保留。句柄持有目标 UTS 空间的引用, 目标进程退出或切换空间后仍可使用。 +``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNET)`` 接受普通只读的 +``/proc//ns/net`` 句柄。调用者需要当前用户空间和目标网络 owner 用户 +空间两侧的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。成功后替换任务网络 +引用,root、cwd、umask 和已有套接字的创建网络保留。允许共享 ``CLONE_FS``, +句柄继续保留目标网络,权限或类型检查失败时保留调用者原网络。 + 无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 -类型返回 ``EINVAL``。当前支持 mount、user 与 UTS 句柄,pidfd 和 nsfs 句柄的 bind +类型返回 ``EINVAL``。当前支持 mount、user、UTS 与 network 句柄,pidfd 和 nsfs 句柄的 bind mount 仍未接通。参见 :doc:`../core-api/mount-namespaces`。 nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` 忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 ``lseek()`` 返回 ``ESPIPE``。 -``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS``、``CLONE_NEWUSER`` 或 -``CLONE_NEWUTS``。 +``NS_GET_NSTYPE`` 按实际句柄返回 ``CLONE_NEWNS``、``CLONE_NEWUSER``、 +``CLONE_NEWUTS`` 或 ``CLONE_NEWNET``。 ``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD 可用于元数据查询,但不能 读写、定位或执行 ioctl。 @@ -226,7 +246,14 @@ inode 引用释放且相关缓存回收后,设备号才能重用。 ``fsmount`` 指定。proc 的全局 PID 视图保留初始用户空间 owner,CREATE 要求 该 owner 的 ``CAP_SYS_ADMIN``。策略及重配置语义见 :doc:`procfs`。 -tmpfs 和 proc 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 +``fsopen("sysfs", FSOPEN_CLOEXEC)`` 捕获当前网络空间的 user owner,并要求其 +``CAP_SYS_ADMIN``。传统 sysfs mount 使用同一 owner。CREATE 再次检查捕获的 +owner,调用者随后切换网络不会改变该权限作用域。sysfs 上下文接受通用 +``source``、``ro`` 和 ``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的 +只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读 +属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。 + +tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 ``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 @@ -317,6 +344,11 @@ bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员 文件描述所有,dup 和 fork 共享锁,最后一个引用释放时清锁并唤醒等待者。 在途系统调用和传递中的描述符引用也会延长 OFD 锁的生命周期。 +普通文件和 socket 均可使用这些锁命令。socket 按完整的匿名 inode 编号识别, +同一端点的别名共享冲突范围,不同端点的锁独立。socket 的 ``SEEK_END`` 基准 +为零,``O_PATH`` 描述符返回 ``EBADF``。关闭 socket 的 POSIX 锁释放规则与 +普通文件相同,OFD 锁持续到最后一个引用释放。 + 两类锁使用同一 inode 和范围冲突规则,包括同一进程持有的不同类型锁。相同 OFD 上的锁可转换、拆分和合并。OFD 请求的 ``l_pid`` 必须为零,否则返回 ``EINVAL``。查询到 OFD 冲突时 ``l_pid`` 为 -1,查询到 POSIX 冲突时为持锁 diff --git a/Documentation/userspace-api/ipv6.rst b/Documentation/userspace-api/ipv6.rst index 9c0440a2..daac689b 100644 --- a/Documentation/userspace-api/ipv6.rst +++ b/Documentation/userspace-api/ipv6.rst @@ -36,6 +36,21 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。 +netlink socket 的 ``SO_SNDBUF`` 和 ``SO_RCVBUF`` 默认有效大小均为 65536 字节。 +设置值按无符号整数裁剪到 65536 后乘二,发送和接收的最小有效值分别为 4608 +和 2304 字节,查询返回有效大小。发送数据报同时受 8192 字节硬上限及有效发送 +缓冲区减 32 字节的限制,超过时返回 ``EMSGSIZE``。短设置值、错误用户指针和 +负长度返回错误并保留原设置。 + +接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 +位置。预留失败时返回 ``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 +已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 +属于实际 socket,传递 FD 或切换网络后继续保留。 + +路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 +字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含 +被忽略的尾部;全部消息无效时不生成回复。预扫描和实际处理使用同一前缀边界。 + 多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。 @@ -44,7 +59,7 @@ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回 raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 ``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD 后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。 -每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态 ``CLONE_NEWNET``、``unshare()`` 和 ``setns()`` 网络空间入口将在 transport 隔离完成后接通。内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。 +每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态通过 ``clone()``、``clone3()`` 或 ``unshare()`` 的 ``CLONE_NEWNET`` 创建网络,通过 ``/proc//ns/net`` 句柄和 ``setns()`` 切换网络。授权与失败语义见 :doc:`abi`,内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。 范围与标准 ========== diff --git a/Documentation/userspace-api/procfs.rst b/Documentation/userspace-api/procfs.rst index 95abbbdd..e2935045 100644 --- a/Documentation/userspace-api/procfs.rst +++ b/Documentation/userspace-api/procfs.rst @@ -98,13 +98,13 @@ flush 的独立统计行/扩展字段。同步统计不分配内存;异步记 * - ``fdinfo/FD`` - 共享 OFD 的位置、用户可见打开标志、该描述符的 CLOEXEC、mount ID/inode, 以及 eventfd/timerfd/epoll 的专项元数据;读取不消费事件或推进定时器。 - * - ``ns/mnt``、``ns/user`` - - 目标任务的挂载与用户命名空间 magic link,跟随时取得保留空间的 nsfs 句柄。 + * - ``ns/mnt``、``ns/user``、``ns/uts``、``ns/net`` + - 目标任务的挂载、用户、UTS 和网络命名空间 magic link,跟随时取得保留空间的 nsfs 句柄。 -``ns`` 目录枚举 ``mnt`` 和 ``user``。读取或跟随链接须通过现有 +``ns`` 目录枚举 ``mnt``、``user``、``uts`` 和 ``net``。读取或跟随链接须通过现有 ``PTRACE_MODE_READ_FSCREDS`` 权限检查。链接保留 PID 身份,每次跟随取得目标 当时的空间。nsfs 句柄在原进程退出或切换空间后继续保留原空间,链接显示为 -``mnt:[inode]`` 或 ``user:[inode]``。同一空间的句柄共享稳定 inode,不同空间 +``mnt:[inode]``、``user:[inode]``、``uts:[inode]`` 或 ``net:[inode]``。同一空间的句柄共享稳定 inode,不同空间 在共同的 nsfs 设备上使用独立 inode。切换接口见 :doc:`abi`。 PSS 通过遍历实际用户 PTE,按物理页的用户映射数分摊;共享同一地址空间的 diff --git a/fs/nsfs/namespace.c b/fs/nsfs/namespace.c index 7f476a1b..1acacb92 100644 --- a/fs/nsfs/namespace.c +++ b/fs/nsfs/namespace.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -20,10 +21,11 @@ struct nsfs_context { struct vfs_namespace *mount; struct user_namespace *user; struct uts_namespace *uts; + struct net_namespace *net; } ns; }; -static uint64_t next_inode = 1, initial_user_inode, initial_uts_inode; +static uint64_t next_inode = 1, initial_user_inode, initial_uts_inode, initial_net_inode; static const struct vfs_backend_ops nsfs_ops; @@ -45,7 +47,8 @@ static bool nsfs_inode(const struct nsfs_context *context, const struct storage_ } /** @brief Render a typed namespace identity without allocating a path. - * @param type CLONE_NEWNS, CLONE_NEWUSER or CLONE_NEWUTS. @param inode Assigned identity. + * @param type CLONE_NEWNS, CLONE_NEWUSER, CLONE_NEWUTS or CLONE_NEWNET. + * @param inode Assigned identity. * @param buffer Required output. @param capacity Maximum bytes, without NUL. * @return Copied byte count or -EOVERFLOW for an exhausted identity allocator. */ @@ -57,6 +60,7 @@ static int nsfs_label(uint32_t type, uint64_t inode, char *buffer, size_t capaci const char *prefix = "mnt:["; if (type == CLONE_NEWUSER) prefix = "user:["; if (type == CLONE_NEWUTS) prefix = "uts:["; + if (type == CLONE_NEWNET) prefix = "net:["; text_string(&text, prefix); text_unsigned(&text, inode); text_string(&text, "]"); @@ -84,6 +88,13 @@ int nsfs_uts_readlink(struct uts_namespace *ns, char *buffer, size_t capacity) nsfs_identity(ns ? &ns->nsfs_inode : &initial_uts_inode), buffer, capacity); } +/** @copydoc nsfs_net_readlink */ +int nsfs_net_readlink(struct net_namespace *ns, char *buffer, size_t capacity) +{ + return nsfs_label(CLONE_NEWNET, + nsfs_identity(ns ? &ns->nsfs_inode : &initial_net_inode), buffer, capacity); +} + /** @brief A detached namespace backend has no named children. */ static int nsfs_lookup(void *context, const struct storage_node *parent, const char *name, struct storage_node *out) @@ -121,6 +132,7 @@ static void nsfs_destroy(void *context) struct nsfs_context *capture = context; if (capture->type == CLONE_NEWUSER) user_namespace_put(capture->ns.user); else if (capture->type == CLONE_NEWUTS) uts_namespace_put(capture->ns.uts); + else if (capture->type == CLONE_NEWNET) net_namespace_put(capture->ns.net); else vfs_namespace_put(capture->ns.mount); kernel_free(capture); } @@ -203,6 +215,7 @@ static int nsfs_create_handle(const struct nsfs_context *value, struct vfs_path *context = *value; if (context->type == CLONE_NEWUSER) user_namespace_get(context->ns.user); else if (context->type == CLONE_NEWUTS) uts_namespace_get(context->ns.uts); + else if (context->type == CLONE_NEWNET) net_namespace_get(context->ns.net); else vfs_namespace_get(context->ns.mount); struct storage_node root = {.type = RELIEFOS_FS_TYPE_DIR}; struct storage_node node = {.type = RELIEFOS_FS_TYPE_FILE, @@ -242,6 +255,14 @@ int nsfs_create_uts_path(struct uts_namespace *ns, struct vfs_path *out) return nsfs_create_handle(&value, out); } +/** @copydoc nsfs_create_net_path */ +int nsfs_create_net_path(struct net_namespace *ns, struct vfs_path *out) +{ + const struct nsfs_context value = {.type = CLONE_NEWNET, + .inode = nsfs_identity(ns ? &ns->nsfs_inode : &initial_net_inode), .ns.net = ns}; + return nsfs_create_handle(&value, out); +} + /** @brief Authenticate provider, retained inode and backend pin together. * @param path Borrowed path, nullable. @return Borrowed capture or NULL. * Execution ownership and the held path stabilize the entire capture. @@ -281,6 +302,16 @@ bool nsfs_path_uts_namespace(const struct vfs_path *path, struct uts_namespace * return true; } +/** @copydoc nsfs_path_net_namespace */ +bool nsfs_path_net_namespace(const struct vfs_path *path, struct net_namespace **out) +{ + struct nsfs_context *context = nsfs_path_context(path); + *out = NULL; + if (!context || context->type != CLONE_NEWNET) return false; + *out = context->ns.net; + return true; +} + /** @copydoc nsfs_path_type */ uint32_t nsfs_path_type(const struct vfs_path *path) { diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index cb5a1aab..96fc9213 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -865,7 +865,8 @@ int proc_mount_node_identity(const char *name,struct task_identity **out,bool *m if(rc)return rc==-ESRCH ? -RELIEFOS_ENOENT : rc; *magic = file && (proc_fd_number(file) >= 0 || proc_text_eq(file, "cwd") || proc_text_eq(file, "root") || proc_text_eq(file, "exe") || - proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user") || proc_text_eq(file, "ns/uts")); + proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user") || + proc_text_eq(file, "ns/uts") || proc_text_eq(file, "ns/net")); return 0; } @@ -898,7 +899,7 @@ int proc_mount_magic_stat(const char *name,struct linux_stat_abi *out) * @param name Live intrinsic proc key, already checked against its retained PID. * @param out Receives one owned path; empty on failure. * @return Zero or negative errno. A namespace link captures the target's - * current mount, user or UTS namespace. The proc link retains only PID identity. + * current mount, user, UTS or network namespace. The proc link retains PID identity. */ int proc_mount_magic_target(const char *name,struct vfs_path *out) { @@ -913,6 +914,7 @@ int proc_mount_magic_target(const char *name,struct vfs_path *out) if (proc_text_eq(file, "ns/mnt")) return nsfs_create_path(sched_task_namespace(task), out); if (proc_text_eq(file, "ns/user")) return nsfs_create_user_path(task->user_ns, out); if (proc_text_eq(file, "ns/uts")) return nsfs_create_uts_path(task->uts_ns, out); + if (proc_text_eq(file, "ns/net")) return nsfs_create_net_path(task->net_ns, out); struct task_fs_paths *paths=sched_task_paths(task); if(proc_text_eq(file,"cwd"))vfs_path_get(&paths->cwd,out); else if(proc_text_eq(file,"root"))vfs_path_get(&paths->root,out); @@ -1117,7 +1119,8 @@ int proc_lookup(const char *path, struct storage_node *out) int kind = proc_path_kind(path, &file, &pid); if ((kind == 2 || kind == 3) && (proc_text_eq(file, "ns") || proc_text_eq(file, "ns/mnt") || - proc_text_eq(file, "ns/user") || proc_text_eq(file, "ns/uts"))) { + proc_text_eq(file, "ns/user") || proc_text_eq(file, "ns/uts") || + proc_text_eq(file, "ns/net"))) { if (!(kind == 3 ? sched_current_task() : sched_find(pid))) return -RELIEFOS_ENOENT; if (out) *out = (struct storage_node){.flags = STORAGE_NODE_FLAG_PROC, .type = proc_text_eq(file, "ns") ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_SYMLINK}; @@ -1375,10 +1378,12 @@ int proc_readlink(const char *path, char *buffer, uint32_t capacity) } task = kind == 3 ? caller : sched_find(pid); if (!task) return -RELIEFOS_ENOENT; - if (proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user") || proc_text_eq(file, "ns/uts")) { + if (proc_text_eq(file, "ns/mnt") || proc_text_eq(file, "ns/user") || + proc_text_eq(file, "ns/uts") || proc_text_eq(file, "ns/net")) { if (!proc_stat_mm_visible(caller, task)) return -RELIEFOS_EACCES; if (proc_text_eq(file, "ns/user")) return nsfs_user_readlink(task->user_ns, buffer, capacity); if (proc_text_eq(file, "ns/uts")) return nsfs_uts_readlink(task->uts_ns, buffer, capacity); + if (proc_text_eq(file, "ns/net")) return nsfs_net_readlink(task->net_ns, buffer, capacity); return nsfs_readlink(sched_task_namespace(task), buffer, capacity); } if (!file || (!proc_text_eq(file, "exe") && !proc_text_eq(file, "cwd") && !proc_text_eq(file, "root") && proc_fd_number(file) < 0)) @@ -1513,7 +1518,7 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * if (kind == 3) pid = sched_current_pid(); if ((kind == 2 || kind == 3) && proc_text_eq(file, "ns")) { if (!sched_find(pid)) return -RELIEFOS_ENOENT; - static const char *const namespaces[] = {"mnt", "user", "uts"}; + static const char *const namespaces[] = {"mnt", "user", "uts", "net"}; if (*offset >= sizeof(namespaces) / sizeof(namespaces[0])) return 0; *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_SYMLINK}; proc_copy(entry->name, sizeof(entry->name), namespaces[(*offset)++]); @@ -1629,7 +1634,8 @@ int proc_control_permissions(const char *name, const struct storage_node *node, const char *leaf = NULL; struct task *owner = proc_view_task(name, &leaf); if (owner && (proc_text_eq(leaf, "ns") || proc_text_eq(leaf, "ns/mnt") || - proc_text_eq(leaf, "ns/user") || proc_text_eq(leaf, "ns/uts"))) { + proc_text_eq(leaf, "ns/user") || proc_text_eq(leaf, "ns/uts") || + proc_text_eq(leaf, "ns/net"))) { value->mode = node->type == RELIEFOS_FS_TYPE_DIR ? 0511 : 0777; if (!sched_task_mm(owner)->nondumpable) { value->uid = owner->euid; diff --git a/fs/vfs/pseudo.c b/fs/vfs/pseudo.c index d03b716c..26c3fff7 100644 --- a/fs/vfs/pseudo.c +++ b/fs/vfs/pseudo.c @@ -16,7 +16,7 @@ struct pseudo_mount { const struct vfs_pseudo_provider *provider; struct pseudo_key *keys,*pending; void *instance; - uint64_t next_id; + uint64_t next_id, mount_flags; }; /** @brief Recheck a provider's instance policy for a held inode identity. @@ -331,23 +331,33 @@ static int pseudo_node_access(void *value,const struct vfs_path *path, return context->provider->access ? context->provider->access(key->name, task, access) : -EOPNOTSUPP; } +/** @brief Read the shared policy retained by a generated filesystem instance. + * @param value Borrowed execution-owned pseudo mount context. + * @return Current backend policy, including sysfs readonly reconfiguration. + */ static uint64_t pseudo_mount_flags(void *value) -{return ((const struct pseudo_mount *)value)->provider->mount_flags;} +{return ((const struct pseudo_mount *)value)->mount_flags;} -/** @brief Admit proc control readonly changes without altering providers. +/** @brief Apply supported generated-filesystem readonly reconfiguration. * @param value Required borrowed pinned pseudo mount context. * @param flags Requested shared policy bits. - * @return Zero or unsupported/readonly errno. Other pseudo filesystems retain - * their prior remount restrictions; VFS publishes attachment policy under - * execution ownership, without allocation or graph locks across callbacks. */ + * @return Zero or unsupported/readonly errno, preserving policy on failure. + * sysfs stores shared readonly state. proc uses attachment policy. Execution + * ownership serializes publication without allocation or graph locks. + */ static int pseudo_remount(void *value, uint64_t flags) { - const struct pseudo_mount *mount = value; + struct pseudo_mount *mount = value; + if (mount->provider->filesystem && !__builtin_strcmp(mount->provider->filesystem, "sysfs")) { + if (flags & ~MS_RDONLY) return -EOPNOTSUPP; + mount->mount_flags = flags; + return 0; + } if (mount->provider->filesystem && !__builtin_strcmp(mount->provider->filesystem, "proc")) { if (flags & ~MS_RDONLY) return -EOPNOTSUPP; return 0; } - uint64_t current = mount->provider->mount_flags & VFS_SUPER_POLICY_MASK; + uint64_t current = mount->mount_flags & VFS_SUPER_POLICY_MASK; if (flags == current) return 0; return (current & MS_RDONLY) && !(flags & MS_RDONLY) ? -EROFS : -EOPNOTSUPP; } @@ -360,11 +370,14 @@ static int pseudo_remount(void *value, uint64_t flags) static int pseudo_remount_options(void *value,uint64_t flags,const char *options) { struct pseudo_mount *mount=value; + if (!mount->provider->reconfigure && options && options[0]) return -EOPNOTSUPP; + uint64_t previous = mount->mount_flags; int rc=pseudo_remount(value,flags); if(rc)return rc; if(mount->provider->reconfigure) - return mount->provider->reconfigure(mount->instance,flags,options); - return options && options[0] ? -EOPNOTSUPP : 0; + rc = mount->provider->reconfigure(mount->instance,flags,options); + if (rc) mount->mount_flags = previous; + return rc; } /** @brief Obtain a live magic target's metadata under its retained identity. @@ -440,7 +453,8 @@ int vfs_pseudo_mount_new_with_state(const struct vfs_pseudo_provider *provider, .getattr=pseudo_node_getattr,.statfs=pseudo_node_statfs}; struct pseudo_mount *context=kernel_malloc(sizeof(*context)+size);int rc=-ENOMEM; if(context) { - *context=(struct pseudo_mount){.provider=provider,.instance=size ? context+1 : NULL,.next_id=1}; + *context=(struct pseudo_mount){.provider=provider,.instance=size ? context+1 : NULL, + .next_id=1,.mount_flags=provider->mount_flags}; if(size)__builtin_memcpy(context->instance,initial,size); struct storage_node root; rc=pseudo_key_lookup(context,provider->root,&root); diff --git a/include/reliefnt/net_namespace.h b/include/reliefnt/net_namespace.h index e91894d1..f6ef99f4 100644 --- a/include/reliefnt/net_namespace.h +++ b/include/reliefnt/net_namespace.h @@ -14,6 +14,7 @@ struct net_ipv6_state; */ struct net_namespace { uint64_t references; + uint64_t nsfs_inode; struct user_namespace *user_ns; struct net_interface *interfaces; struct net_interface loopback; diff --git a/include/reliefnt/nsfs.h b/include/reliefnt/nsfs.h index 1a3924da..c6cee000 100644 --- a/include/reliefnt/nsfs.h +++ b/include/reliefnt/nsfs.h @@ -9,6 +9,7 @@ struct vfs_namespace; struct vfs_path; struct user_namespace; struct uts_namespace; +struct net_namespace; /** @brief Create a detached nsfs path retaining the actual mount graph. * @param ns Borrowed live graph, stable under execution ownership. @@ -33,6 +34,14 @@ int nsfs_create_user_path(struct user_namespace *ns, struct vfs_path *out); */ int nsfs_create_uts_path(struct uts_namespace *ns, struct vfs_path *out); +/** @brief Create an authentic nsfs path retaining a network namespace. + * @param ns Borrowed live network, NULL for the permanent initial network. + * @param out Required empty destination receiving one owned path. + * @return Zero or negative errno; failure leaves the output empty. + * Execution ownership required. Final path release drops the retained network. + */ +int nsfs_create_net_path(struct net_namespace *ns, struct vfs_path *out); + /** @brief Identify the mount graph from an authentic retained nsfs inode. * @param path Borrowed held path under execution ownership, nullable. * @return Borrowed graph valid while the path is held, or NULL for another @@ -56,9 +65,17 @@ bool nsfs_path_user_namespace(const struct vfs_path *path, struct user_namespace */ bool nsfs_path_uts_namespace(const struct vfs_path *path, struct uts_namespace **out); +/** @brief Identify a network through an authentic retained nsfs inode. + * @param path Borrowed held path under execution ownership, nullable. + * @param out Required borrowed output, NULL for the permanent initial network. + * @return True for a network handle; false clears the output. + * The held path keeps the returned network live. + */ +bool nsfs_path_net_namespace(const struct vfs_path *path, struct net_namespace **out); + /** @brief Authenticate an nsfs inode and query its namespace type. * @param path Borrowed held path under execution ownership, nullable. - * @return CLONE_NEWNS, CLONE_NEWUSER, CLONE_NEWUTS, or zero for another inode. + * @return CLONE_NEWNS, CLONE_NEWUSER, CLONE_NEWUTS, CLONE_NEWNET, or zero for another inode. * No allocation, references, user access or textual name resolution. */ uint32_t nsfs_path_type(const struct vfs_path *path); @@ -87,4 +104,12 @@ int nsfs_user_readlink(struct user_namespace *ns, char *buffer, size_t capacity) * Execution ownership serializes lazy inode identity assignment. */ int nsfs_uts_readlink(struct uts_namespace *ns, char *buffer, size_t capacity); + +/** @brief Render a network magic-link label without allocating a handle. + * @param ns Borrowed network, NULL for the permanent initial network. + * @param buffer Required output, without NUL. @param capacity Maximum bytes. + * @return Copied byte count, possibly truncated, or negative errno. + * Execution ownership serializes lazy inode identity assignment. + */ +int nsfs_net_readlink(struct net_namespace *ns, char *buffer, size_t capacity); #endif diff --git a/include/reliefnt/task/accessors.h b/include/reliefnt/task/accessors.h index 1bb39f2e..ebba193e 100644 --- a/include/reliefnt/task/accessors.h +++ b/include/reliefnt/task/accessors.h @@ -315,8 +315,9 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls); * Execution transaction required; takes scheduler_lock. CLONE_FS shares the * actual root/cwd owner; ordinary fork retains independent path references. * CLONE_NEWNS prepares a distinct graph before reserving a task ID. - * User and UTS scopes are retained through publication or rollback. NEWUSER - * creates an empty-map credential scope; NEWUTS copies the current names. + * User, UTS and network scopes are retained through publication or rollback. + * NEWUSER creates an empty-map credential scope; NEWUTS copies current names. + * NEWNET creates an empty network with a separate, initially down loopback. */ int64_t sched_clone_current(const struct trap_frame *frame, uint64_t flags, uint64_t stack, uint64_t parent_tid, diff --git a/include/reliefnt/user_namespace.h b/include/reliefnt/user_namespace.h index 8b95137e..3c46cd09 100644 --- a/include/reliefnt/user_namespace.h +++ b/include/reliefnt/user_namespace.h @@ -145,13 +145,13 @@ int sched_task_user_namespace_create(const struct task *task, struct user_namesp */ void sched_task_user_namespace_install(struct task *task, struct user_namespace *ns); -/** @brief Atomically prepare and install requested user, UTS and filesystem scopes. +/** @brief Atomically prepare and install user, UTS, network and filesystem scopes. * @param task Current execution-owned task, required. - * @param flags Validated CLONE_NEWUSER, CLONE_NEWNS, CLONE_NEWUTS and CLONE_FS flags. + * @param flags Validated CLONE_NEWUSER, CLONE_NEWNS, CLONE_NEWUTS, CLONE_NEWNET and CLONE_FS flags. * @return Zero, -EINVAL for a live thread group, or a preparation error. * Preparation runs outside scheduler_lock. Failures preserve credentials, * root/cwd/umask sharing, namespace references and publication state. UTS-only - * requests preserve CLONE_FS sharing. New mount and UTS scopes require current + * and network-only requests preserve CLONE_FS sharing. New mount, UTS and network scopes require current * CAP_SYS_ADMIN or use authority from the user scope created in this operation. */ int sched_task_namespaces_unshare(struct task *task, uint64_t flags); diff --git a/include/uapi/linux/socket.h b/include/uapi/linux/socket.h index f7afa2e2..f4a33c0b 100644 --- a/include/uapi/linux/socket.h +++ b/include/uapi/linux/socket.h @@ -48,6 +48,8 @@ struct sockaddr_un { #define SO_ERROR 4 #define SO_TYPE 3 #define SO_REUSEADDR 2 +#define SO_SNDBUF 7 +#define SO_RCVBUF 8 #define SO_PASSCRED 16 #define SO_PEERCRED 17 #define SO_RCVLOWAT 18 diff --git a/kernel/sched/clone.c b/kernel/sched/clone.c index 03e8d4c6..4c60252f 100644 --- a/kernel/sched/clone.c +++ b/kernel/sched/clone.c @@ -131,14 +131,14 @@ void sched_vfork_child_done(struct task *child) * @param flags Linux clone flags and exit signal. @param tls Requested TLS base. * @return Zero or the original clone validation errno; no allocation, locks, * user access or state changes occur. - * New mount and UTS scopes require current-scope CAP_SYS_ADMIN unless CLONE_NEWUSER + * New mount, UTS and network scopes require current-scope CAP_SYS_ADMIN unless CLONE_NEWUSER * creates its owning scope in the same operation. */ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) { const uint64_t supported = CSIGNAL | CLONE_VM | CLONE_VFORK | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_PARENT | CLONE_THREAD | CLONE_SYSVSEM | - CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS | + CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS | CLONE_NEWNET | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED | CLONE_UNTRACED | CLONE_CHILD_SETTID | CLONE_CLEAR_SIGHAND; if ((flags & CLONE_NEWNS) && (flags & CLONE_FS)) return -LINUX_EINVAL; @@ -146,10 +146,10 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) if ((flags & CLONE_CLEAR_SIGHAND) && (flags & CLONE_SIGHAND)) return -22; if ((flags & CLONE_THREAD) && !(flags & CLONE_SIGHAND)) return -22; if ((flags & CLONE_SIGHAND) && !(flags & CLONE_VM)) return -22; - if (flags & (CLONE_NEWPID | CLONE_NEWNET)) { + if (flags & CLONE_NEWPID) { /* copy_process() rejects a new PID namespace in the parent's thread * group; copy_namespaces() otherwise checks CAP_SYS_ADMIN before - * reaching the unavailable PID/network namespace backend. */ + * reaching the unavailable PID namespace backend. */ if ((flags & CLONE_NEWPID) && (flags & CLONE_THREAD)) return -LINUX_EINVAL; const struct task *parent = sched_current_task(); return (flags & CLONE_NEWUSER) || @@ -157,7 +157,7 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) ? -LINUX_EINVAL : -LINUX_EPERM; } if (flags & ~supported) return -RELIEFOS_ENOSYS; - if ((flags & (CLONE_NEWNS | CLONE_NEWUTS)) && !(flags & CLONE_NEWUSER)) { + if ((flags & (CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWNET)) && !(flags & CLONE_NEWUSER)) { const struct task *parent = sched_current_task(); if (!parent || !task_ns_capable(parent, parent->user_ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; } @@ -188,8 +188,9 @@ int sched_clone_validate_flags(uint64_t flags,uint64_t tls) * A new mount graph retains the candidate user scope or the parent's current * scope and locks inherited attachments when its owner changes. * CLONE_NEWUTS copies names into a scope owned by the candidate user namespace. - * Other children share the source UTS scope. Network identity is shared by every - * child. Every rollback releases its retained namespace references. + * Other children share the source UTS scope. CLONE_NEWNET creates an empty + * network owned by the candidate user scope, with its own down loopback. + * Other children retain their source network. Rollback releases all captures. */ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flags, uint64_t stack, uint64_t parent_tid, @@ -216,6 +217,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag struct task_fs_paths snapshot = {0}; struct user_namespace *user_ns = NULL; struct uts_namespace *uts_ns = NULL; + struct net_namespace *net_ns = NULL; if (!parent || !parent_frame || parent->kind != TASK_KIND_USER || parent->state == TASK_EXITED || !(*sched_task_as(parent)).cr3) { kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); @@ -229,16 +231,19 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag return -LINUX_EAGAIN; } parent->nproc_exceeded = false; - if (flags & (CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS)) { + if (flags & (CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS | CLONE_NEWNET)) { /* Execution ownership keeps admission and the source stable. VFS can * call into providers on failure, so take no scheduler lock or PID. */ kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); int rc = flags & CLONE_NEWUSER ? sched_task_user_namespace_create(parent, &user_ns) : 0; if (!rc && (flags & CLONE_NEWUTS)) rc = uts_namespace_create(parent->uts_ns, user_ns ? user_ns : parent->user_ns, &uts_ns); + if (!rc && (flags & CLONE_NEWNET)) + rc = net_namespace_create(user_ns ? user_ns : parent->user_ns, &net_ns); if (!rc && (flags & CLONE_NEWNS)) rc = sched_task_fs_snapshot(parent, user_ns ? user_ns : parent->user_ns, &snapshot); if (rc) { + net_namespace_put(net_ns); uts_namespace_put(uts_ns); user_namespace_put(user_ns); sched_task_identity_put(identity); @@ -260,7 +265,8 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag *child = *parent; child->user_ns = user_namespace_get(parent->user_ns); child->uts_ns = flags & CLONE_NEWUTS ? uts_ns : uts_namespace_get(parent->uts_ns); - child->net_ns = net_namespace_get(parent->net_ns); + child->net_ns = flags & CLONE_NEWNET ? net_ns : net_namespace_get(parent->net_ns); + net_ns = NULL; uts_ns = NULL; if (user_ns) { sched_task_user_namespace_install(child, user_ns); @@ -647,6 +653,7 @@ int64_t sched_clone_current(const struct trap_frame *parent_frame, uint64_t flag fail_prepare: kernel_spin_unlock_irqrestore(&scheduler_lock, lock_flags); sched_task_fs_paths_put(&snapshot); + net_namespace_put(net_ns); uts_namespace_put(uts_ns); user_namespace_put(user_ns); sched_task_identity_put(identity); diff --git a/kernel/sched/user_namespace_task.c b/kernel/sched/user_namespace_task.c index fda230d0..e6425065 100644 --- a/kernel/sched/user_namespace_task.c +++ b/kernel/sched/user_namespace_task.c @@ -53,17 +53,22 @@ int sched_task_namespaces_unshare(struct task *task, uint64_t flags) bool new_user = (flags & CLONE_NEWUSER) != 0; bool new_mount = (flags & CLONE_NEWNS) != 0; bool new_uts = (flags & CLONE_NEWUTS) != 0; + bool new_net = (flags & CLONE_NEWNET) != 0; if (new_user && thread_group_pending(sched_task_tgid(task), task)) return -LINUX_EINVAL; - if (!new_user && (new_mount || new_uts) && + if (!new_user && (new_mount || new_uts || new_net) && !task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN)) return -LINUX_EPERM; struct user_namespace *ns = NULL; struct uts_namespace *uts = NULL; + struct net_namespace *net = NULL; int rc = new_user ? sched_task_user_namespace_create(task, &ns) : 0; if (!rc && new_uts) rc = uts_namespace_create(task->uts_ns, new_user ? ns : task->user_ns, &uts); + if (!rc && new_net) + rc = net_namespace_create(new_user ? ns : task->user_ns, &net); if (!rc && (flags & (CLONE_NEWUSER | CLONE_NEWNS | CLONE_FS))) rc = sched_task_fs_unshare(task, new_mount, new_user ? ns : task->user_ns); if (rc) { + net_namespace_put(net); uts_namespace_put(uts); user_namespace_put(ns); return rc; @@ -74,6 +79,11 @@ int sched_task_namespaces_unshare(struct task *task, uint64_t flags) task->uts_ns = uts; uts_namespace_put(old); } + if (new_net) { + struct net_namespace *old = task->net_ns; + task->net_ns = net; + net_namespace_put(old); + } return 0; } diff --git a/kernel/syscall/dispatch.c b/kernel/syscall/dispatch.c index 985bb2fb..bec9d452 100644 --- a/kernel/syscall/dispatch.c +++ b/kernel/syscall/dispatch.c @@ -126,7 +126,7 @@ static int64_t syscall_ioctl_nonblock(struct task *task, int fd, uint64_t argume /** @brief Handle ioctl on an already authenticated namespace inode. * @param task Live caller under execution ownership. - * @param type CLONE_NEWNS or CLONE_NEWUSER from the authenticated inode. + * @param type CLONE_NEWNS, CLONE_NEWUSER, CLONE_NEWUTS or CLONE_NEWNET from the inode. * @param cmd Normalized 32-bit Linux request, after generic FD ioctls. * @param argument User int output for FIONREAD, ignored for other requests. * @return Namespace type, zero for a copied byte count, or negative errno diff --git a/kernel/syscall/fs/locks.c b/kernel/syscall/fs/locks.c index 4e02d0bf..052eb879 100644 --- a/kernel/syscall/fs/locks.c +++ b/kernel/syscall/fs/locks.c @@ -34,7 +34,7 @@ static struct record_lock_waiter { static uint32_t pending_count; static uint32_t pending_capacity; -/** @brief Compare stable filesystem inode identities. +/** @brief Compare stable filesystem or anonymous socket inode identities. * @param a First borrowed inode snapshot. @param b Second borrowed snapshot. * @return True for the same volume, inode number and inode type. */ static bool same_inode(const struct storage_node *a, const struct storage_node *b) @@ -42,6 +42,20 @@ static bool same_inode(const struct storage_node *a, const struct storage_node * return a->volume_id == b->volume_id && a->first_cluster == b->first_cluster && a->type == b->type; } +/** @brief Capture a lock identity, preserving all bits of a socket inode number. + * @param file Borrowed canonical OFD, stable under execution ownership. + * @return Filesystem identity or a socket identity in the separate socket type. + * No allocation or storage access occurs. Request and close use this same key. + */ +static struct storage_node record_lock_inode(const struct task_file *file) +{ + if (file->flags & TASK_FILE_FLAG_SOCKET) + return (struct storage_node){.type = RELIEFOS_FS_TYPE_SOCKET, + .volume_id = (uint32_t)(file->socket_ino >> 32), + .first_cluster = (uint32_t)file->socket_ino}; + return file->node; +} + /** @brief Allocate a serial shared by tasks using one descriptor table. * @param task Current execution-owned task with a live descriptor table. * @return Nonzero lock owner unique among descriptor tables and OFDs. */ @@ -52,7 +66,7 @@ static uint64_t syscall_record_lock_owner(struct task *task) return table->lock_owner; } -/** @brief Release this descriptor table's POSIX locks on a closing inode. +/** @brief Release this descriptor table's POSIX locks on a closing file or socket. * @param task Execution-owned table owner, nullable. * @param descriptor Borrowed closing descriptor or OFD, nullable. * OFD locks survive this operation. Wakes waiters after dropping POSIX locks. */ @@ -61,8 +75,9 @@ void syscall_record_locks_close(struct task *task, struct task_file *descriptor) struct task_file *file = task_file_description(descriptor); uint64_t owner = task ? sched_task_fds(task)->lock_owner : 0; if (!file || !owner) return; + struct storage_node inode = record_lock_inode(file); for (unsigned i = 0; i < RECORD_LOCK_MAX; ++i) - if (records[i].owner == owner && same_inode(&records[i].node, &file->node)) records[i].owner = 0; + if (records[i].owner == owner && same_inode(&records[i].node, &inode)) records[i].owner = 0; kernel_wait_queue_wake_all(&record_waiters); } @@ -230,13 +245,14 @@ static int replace_range(const struct record_lock *request) /** * @brief Query or update POSIX or OFD byte-range locks for the current task. - * @param fd Descriptor naming the regular file. + * @param fd Descriptor naming a regular file or socket. * @param command F_GETLK/F_SETLK/F_SETLKW or their F_OFD counterparts. * @param pointer User pointer to a native flock request/result. * @return Zero, a blocking retry token, or a negative Linux errno. * Uses the syscall's retained OFD across descriptor close/reuse. Caller holds * execution ownership. OFD requests require l_pid=0 and report conflicts owned * by an OFD with l_pid=-1; only POSIX requests participate in deadlock detection. + * Socket locks use the full anonymous inode identity and a zero SEEK_END size. */ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer) { @@ -245,6 +261,7 @@ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer) if (task && task->waiting_queue == &record_waiters) kernel_wait_queue_remove(&record_waiters, task); struct task_file *file = task_file_for_io(task, fd); if (!file || (file->flags & TASK_FILE_FLAG_PATH)) return -LINUX_EBADF; + bool socket = (file->flags & TASK_FILE_FLAG_SOCKET) != 0; if (!user_range_ok(pointer, sizeof(struct native_flock))) return -LINUX_EFAULT; struct native_flock user; __builtin_memcpy(&user, (const void *)(uintptr_t)pointer, sizeof(user)); @@ -256,6 +273,7 @@ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer) int64_t start; if (user.whence == 0) start = 0; else if (user.whence == 1) start = file->offset; + else if (user.whence == 2 && socket) start = 0; else if (user.whence == 2) { int ret = storage_inode_refresh(&file->node); if (ret < 0) return ret; @@ -270,7 +288,7 @@ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer) end = start - 1; if (__builtin_add_overflow(start, user.length, &start) || start < 0) return -LINUX_EINVAL; } - if (file->node.type != RELIEFOS_FS_TYPE_FILE) return -LINUX_EBADF; + if (!socket && file->node.type != RELIEFOS_FS_TYPE_FILE) return -LINUX_EBADF; if (!query && ((user.type == LINUX_F_RDLCK && !file_can_read(file)) || (user.type == LINUX_F_WRLCK && !file_can_write(file)))) return -LINUX_EBADF; if (ofd && !file->record_lock_owner) @@ -278,7 +296,7 @@ int64_t syscall_record_lock(int fd, uint32_t command, uint64_t pointer) struct record_lock request = { .owner = ofd ? file->record_lock_owner : syscall_record_lock_owner(task), .pid = ofd ? -1 : (int32_t)sched_task_tgid(task), - .node = file->node, .type = user.type, .start = start, .end = end}; + .node = record_lock_inode(file), .type = user.type, .start = start, .end = end}; for (unsigned i = 0; i < RECORD_LOCK_MAX && user.type != LINUX_F_UNLCK; ++i) { const struct record_lock *held = &records[i]; if (!conflicts(held, &request)) continue; diff --git a/kernel/syscall/fs/mount.c b/kernel/syscall/fs/mount.c index 0f6f4869..9143b064 100644 --- a/kernel/syscall/fs/mount.c +++ b/kernel/syscall/fs/mount.c @@ -5,6 +5,7 @@ #include #include #include +#include #include /** @brief Resolve both endpoints of a mount move, including propagated moves. @@ -230,8 +231,9 @@ static int mount_backend(struct vfs_namespace *ns,struct task *task,const char * * @return Zero or negative Linux errno/internal EAGAIN. Text and lookup state * remain scope-owned across waits; temporary unscoped allocations are always * freed. The resulting graph owns backend lifetime, without target prefixes. - * tmpfs/devpts creation captures the caller's user scope. Other backends use - * their initial resource owner. Remount authorizes the actual backend owner. + * tmpfs/devpts creation captures the caller's user scope. sysfs captures the + * current network's user owner. Other backends use their initial resource + * owner. Remount authorizes the actual backend owner. * Context parameter writes are descriptor operations; commit checks its owner. */ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_t number, @@ -268,6 +270,8 @@ int64_t syscall_mount_control(struct vfs_namespace *ns,struct task *task,uint64_ if(!rc) { if(!__builtin_strcmp(type.text,"tmpfs") || !__builtin_strcmp(type.text,"devpts")) owner=task->user_ns; + else if(!__builtin_strcmp(type.text,"sysfs")) + owner=task->net_ns ? task->net_ns->user_ns : NULL; if(!task_ns_capable(task,owner,CAP_SYS_ADMIN))rc=-RELIEFOS_EPERM; } if(!rc)rc=task_lookup_user_text(task,a0,VFS_PATH_MAX,true,&source); diff --git a/kernel/syscall/fs/mount_api.c b/kernel/syscall/fs/mount_api.c index a672afac..20e09279 100644 --- a/kernel/syscall/fs/mount_api.c +++ b/kernel/syscall/fs/mount_api.c @@ -1,11 +1,14 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" +#include +#include #include #include enum syscall_fs_type { SYSCALL_FS_TMPFS, SYSCALL_FS_PROC, + SYSCALL_FS_SYSFS, }; /* A context belongs to one open-file description, including its duplicates. */ @@ -34,8 +37,9 @@ void syscall_fs_context_release(void *object) /** @brief Create a supported filesystem configuration owned by a new descriptor. * @param task Calling descriptor-table owner. @param type_user User filesystem name. * @param flags Native fsopen flags. @return Descriptor or negative errno. - * Captures tmpfs user ownership at fsopen. proc keeps the initial PID-view - * owner. Failed allocation leaves no descriptor or namespace reference. + * Captures tmpfs user ownership and sysfs network-owner authority at fsopen. + * proc keeps the initial PID-view owner. sysfs admission also checks its + * network owner. Failure leaves no descriptor or namespace reference. */ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t flags) { @@ -45,7 +49,14 @@ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t fl if (rc) return rc; enum syscall_fs_type filesystem = SYSCALL_FS_TMPFS; if (!__builtin_strcmp(type.text, "proc")) filesystem = SYSCALL_FS_PROC; + else if (!__builtin_strcmp(type.text, "sysfs")) filesystem = SYSCALL_FS_SYSFS; else if (__builtin_strcmp(type.text, "tmpfs")) rc = -RELIEFOS_ENODEV; + struct user_namespace *owner = NULL; + if (filesystem == SYSCALL_FS_TMPFS) owner = task->user_ns; + else if (filesystem == SYSCALL_FS_SYSFS) { + owner = task->net_ns ? task->net_ns->user_ns : NULL; + if (!rc && !task_ns_capable(task, owner, CAP_SYS_ADMIN)) rc = -RELIEFOS_EPERM; + } struct syscall_fs_context *context = NULL; if (!rc) { context = kernel_malloc(sizeof(*context)); @@ -53,8 +64,7 @@ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t fl } if (!rc) { *context = (struct syscall_fs_context){.uid = task->fsuid, .gid = task->fsgid, - .type = filesystem,.user_ns = user_namespace_get( - filesystem == SYSCALL_FS_TMPFS ? task->user_ns : NULL)}; + .type = filesystem, .user_ns = user_namespace_get(owner)}; struct task_file *file = NULL; int fd = task_allocate_fd(task, 0, &file); if (fd < 0) rc = fd; @@ -127,6 +137,10 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con context->source = copy; goto done; } + if (context->type == SYSCALL_FS_SYSFS) { + rc = -RELIEFOS_EINVAL; + goto done; + } size_t key_length = __builtin_strlen(key.text), value_length = __builtin_strlen(value.text); char option[128]; @@ -178,17 +192,27 @@ static int mount_api_commit(struct task *task,struct syscall_fs_context *context if (context->created) return -RELIEFOS_EBUSY; if (!task_ns_capable(task,context->user_ns,CAP_SYS_ADMIN)) return -RELIEFOS_EPERM; struct vfs_mount *mount = NULL; + struct vfs_path root = {0}; uint64_t flags = context->readonly_change > 0 ? MS_RDONLY : 0; if (context->type == SYSCALL_FS_PROC) rc = proc_create_vfs_mount_options(context->options,&mount); + else if (context->type == SYSCALL_FS_SYSFS) + rc = sysfs_create_vfs_mount(&mount); else rc = storage_new_tmpfs_mount("none", flags, context->options, context->uid, context->gid, &mount); if (!rc) rc = vfs_mount_set_source(mount, context->source ? context->source : "none"); if (!rc) rc = vfs_mount_set_user_namespace(mount, context->user_ns); - if (!rc) rc = vfs_mount_detached_root(mount, &context->root); + if (!rc) rc = vfs_mount_detached_root(mount, &root); + if (!rc && context->type == SYSCALL_FS_SYSFS && flags) + rc = vfs_path_remount_options(&root, flags, ""); vfs_mount_put(mount); - if (!rc) context->created = true; + if (!rc) { + context->root = root; + root = (struct vfs_path){0}; + context->created = true; + } + vfs_path_put(&root); } else { if (!context->mounted) return -RELIEFOS_EBUSY; if (!task_ns_capable(task,vfs_path_user_namespace(&context->root),CAP_SYS_ADMIN)) diff --git a/kernel/syscall/process/clone.c b/kernel/syscall/process/clone.c index 5e62e50f..177a541c 100644 --- a/kernel/syscall/process/clone.c +++ b/kernel/syscall/process/clone.c @@ -139,13 +139,13 @@ int64_t syscall_clone3(const struct trap_frame *frame, uint64_t arguments, uint6 * @return Zero (including a no-op for flags=0), or negative Linux errno. * Validate the entire request before preparing or publishing a snapshot. * User scope creation requires a single-threaded caller, mapped effective IDs - * and an unrestricted root. A new mount graph or UTS scope requires current-scope + * and an unrestricted root. A new mount, UTS or network scope requires current-scope * CAP_SYS_ADMIN, or is owned by the user scope created in the same operation. - * UTS-only unshare retains the existing filesystem sharing arrangement. + * UTS-only and network-only unshare retain filesystem sharing. */ int64_t syscall_unshare(struct task *task, uint64_t flags) { - uint64_t supported = CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS | CLONE_FS; + uint64_t supported = CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS | CLONE_NEWNET | CLONE_FS; if (flags & CLONE_NEWUSER) supported |= CLONE_THREAD; if (!task || (flags & ~supported)) return -LINUX_EINVAL; if (!flags) return 0; diff --git a/kernel/syscall/process/setns.c b/kernel/syscall/process/setns.c index 271aebf3..0e27acd7 100644 --- a/kernel/syscall/process/setns.c +++ b/kernel/syscall/process/setns.c @@ -2,19 +2,21 @@ #include "../internal.h" #include #include +#include #include #include #include -/** @brief Join a mount, user or UTS scope through an authentic namespace FD. +/** @brief Join a mount, user, UTS or network scope through an authentic namespace FD. * @param task Live caller; execution ownership keeps its FD table stable. * @param fd Descriptor number (not O_PATH or a pidfd). - * @param type Zero or CLONE_NEWNS/CLONE_NEWUSER/CLONE_NEWUTS matching the inode. + * @param type Zero or the matching CLONE_NEWNS/NEWUSER/NEWUTS/NEWNET flag. * @return Zero or a negative descriptor, capability or namespace error. * Mount graph entry requires current-scope CAP_SYS_ADMIN and CAP_SYS_CHROOT, * plus CAP_SYS_ADMIN in the target graph's owning user scope. * User scope entry requires target CAP_SYS_ADMIN and exclusive thread/FS state. - * UTS entry requires local and owner CAP_SYS_ADMIN; FS sharing is retained. + * UTS and network entry require local and owner CAP_SYS_ADMIN and retain FS sharing. + * Existing sockets retain their creating network independently of task movement. */ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) { @@ -36,6 +38,15 @@ int64_t syscall_setns(struct task *task, int32_t fd, uint32_t type) uts_namespace_put(old); return 0; } + struct net_namespace *net = NULL; + if (nsfs_path_net_namespace(&file->path_ref, &net)) { + if (!task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN) || + !task_ns_capable(task, net ? net->user_ns : NULL, CAP_SYS_ADMIN)) return -LINUX_EPERM; + struct net_namespace *old = task->net_ns; + task->net_ns = net_namespace_get(net); + net_namespace_put(old); + return 0; + } struct vfs_namespace *ns = nsfs_path_namespace(&file->path_ref); if (!ns) return -LINUX_EINVAL; if (!task_ns_capable(task, task->user_ns, CAP_SYS_ADMIN) || diff --git a/net/socket/netlink.c b/net/socket/netlink.c index 76d8b1ec..0e9aaad2 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -30,7 +30,10 @@ /* Dump data and its terminal NLMSG_DONE use separate, bounded datagrams. * A linked registry has no artificial process/socket count limit. */ #define NL_MESSAGE_MAX 8192u -#define NL_QUEUE_BUDGET (8u * NL_MESSAGE_MAX) +#define NL_BUFFER_DEFAULT (8u * NL_MESSAGE_MAX) +#define NL_BUFFER_REQUEST_MAX 65536u +#define NL_SNDBUF_MIN 4608u +#define NL_RCVBUF_MIN 2304u #define NL_UEVENT_KERNEL_GROUP 1u #define NL_UEVENT_UDEV_GROUP 2u #define NL_UEVENT_GROUPS (NL_UEVENT_KERNEL_GROUP | NL_UEVENT_UDEV_GROUP) @@ -46,6 +49,7 @@ struct netlink_socket { struct netlink_message *head, *tail; struct socket_filter *filter; uint32_t port, queued_bytes, groups; + uint32_t sndbuf, rcvbuf; int type, protocol; bool bound, connected, overrun, passcred; bool pktinfo, memberships_initialized; @@ -83,6 +87,16 @@ static struct nl_snapshot *nl_snapshots; static struct netlink_socket *nl_socket(const struct task_file *file) { return file && file->kind == TASK_FILE_KIND_NETLINK ? (void *)(uintptr_t)file->aux : NULL; } +/** @brief Check receive capacity without underflow after a buffer shrink. + * @param s Borrowed socket under execution ownership. + * @param bytes Required queue charge, including multipart reservations. + * @return True when the entire reservation fits. Existing messages stay queued. + */ +static bool nl_queue_room(const struct netlink_socket *s, uint32_t bytes) +{ + return bytes <= s->rcvbuf && s->queued_bytes <= s->rcvbuf - bytes; +} + /** @brief Test a nonzero port against bound endpoints in the creating scope. * @param port Proposed ID. @param except Socket excluded from the comparison. * @return True when another socket in the same namespace and protocol owns it. */ @@ -489,7 +503,7 @@ static int nl_queue_datagram(struct netlink_socket *s, uint32_t port, uint32_t g uint32_t admitted = socket_filter_run(s->filter, data, length); if (!admitted) return 0; - if (s->queued_bytes > NL_QUEUE_BUDGET - NL_MESSAGE_MAX) + if (!nl_queue_room(s, NL_MESSAGE_MAX)) return -LINUX_EAGAIN; struct netlink_message *message = kernel_malloc(sizeof(*message) + admitted); if (!message) @@ -1141,19 +1155,24 @@ static int nl_uevent_send(struct netlink_socket *sender, const void *data, uint3 /** @brief Process a route request or deliver a privileged userspace uevent. * @param file Pinned OFD. @param data Validated bytes. @param length Input length. * @param flags Linux send flags. @param address Optional user destination. - * @param address_length Address length. @return Bytes accepted or errno. */ + * @param address_length Address length. @return Bytes accepted or errno. + * Per-socket send limits retain the bounded datagram maximum. Reply queue + * capacity is reserved before any request mutation or reply publication. + * Route processing consumes the valid message prefix, ignoring malformed or + * incomplete trailing bytes. The accepted byte count includes that tail. + */ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,uint32_t flags, uint64_t address,uint32_t address_length) { struct netlink_socket *s=nl_socket(file); if (!s) return -LINUX_EBADF; if (flags & ~(MSG_DONTWAIT|MSG_NOSIGNAL)) return -LINUX_EOPNOTSUPP; + if (length > NL_MESSAGE_MAX || length > s->sndbuf - 32u) return -LINUX_EMSGSIZE; if (s->protocol == NETLINK_KOBJECT_UEVENT) { if (!length) return -LINUX_ENODATA; - if (length > NL_MESSAGE_MAX) return -LINUX_EMSGSIZE; return nl_uevent_send(s, data, length, address, address_length); } - if (!length || length > NL_MESSAGE_MAX) return -LINUX_EMSGSIZE; + if (!length) return -LINUX_EMSGSIZE; if (address) { if (address_length < sizeof(struct sockaddr_nl)) return -LINUX_EINVAL; struct sockaddr_nl dst; @@ -1164,12 +1183,11 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui const uint8_t *input=data; uint32_t pos=0, maximum_reply=0, requests=0; bool has_dump=false, multipart=false; - while (pos= sizeof(struct nlmsghdr)) { struct nlmsghdr h; __builtin_memcpy(&h,input+pos,sizeof(h)); - if (h.nlmsg_len < sizeof(h) || h.nlmsg_len > length-pos) return -LINUX_EINVAL; + if (h.nlmsg_len < sizeof(h) || h.nlmsg_len > length-pos) break; uint32_t advance=NLMSG_ALIGN(h.nlmsg_len); - if (advance > length-pos) return -LINUX_EINVAL; + if (advance > length-pos) advance=length-pos; uint32_t error_size=NLMSG_ALIGN(sizeof(struct nlmsghdr)+sizeof(struct nlmsgerr)+ h.nlmsg_len-sizeof(struct nlmsghdr)); if (error_size > NL_MESSAGE_MAX-maximum_reply) return -LINUX_ENOBUFS; @@ -1180,9 +1198,14 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui } pos+=advance; } + uint32_t valid_length=pos; + if (!requests) { + int rc=nl_autobind(s,sched_current_task()); + return rc ? rc : (int)length; + } if (has_dump && requests>1) return -LINUX_EOPNOTSUPP; uint32_t reserved=NL_MESSAGE_MAX*(multipart ? 2u : 1u); - if (s->queued_bytes > NL_QUEUE_BUDGET-reserved) return -LINUX_ENOBUFS; + if (!nl_queue_room(s, reserved)) return -LINUX_ENOBUFS; uint8_t *bytes=kernel_malloc(length); if (!bytes) return -LINUX_ENOMEM; __builtin_memcpy(bytes,input,length); @@ -1200,7 +1223,7 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui * conservatively charged one full slot, as other queued datagrams are. */ s->queued_bytes+=reserved; struct nl_builder builder={.message=message,.completion=completion,.net_ns=s->net_ns,.port=s->port}; - for (pos=0;posoverrun ? POLLERR : 0) | (s->head ? events&POLLIN : 0) | - (s->queued_bytes<=NL_QUEUE_BUDGET-NL_MESSAGE_MAX ? events&POLLOUT : 0); + (nl_queue_room(s, NL_MESSAGE_MAX) ? events&POLLOUT : 0); } /** @brief Return the next queued netlink datagram size. @@ -1427,6 +1450,8 @@ static int nl_protocol_option(struct task *task, struct netlink_socket *s, bool * @param a2 Third argument. @param a3 Fourth argument. @param a4 Fifth argument. * @param a5 Sixth argument. @return Syscall result or negative errno. * @note SO_REUSEADDR stores per-socket state without allowing duplicate ports. + * SO_SNDBUF/SO_RCVBUF clamp unsigned requests before doubling, enforce minima, + * and preserve queued messages when shrinking. Getters return effective sizes. * Published sockets retain their creating namespace after FD allocation succeeds. * Filter replacement is published only after the candidate is fully validated. */ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, @@ -1446,7 +1471,8 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, struct task_file *file; int fd=task_allocate_fd(task,0,&file); if (fd<0) { kernel_free(s); return fd; } *s=(struct netlink_socket){.next=netlink_sockets,.net_ns=net_namespace_get(task->net_ns), - .type=type,.protocol=(int)a2}; netlink_sockets=s; + .type=type,.protocol=(int)a2,.sndbuf=NL_BUFFER_DEFAULT, + .rcvbuf=NL_BUFFER_DEFAULT}; netlink_sockets=s; file->flags=TASK_FILE_FLAG_SOCKET|TASK_FILE_FLAG_SOCKET_INET|RELIEFOS_O_RDWR| ((a1&SOCK_NONBLOCK) ? RELIEFOS_O_NONBLOCK : 0); file->fd_flags=(a1&SOCK_CLOEXEC) ? RELIEFOS_FD_CLOEXEC : 0; @@ -1508,15 +1534,25 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, s->filter = NULL; return 0; } - if (a2 != SO_REUSEADDR && (a2 != SO_PASSCRED || s->protocol != NETLINK_KOBJECT_UEVENT)) + if (a2 != SO_REUSEADDR && a2 != SO_SNDBUF && a2 != SO_RCVBUF && + (a2 != SO_PASSCRED || s->protocol != NETLINK_KOBJECT_UEVENT)) return -LINUX_ENOPROTOOPT; if ((int32_t)a4 < (int32_t)sizeof(int32_t)) return -LINUX_EINVAL; - int32_t enable; - int ret = socket_user_import(task, a3, &enable, sizeof(enable)); + int32_t value; + int ret = socket_user_import(task, a3, &value, sizeof(value)); if (ret) return ret; - if (a2 == SO_REUSEADDR) s->reuse_address = enable != 0; - else s->passcred = enable != 0; + if (a2 == SO_SNDBUF || a2 == SO_RCVBUF) { + uint32_t size = (uint32_t)value; + if (size > NL_BUFFER_REQUEST_MAX) size = NL_BUFFER_REQUEST_MAX; + size *= 2u; + uint32_t minimum = a2 == SO_SNDBUF ? NL_SNDBUF_MIN : NL_RCVBUF_MIN; + if (size < minimum) size = minimum; + if (a2 == SO_SNDBUF) s->sndbuf = size; + else s->rcvbuf = size; + kernel_poll_readiness_notify(); + } else if (a2 == SO_REUSEADDR) s->reuse_address = value != 0; + else s->passcred = value != 0; return 0; } int32_t value; @@ -1524,6 +1560,8 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, else if (a2==SO_DOMAIN) value=AF_NETLINK; else if (a2==SO_PROTOCOL) value=s->protocol; else if (a2==SO_REUSEADDR) value=s->reuse_address; + else if (a2==SO_SNDBUF) value=(int32_t)s->sndbuf; + else if (a2==SO_RCVBUF) value=(int32_t)s->rcvbuf; else if (a2==SO_PASSCRED && s->protocol == NETLINK_KOBJECT_UEVENT) value=s->passcred; else if (a2==SO_ERROR) value=s->overrun ? LINUX_ENOBUFS : 0; else return -LINUX_ENOPROTOOPT; diff --git a/tools/test_linux_inventory.py b/tools/test_linux_inventory.py index 129cf188..48c73d95 100644 --- a/tools/test_linux_inventory.py +++ b/tools/test_linux_inventory.py @@ -12,7 +12,7 @@ def host(): '-Iinclude','-Iinclude','-Iinclude/uapi', '-Iinclude','tools/tests/linux_inventory_test.c','fs/vfs/mount_tree.c', 'fs/vfs/lookup_cache.c', 'fs/vfs/path.c','fs/vfs/mount_table.c','fs/vfs/file.c','fs/vfs/open.c','fs/vfs/pseudo.c', 'fs/vfs/attributes.c','fs/proc/mount.c','fs/nsfs/namespace.c','fs/proc/views.c','kernel/syscall/fd/proc.c','fs/vfs/exec_file.c', - 'fs/sysfs/mount.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','kernel/sched/user_namespace.c','kernel/init/uts.c','fs/security/access.c','-o',executable]) + 'fs/sysfs/mount.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','kernel/sched/user_namespace.c','kernel/init/uts.c','net/namespace/namespace.c','net/ipv6/state.c','fs/security/access.c','-o',executable]) run([executable]) if __name__ == "__main__": diff --git a/tools/test_lock_profile.py b/tools/test_lock_profile.py index 2e1d42ca..3dff5fe6 100644 --- a/tools/test_lock_profile.py +++ b/tools/test_lock_profile.py @@ -23,7 +23,7 @@ binary = str(Path(directory) / "proc") sources = ["tools/tests/lock_profile_proc_test.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", - "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "fs/security/access.c"] + "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "net/namespace/namespace.c", "net/ipv6/state.c", "fs/security/access.c"] if (ROOT / "kernel/sync/profile.c").exists(): sources.append("kernel/sync/profile.c") subprocess.run(["cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", @@ -51,6 +51,6 @@ "-Iinclude", "-Iinclude/uapi", "tools/tests/lock_profile_sync_io_test.c", "tools/tests/task8_host_stubs/writable_alias_model.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "tools/tests/task8_host_stubs/user_ram_unreached.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", - "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "fs/security/access.c", "kernel/sync/profile.c", + "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "net/namespace/namespace.c", "net/ipv6/state.c", "fs/security/access.c", "kernel/sync/profile.c", "-o", binary], cwd=ROOT, check=True) subprocess.run([binary], cwd=ROOT, check=True, timeout=10) diff --git a/tools/test_memory_reporting.py b/tools/test_memory_reporting.py index c2f7761d..e3b51337 100644 --- a/tools/test_memory_reporting.py +++ b/tools/test_memory_reporting.py @@ -74,7 +74,7 @@ def run_cases(output, cases): "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", - "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "kernel/sched/oom.c", "fs/security/access.c", + "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/sched/oom.c", "fs/security/access.c", "fs/proc/memory.c", "mm/reclaim/stats.c", "mm/reclaim/oom.c"] proc_command = [clang, "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index cbffaea2..2e306999 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -23,7 +23,7 @@ def test_real_tmpfs_without_text_routing(self): "-Wl,--gc-sections", "-Wl,--wrap=storage_ext4_read_inode", "-Wl,--wrap=storage_read_device", "-Wl,--wrap=storage_inode_stat", "-Wl,--wrap=storage_backend_commit_rename_metadata", "-Wl,--wrap=storage_cluster_write", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-Iinclude", "-Iinclude/uapi", "tools/tests/mount_backend_test.c", "kernel/dma/buffer.c", "drivers/storage/ahci/dma.c", "drivers/storage/ahci/interrupt.c", "drivers/storage/nvme/queue.c", "block/partition/mbr.c", "fs/cgroup/filesystem.c", "fs/cgroup/hierarchy.c", "fs/vfs/notify.c", "fs/nsfs/namespace.c", "kernel/sched/user_namespace.c", - "kernel/init/uts.c", + "kernel/init/uts.c", "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/syscall/dispatch.c", "kernel/syscall/io/legacy_io.c", "kernel/syscall/io/io.c", "kernel/syscall/io/file_io.c", "kernel/syscall/io/seek.c", "kernel/syscall/io/transfer.c", "kernel/syscall/io/directory.c", "kernel/syscall/fs/metadata.c", "tools/tests/mount_backend_io_boundaries.c", diff --git a/tools/test_procfs.py b/tools/test_procfs.py index 6ebc9698..e69eed3a 100644 --- a/tools/test_procfs.py +++ b/tools/test_procfs.py @@ -21,7 +21,8 @@ def test_real_procfs_directory_lookup_and_enumeration(self): "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", - "fs/security/access.c", "-o", executable], + "fs/security/access.c", "net/namespace/namespace.c", + "net/ipv6/state.c", "-o", executable], cwd=ROOT, check=True) subprocess.run([executable], check=True, timeout=10) diff --git a/tools/test_rootfs.py b/tools/test_rootfs.py index ded82301..8a8345f9 100644 --- a/tools/test_rootfs.py +++ b/tools/test_rootfs.py @@ -19,7 +19,7 @@ def test_kernel_modules(self): extra = (["fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/mount_table.c", "fs/vfs/path.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/pseudo.c", "fs/vfs/attributes.c", "fs/proc/mount.c", "fs/nsfs/namespace.c", "fs/proc/views.c", "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", - "fs/security/access.c", "kernel/init/uts.c"] if name in ("procfs_directories", "rootfs_paths") else []) + "fs/security/access.c", "kernel/init/uts.c", "net/namespace/namespace.c", "net/ipv6/state.c"] if name in ("procfs_directories", "rootfs_paths") else []) if name == "rootfs_uts": extra = ["kernel/sched/user_namespace.c"] if name in ("linux_permissions", "chroot_paths"): diff --git a/tools/tests/descriptor_table_test.c b/tools/tests/descriptor_table_test.c index 31c1d0a6..f03733a0 100644 --- a/tools/tests/descriptor_table_test.c +++ b/tools/tests/descriptor_table_test.c @@ -433,6 +433,8 @@ void task_shm_release(struct task_file *file) { (void)file; } void task_packet_release(struct task_file *file) { (void)file; abort(); } void task_udp_release(struct task_file *file) { (void)file; abort(); } void net_socket_release_fd(int32_t handle) { (void)handle; abort(); } +struct net_namespace *net_socket_namespace(int32_t handle) +{ (void)handle; abort(); } int64_t syscall_socket_mmsg(bool receiving, int fd, uint64_t vector, uint32_t length, uint32_t flags, uint64_t timeout) { (void)receiving; (void)fd; (void)vector; (void)length; (void)flags; (void)timeout; abort(); } @@ -2045,6 +2047,100 @@ struct descriptor_record_lock { int32_t pid, trailing_padding; }; +/** @brief Socket identity must admit POSIX/OFD locks and survive descriptor reuse. */ +static void test_socket_record_locks(void) +{ + extern struct task *current_task[]; + const unsigned commands[] = {LINUX_F_SETLKW, LINUX_F_OFD_SETLKW}; + for (unsigned mode = 0; mode < 2; ++mode) { + struct task *parent = calloc(1, sizeof(*parent)); + struct task *child = calloc(1, sizeof(*child)); + assert(parent && child); + parent->pid = parent->tgid = 1390; + child->pid = child->tgid = 1391; + parent->limits.nofile.rlim_cur = child->limits.nofile.rlim_cur = 32; + /* Scalar socket descriptors isolate locking from transport protocols. */ + const uint64_t identities[] = {0x100000010000002aULL, 0x100000010000002aULL, + 0x100000020000002aULL, 0x100000010000002bULL}; + for (unsigned i = 0; i < 4; ++i) { + struct task_file *file; + assert(task_allocate_fd(parent, 3, &file) == (int)i + 3); + file->flags = TASK_FILE_FLAG_SOCKET | RELIEFOS_O_RDWR; + file->socket_ino = identities[i]; + file->node.type = RELIEFOS_FS_TYPE_SOCKET; + } + current_task[0] = descriptor_dispatch_task = parent; + struct descriptor_record_lock lock = {.type = LINUX_F_WRLCK, .length = 1}; + int64_t result = syscall_legacy_descriptors(LINUX_SYS_FCNTL, 3, commands[mode], + (uintptr_t)&lock, 0, 0, 0); + if (result) + fprintf(stderr, "FAIL socket fcntl command=%u returned %lld, expected 0\n", + commands[mode], (long long)result); + assert(result == 0); + /* Socket SEEK_END is based on zero and must avoid storage refresh. */ + lock.whence = 2; + assert(!syscall_record_lock(3, commands[mode], (uintptr_t)&lock)); + lock.whence = 0; + int alias = task_duplicate_file_fd(parent, 3, 7, 0); + assert(alias == 7); + child->fd_table = parent->fd_table; + child->fd_table.lock_owner = 0; + assert(!syscall_clone_task_files(parent, child)); + current_task[0] = descriptor_dispatch_task = child; + const unsigned set = mode ? LINUX_F_OFD_SETLK : LINUX_F_SETLK; + assert(syscall_record_lock(4, set, (uintptr_t)&lock) == -RELIEFOS_EAGAIN); + struct descriptor_record_lock query = lock; + assert(!syscall_record_lock(4, mode ? LINUX_F_OFD_GETLK : LINUX_F_GETLK, + (uintptr_t)&query)); + assert(query.type == LINUX_F_WRLCK && query.pid == (mode ? -1 : 1390)); + assert(!syscall_record_lock(5, set, (uintptr_t)&lock)); + assert(!syscall_record_lock(6, set, (uintptr_t)&lock)); + struct task_file *path; + assert(task_allocate_fd(child, 8, &path) == 8); + path->flags = TASK_FILE_FLAG_SOCKET | TASK_FILE_FLAG_PATH | RELIEFOS_O_RDWR; + path->socket_ino = identities[0]; + path->node.type = RELIEFOS_FS_TYPE_SOCKET; + assert(syscall_record_lock(8, set, (uintptr_t)&lock) == -RELIEFOS_EBADF); + task_discard_file_fd(child, 8); + current_task[0] = descriptor_dispatch_task = parent; + /* POSIX close drops this task's lock even while another alias remains. */ + task_discard_file_fd(parent, alias); + current_task[0] = descriptor_dispatch_task = child; + assert(syscall_record_lock(4, set, (uintptr_t)&lock) == + (mode ? -RELIEFOS_EAGAIN : 0)); + if (!mode) { + lock.type = LINUX_F_UNLCK; + assert(!syscall_record_lock(4, set, (uintptr_t)&lock)); + lock.type = LINUX_F_WRLCK; + } + current_task[0] = descriptor_dispatch_task = parent; + task_discard_file_fd(parent, 3); + struct task_file *reused; + assert(task_allocate_fd(parent, 3, &reused) == 3); + reused->flags = TASK_FILE_FLAG_SOCKET | RELIEFOS_O_RDWR; + reused->socket_ino = 0x100000030000002aULL; + reused->node.type = RELIEFOS_FS_TYPE_SOCKET; + assert(!syscall_record_lock(3, set, (uintptr_t)&lock)); + task_discard_file_fd(parent, 3); + current_task[0] = descriptor_dispatch_task = child; + if (mode) { + assert(syscall_record_lock(4, set, (uintptr_t)&lock) == -RELIEFOS_EAGAIN); + task_discard_file_fd(child, 3); + assert(syscall_record_lock(4, set, (uintptr_t)&lock) == -RELIEFOS_EAGAIN); + task_discard_file_fd(child, alias); + } + assert(!syscall_record_lock(4, set, (uintptr_t)&lock)); + clear_task_files(parent); + clear_task_files(child); + sched_task_file_release(parent); + sched_task_file_release(child); + current_task[0] = descriptor_dispatch_task = NULL; + free(parent); + free(child); + } + puts("PASS socket record locks: POSIX/OFD, full inode identity, task conflict, dup/fork/close, O_PATH and FD reuse"); +} + /** @brief Exercise OFD locks through actual fcntl, dup/fork and final cleanup. */ static void test_ofd_record_lock_lifetime(void) { @@ -3560,6 +3656,7 @@ static void test_proc_ofd_lifetime(void) int main(void) { + test_socket_record_locks(); test_ofd_record_lock_lifetime(); test_record_lock_retry_description(); test_proc_ofd_lifetime(); diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index d100234c..8df1edd2 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -204,6 +204,59 @@ static void check_route_completion(int fd) net_config.gateway_ip=gateway; } +/* iproute2 retains a zero-filled reserve after the declared address request. */ +static void check_netlink_datagram_tail(int fd) +{ + struct { + struct nlmsghdr header; + struct ifaddrmsg address; + unsigned char reserve[128]; + } request={ + .header={.nlmsg_len=sizeof(struct nlmsghdr)+sizeof(struct ifaddrmsg), + .nlmsg_type=RTM_GETADDR,.nlmsg_flags=NLM_F_REQUEST|NLM_F_DUMP,.nlmsg_seq=190}, + .address={.ifa_family=AF_INET}}; + assert(sizeof(request)==152 && request.header.nlmsg_len==24); + int sent=send_req(fd,&request,sizeof(request)); + if(sent!=(int)sizeof(request)) + fprintf(stderr,"padded RTM_GETADDR send returned %d, expected 152\n",sent); + assert(sent==(int)sizeof(request)); + unsigned char output[8192]; + int count=receive_dump(fd,output,sizeof(output)); + struct nlmsghdr *reply=(void *)output; + assert(count>0 && reply->nlmsg_type==RTM_NEWADDR && reply->nlmsg_seq==190); + assert(receive(fd,output,sizeof(output))==-LINUX_EAGAIN); + + /* An incomplete next header terminates parsing after the valid prefix. */ + memset(request.reserve,0xff,sizeof(request.reserve)); + assert(send_req(fd,&request,request.header.nlmsg_len+3)==(int)request.header.nlmsg_len+3); + assert(receive_dump(fd,output,sizeof(output))>0); + assert(receive(fd,output,sizeof(output))==-LINUX_EAGAIN); + + /* Invalid complete headers are ignored, including at the datagram start. */ + const uint32_t invalid_lengths[]={0,sizeof(struct nlmsghdr)-1,sizeof(struct nlmsghdr)+1}; + for(unsigned i=0;i0); + assert(receive(fd,output,sizeof(output))==-LINUX_EAGAIN); + assert(send_req(fd,&invalid,sizeof(invalid))==sizeof(invalid)); + assert(receive(fd,output,sizeof(output))==-LINUX_EAGAIN); + } + /* The final rtgenmsg needs no bytes beyond its declared unaligned length. */ + struct {struct nlmsghdr header;uint8_t family;} generic={ + .header={.nlmsg_len=sizeof(struct nlmsghdr)+1,.nlmsg_type=RTM_GETADDR, + .nlmsg_flags=NLM_F_REQUEST|NLM_F_DUMP,.nlmsg_seq=192},.family=AF_INET}; + assert(send_req(fd,&generic,generic.header.nlmsg_len)==(int)generic.header.nlmsg_len); + count=receive_dump(fd,output,sizeof(output)); + reply=(void *)output; + assert(count>0 && reply->nlmsg_type==RTM_NEWADDR && reply->nlmsg_seq==192); + assert(receive(fd,output,sizeof(output))==-LINUX_EAGAIN); + puts("PASS netlink datagram valid prefix, padded reserve, ignored invalid tail and final alignment"); +} + static void check_dump_boundaries(int fd) { struct { struct nlmsghdr h; struct ifaddrmsg m; } request = { @@ -225,7 +278,7 @@ static void check_dump_boundaries(int fd) unsigned accepted=0; int rc; while ((rc=send_req(fd,&request,sizeof(request)))==(int)sizeof(request)) - assert(++accepted<=NL_QUEUE_BUDGET/NL_MESSAGE_MAX); + assert(++accepted <= 8); assert(rc==-LINUX_ENOBUFS && accepted); for (unsigned i=0;i0); assert(receive(fd,output,sizeof(output))==-LINUX_EAGAIN); @@ -411,6 +464,119 @@ static void check_netlink_namespace_failures(void) puts("PASS netlink namespace cleanup: ENOMEM, EMFILE and final socket release"); } +/** @brief Buffer options must control independent per-socket send/receive limits. */ +static void check_netlink_buffers(void) +{ + const int protocols[] = {NETLINK_ROUTE, NETLINK_KOBJECT_UEVENT}; + for (unsigned protocol = 0; protocol < 2; ++protocol) { + int fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[protocol], 0, 0); + int other = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, protocols[protocol], 0, 0); + assert(fd >= 0 && other >= 0); + const unsigned options[] = {7, 8}; + for (unsigned i = 0; i < 2; ++i) { + int32_t value = -1; + uint32_t size = sizeof(value); + long result = call(__NR_getsockopt, fd, SOL_SOCKET, options[i], + (uintptr_t)&value, (uintptr_t)&size); + if (result) + fprintf(stderr, "FAIL netlink buffer option=%u get returned %ld, expected 0\n", + options[i], result); + assert(result == 0 && value == 65536 && size == sizeof(value)); + const int32_t requests[] = {0, 8192, 65536, 65537, -1}; + const int32_t expected[] = {i ? 2304 : 4608, 16384, 131072, 131072, 131072}; + for (unsigned j = 0; j < 5; ++j) { + value = requests[j]; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, options[i], + (uintptr_t)&value, sizeof(value))); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, options[i], + (uintptr_t)&value, (uintptr_t)&size)); + assert(value == expected[j]); + } + value = 8192; + assert(call(__NR_setsockopt, fd, SOL_SOCKET, options[i], (uintptr_t)&value, 3) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, fd, SOL_SOCKET, options[i], (uintptr_t)&value, UINT32_MAX) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, fd, SOL_SOCKET, options[i], 0, sizeof(value)) == -LINUX_EFAULT); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, options[i], (uintptr_t)&value, (uintptr_t)&size)); + assert(value == 131072); + size = UINT32_MAX; + assert(call(__NR_getsockopt, fd, SOL_SOCKET, options[i], (uintptr_t)&value, (uintptr_t)&size) == -LINUX_EINVAL); + size = sizeof(value); + assert(call(__NR_getsockopt, fd, SOL_SOCKET, options[i], 0, (uintptr_t)&size) == -LINUX_EFAULT); + assert(call(__NR_getsockopt, fd, SOL_SOCKET, options[i], (uintptr_t)&value, 0) == -LINUX_EFAULT); + assert(!call(__NR_getsockopt, other, SOL_SOCKET, options[i], (uintptr_t)&value, (uintptr_t)&size)); + assert(value == 65536); + } + int32_t value = 0; + uint32_t size = sizeof(value); + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, 7, (uintptr_t)&value, sizeof(value))); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, 8, (uintptr_t)&value, (uintptr_t)&size)); + assert(value == 131072); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, 7, (uintptr_t)&value, (uintptr_t)&size)); + assert(value == 4608); + task_netlink_release(&files[other]); files[other] = (struct task_file){0}; + task_netlink_release(&files[fd]); files[fd] = (struct task_file){0}; + } + assert(!allocations); +} + +/** @brief Enforce slot reservations and send limits through real route requests. */ +static void check_netlink_buffer_limits(void) +{ + int fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(fd >= 0); + int32_t value = 8192; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, 8, (uintptr_t)&value, sizeof(value))); + struct nlmsghdr request = {.nlmsg_len = sizeof(request), .nlmsg_type = 0xffff, + .nlmsg_flags = NLM_F_REQUEST, .nlmsg_seq = 800}; + unsigned char output[8192]; + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + assert(send_req(fd, &request, sizeof(request)) == -LINUX_ENOBUFS); + assert(receive(fd, output, sizeof(output)) > 0); + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + /* Shrinking below one slot preserves queued datagrams and denies new ones. */ + value = 0; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, 8, (uintptr_t)&value, sizeof(value))); + assert(send_req(fd, &request, sizeof(request)) == -LINUX_ENOBUFS); + assert(receive(fd, output, sizeof(output)) > 0); + assert(receive(fd, output, sizeof(output)) > 0); + assert(receive(fd, output, sizeof(output)) == -LINUX_EAGAIN); + assert(send_req(fd, &request, sizeof(request)) == -LINUX_ENOBUFS); + value = 8192; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, 8, (uintptr_t)&value, sizeof(value))); + struct { struct nlmsghdr h; struct ifinfomsg m; } dump = { + .h = {.nlmsg_len = sizeof(dump), .nlmsg_type = RTM_GETLINK, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP, .nlmsg_seq = 801}, + .m = {.ifi_family = AF_UNSPEC}, + }; + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + assert(send_req(fd, &dump, sizeof(dump)) == -LINUX_ENOBUFS); + assert(receive(fd, output, sizeof(output)) > 0); + assert(send_req(fd, &dump, sizeof(dump)) == sizeof(dump)); + assert(send_req(fd, &request, sizeof(request)) == -LINUX_ENOBUFS); + assert(receive_dump(fd, output, sizeof(output)) > 0); + value = 4096; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, 8, (uintptr_t)&value, sizeof(value))); + assert(send_req(fd, &dump, sizeof(dump)) == -LINUX_ENOBUFS); + value = 8192; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, 8, (uintptr_t)&value, sizeof(value))); + value = 0; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, 7, (uintptr_t)&value, sizeof(value))); + unsigned char payload[8196] = {0}; + struct nlmsghdr large = request; + large.nlmsg_len = 4576; + memcpy(payload, &large, sizeof(large)); + assert(send_req(fd, payload, 4577) == -LINUX_EMSGSIZE); + assert(send_req(fd, payload, 4576) == 4576); + assert(receive(fd, output, sizeof(output)) > 0); + value = 65536; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, 7, (uintptr_t)&value, sizeof(value))); + assert(send_req(fd, payload, 8196) == -LINUX_EMSGSIZE); + task_netlink_release(&files[fd]); files[fd] = (struct task_file){0}; + assert(!allocations); + puts("PASS netlink buffer limits: doubling/clamp/minimum, independent options, queue shrink/drain, dump reservation and send boundary"); +} + /** @brief Verify SO_REUSEADDR state without changing netlink port exclusivity. */ static void check_netlink_reuseaddr(void) { @@ -1181,6 +1347,8 @@ static void check_scoped_ipv6_control(void) int main(void) { + check_netlink_buffers(); + check_netlink_buffer_limits(); check_netlink_namespace_ports(); check_netlink_namespace_delivery(); check_netlink_namespace_events(); @@ -1200,6 +1368,7 @@ int main(void) assert(fd >= 0 && files[fd].socket_ino); check_route_completion(fd); check_dump_boundaries(fd); + check_netlink_datagram_tail(fd); struct { struct nlmsghdr h; struct ifinfomsg m; } link = { .h={.nlmsg_len=sizeof(link),.nlmsg_type=RTM_GETLINK,.nlmsg_flags=NLM_F_REQUEST|NLM_F_DUMP,.nlmsg_seq=42}, .m={.ifi_family=AF_UNSPEC}}; diff --git a/tools/tests/linux_inventory_test.c b/tools/tests/linux_inventory_test.c index 5577fc75..73b17375 100644 --- a/tools/tests/linux_inventory_test.c +++ b/tools/tests/linux_inventory_test.c @@ -220,6 +220,14 @@ static void check_foreground_sysfs(void) assert(!vfs_namespace_init(&ns, mount)); vfs_mount_put(mount); assert(!vfs_namespace_root(&ns, &root)); + /* Use the actual sysfs provider to check shared readonly reconfiguration. */ + assert(!vfs_path_remount_options(&root, MS_RDONLY, "")); + assert(vfs_path_mount_flags(&root) & MS_RDONLY); + assert(vfs_path_remount_options(&root, 0, "unknown=1") == -EOPNOTSUPP); + assert(vfs_path_mount_flags(&root) & MS_RDONLY); + assert(!vfs_path_remount_options(&root, 0, "")); + assert(!(vfs_path_mount_flags(&root) & MS_RDONLY)); + assert(!vfs_path_lookup(&ns, &root, &root, "class/tty/tty0/active", VFS_LOOKUP_FOLLOW, &active)); assert(!vfs_path_lookup(&ns, &root, &root, "devices/virtual/tty/tty0/active", diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 41ff159d..613ddbe4 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -36,6 +36,7 @@ int kernel_signal_queue_task(struct task *task,int signal_number) #include #include #include +#include #include #include #include @@ -3129,6 +3130,186 @@ static void runtime_proc_mount_api(struct vfs_namespace *ns,const struct vfs_pat puts("PASS proc mount API: parameter validation, create retry, legacy options and attachment"); } +/** @brief Check captured network-owner authority and failed context publication. */ +static void runtime_sysfs_owner_mount_api(struct vfs_namespace *ns,const struct vfs_path *root, + const char *type,const char *target) +{ + struct task creator={.euid=5000}; + struct user_namespace *owner=NULL,*sibling=NULL; + assert(!user_namespace_create(&creator,&owner)); + assert(!user_namespace_create(&creator,&sibling)); + struct net_namespace *network=NULL; + assert(!net_namespace_create(owner,&network)); + struct task actor={.pid=909,.user_ns=owner,.euid=5000, + .cap_effective=1ULL<nofile.rlim_cur=32; + vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); + struct vfs_namespace *owned=NULL; + assert(!vfs_namespace_clone_owned(ns,owner,&actor.fs_paths.root,&actor.fs_paths.cwd,&owned)); + uint64_t references=owner->references; + assert(scoped_mount_call(owned,&actor,__NR_fsopen,(uintptr_t)type,0,0,0,0)==-EPERM); + assert(scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,(uintptr_t)type, + (uintptr_t)target,(uintptr_t)type,0,0)==-EPERM); + assert(owner->references==references); + + actor.net_ns=network; + sched_task_limits(&actor)->nofile.rlim_cur=0; + assert(scoped_mount_call(owned,&actor,__NR_fsopen,(uintptr_t)type,0,0,0,0)==-EMFILE); + assert(owner->references==references && network->references==1); + sched_task_limits(&actor)->nofile.rlim_cur=32; + bool opened=false; + int context=-1; + for(int budget=0;budget<16 && !opened;++budget) { + test_fail_heap_after=budget; + context=scoped_mount_call(owned,&actor,__NR_fsopen,(uintptr_t)type,0,0,0,0); + test_fail_heap_after=-1; + opened=context>=0; + if(!opened) { + assert(context==-ENOMEM); + assert(owner->references==references && network->references==1); + } + } + assert(opened && owner->references==references+1); + assert(!(task_descriptor_for_fd(&actor,context)->fd_flags & RELIEFOS_FD_CLOEXEC)); + actor.cap_effective=0; + assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,6,0,0,0)==-EPERM); + actor.cap_effective=1ULL<references==references+1); + actor.user_ns=owner; + /* Moving networks cannot replace the owner captured when the context opened. */ + initial_sysfs_error=true; + assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,6,0,0,0)==-EIO); + initial_sysfs_error=false; + assert(owner->references==references+1); + assert(!scoped_mount_call(owned,&actor,__NR_fsconfig,context,6,0,0,0)); + int mountfd=scoped_mount_call(owned,&actor,__NR_fsmount,context,0,0,0,0); + assert(mountfd>=0); + struct task_file *mount_file=task_file_for_fd(&actor,mountfd); + assert(vfs_path_user_namespace(&mount_file->path_ref)==owner); + assert(!strcmp(mount_file->path_ref.mount->source,"none")); + assert(!(task_descriptor_for_fd(&actor,mountfd)->fd_flags & RELIEFOS_FD_CLOEXEC)); + task_discard_file_fd(&actor,context);task_discard_file_fd(&actor,mountfd); + while(vfs_reclaim_pending())vfs_reclaim_mounts(UINT32_MAX); + assert(owner->references==references); + + actor.net_ns=network; + assert(!scoped_mount_call(owned,&actor,LINUX_SYS_MOUNT,(uintptr_t)type, + (uintptr_t)target,(uintptr_t)type,0,0)); + struct vfs_path attached={0}; + assert(!vfs_path_lookup(owned,&actor.fs_paths.root,&actor.fs_paths.cwd,target,0,&attached)); + assert(vfs_path_user_namespace(&attached)==owner); + assert(!vfs_mount_unmount(owned,&attached));vfs_path_put(&attached); + actor.net_ns=NULL; + vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + vfs_namespace_put(owned); + while(vfs_reclaim_pending())vfs_reclaim_mounts(UINT32_MAX); + assert(network->references==1); + net_namespace_put(network); + assert(owner->references==1 && sibling->references==1); + user_namespace_put(owner);user_namespace_put(sibling); + puts("PASS sysfs network owner admission, captured CREATE authority and reference rollback"); +} + +/** @brief Exercise sysfs creation and attachment in the initial user namespace. */ +static void runtime_sysfs_mount_api(struct vfs_namespace *ns,const struct vfs_path *root, + struct tmpfs_super *fs) +{ + struct tmpfs_super *sysfs_fixture=NULL; + assert(!g_volumes[5].ready); + assert(!tmpfs_new(5,0,NULL,0,0,&sysfs_fixture)); + g_volumes[5]=(struct storage_volume){.volume_id=5,.kind=STORAGE_VOLUME_ANONYMOUS, + .ready=true,.filesystem=STORAGE_FILESYSTEM_TMPFS,.fs_ops=&storage_tmpfs_ops, + .tmpfs=sysfs_fixture}; + struct { + char type[8],source[8],label[24],unknown[16],value[8],ro[4],rw[4]; + char target[32],empty[1]; + } user={"sysfs","source","sysfs fixture","unknown","1","ro","rw", + "/sysfs-new-api",""}; + struct task actor={.pid=908,.cap_effective=1ULL<nofile.rlim_cur=32; + vfs_path_get(root,&actor.fs_paths.root);vfs_path_get(root,&actor.fs_paths.cwd); + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + assert(!tmpfs_create(fs,user.target,LINUX_S_IFDIR|0755,NULL,NULL)); + + actor.cap_effective=0; + assert(scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.type,0,0,0,0)==-EPERM); + actor.cap_effective=1ULL<=0); + assert(task_descriptor_for_fd(&actor,context)->fd_flags & RELIEFOS_FD_CLOEXEC); + assert(scoped_mount_call(ns,&actor,__NR_fsmount,context,0,0,0,0)==-EINVAL); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.source,0,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.label,0)); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.type,0)==-EINVAL); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.unknown,(uintptr_t)user.value,0)==-EINVAL); + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.unknown,0,0)==-EINVAL); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.ro,0,0)); + actor.cap_effective=0; + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)==-EPERM); + actor.cap_effective=1ULL<=0); + assert(task_descriptor_for_fd(&actor,mountfd)->fd_flags & RELIEFOS_FD_CLOEXEC); + struct task_file *mount_file=task_file_for_fd(&actor,mountfd); + assert(mount_file && vfs_path_node(&mount_file->path_ref)->volume_id==5); + assert(!strcmp(mount_file->path_ref.mount->source,user.label)); + assert(!vfs_path_user_namespace(&mount_file->path_ref)); + assert((vfs_path_mount_flags(&mount_file->path_ref)&(MS_RDONLY|MS_NODEV|MS_NOSUID|MS_NOEXEC))== + (MS_RDONLY|MS_NODEV|MS_NOSUID|MS_NOEXEC)); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.rw,0,0)); + actor.cap_effective=0; + assert(scoped_mount_call(ns,&actor,__NR_fsconfig,context,7,0,0,0)==-EPERM); + assert(vfs_path_mount_flags(&mount_file->path_ref)&MS_RDONLY); + actor.cap_effective=1ULL<path_ref)&MS_RDONLY)); + assert(!strcmp(mount_file->path_ref.mount->source,user.label)); + actor.cap_effective=0; + assert(scoped_mount_call(ns,&actor,__NR_move_mount,mountfd,(uintptr_t)user.empty, + (uint32_t)LINUX_AT_FDCWD,(uintptr_t)user.target,4)==-EPERM); + actor.cap_effective=1ULL<path_ref)); + task_discard_file_fd(&actor,context);task_discard_file_fd(&actor,mountfd); + assert(!vfs_mount_unmount(ns,&attached));vfs_path_put(&attached); + /* Explicit attachment readonly survives a shared backend rw transition. */ + context=scoped_mount_call(ns,&actor,__NR_fsopen,(uintptr_t)user.type,0,0,0,0); + assert(context>=0); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.ro,0,0)); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,6,0,0,0)); + mountfd=scoped_mount_call(ns,&actor,__NR_fsmount,context,0,MS_RDONLY,0,0); + assert(mountfd>=0); + mount_file=task_file_for_fd(&actor,mountfd); + assert(vfs_path_mount_flags(&mount_file->path_ref)&MS_RDONLY); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.rw,0,0)); + assert(!scoped_mount_call(ns,&actor,__NR_fsconfig,context,7,0,0,0)); + assert(vfs_path_mount_flags(&mount_file->path_ref)&MS_RDONLY); + task_discard_file_fd(&actor,context);task_discard_file_fd(&actor,mountfd); + runtime_sysfs_owner_mount_api(ns,root,user.type,user.target); + assert(!tmpfs_unlink(fs,user.target,true)); + vfs_path_put(&actor.fs_paths.root);vfs_path_put(&actor.fs_paths.cwd); + assert(!g_volumes[5].vfs_mounts && !storage_inode_volume_busy(5)); + tmpfs_destroy(sysfs_fixture);g_volumes[5]=(struct storage_volume){0}; + lookup_user_base=lookup_user_bytes=0; + puts("PASS sysfs mount API source, options, CLOEXEC, authority and attachment"); +} + /** @brief Read a generated cgroup control by its retained inode and check exact bytes. */ static void cgroup_check_text(const struct vfs_path *directory,const char *name,const char *expected) { @@ -5062,6 +5243,7 @@ int main(int argc,char **argv) runtime_detached_mount(&ns,&root); runtime_new_mount_api(&ns,&root,fs); runtime_proc_mount_api(&ns,&root,fs); + runtime_sysfs_mount_api(&ns,&root,fs); runtime_attachment_policies(&ns,&root); runtime_mount_syscalls(&ns,&root,fs); runtime_mount_user_authority(&ns,&root,fs); diff --git a/tools/tests/mount_namespace_task_test.c b/tools/tests/mount_namespace_task_test.c index 587cbbcd..0d7410e0 100644 --- a/tools/tests/mount_namespace_task_test.c +++ b/tools/tests/mount_namespace_task_test.c @@ -30,12 +30,17 @@ int task_fd_descriptor_flags(struct task *task, int fd) static int mount_budget = -1; static int user_namespace_budget = -1; static int uts_namespace_budget = -1; +static int net_namespace_budget = -1; static unsigned mount_allocations, charges; static const struct task *unpublished_child; /** @brief Fail the second snapshot attachment, after staging the first one. */ bool namespace_heap_admit(uint64_t size) { + if (size == sizeof(struct net_namespace) && net_namespace_budget >= 0) { + assert(!scheduler_lock.state); + return net_namespace_budget-- > 0; + } if (size == sizeof(struct uts_namespace) && uts_namespace_budget >= 0) { assert(!scheduler_lock.state); return uts_namespace_budget-- > 0; @@ -116,7 +121,7 @@ static void check_unshare(struct task *task, const struct task *unpublished) assert(syscall_unshare(task, CLONE_NEWNS) == -LINUX_EPERM); task->cap_effective = capability; assert(syscall_unshare(task, CLONE_NEWNS | (1ULL << 40)) == -LINUX_EINVAL); - assert(syscall_unshare(task, CLONE_NEWNS | CLONE_NEWNET) == -LINUX_EINVAL); + assert(syscall_unshare(task, CLONE_NEWNS | CLONE_NEWPID) == -LINUX_EINVAL); assert(!task_promote_shared(task, CLONE_FS)); struct task sibling = {.shared_fs = task->shared_fs}; ++sibling.shared_fs->references; @@ -619,6 +624,156 @@ static void check_uts_setns(struct task *task) puts("PASS UTS setns typed handles, local/owner authority, shared FS and held lifetime"); } +/** @brief Catch shared network creation, wrong owners and partial namespace publication. */ +static void check_net_creation(struct task *parent, struct task *child, + struct clone_operands *user) +{ + struct net_namespace *source = parent->net_ns; + const uint64_t admin = UINT64_C(1) << CAP_SYS_ADMIN; + for (unsigned versioned = 0; versioned < 2; ++versioned) { + parent->cap_effective = 0; + assert(clone_namespace(parent, user, versioned, CLONE_NEWNET) == -LINUX_EPERM); + parent->cap_effective = admin; + assert(clone_namespace(parent, user, versioned, 0) > 0); + assert(child->net_ns == source && source->references == 2); + retire_child(child); + assert(source->references == 1); + + uint64_t created = proc_created, mount_id = next_mount_id; + unsigned old_charges = charges, pages = live_pages(); + uint64_t flags = CLONE_NEWNET | CLONE_PARENT_SETTID | CLONE_CHILD_SETTID; + user->parent_tid = user->child_tid = 0x44444444; + net_namespace_budget = 0; + assert(clone_namespace(parent, user, versioned, flags) == -LINUX_ENOMEM); + net_namespace_budget = -1; + unpublished_child = child; + mount_budget = 1; + assert(clone_namespace(parent, user, versioned, flags | CLONE_NEWNS) == -LINUX_ENOMEM); + mount_budget = -1; + shm_physical_budget = 0; + assert(clone_namespace(parent, user, versioned, flags) == -LINUX_ENOMEM); + shm_physical_budget = -1; + assert(!child->pid && !child->net_ns && !child->user_ns); + assert(source->references == 1 && proc_created == created && charges == old_charges); + assert(next_mount_id == mount_id && live_pages() == pages); + assert(user->parent_tid == 0x44444444 && user->child_tid == 0x44444444); + + assert(clone_namespace(parent, user, versioned, CLONE_NEWNET | CLONE_FS) > 0); + assert(child->net_ns && child->net_ns != source && child->net_ns->references == 1); + assert(!child->net_ns->user_ns && !child->net_ns->loopback.up); + assert(!child->net_ns->interfaces && !child->net_ns->ipv4_routes); + assert(child->shared_fs == parent->shared_fs); + retire_child(child); + parent->cap_effective = 0; + assert(clone_namespace(parent, user, versioned, CLONE_NEWUSER | CLONE_NEWNET) > 0); + assert(child->net_ns->user_ns == child->user_ns && child->user_ns->references == 2); + assert(task_ns_capable(child, child->net_ns->user_ns, CAP_SYS_ADMIN)); + assert(!task_ns_capable(child, source->user_ns, CAP_SYS_ADMIN)); + retire_child(child); + parent->cap_effective = admin; + } + + assert(!task_promote_shared(parent, CLONE_FS)); + struct task sibling = {.shared_fs = parent->shared_fs}; + ++sibling.shared_fs->references; + struct vfs_namespace *mount = sched_task_namespace(parent); + struct uts_namespace *uts = parent->uts_ns; + parent->cap_effective = 0; + assert(syscall_unshare(parent, CLONE_NEWNET) == -LINUX_EPERM); + parent->cap_effective = admin; + net_namespace_budget = 0; + assert(syscall_unshare(parent, CLONE_NEWNET) == -LINUX_ENOMEM); + net_namespace_budget = 0; + assert(syscall_unshare(parent, CLONE_NEWUSER | CLONE_NEWUTS | CLONE_NEWNET) == -LINUX_ENOMEM); + net_namespace_budget = -1; + unpublished_child = child; + mount_budget = 1; + assert(syscall_unshare(parent, CLONE_NEWNET | CLONE_NEWNS) == -LINUX_ENOMEM); + mount_budget = -1; + assert(parent->net_ns == source && source->references == 1 && !parent->user_ns); + assert(parent->uts_ns == uts && sched_task_namespace(parent) == mount); + assert(parent->shared_fs == sibling.shared_fs && parent->shared_fs->references == 2); + net_namespace_get(source); + assert(!syscall_unshare(parent, CLONE_NEWNET)); + assert(parent->net_ns != source && !parent->net_ns->user_ns); + assert(parent->shared_fs == sibling.shared_fs && parent->shared_fs->references == 2); + net_namespace_put(parent->net_ns); + parent->net_ns = source; + sched_task_fs_release(&sibling); + net_namespace_get(source); + parent->cap_effective = 0; + assert(!syscall_unshare(parent, CLONE_NEWUSER | CLONE_NEWNET)); + assert(parent->net_ns != source && parent->net_ns->user_ns == parent->user_ns); + assert(parent->user_ns->references == 2); + assert(task_ns_capable(parent, parent->net_ns->user_ns, CAP_SYS_ADMIN)); + assert(!task_ns_capable(parent, source->user_ns, CAP_SYS_ADMIN)); + net_namespace_put(parent->net_ns); + parent->net_ns = source; + assert(parent->user_ns->references == 1); + user_namespace_put(parent->user_ns); + parent->user_ns = NULL; + parent->cap_effective = admin; + puts("PASS NEWNET clone/clone3 sharing, owned creation, unshare and atomic rollback"); +} + +/** @brief Exercise real network handles, dual authority and FD-held namespace lifetime. */ +static void check_net_setns(struct task *task) +{ + struct net_namespace *source = net_namespace_get(task->net_ns), *target = NULL; + struct user_namespace *owner = NULL; + assert(!user_namespace_create(task, &owner)); + assert(!net_namespace_create(owner, &target)); + assert(!nsfs_create_net_path(target, &handle_file.path_ref)); + assert(!nsfs_create_net_path(NULL, &ordinary_file.path_ref)); + struct net_namespace *initial = (void *)1; + assert(nsfs_path_net_namespace(&ordinary_file.path_ref, &initial) && !initial); + struct net_namespace *borrowed = NULL; + assert(nsfs_path_net_namespace(&handle_file.path_ref, &borrowed) && borrowed == target); + assert(nsfs_path_type(&handle_file.path_ref) == CLONE_NEWNET); + net_namespace_put(target); + assert(target->references == 1 && owner->references == 2); + assert(syscall_setns(task, 3, CLONE_NEWUTS) == -LINUX_EINVAL); + handle_file.flags = TASK_FILE_FLAG_PATH; + assert(syscall_setns(task, 3, CLONE_NEWNET) == -LINUX_EBADF); + handle_file.flags = 0; + task->cap_effective = 0; + assert(syscall_setns(task, 3, CLONE_NEWNET) == -LINUX_EPERM); + assert(task->net_ns == source && target->references == 1); + task->cap_effective = UINT64_C(1) << CAP_SYS_ADMIN; + assert(!task_promote_shared(task, CLONE_FS)); + struct task sibling = {.shared_fs = task->shared_fs}; + ++sibling.shared_fs->references; + assert(!syscall_setns(task, 3, 0)); + assert(task->net_ns == target && target->references == 2); + assert(task->shared_fs == sibling.shared_fs && task->shared_fs->references == 2); + assert(!syscall_setns(task, 3, CLONE_NEWNET) && target->references == 2); + assert(!syscall_setns(task, 4, CLONE_NEWNET) && !task->net_ns); + assert(target->references == 1); + struct vfs_path retained = {0}; + vfs_path_get(&handle_file.path_ref, &retained); + vfs_path_put(&handle_file.path_ref); + handle_file.path_ref = retained; + assert(target->references == 1); + assert(!syscall_setns(task, 3, CLONE_NEWNET) && target->references == 2); + task->user_ns = owner; + assert(syscall_setns(task, 4, CLONE_NEWNET) == -LINUX_EPERM); + task->cap_effective = 0; + assert(syscall_setns(task, 3, CLONE_NEWNET) == -LINUX_EPERM); + task->cap_effective = UINT64_C(1) << CAP_SYS_ADMIN; + assert(!syscall_setns(task, 3, CLONE_NEWNET)); + task->user_ns = NULL; + user_namespace_put(owner); + vfs_path_put(&handle_file.path_ref); + while (vfs_reclaim_mounts(16)) {} + assert(target->references == 1 && target->user_ns->references == 1); + assert(!syscall_setns(task, 4, CLONE_NEWNET) && !task->net_ns); + assert(task->shared_fs == sibling.shared_fs); + vfs_path_put(&ordinary_file.path_ref); + sched_task_fs_release(&sibling); + task->net_ns = source; + puts("PASS network setns authentic handles, local/owner authority and FD lifetime"); +} + int main(void) { struct sched_task_object parent_object = {0}, child_object = {0}; @@ -746,6 +901,8 @@ int main(void) check_mount_user_setns(parent); check_uts_creation(parent, child, user); check_uts_setns(parent); + check_net_creation(parent, child, user); + check_net_setns(parent); assert(parent->net_ns == network && network->references == 1); parent->net_ns = NULL; net_namespace_put(network); diff --git a/tools/tests/procfs_directories_test.c b/tools/tests/procfs_directories_test.c index 1170d999..84a889b3 100644 --- a/tools/tests/procfs_directories_test.c +++ b/tools/tests/procfs_directories_test.c @@ -9,6 +9,7 @@ #include #include #include +#include int sound_service_card_snapshot(uint32_t index, uint32_t *out_id, struct audio_card_identity *identity) { (void)index; (void)out_id; (void)identity; return -2; } @@ -803,6 +804,8 @@ static void test_proc_mount_namespace_handles(void) assert(entry.type == RELIEFOS_FS_TYPE_SYMLINK && !strcmp(entry.name, "user")); assert(proc_readdir("/proc/43/ns", &cursor, &entry) == 1); assert(entry.type == RELIEFOS_FS_TYPE_SYMLINK && !strcmp(entry.name, "uts")); + assert(proc_readdir("/proc/43/ns", &cursor, &entry) == 1); + assert(entry.type == RELIEFOS_FS_TYPE_SYMLINK && !strcmp(entry.name, "net")); assert(!proc_readdir("/proc/43/ns", &cursor, &entry)); cursor = 0; bool listed = false; @@ -910,10 +913,62 @@ static void test_proc_mount_namespace_handles(void) assert(!vfs_path_stat(&fresh, &st) && st.st_ino == initial_uts_ino); vfs_path_put(&fresh); } + struct vfs_path net = {0}, initial_net = {0}, net_link = {0}; + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/net", VFS_LOOKUP_FOLLOW, &initial_net)); + struct net_namespace *borrowed_net = (void *)1; + assert(nsfs_path_type(&initial_net) == CLONE_NEWNET); + assert(nsfs_path_net_namespace(&initial_net, &borrowed_net) && !borrowed_net); + assert(!vfs_path_stat(&initial_net, &st) && st.st_dev == device); + uint64_t initial_net_ino = st.st_ino; + assert(initial_net_ino != initial_uts_ino && initial_net_ino != initial_user_ino); + assert(!net_namespace_create(NULL, &foreign.net_ns)); + struct net_namespace *net_scope = foreign.net_ns; + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/net", 0, &net_link)); + current.cap_effective = 0; + char net_label[64] = {0}, net_expected[64]; + assert(vfs_path_readlink(&net_link, net_label, sizeof(net_label), &length) == -EACCES); + assert(vfs_path_lookup(&ns, &root, &root, "43/ns/net", VFS_LOOKUP_FOLLOW, &net) == -EACCES); + current.cap_effective = UINT64_C(1) << CAP_SYS_PTRACE; + proc_allocation_budget = 0; + assert(vfs_path_lookup(&ns, &root, &root, "43/ns/net", VFS_LOOKUP_FOLLOW, &net) == -ENOMEM); + proc_allocation_budget = -1; + assert(!net.mount && net_scope->references == 1); + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/net", VFS_LOOKUP_FOLLOW, &net)); + assert(nsfs_path_net_namespace(&net, &borrowed_net) && borrowed_net == net_scope); + assert(net_scope->references == 2 && nsfs_path_type(&net) == CLONE_NEWNET); + assert(!vfs_path_stat(&net, &st) && st.st_mode == (LINUX_S_IFREG | 0444)); + assert(!vfs_path_statfs(&net, &fs) && fs.f_type == 0x6e736673); + uint64_t net_ino = st.st_ino; + assert(net_ino != initial_net_ino && net_ino != uts_ino && net_ino != ino); + snprintf(net_expected, sizeof(net_expected), "net:[%" PRIu64 "]", net_ino); + proc_allocation_budget = 0; + count = proc_readlink("/proc/43/ns/net", net_label, sizeof(net_label)); + proc_allocation_budget = -1; + assert(count == (int)strlen(net_expected) && !memcmp(net_label, net_expected, count)); + assert(proc_readlink("/proc/43/ns/net", net_label, 5) == 5 && !memcmp(net_label, "net:[", 5)); + const char *const net_aliases[] = {"self/ns/net", "thread-self/ns/net", "42/task/42/ns/net"}; + for (unsigned i = 0; i < 3; ++i) { + assert(!vfs_path_lookup(&ns, &root, &root, net_aliases[i], VFS_LOOKUP_FOLLOW, &fresh)); + assert(!vfs_path_stat(&fresh, &st) && st.st_ino == initial_net_ino); + vfs_path_put(&fresh); + } + foreign.net_ns = NULL; + net_namespace_put(net_scope); + assert(net_scope->references == 1); foreign.uts_ns = NULL; uts_namespace_put(uts_scope); assert(uts_scope->references == 1); sched_task_identity_detach(&foreign); /* Retire the identity, reusing PID 43. */ + assert(vfs_path_readlink(&net_link, net_label, sizeof(net_label), &length) == -ENOENT); + assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/net", VFS_LOOKUP_FOLLOW, &fresh)); + assert(!vfs_path_stat(&fresh, &st) && st.st_ino == initial_net_ino); + vfs_path_put(&fresh); + assert(!vfs_path_stat(&net, &st) && st.st_ino == net_ino); + assert(!vfs_path_format_link(&ns, &root, &net, net_label, sizeof(net_label))); + assert(!strcmp(net_label, net_expected)); + vfs_path_put(&net); + vfs_path_put(&initial_net); + vfs_path_put(&net_link); assert(vfs_path_readlink(&uts_link, uts_label, sizeof(uts_label), &length) == -ENOENT); assert(!vfs_path_lookup(&ns, &root, &root, "43/ns/uts", VFS_LOOKUP_FOLLOW, &fresh)); assert(!vfs_path_stat(&fresh, &st) && st.st_ino == initial_uts_ino); @@ -947,7 +1002,7 @@ static void test_proc_mount_namespace_handles(void) assert(!vfs_reclaim_pending()); assert(!vfs_namespace_destroy(&ns)); assert(proc_allocations == before); - puts("PASS proc mount/user/UTS handles, aliases, permissions, OOM, stable identity and PID reuse"); + puts("PASS proc mount/user/UTS/net handles, aliases, permissions, OOM, stable identity and PID reuse"); } /** @brief Exercise live UTS sysctl writes, scoped names and mount restrictions. */ diff --git a/tools/tests/test-version.sh b/tools/tests/test-version.sh index b0c49f6e..a4b31075 100644 --- a/tools/tests/test-version.sh +++ b/tools/tests/test-version.sh @@ -45,6 +45,7 @@ ${HOSTCC:-cc} -std=c11 -O1 -g -fsanitize=address,undefined \ "$kernel/fs/vfs/file.c" "$kernel/fs/vfs/open.c" "$kernel/fs/vfs/pseudo.c" \ "$kernel/fs/vfs/attributes.c" "$kernel/fs/proc/mount.c" "$kernel/fs/nsfs/namespace.c" "$kernel/fs/proc/views.c" \ "$kernel/kernel/syscall/fd/proc.c" "$kernel/fs/vfs/exec_file.c" \ - "$kernel/kernel/sched/identity.c" "$kernel/kernel/sched/user_namespace.c" "$kernel/fs/security/access.c" -o "$work/procfs" + "$kernel/kernel/sched/identity.c" "$kernel/kernel/sched/user_namespace.c" "$kernel/fs/security/access.c" \ + "$kernel/kernel/init/uts.c" "$kernel/net/namespace/namespace.c" "$kernel/net/ipv6/state.c" -o "$work/procfs" "$work/procfs" printf 'kernel version renderer: base, suffixes, ABI, no-op, reset, validation and procfs passed\n' From 61684adf4ea3a7ca8ab9bbbba0f9a8d1a4dd6604 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 11:45:18 +0800 Subject: [PATCH 78/97] feat(net): support official systemd networkd and resolved --- .../en/LC_MESSAGES/userspace-api/abi.po | 28 +- .../en/LC_MESSAGES/userspace-api/ipv6.po | 130 ++- .../ja/LC_MESSAGES/userspace-api/abi.po | 26 +- .../ja/LC_MESSAGES/userspace-api/ipv6.po | 130 ++- Documentation/userspace-api/abi.rst | 20 +- Documentation/userspace-api/ipv6.rst | 88 +- configs/header-export.list | 5 + fs/sysfs/Kbuild | 2 +- fs/sysfs/internal.h | 119 +++ fs/sysfs/mount.c | 60 +- fs/sysfs/network.c | 174 ++++ fs/sysfs/parameters.c | 13 + fs/sysfs/sysfs.c | 116 ++- fs/sysfs/uevent.c | 91 ++ fs/vfs/pseudo.c | 36 +- include/reliefnt/inventory.h | 11 +- include/reliefnt/net.h | 48 +- include/reliefnt/net_interface.h | 89 +- include/reliefnt/net_ipv6.h | 42 +- include/reliefnt/net_namespace.h | 2 + include/reliefnt/net_nexthop.h | 52 ++ include/reliefnt/net_udp.h | 67 +- include/reliefnt/netlink.h | 28 + include/reliefnt/pseudo_fs.h | 21 +- include/uapi/linux/errqueue.h | 22 + include/uapi/linux/genetlink.h | 47 + include/uapi/linux/if.h | 1 + include/uapi/linux/if_addr.h | 3 + include/uapi/linux/if_packet.h | 21 + include/uapi/linux/in.h | 46 + include/uapi/linux/in6.h | 1 + include/uapi/linux/neighbour.h | 26 + include/uapi/linux/netlink.h | 10 + include/uapi/linux/nexthop.h | 23 + include/uapi/linux/rtnetlink.h | 24 + include/uapi/linux/socket.h | 4 + kernel/syscall/event/timerfd.c | 21 +- kernel/syscall/fs/mount_api.c | 9 +- kernel/syscall/internal.h | 14 + kernel/syscall/ipc/socket.c | 163 +++- net/core.c | 3 + net/interface/Kbuild | 2 +- net/interface/config.c | 7 +- net/interface/ioctl.c | 43 +- net/interface/nexthop.c | 92 ++ net/interface/routes.c | 62 +- net/interface/socket.c | 41 +- net/interface/state.c | 155 +++- net/internal.h | 4 + net/ipv4/core.c | 47 +- net/ipv4/udp.c | 90 +- net/ipv6/core.c | 113 ++- net/link/arp.c | 20 + net/link/ethernet.c | 5 +- net/namespace/namespace.c | 6 + net/socket/netlink.c | 843 ++++++++++++++--- net/socket/packet.c | 220 ++++- net/socket/udp.c | 591 +++++++++++- net/tcp/output.c | 14 +- net/tcp/socket.c | 59 +- tools/test_ipv6_control.py | 2 +- tools/test_ipv6_protocol.py | 3 +- tools/test_ipv6_transport.py | 4 +- tools/test_linux_inventory.py | 5 +- tools/test_net_multinic_data.py | 2 +- tools/test_openrc_network.py | 2 +- tools/tests/ipv6_control_test.c | 859 +++++++++++++++++- tools/tests/ipv6_protocol_test.c | 202 ++++ tools/tests/ipv6_tcp_test.c | 8 +- tools/tests/ipv6_transport_test.c | 22 +- tools/tests/ipv6_vector_stubs.c | 2 - tools/tests/ipv6_vector_test.c | 301 ++++++ tools/tests/linux_inventory_test.c | 288 +++++- tools/tests/modules/network.h | 1 + tools/tests/mount_backend_test.c | 13 +- tools/tests/net_interface_test.c | 23 + tools/tests/net_multi_interface_test.c | 16 +- tools/tests/net_multinic_data_test.c | 28 +- tools/tests/net_packet_test.c | 150 +++ tools/tests/task8_host_fixtures.json | 34 + .../task8_host_stubs/descriptor_unreached.c | 1 + .../fix1-packet-front-unreached.c | 4 +- .../fix1-tcp-front-unreached.c | 6 +- .../task8_host_stubs/fix1-timerfd-entry.c | 11 + ...ate-3-inet-message-user-candidate-3.stub.c | 6 +- ...didate-3-net-ioctl-user-candidate-3.stub.c | 16 +- .../task8_host_stubs/packet_tcp_unreached.c | 1 + ...-collector-green-2-socket_dispatch_stubs.c | 3 + tools/tests/task8_inet_packet_probe_test.c | 69 ++ tools/tests/task8_inet_tcp_probe_test.c | 73 +- tools/tests/task8_timerfd_clock_test.c | 84 ++ tools/tests/task8_timerfd_entry_test.c | 4 + tools/tests/task8_timerfd_snapshot_test.c | 2 + tools/tests/task8_timerfd_user_test.c | 7 +- tools/tests/tcp_state_test.c | 254 +++++- tools/tests/udp_socket_test.c | 850 +++++++++++++++++ 96 files changed, 7064 insertions(+), 542 deletions(-) create mode 100644 fs/sysfs/network.c create mode 100644 fs/sysfs/uevent.c create mode 100644 include/reliefnt/net_nexthop.h create mode 100644 include/uapi/linux/errqueue.h create mode 100644 include/uapi/linux/genetlink.h create mode 100644 include/uapi/linux/in.h create mode 100644 include/uapi/linux/neighbour.h create mode 100644 include/uapi/linux/nexthop.h create mode 100644 net/interface/nexthop.c create mode 100644 tools/tests/task8_timerfd_clock_test.c diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index de545279..600e3e0c 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -373,20 +373,8 @@ msgstr "" "owner. CREATE requires ``CAP_SYS_ADMIN`` in that owner. See :doc:`procfs` " "for policy and reconfiguration semantics." -msgid "" -"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 捕获当前网络空间的 user owner,并要求其 ``CAP_SYS_ADMIN``。传统 sysfs " -"mount 使用同一 owner。CREATE 再次检查捕获的 owner,调用者随后切换网络不会改变该权限作用域。sysfs 上下文接受通用 ``source``、``ro`` 和 " -"``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的 只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读 " -"属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" -msgstr "" -"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` captures the current network namespace's user owner and" -" requires its ``CAP_SYS_ADMIN``. Legacy sysfs mount uses the same owner. CREATE checks the " -"captured owner again. A later network switch preserves this authority scope. sysfs contexts " -"accept the generic ``source``, ``ro`` and ``rw`` parameters. Unknown private options return " -"``EINVAL``. The shared backend retains the CREATE readonly setting, and RECONFIGURE can " -"update that state. An independent ``fsmount`` readonly attribute continues to restrict its " -"attachment. Allocation, descriptor installation and creation failures release candidate " -"references and allow retry." +msgid "``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 同时保留当前网络空间及其 user owner,并要求该 owner 的 ``CAP_SYS_ADMIN``。CREATE 再次检查捕获的 owner,并使用捕获的网络创建 sysfs 视图。上下文传递或调用者随后切换网络时,这两项捕获继续生效。传统 sysfs mount 同样使用挂载时的网络及其 owner。sysfs 上下文接受通用 ``source``、``ro`` 和 ``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" +msgstr "``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` retains both the current network namespace and its user owner and requires ``CAP_SYS_ADMIN`` in that owner. CREATE checks the captured owner again and creates the sysfs view in the captured network. Passing the context or subsequently switching the caller's network preserves both captures. A legacy sysfs mount likewise uses the network and its owner at mount time. A sysfs context accepts the generic ``source``, ``ro`` and ``rw`` parameters. Unknown private options return ``EINVAL``. CREATE stores readonly policy in the shared backend, RECONFIGURE can update it, and independent readonly attributes from ``fsmount`` continue to restrict their respective mounts. Allocation, descriptor installation and creation failures release candidate references and allow retries." msgid "" "tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 " @@ -630,3 +618,15 @@ msgstr "" msgid "普通文件和 socket 均可使用这些锁命令。socket 按完整的匿名 inode 编号识别, 同一端点的别名共享冲突范围,不同端点的锁独立。socket 的 ``SEEK_END`` 基准 为零,``O_PATH`` 描述符返回 ``EBADF``。关闭 socket 的 POSIX 锁释放规则与 普通文件相同,OFD 锁持续到最后一个引用释放。" msgstr "Regular files and sockets support these lock commands. Socket identity uses the complete anonymous inode number. Aliases of one endpoint share conflict ranges, while separate endpoints have independent locks. A socket uses zero as the ``SEEK_END`` base, and an ``O_PATH`` descriptor returns ``EBADF``. Closing a socket follows the regular-file POSIX lock release rules. OFD locks remain until the final reference is released." + +msgid "sysfs 已公开的 block、PCI 和 DRM 设备 ``uevent`` 控制由 kernel UID 0 所有,模式为 0644,权限检查沿用现有 DAC 与 kernel UID 语义。支持 ``O_TRUNC`` 的零长度截断,截断本身不发布事件。写入直接提交事件,action 与可选 UUID 的格式同网络 ``uevent``,见 :doc:`ipv6`。非法输入、只读挂载或权限检查失败均不发布事件。" +msgstr "Sysfs exposes writable ``uevent`` controls for its published block, PCI and DRM devices, owned by kernel UID 0 with mode 0644. Permission checks follow existing DAC and kernel UID semantics. Zero-length truncation for ``O_TRUNC`` is supported and emits no event. Writes commit events immediately. The action and optional UUID use the same format as network ``uevent`` controls, described in :doc:`ipv6`. Invalid input, a readonly mount or a failed permission check emits no event." + +msgid "timerfd 时钟" +msgstr "timerfd clocks" + +msgid "``timerfd_create()`` 支持 ``CLOCK_REALTIME``、``CLOCK_MONOTONIC`` 和 ``CLOCK_BOOTTIME``,接受 ``TFD_CLOEXEC`` 与 ``TFD_NONBLOCK``。绝对截止时间 按创建时选定的时钟解释,周期到期累计可读次数。``timerfd_settime()`` 的 ``it_value`` 为零时解除定时器,包括 ``TFD_TIMER_ABSTIME`` 模式。" +msgstr "``timerfd_create()`` supports ``CLOCK_REALTIME``, ``CLOCK_MONOTONIC`` and ``CLOCK_BOOTTIME`` with ``TFD_CLOEXEC`` and ``TFD_NONBLOCK``. Absolute deadlines use the clock selected at creation, and periodic expirations accumulate the readable count. A zero ``it_value`` in ``timerfd_settime()`` disarms the timer, including in ``TFD_TIMER_ABSTIME`` mode." + +msgid "``CLOCK_BOOTTIME`` 使用现有启动时间时钟,当前与单调时钟共用计时来源。 官方 systemd 的 DHCP 重传定时器通过该接口运行。" +msgstr "``CLOCK_BOOTTIME`` uses the existing boot-time clock, which currently shares its time source with the monotonic clock. Official systemd DHCP retransmission timers use this interface." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po index 74c4db61..24476fc0 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po @@ -21,13 +21,13 @@ msgstr "Interfaces and Packets" msgid "" "IPv6 与 IPv4 共用描述符、等待队列、权限和网络执行上下文。应用使用 Linux x86-64 socket ABI 和 POSIX socket 调用,不需要 ReliefNT 私有 " -"IPv6 调用。 ``AF_INET6`` 为 10,``sockaddr_in6`` 大小为 28 字节;地址和端口为网络字节序, ``sin6_scope_id`` 是接口索引。当前 " -"``lo`` 为 1,``eth0`` 为 2。 链路本地地址需要正确的区域标识。" +"IPv6 调用。 ``AF_INET6`` 为 10,``sockaddr_in6`` 大小为 28 字节;地址和端口为网络字节序, ``sin6_scope_id`` 是接口索引。默认 " +"``lo`` 为 1,首个物理接口 ``eth0`` 为 2。 链路本地地址需要正确的区域标识。" msgstr "" "IPv6 shares descriptors, wait queues, permissions, and the network execution context with IPv4. " "Applications use the Linux x86-64 socket ABI and POSIX socket calls, without private ReliefNT IPv6" " calls. ``AF_INET6`` is 10 and ``sockaddr_in6`` is 28 bytes; addresses and ports use network byte " -"order, and ``sin6_scope_id`` is the interface index. Currently ``lo`` is 1 and ``eth0`` is 2. " +"order, and ``sin6_scope_id`` is the interface index. By default ``lo`` is 1 and the first physical interface ``eth0`` is 2. " "Link-local addresses require the correct scope identifier." msgid "" @@ -60,8 +60,11 @@ msgstr "Configuration and Observation" msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。" msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 addresses and routes in the network scope retained when the socket was created, including after FD transfer. Changes require ``CAP_NET_ADMIN`` in the network owner's user namespace. ``getifaddrs()`` obtains that scope's IPv6 addresses through standard queries. IPv6 address and route ioctls use the selected network's state and owner authority, with layouts selected by socket family. Interface ioctls on UDP, TCP, raw and AF_PACKET sockets, and address and route ioctls on IPv6 sockets, all use the creating network." -msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" -msgstr "Route multicast supports link, IPv6 address and IPv6 route groups. IPv4 address and route multicast remain unimplemented, and subscriptions to those groups return ``EOPNOTSUPP``. Each network namespace maintains its own subscription snapshots, published after all captures succeed and released when its final subscriber closes or unsubscribes. Change notifications and overruns are delivered by network scope. Receive queue overflow reports ``ENOBUFS``, and callers should query again." +msgid "路由多播发布链路、IPv4/IPv6 地址和路由的新增、变更与删除。IPv4 路由包含直连、默认及显式路由,metric 替换发布旧路由删除和新路由添加。接口删除时,地址通知保留原接口名称与地址。每个网络空间独立维护订阅快照,全部捕获成功后替换,最后一个订阅关闭或退订时释放。快照捕获失败保留旧基线并报告 overrun,后续变更重新捕获。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" +msgstr "Route multicast publishes link, IPv4/IPv6 address and route additions, changes and deletions. IPv4 routes include connected, default and explicit routes. Replacing a metric publishes deletion of the old route and addition of the new one. Address notifications retain the original interface name and address after interface deletion. Each network namespace maintains its own subscription snapshots, replaced after all captures succeed and released when its final subscriber closes or unsubscribes. Capture failure preserves the old baseline and reports an overrun, with capture retried on a subsequent change. Change notifications and overruns follow the network scope. Receive queue overflow reports ``ENOBUFS``, and callers should query again." + +msgid "路由 socket 接受 Linux 6.12 的标准组编号 1 至 36,支持 networkd 和 resolved 的订阅组合。实际事件由对应子系统提供,具体请求仍按其实现能力校验。``sockaddr_nl.nl_groups`` 表示低 32 位,``NETLINK_ADD_MEMBERSHIP`` 和 ``NETLINK_DROP_MEMBERSHIP`` 按组编号操作。初始化后的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 8 字节位图,短缓冲区复制可容纳的完整 32 位字并报告完整所需长度;uevent 位图长度为 4 字节。" +msgstr "Route sockets accept standard Linux 6.12 group numbers 1 through 36, supporting the subscription combinations used by networkd and resolved. The corresponding subsystems supply events, and individual requests are validated against their implemented capabilities. ``sockaddr_nl.nl_groups`` represents the low 32 bits. ``NETLINK_ADD_MEMBERSHIP`` and ``NETLINK_DROP_MEMBERSHIP`` operate on group numbers. After initialization, ``NETLINK_LIST_MEMBERSHIPS`` returns an 8-byte bitmap. Short buffers receive the complete 32-bit words that fit and report the full required length. The uevent bitmap is 4 bytes long." msgid "" "多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 " @@ -139,3 +142,120 @@ msgstr "" "alignment padding. A successful send returns the entire datagram length, including the " "ignored tail. A datagram with no valid messages generates no replies. Prescanning and " "processing use the same prefix boundary." + +msgid "IPv4 选项与 UDP 消息" +msgstr "IPv4 Options and UDP Messages" + +msgid "UDP 和 TCP 的 IPv4 及 IPv4 映射通信支持 ``SOL_IP`` 的 ``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL`` 和 ``IP_MTU_DISCOVER``。TTL 默认 64,接受 1 至 255,设置 -1 恢复默认值。接收辅助信息选项默认关闭。MTU discovery 默认 ``IP_PMTUDISC_WANT``,接受从 ``IP_PMTUDISC_DONT`` 到 ``IP_PMTUDISC_OMIT`` 的 0 至 5。当前 IPv4 输出仅在 ``DO`` 或 ``PROBE`` 时设置 DF,其余模式清除 DF。这些模式的设置与查询支持有上述报文效果,完整 IPv4 PMTU 探测与分片仍有实现边界。" +msgstr "IPv4 and IPv4-mapped communication on UDP and TCP supports the ``SOL_IP`` options ``IP_TTL``, ``IP_PKTINFO``, ``IP_RECVTTL`` and ``IP_MTU_DISCOVER``. TTL defaults to 64, accepts 1 through 255, and resets to the default with -1. Receive ancillary information options default to disabled. MTU discovery defaults to ``IP_PMTUDISC_WANT`` and accepts values 0 through 5, from ``IP_PMTUDISC_DONT`` to ``IP_PMTUDISC_OMIT``. Current IPv4 output sets DF only for ``DO`` or ``PROBE`` and clears it for the other modes. Setting and querying these modes has the packet effects described here. Full IPv4 PMTU discovery and fragmentation remain subject to implementation limits." + +msgid "TCP 被动建立的子连接继承上述四项 IPv4 选项,IPv6 hop limit 与 PMTU 配置独立保存。TCP 上的 ``IP_PKTINFO`` 和 ``IP_RECVTTL`` 保存配置并由子连接继承,接收辅助数据由 UDP 路径提供。" +msgstr "Passively established TCP child connections inherit all four IPv4 options. IPv6 hop limit and PMTU configuration are stored independently. On TCP, ``IP_PKTINFO`` and ``IP_RECVTTL`` retain configuration that child connections inherit. Receive ancillary data is provided by the UDP path." + +msgid "UDP IPv4 多播提供 ``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL`` 及 ``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP``。接口选择支持 ``in_addr``、``ip_mreq`` 和 ``ip_mreqn``,成员操作支持后两种布局。多播 TTL 默认 1,-1 恢复默认值,0 仅本地投递。loop 和 all 默认开启。接收按创建网络、组地址、入站接口、端口和已连接对端筛选,并向所有匹配的 socket 投递。``IP_MULTICAST_ALL=1`` 可使用同网络其他 socket 的组成员资格,设置 0 后仅使用本 socket 成员资格。" +msgstr "UDP IPv4 multicast provides ``IP_MULTICAST_IF``, ``IP_MULTICAST_TTL``, ``IP_MULTICAST_LOOP``, ``IP_MULTICAST_ALL`` and ``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP``. Interface selection accepts ``in_addr``, ``ip_mreq`` and ``ip_mreqn``, and membership operations accept the latter two layouts. Multicast TTL defaults to 1, resets with -1, and limits delivery to the local host with 0. Loop and all default to enabled. Reception filters by creating network, group address, ingress interface, port and connected peer, delivering to all matching sockets. ``IP_MULTICAST_ALL=1`` can use group memberships of other sockets in the same network. With 0, only the receiving socket's memberships apply." + +msgid "多播发送在创建网络中选择路由和源地址,以太网目的地址使用 ``01:00:5e`` 加组地址低 23 位的映射。TTL 为 0 或选择 loopback 时仅按 loop 设置进行本地投递。非初始网络的发送受其可见接口限制。当前成员资格用于本地接收筛选,尚未实现 IGMP 报告与查询,启用 IGMP snooping 的网络可能需要额外配置才能转发流量。" +msgstr "Multicast transmission selects routes and source addresses in the creating network. Ethernet destination addresses use ``01:00:5e`` followed by the low 23 bits of the group address. A TTL of 0 or selection of loopback limits delivery to the local host according to the loop setting. Transmission from noninitial networks is limited to their visible interfaces. Memberships currently provide local receive filtering. IGMP reports and queries remain unimplemented, and networks with IGMP snooping may require additional configuration to forward traffic." + +msgid "UDP ``recvmsg()`` 在启用 IPv4 选项后通过 ``SOL_IP/IP_PKTINFO`` 和 ``SOL_IP/IP_TTL`` 返回实际入站接口、目的地址和 TTL,IPv4 映射报文也使用该布局。``in_pktinfo.ipi_addr`` 为报文目的地址,``ipi_spec_dst`` 为接收接口的本地 IPv4 地址,``ipi_ifindex`` 为入站接口索引。原生 IPv6 使用 ``IPV6_PKTINFO`` 和 hop-limit 辅助数据。控制缓冲区不足设置 ``MSG_CTRUNC``,载荷截断设置 ``MSG_TRUNC``,支持 ``MSG_PEEK``。向量 I/O 保持单个 UDP 数据报的边界。" +msgstr "With IPv4 options enabled, UDP ``recvmsg()`` returns the actual ingress interface, destination address and TTL through ``SOL_IP/IP_PKTINFO`` and ``SOL_IP/IP_TTL``. IPv4-mapped packets use the same layout. ``in_pktinfo.ipi_addr`` is the packet destination, ``ipi_spec_dst`` is the receiving interface's local IPv4 address, and ``ipi_ifindex`` is the ingress interface index. Native IPv6 uses ``IPV6_PKTINFO`` and hop-limit ancillary data. Insufficient control space sets ``MSG_CTRUNC`` and payload truncation sets ``MSG_TRUNC``. ``MSG_PEEK`` is supported. Vector I/O preserves a single UDP datagram boundary." + +msgid "UDP ``sendmsg()`` 可用 ``SOL_IP/IP_PKTINFO`` 的 ``ipi_ifindex`` 与 ``ipi_spec_dst`` 为单条消息选择接口和源地址,用 ``SOL_IP/IP_TTL`` 设置 1 至 255 的 TTL。IPv6 socket 还支持 ``IPV6_PKTINFO`` 与 hop-limit 辅助数据。发送前导入并校验控制信息,消息覆盖值不改变持久选项,接口和源地址仍受创建网络及 ``SO_BINDTODEVICE`` 约束。" +msgstr "UDP ``sendmsg()`` can select an interface and source address for one message using ``ipi_ifindex`` and ``ipi_spec_dst`` in ``SOL_IP/IP_PKTINFO``, and a TTL from 1 through 255 using ``SOL_IP/IP_TTL``. IPv6 sockets also support ``IPV6_PKTINFO`` and hop-limit ancillary data. Control information is imported and validated before transmission. Per-message overrides preserve persistent options, and interface and source selection remain constrained by the creating network and ``SO_BINDTODEVICE``." + +msgid "``NETLINK_GENERIC`` 提供标准控制族 ``nlctrl``,family ID 为 16,版本为 2。``CTRL_CMD_GETFAMILY`` 支持按 ``CTRL_ATTR_FAMILY_NAME`` 或 ``CTRL_ATTR_FAMILY_ID`` 查询,同时提供时优先名称。dump 返回已注册族及独立的 ``NLMSG_DONE``,回复公布查询操作和 ``notify`` 组 16。未知族通过 ``NLMSG_ERROR`` 返回 ``ENOENT``,未实现的控制命令返回 ``EOPNOTSUPP``。当前注册族仅有 ``nlctrl``,无线 ``nl80211`` 族尚未提供。socket 保留创建网络并复用端口、队列、ACK 和错误处理语义。" +msgstr "``NETLINK_GENERIC`` provides the standard ``nlctrl`` controller family with family ID 16 and version 2. ``CTRL_CMD_GETFAMILY`` looks up ``CTRL_ATTR_FAMILY_NAME`` or ``CTRL_ATTR_FAMILY_ID``, preferring the name when both are supplied. Dumps return registered families and a separate ``NLMSG_DONE``. Replies advertise the query operation and ``notify`` group 16. Unknown families return ``ENOENT`` through ``NLMSG_ERROR``, and unimplemented controller commands return ``EOPNOTSUPP``. The currently registered family is ``nlctrl`` alone. The wireless ``nl80211`` family remains unavailable. Sockets retain their creating network and reuse port, queue, ACK and error-handling semantics." + +msgid "IPv4 地址的 ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知投递到 ``RTNLGRP_IPV4_IFADDR``,IPv4 路由的 ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` 通知投递到 ``RTNLGRP_IPV4_ROUTE``。订阅与通知均沿用 socket 创建网络。" +msgstr "IPv4 address ``RTM_NEWADDR`` / ``RTM_DELADDR`` notifications go to ``RTNLGRP_IPV4_IFADDR``, and IPv4 route ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` notifications go to ``RTNLGRP_IPV4_ROUTE``. Subscriptions and notifications both follow the socket's creating network." + +msgid "``NETLINK_GENERIC`` 的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 4 字节位图,控制族 ``notify`` 使用组 16。" +msgstr "``NETLINK_LIST_MEMBERSHIPS`` on ``NETLINK_GENERIC`` returns a 4-byte bitmap. The controller's ``notify`` group uses group 16." + +msgid "TCP IPv6 socket 支持 ``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` 的独立状态,默认关闭,任意非零设置值查询为 1,零查询为 0。原生 IPv6 和 IPv4 映射的被动子连接继承这两项,建立后各自保存状态。TCP 保存这些接收配置,当前 ``recvmsg()`` 仅交付流数据,UDP 提供上述接收辅助数据。" +msgstr "TCP IPv6 sockets support independent ``IPV6_RECVPKTINFO`` and ``IPV6_RECVHOPLIMIT`` state, disabled by default. Any nonzero setting reads back as 1, and zero reads back as 0. Native IPv6 and IPv4-mapped passive child connections inherit both options and retain independent state after creation. TCP stores these receive settings, and its current ``recvmsg()`` delivers stream data only. UDP provides the receive ancillary data described above." + +msgid "``RTM_GETNEIGH`` dump 从 socket 创建网络的 ARP 和 NDP 快照输出邻居,支持 ``AF_UNSPEC``、``AF_INET``、``AF_INET6`` 及接口索引筛选。IPv4 的 ``NDA_DST`` 转为网络字节序,缓存地址映射以 ``NUD_STALE`` 表示,IPv6 保留现有 NUD 状态。回复包含接口、目的地址及可用的链路层地址。``AF_BRIDGE`` 和 ``NTF_PROXY`` 查询返回空表及 ``NLMSG_DONE``,邻居新增、修改和删除请求返回 ``EOPNOTSUPP``。" +msgstr "``RTM_GETNEIGH`` dumps render neighbors from ARP and NDP snapshots in the socket's creating network, supporting ``AF_UNSPEC``, ``AF_INET``, ``AF_INET6`` and interface-index filtering. IPv4 ``NDA_DST`` is converted to network byte order. Cached address mappings use ``NUD_STALE``, and IPv6 retains the existing NUD state. Replies include the interface, destination address and available link-layer address. ``AF_BRIDGE`` and ``NTF_PROXY`` queries return an empty table and ``NLMSG_DONE``. Requests to add, modify or delete neighbors return ``EOPNOTSUPP``." + +msgid "``AF_BRIDGE`` 的 ``RTM_GETLINK`` dump 返回空表及 ``NLMSG_DONE``。" +msgstr "``RTM_GETLINK`` dumps for ``AF_BRIDGE`` return an empty table and ``NLMSG_DONE``." + +msgid "独立单路径 nexthop 按 socket 创建网络保存。``RTM_NEWNEXTHOP`` 和 ``RTM_DELNEXTHOP`` 按非零 ``NHA_ID`` 创建、替换或删除 IPv4/IPv6 对象,支持 ``NHA_OIF``、``NHA_GATEWAY`` 和 ``RTNH_F_ONLINK``。``RTM_GETNEXTHOP`` 支持按 ID 查询,以及按地址族、ID 和接口筛选的 dump,dump 以 ``NLMSG_DONE`` 结束。路由通过 ``RTA_NH_ID`` 引用同网络、同地址族的对象。替换对象同步更新依赖路由,删除对象或接口同时删除依赖路由,网络销毁释放全部对象。分配失败保留对象和路由状态。nexthop group、blackhole 和封装请求返回 ``EOPNOTSUPP``。" +msgstr "Standalone single-path nexthops belong to the socket's creating network. ``RTM_NEWNEXTHOP`` and ``RTM_DELNEXTHOP`` create, replace or delete IPv4/IPv6 objects by nonzero ``NHA_ID``, supporting ``NHA_OIF``, ``NHA_GATEWAY`` and ``RTNH_F_ONLINK``. ``RTM_GETNEXTHOP`` supports lookup by ID and dumps filtered by address family, ID and interface, ending each dump with ``NLMSG_DONE``. Routes use ``RTA_NH_ID`` to reference objects in the same network and address family. Replacement updates dependent routes, deleting an object or interface also deletes dependent routes, and network destruction releases all objects. Allocation failure preserves object and route state. Nexthop group, blackhole and encapsulation requests return ``EOPNOTSUPP``." + +msgid "TCP 开放文件描述的最后一个引用关闭时,未连接的绑定端点及 listener 立即释放端口、缓冲区和创建网络引用,服务可立即重新绑定监听地址。已有关联对端的端点继续按协议状态回收,排队数据、FIN 和 TIME_WAIT 保留各自的生命周期。" +msgstr "When a TCP open file description is finally closed, an unconnected bound endpoint or listener immediately releases its port, buffers and creating-network reference, allowing services to rebind their listening address immediately. Endpoints with an associated peer continue to be collected according to protocol state. Queued data, FIN and TIME_WAIT retain their respective lifetimes." + +msgid "``SOL_SOCKET`` 的 ``SO_BINDTODEVICE`` 在 socket 创建网络中按名称查找设备,空名称解除绑定。``SO_BINDTOIFINDEX`` 的编号为 62,按 ``int`` 接口索引设置或查询同一绑定。正索引允许对应尚不存在或已删除的设备,负值返回 ``EINVAL``,0 解除绑定。两者的绑定均属于 socket 创建网络,任务切换网络或传递 FD 后继续使用该网络。当前已有非零绑定时,修改绑定或解绑需要创建网络 user owner 的 ``CAP_NET_RAW``。" +msgstr "At ``SOL_SOCKET``, ``SO_BINDTODEVICE`` looks up a device by name in the socket's creating network. An empty name clears the binding. ``SO_BINDTOIFINDEX``, numbered 62, sets or queries the same binding with an ``int`` interface index. Positive indices may refer to devices that do not yet exist or have been removed. Negative values return ``EINVAL``, and 0 clears the binding. Both bindings belong to the socket's creating network, which remains in use across task network changes and FD passing. Changing or clearing a currently nonzero binding requires ``CAP_NET_RAW`` in the creating network's user owner." + +msgid "IPv4 地址查询和新增、删除通知携带 ``ifaddrmsg.ifa_flags``、32 位 ``IFA_FLAGS``、scope、``IFA_CACHEINFO`` 及可选的 ``IFA_RT_PRIORITY``。每个接口保存一个主 IPv4 地址,支持 ``IFA_F_PERMANENT``、``IFA_F_DEPRECATED`` 和 ``IFA_F_NOPREFIXROUTE``。有限有效期清除 PERMANENT,首选期到期设置 DEPRECATED,有效期到期删除地址。NOPREFIXROUTE 抑制自动前缀路由,IFA_RT_PRIORITY 设置其 metric。省略有效期时地址永久有效。" +msgstr "IPv4 address queries and addition and deletion notifications carry ``ifaddrmsg.ifa_flags``, 32-bit ``IFA_FLAGS``, scope, ``IFA_CACHEINFO`` and optional ``IFA_RT_PRIORITY``. Each interface retains one primary IPv4 address, supporting ``IFA_F_PERMANENT``, ``IFA_F_DEPRECATED`` and ``IFA_F_NOPREFIXROUTE``. A finite valid lifetime clears PERMANENT, preferred-lifetime expiry sets DEPRECATED, and valid-lifetime expiry deletes the address. NOPREFIXROUTE suppresses the automatic prefix route, and IFA_RT_PRIORITY sets its metric. Omitting lifetimes makes the address permanent." + +msgid "IPv6 地址使用相同的租期和前缀 metric 属性,支持 NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE 和 MANAGETEMPADDR。MANAGETEMPADDR 要求 /64 前缀并保存配置标志,临时隐私地址的自动生成仍待实现。自动前缀路由随地址、metric、标志和有效期维护,同时保留同前缀的其他有效地址及 RA 路由贡献。" +msgstr "IPv6 addresses use the same lifetime and prefix-metric attributes and support NODAD, PERMANENT, DEPRECATED, NOPREFIXROUTE and MANAGETEMPADDR. MANAGETEMPADDR requires a /64 prefix and retains the configuration flag. Automatic generation of temporary privacy addresses remains pending. Automatic prefix routes track addresses, metrics, flags and lifetimes while preserving contributions from other valid addresses with the same prefix and from RA routes." + +msgid "IPv4/IPv6 的 ``RTM_NEWADDR`` 允许仅携带 ``NLM_F_REPLACE`` 创建地址。已有地址遇 ``NLM_F_EXCL`` 或缺少 REPLACE 时返回 ``EEXIST``,校验失败保留原配置。``RTM_NEWROUTE`` 接受 ``NLM_F_APPEND``,新增路由保留同优先级存活路由的插入顺序。修改请求的 ``NLM_F_ECHO`` 和其他修改消息上的 APPEND 返回 ``EOPNOTSUPP``。" +msgstr "IPv4/IPv6 ``RTM_NEWADDR`` permits address creation with ``NLM_F_REPLACE`` alone. An existing address returns ``EEXIST`` with ``NLM_F_EXCL`` or without REPLACE. Validation failure preserves the configuration. ``RTM_NEWROUTE`` accepts ``NLM_F_APPEND``, and new routes preserve insertion order among surviving routes with equal priority. ``NLM_F_ECHO`` on mutation requests and APPEND on other mutation messages return ``EOPNOTSUPP``." + +msgid "IPv4/IPv6 路由支持 ``RTA_PREFSRC`` 及 ``RTNH_F_ONLINK``,首选源地址须已配置在同网络。IPv6 还支持 ``RTA_PREF`` 的低、中、高优先级与 ``RTA_EXPIRES`` 秒级有效期,到期发布删除通知。IPv6 路由身份包含目的前缀、接口、网关、nexthop ID 和 metric,同路径不同 metric 可共存。选路依次比较最长前缀、较低 metric 和较高 preference,完全相同时保留先插入路由。REPLACE 更新匹配条目,目标缺失且未携带 CREATE 时返回 ``ESRCH``。" +msgstr "IPv4/IPv6 routes support ``RTA_PREFSRC`` and ``RTNH_F_ONLINK``. Preferred source addresses must be configured in the same network. IPv6 also supports low, medium and high ``RTA_PREF`` preference and ``RTA_EXPIRES`` lifetimes in seconds, publishing deletion notifications on expiry. IPv6 route identity includes the destination prefix, interface, gateway, nexthop ID and metric, allowing different metrics on the same path. Selection compares longest prefix, lower metric and higher preference in that order, retaining the earlier route on a complete tie. REPLACE updates a matching entry and returns ``ESRCH`` when the target is absent and CREATE is omitted." + +msgid "网络 sysfs 与设备事件" +msgstr "Network sysfs and Device Events" + +msgid "sysfs 挂载保留创建时捕获的网络空间,后续 lookup、readdir、read 和 write 均使用该视图。任务执行 ``setns()``、``unshare()`` 或传递挂载句柄后,已有挂载继续观察原网络。``fsopen(\"sysfs\")`` 的网络与 owner 捕获及 CREATE 授权见 :doc:`abi`。" +msgstr "A sysfs mount retains the network namespace captured at creation. Subsequent lookup, readdir, read and write operations use that view. Existing mounts continue to observe the original network after a task calls ``setns()`` or ``unshare()`` or passes a mount handle. See :doc:`abi` for network and owner capture by ``fsopen(\"sysfs\")`` and CREATE authorization." + +msgid "``/sys/class/net/`` 是指向 canonical 设备节点的符号链接。loopback 位于 ``/sys/devices/virtual/net/lo``,物理接口位于对应 PCI function 下的 ``net/``,``device`` 链接指向 PCI 父节点,``subsystem`` 链接指向 ``/sys/class/net``。属性包含 ``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier`` 和 ``uevent``。物理接口仅在初始网络中可见。接口移除后,持有的旧 inode 在重新打开、读取或写入时返回 ``ENOENT``。" +msgstr "``/sys/class/net/`` is a symbolic link to the canonical device node. Loopback resides at ``/sys/devices/virtual/net/lo``. A physical interface resides at ``net/`` below its PCI function, with ``device`` linking to the PCI parent and ``subsystem`` linking to ``/sys/class/net``. Attributes include ``ifindex``, ``iflink``, ``address``, ``broadcast``, ``type``, ``mtu``, ``flags``, ``operstate``, ``carrier`` and ``uevent``. Physical interfaces are visible only in the initial network. After interface removal, reopening, reading or writing a retained old inode returns ``ENOENT``." + +msgid "网络 ``uevent`` 文件由 root 所有,模式为 0644,写入遵循常规 DAC 与挂载只读策略。只读挂载也阻止 root 写入。读取提供 ``INTERFACE`` 和 ``IFINDEX``。写入接受 ``add``、``remove``、``change``、``move``、``online``、``offline``、``bind`` 或 ``unbind``,可在一个空格后附加 36 字符的十六进制 UUID,连字符位于标准位置,末尾可带一个换行。无 UUID 时事件使用 ``SYNTH_UUID=0``,提供 UUID 时按输入传递。无效 action、UUID 或 embedded NUL 返回 ``EINVAL``,并保持事件队列不变。" +msgstr "Network ``uevent`` files are root-owned with mode 0644. Writes follow normal DAC and mount readonly policy. Readonly mounts also prevent root writes. Reads provide ``INTERFACE`` and ``IFINDEX``. Writes accept ``add``, ``remove``, ``change``, ``move``, ``online``, ``offline``, ``bind`` or ``unbind``, optionally followed by one space and a 36-character hexadecimal UUID with hyphens in the standard positions. One trailing newline is allowed. Events without a UUID use ``SYNTH_UUID=0``. A supplied UUID is passed through as entered. An invalid action, UUID or embedded NUL returns ``EINVAL`` and preserves the event queue." + +msgid "``NETLINK_KOBJECT_UEVENT`` 的网络设备事件按订阅 socket 的创建网络筛选。物理接口注册和移除分别发布 ``add`` 和 ``remove``,移除事件保留注册时的设备身份。sysfs 合成事件使用挂载捕获的网络,事件携带 action、设备路径、``SUBSYSTEM=net``、``INTERFACE`` 和 ``IFINDEX``,合成事件还携带 ``SYNTH_UUID``。其他网络的订阅者不会收到该网络事件,任务随后切换网络也保留已有 socket 的订阅范围。" +msgstr "Network device events on ``NETLINK_KOBJECT_UEVENT`` are filtered by each subscribing socket's creating network. Physical interface registration and removal publish ``add`` and ``remove`` respectively. Removal events preserve the device identity captured at registration. Synthetic sysfs events use the network captured by the mount. Events carry the action, device path, ``SUBSYSTEM=net``, ``INTERFACE`` and ``IFINDEX``, with synthetic events also carrying ``SYNTH_UUID``. Subscribers in other networks receive no such network event. Subsequent task network changes preserve the subscription scope of existing sockets." + +msgid "block、PCI 和 DRM 已公开的设备 ``uevent`` 控制同样接受上述 action 与可选 UUID,权限和即时写入语义见 :doc:`abi`。事件属性取自同一设备的当前真实 inventory,``SUBSYSTEM`` 取自该设备的 ``subsystem`` 链接,并附带 ``SYNTH_UUID``。这些 global 设备事件仅投递给初始 user namespace 所拥有的网络空间中的订阅者,包含永久初始网络。网络设备事件继续严格按 socket 创建网络与挂载捕获网络隔离。" +msgstr "The published ``uevent`` controls for block, PCI and DRM devices accept the same actions and optional UUID. See :doc:`abi` for permissions and immediate-write semantics. Event properties come from the current real inventory of the same device. ``SUBSYSTEM`` comes from that device's ``subsystem`` link, and ``SYNTH_UUID`` is appended. These global device events reach subscribers only in network namespaces owned by the initial user namespace, including the permanent initial network. Network device events retain strict isolation by the socket's creating network and the mount's captured network." + +msgid "``RTM_SETLINK`` 与 ``RTM_NEWLINK`` 在提供正接口索引和 ``IFLA_IFNAME`` 时执行重命名,索引为 0 时按名称选择已有接口。``SIOCSIFNAME`` 使用相同的创建网络与 ``CAP_NET_ADMIN`` 授权。重命名保留接口索引和 UP 状态,更新 ioctl、socket 设备绑定查询及 sysfs 名称,并发布同网络的 ``RTM_NEWLINK`` 与携带 ``DEVPATH_OLD`` 的 ``move`` 事件。名称最长 15 字节,空白、斜线、冒号、``.`` 和 ``..`` 返回 ``EINVAL``,同网络名称冲突返回 ``EEXIST``。单个 ``%d`` 模板选择 0 至 32767 内首个空闲编号,同名请求不发布事件。``name_assign_type`` 对枚举物理名称报告 1,重命名后报告 4。" +msgstr "``RTM_SETLINK`` and ``RTM_NEWLINK`` rename an interface when given a positive interface index and ``IFLA_IFNAME``. An index of 0 selects an existing interface by name. ``SIOCSIFNAME`` uses the same creating-network scope and ``CAP_NET_ADMIN`` authorization. Renaming preserves the interface index and UP state, updates ioctl, socket device-binding queries and sysfs names, and publishes a same-network ``RTM_NEWLINK`` and a ``move`` event carrying ``DEVPATH_OLD``. Names contain at most 15 bytes. Whitespace, slash, colon, ``.`` and ``..`` return ``EINVAL``, and a name collision in the same network returns ``EEXIST``. A single ``%d`` template selects the first free unit from 0 through 32767. A same-name request publishes no event. ``name_assign_type`` reports 1 for enumerated physical names and 4 after a rename." + +msgid "packet socket 与链路接收" +msgstr "Packet sockets and link reception" + +msgid "``AF_PACKET`` 的 ``SO_ATTACH_FILTER`` 与 ``SO_DETACH_FILTER`` 复用 classic BPF 校验和执行器。过滤结果为 0 时丢弃报文,正值限制保留长度。替换失败保留旧过滤器。``bind()`` 的零 ``sll_protocol`` 保留创建时选择的协议。" +msgstr "``SO_ATTACH_FILTER`` and ``SO_DETACH_FILTER`` on ``AF_PACKET`` use the classic BPF validator and interpreter. A zero result drops the frame, and a positive result limits its retained length. Failed replacement preserves the previous filter. A zero ``sll_protocol`` in ``bind()`` retains the protocol selected at creation." + +msgid "``SOL_PACKET`` 的 ``PACKET_ADD_MEMBERSHIP`` 与 ``PACKET_DROP_MEMBERSHIP`` 支持按创建网络、接口及六字节地址管理 ``PACKET_MR_MULTICAST``,重复加入按引用计数回收。最后关闭或设备移除释放订阅。额外链路组播按同网络、同接口的订阅执行软件接收筛选。当前其他成员类型返回 ``EINVAL``。" +msgstr "At ``SOL_PACKET``, ``PACKET_ADD_MEMBERSHIP`` and ``PACKET_DROP_MEMBERSHIP`` manage ``PACKET_MR_MULTICAST`` by creating network, interface and six-byte address. Duplicate joins are reference counted. Final close and device removal release subscriptions. Additional link multicast is admitted in software using subscriptions in the same network and interface. Other membership types currently return ``EINVAL``." + +msgid "``PACKET_AUXDATA`` 在 ``recvmsg()`` 返回 ``tpacket_auxdata``,包括过滤前长度、保留长度及链路偏移。RAW 报文的网络偏移为 14,DGRAM 为 0。``SO_TIMESTAMP_OLD`` 与 ``SO_TIMESTAMP_NEW`` 提供 realtime 微秒时间戳,排队时采样,接收前才启用时延迟采样,重复 ``MSG_PEEK`` 保留同一样本。输出内存准备失败保留队列,控制缓冲区不足设置 ``MSG_CTRUNC``。" +msgstr "``PACKET_AUXDATA`` returns ``tpacket_auxdata`` through ``recvmsg()``, including the pre-filter length, retained length and link offsets. The network offset is 14 for RAW frames and 0 for DGRAM frames. ``SO_TIMESTAMP_OLD`` and ``SO_TIMESTAMP_NEW`` provide realtime microsecond timestamps sampled at enqueue, or lazily when enabled after arrival. Repeated ``MSG_PEEK`` retains the same sample. Output-memory preparation failure preserves the queue, and insufficient control space sets ``MSG_CTRUNC``." + +msgid "UDP 和 packet socket 的 ``SO_PRIORITY`` 保存有符号整数优先级,默认 0。0 至 6 可直接设置,其他值需要 socket 创建网络 user owner 的 ``CAP_NET_RAW`` 或 ``CAP_NET_ADMIN``。用户内存或权限检查失败保留原值。" +msgstr "``SO_PRIORITY`` on UDP and packet sockets stores a signed integer priority, initially 0. Values from 0 through 6 can be set directly. Other values require ``CAP_NET_RAW`` or ``CAP_NET_ADMIN`` in the user owner of the socket creation network. Failed user-memory or permission checks preserve the previous value." + +msgid "UDP 的 ``IP_TOS`` 默认 0,保存输入低八位并写入实际 IPv4 首部,包含 DSCP 和 ECN 位。TOS 变化同时按 Linux 的 TOS 映射更新 socket 优先级。``IP_FREEBIND`` 默认关闭,开启后允许绑定尚未配置的 IPv4 地址及 IPv4 映射地址。端口冲突、设备绑定、特权端口授权和创建网络范围仍按原规则检查,发送继续要求有效路由。" +msgstr "UDP ``IP_TOS`` defaults to 0 and stores the low eight input bits in the actual IPv4 header, including DSCP and ECN. A TOS change also updates socket priority using the Linux TOS mapping. ``IP_FREEBIND`` defaults to disabled and permits binding unconfigured IPv4 and IPv4-mapped addresses when enabled. Port conflicts, device bindings, privileged-port authorization and the creating-network scope retain their checks. Sending still requires a valid route." + +msgid "UDP 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 返回 realtime 微秒时间戳,支持原生 IPv4、IPv6 和 IPv4 映射报文。启用时在入队采样,接收前才启用则在首次接收时采样。``MSG_PEEK`` 和切换时间戳格式保留已有样本,关闭选项后停止交付时间戳。时间戳通过 ``SOL_SOCKET`` 辅助消息返回,可与 IP packet info 和 TTL 同时使用。输出内存准备失败保留队列,控制区不足设置 ``MSG_CTRUNC``。" +msgstr "UDP ``SO_TIMESTAMP_OLD`` and ``SO_TIMESTAMP_NEW`` return realtime microsecond timestamps for native IPv4, IPv6 and IPv4-mapped datagrams. Enabled sockets sample at enqueue. Enabling after arrival samples at the first receive. ``MSG_PEEK`` and timestamp-format changes retain the sample. Disabling stops timestamp delivery. ``SOL_SOCKET`` ancillary messages carry timestamps alongside IP packet information and TTL. Output-memory preparation failure preserves the queue, and insufficient control space sets ``MSG_CTRUNC``." + +msgid "UDP 的 ``IP_UNICAST_IF`` 和 ``IPV6_UNICAST_IF`` 分别保存 IPv4 和 IPv6 的默认单播出口。设置与查询均使用网络字节序的 32 位接口索引,设置长度必须恰好为 4 字节。0 清除配置,非零索引必须存在于 socket 创建网络中,否则返回 ``EADDRNOTAVAIL``。已有设备绑定时设置非零索引返回 ``EINVAL``。普通用户可设置这些选项,接收筛选继续使用原有设备绑定。消息级接口、显式 scope 和设备绑定优先于默认单播出口;IPv4 映射发送使用 IPv4 配置。" +msgstr "UDP ``IP_UNICAST_IF`` and ``IPV6_UNICAST_IF`` retain separate default IPv4 and IPv6 unicast output interfaces. Setters and getters use a network-byte-order 32-bit interface index, and setters require exactly four bytes. Zero clears the setting. A nonzero index must exist in the socket's creating network, otherwise the setter returns ``EADDRNOTAVAIL``. Setting a nonzero index on a device-bound socket returns ``EINVAL``. Ordinary users can set these options. Receive filtering continues to use the existing device binding. Per-message interfaces, explicit scope and device binding take precedence over the default unicast interface. IPv4-mapped output uses the IPv4 setting." + +msgid "UDP 扩展错误队列" +msgstr "UDP Extended Error Queue" + +msgid "``IP_RECVERR`` 和 ``IPV6_RECVERR`` 默认关闭。启用后,经过校验的 IPv4 ICMP 或 ICMPv6 错误按 socket 创建网络、接口及原始 UDP 地址和端口关联到独立错误队列。记录保存 ``sock_extended_err`` 的 errno、origin、type、code 和 MTU,以及错误发送者、原始目的地址和被引用的 UDP 载荷。IPv4 映射 socket 返回原生 IPv6 地址布局。" +msgstr "``IP_RECVERR`` and ``IPV6_RECVERR`` default to disabled. When enabled, validated IPv4 ICMP and ICMPv6 errors are matched to an independent error queue using the socket's creating network, interface, and original UDP addresses and ports. Records retain the errno, origin, type, code and MTU in ``sock_extended_err``, the offender, original destination and quoted UDP payload. IPv4-mapped sockets return native IPv6 address layouts." + +msgid "``recvmsg(MSG_ERRQUEUE)`` 通过 ``msg_name`` 返回原始目的地址,通过 ``SOL_IP/IP_RECVERR`` 或 ``SOL_IPV6/IPV6_RECVERR`` 辅助消息返回扩展错误及其发送者,并设置输出 ``MSG_ERRQUEUE``。队列为空时立即返回 ``EAGAIN``,设置 ``MSG_PEEK`` 仍消费该条错误。载荷和控制区不足分别报告 ``MSG_TRUNC`` 和 ``MSG_CTRUNC``。用户输出内存准备失败保留记录,成功读取后按下一条错误更新待处理 errno。" +msgstr "``recvmsg(MSG_ERRQUEUE)`` returns the original destination in ``msg_name`` and the extended error and offender in a ``SOL_IP/IP_RECVERR`` or ``SOL_IPV6/IPV6_RECVERR`` control message, setting output ``MSG_ERRQUEUE``. An empty queue immediately returns ``EAGAIN``. ``MSG_PEEK`` still consumes the error record. Insufficient payload and control capacity report ``MSG_TRUNC`` and ``MSG_CTRUNC`` respectively. Failed user-output preparation preserves the record. Successful reads update the pending errno from the next error." + +msgid "错误记录与普通数据报分别持有存储,待处理 errno 或错误队列可触发 ``POLLERR``。查询 ``SO_ERROR`` 清除待处理 errno,已排队记录继续可读。关闭相应 RECVERR 选项会清空错误队列,保留普通数据和待处理 errno。分配失败或队列达到上限时保留已有记录并继续报告 socket 错误。最后关闭释放全部记录及创建网络引用。" +msgstr "Error records and ordinary datagrams own separate storage. A pending errno or queued error can trigger ``POLLERR``. Reading ``SO_ERROR`` clears the pending errno while queued records remain readable. Disabling the corresponding RECVERR option clears the error queue while retaining ordinary data and the pending errno. Allocation failure or a full queue preserves existing records and continues to report the socket error. Final close releases all records and the creating-network reference." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index d16b4598..422cc34b 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -328,18 +328,8 @@ msgstr "" "として保持し、CREATE にはその owner における ``CAP_SYS_ADMIN`` が必要です。ポリシーと再構成の意味は " ":doc:`procfs` を参照してください。" -msgid "" -"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 捕获当前网络空间的 user owner,并要求其 ``CAP_SYS_ADMIN``。传统 sysfs " -"mount 使用同一 owner。CREATE 再次检查捕获的 owner,调用者随后切换网络不会改变该权限作用域。sysfs 上下文接受通用 ``source``、``ro`` 和 " -"``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的 只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读 " -"属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" -msgstr "" -"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` は現在のネットワーク名前空間の user owner を保持し、その ``CAP_SYS_ADMIN`` " -"を要求します。従来の sysfs mount も同じ owner を使用します。CREATE は保持した owner " -"の権限を再確認します。その後ネットワークを切り替えても、この権限スコープは維持されます。sysfs コンテキストは汎用の ``source``、``ro``、``rw`` " -"パラメーターを受け付け、未知の固有オプションには ``EINVAL`` を返します。CREATE の読み取り専用設定は共有バックエンドに保持され、RECONFIGURE " -"で更新できます。``fsmount`` " -"の独立した読み取り専用属性は、そのマウントを引き続き制限します。メモリー割り当て、記述子の登録、作成に失敗した場合は候補の参照を解放し、再試行できます。" +msgid "``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 同时保留当前网络空间及其 user owner,并要求该 owner 的 ``CAP_SYS_ADMIN``。CREATE 再次检查捕获的 owner,并使用捕获的网络创建 sysfs 视图。上下文传递或调用者随后切换网络时,这两项捕获继续生效。传统 sysfs mount 同样使用挂载时的网络及其 owner。sysfs 上下文接受通用 ``source``、``ro`` 和 ``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" +msgstr "``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` は現在のネットワーク名前空間とその user owner の両方を保持し、その owner の ``CAP_SYS_ADMIN`` を要求します。CREATE は取得済み owner を再検査し、取得済みネットワーク内の sysfs ビューを作成します。コンテキストの受け渡しや呼び出し元のネットワーク切り替え後も、両方の取得内容を維持します。従来の sysfs mount もマウント時のネットワークとその owner を使用します。sysfs コンテキストは共通の ``source``、``ro``、``rw`` パラメーターを受け付けます。未知の固有オプションは ``EINVAL`` を返します。CREATE の読み取り専用設定は共有バックエンドに保持され、RECONFIGURE で更新できます。``fsmount`` による独立した読み取り専用属性は対応するマウントを引き続き制限します。割り当て、記述子の登録、作成に失敗した場合は候補の参照を解放し、再試行できます。" msgid "" "tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 " @@ -557,3 +547,15 @@ msgstr "" msgid "普通文件和 socket 均可使用这些锁命令。socket 按完整的匿名 inode 编号识别, 同一端点的别名共享冲突范围,不同端点的锁独立。socket 的 ``SEEK_END`` 基准 为零,``O_PATH`` 描述符返回 ``EBADF``。关闭 socket 的 POSIX 锁释放规则与 普通文件相同,OFD 锁持续到最后一个引用释放。" msgstr "通常ファイルと socket はこれらのロックコマンドを使用できます。socket は匿名 inode 番号全体で識別し、同じエンドポイントの別名は競合範囲を共有します。異なるエンドポイントのロックは独立します。socket の ``SEEK_END`` 基準はゼロで、``O_PATH`` 記述子は ``EBADF`` を返します。socket を閉じた際の POSIX ロック解放規則は通常ファイルと同じです。OFD ロックは最後の参照が解放されるまで保持されます。" + +msgid "sysfs 已公开的 block、PCI 和 DRM 设备 ``uevent`` 控制由 kernel UID 0 所有,模式为 0644,权限检查沿用现有 DAC 与 kernel UID 语义。支持 ``O_TRUNC`` 的零长度截断,截断本身不发布事件。写入直接提交事件,action 与可选 UUID 的格式同网络 ``uevent``,见 :doc:`ipv6`。非法输入、只读挂载或权限检查失败均不发布事件。" +msgstr "sysfs が公開する block、PCI、DRM デバイスの ``uevent`` 制御は kernel UID 0 が所有し、モードは 0644 です。権限検査には既存の DAC と kernel UID の意味論を適用します。``O_TRUNC`` の長さ 0 の切り詰めをサポートし、切り詰め自体はイベントを発行しません。書き込みはイベントを直ちにコミットします。action と任意の UUID の形式はネットワーク ``uevent`` と共通で、:doc:`ipv6` に記載されています。不正な入力、読み取り専用マウント、権限検査の失敗ではイベントを発行しません。" + +msgid "timerfd 时钟" +msgstr "timerfd のクロック" + +msgid "``timerfd_create()`` 支持 ``CLOCK_REALTIME``、``CLOCK_MONOTONIC`` 和 ``CLOCK_BOOTTIME``,接受 ``TFD_CLOEXEC`` 与 ``TFD_NONBLOCK``。绝对截止时间 按创建时选定的时钟解释,周期到期累计可读次数。``timerfd_settime()`` 的 ``it_value`` 为零时解除定时器,包括 ``TFD_TIMER_ABSTIME`` 模式。" +msgstr "``timerfd_create()`` は ``CLOCK_REALTIME``、``CLOCK_MONOTONIC``、``CLOCK_BOOTTIME`` と ``TFD_CLOEXEC``、``TFD_NONBLOCK`` をサポートします。絶対期限は作成時に選択したクロックで解釈され、周期的な満了は読み取り可能な回数に累積されます。``timerfd_settime()`` の ``it_value`` がゼロの場合、``TFD_TIMER_ABSTIME`` モードでもタイマーを解除します。" + +msgid "``CLOCK_BOOTTIME`` 使用现有启动时间时钟,当前与单调时钟共用计时来源。 官方 systemd 的 DHCP 重传定时器通过该接口运行。" +msgstr "``CLOCK_BOOTTIME`` は既存の起動時刻クロックを使用し、現在は単調クロックと時刻源を共有します。公式 systemd の DHCP 再送タイマーはこのインターフェースを使用します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po index 796f4215..628f454d 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po @@ -21,12 +21,12 @@ msgstr "インターフェースとパケット" msgid "" "IPv6 与 IPv4 共用描述符、等待队列、权限和网络执行上下文。应用使用 Linux x86-64 socket ABI 和 POSIX socket 调用,不需要 ReliefNT 私有 " -"IPv6 调用。 ``AF_INET6`` 为 10,``sockaddr_in6`` 大小为 28 字节;地址和端口为网络字节序, ``sin6_scope_id`` 是接口索引。当前 " -"``lo`` 为 1,``eth0`` 为 2。 链路本地地址需要正确的区域标识。" +"IPv6 调用。 ``AF_INET6`` 为 10,``sockaddr_in6`` 大小为 28 字节;地址和端口为网络字节序, ``sin6_scope_id`` 是接口索引。默认 " +"``lo`` 为 1,首个物理接口 ``eth0`` 为 2。 链路本地地址需要正确的区域标识。" msgstr "" "IPv6 は IPv4 と記述子、待ち行列、権限、ネットワーク実行コンテキストを共有します。アプリケーションは Linux x86-64 socket ABI と POSIX socket " "呼び出しを使い、ReliefNT 独自の IPv6 呼び出しは不要です。``AF_INET6`` は 10、``sockaddr_in6`` は 28 " -"バイトです。アドレスとポートはネットワークバイト順で、``sin6_scope_id`` はインターフェース索引です。現在は ``lo`` が 1、``eth0`` が 2 " +"バイトです。アドレスとポートはネットワークバイト順で、``sin6_scope_id`` はインターフェース索引です。既定では ``lo`` が 1、最初の物理インターフェース ``eth0`` が 2 " "です。リンクローカルアドレスには正しいスコープ識別子が必要です。" msgid "" @@ -55,8 +55,11 @@ msgstr "設定と観測" msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。" msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` はソケット作成時に保持したネットワーク scope のリンク、IPv4/IPv6 アドレス、経路を照会・変更し、FD 転送後もその scope を使用します。変更にはネットワークの user owner における ``CAP_NET_ADMIN`` が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 アドレスを取得します。IPv6 アドレスと経路の ioctl は対象ネットワークの状態と owner 権限を使用し、引数形式は socket family で選択します。UDP、TCP、raw、AF_PACKET のインターフェース ioctl と、IPv6 ソケットのアドレスおよび経路 ioctl は、すべて作成元ネットワークを使用します。" -msgid "路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" -msgstr "ルートマルチキャストはリンク、IPv6 アドレス、IPv6 ルートのグループに対応します。IPv4 アドレスとルートのマルチキャストは未実装で、該当グループの購読は ``EOPNOTSUPP`` を返します。各ネットワーク名前空間は独立した購読スナップショットを保持し、すべての取得が成功してから公開します。最後の購読者が閉じるか購読を解除すると解放します。変更通知と overrun はネットワーク scope ごとに配信し、受信キューのオーバーフローは ``ENOBUFS`` を報告するため、呼び出し元は再照会してください。" +msgid "路由多播发布链路、IPv4/IPv6 地址和路由的新增、变更与删除。IPv4 路由包含直连、默认及显式路由,metric 替换发布旧路由删除和新路由添加。接口删除时,地址通知保留原接口名称与地址。每个网络空间独立维护订阅快照,全部捕获成功后替换,最后一个订阅关闭或退订时释放。快照捕获失败保留旧基线并报告 overrun,后续变更重新捕获。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" +msgstr "ルートマルチキャストはリンク、IPv4/IPv6 アドレスと経路の追加、変更、削除を配信します。IPv4 経路には直結、デフォルト、明示的な経路が含まれ、metric の置換時は旧経路の削除と新経路の追加を配信します。インターフェース削除後もアドレス通知に元の名前とアドレスを保持します。各ネットワーク名前空間は独立した購読スナップショットを保持し、すべての取得が成功してから置換し、最後の購読者が閉じるか購読を解除すると解放します。取得失敗時は旧ベースラインを保持して overrun を報告し、後続の変更で再取得します。変更通知と overrun はネットワーク scope に従います。受信キューのオーバーフローは ``ENOBUFS`` を報告するため、呼び出し元は再照会してください。" + +msgid "路由 socket 接受 Linux 6.12 的标准组编号 1 至 36,支持 networkd 和 resolved 的订阅组合。实际事件由对应子系统提供,具体请求仍按其实现能力校验。``sockaddr_nl.nl_groups`` 表示低 32 位,``NETLINK_ADD_MEMBERSHIP`` 和 ``NETLINK_DROP_MEMBERSHIP`` 按组编号操作。初始化后的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 8 字节位图,短缓冲区复制可容纳的完整 32 位字并报告完整所需长度;uevent 位图长度为 4 字节。" +msgstr "ルート socket は Linux 6.12 の標準グループ番号 1 から 36 を受け付け、networkd と resolved の購読の組み合わせに対応します。実際のイベントは対応するサブシステムが提供し、個々の要求は実装済みの能力に従って検証します。``sockaddr_nl.nl_groups`` は下位 32 ビットを表し、``NETLINK_ADD_MEMBERSHIP`` と ``NETLINK_DROP_MEMBERSHIP`` はグループ番号を指定します。初期化後の ``NETLINK_LIST_MEMBERSHIPS`` は 8 バイトのビットマップを返します。短いバッファーには収まる完全な 32 ビット語をコピーし、必要な全長を報告します。uevent のビットマップ長は 4 バイトです。" msgid "" "多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 " @@ -121,3 +124,120 @@ msgid "" "路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含 " "被忽略的尾部;全部消息无效时不生成回复。预扫描和实际处理使用同一前缀边界。" msgstr "ルート要求はデータグラム内の有効なメッセージの先頭部分を順番に処理し、最初の不正または不完全なメッセージとそれ以降のバイトを無視します。最後の完全なメッセージではアラインメントのパディングを省略できます。送信が成功すると、無視した末尾を含むデータグラム全体のバイト数を返します。有効なメッセージがない場合は返信を生成しません。事前走査と実際の処理は同じ先頭部分の境界を使用します。" + +msgid "IPv4 选项与 UDP 消息" +msgstr "IPv4 オプションと UDP メッセージ" + +msgid "UDP 和 TCP 的 IPv4 及 IPv4 映射通信支持 ``SOL_IP`` 的 ``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL`` 和 ``IP_MTU_DISCOVER``。TTL 默认 64,接受 1 至 255,设置 -1 恢复默认值。接收辅助信息选项默认关闭。MTU discovery 默认 ``IP_PMTUDISC_WANT``,接受从 ``IP_PMTUDISC_DONT`` 到 ``IP_PMTUDISC_OMIT`` 的 0 至 5。当前 IPv4 输出仅在 ``DO`` 或 ``PROBE`` 时设置 DF,其余模式清除 DF。这些模式的设置与查询支持有上述报文效果,完整 IPv4 PMTU 探测与分片仍有实现边界。" +msgstr "UDP と TCP の IPv4 および IPv4 マップ通信は、``SOL_IP`` の ``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL``、``IP_MTU_DISCOVER`` をサポートします。TTL の既定値は 64 で、1 から 255 を受け付け、-1 で既定値に戻ります。受信補助情報オプションは既定で無効です。MTU discovery の既定値は ``IP_PMTUDISC_WANT`` で、``IP_PMTUDISC_DONT`` から ``IP_PMTUDISC_OMIT`` までの 0 から 5 を受け付けます。現在の IPv4 出力は ``DO`` または ``PROBE`` でのみ DF を設定し、他のモードでは解除します。これらのモードの設定と取得には、ここに記載したパケットへの効果があります。完全な IPv4 PMTU 探索と断片化には実装上の制限が残っています。" + +msgid "TCP 被动建立的子连接继承上述四项 IPv4 选项,IPv6 hop limit 与 PMTU 配置独立保存。TCP 上的 ``IP_PKTINFO`` 和 ``IP_RECVTTL`` 保存配置并由子连接继承,接收辅助数据由 UDP 路径提供。" +msgstr "受動的に確立された TCP 子接続は、上記の 4 つの IPv4 オプションを継承します。IPv6 hop limit と PMTU 設定は独立して保存されます。TCP の ``IP_PKTINFO`` と ``IP_RECVTTL`` は設定を保存し、子接続に継承します。受信補助データは UDP 経路で提供されます。" + +msgid "UDP IPv4 多播提供 ``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL`` 及 ``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP``。接口选择支持 ``in_addr``、``ip_mreq`` 和 ``ip_mreqn``,成员操作支持后两种布局。多播 TTL 默认 1,-1 恢复默认值,0 仅本地投递。loop 和 all 默认开启。接收按创建网络、组地址、入站接口、端口和已连接对端筛选,并向所有匹配的 socket 投递。``IP_MULTICAST_ALL=1`` 可使用同网络其他 socket 的组成员资格,设置 0 后仅使用本 socket 成员资格。" +msgstr "UDP IPv4 マルチキャストは ``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL``、``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP`` を提供します。インターフェース選択は ``in_addr``、``ip_mreq``、``ip_mreqn`` を受け付け、メンバー操作は後者 2 形式を受け付けます。マルチキャスト TTL の既定値は 1 で、-1 で既定値に戻り、0 ではローカル配送に限定します。loop と all は既定で有効です。受信は作成時ネットワーク、グループアドレス、入力インターフェース、ポート、接続済み相手で選別し、一致するすべてのソケットに配送します。``IP_MULTICAST_ALL=1`` は同じネットワークの他のソケットのメンバー資格も利用し、0 では自身のメンバー資格のみを利用します。" + +msgid "多播发送在创建网络中选择路由和源地址,以太网目的地址使用 ``01:00:5e`` 加组地址低 23 位的映射。TTL 为 0 或选择 loopback 时仅按 loop 设置进行本地投递。非初始网络的发送受其可见接口限制。当前成员资格用于本地接收筛选,尚未实现 IGMP 报告与查询,启用 IGMP snooping 的网络可能需要额外配置才能转发流量。" +msgstr "マルチキャスト送信は作成時ネットワークで経路と送信元を選択します。Ethernet 宛先は ``01:00:5e`` にグループアドレスの下位 23 ビットを組み合わせます。TTL が 0 または loopback を選択した場合は、loop 設定に従うローカル配送に限定します。初期以外のネットワークからの送信は、そこで見えるインターフェースに制限されます。現在のメンバー資格はローカル受信の選別に使われます。IGMP レポートとクエリは未実装で、IGMP snooping を有効にしたネットワークでは転送のために追加設定が必要になる場合があります。" + +msgid "UDP ``recvmsg()`` 在启用 IPv4 选项后通过 ``SOL_IP/IP_PKTINFO`` 和 ``SOL_IP/IP_TTL`` 返回实际入站接口、目的地址和 TTL,IPv4 映射报文也使用该布局。``in_pktinfo.ipi_addr`` 为报文目的地址,``ipi_spec_dst`` 为接收接口的本地 IPv4 地址,``ipi_ifindex`` 为入站接口索引。原生 IPv6 使用 ``IPV6_PKTINFO`` 和 hop-limit 辅助数据。控制缓冲区不足设置 ``MSG_CTRUNC``,载荷截断设置 ``MSG_TRUNC``,支持 ``MSG_PEEK``。向量 I/O 保持单个 UDP 数据报的边界。" +msgstr "IPv4 オプションを有効にすると、UDP ``recvmsg()`` は ``SOL_IP/IP_PKTINFO`` と ``SOL_IP/IP_TTL`` で実際の入力インターフェース、宛先、TTL を返します。IPv4 マップパケットも同じ形式を使います。``in_pktinfo.ipi_addr`` はパケット宛先、``ipi_spec_dst`` は受信インターフェースのローカル IPv4 アドレス、``ipi_ifindex`` は入力インターフェース索引です。ネイティブ IPv6 は ``IPV6_PKTINFO`` と hop-limit 補助データを使います。制御領域不足では ``MSG_CTRUNC``、ペイロード切り詰めでは ``MSG_TRUNC`` を設定し、``MSG_PEEK`` もサポートします。ベクトル I/O は単一 UDP データグラムの境界を保ちます。" + +msgid "UDP ``sendmsg()`` 可用 ``SOL_IP/IP_PKTINFO`` 的 ``ipi_ifindex`` 与 ``ipi_spec_dst`` 为单条消息选择接口和源地址,用 ``SOL_IP/IP_TTL`` 设置 1 至 255 的 TTL。IPv6 socket 还支持 ``IPV6_PKTINFO`` 与 hop-limit 辅助数据。发送前导入并校验控制信息,消息覆盖值不改变持久选项,接口和源地址仍受创建网络及 ``SO_BINDTODEVICE`` 约束。" +msgstr "UDP ``sendmsg()`` は ``SOL_IP/IP_PKTINFO`` の ``ipi_ifindex`` と ``ipi_spec_dst`` でメッセージ単位のインターフェースと送信元を選び、``SOL_IP/IP_TTL`` で 1 から 255 の TTL を指定できます。IPv6 ソケットは ``IPV6_PKTINFO`` と hop-limit 補助データもサポートします。送信前に制御情報を取り込み検証します。メッセージ単位の指定は永続オプションを変更せず、インターフェースと送信元の選択には作成時ネットワークと ``SO_BINDTODEVICE`` の制約が適用されます。" + +msgid "``NETLINK_GENERIC`` 提供标准控制族 ``nlctrl``,family ID 为 16,版本为 2。``CTRL_CMD_GETFAMILY`` 支持按 ``CTRL_ATTR_FAMILY_NAME`` 或 ``CTRL_ATTR_FAMILY_ID`` 查询,同时提供时优先名称。dump 返回已注册族及独立的 ``NLMSG_DONE``,回复公布查询操作和 ``notify`` 组 16。未知族通过 ``NLMSG_ERROR`` 返回 ``ENOENT``,未实现的控制命令返回 ``EOPNOTSUPP``。当前注册族仅有 ``nlctrl``,无线 ``nl80211`` 族尚未提供。socket 保留创建网络并复用端口、队列、ACK 和错误处理语义。" +msgstr "``NETLINK_GENERIC`` は family ID 16、バージョン 2 の標準制御族 ``nlctrl`` を提供します。``CTRL_CMD_GETFAMILY`` は ``CTRL_ATTR_FAMILY_NAME`` または ``CTRL_ATTR_FAMILY_ID`` で検索し、両方ある場合は名前を優先します。dump は登録済みの族と独立した ``NLMSG_DONE`` を返し、応答は照会操作と ``notify`` グループ 16 を通知します。未知の族は ``NLMSG_ERROR`` で ``ENOENT`` を返し、未実装の制御コマンドは ``EOPNOTSUPP`` を返します。現在登録されている族は ``nlctrl`` のみで、無線の ``nl80211`` 族は未提供です。ソケットは作成時ネットワークを保持し、ポート、キュー、ACK、エラー処理の意味論を共有します。" + +msgid "IPv4 地址的 ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知投递到 ``RTNLGRP_IPV4_IFADDR``,IPv4 路由的 ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` 通知投递到 ``RTNLGRP_IPV4_ROUTE``。订阅与通知均沿用 socket 创建网络。" +msgstr "IPv4 アドレスの ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知は ``RTNLGRP_IPV4_IFADDR`` に、IPv4 経路の ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` 通知は ``RTNLGRP_IPV4_ROUTE`` に配送します。購読と通知はともにソケットの作成時ネットワークに従います。" + +msgid "``NETLINK_GENERIC`` 的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 4 字节位图,控制族 ``notify`` 使用组 16。" +msgstr "``NETLINK_GENERIC`` の ``NETLINK_LIST_MEMBERSHIPS`` は 4 バイトのビットマップを返します。制御族の ``notify`` はグループ 16 を使います。" + +msgid "TCP IPv6 socket 支持 ``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` 的独立状态,默认关闭,任意非零设置值查询为 1,零查询为 0。原生 IPv6 和 IPv4 映射的被动子连接继承这两项,建立后各自保存状态。TCP 保存这些接收配置,当前 ``recvmsg()`` 仅交付流数据,UDP 提供上述接收辅助数据。" +msgstr "TCP IPv6 ソケットは ``IPV6_RECVPKTINFO`` と ``IPV6_RECVHOPLIMIT`` の独立した状態をサポートし、既定で無効です。非ゼロの設定値は 1、ゼロは 0 として取得されます。ネイティブ IPv6 と IPv4 マップの受動子接続は両方を継承し、作成後はそれぞれ独立した状態を保持します。TCP はこれらの受信設定を保存し、現在の ``recvmsg()`` はストリームデータのみを配送します。上記の受信補助データは UDP が提供します。" + +msgid "``RTM_GETNEIGH`` dump 从 socket 创建网络的 ARP 和 NDP 快照输出邻居,支持 ``AF_UNSPEC``、``AF_INET``、``AF_INET6`` 及接口索引筛选。IPv4 的 ``NDA_DST`` 转为网络字节序,缓存地址映射以 ``NUD_STALE`` 表示,IPv6 保留现有 NUD 状态。回复包含接口、目的地址及可用的链路层地址。``AF_BRIDGE`` 和 ``NTF_PROXY`` 查询返回空表及 ``NLMSG_DONE``,邻居新增、修改和删除请求返回 ``EOPNOTSUPP``。" +msgstr "``RTM_GETNEIGH`` dump は、ソケットの作成時ネットワークの ARP と NDP スナップショットから隣接エントリを出力し、``AF_UNSPEC``、``AF_INET``、``AF_INET6`` とインターフェース索引による絞り込みをサポートします。IPv4 の ``NDA_DST`` はネットワークバイト順に変換され、キャッシュされたアドレス対応は ``NUD_STALE`` で表されます。IPv6 は既存の NUD 状態を保持します。応答にはインターフェース、宛先アドレス、利用可能なリンク層アドレスが含まれます。``AF_BRIDGE`` と ``NTF_PROXY`` の照会は空の表と ``NLMSG_DONE`` を返し、隣接エントリの追加、変更、削除要求は ``EOPNOTSUPP`` を返します。" + +msgid "``AF_BRIDGE`` 的 ``RTM_GETLINK`` dump 返回空表及 ``NLMSG_DONE``。" +msgstr "``AF_BRIDGE`` の ``RTM_GETLINK`` dump は空の表と ``NLMSG_DONE`` を返します。" + +msgid "独立单路径 nexthop 按 socket 创建网络保存。``RTM_NEWNEXTHOP`` 和 ``RTM_DELNEXTHOP`` 按非零 ``NHA_ID`` 创建、替换或删除 IPv4/IPv6 对象,支持 ``NHA_OIF``、``NHA_GATEWAY`` 和 ``RTNH_F_ONLINK``。``RTM_GETNEXTHOP`` 支持按 ID 查询,以及按地址族、ID 和接口筛选的 dump,dump 以 ``NLMSG_DONE`` 结束。路由通过 ``RTA_NH_ID`` 引用同网络、同地址族的对象。替换对象同步更新依赖路由,删除对象或接口同时删除依赖路由,网络销毁释放全部对象。分配失败保留对象和路由状态。nexthop group、blackhole 和封装请求返回 ``EOPNOTSUPP``。" +msgstr "独立した単一路 nexthop はソケット作成時のネットワークに属します。``RTM_NEWNEXTHOP`` と ``RTM_DELNEXTHOP`` は非ゼロの ``NHA_ID`` で IPv4/IPv6 オブジェクトを作成、置換、削除し、``NHA_OIF``、``NHA_GATEWAY``、``RTNH_F_ONLINK`` をサポートします。``RTM_GETNEXTHOP`` は ID による照会と、アドレス族、ID、インターフェースによる dump の絞り込みを提供し、dump は ``NLMSG_DONE`` で終了します。経路は ``RTA_NH_ID`` で同一ネットワーク、同一アドレス族のオブジェクトを参照します。置換は依存経路を更新し、オブジェクトまたはインターフェースの削除は依存経路も削除します。ネットワーク破棄時にはすべてのオブジェクトを解放します。メモリー割り当て失敗時はオブジェクトと経路の状態を保持します。nexthop group、blackhole、カプセル化要求は ``EOPNOTSUPP`` を返します。" + +msgid "TCP 开放文件描述的最后一个引用关闭时,未连接的绑定端点及 listener 立即释放端口、缓冲区和创建网络引用,服务可立即重新绑定监听地址。已有关联对端的端点继续按协议状态回收,排队数据、FIN 和 TIME_WAIT 保留各自的生命周期。" +msgstr "TCP の最後のオープンファイル記述を閉じると、未接続のバインド済みエンドポイントと listener はポート、バッファー、作成ネットワークへの参照を直ちに解放し、サービスは待ち受けアドレスをすぐに再バインドできます。関連する相手を持つエンドポイントはプロトコル状態に従って回収され、キュー内データ、FIN、TIME_WAIT はそれぞれの寿命を維持します。" + +msgid "``SOL_SOCKET`` 的 ``SO_BINDTODEVICE`` 在 socket 创建网络中按名称查找设备,空名称解除绑定。``SO_BINDTOIFINDEX`` 的编号为 62,按 ``int`` 接口索引设置或查询同一绑定。正索引允许对应尚不存在或已删除的设备,负值返回 ``EINVAL``,0 解除绑定。两者的绑定均属于 socket 创建网络,任务切换网络或传递 FD 后继续使用该网络。当前已有非零绑定时,修改绑定或解绑需要创建网络 user owner 的 ``CAP_NET_RAW``。" +msgstr "``SOL_SOCKET`` の ``SO_BINDTODEVICE`` は、ソケット作成時のネットワーク内で名前からデバイスを検索します。空の名前はバインドを解除します。番号 62 の ``SO_BINDTOIFINDEX`` は ``int`` 型のインターフェース索引で同じバインドを設定または取得します。正の索引は、まだ存在しないデバイスや削除済みのデバイスを指すことができます。負の値は ``EINVAL`` を返し、0 はバインドを解除します。どちらのバインドもソケット作成時のネットワークに属し、タスクのネットワーク切り替えや FD の受け渡し後もそのネットワークを使用します。現在のバインドが非ゼロの場合、変更や解除には作成時ネットワークの user owner における ``CAP_NET_RAW`` が必要です。" + +msgid "IPv4 地址查询和新增、删除通知携带 ``ifaddrmsg.ifa_flags``、32 位 ``IFA_FLAGS``、scope、``IFA_CACHEINFO`` 及可选的 ``IFA_RT_PRIORITY``。每个接口保存一个主 IPv4 地址,支持 ``IFA_F_PERMANENT``、``IFA_F_DEPRECATED`` 和 ``IFA_F_NOPREFIXROUTE``。有限有效期清除 PERMANENT,首选期到期设置 DEPRECATED,有效期到期删除地址。NOPREFIXROUTE 抑制自动前缀路由,IFA_RT_PRIORITY 设置其 metric。省略有效期时地址永久有效。" +msgstr "IPv4 アドレスの照会および追加・削除通知は ``ifaddrmsg.ifa_flags``、32 ビットの ``IFA_FLAGS``、scope、``IFA_CACHEINFO``、任意の ``IFA_RT_PRIORITY`` を含みます。各インターフェースは主 IPv4 アドレスを一つ保持し、``IFA_F_PERMANENT``、``IFA_F_DEPRECATED``、``IFA_F_NOPREFIXROUTE`` をサポートします。有限の有効期間は PERMANENT を解除し、優先期間の満了は DEPRECATED を設定し、有効期間の満了はアドレスを削除します。NOPREFIXROUTE は自動プレフィックス経路を抑制し、IFA_RT_PRIORITY はその metric を設定します。期間を省略したアドレスは永続です。" + +msgid "IPv6 地址使用相同的租期和前缀 metric 属性,支持 NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE 和 MANAGETEMPADDR。MANAGETEMPADDR 要求 /64 前缀并保存配置标志,临时隐私地址的自动生成仍待实现。自动前缀路由随地址、metric、标志和有效期维护,同时保留同前缀的其他有效地址及 RA 路由贡献。" +msgstr "IPv6 アドレスも同じ期間とプレフィックス metric 属性を使用し、NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE、MANAGETEMPADDR をサポートします。MANAGETEMPADDR は /64 プレフィックスを要求して設定フラグを保持します。一時プライバシーアドレスの自動生成は今後の実装です。自動プレフィックス経路はアドレス、metric、フラグ、有効期間に追従し、同じプレフィックスの他の有効アドレスと RA 経路からの寄与を保持します。" + +msgid "IPv4/IPv6 的 ``RTM_NEWADDR`` 允许仅携带 ``NLM_F_REPLACE`` 创建地址。已有地址遇 ``NLM_F_EXCL`` 或缺少 REPLACE 时返回 ``EEXIST``,校验失败保留原配置。``RTM_NEWROUTE`` 接受 ``NLM_F_APPEND``,新增路由保留同优先级存活路由的插入顺序。修改请求的 ``NLM_F_ECHO`` 和其他修改消息上的 APPEND 返回 ``EOPNOTSUPP``。" +msgstr "IPv4/IPv6 の ``RTM_NEWADDR`` は ``NLM_F_REPLACE`` 単独でアドレスを作成できます。既存アドレスに ``NLM_F_EXCL`` がある場合、または REPLACE がない場合は ``EEXIST`` を返します。検証失敗時は元の設定を保持します。``RTM_NEWROUTE`` は ``NLM_F_APPEND`` を受け入れ、新しい経路は同じ優先度の既存経路の挿入順序を維持します。変更要求の ``NLM_F_ECHO`` と他の変更メッセージの APPEND は ``EOPNOTSUPP`` を返します。" + +msgid "IPv4/IPv6 路由支持 ``RTA_PREFSRC`` 及 ``RTNH_F_ONLINK``,首选源地址须已配置在同网络。IPv6 还支持 ``RTA_PREF`` 的低、中、高优先级与 ``RTA_EXPIRES`` 秒级有效期,到期发布删除通知。IPv6 路由身份包含目的前缀、接口、网关、nexthop ID 和 metric,同路径不同 metric 可共存。选路依次比较最长前缀、较低 metric 和较高 preference,完全相同时保留先插入路由。REPLACE 更新匹配条目,目标缺失且未携带 CREATE 时返回 ``ESRCH``。" +msgstr "IPv4/IPv6 経路は ``RTA_PREFSRC`` と ``RTNH_F_ONLINK`` をサポートし、優先送信元アドレスは同じネットワークに設定済みである必要があります。IPv6 は ``RTA_PREF`` の低・中・高優先度と ``RTA_EXPIRES`` による秒単位の有効期間も提供し、満了時に削除通知を発行します。IPv6 経路の識別には宛先プレフィックス、インターフェース、ゲートウェイ、nexthop ID、metric が含まれ、同じ経路で異なる metric が共存できます。選択は最長プレフィックス、低い metric、高い preference の順に比較し、完全に等しい場合は先に挿入した経路を保持します。REPLACE は一致するエントリを更新し、対象が存在せず CREATE がない場合は ``ESRCH`` を返します。" + +msgid "网络 sysfs 与设备事件" +msgstr "ネットワーク sysfs とデバイスイベント" + +msgid "sysfs 挂载保留创建时捕获的网络空间,后续 lookup、readdir、read 和 write 均使用该视图。任务执行 ``setns()``、``unshare()`` 或传递挂载句柄后,已有挂载继续观察原网络。``fsopen(\"sysfs\")`` 的网络与 owner 捕获及 CREATE 授权见 :doc:`abi`。" +msgstr "sysfs マウントは作成時に取得したネットワーク名前空間を保持し、その後の lookup、readdir、read、write はこのビューを使用します。タスクが ``setns()`` や ``unshare()`` を実行した後、またはマウントハンドルを受け渡した後も、既存のマウントは元のネットワークを参照します。``fsopen(\"sysfs\")`` によるネットワークと owner の取得、および CREATE の認可は :doc:`abi` を参照してください。" + +msgid "``/sys/class/net/`` 是指向 canonical 设备节点的符号链接。loopback 位于 ``/sys/devices/virtual/net/lo``,物理接口位于对应 PCI function 下的 ``net/``,``device`` 链接指向 PCI 父节点,``subsystem`` 链接指向 ``/sys/class/net``。属性包含 ``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier`` 和 ``uevent``。物理接口仅在初始网络中可见。接口移除后,持有的旧 inode 在重新打开、读取或写入时返回 ``ENOENT``。" +msgstr "``/sys/class/net/`` は canonical デバイスノードへのシンボリックリンクです。loopback は ``/sys/devices/virtual/net/lo`` に配置されます。物理インターフェースは対応する PCI function 配下の ``net/`` に配置され、``device`` は PCI 親ノードを、``subsystem`` は ``/sys/class/net`` を指します。属性には ``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier``、``uevent`` が含まれます。物理インターフェースは初期ネットワークでのみ可視です。インターフェース削除後、保持済みの旧 inode を再度開く操作、読み取り、書き込みは ``ENOENT`` を返します。" + +msgid "网络 ``uevent`` 文件由 root 所有,模式为 0644,写入遵循常规 DAC 与挂载只读策略。只读挂载也阻止 root 写入。读取提供 ``INTERFACE`` 和 ``IFINDEX``。写入接受 ``add``、``remove``、``change``、``move``、``online``、``offline``、``bind`` 或 ``unbind``,可在一个空格后附加 36 字符的十六进制 UUID,连字符位于标准位置,末尾可带一个换行。无 UUID 时事件使用 ``SYNTH_UUID=0``,提供 UUID 时按输入传递。无效 action、UUID 或 embedded NUL 返回 ``EINVAL``,并保持事件队列不变。" +msgstr "ネットワークの ``uevent`` ファイルは root 所有で、モードは 0644 です。書き込みには通常の DAC とマウントの読み取り専用ポリシーが適用されます。読み取り専用マウントは root による書き込みも拒否します。読み取りは ``INTERFACE`` と ``IFINDEX`` を提供します。書き込みは ``add``、``remove``、``change``、``move``、``online``、``offline``、``bind``、``unbind`` を受け付け、任意でスペース 1 個と、標準位置にハイフンを持つ 36 文字の 16 進 UUID を続けられます。末尾の改行 1 個も許可されます。UUID がないイベントは ``SYNTH_UUID=0`` を使用し、指定された UUID は入力どおりに渡されます。不正な action、UUID、埋め込み NUL は ``EINVAL`` を返し、イベントキューを維持します。" + +msgid "``NETLINK_KOBJECT_UEVENT`` 的网络设备事件按订阅 socket 的创建网络筛选。物理接口注册和移除分别发布 ``add`` 和 ``remove``,移除事件保留注册时的设备身份。sysfs 合成事件使用挂载捕获的网络,事件携带 action、设备路径、``SUBSYSTEM=net``、``INTERFACE`` 和 ``IFINDEX``,合成事件还携带 ``SYNTH_UUID``。其他网络的订阅者不会收到该网络事件,任务随后切换网络也保留已有 socket 的订阅范围。" +msgstr "``NETLINK_KOBJECT_UEVENT`` のネットワークデバイスイベントは、購読ソケット作成時のネットワークに基づいて選別されます。物理インターフェースの登録と削除は、それぞれ ``add`` と ``remove`` を発行します。削除イベントは登録時に取得したデバイス識別情報を保持します。sysfs の合成イベントはマウントが取得したネットワークを使用します。イベントは action、デバイスパス、``SUBSYSTEM=net``、``INTERFACE``、``IFINDEX`` を含み、合成イベントはさらに ``SYNTH_UUID`` を含みます。他のネットワークの購読者にはそのネットワークイベントは届きません。タスクが後でネットワークを切り替えても、既存ソケットの購読範囲を維持します。" + +msgid "block、PCI 和 DRM 已公开的设备 ``uevent`` 控制同样接受上述 action 与可选 UUID,权限和即时写入语义见 :doc:`abi`。事件属性取自同一设备的当前真实 inventory,``SUBSYSTEM`` 取自该设备的 ``subsystem`` 链接,并附带 ``SYNTH_UUID``。这些 global 设备事件仅投递给初始 user namespace 所拥有的网络空间中的订阅者,包含永久初始网络。网络设备事件继续严格按 socket 创建网络与挂载捕获网络隔离。" +msgstr "block、PCI、DRM デバイスが公開する ``uevent`` 制御も、上記の action と任意の UUID を受け付けます。権限と即時書き込みの意味論は :doc:`abi` を参照してください。イベント属性は同じデバイスの現在の実際の inventory から取得します。``SUBSYSTEM`` はそのデバイスの ``subsystem`` リンクから取得し、``SYNTH_UUID`` を付加します。これらの global デバイスイベントは、永続的な初期ネットワークを含む、初期 user namespace が所有するネットワーク名前空間内の購読者にのみ配送されます。ネットワークデバイスイベントは、ソケット作成時のネットワークとマウントが取得したネットワークによる厳密な隔離を維持します。" + +msgid "``RTM_SETLINK`` 与 ``RTM_NEWLINK`` 在提供正接口索引和 ``IFLA_IFNAME`` 时执行重命名,索引为 0 时按名称选择已有接口。``SIOCSIFNAME`` 使用相同的创建网络与 ``CAP_NET_ADMIN`` 授权。重命名保留接口索引和 UP 状态,更新 ioctl、socket 设备绑定查询及 sysfs 名称,并发布同网络的 ``RTM_NEWLINK`` 与携带 ``DEVPATH_OLD`` 的 ``move`` 事件。名称最长 15 字节,空白、斜线、冒号、``.`` 和 ``..`` 返回 ``EINVAL``,同网络名称冲突返回 ``EEXIST``。单个 ``%d`` 模板选择 0 至 32767 内首个空闲编号,同名请求不发布事件。``name_assign_type`` 对枚举物理名称报告 1,重命名后报告 4。" +msgstr "``RTM_SETLINK`` と ``RTM_NEWLINK`` は、正のインターフェース索引と ``IFLA_IFNAME`` が指定された場合に名前を変更します。索引 0 は名前で既存のインターフェースを選択します。``SIOCSIFNAME`` も作成時ネットワークの範囲と ``CAP_NET_ADMIN`` による認可を使います。名前変更では索引と UP 状態を保持し、ioctl、socket のデバイス束縛照会、sysfs の名前を更新します。同じネットワークに ``RTM_NEWLINK`` と ``DEVPATH_OLD`` を含む ``move`` イベントを配信します。名前は最大 15 バイトです。空白、スラッシュ、コロン、``.``、``..`` は ``EINVAL``、同じネットワーク内の名前衝突は ``EEXIST`` を返します。単一の ``%d`` テンプレートは 0 から 32767 までの最初の空き番号を選びます。同名への要求はイベントを配信しません。``name_assign_type`` は列挙された物理名で 1、名前変更後は 4 を返します。" + +msgid "packet socket 与链路接收" +msgstr "Packet socket とリンク受信" + +msgid "``AF_PACKET`` 的 ``SO_ATTACH_FILTER`` 与 ``SO_DETACH_FILTER`` 复用 classic BPF 校验和执行器。过滤结果为 0 时丢弃报文,正值限制保留长度。替换失败保留旧过滤器。``bind()`` 的零 ``sll_protocol`` 保留创建时选择的协议。" +msgstr "``AF_PACKET`` の ``SO_ATTACH_FILTER`` と ``SO_DETACH_FILTER`` は classic BPF の検証器と実行器を使用します。結果が 0 ならフレームを破棄し、正なら保持する長さを制限します。置換に失敗すると以前のフィルターを保持します。``bind()`` の ``sll_protocol`` が 0 の場合、作成時のプロトコルを保持します。" + +msgid "``SOL_PACKET`` 的 ``PACKET_ADD_MEMBERSHIP`` 与 ``PACKET_DROP_MEMBERSHIP`` 支持按创建网络、接口及六字节地址管理 ``PACKET_MR_MULTICAST``,重复加入按引用计数回收。最后关闭或设备移除释放订阅。额外链路组播按同网络、同接口的订阅执行软件接收筛选。当前其他成员类型返回 ``EINVAL``。" +msgstr "``SOL_PACKET`` の ``PACKET_ADD_MEMBERSHIP`` と ``PACKET_DROP_MEMBERSHIP`` は、作成ネットワーク、インターフェース、6 バイトのアドレスで ``PACKET_MR_MULTICAST`` を管理します。重複参加は参照数で管理し、最後の close とデバイス削除で購読を解放します。追加のリンクマルチキャストは同じネットワークとインターフェースの購読に基づきソフトウェアで受信を選別します。他のメンバー種別は現在 ``EINVAL`` を返します。" + +msgid "``PACKET_AUXDATA`` 在 ``recvmsg()`` 返回 ``tpacket_auxdata``,包括过滤前长度、保留长度及链路偏移。RAW 报文的网络偏移为 14,DGRAM 为 0。``SO_TIMESTAMP_OLD`` 与 ``SO_TIMESTAMP_NEW`` 提供 realtime 微秒时间戳,排队时采样,接收前才启用时延迟采样,重复 ``MSG_PEEK`` 保留同一样本。输出内存准备失败保留队列,控制缓冲区不足设置 ``MSG_CTRUNC``。" +msgstr "``PACKET_AUXDATA`` は ``recvmsg()`` で ``tpacket_auxdata`` を返し、フィルター前の長さ、保持長、リンクオフセットを含みます。ネットワークオフセットは RAW で 14、DGRAM で 0 です。``SO_TIMESTAMP_OLD`` と ``SO_TIMESTAMP_NEW`` は realtime のマイクロ秒タイムスタンプを提供します。キュー投入時、または到着後に有効化した場合は受信時に採取し、繰り返す ``MSG_PEEK`` でも同じ値を保持します。出力メモリー準備の失敗ではキューを保持し、制御領域不足は ``MSG_CTRUNC`` を設定します。" + +msgid "UDP 和 packet socket 的 ``SO_PRIORITY`` 保存有符号整数优先级,默认 0。0 至 6 可直接设置,其他值需要 socket 创建网络 user owner 的 ``CAP_NET_RAW`` 或 ``CAP_NET_ADMIN``。用户内存或权限检查失败保留原值。" +msgstr "UDP と packet socket の ``SO_PRIORITY`` は符号付き整数の優先度を保持し、初期値は 0 です。0 から 6 は直接設定でき、それ以外の値には socket 作成ネットワークの user owner に対する ``CAP_NET_RAW`` または ``CAP_NET_ADMIN`` が必要です。ユーザーメモリーまたは権限の検査に失敗すると以前の値を保持します。" + +msgid "UDP 的 ``IP_TOS`` 默认 0,保存输入低八位并写入实际 IPv4 首部,包含 DSCP 和 ECN 位。TOS 变化同时按 Linux 的 TOS 映射更新 socket 优先级。``IP_FREEBIND`` 默认关闭,开启后允许绑定尚未配置的 IPv4 地址及 IPv4 映射地址。端口冲突、设备绑定、特权端口授权和创建网络范围仍按原规则检查,发送继续要求有效路由。" +msgstr "UDP の ``IP_TOS`` は初期値 0 で、入力の下位 8 ビットを DSCP と ECN を含め実際の IPv4 ヘッダーに設定します。TOS の変更時には Linux の TOS マッピングで socket 優先度も更新します。``IP_FREEBIND`` は初期状態で無効で、有効にすると未設定の IPv4 アドレスと IPv4 mapped アドレスに bind できます。ポート競合、デバイス bind、特権ポート権限、作成ネットワークの検査を維持し、送信には有効な経路が必要です。" + +msgid "UDP 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 返回 realtime 微秒时间戳,支持原生 IPv4、IPv6 和 IPv4 映射报文。启用时在入队采样,接收前才启用则在首次接收时采样。``MSG_PEEK`` 和切换时间戳格式保留已有样本,关闭选项后停止交付时间戳。时间戳通过 ``SOL_SOCKET`` 辅助消息返回,可与 IP packet info 和 TTL 同时使用。输出内存准备失败保留队列,控制区不足设置 ``MSG_CTRUNC``。" +msgstr "UDP の ``SO_TIMESTAMP_OLD`` と ``SO_TIMESTAMP_NEW`` は native IPv4、IPv6、IPv4 mapped データグラムに realtime のマイクロ秒時刻を返します。有効時はキュー追加時に採取し、到着後に有効にすると最初の受信時に採取します。``MSG_PEEK`` と時刻形式の変更で同じ標本を保持し、無効にすると時刻の出力を停止します。``SOL_SOCKET`` 補助メッセージで IP packet info や TTL と共に返します。出力メモリーの準備失敗ではキューを保持し、制御領域不足では ``MSG_CTRUNC`` を設定します。" + +msgid "UDP 的 ``IP_UNICAST_IF`` 和 ``IPV6_UNICAST_IF`` 分别保存 IPv4 和 IPv6 的默认单播出口。设置与查询均使用网络字节序的 32 位接口索引,设置长度必须恰好为 4 字节。0 清除配置,非零索引必须存在于 socket 创建网络中,否则返回 ``EADDRNOTAVAIL``。已有设备绑定时设置非零索引返回 ``EINVAL``。普通用户可设置这些选项,接收筛选继续使用原有设备绑定。消息级接口、显式 scope 和设备绑定优先于默认单播出口;IPv4 映射发送使用 IPv4 配置。" +msgstr "UDP の ``IP_UNICAST_IF`` と ``IPV6_UNICAST_IF`` は、IPv4 と IPv6 のデフォルトのユニキャスト送信インターフェースを個別に保持します。設定と取得にはネットワークバイト順の 32 ビットインターフェース索引を使用し、設定値の長さは正確に 4 バイトである必要があります。0 は設定を解除します。非ゼロの索引はソケット作成時のネットワークに存在する必要があり、存在しない場合は ``EADDRNOTAVAIL`` を返します。デバイスにバインド済みのソケットへの非ゼロ索引の設定は ``EINVAL`` を返します。一般ユーザーも設定でき、受信の選別には既存のデバイスバインドを引き続き使用します。メッセージ単位のインターフェース、明示的な scope、デバイスバインドは、デフォルトのユニキャスト送信先より優先されます。IPv4 マップ送信は IPv4 の設定を使用します。" + +msgid "UDP 扩展错误队列" +msgstr "UDP 拡張エラーキュー" + +msgid "``IP_RECVERR`` 和 ``IPV6_RECVERR`` 默认关闭。启用后,经过校验的 IPv4 ICMP 或 ICMPv6 错误按 socket 创建网络、接口及原始 UDP 地址和端口关联到独立错误队列。记录保存 ``sock_extended_err`` 的 errno、origin、type、code 和 MTU,以及错误发送者、原始目的地址和被引用的 UDP 载荷。IPv4 映射 socket 返回原生 IPv6 地址布局。" +msgstr "``IP_RECVERR`` と ``IPV6_RECVERR`` はデフォルトで無効です。有効にすると、検証済みの IPv4 ICMP または ICMPv6 エラーを、ソケット作成時のネットワーク、インターフェース、元の UDP アドレスとポートに基づいて独立したエラーキューに関連付けます。各記録は ``sock_extended_err`` の errno、origin、type、code、MTU と、エラー送信元、元の宛先、引用された UDP ペイロードを保持します。IPv4 マップソケットはネイティブ IPv6 のアドレスレイアウトを返します。" + +msgid "``recvmsg(MSG_ERRQUEUE)`` 通过 ``msg_name`` 返回原始目的地址,通过 ``SOL_IP/IP_RECVERR`` 或 ``SOL_IPV6/IPV6_RECVERR`` 辅助消息返回扩展错误及其发送者,并设置输出 ``MSG_ERRQUEUE``。队列为空时立即返回 ``EAGAIN``,设置 ``MSG_PEEK`` 仍消费该条错误。载荷和控制区不足分别报告 ``MSG_TRUNC`` 和 ``MSG_CTRUNC``。用户输出内存准备失败保留记录,成功读取后按下一条错误更新待处理 errno。" +msgstr "``recvmsg(MSG_ERRQUEUE)`` は元の宛先を ``msg_name`` に、拡張エラーとその送信元を ``SOL_IP/IP_RECVERR`` または ``SOL_IPV6/IPV6_RECVERR`` の補助メッセージに返し、出力に ``MSG_ERRQUEUE`` を設定します。キューが空の場合は直ちに ``EAGAIN`` を返します。``MSG_PEEK`` を指定してもエラー記録を消費します。ペイロードと制御領域の容量不足は、それぞれ ``MSG_TRUNC`` と ``MSG_CTRUNC`` で通知します。ユーザー出力メモリの準備に失敗した場合は記録を保持します。読み取りが成功すると、次のエラーに基づいて保留中の errno を更新します。" + +msgid "错误记录与普通数据报分别持有存储,待处理 errno 或错误队列可触发 ``POLLERR``。查询 ``SO_ERROR`` 清除待处理 errno,已排队记录继续可读。关闭相应 RECVERR 选项会清空错误队列,保留普通数据和待处理 errno。分配失败或队列达到上限时保留已有记录并继续报告 socket 错误。最后关闭释放全部记录及创建网络引用。" +msgstr "エラー記録と通常のデータグラムは、それぞれ独立した記憶領域を所有します。保留中の errno またはエラーキューにより ``POLLERR`` が発生します。``SO_ERROR`` の取得は保留中の errno をクリアし、キュー内の記録は引き続き読み取れます。対応する RECVERR オプションを無効にするとエラーキューを空にし、通常のデータと保留中の errno は保持します。メモリ割り当ての失敗やキュー上限到達時は既存の記録を保持し、ソケットエラーの通知を継続します。最後のクローズですべての記録と作成時のネットワーク参照を解放します。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 5ea412b0..9779dcb7 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -21,6 +21,17 @@ vDSO 的 ELF 符号版本、辅助向量、vvar 邻接映射及时间读取均 接口修改同步内核、导出头、用户态包装、消费者和必要验证,不以更新 golden 替代布局或语义审查。 +timerfd 时钟 +============ + +``timerfd_create()`` 支持 ``CLOCK_REALTIME``、``CLOCK_MONOTONIC`` 和 +``CLOCK_BOOTTIME``,接受 ``TFD_CLOEXEC`` 与 ``TFD_NONBLOCK``。绝对截止时间 +按创建时选定的时钟解释,周期到期累计可读次数。``timerfd_settime()`` 的 +``it_value`` 为零时解除定时器,包括 ``TFD_TIMER_ABSTIME`` 模式。 + +``CLOCK_BOOTTIME`` 使用现有启动时间时钟,当前与单调时钟共用计时来源。 +官方 systemd 的 DHCP 重传定时器通过该接口运行。 + 按任务选择 uname 系统名 ======================== @@ -246,12 +257,9 @@ inode 引用释放且相关缓存回收后,设备号才能重用。 ``fsmount`` 指定。proc 的全局 PID 视图保留初始用户空间 owner,CREATE 要求 该 owner 的 ``CAP_SYS_ADMIN``。策略及重配置语义见 :doc:`procfs`。 -``fsopen("sysfs", FSOPEN_CLOEXEC)`` 捕获当前网络空间的 user owner,并要求其 -``CAP_SYS_ADMIN``。传统 sysfs mount 使用同一 owner。CREATE 再次检查捕获的 -owner,调用者随后切换网络不会改变该权限作用域。sysfs 上下文接受通用 -``source``、``ro`` 和 ``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的 -只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读 -属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。 +``fsopen("sysfs", FSOPEN_CLOEXEC)`` 同时保留当前网络空间及其 user owner,并要求该 owner 的 ``CAP_SYS_ADMIN``。CREATE 再次检查捕获的 owner,并使用捕获的网络创建 sysfs 视图。上下文传递或调用者随后切换网络时,这两项捕获继续生效。传统 sysfs mount 同样使用挂载时的网络及其 owner。sysfs 上下文接受通用 ``source``、``ro`` 和 ``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。 + +sysfs 已公开的 block、PCI 和 DRM 设备 ``uevent`` 控制由 kernel UID 0 所有,模式为 0644,权限检查沿用现有 DAC 与 kernel UID 语义。支持 ``O_TRUNC`` 的零长度截断,截断本身不发布事件。写入直接提交事件,action 与可选 UUID 的格式同网络 ``uevent``,见 :doc:`ipv6`。非法输入、只读挂载或权限检查失败均不发布事件。 tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 diff --git a/Documentation/userspace-api/ipv6.rst b/Documentation/userspace-api/ipv6.rst index daac689b..5d0738a8 100644 --- a/Documentation/userspace-api/ipv6.rst +++ b/Documentation/userspace-api/ipv6.rst @@ -8,7 +8,7 @@ IPv6 双栈 IPv6 与 IPv4 共用描述符、等待队列、权限和网络执行上下文。应用使用 Linux x86-64 socket ABI 和 POSIX socket 调用,不需要 ReliefNT 私有 IPv6 调用。 ``AF_INET6`` 为 10,``sockaddr_in6`` 大小为 28 字节;地址和端口为网络字节序, -``sin6_scope_id`` 是接口索引。当前 ``lo`` 为 1,``eth0`` 为 2。 +``sin6_scope_id`` 是接口索引。默认 ``lo`` 为 1,首个物理接口 ``eth0`` 为 2。 链路本地地址需要正确的区域标识。 TCP、UDP 和 raw socket 的 ``bind`` 与 Linux 一样,只对需要区域标识的地址 @@ -29,12 +29,81 @@ IPv6 socket 默认允许 IPv4 映射地址;应用可在绑定前使用 ``IPV6_ hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回错误, 不能将未实现功能报告为设置成功。 +``SOL_SOCKET`` 的 ``SO_BINDTODEVICE`` 在 socket 创建网络中按名称查找设备,空名称解除绑定。``SO_BINDTOIFINDEX`` 的编号为 62,按 ``int`` 接口索引设置或查询同一绑定。正索引允许对应尚不存在或已删除的设备,负值返回 ``EINVAL``,0 解除绑定。两者的绑定均属于 socket 创建网络,任务切换网络或传递 FD 后继续使用该网络。当前已有非零绑定时,修改绑定或解绑需要创建网络 user owner 的 ``CAP_NET_RAW``。 + +IPv4 选项与 UDP 消息 +================================ + +UDP 和 packet socket 的 ``SO_PRIORITY`` 保存有符号整数优先级,默认 0。0 至 6 可直接设置,其他值需要 socket 创建网络 user owner 的 ``CAP_NET_RAW`` 或 ``CAP_NET_ADMIN``。用户内存或权限检查失败保留原值。 + +UDP 的 ``IP_TOS`` 默认 0,保存输入低八位并写入实际 IPv4 首部,包含 DSCP 和 ECN 位。TOS 变化同时按 Linux 的 TOS 映射更新 socket 优先级。``IP_FREEBIND`` 默认关闭,开启后允许绑定尚未配置的 IPv4 地址及 IPv4 映射地址。端口冲突、设备绑定、特权端口授权和创建网络范围仍按原规则检查,发送继续要求有效路由。 + +UDP 的 ``IP_UNICAST_IF`` 和 ``IPV6_UNICAST_IF`` 分别保存 IPv4 和 IPv6 的默认单播出口。设置与查询均使用网络字节序的 32 位接口索引,设置长度必须恰好为 4 字节。0 清除配置,非零索引必须存在于 socket 创建网络中,否则返回 ``EADDRNOTAVAIL``。已有设备绑定时设置非零索引返回 ``EINVAL``。普通用户可设置这些选项,接收筛选继续使用原有设备绑定。消息级接口、显式 scope 和设备绑定优先于默认单播出口;IPv4 映射发送使用 IPv4 配置。 + +UDP 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 返回 realtime 微秒时间戳,支持原生 IPv4、IPv6 和 IPv4 映射报文。启用时在入队采样,接收前才启用则在首次接收时采样。``MSG_PEEK`` 和切换时间戳格式保留已有样本,关闭选项后停止交付时间戳。时间戳通过 ``SOL_SOCKET`` 辅助消息返回,可与 IP packet info 和 TTL 同时使用。输出内存准备失败保留队列,控制区不足设置 ``MSG_CTRUNC``。 + +UDP 和 TCP 的 IPv4 及 IPv4 映射通信支持 ``SOL_IP`` 的 ``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL`` 和 ``IP_MTU_DISCOVER``。TTL 默认 64,接受 1 至 255,设置 -1 恢复默认值。接收辅助信息选项默认关闭。MTU discovery 默认 ``IP_PMTUDISC_WANT``,接受从 ``IP_PMTUDISC_DONT`` 到 ``IP_PMTUDISC_OMIT`` 的 0 至 5。当前 IPv4 输出仅在 ``DO`` 或 ``PROBE`` 时设置 DF,其余模式清除 DF。这些模式的设置与查询支持有上述报文效果,完整 IPv4 PMTU 探测与分片仍有实现边界。 + +TCP 被动建立的子连接继承上述四项 IPv4 选项,IPv6 hop limit 与 PMTU 配置独立保存。TCP 上的 ``IP_PKTINFO`` 和 ``IP_RECVTTL`` 保存配置并由子连接继承,接收辅助数据由 UDP 路径提供。 + +TCP IPv6 socket 支持 ``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` 的独立状态,默认关闭,任意非零设置值查询为 1,零查询为 0。原生 IPv6 和 IPv4 映射的被动子连接继承这两项,建立后各自保存状态。TCP 保存这些接收配置,当前 ``recvmsg()`` 仅交付流数据,UDP 提供上述接收辅助数据。 + +TCP 开放文件描述的最后一个引用关闭时,未连接的绑定端点及 listener 立即释放端口、缓冲区和创建网络引用,服务可立即重新绑定监听地址。已有关联对端的端点继续按协议状态回收,排队数据、FIN 和 TIME_WAIT 保留各自的生命周期。 + +UDP IPv4 多播提供 ``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL`` 及 ``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP``。接口选择支持 ``in_addr``、``ip_mreq`` 和 ``ip_mreqn``,成员操作支持后两种布局。多播 TTL 默认 1,-1 恢复默认值,0 仅本地投递。loop 和 all 默认开启。接收按创建网络、组地址、入站接口、端口和已连接对端筛选,并向所有匹配的 socket 投递。``IP_MULTICAST_ALL=1`` 可使用同网络其他 socket 的组成员资格,设置 0 后仅使用本 socket 成员资格。 + +多播发送在创建网络中选择路由和源地址,以太网目的地址使用 ``01:00:5e`` 加组地址低 23 位的映射。TTL 为 0 或选择 loopback 时仅按 loop 设置进行本地投递。非初始网络的发送受其可见接口限制。当前成员资格用于本地接收筛选,尚未实现 IGMP 报告与查询,启用 IGMP snooping 的网络可能需要额外配置才能转发流量。 + +UDP ``recvmsg()`` 在启用 IPv4 选项后通过 ``SOL_IP/IP_PKTINFO`` 和 ``SOL_IP/IP_TTL`` 返回实际入站接口、目的地址和 TTL,IPv4 映射报文也使用该布局。``in_pktinfo.ipi_addr`` 为报文目的地址,``ipi_spec_dst`` 为接收接口的本地 IPv4 地址,``ipi_ifindex`` 为入站接口索引。原生 IPv6 使用 ``IPV6_PKTINFO`` 和 hop-limit 辅助数据。控制缓冲区不足设置 ``MSG_CTRUNC``,载荷截断设置 ``MSG_TRUNC``,支持 ``MSG_PEEK``。向量 I/O 保持单个 UDP 数据报的边界。 + +UDP ``sendmsg()`` 可用 ``SOL_IP/IP_PKTINFO`` 的 ``ipi_ifindex`` 与 ``ipi_spec_dst`` 为单条消息选择接口和源地址,用 ``SOL_IP/IP_TTL`` 设置 1 至 255 的 TTL。IPv6 socket 还支持 ``IPV6_PKTINFO`` 与 hop-limit 辅助数据。发送前导入并校验控制信息,消息覆盖值不改变持久选项,接口和源地址仍受创建网络及 ``SO_BINDTODEVICE`` 约束。 + +UDP 扩展错误队列 +-------------------- + +``IP_RECVERR`` 和 ``IPV6_RECVERR`` 默认关闭。启用后,经过校验的 IPv4 ICMP 或 ICMPv6 错误按 socket 创建网络、接口及原始 UDP 地址和端口关联到独立错误队列。记录保存 ``sock_extended_err`` 的 errno、origin、type、code 和 MTU,以及错误发送者、原始目的地址和被引用的 UDP 载荷。IPv4 映射 socket 返回原生 IPv6 地址布局。 + +``recvmsg(MSG_ERRQUEUE)`` 通过 ``msg_name`` 返回原始目的地址,通过 ``SOL_IP/IP_RECVERR`` 或 ``SOL_IPV6/IPV6_RECVERR`` 辅助消息返回扩展错误及其发送者,并设置输出 ``MSG_ERRQUEUE``。队列为空时立即返回 ``EAGAIN``,设置 ``MSG_PEEK`` 仍消费该条错误。载荷和控制区不足分别报告 ``MSG_TRUNC`` 和 ``MSG_CTRUNC``。用户输出内存准备失败保留记录,成功读取后按下一条错误更新待处理 errno。 + +错误记录与普通数据报分别持有存储,待处理 errno 或错误队列可触发 ``POLLERR``。查询 ``SO_ERROR`` 清除待处理 errno,已排队记录继续可读。关闭相应 RECVERR 选项会清空错误队列,保留普通数据和待处理 errno。分配失败或队列达到上限时保留已有记录并继续报告 socket 错误。最后关闭释放全部记录及创建网络引用。 + +packet socket 与链路接收 +======================================== + +``AF_PACKET`` 的 ``SO_ATTACH_FILTER`` 与 ``SO_DETACH_FILTER`` 复用 classic BPF 校验和执行器。过滤结果为 0 时丢弃报文,正值限制保留长度。替换失败保留旧过滤器。``bind()`` 的零 ``sll_protocol`` 保留创建时选择的协议。 + +``SOL_PACKET`` 的 ``PACKET_ADD_MEMBERSHIP`` 与 ``PACKET_DROP_MEMBERSHIP`` 支持按创建网络、接口及六字节地址管理 ``PACKET_MR_MULTICAST``,重复加入按引用计数回收。最后关闭或设备移除释放订阅。额外链路组播按同网络、同接口的订阅执行软件接收筛选。当前其他成员类型返回 ``EINVAL``。 + +``PACKET_AUXDATA`` 在 ``recvmsg()`` 返回 ``tpacket_auxdata``,包括过滤前长度、保留长度及链路偏移。RAW 报文的网络偏移为 14,DGRAM 为 0。``SO_TIMESTAMP_OLD`` 与 ``SO_TIMESTAMP_NEW`` 提供 realtime 微秒时间戳,排队时采样,接收前才启用时延迟采样,重复 ``MSG_PEEK`` 保留同一样本。输出内存准备失败保留队列,控制缓冲区不足设置 ``MSG_CTRUNC``。 + 配置与观测 ========== ``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。 -路由多播支持链路、IPv6 地址和 IPv6 路由组,IPv4 地址及路由多播尚未实现,相应订阅返回 ``EOPNOTSUPP``。每个网络空间独立维护订阅快照,全部捕获成功后发布,最后一个订阅关闭或退订时释放。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。 +``RTM_GETNEIGH`` dump 从 socket 创建网络的 ARP 和 NDP 快照输出邻居,支持 ``AF_UNSPEC``、``AF_INET``、``AF_INET6`` 及接口索引筛选。IPv4 的 ``NDA_DST`` 转为网络字节序,缓存地址映射以 ``NUD_STALE`` 表示,IPv6 保留现有 NUD 状态。回复包含接口、目的地址及可用的链路层地址。``AF_BRIDGE`` 和 ``NTF_PROXY`` 查询返回空表及 ``NLMSG_DONE``,邻居新增、修改和删除请求返回 ``EOPNOTSUPP``。 + +``AF_BRIDGE`` 的 ``RTM_GETLINK`` dump 返回空表及 ``NLMSG_DONE``。 + +独立单路径 nexthop 按 socket 创建网络保存。``RTM_NEWNEXTHOP`` 和 ``RTM_DELNEXTHOP`` 按非零 ``NHA_ID`` 创建、替换或删除 IPv4/IPv6 对象,支持 ``NHA_OIF``、``NHA_GATEWAY`` 和 ``RTNH_F_ONLINK``。``RTM_GETNEXTHOP`` 支持按 ID 查询,以及按地址族、ID 和接口筛选的 dump,dump 以 ``NLMSG_DONE`` 结束。路由通过 ``RTA_NH_ID`` 引用同网络、同地址族的对象。替换对象同步更新依赖路由,删除对象或接口同时删除依赖路由,网络销毁释放全部对象。分配失败保留对象和路由状态。nexthop group、blackhole 和封装请求返回 ``EOPNOTSUPP``。 + +``NETLINK_GENERIC`` 提供标准控制族 ``nlctrl``,family ID 为 16,版本为 2。``CTRL_CMD_GETFAMILY`` 支持按 ``CTRL_ATTR_FAMILY_NAME`` 或 ``CTRL_ATTR_FAMILY_ID`` 查询,同时提供时优先名称。dump 返回已注册族及独立的 ``NLMSG_DONE``,回复公布查询操作和 ``notify`` 组 16。未知族通过 ``NLMSG_ERROR`` 返回 ``ENOENT``,未实现的控制命令返回 ``EOPNOTSUPP``。当前注册族仅有 ``nlctrl``,无线 ``nl80211`` 族尚未提供。socket 保留创建网络并复用端口、队列、ACK 和错误处理语义。 + +IPv4 地址查询和新增、删除通知携带 ``ifaddrmsg.ifa_flags``、32 位 ``IFA_FLAGS``、scope、``IFA_CACHEINFO`` 及可选的 ``IFA_RT_PRIORITY``。每个接口保存一个主 IPv4 地址,支持 ``IFA_F_PERMANENT``、``IFA_F_DEPRECATED`` 和 ``IFA_F_NOPREFIXROUTE``。有限有效期清除 PERMANENT,首选期到期设置 DEPRECATED,有效期到期删除地址。NOPREFIXROUTE 抑制自动前缀路由,IFA_RT_PRIORITY 设置其 metric。省略有效期时地址永久有效。 + +IPv6 地址使用相同的租期和前缀 metric 属性,支持 NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE 和 MANAGETEMPADDR。MANAGETEMPADDR 要求 /64 前缀并保存配置标志,临时隐私地址的自动生成仍待实现。自动前缀路由随地址、metric、标志和有效期维护,同时保留同前缀的其他有效地址及 RA 路由贡献。 + +IPv4/IPv6 的 ``RTM_NEWADDR`` 允许仅携带 ``NLM_F_REPLACE`` 创建地址。已有地址遇 ``NLM_F_EXCL`` 或缺少 REPLACE 时返回 ``EEXIST``,校验失败保留原配置。``RTM_NEWROUTE`` 接受 ``NLM_F_APPEND``,新增路由保留同优先级存活路由的插入顺序。修改请求的 ``NLM_F_ECHO`` 和其他修改消息上的 APPEND 返回 ``EOPNOTSUPP``。 + +IPv4/IPv6 路由支持 ``RTA_PREFSRC`` 及 ``RTNH_F_ONLINK``,首选源地址须已配置在同网络。IPv6 还支持 ``RTA_PREF`` 的低、中、高优先级与 ``RTA_EXPIRES`` 秒级有效期,到期发布删除通知。IPv6 路由身份包含目的前缀、接口、网关、nexthop ID 和 metric,同路径不同 metric 可共存。选路依次比较最长前缀、较低 metric 和较高 preference,完全相同时保留先插入路由。REPLACE 更新匹配条目,目标缺失且未携带 CREATE 时返回 ``ESRCH``。 + +IPv4 地址的 ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知投递到 ``RTNLGRP_IPV4_IFADDR``,IPv4 路由的 ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` 通知投递到 ``RTNLGRP_IPV4_ROUTE``。订阅与通知均沿用 socket 创建网络。 + +路由多播发布链路、IPv4/IPv6 地址和路由的新增、变更与删除。IPv4 路由包含直连、默认及显式路由,metric 替换发布旧路由删除和新路由添加。接口删除时,地址通知保留原接口名称与地址。每个网络空间独立维护订阅快照,全部捕获成功后替换,最后一个订阅关闭或退订时释放。快照捕获失败保留旧基线并报告 overrun,后续变更重新捕获。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。 + +路由 socket 接受 Linux 6.12 的标准组编号 1 至 36,支持 networkd 和 resolved 的订阅组合。实际事件由对应子系统提供,具体请求仍按其实现能力校验。``sockaddr_nl.nl_groups`` 表示低 32 位,``NETLINK_ADD_MEMBERSHIP`` 和 ``NETLINK_DROP_MEMBERSHIP`` 按组编号操作。初始化后的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 8 字节位图,短缓冲区复制可容纳的完整 32 位字并报告完整所需长度;uevent 位图长度为 4 字节。 + +``NETLINK_GENERIC`` 的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 4 字节位图,控制族 ``notify`` 使用组 16。 netlink socket 的 ``SO_SNDBUF`` 和 ``SO_RCVBUF`` 默认有效大小均为 65536 字节。 设置值按无符号整数裁剪到 65536 后乘二,发送和接收的最小有效值分别为 4608 @@ -61,6 +130,21 @@ raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP 错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态通过 ``clone()``、``clone3()`` 或 ``unshare()`` 的 ``CLONE_NEWNET`` 创建网络,通过 ``/proc//ns/net`` 句柄和 ``setns()`` 切换网络。授权与失败语义见 :doc:`abi`,内部生命周期与 proc 范围见 :doc:`../core-api/mount-namespaces`。 +网络 sysfs 与设备事件 +============================ + +sysfs 挂载保留创建时捕获的网络空间,后续 lookup、readdir、read 和 write 均使用该视图。任务执行 ``setns()``、``unshare()`` 或传递挂载句柄后,已有挂载继续观察原网络。``fsopen("sysfs")`` 的网络与 owner 捕获及 CREATE 授权见 :doc:`abi`。 + +``/sys/class/net/`` 是指向 canonical 设备节点的符号链接。loopback 位于 ``/sys/devices/virtual/net/lo``,物理接口位于对应 PCI function 下的 ``net/``,``device`` 链接指向 PCI 父节点,``subsystem`` 链接指向 ``/sys/class/net``。属性包含 ``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier`` 和 ``uevent``。物理接口仅在初始网络中可见。接口移除后,持有的旧 inode 在重新打开、读取或写入时返回 ``ENOENT``。 + +``RTM_SETLINK`` 与 ``RTM_NEWLINK`` 在提供正接口索引和 ``IFLA_IFNAME`` 时执行重命名,索引为 0 时按名称选择已有接口。``SIOCSIFNAME`` 使用相同的创建网络与 ``CAP_NET_ADMIN`` 授权。重命名保留接口索引和 UP 状态,更新 ioctl、socket 设备绑定查询及 sysfs 名称,并发布同网络的 ``RTM_NEWLINK`` 与携带 ``DEVPATH_OLD`` 的 ``move`` 事件。名称最长 15 字节,空白、斜线、冒号、``.`` 和 ``..`` 返回 ``EINVAL``,同网络名称冲突返回 ``EEXIST``。单个 ``%d`` 模板选择 0 至 32767 内首个空闲编号,同名请求不发布事件。``name_assign_type`` 对枚举物理名称报告 1,重命名后报告 4。 + +网络 ``uevent`` 文件由 root 所有,模式为 0644,写入遵循常规 DAC 与挂载只读策略。只读挂载也阻止 root 写入。读取提供 ``INTERFACE`` 和 ``IFINDEX``。写入接受 ``add``、``remove``、``change``、``move``、``online``、``offline``、``bind`` 或 ``unbind``,可在一个空格后附加 36 字符的十六进制 UUID,连字符位于标准位置,末尾可带一个换行。无 UUID 时事件使用 ``SYNTH_UUID=0``,提供 UUID 时按输入传递。无效 action、UUID 或 embedded NUL 返回 ``EINVAL``,并保持事件队列不变。 + +``NETLINK_KOBJECT_UEVENT`` 的网络设备事件按订阅 socket 的创建网络筛选。物理接口注册和移除分别发布 ``add`` 和 ``remove``,移除事件保留注册时的设备身份。sysfs 合成事件使用挂载捕获的网络,事件携带 action、设备路径、``SUBSYSTEM=net``、``INTERFACE`` 和 ``IFINDEX``,合成事件还携带 ``SYNTH_UUID``。其他网络的订阅者不会收到该网络事件,任务随后切换网络也保留已有 socket 的订阅范围。 + +block、PCI 和 DRM 已公开的设备 ``uevent`` 控制同样接受上述 action 与可选 UUID,权限和即时写入语义见 :doc:`abi`。事件属性取自同一设备的当前真实 inventory,``SUBSYSTEM`` 取自该设备的 ``subsystem`` 链接,并附带 ``SYNTH_UUID``。这些 global 设备事件仅投递给初始 user namespace 所拥有的网络空间中的订阅者,包含永久初始网络。网络设备事件继续严格按 socket 创建网络与挂载捕获网络隔离。 + 范围与标准 ========== diff --git a/configs/header-export.list b/configs/header-export.list index c3db0ad8..452ff9a3 100644 --- a/configs/header-export.list +++ b/configs/header-export.list @@ -26,6 +26,7 @@ include/uapi/linux/capability.h include/uapi/linux/dirent.h include/uapi/linux/epoll.h include/uapi/linux/errno.h +include/uapi/linux/errqueue.h include/uapi/linux/eventfd.h include/uapi/linux/fb.h include/uapi/linux/fcntl.h @@ -36,6 +37,7 @@ include/uapi/linux/if.h include/uapi/linux/if_addr.h include/uapi/linux/if_link.h include/uapi/linux/if_packet.h +include/uapi/linux/in.h include/uapi/linux/in6.h include/uapi/linux/input.h include/uapi/linux/inotify.h @@ -66,6 +68,9 @@ include/uapi/linux/signalfd.h include/uapi/linux/socket.h include/uapi/linux/ipv6_route.h include/uapi/linux/netlink.h +include/uapi/linux/neighbour.h +include/uapi/linux/nexthop.h +include/uapi/linux/genetlink.h include/uapi/linux/rtnetlink.h include/uapi/linux/soundcard.h include/uapi/linux/stat.h diff --git a/fs/sysfs/Kbuild b/fs/sysfs/Kbuild index 8b1b1a05..9bdfe056 100644 --- a/fs/sysfs/Kbuild +++ b/fs/sysfs/Kbuild @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 # Objects are owned by this directory; child modules own their own lists. -obj-y := mount.o sysfs.o parameters.o +obj-y := mount.o sysfs.o parameters.o network.o uevent.o include $(srctree)/scripts/Makefile.module diff --git a/fs/sysfs/internal.h b/fs/sysfs/internal.h index c64f5406..1162cbeb 100644 --- a/fs/sysfs/internal.h +++ b/fs/sysfs/internal.h @@ -3,6 +3,63 @@ #define RELIEFNT_SYSFS_INTERNAL_H #include #include +#include +#include + +enum attribute { + A_DIR, + A_LINK, + A_DMI, + A_CPUSET, + A_CPU_ONLINE, + A_TTY_ACTIVE, + A_PACKAGE, + A_CORE, + A_SIBLINGS, + A_PACKAGE_LIST, + A_PCI_VENDOR, + A_PCI_DEVICE, + A_PCI_CLASS, + A_PCI_REV, + A_PCI_SUBVENDOR, + A_PCI_SUBDEVICE, + A_PCI_ALIAS, + A_PCI_CONFIG, + A_FB_NAME, + A_FB_SIZE, + A_FB_BPP, + A_FB_STRIDE, + A_FB_MODES, + A_DRM_MODES, + A_DRM_EDID, + A_CONNECTED, + A_ENABLED, + A_PCI_UEVENT, + A_BLOCK_NUMBER, + A_BLOCK_TEXT, + A_BLOCK_FS_TEXT, + A_DRM_DEV, + A_DRM_UEVENT, + A_DRM_RENDER_DEV, + A_DRM_RENDER_UEVENT, + A_MODULE_TEXT, + A_MODULE_NUMBER, + A_MODULE_PARAMETER, + A_ERROR +}; +struct sys_node { + const char *path; + enum attribute attr; + uint32_t index; + const char *target; + const char *parameter; + uint64_t value; +}; +typedef int (*sys_visit)(const struct sys_node *, void *); + +struct sysfs_instance { + struct net_namespace *net_ns; +}; #define SYSFS_TTY0_ACTIVE "/sys/devices/virtual/tty/tty0/active" @@ -40,4 +97,66 @@ int sysfs_parameter_truncate(const char *path,uint64_t length); * Execution ownership required; no references escape the function. */ int sysfs_parameter_permissions(const char *path,const struct storage_node *node,struct reliefos_permissions *value,bool write); + +/** @brief Resolve a key using a mount's retained network view. + * @param instance Borrowed sysfs_instance. @param path Intrinsic key. + * @param node Required metadata output. @return Zero or negative errno. + * Execution ownership serializes inventory access without transferring pins. + */ +int sysfs_lookup_instance(void *instance,const char *path,struct storage_node *node); +/** @brief Read inventory in the retained network view. + * @param instance Borrowed sysfs_instance. @param path Intrinsic key. + * @param offset Byte offset. @param buffer Output buffer. + * @param capacity Buffer size. @param read Required byte count. + * @return Zero or negative errno. No allocation or ownership transfer. + */ +int sysfs_read_instance(void *instance,const char *path,uint64_t offset, + void *buffer,uint32_t capacity,uint32_t *read); +/** @brief Enumerate children in the retained network view. + * @param instance Borrowed sysfs_instance. @param path Intrinsic directory. + * @param cursor Mutable enumeration offset. @param entry Required output. + * @return One entry, zero EOF or negative errno under execution ownership. + */ +int sysfs_readdir_instance(void *instance,const char *path,uint64_t *cursor, + struct reliefos_dir_entry *entry); +/** @brief Read a relative device link in the retained network view. + * @param instance Borrowed sysfs_instance. @param path Intrinsic link. + * @param buffer Output bytes. @param capacity Available bytes. + * @return Link length or negative errno. No ownership transfer. + */ +int sysfs_readlink_instance(void *instance,const char *path,char *buffer,uint32_t capacity); +/** @brief Visit live network devices and their attributes without allocation. + * @param ns Borrowed retained scope. @param visit Synchronous node consumer. + * @param context Consumer data. @return Visitor result under execution ownership. + */ +int sysfs_network_walk(struct net_namespace *ns,sys_visit visit,void *context); +/** @brief Identify intrinsic paths belonging to network class/device inventory. + * @param path Borrowed intrinsic path. @return True for a network key. + */ +bool sysfs_network_key(const char *path); +/** @brief Identify a canonical network device's uevent control. + * @param path Borrowed intrinsic path. @return True for a network uevent key. + */ +bool sysfs_network_uevent_key(const char *path); +/** @brief Identify a canonical device uevent control for store and mode policy. + * @param path Borrowed intrinsic path whose live inode is checked by the provider. + * @return True for a device uevent key. No lookup or allocation. + */ +bool sysfs_uevent_key(const char *path); +/** @brief Emit a parsed action for a live interface in the mount's network. + * @param instance Borrowed retained sysfs view. @param path Intrinsic control key. + * @param action Validated action. @param uuid Validated synthetic UUID or 0. + * @return Zero or ENOENT. Execution ownership stabilizes the interface identity. + */ +int sysfs_network_uevent(void *instance,const char *path,const char *action,const char *uuid); +/** @brief Store a device uevent action or an ordinary module parameter. + * @param instance Borrowed retained sysfs view. @param path Live intrinsic key. + * @param offset Ignored whole-value offset. @param buffer Validated bytes. + * @param length Byte count. @param written Required count, cleared on failure. + * @return Zero or negative errno. Execution-owned, network events retain the + * mount's scope and global device events retain initial-user delivery policy. + * All property bytes are copied before return. + */ +int sysfs_write_instance(void *instance,const char *path,uint64_t offset, + const void *buffer,uint32_t length,uint32_t *written); #endif diff --git a/fs/sysfs/mount.c b/fs/sysfs/mount.c index 2655cbc2..b5be47a9 100644 --- a/fs/sysfs/mount.c +++ b/fs/sysfs/mount.c @@ -7,6 +7,7 @@ #include #include #include +#include #include "internal.h" #include @@ -138,20 +139,59 @@ static void sysfs_foreground_close(void *state) kernel_free(state); } -/** @brief Construct a detached sysfs mount with descriptor-authorized stores and VT events. - * @param out Required empty output, receiving one owned mount on success. - * @return Zero or negative errno with balanced generated inode identities. - * Execution-owned task context; inventory stays immutable, while parameter - * modes and setters follow their owning module descriptors. +/** @brief Retain the network captured by this generated filesystem instance. + * @param instance Copied sysfs view, acquired before any provider lookup. */ -int sysfs_create_vfs_mount(struct vfs_mount **out) +static void sysfs_instance_get(void *instance) +{ + struct sysfs_instance *view=instance; + net_namespace_get(view->net_ns); +} + +/** @brief Release the network after the final generated inode is destroyed. + * @param instance Owned sysfs view whose reference is consumed once. + */ +static void sysfs_instance_put(void *instance) +{ + struct sysfs_instance *view=instance; + net_namespace_put(view->net_ns); +} + +/** @brief Reject retained network keys after their original interface disappears. + * @param instance Borrowed mount view. @param name Intrinsic generated path. + * @param identity Module identity handled by the separate identity callbacks. + * @return Zero or negative lookup errno under execution ownership. + * Interface indices are never reused within the captured network. + */ +static int sysfs_key_authorize(void *instance,const char *name,void *identity) { - static const struct vfs_pseudo_provider provider={.root="/sys",.filesystem="sysfs",.lookup=sysfs_lookup, - .read=sysfs_read,.write=sysfs_parameter_write,.truncate=sysfs_parameter_truncate, - .readdir=sysfs_readdir,.readlink=sysfs_readlink,.permissions=sysfs_parameter_permissions, + (void)identity; + if(!sysfs_network_key(name))return 0; + struct storage_node node; + return sysfs_lookup_instance(instance,name,&node); +} + +/** @copydoc sysfs_create_vfs_mount_in_net */ +int sysfs_create_vfs_mount_in_net(struct net_namespace *ns,struct vfs_mount **out) +{ + static const struct vfs_pseudo_provider provider={.root="/sys",.filesystem="sysfs", + .lookup_instance=sysfs_lookup_instance,.read_instance=sysfs_read_instance, + .write_instance=sysfs_write_instance,.truncate=sysfs_parameter_truncate, + .readdir_instance=sysfs_readdir_instance,.readlink_instance=sysfs_readlink_instance, + .permissions=sysfs_parameter_permissions,.immediate_write=sysfs_uevent_key, + .get_instance=sysfs_instance_get,.put_instance=sysfs_instance_put, + .authorize=sysfs_key_authorize, .get_identity=sysfs_key_identity,.identity_alive=sysfs_key_alive,.put_identity=sysfs_key_put, .open=sysfs_foreground_open,.read_open=sysfs_foreground_read, .poll_open=sysfs_foreground_poll,.close=sysfs_foreground_close }; - return vfs_pseudo_mount_new(&provider,out); + const struct sysfs_instance view={.net_ns=ns}; + return vfs_pseudo_mount_new_with_state(&provider,&view,sizeof(view),out); +} + +/** @copydoc sysfs_create_vfs_mount */ +int sysfs_create_vfs_mount(struct vfs_mount **out) +{ + const struct task *task=sched_current_task(); + return sysfs_create_vfs_mount_in_net(task ? task->net_ns : NULL,out); } diff --git a/fs/sysfs/network.c b/fs/sysfs/network.c new file mode 100644 index 00000000..a4f1bf01 --- /dev/null +++ b/fs/sysfs/network.c @@ -0,0 +1,174 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "internal.h" +#include +#include +#include +#include + +/** @brief Visit a copied network attribute with no retained caller pointers. + * @param visit Synchronous consumer. @param context Consumer data. + * @param base Canonical directory. @param suffix Local attribute suffix. + * @param type Generated node kind. @param value Numeric value or read errno. + * @param text Optional text/link value. @return Consumer result. + */ +static int network_emit(sys_visit visit,void *context,const char *base,const char *suffix, + enum attribute type,uint64_t value,const char *text) +{ + char path[RELIEFOS_FS_PATH_LEN]; + struct text_stream stream={.buffer=path,.capacity=sizeof(path)-1}; + text_string(&stream,base);text_string(&stream,suffix);path[stream.written]=0; + const struct sys_node node={.path=path,.attr=type,.value=value,.target=text}; + return visit(&node,context); +} + +/** @brief Format the Linux colon-separated six-byte hardware address. + * @param out Required 18-byte output. @param mac Borrowed six bytes. + */ +static void network_address(char out[18],const uint8_t mac[6]) +{ + struct text_stream stream={.buffer=out,.capacity=17}; + for(unsigned i=0;i<6;++i) { + if(i)text_string(&stream,":"); + text_hex(&stream,mac[i],2); + } + out[stream.written]=0; +} + +/** @brief Avoid duplicate net directories for multiple ports on one PCI function. + * @param ns Borrowed network. @param iface Current live interface. + * @return True if an earlier live interface already emitted the same parent. + */ +static bool network_parent_emitted(struct net_namespace *ns,const struct net_interface *iface) +{ + for(uint32_t index=net_interface_next(ns,NET_IF_LOOPBACK);index && indexindex; + index=net_interface_next(ns,index)) { + const struct net_interface *earlier=net_interface_get(ns,index); + if(earlier && earlier->device.present && earlier->device.bus==iface->device.bus && + earlier->device.slot==iface->device.slot && earlier->device.function==iface->device.function) + return true; + } + return false; +} + +/** @copydoc sysfs_network_walk */ +int sysfs_network_walk(struct net_namespace *ns,sys_visit visit,void *context) +{ + int rc=network_emit(visit,context,"/sys/class/net","",A_DIR,0,NULL); + if(!rc)rc=network_emit(visit,context,"/sys/devices/virtual/net","",A_DIR,0,NULL); + if(rc)return rc; + for(uint32_t index=net_interface_next(ns,0);index;index=net_interface_next(ns,index)) { + const struct net_interface *iface=net_interface_get(ns,index); + char devpath[NET_IF_DEVICE_PATH_LEN],name[NET_IF_NAME_LEN]; + if(!iface || net_interface_device_path(ns,index,devpath) || + !net_interface_name(ns,index,name))continue; + char base[RELIEFOS_FS_PATH_LEN],alias[RELIEFOS_FS_PATH_LEN]; + struct text_stream text={.buffer=base,.capacity=sizeof(base)-1}; + text_string(&text,"/sys");text_string(&text,devpath);base[text.written]=0; + if(iface->device.present && !network_parent_emitted(ns,iface)) { + char parent[RELIEFOS_FS_PATH_LEN]; + size_t length=__builtin_strlen(base)-__builtin_strlen(name)-1; + __builtin_memcpy(parent,base,length);parent[length]=0; + if((rc=network_emit(visit,context,parent,"",A_DIR,0,NULL)))return rc; + } + text=(struct text_stream){.buffer=alias,.capacity=sizeof(alias)-1}; + text_string(&text,"/sys/class/net/");text_string(&text,name);alias[text.written]=0; + char target[RELIEFOS_FS_PATH_LEN]; + text=(struct text_stream){.buffer=target,.capacity=sizeof(target)-1}; + text_string(&text,"../..");text_string(&text,devpath);target[text.written]=0; + if((rc=network_emit(visit,context,alias,"",A_LINK,0,target)))return rc; + char subsystem[48]; + text=(struct text_stream){.buffer=subsystem,.capacity=sizeof(subsystem)-1}; + for(const char *p=devpath;*p;++p)if(*p=='/')text_string(&text,"../"); + text_string(&text,"class/net");subsystem[text.written]=0; + if((rc=network_emit(visit,context,base,"",A_DIR,0,NULL)) || + (rc=network_emit(visit,context,base,"/subsystem",A_LINK,0,subsystem)))return rc; + if(iface->device.present && + (rc=network_emit(visit,context,base,"/device",A_LINK,0,"../..")))return rc; + + bool loopback=index==NET_IF_LOOPBACK; + bool carrier=loopback || netdev_is_ready(index); + uint32_t flags=loopback ? IFF_LOOPBACK : IFF_BROADCAST|IFF_MULTICAST; + if(iface->up)flags|=IFF_UP; + if(iface->up && carrier)flags|=IFF_RUNNING; + if(carrier && (!loopback || iface->up))flags|=0x10000u; + char flag_text[16],address[18],broadcast[18],event[64]; + text=(struct text_stream){.buffer=flag_text,.capacity=sizeof(flag_text)-1}; + text_string(&text,"0x");text_hex(&text,flags,flags>65535 ? 5 : 4);flag_text[text.written]=0; + static const uint8_t zero[6],all[6]={255,255,255,255,255,255}; + network_address(address,loopback ? zero : iface->device.mac); + network_address(broadcast,loopback ? zero : all); + text=(struct text_stream){.buffer=event,.capacity=sizeof(event)-1}; + text_string(&text,"INTERFACE=");text_string(&text,name); + text_string(&text,"\nIFINDEX=");text_unsigned(&text,index);event[text.written]=0; + const char *operstate="down"; + if(iface->up)operstate=loopback ? "unknown" : carrier ? "up" : "down"; + const struct { + const char *suffix; + enum attribute type; + uint64_t value; + const char *text; + } attributes[]={ + {"/ifindex",A_BLOCK_NUMBER,index,NULL}, + {"/iflink",A_BLOCK_NUMBER,index,NULL}, + {"/address",A_BLOCK_TEXT,0,address}, + {"/broadcast",A_BLOCK_TEXT,0,broadcast}, + {"/addr_len",A_BLOCK_NUMBER,6,NULL}, + {"/type",A_BLOCK_NUMBER,loopback ? 772 : 1,NULL}, + {"/mtu",A_BLOCK_NUMBER,loopback ? 65536 : 1500,NULL}, + {"/flags",A_BLOCK_TEXT,0,flag_text}, + {"/operstate",A_BLOCK_TEXT,0,operstate}, + {"/carrier",iface->up ? A_BLOCK_NUMBER : A_ERROR,iface->up ? carrier : EINVAL,NULL}, + {"/dormant",iface->up ? A_BLOCK_NUMBER : A_ERROR,iface->up ? 0 : EINVAL,NULL}, + {"/link_mode",A_BLOCK_NUMBER,0,NULL}, + {"/addr_assign_type",A_BLOCK_NUMBER,0,NULL}, + {"/name_assign_type",A_BLOCK_NUMBER,iface->name_assign_type,NULL}, + {"/tx_queue_len",A_BLOCK_NUMBER,1000,NULL}, + {"/netdev_group",A_BLOCK_NUMBER,0,NULL}, + {"/dev_port",A_BLOCK_NUMBER,0,NULL}, + {"/dev_id",A_BLOCK_TEXT,0,"0x0"}, + {"/uevent",A_BLOCK_TEXT,0,event}, + }; + for(unsigned i=0;i=7 && !__builtin_strcmp(path+length-7,"/uevent"); +} + +/** @copydoc sysfs_network_uevent */ +int sysfs_network_uevent(void *instance,const char *path,const char *action,const char *uuid) +{ + struct net_namespace *ns=((struct sysfs_instance *)instance)->net_ns; + uint32_t found=0; + for(uint32_t index=net_interface_next(ns,0);index;index=net_interface_next(ns,index)) { + char device[NET_IF_DEVICE_PATH_LEN]; + if(net_interface_device_path(ns,index,device))continue; + size_t size=__builtin_strlen(device); + if(!__builtin_strncmp(path,"/sys",4) && !__builtin_strncmp(path+4,device,size) && + !__builtin_strcmp(path+4+size,"/uevent")){found=index;break;} + } + if(!found)return -ENOENT; + net_interface_uevent(ns,found,action,uuid);return 0; +} diff --git a/fs/sysfs/parameters.c b/fs/sysfs/parameters.c index 7b59dc1c..f502ce88 100644 --- a/fs/sysfs/parameters.c +++ b/fs/sysfs/parameters.c @@ -3,6 +3,14 @@ #include #include +/** @copydoc sysfs_uevent_key */ +bool sysfs_uevent_key(const char *path) +{ + if(__builtin_strncmp(path,"/sys/devices/",13))return false; + size_t length=__builtin_strlen(path); + return length>=20 && !__builtin_strcmp(path+length-7,"/uevent"); +} + /** @brief Decode a generated parameter key without global pathname routing. * @param path Borrowed intrinsic sysfs key. * @param module Required fixed-size module output. @@ -57,6 +65,7 @@ int sysfs_parameter_write(const char *path,uint64_t offset,const void *buffer,ui */ int sysfs_parameter_truncate(const char *path,uint64_t length) { + if(sysfs_uevent_key(path))return length ? -EINVAL : 0; struct module_parameter_info info;int rc=sysfs_parameter_info(path,&info); if(rc)return rc==-ENOENT ? -EROFS : rc; if(!(info.permissions&0222u))return -EIO; @@ -73,6 +82,10 @@ int sysfs_parameter_truncate(const char *path,uint64_t length) int sysfs_parameter_permissions(const char *path,const struct storage_node *node,struct reliefos_permissions *value,bool write) { if(write)return -EROFS; + if(sysfs_uevent_key(path)) { + *value=(struct reliefos_permissions){0644,0,0}; + return 0; + } char module[MODULE_NAME_LEN];const char *name; if(!sysfs_parameter_key(path,module,&name))return fs_virtual_permissions(path,node,value,false); struct module_parameter_info info;int rc=sysfs_parameter_info(path,&info); diff --git a/fs/sysfs/sysfs.c b/fs/sysfs/sysfs.c index 613959c4..4ef59d6d 100644 --- a/fs/sysfs/sysfs.c +++ b/fs/sysfs/sysfs.c @@ -12,6 +12,7 @@ #include #include #include +#include #include "../ext_common/storage_ext4_types.h" #include "internal.h" @@ -24,55 +25,6 @@ static const char *dmi_fields[] = {"bios_vendor", "bios_version", "bios_dat "product_name", "product_version", "product_serial", "product_uuid", "product_sku", "product_family", "board_vendor", "board_name", "board_version", "board_serial", "chassis_vendor"}; -enum attribute { - A_DIR, - A_LINK, - A_DMI, - A_CPUSET, - A_CPU_ONLINE, - A_TTY_ACTIVE, - A_PACKAGE, - A_CORE, - A_SIBLINGS, - A_PACKAGE_LIST, - A_PCI_VENDOR, - A_PCI_DEVICE, - A_PCI_CLASS, - A_PCI_REV, - A_PCI_SUBVENDOR, - A_PCI_SUBDEVICE, - A_PCI_ALIAS, - A_PCI_CONFIG, - A_FB_NAME, - A_FB_SIZE, - A_FB_BPP, - A_FB_STRIDE, - A_FB_MODES, - A_DRM_MODES, - A_DRM_EDID, - A_CONNECTED, - A_ENABLED, - A_PCI_UEVENT, - A_BLOCK_NUMBER, - A_BLOCK_TEXT, - A_BLOCK_FS_TEXT, - A_DRM_DEV, - A_DRM_UEVENT, - A_DRM_RENDER_DEV, - A_DRM_RENDER_UEVENT, - A_MODULE_TEXT, - A_MODULE_NUMBER, - A_MODULE_PARAMETER -}; -struct sys_node { - const char *path; - enum attribute attr; - uint32_t index; - const char *target; - const char *parameter; - uint64_t value; -}; -typedef int (*sys_visit)(const struct sys_node *, void *); /** @brief Cache PCI identities once, under the caller's kernel execution lock. */ static int sys_pci_init(void) { @@ -460,7 +412,7 @@ static int sys_modules_walk(sys_visit visit,void *context) return 0; } /** @brief Walk sysfs nodes, including the empty cgroup2 mountpoint. */ -static int sys_walk(sys_visit visit, void *ctx) +static int sys_walk(struct net_namespace *ns, sys_visit visit, void *ctx) { static const char *dirs[] = {"/sys", "/sys/fs", @@ -501,6 +453,7 @@ static int sys_walk(sys_visit visit, void *ctx) "../../devices/virtual/tty/tty0")) || (ret = sys_emit(visit, ctx, SYSFS_TTY0_ACTIVE, A_TTY_ACTIVE, foreground, NULL)))) return ret; + if((ret=sysfs_network_walk(ns,visit,ctx))) return ret; if((ret=sys_modules_walk(visit,ctx))) return ret; const struct platform_dmi_info *dmi = platform_dmi(); char path[RELIEFOS_FS_PATH_LEN], target[RELIEFOS_FS_PATH_LEN]; @@ -588,6 +541,8 @@ static int sys_walk(sys_visit visit, void *ctx) if ((ret = sys_emit(visit, ctx, path, A_DRM_UEVENT, i, 0))) return ret; sys_pci_path(path, "/sys/devices/pci0000:00/", i, "/drm/card0/device"); if ((ret = sys_emit(visit, ctx, path, A_LINK, i, "../.."))) return ret; + sys_pci_path(path, "/sys/devices/pci0000:00/", i, "/drm/card0/subsystem"); + if ((ret = sys_emit(visit, ctx, path, A_LINK, i, "../../../../../class/drm"))) return ret; sys_pci_path(target, "../../devices/pci0000:00/", i, "/drm/card0"); if ((ret = sys_emit(visit, ctx, "/sys/class/drm/card0", A_LINK, i, target))) return ret; @@ -610,6 +565,10 @@ static int sys_walk(sys_visit visit, void *ctx) "/drm/renderD128/device"); if ((ret = sys_emit(visit, ctx, path, A_LINK, i, "../.."))) return ret; + sys_pci_path(path, "/sys/devices/pci0000:00/", i, + "/drm/renderD128/subsystem"); + if ((ret = sys_emit(visit, ctx, path, A_LINK, i, "../../../../../class/drm"))) + return ret; sys_pci_path(target, "../../devices/pci0000:00/", i, "/drm/renderD128"); if ((ret = sys_emit(visit, ctx, "/sys/class/drm/renderD128", @@ -928,6 +887,8 @@ static int sys_match(const struct sys_node *n, void *context) return -22; text_string(&r->stream, n->target); } else if (r->read) { + if (n->attr == A_ERROR) + return -(int)n->value; if (n->attr == A_DIR) return -21; if (n->attr == A_LINK) @@ -941,14 +902,14 @@ static int sys_match(const struct sys_node *n, void *context) return 1; } /** @brief Resolve a generated sysfs node without following its final link. */ -int sysfs_lookup(const char *path, struct storage_node *out) +int sysfs_lookup_instance(void *instance, const char *path, struct storage_node *out) { struct sys_request r = {.path = path, .node = out}; - int ret = sys_walk(sys_match, &r); + int ret = sys_walk(((struct sysfs_instance *)instance)->net_ns, sys_match, &r); return ret == 1 ? 0 : ret < 0 ? ret : -2; } /** @brief Read a bounded attribute range; caller holds the kernel execution lock. */ -int sysfs_read(const char *path, uint64_t offset, void *buffer, uint32_t length, uint32_t *out_read) +int sysfs_read_instance(void *instance, const char *path, uint64_t offset, void *buffer, uint32_t length, uint32_t *out_read) { if (out_read) *out_read = 0; @@ -956,19 +917,19 @@ int sysfs_read(const char *path, uint64_t offset, void *buffer, uint32_t length, return -22; struct sys_request r = { .path = path, .read = true, .stream = {.offset = offset, .buffer = buffer, .capacity = length}}; - int ret = sys_walk(sys_match, &r); + int ret = sys_walk(((struct sysfs_instance *)instance)->net_ns, sys_match, &r); if (out_read && ret == 1) *out_read = r.stream.written; return ret == 1 ? 0 : ret < 0 ? ret : -2; } /** @brief Return truncated symlink bytes, without terminating NUL. */ -int sysfs_readlink(const char *path, char *buffer, uint32_t capacity) +int sysfs_readlink_instance(void *instance, const char *path, char *buffer, uint32_t capacity) { if (!buffer || !capacity) return -22; struct sys_request r = { .path = path, .link = true, .stream = {.buffer = buffer, .capacity = capacity}}; - int ret = sys_walk(sys_match, &r); + int ret = sys_walk(((struct sysfs_instance *)instance)->net_ns, sys_match, &r); return ret == 1 ? (int)r.stream.written : ret < 0 ? ret : -2; } struct sys_directory { @@ -1000,19 +961,56 @@ static int sys_child(const struct sys_node *n, void *context) return 1; } /** @brief Enumerate exactly the same immediate children visible to lookup. */ -int sysfs_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry *entry) +int sysfs_readdir_instance(void *instance, const char *path, uint64_t *offset, struct reliefos_dir_entry *entry) { if (!path || !offset || !entry) return -22; struct storage_node node; - int ret = sysfs_lookup(path, &node); + int ret = sysfs_lookup_instance(instance, path, &node); if (ret < 0) return ret; if (node.type != RELIEFOS_FS_TYPE_DIR) return -20; struct sys_directory d = {path, (uint32_t)__builtin_strlen(path), *offset, entry}; - ret = sys_walk(sys_child, &d); + ret = sys_walk(((struct sysfs_instance *)instance)->net_ns, sys_child, &d); if (ret == 1) ++*offset; return ret; } + +/** @brief Capture the caller's network for the legacy direct inventory API. + * @return Borrowed current scope, or the permanent initial network before tasks. + */ +static struct sysfs_instance sysfs_current_view(void) +{ + const struct task *task=sched_current_task(); + return (struct sysfs_instance){.net_ns=task ? task->net_ns : NULL}; +} + +/** @copydoc sysfs_lookup */ +int sysfs_lookup(const char *path,struct storage_node *out) +{ + struct sysfs_instance view=sysfs_current_view(); + return sysfs_lookup_instance(&view,path,out); +} + +/** @copydoc sysfs_read */ +int sysfs_read(const char *path,uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read) +{ + struct sysfs_instance view=sysfs_current_view(); + return sysfs_read_instance(&view,path,offset,buffer,capacity,read); +} + +/** @copydoc sysfs_readlink */ +int sysfs_readlink(const char *path,char *buffer,uint32_t capacity) +{ + struct sysfs_instance view=sysfs_current_view(); + return sysfs_readlink_instance(&view,path,buffer,capacity); +} + +/** @copydoc sysfs_readdir */ +int sysfs_readdir(const char *path,uint64_t *cursor,struct reliefos_dir_entry *entry) +{ + struct sysfs_instance view=sysfs_current_view(); + return sysfs_readdir_instance(&view,path,cursor,entry); +} diff --git a/fs/sysfs/uevent.c b/fs/sysfs/uevent.c new file mode 100644 index 00000000..99c171af --- /dev/null +++ b/fs/sysfs/uevent.c @@ -0,0 +1,91 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "internal.h" +#include +#include + +/** @brief Decode one action and optional RFC 4122 UUID from a sysfs store. + * @param buffer Validated bytes. @param length Byte count. + * @param action Receives a validated kobject action. + * @param uuid Receives the synthetic UUID, or 0 for an ordinary trigger. + * @return Zero or EINVAL with no event emitted. No allocation. + */ +static int sysfs_parse_uevent(const void *buffer,uint32_t length,char action[8],char uuid[37]) +{ + const char *bytes=buffer; + if(length && bytes[length-1]=='\n')--length; + uint32_t split=0; + while(split=8)return -EINVAL; + __builtin_memcpy(action,bytes,split);action[split]=0; + static const char *const actions[]={"add","remove","change","move","online","offline","bind","unbind"}; + bool valid=false; + for(unsigned i=0;i='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F')))return -EINVAL; + uuid[i]=c; + } + uuid[36]=0;return 0; +} + +/** @brief Copy a device's live subsystem and NUL-separated event properties. + * @param instance Borrowed sysfs view. @param path Canonical uevent key. + * @param uuid Validated synthetic UUID or 0. @param action Validated action. + * @return Zero or negative lookup/size errno with no event on failure. + * Execution ownership stabilizes inventory. Stack buffers never escape. + */ +static int sysfs_device_uevent(void *instance,const char *path,const char *uuid,const char *action) +{ + char sibling[RELIEFOS_FS_PATH_LEN],subsystem[RELIEFOS_FS_PATH_LEN]; + size_t size=__builtin_strlen(path); + if(size+sizeof("subsystem")-sizeof("uevent")>=sizeof(sibling))return -ENAMETOOLONG; + __builtin_memcpy(sibling,path,size-6); + __builtin_memcpy(sibling+size-6,"subsystem",sizeof("subsystem")); + int rc=sysfs_readlink_instance(instance,sibling,subsystem,sizeof(subsystem)-1); + if(rc<0)return rc; + if((uint32_t)rc>=sizeof(subsystem)-1)return -E2BIG; + subsystem[rc]=0; + const char *name=subsystem; + for(const char *p=subsystem;*p;++p)if(*p=='/')name=p+1; + if(!*name)return -EINVAL; + + char properties[384]; + uint32_t count=0,capacity=sizeof(properties)-sizeof("SYNTH_UUID=")-37; + rc=sysfs_read_instance(instance,path,0,properties,capacity,&count); + if(rc)return rc; + if(count==capacity)return -E2BIG; + for(uint32_t i=0;i + +#define GENL_NAMSIZ 16 +#define GENL_MIN_ID NLMSG_MIN_TYPE +#define GENL_MAX_ID 1023 +#define GENL_ID_CTRL NLMSG_MIN_TYPE +#define GENL_ID_VFS_DQUOT (NLMSG_MIN_TYPE + 1) +#define GENL_ID_PMCRAID (NLMSG_MIN_TYPE + 2) +#define GENL_START_ALLOC (NLMSG_MIN_TYPE + 3) +struct genlmsghdr { uint8_t cmd, version; uint16_t reserved; }; +#define GENL_HDRLEN NLMSG_ALIGN(sizeof(struct genlmsghdr)) +#define GENL_ADMIN_PERM 0x01 +#define GENL_CMD_CAP_DO 0x02 +#define GENL_CMD_CAP_DUMP 0x04 +#define GENL_CMD_CAP_HASPOL 0x08 +#define GENL_UNS_ADMIN_PERM 0x10 + +enum { + CTRL_CMD_UNSPEC, CTRL_CMD_NEWFAMILY, CTRL_CMD_DELFAMILY, CTRL_CMD_GETFAMILY, + CTRL_CMD_NEWOPS, CTRL_CMD_DELOPS, CTRL_CMD_GETOPS, CTRL_CMD_NEWMCAST_GRP, + CTRL_CMD_DELMCAST_GRP, CTRL_CMD_GETMCAST_GRP, CTRL_CMD_GETPOLICY, __CTRL_CMD_MAX +}; +#define CTRL_CMD_MAX (__CTRL_CMD_MAX - 1) +enum { + CTRL_ATTR_UNSPEC, CTRL_ATTR_FAMILY_ID, CTRL_ATTR_FAMILY_NAME, CTRL_ATTR_VERSION, + CTRL_ATTR_HDRSIZE, CTRL_ATTR_MAXATTR, CTRL_ATTR_OPS, CTRL_ATTR_MCAST_GROUPS, + CTRL_ATTR_POLICY, CTRL_ATTR_OP_POLICY, CTRL_ATTR_OP, __CTRL_ATTR_MAX +}; +#define CTRL_ATTR_MAX (__CTRL_ATTR_MAX - 1) +enum { CTRL_ATTR_OP_UNSPEC, CTRL_ATTR_OP_ID, CTRL_ATTR_OP_FLAGS, __CTRL_ATTR_OP_MAX }; +#define CTRL_ATTR_OP_MAX (__CTRL_ATTR_OP_MAX - 1) +enum { + CTRL_ATTR_MCAST_GRP_UNSPEC, CTRL_ATTR_MCAST_GRP_NAME, CTRL_ATTR_MCAST_GRP_ID, + __CTRL_ATTR_MCAST_GRP_MAX +}; +#define CTRL_ATTR_MCAST_GRP_MAX (__CTRL_ATTR_MCAST_GRP_MAX - 1) +enum { + CTRL_ATTR_POLICY_UNSPEC, CTRL_ATTR_POLICY_DO, CTRL_ATTR_POLICY_DUMP, + __CTRL_ATTR_POLICY_DUMP_MAX +}; +#define CTRL_ATTR_POLICY_DUMP_MAX (__CTRL_ATTR_POLICY_DUMP_MAX - 1) +#define CTRL_ATTR_POLICY_MAX (__CTRL_ATTR_POLICY_DUMP_MAX - 1) +_Static_assert(sizeof(struct genlmsghdr) == 4, "Linux genlmsghdr"); +#endif diff --git a/include/uapi/linux/if.h b/include/uapi/linux/if.h index 89db8a57..c6066113 100644 --- a/include/uapi/linux/if.h +++ b/include/uapi/linux/if.h @@ -37,6 +37,7 @@ struct rtentry { #define SIOCSIFNETMASK 0x891c #define SIOCGIFMTU 0x8921 #define SIOCSIFMTU 0x8922 +#define SIOCSIFNAME 0x8923 #define SIOCGIFTXQLEN 0x8942 #define SIOCSIFTXQLEN 0x8943 #define SIOCGIFHWADDR 0x8927 diff --git a/include/uapi/linux/if_addr.h b/include/uapi/linux/if_addr.h index 61c7bf50..2e663061 100644 --- a/include/uapi/linux/if_addr.h +++ b/include/uapi/linux/if_addr.h @@ -10,9 +10,12 @@ struct ifa_cacheinfo { uint32_t ifa_prefered, ifa_valid, cstamp, tstamp; }; #define IFA_BROADCAST 4 #define IFA_CACHEINFO 6 #define IFA_FLAGS 8 +#define IFA_RT_PRIORITY 9 #define IFA_F_NODAD 0x02 #define IFA_F_DADFAILED 0x08 #define IFA_F_DEPRECATED 0x20 #define IFA_F_TENTATIVE 0x40 #define IFA_F_PERMANENT 0x80 +#define IFA_F_MANAGETEMPADDR 0x100 +#define IFA_F_NOPREFIXROUTE 0x200 #endif diff --git a/include/uapi/linux/if_packet.h b/include/uapi/linux/if_packet.h index ac1b3cd8..fe3694c3 100644 --- a/include/uapi/linux/if_packet.h +++ b/include/uapi/linux/if_packet.h @@ -14,4 +14,25 @@ struct sockaddr_ll { #define PACKET_MULTICAST 2 #define PACKET_OTHERHOST 3 #define PACKET_OUTGOING 4 + +#define PACKET_ADD_MEMBERSHIP 1 +#define PACKET_DROP_MEMBERSHIP 2 +#define PACKET_AUXDATA 8 +#define PACKET_MR_MULTICAST 0 +#define PACKET_MR_PROMISC 1 +#define PACKET_MR_ALLMULTI 2 +#define TP_STATUS_USER 1u + +struct packet_mreq { + int32_t mr_ifindex; + uint16_t mr_type, mr_alen; + uint8_t mr_address[8]; +}; + +struct tpacket_auxdata { + uint32_t tp_status, tp_len, tp_snaplen; + uint16_t tp_mac, tp_net, tp_vlan_tci, tp_vlan_tpid; +}; +_Static_assert(sizeof(struct packet_mreq) == 16, "Linux packet_mreq size"); +_Static_assert(sizeof(struct tpacket_auxdata) == 20, "Linux tpacket_auxdata size"); #endif diff --git a/include/uapi/linux/in.h b/include/uapi/linux/in.h new file mode 100644 index 00000000..8dc21d7b --- /dev/null +++ b/include/uapi/linux/in.h @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_UAPI_LINUX_IN_H +#define RELIEFNT_UAPI_LINUX_IN_H + +#include + +/* Linux IPv4 socket ABI. Address fields use network byte order. */ +struct in_addr { uint32_t s_addr; }; +struct ip_mreq { struct in_addr imr_multiaddr, imr_interface; }; +struct ip_mreqn { + struct in_addr imr_multiaddr, imr_address; + int32_t imr_ifindex; +}; +struct in_pktinfo { + int32_t ipi_ifindex; + struct in_addr ipi_spec_dst, ipi_addr; +}; + +#define IPPROTO_IP 0 +#define SOL_IP 0 +#define IP_TOS 1 +#define IP_TTL 2 +#define IP_PKTINFO 8 +#define IP_MTU_DISCOVER 10 +#define IP_RECVERR 11 +#define IP_RECVTTL 12 +#define IP_FREEBIND 15 +#define IP_MULTICAST_IF 32 +#define IP_MULTICAST_TTL 33 +#define IP_MULTICAST_LOOP 34 +#define IP_ADD_MEMBERSHIP 35 +#define IP_DROP_MEMBERSHIP 36 +#define IP_MULTICAST_ALL 49 +#define IP_UNICAST_IF 50 +#define IP_PMTUDISC_DONT 0 +#define IP_PMTUDISC_WANT 1 +#define IP_PMTUDISC_DO 2 +#define IP_PMTUDISC_PROBE 3 +#define IP_PMTUDISC_INTERFACE 4 +#define IP_PMTUDISC_OMIT 5 + +_Static_assert(sizeof(struct ip_mreq) == 8, "Linux ip_mreq size"); +_Static_assert(sizeof(struct ip_mreqn) == 12, "Linux ip_mreqn size"); +_Static_assert(sizeof(struct in_pktinfo) == 12, "Linux in_pktinfo size"); + +#endif diff --git a/include/uapi/linux/in6.h b/include/uapi/linux/in6.h index b818eea1..d31a2576 100644 --- a/include/uapi/linux/in6.h +++ b/include/uapi/linux/in6.h @@ -50,6 +50,7 @@ struct in6_ifreq { struct in6_addr ifr6_addr; uint32_t ifr6_prefixlen; int32_t i #define IPV6_DONTFRAG 62 #define IPV6_RECVTCLASS 66 #define IPV6_TCLASS 67 +#define IPV6_UNICAST_IF 76 #define IPV6_PMTUDISC_DONT 0 #define IPV6_PMTUDISC_WANT 1 #define IPV6_PMTUDISC_DO 2 diff --git a/include/uapi/linux/neighbour.h b/include/uapi/linux/neighbour.h new file mode 100644 index 00000000..2e7ae0f2 --- /dev/null +++ b/include/uapi/linux/neighbour.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_UAPI_LINUX_NEIGHBOUR_H +#define RELIEFNT_UAPI_LINUX_NEIGHBOUR_H +#include + +struct ndmsg { + uint8_t ndm_family, ndm_pad1; + uint16_t ndm_pad2; + int32_t ndm_ifindex; + uint16_t ndm_state; + uint8_t ndm_flags, ndm_type; +}; + +#define NDA_DST 1 +#define NDA_LLADDR 2 +#define NTF_PROXY 0x08 +#define NUD_INCOMPLETE 0x01 +#define NUD_REACHABLE 0x02 +#define NUD_STALE 0x04 +#define NUD_DELAY 0x08 +#define NUD_PROBE 0x10 +#define NUD_FAILED 0x20 +#define NUD_NOARP 0x40 +#define NUD_PERMANENT 0x80 + +#endif diff --git a/include/uapi/linux/netlink.h b/include/uapi/linux/netlink.h index 57d39a35..17ca1036 100644 --- a/include/uapi/linux/netlink.h +++ b/include/uapi/linux/netlink.h @@ -7,6 +7,7 @@ #endif #define NETLINK_ROUTE 0 #define NETLINK_KOBJECT_UEVENT 15 +#define NETLINK_GENERIC 16 #define SOL_NETLINK 270 #define NETLINK_ADD_MEMBERSHIP 1 #define NETLINK_DROP_MEMBERSHIP 2 @@ -25,6 +26,14 @@ struct nlmsgerr { int32_t error; struct nlmsghdr msg; }; #define NLMSG_ERROR 2 #define NLMSG_DONE 3 #define NLMSG_OVERRUN 4 +#define NLMSG_MIN_TYPE 0x10 +struct nlattr { uint16_t nla_len, nla_type; }; +#define NLA_F_NESTED (1u << 15) +#define NLA_F_NET_BYTEORDER (1u << 14) +#define NLA_TYPE_MASK (~(NLA_F_NESTED | NLA_F_NET_BYTEORDER)) +#define NLA_ALIGNTO 4 +#define NLA_ALIGN(n) (((n) + NLA_ALIGNTO - 1) & ~(NLA_ALIGNTO - 1)) +#define NLA_HDRLEN ((uint32_t)NLA_ALIGN(sizeof(struct nlattr))) #define NLM_F_REQUEST 0x001 #define NLM_F_MULTI 0x002 #define NLM_F_ACK 0x004 @@ -39,4 +48,5 @@ struct nlmsgerr { int32_t error; struct nlmsghdr msg; }; _Static_assert(sizeof(struct sockaddr_nl)==12, "Linux sockaddr_nl"); _Static_assert(sizeof(struct nl_pktinfo)==4, "Linux nl_pktinfo"); _Static_assert(sizeof(struct nlmsghdr)==16, "Linux nlmsghdr"); +_Static_assert(sizeof(struct nlattr)==4, "Linux nlattr"); #endif diff --git a/include/uapi/linux/nexthop.h b/include/uapi/linux/nexthop.h new file mode 100644 index 00000000..f8eda7b5 --- /dev/null +++ b/include/uapi/linux/nexthop.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_UAPI_LINUX_NEXTHOP_H +#define RELIEFNT_UAPI_LINUX_NEXTHOP_H +#include + +struct nhmsg { + uint8_t nh_family, nh_scope, nh_protocol, resvd; + uint32_t nh_flags; +}; + +#define NHA_ID 1 +#define NHA_GROUP 2 +#define NHA_GROUP_TYPE 3 +#define NHA_BLACKHOLE 4 +#define NHA_OIF 5 +#define NHA_GATEWAY 6 +#define NHA_ENCAP_TYPE 7 +#define NHA_ENCAP 8 +#define NHA_GROUPS 9 +#define NHA_MASTER 10 +#define NHA_FDB 11 + +#endif diff --git a/include/uapi/linux/rtnetlink.h b/include/uapi/linux/rtnetlink.h index 0164a91a..0ca44bfd 100644 --- a/include/uapi/linux/rtnetlink.h +++ b/include/uapi/linux/rtnetlink.h @@ -20,6 +20,12 @@ struct rtmsg { uint8_t rtm_family, rtm_dst_len, rtm_src_len, rtm_tos; #define RTM_NEWROUTE 24 #define RTM_DELROUTE 25 #define RTM_GETROUTE 26 +#define RTM_NEWNEIGH 28 +#define RTM_DELNEIGH 29 +#define RTM_GETNEIGH 30 +#define RTM_NEWNEXTHOP 104 +#define RTM_DELNEXTHOP 105 +#define RTM_GETNEXTHOP 106 #define RTA_DST 1 #define RTA_SRC 2 #define RTA_IIF 3 @@ -28,6 +34,10 @@ struct rtmsg { uint8_t rtm_family, rtm_dst_len, rtm_src_len, rtm_tos; #define RTA_PRIORITY 6 #define RTA_PREFSRC 7 #define RTA_TABLE 15 +#define RTA_PREF 20 +#define RTA_EXPIRES 23 +#define RTA_NH_ID 30 +#define RTNH_F_ONLINK 4 #define RTN_UNICAST 1 #define RTN_LOCAL 2 #define RTPROT_KERNEL 2 @@ -41,9 +51,23 @@ struct rtmsg { uint8_t rtm_family, rtm_dst_len, rtm_src_len, rtm_tos; #define RT_TABLE_MAIN 254 #define RT_TABLE_LOCAL 255 #define RTMGRP_LINK 0x1 +#define RTMGRP_NEIGH 0x4 +#define RTMGRP_TC 0x8 +#define RTMGRP_IPV4_IFADDR 0x10 +#define RTMGRP_IPV4_ROUTE 0x40 +#define RTMGRP_IPV4_RULE 0x80 #define RTMGRP_IPV6_IFADDR 0x100 #define RTMGRP_IPV6_ROUTE 0x400 #define RTNLGRP_LINK 1 +#define RTNLGRP_NEIGH 3 +#define RTNLGRP_TC 4 +#define RTNLGRP_IPV4_IFADDR 5 +#define RTNLGRP_IPV4_ROUTE 7 +#define RTNLGRP_IPV4_RULE 8 #define RTNLGRP_IPV6_IFADDR 9 #define RTNLGRP_IPV6_ROUTE 11 +#define RTNLGRP_IPV6_RULE 19 +#define RTNLGRP_NEXTHOP 32 +#define RTNLGRP_STATS 36 +#define RTNLGRP_MAX RTNLGRP_STATS #endif diff --git a/include/uapi/linux/socket.h b/include/uapi/linux/socket.h index f4a33c0b..9ef9e8eb 100644 --- a/include/uapi/linux/socket.h +++ b/include/uapi/linux/socket.h @@ -32,6 +32,7 @@ struct sockaddr_un { #define AF_UNSPEC 0 #define AF_UNIX 1 #define AF_INET 2 +#define AF_BRIDGE 7 #define AF_INET6 10 #define AF_NETLINK 16 #define AF_PACKET 17 @@ -44,12 +45,14 @@ struct sockaddr_un { #define SOL_SOCKET 1 #define SOL_TCP 6 #define SOL_RAW 255 +#define SOL_PACKET 263 #define TCP_NODELAY 1 #define SO_ERROR 4 #define SO_TYPE 3 #define SO_REUSEADDR 2 #define SO_SNDBUF 7 #define SO_RCVBUF 8 +#define SO_PRIORITY 12 #define SO_PASSCRED 16 #define SO_PEERCRED 17 #define SO_RCVLOWAT 18 @@ -60,6 +63,7 @@ struct sockaddr_un { #define SO_SNDTIMEO_NEW 67 #define SO_ACCEPTCONN 30 #define SO_BINDTODEVICE 25 +#define SO_BINDTOIFINDEX 62 #define SO_ATTACH_FILTER 26 #define SO_DETACH_FILTER 27 #define SO_TIMESTAMP_OLD 29 diff --git a/kernel/syscall/event/timerfd.c b/kernel/syscall/event/timerfd.c index 48477369..f83af86d 100644 --- a/kernel/syscall/event/timerfd.c +++ b/kernel/syscall/event/timerfd.c @@ -64,6 +64,12 @@ void task_timerfd_update(struct task_timerfd *timer) timer->expiry_tick += periods * timer->interval_ticks; } +/** + * @brief Create an independent REALTIME, MONOTONIC or BOOTTIME timer descriptor. + * @param clockid Linux clock used to interpret absolute deadlines. + * @param flags TFD_CLOEXEC and TFD_NONBLOCK descriptor options. + * @return New descriptor or negative validation, allocation or descriptor errno. + */ int64_t syscall_timerfd_create(uint64_t clockid, uint32_t flags) { struct task *task = sched_current_task(); @@ -73,7 +79,8 @@ int64_t syscall_timerfd_create(uint64_t clockid, uint32_t flags) struct task_timerfd *timer; struct task_file *file; int fd; - if (!task || (clockid != LINUX_CLOCK_REALTIME && clockid != LINUX_CLOCK_MONOTONIC) || + if (!task || (clockid != LINUX_CLOCK_REALTIME && clockid != LINUX_CLOCK_MONOTONIC && + clockid != LINUX_CLOCK_BOOTTIME) || (flags & ~(TFD_CLOEXEC | TFD_NONBLOCK))) return -RELIEFOS_EINVAL; timer = kernel_malloc(sizeof(*timer)); if (!timer) return -RELIEFOS_ENOMEM; @@ -87,6 +94,14 @@ int64_t syscall_timerfd_create(uint64_t clockid, uint32_t flags) return fd; } +/** + * @brief Arm or disarm a timer using a relative or selected-clock deadline. + * @param fd_arg Timer descriptor retained by the syscall entry when admitted. + * @param flags TFD_TIMER_ABSTIME and TFD_TIMER_CANCEL_ON_SET request bits. + * @param value_ptr User specification address; a zero it_value disarms the timer. + * @param old_ptr Optional user output address for the previous specification. + * @return Zero, negative errno or private page-in contention before mutation. + */ int64_t syscall_timerfd_settime(uint64_t fd_arg, uint32_t flags, uint64_t value_ptr, uint64_t old_ptr) { @@ -124,7 +139,9 @@ int64_t syscall_timerfd_settime(uint64_t fd_arg, uint32_t flags, } old.it_interval.tv_sec = (int64_t)(timer->interval_ticks / RELIEFNT_TICK_HZ); old.it_interval.tv_nsec = (int64_t)((timer->interval_ticks % RELIEFNT_TICK_HZ) * (1000000000ULL / RELIEFNT_TICK_HZ)); - if (flags & TFD_TIMER_ABSTIME) { + if (!value.it_value.tv_sec && !value.it_value.tv_nsec) { + initial = 0; + } else if (flags & TFD_TIMER_ABSTIME) { struct linux_timespec now = {0}; if (time_clock_get(timer->clockid, &now) < 0) return -RELIEFOS_EINVAL; if (value.it_value.tv_sec < now.tv_sec || diff --git a/kernel/syscall/fs/mount_api.c b/kernel/syscall/fs/mount_api.c index 20e09279..09337e15 100644 --- a/kernel/syscall/fs/mount_api.c +++ b/kernel/syscall/fs/mount_api.c @@ -15,6 +15,7 @@ enum syscall_fs_type { struct syscall_fs_context { struct vfs_path root; struct user_namespace *user_ns; + struct net_namespace *net_ns; char *source; uint32_t uid, gid; enum syscall_fs_type type; @@ -30,6 +31,7 @@ void syscall_fs_context_release(void *object) if (!context) return; vfs_path_put(&context->root); user_namespace_put(context->user_ns); + net_namespace_put(context->net_ns); kernel_free(context->source); kernel_free(context); } @@ -37,7 +39,7 @@ void syscall_fs_context_release(void *object) /** @brief Create a supported filesystem configuration owned by a new descriptor. * @param task Calling descriptor-table owner. @param type_user User filesystem name. * @param flags Native fsopen flags. @return Descriptor or negative errno. - * Captures tmpfs user ownership and sysfs network-owner authority at fsopen. + * Captures tmpfs user ownership and sysfs network view and authority at fsopen. * proc keeps the initial PID-view owner. sysfs admission also checks its * network owner. Failure leaves no descriptor or namespace reference. */ @@ -64,7 +66,8 @@ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t fl } if (!rc) { *context = (struct syscall_fs_context){.uid = task->fsuid, .gid = task->fsgid, - .type = filesystem, .user_ns = user_namespace_get(owner)}; + .type = filesystem, .user_ns = user_namespace_get(owner), + .net_ns = filesystem == SYSCALL_FS_SYSFS ? net_namespace_get(task->net_ns) : NULL}; struct task_file *file = NULL; int fd = task_allocate_fd(task, 0, &file); if (fd < 0) rc = fd; @@ -197,7 +200,7 @@ static int mount_api_commit(struct task *task,struct syscall_fs_context *context if (context->type == SYSCALL_FS_PROC) rc = proc_create_vfs_mount_options(context->options,&mount); else if (context->type == SYSCALL_FS_SYSFS) - rc = sysfs_create_vfs_mount(&mount); + rc = sysfs_create_vfs_mount_in_net(context->net_ns,&mount); else rc = storage_new_tmpfs_mount("none", flags, context->options, context->uid, context->gid, &mount); diff --git a/kernel/syscall/internal.h b/kernel/syscall/internal.h index 8ef8a8f7..33dc1260 100644 --- a/kernel/syscall/internal.h +++ b/kernel/syscall/internal.h @@ -885,8 +885,22 @@ int64_t syscall_eventfd_create(uint64_t initial, uint32_t flags); void task_timerfd_update(struct task_timerfd *timer); +/** + * @brief Create an independent REALTIME, MONOTONIC or BOOTTIME timer descriptor. + * @param clockid Linux clock used to interpret absolute deadlines. + * @param flags TFD_CLOEXEC and TFD_NONBLOCK descriptor options. + * @return New descriptor or negative validation, allocation or descriptor errno. + */ int64_t syscall_timerfd_create(uint64_t clockid, uint32_t flags); +/** + * @brief Arm or disarm a timer using a relative or selected-clock deadline. + * @param fd_arg Timer descriptor retained by the syscall entry when admitted. + * @param flags TFD_TIMER_ABSTIME and TFD_TIMER_CANCEL_ON_SET request bits. + * @param value_ptr User specification address; a zero it_value disarms the timer. + * @param old_ptr Optional user output address for the previous specification. + * @return Zero, negative errno or private page-in contention before mutation. + */ int64_t syscall_timerfd_settime(uint64_t fd_arg, uint32_t flags, uint64_t value_ptr, uint64_t old_ptr); diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 21430409..26dba7f6 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -1358,7 +1359,7 @@ void task_inet_release(struct task_file *file) } /** - * @brief Read or update supported socket, TCP and IPv6 options for a TCP socket. + * @brief Read or update socket, TCP, IPv4 and IPv6 options for a TCP socket. * @param setting Select setsockopt when true, getsockopt otherwise. * @param level Socket option level. * @param option Option identifier. @@ -1369,39 +1370,48 @@ void task_inet_release(struct task_file *file) * @note Linux SO_*TIMEO values are converted to scheduler ticks with ceiling * rounding. An all-zero timeval maps to an infinite wait; negative seconds map * to an immediate timeout and are reported by getsockopt as (0, 0). - * SO_BINDTODEVICE resolves and authorizes against the endpoint's creation network. + * SO_BINDTODEVICE resolves and both binding options authorize against the + * endpoint's creation network. SO_BINDTOIFINDEX accepts nonnegative indices. + * SOL_IP accepts byte-sized scalar input and returns one byte for short output. */ static int inet_socket_option(bool setting, int level, int option, uint64_t address, uint64_t length, int32_t handle) { - if (level == SOL_SOCKET && option == SO_BINDTODEVICE) { + if (level == SOL_SOCKET && (option == SO_BINDTODEVICE || option == SO_BINDTOIFINDEX)) { uint32_t index = 0; int result = net_socket_bound_device(handle, false, &index); if (result < 0) return result; - result = net_interface_device_option(net_socket_namespace(handle), setting, address, length, &index); + result = net_interface_device_option(net_socket_namespace(handle), setting, + (uint32_t)option, address, length, &index); if (result < 0) return result; return setting ? net_socket_bound_device(handle, true, &index) : 0; } bool nodelay = level == SOL_TCP && option == TCP_NODELAY; - if (level == SOL_IPV6 || nodelay || (level == SOL_SOCKET && option == SO_REUSEADDR)) { + if (level == SOL_IP || level == SOL_IPV6 || nodelay || + (level == SOL_SOCKET && option == SO_REUSEADDR)) { int value = 0; uint32_t size = (uint32_t)length; if (setting) { - if ((int32_t)size < (int32_t)sizeof(value)) return -LINUX_EINVAL; - int prep = socket_user_prepare(sched_current_task(), address, sizeof(value), false); + uint32_t bytes = level == SOL_IP && size < sizeof(value) ? 1 : sizeof(value); + if ((int32_t)size < (int32_t)bytes) return -LINUX_EINVAL; + int prep = socket_user_prepare(sched_current_task(), address, bytes, false); if (prep) return prep; - if (!user_range_ok(address, sizeof(value))) return -LINUX_EFAULT; - __builtin_memcpy(&value, (void *)(uintptr_t)address, sizeof(value)); + if (!user_range_ok(address, bytes)) return -LINUX_EFAULT; + __builtin_memcpy(&value, (void *)(uintptr_t)address, bytes); return nodelay ? net_socket_nodelay(handle, true, &value) : + level == SOL_IP ? net_socket_ipv4_option(handle, true, (uint32_t)option, &value) : level == SOL_IPV6 ? net_socket_ipv6_option(handle, true, (uint32_t)option, &value) : net_socket_reuse(handle, true, &value); } int prep = socket_user_length(sched_current_task(), length, &size); if (prep) return prep; if ((int32_t)size < 0) return -LINUX_EINVAL; int ret = nodelay ? net_socket_nodelay(handle, false, &value) : + level == SOL_IP ? net_socket_ipv4_option(handle, false, (uint32_t)option, &value) : level == SOL_IPV6 ? net_socket_ipv6_option(handle, false, (uint32_t)option, &value) : net_socket_reuse(handle, false, &value); if (ret < 0) return ret; if (size > sizeof(value)) size = sizeof(value); + if (level == SOL_IP && size && size < sizeof(value) && value >= 0 && value <= 255) + size = 1; prep = socket_user_prepare(sched_current_task(), address, size, true); if (prep) return prep; if (size && !user_range_writable(address, size)) return -LINUX_EFAULT; if (size) __builtin_memcpy((void *)(uintptr_t)address, &value, size); @@ -2571,6 +2581,72 @@ complete_message: ; } #endif +/** @brief Snapshot and validate per-message UDP source, device and hop controls. + * @param file Pinned UDP OFD retaining its creation network. + * @param message Imported message with optional user control storage. + * @param info Caller-owned hints initialized to socket defaults. + * @return Zero, negative errno, or a user-memory prerequisite marker. + * All controls are imported before transmission. Persistent options are unchanged. + */ +static int udp_message_control(struct task_file *file, const struct msghdr *message, + struct net_udp_tx_info *info) +{ + if (message->msg_controllen > UNIX_SOCKET_CMSG_CAP) return -LINUX_ENOBUFS; + struct task_user_text control = {0}; + int result = task_lookup_user_bytes(sched_current_task(), (uintptr_t)message->msg_control, + message->msg_controllen, &control); + if (result) return result; + bool ipv6 = task_udp_address_size(file) == sizeof(struct sockaddr_in6); + uint64_t offset = 0; + while (message->msg_controllen - offset >= sizeof(struct cmsghdr)) { + struct cmsghdr header; + __builtin_memcpy(&header, control.text + offset, sizeof(header)); + if (header.cmsg_len < CMSG_LEN(0) || header.cmsg_len > message->msg_controllen - offset) { + result = -LINUX_EINVAL; + break; + } + const void *value = control.text + offset + CMSG_LEN(0); + uint64_t length = header.cmsg_len - CMSG_LEN(0); + if (header.cmsg_level == SOL_IP && header.cmsg_type == IP_PKTINFO) { + struct in_pktinfo packet; + if (length != sizeof(packet)) { result = -LINUX_EINVAL; break; } + __builtin_memcpy(&packet, value, sizeof(packet)); + if (packet.ipi_ifindex < 0) { result = -LINUX_EINVAL; break; } + if (packet.ipi_ifindex) info->ifindex = (uint32_t)packet.ipi_ifindex; + info->source4 = ntohl(packet.ipi_spec_dst.s_addr); + } else if (header.cmsg_level == SOL_IP && header.cmsg_type == IP_TTL) { + int ttl; + if (length != sizeof(ttl)) { result = -LINUX_EINVAL; break; } + __builtin_memcpy(&ttl, value, sizeof(ttl)); + if (ttl < 1 || ttl > 255) { result = -LINUX_EINVAL; break; } + info->ttl = ttl; + } else if (ipv6 && header.cmsg_level == SOL_IPV6 && header.cmsg_type == IPV6_PKTINFO) { + struct in6_pktinfo packet; + if (length < sizeof(packet)) { result = -LINUX_EINVAL; break; } + __builtin_memcpy(&packet, value, sizeof(packet)); + if (packet.ipi6_ifindex > INT32_MAX) { result = -LINUX_EINVAL; break; } + if (packet.ipi6_ifindex) info->ifindex = packet.ipi6_ifindex; + info->source6 = packet.ipi6_addr; + } else if (ipv6 && header.cmsg_level == SOL_IPV6 && + (header.cmsg_type == IPV6_HOPLIMIT || header.cmsg_type == IPV6_2292HOPLIMIT)) { + int hops; + if (length != sizeof(hops)) { result = -LINUX_EINVAL; break; } + __builtin_memcpy(&hops, value, sizeof(hops)); + if (hops < -1 || hops > 255) { result = -LINUX_EINVAL; break; } + info->hops = hops; + } else if (header.cmsg_level == SOL_IP || header.cmsg_level == SOL_SOCKET || + (ipv6 && header.cmsg_level == SOL_IPV6)) { + result = -LINUX_EINVAL; + break; + } + uint64_t step = CMSG_ALIGN(header.cmsg_len); + if (step > message->msg_controllen - offset) break; + offset += step; + } + kernel_free(control.allocation); + return result; +} + /** * @brief Perform one staged INET datagram or stream message. * @param file Pinned open socket description. @@ -2586,6 +2662,11 @@ complete_message: ; * the receiving caller's user namespace at final control-message copyout. * NETLINK_PKTINFO precedes credentials and reports the destination group index, * including zero for unicast, independently of source-address output. + * UDP and packet ancillary output includes enabled realtime timestamps. Packet + * sockets also expose enabled AUXDATA. All emitted control bytes are prepared + * before dequeue, so output-memory failure preserves the queued datagram. + * UDP MSG_ERRQUEUE returns the original destination, quoted payload and a native + * extended-error control message. Internal receive probing preserves that queue. */ static int64_t inet_message(struct task_file *file, uint64_t user_header, struct msghdr message, uint32_t flags, bool receiving, @@ -2597,9 +2678,15 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, bool netlink_pktinfo = receiving && netlink && task_netlink_pktinfo(file); bool udp = file->kind == TASK_FILE_KIND_UDP; bool datagram = udp || packet || netlink; - if (flags & ~(MSG_DONTWAIT | MSG_NOSIGNAL | MSG_PEEK | MSG_TRUNC | MSG_WAITALL | MSG_CMSG_CLOEXEC)) + if (flags & ~(MSG_DONTWAIT | MSG_NOSIGNAL | MSG_PEEK | MSG_TRUNC | MSG_WAITALL | MSG_CMSG_CLOEXEC | + (receiving && udp ? MSG_ERRQUEUE : 0))) return -LINUX_EOPNOTSUPP; - if (!receiving && message.msg_controllen) return -LINUX_EINVAL; + struct net_udp_tx_info tx_info = {.ttl = -1, .hops = -1}; + if (!receiving && message.msg_controllen) { + if (!udp) return -LINUX_EINVAL; + int result = udp_message_control(file, &message, &tx_info); + if (result) return result; + } uint32_t datagram_limit = packet ? (task_packet_address_size(file) == sizeof(struct sockaddr_in6) ? 65535u : 1514u) : udp ? (task_udp_address_size(file) == sizeof(struct sockaddr_in6) ? 65527u : 1472u) : 32768u; if (!receiving && datagram && total > datagram_limit) return -LINUX_EMSGSIZE; @@ -2626,7 +2713,10 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, } if (receiving && (udp || packet || netlink_passcred || netlink_pktinfo) && message.msg_controllen && message.msg_control) { uint64_t limit = netlink ? (netlink_passcred ? CMSG_SPACE(sizeof(struct ucred)) : 0) + - (netlink_pktinfo ? CMSG_SPACE(sizeof(struct nl_pktinfo)) : 0) : 88; + (netlink_pktinfo ? CMSG_SPACE(sizeof(struct nl_pktinfo)) : 0) : + flags & MSG_ERRQUEUE ? CMSG_SPACE(sizeof(struct sock_extended_err) + sizeof(struct sockaddr_in6)) : + CMSG_SPACE(sizeof(struct in6_pktinfo)) + 2 * CMSG_SPACE(sizeof(int)) + + CMSG_SPACE(sizeof(struct linux_timeval)) + CMSG_SPACE(sizeof(struct tpacket_auxdata)); uint64_t copied = message.msg_controllen < limit ? message.msg_controllen : limit; int prep = socket_user_prepare(sched_current_task(), (uintptr_t)message.msg_control, copied, true); if (prep) return prep; @@ -2723,6 +2813,7 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, offset += n; } output->flags = datagram && (uint64_t)ret > size ? MSG_TRUNC : 0; + if (udp_info.error_queue) output->flags |= MSG_ERRQUEUE; uint64_t used = 0; if (netlink_pktinfo || netlink_passcred) { const struct sockaddr_nl *from = (const void *)&source; @@ -2748,19 +2839,48 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, used += CMSG_SPACE(copy) < available ? CMSG_SPACE(copy) : available; } } - if ((udp || packet) && (udp_info.pktinfo || udp_info.hoplimit || udp_info.old_hoplimit)) { + if ((udp || packet) && (udp_info.pktinfo || udp_info.hoplimit || udp_info.old_hoplimit || + udp_info.timestamp_option || udp_info.packet_auxdata || udp_info.error_queue)) { struct in6_pktinfo pktinfo = {.ipi6_addr = udp_info.destination, .ipi6_ifindex = udp_info.ifindex}; - for (unsigned which = 0; which < 3; ++which) { - bool enabled = which == 0 ? udp_info.pktinfo : which == 1 ? udp_info.hoplimit : udp_info.old_hoplimit; - if (!enabled) continue; - const void *value = which == 0 ? (const void *)&pktinfo : (const void *)&udp_info.hops; - uint64_t value_size = which == 0 ? sizeof(pktinfo) : sizeof(udp_info.hops); + struct in_pktinfo pktinfo4 = {.ipi_ifindex = (int32_t)udp_info.ifindex}; + if (udp_info.ipv4) { + __builtin_memcpy(&pktinfo4.ipi_addr.s_addr, udp_info.destination.s6_addr + 12, 4); + struct reliefos_net_config config = {0}; + if (!net_interface_get_config(task_udp_namespace(file), udp_info.ifindex, &config)) + pktinfo4.ipi_spec_dst.s_addr = htonl(config.local_ip); + if (net_interface_for_ipv4(task_udp_namespace(file), ntohl(pktinfo4.ipi_addr.s_addr))) + pktinfo4.ipi_spec_dst = pktinfo4.ipi_addr; + } + const struct { + bool enabled; + int level, type; + const void *value; + uint64_t size; + } controls[] = { + {udp_info.error_queue, udp_info.ipv4 ? SOL_IP : SOL_IPV6, + udp_info.ipv4 ? IP_RECVERR : IPV6_RECVERR, &udp_info.extended, + sizeof(struct sock_extended_err) + (udp_info.ipv4 ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))}, + {udp_info.pktinfo, udp_info.ipv4 ? SOL_IP : SOL_IPV6, + udp_info.ipv4 ? IP_PKTINFO : IPV6_PKTINFO, + udp_info.ipv4 ? (const void *)&pktinfo4 : (const void *)&pktinfo, + udp_info.ipv4 ? sizeof(pktinfo4) : sizeof(pktinfo)}, + {udp_info.hoplimit, udp_info.ipv4 ? SOL_IP : SOL_IPV6, + udp_info.ipv4 ? IP_TTL : IPV6_HOPLIMIT, &udp_info.hops, sizeof(udp_info.hops)}, + {udp_info.old_hoplimit, SOL_IPV6, IPV6_2292HOPLIMIT, &udp_info.hops, sizeof(udp_info.hops)}, + {udp_info.timestamp_option != 0, SOL_SOCKET, (int)udp_info.timestamp_option, + &udp_info.timestamp, sizeof(udp_info.timestamp)}, + {udp_info.packet_auxdata, SOL_PACKET, PACKET_AUXDATA, &udp_info.auxdata, sizeof(udp_info.auxdata)}, + }; + for (unsigned which = 0; which < sizeof(controls) / sizeof(controls[0]); ++which) { + if (!controls[which].enabled) continue; + const void *value = controls[which].value; + uint64_t value_size = controls[which].size; uint64_t available = message.msg_controllen > used ? message.msg_controllen - used : 0; if (!message.msg_control || available < CMSG_LEN(0)) { output->flags |= MSG_CTRUNC; continue; } uint64_t copy = available - CMSG_LEN(0); if (copy > value_size) copy = value_size; - struct cmsghdr header = {.cmsg_len = CMSG_LEN(copy), .cmsg_level = SOL_IPV6, - .cmsg_type = which == 0 ? IPV6_PKTINFO : which == 1 ? IPV6_HOPLIMIT : IPV6_2292HOPLIMIT}; + struct cmsghdr header = {.cmsg_len = CMSG_LEN(copy), + .cmsg_level = controls[which].level, .cmsg_type = controls[which].type}; uint8_t *control = (uint8_t *)message.msg_control + used; __builtin_memcpy(control, &header, sizeof(header)); if (copy) __builtin_memcpy(control + CMSG_LEN(0), value, copy); @@ -2776,7 +2896,8 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, } else { if (netlink) ret = task_netlink_send(file, payload, size, flags, (uintptr_t)message.msg_name, message.msg_namelen); else if (packet) ret = task_packet_send(file, payload, size, flags, (uintptr_t)message.msg_name, message.msg_namelen); - else if (udp) ret = task_udp_send(file, payload, size, flags, (uintptr_t)message.msg_name, message.msg_namelen); + else if (udp) ret = task_udp_send_ex(file, payload, size, flags, (uintptr_t)message.msg_name, + message.msg_namelen, &tx_info); else ret = task_inet_write(&local, payload, size); } done: diff --git a/net/core.c b/net/core.c index 247ae9b8..c27e14a0 100644 --- a/net/core.c +++ b/net/core.c @@ -91,6 +91,7 @@ void net_device_attached(uint32_t ifindex) } net_ipv6_link_changed_on(NULL, ifindex, net_interface_is_up(NULL, ifindex)); netlink_ipv6_changed(NULL); + net_interface_uevent(NULL, ifindex, "add", NULL); } /** @brief Retire initial-network sockets and discovery state of a removed device. @@ -108,6 +109,7 @@ void net_device_detached(uint32_t ifindex) net_packet_device_detached(ifindex); net_ipv6_detached_on(NULL, ifindex); net_arp_cache_clear_on(ifindex); + net_interface_uevent(NULL, ifindex, "remove", NULL); net_interface_remove(ifindex); netlink_ipv6_changed(NULL); } @@ -129,6 +131,7 @@ void net_device_retry_registration(void) if (!net_interface_register(index)) { net_ipv6_link_changed_on(NULL, index, net_interface_is_up(NULL, index)); netlink_ipv6_changed(NULL); + net_interface_uevent(NULL, index, "add", NULL); } return; } diff --git a/net/interface/Kbuild b/net/interface/Kbuild index 9ee13f13..c21fa040 100644 --- a/net/interface/Kbuild +++ b/net/interface/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := config.o state.o routes.o ioctl.o socket.o +obj-y := config.o state.o routes.o nexthop.o ioctl.o socket.o include $(srctree)/scripts/Makefile.module diff --git a/net/interface/config.c b/net/interface/config.c index 3505fd53..0958e40e 100644 --- a/net/interface/config.c +++ b/net/interface/config.c @@ -238,7 +238,11 @@ void net_set_static_fallback(void) uint32_t index = net_interface_next(NULL, NET_IF_LOOPBACK); struct net_interface *iface = net_interface_get(NULL, index); net_arp_cache_clear_on(index); - if (iface) { iface->broadcast = 0; iface->default_metric = 0; } + if (iface) { + iface->broadcast = 0; + iface->default_metric = 0; + iface->ipv4_address = (struct net_ipv4_address_state){0}; + } net_dhcp_dns_ip = 0; net_dhcp_acquired_ms = 0; net_config = (struct reliefos_net_config){ @@ -275,6 +279,7 @@ void net_apply_dhcp_offer(const struct net_dhcp_offer *offer) if (iface) { iface->broadcast = net_config.local_ip | ~net_config.subnet_mask; iface->default_metric = 0; + iface->ipv4_address = (struct net_ipv4_address_state){0}; } net_config.gateway_ip = offer->router_ip; net_dhcp_dns_ip = offer->dns_ip; diff --git a/net/interface/ioctl.c b/net/interface/ioctl.c index b7c92d96..b6ac4b06 100644 --- a/net/interface/ioctl.c +++ b/net/interface/ioctl.c @@ -2,6 +2,7 @@ #include "../internal.h" #include #include +#include #include #include #include @@ -146,13 +147,27 @@ static int interface_route(struct net_namespace *ns, struct task *task, uint32_t /** @copydoc net_interface_configure_ipv4 */ int net_interface_configure_ipv4(struct net_namespace *ns, uint32_t index, uint32_t address, uint32_t mask, uint32_t broadcast) +{ + const struct net_ipv4_address_state policy = { + .flags = IFA_F_PERMANENT, + .scope = index == NET_IF_LOOPBACK ? RT_SCOPE_HOST : RT_SCOPE_UNIVERSE, + }; + return net_interface_set_ipv4(ns, index, address, mask, broadcast, &policy); +} + +/** @copydoc net_interface_set_ipv4 */ +int net_interface_set_ipv4(struct net_namespace *ns, uint32_t index, uint32_t address, + uint32_t mask, uint32_t broadcast, + const struct net_ipv4_address_state *policy) { struct net_interface *iface = net_interface_get(ns, index); if (!iface) return index == NET_IF_LOOPBACK ? -LINUX_EOPNOTSUPP : -LINUX_ENODEV; - if (((~mask) & ((~mask) + 1u)) || address >= 0xe0000000u) return -LINUX_EINVAL; + if (!policy || ((~mask) & ((~mask) + 1u)) || address >= 0xe0000000u || + (policy->valid_until && policy->preferred_until > policy->valid_until)) return -LINUX_EINVAL; iface->config.local_ip = address; iface->config.subnet_mask = mask; iface->broadcast = broadcast; + iface->ipv4_address = address ? *policy : (struct net_ipv4_address_state){0}; if (!address) iface->config.gateway_ip = 0; iface->config.source = address ? RELIEFOS_NET_CONFIG_SOURCE_STATIC : RELIEFOS_NET_CONFIG_SOURCE_NONE; iface->config.lease_seconds = iface->config.dhcp_server_ip = 0; @@ -161,10 +176,29 @@ int net_interface_configure_ipv4(struct net_namespace *ns, uint32_t index, uint3 return 0; } +/** @copydoc net_interface_ipv4_poll */ +void net_interface_ipv4_poll(struct net_namespace *ns) +{ + uint64_t now = time_uptime_ms(); + for (uint32_t index = net_interface_next(ns, 0); index; + index = net_interface_next(ns, index)) { + struct net_interface *iface = net_interface_get(ns, index); + if (!iface || !iface->config.local_ip) continue; + struct net_ipv4_address_state *policy = &iface->ipv4_address; + if (policy->valid_until && policy->valid_until != UINT64_MAX && now >= policy->valid_until) { + (void)net_interface_configure_ipv4(ns, index, 0, 0, 0); + } else if (!(policy->flags & IFA_F_DEPRECATED) && policy->preferred_until && + policy->preferred_until != UINT64_MAX && now >= policy->preferred_until) { + policy->flags |= IFA_F_DEPRECATED; + netlink_network_changed(ns); + } + } +} + /** @copydoc net_interface_ioctl */ int net_interface_ioctl(struct net_namespace *ns, uint32_t request, uint64_t address) { - bool change = request == SIOCSIFFLAGS || request == SIOCSIFADDR || + bool change = request == SIOCSIFFLAGS || request == SIOCSIFNAME || request == SIOCSIFADDR || request == SIOCSIFNETMASK || request == SIOCSIFBRDADDR || request == SIOCSIFMTU || request == SIOCADDRT || request == SIOCDELRT; struct task *task = sched_current_task(); @@ -177,7 +211,7 @@ int net_interface_ioctl(struct net_namespace *ns, uint32_t request, uint64_t add case SIOCGIFNAME: case SIOCGIFINDEX: case SIOCGIFHWADDR: case SIOCGIFFLAGS: case SIOCSIFFLAGS: case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFMTU: - case SIOCSIFMTU: case SIOCGIFTXQLEN: break; + case SIOCSIFMTU: case SIOCSIFNAME: case SIOCGIFTXQLEN: break; default: return -LINUX_ENOTTY; } struct ifreq req; @@ -201,6 +235,9 @@ int net_interface_ioctl(struct net_namespace *ns, uint32_t request, uint64_t add bool loop = index == NET_IF_LOOPBACK; struct net_interface *iface = net_interface_get(ns, index); switch (request) { + case SIOCSIFNAME: + req.data.pad[IFNAMSIZ - 1] = 0; + return net_interface_rename(ns, index, (const char *)req.data.pad); case SIOCGIFINDEX: req.data.value = (int32_t)index; break; case SIOCGIFHWADDR: net_memzero(&req.data, sizeof(req.data)); diff --git a/net/interface/nexthop.c b/net/interface/nexthop.c new file mode 100644 index 00000000..6c78fb37 --- /dev/null +++ b/net/interface/nexthop.c @@ -0,0 +1,92 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Serialized by ordinary network execution ownership, as are route tables. */ +static struct net_nexthop_node *initial_nexthops; + +/** @copydoc net_nexthop_get */ +const struct net_nexthop *net_nexthop_get(struct net_namespace *ns, uint32_t id) +{ + for (struct net_nexthop_node *entry = ns ? ns->nexthops : initial_nexthops; + entry; entry = entry->next) { + if (entry->value.id == id) return &entry->value; + if (entry->value.id > id) break; + } + return NULL; +} + +/** @copydoc net_nexthop_next */ +const struct net_nexthop *net_nexthop_next(struct net_namespace *ns, uint32_t after) +{ + for (struct net_nexthop_node *entry = ns ? ns->nexthops : initial_nexthops; + entry; entry = entry->next) + if (entry->value.id > after) return &entry->value; + return NULL; +} + +/** @copydoc net_nexthop_update */ +int net_nexthop_update(struct net_namespace *ns, const struct net_nexthop *value, + bool remove, bool replace, bool create) +{ + if (!value || !value->id) return -LINUX_EINVAL; + struct net_nexthop_node **slot = ns ? &ns->nexthops : &initial_nexthops; + while (*slot && (*slot)->value.id < value->id) slot = &(*slot)->next; + struct net_nexthop_node *entry = *slot; + bool found = entry && entry->value.id == value->id; + if (remove) { + if (!found) return -LINUX_ENOENT; + struct net_nexthop old = entry->value; + *slot = entry->next; + net_ipv4_nexthop_changed(ns, old.id, NULL); + net_ipv6_nexthop_changed(ns, old.id, NULL); + kernel_free(entry); + netlink_network_changed(ns); + netlink_nexthop_changed(ns, &old, true); + return 0; + } + if (value->family != AF_INET && value->family != AF_INET6) return -LINUX_EAFNOSUPPORT; + if (value->flags & ~RTNH_F_ONLINK) return -LINUX_EOPNOTSUPP; + if (!net_interface_exists(ns, value->ifindex)) return -LINUX_ENODEV; + if ((value->family == AF_INET && value->gateway.ipv4 >= 0xe0000000u) || + (value->family == AF_INET6 && value->gateway.ipv6.s6_addr[0] == 0xff)) + return -LINUX_EINVAL; + if (found) { + if (!replace) return -LINUX_EEXIST; + if (entry->value.family != value->family) return -LINUX_EAFNOSUPPORT; + entry->value = *value; + net_ipv4_nexthop_changed(ns, value->id, value); + net_ipv6_nexthop_changed(ns, value->id, value); + } else { + if (!create) return -LINUX_ENOENT; + entry = kernel_malloc(sizeof(*entry)); + if (!entry) return -LINUX_ENOMEM; + entry->value = *value; + entry->next = *slot; + *slot = entry; + } + netlink_network_changed(ns); + netlink_nexthop_changed(ns, value, false); + return 0; +} + +/** @copydoc net_nexthops_remove_interface */ +void net_nexthops_remove_interface(struct net_namespace *ns, uint32_t ifindex) +{ + const struct net_nexthop *value; + uint32_t after = 0; + while ((value = net_nexthop_next(ns, after))) { + after = value->id; + if (value->ifindex == ifindex) { + struct net_nexthop removed = *value; + (void)net_nexthop_update(ns, &removed, true, false, false); + } + } +} diff --git a/net/interface/routes.c b/net/interface/routes.c index 05334c95..01e42b69 100644 --- a/net/interface/routes.c +++ b/net/interface/routes.c @@ -2,8 +2,11 @@ #include #include #include +#include #include #include +#include +#include static struct net_ipv4_route_node *ipv4_routes; @@ -36,13 +39,17 @@ uint32_t net_ipv4_routes(struct net_namespace *ns, struct net_ipv4_route *out, u struct net_interface *iface = net_interface_get(ns, index); if (!iface || !iface->config.local_ip || (index == NET_IF_LOOPBACK && !iface->up)) continue; - ipv4_snapshot_add(out, capacity, &count, (struct net_ipv4_route){ + if (!(iface->ipv4_address.flags & IFA_F_NOPREFIXROUTE)) + ipv4_snapshot_add(out, capacity, &count, (struct net_ipv4_route){ .destination = iface->config.local_ip & iface->config.subnet_mask, - .mask = iface->config.subnet_mask, .ifindex = index, .flags = RTF_UP}); + .mask = iface->config.subnet_mask, .ifindex = index, + .metric = iface->ipv4_address.metric, .flags = RTF_UP, + .protocol = RTPROT_KERNEL, .scope = RT_SCOPE_LINK}); if (iface->config.gateway_ip) ipv4_snapshot_add(out, capacity, &count, (struct net_ipv4_route){ .gateway = iface->config.gateway_ip, .ifindex = index, - .metric = iface->default_metric, .flags = RTF_UP | RTF_GATEWAY}); + .metric = iface->default_metric, .flags = RTF_UP | RTF_GATEWAY, + .protocol = RTPROT_BOOT}); } for (struct net_ipv4_route_node *entry = ns ? ns->ipv4_routes : ipv4_routes; entry; entry = entry->next) ipv4_snapshot_add(out, capacity, &count, entry->route); @@ -89,14 +96,15 @@ int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32 .destination = destination, .next_hop = destination, .ifindex = local}; return 0; } - if (destination == UINT32_MAX) { - uint32_t index = scope; + bool multicast = (destination & 0xf0000000u) == 0xe0000000u; + if (destination == UINT32_MAX || multicast) { + uint32_t index = scope ? scope : source ? net_interface_for_ipv4(ns, source) : 0; if (!index) { for (index = net_interface_next(ns, NET_IF_LOOPBACK); index; index = net_interface_next(ns, index)) if (net_interface_is_ready(ns, index)) break; } - if (!index || index == NET_IF_LOOPBACK) return -LINUX_ENETUNREACH; + if (!index || (!multicast && index == NET_IF_LOOPBACK)) return -LINUX_ENETUNREACH; if (!net_interface_is_ready(ns, index)) return -LINUX_ENETDOWN; struct net_interface *iface = net_interface_get(ns, index); *out = (struct net_ipv4_path){.source = source ? source : iface->config.local_ip, @@ -113,8 +121,10 @@ int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32 (index == NET_IF_LOOPBACK && !iface->up)) continue; struct net_ipv4_route connected = { .destination = iface->config.local_ip & iface->config.subnet_mask, - .mask = iface->config.subnet_mask, .ifindex = index, .flags = RTF_UP}; - ipv4_consider(ns, &connected, destination, scope, &best, &found); + .mask = iface->config.subnet_mask, .ifindex = index, + .metric = iface->ipv4_address.metric, .flags = RTF_UP}; + if (!(iface->ipv4_address.flags & IFA_F_NOPREFIXROUTE)) + ipv4_consider(ns, &connected, destination, scope, &best, &found); if (iface->config.gateway_ip) { struct net_ipv4_route def = {.gateway = iface->config.gateway_ip, .ifindex = index, .metric = iface->default_metric, .flags = RTF_UP | RTF_GATEWAY}; @@ -126,7 +136,9 @@ int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32 if (!found) return -LINUX_ENETUNREACH; struct net_interface *iface = net_interface_get(ns, best.ifindex); if (!source && (!iface || !iface->config.local_ip)) return -LINUX_EADDRNOTAVAIL; - *out = (struct net_ipv4_path){.source = source ? source : iface->config.local_ip, + uint32_t selected_source = best.preferred_source; + if (!net_interface_for_ipv4(ns, selected_source)) selected_source = iface->config.local_ip; + *out = (struct net_ipv4_path){.source = source ? source : selected_source, .destination = destination, .next_hop = best.gateway ? best.gateway : destination, .ifindex = best.ifindex}; return 0; @@ -143,14 +155,17 @@ int net_ipv4_route_update(struct net_namespace *ns, const struct net_ipv4_route if ((route.flags & RTF_HOST) && route.mask != UINT32_MAX) return -LINUX_EINVAL; struct net_interface *iface = net_interface_get(ns, route.ifindex); if (!iface) return -LINUX_ENODEV; - if (!remove && route.gateway && (!iface->config.local_ip || + if (!remove && route.preferred_source && !net_interface_for_ipv4(ns, route.preferred_source)) + return -LINUX_EADDRNOTAVAIL; + if (!remove && !route.onlink && route.gateway && (!iface->config.local_ip || (route.gateway & iface->config.subnet_mask) != (iface->config.local_ip & iface->config.subnet_mask))) return -LINUX_ENETUNREACH; route.flags |= RTF_UP; /* The compatibility configuration owns one default gateway per NIC. * This also keeps DHCP's existing default-route updates observable. */ - if (!route.mask && route.gateway) { + if (!route.mask && route.gateway && !route.protocol && !route.scope && + !route.preferred_source && !route.nexthop_id && !route.onlink) { if (remove) { if (!iface->config.gateway_ip || iface->config.gateway_ip != route.gateway) return -LINUX_ESRCH; @@ -168,7 +183,8 @@ int net_ipv4_route_update(struct net_namespace *ns, const struct net_ipv4_route while (*slot) { struct net_ipv4_route *r = &(*slot)->route; if (r->destination == route.destination && r->mask == route.mask && - r->ifindex == route.ifindex && r->gateway == route.gateway) break; + r->ifindex == route.ifindex && r->gateway == route.gateway && + r->nexthop_id == route.nexthop_id) break; slot = &(*slot)->next; } if (remove) { @@ -190,3 +206,25 @@ int net_ipv4_route_update(struct net_namespace *ns, const struct net_ipv4_route *slot = entry; return 0; } + +/** @copydoc net_ipv4_nexthop_changed */ +void net_ipv4_nexthop_changed(struct net_namespace *ns, uint32_t id, + const struct net_nexthop *nexthop) +{ + struct net_ipv4_route_node **slot = ns ? &ns->ipv4_routes : &ipv4_routes; + while (*slot) { + struct net_ipv4_route_node *entry = *slot; + if (entry->route.nexthop_id != id) { slot = &entry->next; continue; } + if (!nexthop) { + *slot = entry->next; + kernel_free(entry); + continue; + } + entry->route.ifindex = nexthop->ifindex; + entry->route.gateway = nexthop->gateway.ipv4; + entry->route.onlink = (nexthop->flags & RTNH_F_ONLINK) != 0; + entry->route.flags &= ~RTF_GATEWAY; + if (entry->route.gateway) entry->route.flags |= RTF_GATEWAY; + slot = &entry->next; + } +} diff --git a/net/interface/socket.c b/net/interface/socket.c index 11903938..4f54c5a1 100644 --- a/net/interface/socket.c +++ b/net/interface/socket.c @@ -7,17 +7,21 @@ #include #include #include +#include -/** @brief Apply Linux SO_BINDTODEVICE validation for one socket's bound index. +/** @brief Apply Linux named or numeric binding for one socket's bound index. * @param ns Borrowed creating network, NULL for the initial network. - * @param set Update when true, query otherwise. @param address User name buffer. + * @param set Update when true, query otherwise. + * @param option SO_BINDTODEVICE or SO_BINDTOIFINDEX. + * @param address User name or native int buffer. * @param length Input byte count for updates, user socklen_t pointer for queries. * @param index Current bound device; changed only after a successful update. * @return Zero or negative errno. User memory is copied with the socket helpers * under execution ownership. Updating a bound socket requires CAP_NET_RAW in * the network owner user namespace. No provider pointer escapes. */ -int net_interface_device_option(struct net_namespace *ns, bool set, uint64_t address, uint64_t length, uint32_t *index) +int net_interface_device_option(struct net_namespace *ns, bool set, uint32_t option, + uint64_t address, uint64_t length, uint32_t *index) { if (!index) return -LINUX_EINVAL; struct task *task = sched_current_task(); @@ -26,13 +30,23 @@ int net_interface_device_option(struct net_namespace *ns, bool set, uint64_t add uint32_t size = (uint32_t)length; if ((int32_t)size < 0) return -LINUX_EINVAL; if (!task) return -LINUX_EPERM; - if (size >= sizeof(name)) size = sizeof(name) - 1; - if (size) { - int result = socket_user_import(task, address, name, size); + uint32_t selected; + if (option == SO_BINDTOIFINDEX) { + int value; + if (size < sizeof(value)) return -LINUX_EINVAL; + int result = socket_user_import(task, address, &value, sizeof(value)); if (result) return result; + if (value < 0) return -LINUX_EINVAL; + selected = (uint32_t)value; + } else { + if (size >= sizeof(name)) size = sizeof(name) - 1; + if (size) { + int result = socket_user_import(task, address, name, size); + if (result) return result; + } + selected = name[0] ? net_interface_index(ns, name) : 0; + if (name[0] && !selected) return -LINUX_ENODEV; } - uint32_t selected = name[0] ? net_interface_index(ns, name) : 0; - if (name[0] && !selected) return -LINUX_ENODEV; if (*index && !task_ns_capable(task, ns ? ns->user_ns : NULL, CAP_NET_RAW)) return -LINUX_EPERM; *index = selected; return 0; @@ -41,6 +55,17 @@ int net_interface_device_option(struct net_namespace *ns, bool set, uint64_t add int result = socket_user_length(task, length, &capacity); if (result) return result; if ((int32_t)capacity < 0) return -LINUX_EINVAL; + if (option == SO_BINDTOIFINDEX) { + uint32_t size = capacity < sizeof(*index) ? capacity : sizeof(*index); + result = socket_user_prepare(task, address, size, true); + if (result) return result; + if (size) { + if (!user_range_writable(address, size)) return -LINUX_EFAULT; + __builtin_memcpy((void *)(uintptr_t)address, index, size); + } + *(uint32_t *)(uintptr_t)length = size; + return 0; + } uint32_t size = 0; if (*index) { if (capacity < sizeof(name)) return -LINUX_EINVAL; diff --git a/net/interface/state.c b/net/interface/state.c index 95db581b..68e14426 100644 --- a/net/interface/state.c +++ b/net/interface/state.c @@ -3,7 +3,10 @@ #include #include #include +#include #include +#include +#include #include /* All state is serialized by the existing network execution owner. */ @@ -15,6 +18,17 @@ static struct net_interface initial_loopback = { .config = {.local_ip = 0x7f000001u, .subnet_mask = 0xff000000u}, }; +/** @brief Format the registration-time Ethernet name without retained state. + * @param index Candidate Ethernet unit plus two. @param out Fixed name output. + */ +static void interface_default_name(uint32_t index, char out[NET_IF_NAME_LEN]) +{ + struct text_stream text = {.buffer = out, .capacity = NET_IF_NAME_LEN - 1}; + text_string(&text, "eth"); + text_unsigned(&text, index - 2); + out[text.written] = 0; +} + /** @copydoc net_interface_register */ int net_interface_register(uint32_t index) { @@ -26,6 +40,14 @@ int net_interface_register(uint32_t index) if (!iface) return -LINUX_ENOMEM; __builtin_memset(iface, 0, sizeof(*iface)); iface->index = index; + uint32_t candidate = index; + do { + interface_default_name(candidate, iface->name); + ++candidate; + if (candidate < 2) candidate = 2; + } while (net_interface_index(NULL, iface->name)); + iface->name_assign_type = 1; + netdev_get_info(index, &iface->device); iface->up = true; iface->next = *slot; *slot = iface; @@ -39,6 +61,7 @@ void net_interface_remove(uint32_t index) while (*slot && (*slot)->index != index) slot = &(*slot)->next; if (!*slot) return; struct net_interface *iface = *slot; + net_nexthops_remove_interface(NULL, index); net_ipv4_routes_remove_interface(NULL, index); *slot = iface->next; kernel_free(iface); @@ -71,37 +94,129 @@ bool net_interface_exists(struct net_namespace *ns, uint32_t index) /** @copydoc net_interface_name */ bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[NET_IF_NAME_LEN]) { - if (!out || !net_interface_exists(ns, index)) return false; + struct net_interface *iface = net_interface_get(ns, index); + if (!out || !iface) return false; __builtin_memset(out, 0, NET_IF_NAME_LEN); - if (index == NET_IF_LOOPBACK) { + if (iface->name[0]) { + __builtin_memcpy(out, iface->name, NET_IF_NAME_LEN); + } else if (index == NET_IF_LOOPBACK) { out[0] = 'l'; out[1] = 'o'; - return true; + } else { + interface_default_name(index, out); } - out[0] = 'e'; out[1] = 't'; out[2] = 'h'; - uint32_t value = index - 2, count = 0; - char digits[10]; - do { digits[count++] = (char)('0' + value % 10); value /= 10; } while (value); - for (uint32_t i = 0; i < count; ++i) out[3 + i] = digits[count - i - 1]; return true; } +/** @copydoc net_interface_device_path */ +int net_interface_device_path(struct net_namespace *ns,uint32_t index, + char out[NET_IF_DEVICE_PATH_LEN]) +{ + out[0]=0; + struct net_interface *iface=net_interface_get(ns,index); + char name[NET_IF_NAME_LEN]; + if(!iface || !net_interface_name(ns,index,name))return -ENODEV; + struct text_stream text={.buffer=out,.capacity=NET_IF_DEVICE_PATH_LEN-1}; + if(index==NET_IF_LOOPBACK || !iface->device.present)text_string(&text,"/devices/virtual"); + else { + text_string(&text,"/devices/pci0000:00/0000:"); + text_hex(&text,iface->device.bus,2);text_string(&text,":"); + text_hex(&text,iface->device.slot,2);text_string(&text,"."); + text_hex(&text,iface->device.function,1); + } + text_string(&text,"/net/");text_string(&text,name);out[text.written]=0; + return 0; +} + +/** @brief Publish copied interface properties with optional synthetic or rename data. + * @param ns Borrowed scope. @param index Live interface. @param action Valid action. + * @param uuid Optional UUID. @param old_path Optional pre-rename canonical path. + */ +static void interface_uevent(struct net_namespace *ns, uint32_t index, + const char *action, const char *uuid, const char *old_path) +{ + char path[NET_IF_DEVICE_PATH_LEN],name[NET_IF_NAME_LEN],properties[256]; + if(net_interface_device_path(ns,index,path) || !net_interface_name(ns,index,name))return; + struct text_stream text={.buffer=properties,.capacity=sizeof(properties)}; + text_string(&text,"INTERFACE=");text_string(&text,name);text_bytes(&text,"",1); + text_string(&text,"IFINDEX=");text_unsigned(&text,index);text_bytes(&text,"",1); + if(uuid) { + text_string(&text,"SYNTH_UUID=");text_string(&text,uuid);text_bytes(&text,"",1); + } + if (old_path) { + text_string(&text, "DEVPATH_OLD="); + text_string(&text, old_path); + text_bytes(&text, "", 1); + } + if(text.position<=sizeof(properties)) + netlink_uevent_network(ns,action,path,"net",properties,text.written); +} + +/** @copydoc net_interface_uevent */ +void net_interface_uevent(struct net_namespace *ns, uint32_t index, + const char *action, const char *uuid) +{ + interface_uevent(ns, index, action, uuid, NULL); +} + /** @copydoc net_interface_index */ uint32_t net_interface_index(struct net_namespace *ns, const char *name) { if (!name) return 0; - if (!__builtin_strcmp(name, "lo")) return NET_IF_LOOPBACK; - if (name[0] != 'e' || name[1] != 't' || name[2] != 'h' || - name[3] < '0' || name[3] > '9') return 0; - if (name[3] == '0' && name[4]) return 0; - uint32_t value = 0, i = 3; - for (; name[i]; ++i) { - if (i >= NET_IF_NAME_LEN - 1 || name[i] < '0' || name[i] > '9' || - value > (UINT32_MAX - 2u - (uint32_t)(name[i] - '0')) / 10u) - return 0; - value = value * 10u + (uint32_t)(name[i] - '0'); + for (uint32_t index = net_interface_next(ns, 0); index; + index = net_interface_next(ns, index)) { + char current[NET_IF_NAME_LEN]; + if (net_interface_name(ns, index, current) && !__builtin_strcmp(name, current)) + return index; } - uint32_t index = value + 2u; - return net_interface_get(ns, index) ? index : 0; + return 0; +} + +/** @copydoc net_interface_rename */ +int net_interface_rename(struct net_namespace *ns, uint32_t index, const char *name) +{ + struct net_interface *iface = net_interface_get(ns, index); + if (!iface) return -LINUX_ENODEV; + if (!name || !name[0] || !__builtin_strcmp(name, ".") || !__builtin_strcmp(name, "..")) + return -LINUX_EINVAL; + unsigned length = 0; + const char *format = NULL; + for (; length < NET_IF_NAME_LEN && name[length]; ++length) { + unsigned char c = (unsigned char)name[length]; + if (c == '/' || c == ':' || c == ' ' || (c >= '\t' && c <= '\r')) + return -LINUX_EINVAL; + if (c == '%') { + if (format || length + 1 >= NET_IF_NAME_LEN || name[length + 1] != 'd') + return -LINUX_EINVAL; + format = name + length; + } + } + if (length == NET_IF_NAME_LEN) return -LINUX_EINVAL; + char current[NET_IF_NAME_LEN], candidate[NET_IF_NAME_LEN] = {0}; + net_interface_name(ns, index, current); + if (!__builtin_strcmp(current, name)) return 0; + __builtin_memcpy(candidate, name, length + 1); + if (format) { + unsigned unit = 0; + for (; unit < 32768; ++unit) { + struct text_stream text = {.buffer = candidate, .capacity = sizeof(candidate) - 1}; + text_bytes(&text, name, (uint32_t)(format - name)); + text_unsigned(&text, unit); + text_string(&text, format + 2); + candidate[text.written] = 0; + if (!net_interface_index(ns, candidate)) break; + } + if (unit == 32768) return -LINUX_ENFILE; + } else if (net_interface_index(ns, candidate)) { + return -LINUX_EEXIST; + } + char old_path[NET_IF_DEVICE_PATH_LEN]; + net_interface_device_path(ns, index, old_path); + __builtin_memset(iface->name, 0, sizeof(iface->name)); + __builtin_memcpy(iface->name, candidate, __builtin_strlen(candidate) + 1); + iface->name_assign_type = 4; + interface_uevent(ns, index, "move", NULL, old_path); + netlink_network_changed(ns); + return 0; } /** @copydoc net_interface_is_up */ diff --git a/net/internal.h b/net/internal.h index b0167d70..b25c90e8 100644 --- a/net/internal.h +++ b/net/internal.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -178,6 +179,9 @@ struct net_socket { bool ipv6, mapped, v6only, bound, reuse, dont_fragment; bool nodelay; int unicast_hops, mtu_discover; + int ipv4_ttl, ipv4_mtu_discover; + bool ipv4_pktinfo, ipv4_recvttl; + bool recv_pktinfo, recv_hoplimit; uint32_t backlog; struct net_socket *listener; uint16_t local_port; diff --git a/net/ipv4/core.c b/net/ipv4/core.c index 5ef524da..8306a292 100644 --- a/net/ipv4/core.c +++ b/net/ipv4/core.c @@ -1,32 +1,53 @@ #include "../internal.h" /** - * Net ip for us. - * @param dst_ip Value supplied by the caller. - * @return The value or status produced by the operation. + * @brief Admit local, broadcast and multicast IPv4 for transport-level filtering. + * @param dst_ip Host-order IPv4 destination. + * @return Nonzero for a receivable destination. */ static int net_ip_for_us(uint32_t dst_ip); static uint16_t net_packet_ip_id; + +/** @brief Translate a checked IPv4 ICMP error to its Linux socket errno. + * @param type ICMP message type. @param code ICMP message code. + * @return Positive errno, or zero for a message outside the supported error set. */ +static int net_icmp_errno(uint8_t type, uint8_t code) +{ + static const int unreachable[] = { + LINUX_ENETUNREACH, LINUX_EHOSTUNREACH, LINUX_ENOPROTOOPT, LINUX_ECONNREFUSED, + LINUX_EMSGSIZE, LINUX_EOPNOTSUPP, LINUX_ENETUNREACH, LINUX_EHOSTDOWN, + LINUX_ENONET, LINUX_ENETUNREACH, LINUX_EHOSTUNREACH, LINUX_ENETUNREACH, + LINUX_EHOSTUNREACH, LINUX_EACCES, LINUX_EHOSTUNREACH, LINUX_EHOSTUNREACH + }; + if (type == 3 && code < sizeof(unreachable) / sizeof(unreachable[0])) + return unreachable[code]; + if (type == 11 && code <= 1) return LINUX_EHOSTUNREACH; + if (type == 12 && code <= 2) return LINUX_EPROTO; + return 0; +} /** - * Net ip for us. - * @param dst_ip Value supplied by the caller. - * @return The value or status produced by the operation. + * @brief Admit local, broadcast and multicast IPv4 for transport-level filtering. + * @param dst_ip Host-order IPv4 destination. + * @return Nonzero for a receivable destination. */ static int net_ip_for_us(uint32_t dst_ip) { return net_interface_for_ipv4(NULL, dst_ip) != 0 || + (dst_ip & 0xf0000000u) == 0xe0000000u || dst_ip == 0xffffffffu || dst_ip == 0; } /** * @brief Validate and dispatch an IPv4 Ethernet frame under network execution ownership. + * @param ifindex Receiving interface in the initial network. * @param frame Borrowed complete Ethernet frame, including its source MAC. * @param len Available frame bytes. * @param ping_wait Optional legacy ICMP waiter. * @param udp_wait Optional legacy UDP waiter. * @param tcp_wait Optional legacy TCP waiter. + * Valid ICMP errors retain the offender, MTU and original UDP quote for MSG_ERRQUEUE. */ void net_handle_ipv4_on(uint32_t ifindex, const uint8_t *frame, uint32_t len, struct net_ping_wait *ping_wait, @@ -76,7 +97,19 @@ void net_handle_ipv4_on(uint32_t ifindex, const uint8_t *frame, uint32_t len, } icmp = ip + ihl; icmp_len = (uint16_t)(total_len - ihl); - if (icmp_len < 8) { + if (icmp_len < 8 || net_checksum(icmp, icmp_len)) { + return; + } + int error = net_icmp_errno(icmp[0], icmp[1]); + if (error && icmp_len >= 36) { + struct sock_extended_err extended = {.ee_errno = (uint32_t)error, + .ee_origin = SO_EE_ORIGIN_ICMP, .ee_type = icmp[0], .ee_code = icmp[1], + .ee_info = icmp[0] == 3 && icmp[1] == 4 ? net_get_u16(icmp + 6) : 0}; + struct sockaddr_storage offender = {0}; + struct sockaddr_in from = {.sin_family = AF_INET, + .sin_addr.s_addr = __builtin_bswap32(src_ip)}; + net_memcpy(&offender, &from, sizeof(from)); + net_udp_error_input(NULL, ifindex, icmp + 8, icmp_len - 8, &extended, &offender); return; } if (icmp[0] == ICMP_ECHO_REPLY && ping_wait && diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c index f9bfe74c..0d935662 100644 --- a/net/ipv4/udp.c +++ b/net/ipv4/udp.c @@ -2,21 +2,19 @@ -/** - * Net send udp to mac. - * @param dst_mac Value supplied by the caller. - * @param src_ip Value supplied by the caller. - * @param dst_ip Value supplied by the caller. - * @param src_port Value supplied by the caller. - * @param dst_port Value supplied by the caller. - * @param payload Value supplied by the caller. - * @param payload_len Value supplied by the caller. - * @return The value or status produced by the operation. +/** @brief Build a UDP Ethernet frame with explicit IPv4 TOS, TTL and DF state. + * @param ifindex Ready output link. @param dst_mac Destination MAC. + * @param src_ip Host-order source. @param dst_ip Peer address. + * @param src_port Local port. @param dst_port Peer port. + * @param payload Borrowed bytes. @param payload_len Byte count. + * @param ttl IPv4 time to live. @param dont_fragment IPv4 DF policy. + * @param tos Full IPv4 DSCP and ECN byte, covered by the header checksum. + * @return Driver result or negative errno. Caller holds network execution ownership. */ -int net_send_udp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint32_t src_ip, - uint32_t dst_ip, uint16_t src_port, - uint16_t dst_port, const uint8_t *payload, - uint32_t payload_len) +static int udp_send_frame(uint32_t ifindex, const uint8_t *dst_mac, uint32_t src_ip, + uint32_t dst_ip, uint16_t src_port, uint16_t dst_port, + const uint8_t *payload, uint32_t payload_len, + uint8_t ttl, bool dont_fragment, uint8_t tos) { uint8_t frame[NET_FRAME_MAX]; uint8_t *ip = frame + 14; @@ -31,11 +29,11 @@ int net_send_udp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint32_t sr net_memzero(frame, 42u + payload_len); net_write_eth_on(ifindex, frame, dst_mac, ETH_TYPE_IPV4); ip[0] = 0x45; - ip[1] = 0; + ip[1] = tos; net_put_u16(ip + 2, total_len); net_put_u16(ip + 4, net_ipv4_id++); - net_put_u16(ip + 6, 0); - ip[8] = 64; + net_put_u16(ip + 6, dont_fragment ? 0x4000 : 0); + ip[8] = ttl; ip[9] = IPV4_PROTO_UDP; net_put_u32(ip + 12, src_ip); net_put_u32(ip + 16, dst_ip); @@ -48,6 +46,21 @@ int net_send_udp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint32_t sr return net_interface_is_ready(NULL, ifindex) ? netdev_send(ifindex, frame, 42u + payload_len) : -LINUX_ENETDOWN; } +/** @brief Build a compatibility UDP frame with TOS zero, TTL 64 and fragmentation permitted. + * @param ifindex Output device. @param dst_mac Destination MAC. + * @param src_ip Source address. @param dst_ip Peer address. + * @param src_port Local port. @param dst_port Peer port. + * @param payload Borrowed bytes. @param payload_len Bytes. + * @return Driver result or negative errno. Caller holds network execution ownership. + */ +int net_send_udp_to_mac_on(uint32_t ifindex, const uint8_t *dst_mac, uint32_t src_ip, + uint32_t dst_ip, uint16_t src_port, uint16_t dst_port, + const uint8_t *payload, uint32_t payload_len) +{ + return udp_send_frame(ifindex, dst_mac, src_ip, dst_ip, src_port, dst_port, + payload, payload_len, 64, false, 0); +} + /** * Net handle udp. * @param ip Value supplied by the caller. @@ -80,7 +93,8 @@ void net_handle_udp_on(uint32_t ifindex, const uint8_t *ip, uint32_t total_len, sum += IPV4_PROTO_UDP + udp_len; if (net_checksum_finish(net_checksum_partial(sum, udp, udp_len))) return; } - net_udp_input(NULL, src_ip, net_get_u32(ip + 16), src_port, dst_port, udp + 8, udp_len - 8, (int)ifindex); + net_udp_input_ex(NULL, src_ip, net_get_u32(ip + 16), src_port, dst_port, + udp + 8, udp_len - 8, (int)ifindex, ip[8]); if (!udp_wait || udp_wait->done || (udp_wait->ifindex && udp_wait->ifindex != ifindex)) return; if (udp_wait->src_port && src_port != udp_wait->src_port) { return; @@ -109,14 +123,11 @@ void net_handle_udp(const uint8_t *ip, uint32_t total_len, uint32_t ihl, net_handle_udp_on(netdev_next(0), ip, total_len, ihl, src_ip, wait); } -/** @brief Send an IPv4 datagram with an explicit bound interface or route selection. - * @param ns Borrowed route network. Hardware output belongs to the initial network. - * @param ifindex Bound device or zero. @param source Optional source address. - * @param destination Peer address. @param source_port Local port. @param destination_port Peer port. - * @param data Borrowed payload. @param length Bytes. @return Zero or negative errno. */ -int net_ipv4_send_udp_on(struct net_namespace *ns, uint32_t ifindex, uint32_t source, uint32_t destination, - uint16_t source_port, uint16_t destination_port, - const void *data, uint32_t length) +/** @copydoc net_ipv4_send_udp_options_tos */ +int net_ipv4_send_udp_options_tos(struct net_namespace *ns, uint32_t ifindex, uint32_t source, + uint32_t destination, uint16_t source_port, uint16_t destination_port, + const void *data, uint32_t length, uint8_t ttl, bool dont_fragment, + uint8_t tos) { if (length > 1472 || (length && !data)) return -LINUX_EMSGSIZE; struct net_ipv4_path path; @@ -127,13 +138,36 @@ int net_ipv4_send_udp_on(struct net_namespace *ns, uint32_t ifindex, uint32_t so struct net_interface *interface = net_interface_get(ns, path.ifindex); if (destination == UINT32_MAX || (interface && destination == interface->broadcast)) net_memcpy(mac, net_broadcast_mac, 6); + else if ((destination & 0xf0000000u) == 0xe0000000u) { + const uint8_t group_mac[6] = {1, 0, 0x5e, (uint8_t)((destination >> 16) & 0x7f), + (uint8_t)(destination >> 8), (uint8_t)destination}; + net_memcpy(mac, group_mac, sizeof(group_mac)); + } else if (net_resolve_mac_on(path.ifindex, path.next_hop, 1000, mac) < 0) return -LINUX_EHOSTUNREACH; - result = net_send_udp_to_mac_on(path.ifindex, mac, path.source, destination, - source_port, destination_port, data, length); + result = udp_send_frame(path.ifindex, mac, path.source, destination, + source_port, destination_port, data, length, ttl, dont_fragment, tos); return result < 0 ? result : 0; } +/** @copydoc net_ipv4_send_udp_options */ +int net_ipv4_send_udp_options(struct net_namespace *ns, uint32_t ifindex, uint32_t source, + uint32_t destination, uint16_t source_port, uint16_t destination_port, + const void *data, uint32_t length, uint8_t ttl, bool dont_fragment) +{ + return net_ipv4_send_udp_options_tos(ns, ifindex, source, destination, source_port, + destination_port, data, length, ttl, dont_fragment, 0); +} + +/** @copydoc net_ipv4_send_udp_on */ +int net_ipv4_send_udp_on(struct net_namespace *ns, uint32_t ifindex, uint32_t source, + uint32_t destination, uint16_t source_port, uint16_t destination_port, + const void *data, uint32_t length) +{ + return net_ipv4_send_udp_options(ns, ifindex, source, destination, source_port, + destination_port, data, length, 64, false); +} + /** @brief Send initial-network UDP with automatic output device selection. * @param source Optional source. @param destination Peer. @param source_port Local port. * @param destination_port Peer port. @param data Payload. @param length Bytes. diff --git a/net/ipv6/core.c b/net/ipv6/core.c index be522436..746f7b50 100644 --- a/net/ipv6/core.c +++ b/net/ipv6/core.c @@ -5,8 +5,10 @@ #include #include #include +#include #include #include +#include #define IPV6_ETHERTYPE 0x86ddu #define IPV6_LINK_MTU 1500u @@ -227,39 +229,72 @@ int net_ipv6_multicast_change(struct net_namespace *ns, const struct in6_addr *a g->reports=2;g->query_pending=false;g->report_at=time_uptime_ms();return 0;} return -LINUX_ENOBUFS; } -/** @brief Add, replace or remove a route. @param ns Borrowed network, NULL for the permanent initial network. +/** @brief Add, replace or remove a metric-qualified route while preserving insertion order. + * @param ns Borrowed network, NULL for the permanent initial network. * @param route Checked route in network byte order. * @param remove Remove rather than add. @return Zero or negative errno. */ int net_ipv6_route_update(struct net_namespace *ns, const struct net_ipv6_route *route,bool remove) { struct net_ipv6_state *state = net_ipv6_state_get(ns); if(!route || route->prefix_length>128 || !net_interface_exists(state->net_ns, route->ifindex) || - ipv6_multicast(&route->gateway))return -LINUX_EINVAL; + ipv6_multicast(&route->gateway) || route->preference==2 || route->preference>3)return -LINUX_EINVAL; + if(!remove && !ipv6_unspecified(&route->preferred_source) && + !ipv6_find_address(state,&route->preferred_source,0))return -LINUX_EADDRNOTAVAIL; struct net_ipv6_route normalized=*route;ipv6_mask(&normalized.destination,normalized.prefix_length); struct ipv6_route_slot *free_slot=0; for(uint32_t i=0;iroutes[i];if(!s->used){if(!free_slot)free_slot=s;continue;} if(s->value.ifindex==normalized.ifindex && s->value.prefix_length==normalized.prefix_length && - ipv6_equal(&s->value.destination,&normalized.destination) && ipv6_equal(&s->value.gateway,&normalized.gateway)){ + ipv6_equal(&s->value.destination,&normalized.destination) && ipv6_equal(&s->value.gateway,&normalized.gateway) && + s->value.nexthop_id==normalized.nexthop_id && s->value.metric==normalized.metric){ if(remove)s->used=false;else{s->value=normalized;s->automatic=false;s->address_until=s->ra_until=0;} netlink_ipv6_changed(state->net_ns);return 0;} } if(remove)return -LINUX_ESRCH; if(!free_slot)return -LINUX_ENOBUFS; - free_slot->value=normalized;free_slot->used=true;free_slot->automatic=false;netlink_ipv6_changed(state->net_ns);return 0; + /* Reuse capacity without moving a new route ahead of surviving equal-priority routes. */ + struct ipv6_route_slot *last = &state->routes[IPV6_ROUTE_MAX - 1]; + __builtin_memmove(free_slot, free_slot + 1, (size_t)(last - free_slot) * sizeof(*free_slot)); + *last = (struct ipv6_route_slot){.value = normalized, .used = true}; + netlink_ipv6_changed(state->net_ns); + return 0; +} + +/** @copydoc net_ipv6_nexthop_changed */ +void net_ipv6_nexthop_changed(struct net_namespace *ns, uint32_t id, + const struct net_nexthop *nexthop) +{ + struct net_ipv6_state *state = net_ipv6_state_get(ns); + for (uint32_t i=0;iroutes[i]; + if (!slot->used || slot->value.nexthop_id != id) continue; + if (!nexthop) { slot->used=false; continue; } + slot->value.ifindex = nexthop->ifindex; + slot->value.gateway = nexthop->gateway.ipv6; + slot->value.onlink = (nexthop->flags & RTNH_F_ONLINK) != 0; + slot->value.flags &= ~RTF_GATEWAY; + if (!ipv6_unspecified(&slot->value.gateway)) slot->value.flags |= RTF_GATEWAY; + } } + /** @brief Recompute an automatic connected route from manually assigned addresses. * @param state Borrowed protocol owner under network execution ownership. * @param address An address in the prefix. @param bits Prefix width. * @return Zero or negative capacity errno. * @param ifindex Stable interface index within this network. + * @param metric Requested prefix-route metric, zero selects the default 256. + * The caller publishes the final address and route state after successful mutation. */ -static int ipv6_connected_route(struct net_ipv6_state *state, const struct in6_addr *address,uint32_t bits,uint32_t ifindex) +static int ipv6_connected_route(struct net_ipv6_state *state, const struct in6_addr *address, + uint32_t bits,uint32_t ifindex,uint32_t metric) { + if (!metric) metric=256; struct in6_addr prefix=*address;ipv6_mask(&prefix,bits);uint64_t deadline=0,now=time_uptime_ms(); for(uint32_t i=0;iaddresses[i]; - if(a->used && !a->autonomous && a->value.ifindex==ifindex && a->value.prefix_length==bits && + uint32_t priority=a->value.route_metric ? a->value.route_metric : 256; + if(a->used && !a->autonomous && !(a->value.flags & NET_IPV6_ADDR_NOPREFIXROUTE) && + priority==metric && a->value.ifindex==ifindex && a->value.prefix_length==bits && ipv6_prefix_equal(&a->value.address,&prefix,bits) && !ipv6_expired(a->value.valid_until,now) && a->value.valid_until>deadline)deadline=a->value.valid_until; } @@ -268,18 +303,19 @@ static int ipv6_connected_route(struct net_ipv6_state *state, const struct in6_a struct ipv6_route_slot *r=&state->routes[i]; if(!r->used){if(!empty)empty=r;continue;} if(r->value.ifindex==ifindex && r->value.prefix_length==bits && ipv6_unspecified(&r->value.gateway) && + r->value.metric==metric && !r->value.nexthop_id && ipv6_equal(&r->value.destination,&prefix)){slot=r;break;} } if(slot && !slot->automatic)return 0; if(!slot){if(!deadline)return 0;if(!empty)return -LINUX_ENOBUFS;slot=empty;net_memzero(slot,sizeof(*slot)); slot->used=true;slot->automatic=true;slot->value.destination=prefix;slot->value.ifindex=ifindex; - slot->value.prefix_length=bits;slot->value.metric=256; + slot->value.prefix_length=bits;slot->value.metric=metric;slot->value.protocol=RTPROT_KERNEL; slot->value.flags=RTF_UP | (bits==128?RTF_HOST:0);} slot->address_until=deadline; if(slot->ra_until && ipv6_expired(slot->ra_until,now))slot->ra_until=0; slot->value.valid_until=slot->address_until>slot->ra_until?slot->address_until:slot->ra_until; if(!slot->value.valid_until)slot->used=false; - netlink_ipv6_changed(state->net_ns);return 0; + return 0; } /** @brief Apply a manual or SLAAC address and associated membership. * @param state Borrowed protocol owner under network execution ownership. @@ -297,16 +333,16 @@ static int ipv6_address_set(struct net_ipv6_state *state, const struct net_ipv6_ if(slot->value.ifindex!=1)(void)net_ipv6_multicast_change(state->net_ns, &group,slot->value.ifindex,-1); bool connected=slot->value.ifindex!=1 && !slot->autonomous; struct net_ipv6_address old=slot->value;slot->used=false; - if(connected)(void)ipv6_connected_route(state,&old.address,old.prefix_length,old.ifindex); + if(connected)(void)ipv6_connected_route(state,&old.address,old.prefix_length,old.ifindex,old.route_metric); netlink_ipv6_changed(state->net_ns);return 0;} if(slot){struct net_ipv6_address old=slot->value;bool old_auto=slot->autonomous; uint32_t flags=slot->value.flags & (NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED); slot->value=*address;slot->value.flags|=flags;slot->value.scope=ipv6_scope(&address->address); slot->autonomous=autonomous; - if(old.ifindex!=1 && !old_auto)(void)ipv6_connected_route(state,&old.address,old.prefix_length,old.ifindex); - if(address->ifindex!=1 && !autonomous){int rc=ipv6_connected_route(state,&address->address,address->prefix_length,address->ifindex); + if(old.ifindex!=1 && !old_auto)(void)ipv6_connected_route(state,&old.address,old.prefix_length,old.ifindex,old.route_metric); + if(address->ifindex!=1 && !autonomous){int rc=ipv6_connected_route(state,&address->address,address->prefix_length,address->ifindex,address->route_metric); if(rc<0){slot->value=old;slot->autonomous=old_auto; - if(old.ifindex!=1 && !old_auto)(void)ipv6_connected_route(state,&old.address,old.prefix_length,old.ifindex); + if(old.ifindex!=1 && !old_auto)(void)ipv6_connected_route(state,&old.address,old.prefix_length,old.ifindex,old.route_metric); return rc;}} netlink_ipv6_changed(state->net_ns);return 0;} for(uint32_t i=0;iaddresses[i].used){slot=&state->addresses[i];break;} @@ -322,7 +358,7 @@ static int ipv6_address_set(struct net_ipv6_state *state, const struct net_ipv6_ struct ipv6_group_slot *g=ipv6_find_group(state,&group,address->ifindex); if(g && g->refs==1 && g->reports==2){g->report_at=slot->dad_at;slot->dad_wait_mld=true;} } - if(address->ifindex!=1 && !autonomous){int ret=ipv6_connected_route(state,&address->address,address->prefix_length,address->ifindex); + if(address->ifindex!=1 && !autonomous){int ret=ipv6_connected_route(state,&address->address,address->prefix_length,address->ifindex,address->route_metric); if(ret<0){slot->used=false;(void)net_ipv6_multicast_change(state->net_ns, &group,address->ifindex,-1);return ret;}} netlink_ipv6_changed(state->net_ns);return 0; } @@ -347,6 +383,7 @@ int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination, if(!destination || !out_path || ipv6_unspecified(destination) || (scope && !net_interface_exists(state->net_ns, scope)))return -LINUX_EINVAL; uint64_t now=time_uptime_ms();uint32_t ifindex=0,mtu=IPV6_LINK_MTU; struct in6_addr next=*destination; + struct in6_addr route_source=ipv6_zero; struct ipv6_address_slot *local=ipv6_find_address(state,destination,scope); if(ipv6_equal(destination,&ipv6_loop)){ifindex=1;mtu=65575;} else if(local && !(local->value.flags&(NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED))){ @@ -371,11 +408,16 @@ int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination, if(!binding || binding->value.flags&(NET_IPV6_ADDR_TENTATIVE|NET_IPV6_ADDR_DADFAILED) || ipv6_expired(binding->value.valid_until,now))continue; } + int preference=r->value.preference==1 ? 1 : r->value.preference==3 ? -1 : 0; + int best_preference=!best ? 0 : best->value.preference==1 ? 1 : best->value.preference==3 ? -1 : 0; if(!best || r->value.prefix_length>best->value.prefix_length || - (r->value.prefix_length==best->value.prefix_length && r->value.metricvalue.metric))best=r; + (r->value.prefix_length==best->value.prefix_length && + (r->value.metricvalue.metric || + (r->value.metric==best->value.metric && preference>best_preference))))best=r; } if(!best)return matched_route?-LINUX_EADDRNOTAVAIL:-LINUX_ENETUNREACH; ifindex=best->value.ifindex; + route_source=best->value.preferred_source; if(!ipv6_unspecified(&best->value.gateway))next=best->value.gateway; } if(scope && scope!=ifindex)return -LINUX_ENETUNREACH; @@ -399,6 +441,7 @@ int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination, if(ifindex!=1 && link_destination && ipv6_linklocal(&a->value.address))score+=512; if(!(a->value.flags&NET_IPV6_ADDR_DEPRECATED) && !ipv6_expired(a->value.preferred_until,now))score+=256; if(ipv6_equal(destination,&a->value.address))score+=512; + if(ipv6_equal(&route_source,&a->value.address))score+=2048; if(!source || score>best_score){source=a;best_score=score;} } if(!source)return -LINUX_EADDRNOTAVAIL; @@ -793,6 +836,22 @@ static void ipv6_error(struct net_ipv6_state *state, const uint8_t *ip,uint32_t net_put_u16(error+2,net_ipv6_checksum(&path.source,&path.destination,58,error,n+8)); if(net_ipv6_output(state->net_ns, &path,58,error,n+8,64,0,false,false)>=0)++state->error_count; } +/** @brief Translate received ICMPv6 errors to Linux socket errno values. + * @param type Error type from one through four. @param code Type-specific error code. + * @return Positive errno, with EPROTO for an unknown destination-unreachable code. */ +static int ipv6_icmp_errno(uint8_t type, uint8_t code) +{ + static const int unreachable[] = { + LINUX_ENETUNREACH, LINUX_EACCES, LINUX_EHOSTUNREACH, LINUX_EHOSTUNREACH, + LINUX_ECONNREFUSED, LINUX_EACCES, LINUX_EACCES + }; + if (type == 1 && code < sizeof(unreachable) / sizeof(unreachable[0])) + return unreachable[code]; + if (type == 2) return LINUX_EMSGSIZE; + if (type == 3) return LINUX_EHOSTUNREACH; + return LINUX_EPROTO; +} + /** @brief Process a validated ICMPv6 message. @param state Borrowed protocol owner under network execution ownership. * @param ip Original packet. * @param ip_length IPv6 bytes. @param icmp Message. @param length Message bytes. @@ -810,12 +869,20 @@ static void ipv6_icmp(struct net_ipv6_state *state, const uint8_t *ip,uint32_t i reply[2]=reply[3]=0;net_put_u16(reply+2,net_ipv6_checksum(&path.source,&path.destination,58,reply,length)); (void)net_ipv6_output(state->net_ns, &path,58,reply,length,64,0,false,false);kernel_free(reply);return; } - if(icmp[0]>=1 && icmp[0]<=4 && icmp[1]<=4 && length>=48){ - int error=icmp[0]==1?(icmp[1]==4?LINUX_ECONNREFUSED:LINUX_EHOSTUNREACH): - (icmp[0]==2?LINUX_EMSGSIZE:(icmp[0]==3?LINUX_ETIMEDOUT:LINUX_EPROTO)); + if(icmp[0]>=1 && icmp[0]<=4 && length>=48){ + int error=ipv6_icmp_errno(icmp[0], icmp[1]); uint32_t mtu=icmp[0]==2?net_get_u32(icmp+4):0; if(icmp[0]==2)ipv6_update_pmtu(state,ifindex,icmp+8,length-8,mtu); - net_ipv6_socket_error_on(state->net_ns, ifindex,icmp+8,length-8,error,mtu);return; + struct sock_extended_err extended = {.ee_errno = (uint32_t)error, + .ee_origin = SO_EE_ORIGIN_ICMP6, .ee_type = icmp[0], .ee_code = icmp[1], + .ee_info = mtu}; + struct sockaddr_storage offender = {0}; + struct sockaddr_in6 from = {.sin6_family = AF_INET6, .sin6_addr = src, + .sin6_scope_id = ipv6_linklocal(&src) ? ifindex : 0}; + net_memcpy(&offender, &from, sizeof(from)); + net_ipv6_socket_extended_error_on(state->net_ns, ifindex, icmp + 8, + length - 8, &extended, &offender); + return; } if(ifindex==1 || fragmented || ip[7]!=255 || icmp[1]!=0 || !ethernet_mac)return; if(icmp[0]==134){ipv6_router_advertisement(state,ifindex,&src,icmp,length);return;} @@ -1198,9 +1265,16 @@ bool net_ipv6_maintenance_pending(void) struct net_ipv6_state *initial = net_ipv6_state_get(NULL); if (initial->initialized) for (uint32_t i=netdev_next(0);i;i=netdev_next(i)) if (net_interface_is_ready(NULL, i)) return true; - for (struct net_ipv6_state *state=initial;state;state=state->next) + for (struct net_ipv6_state *state=initial;state;state=state->next) { + for (uint32_t index = net_interface_next(state->net_ns, 0); index; + index = net_interface_next(state->net_ns, index)) { + struct net_interface *iface = net_interface_get(state->net_ns, index); + if (iface && iface->config.local_ip && iface->ipv4_address.valid_until && + iface->ipv4_address.valid_until != UINT64_MAX) return true; + } for (uint32_t i=0;ipending[i].used && state->pending[i].loopback) return true; + } return false; } /** @brief Deliver a retained packet locally without recursing into a socket send call. @@ -1293,6 +1367,7 @@ void net_ipv6_poll(void) struct net_ipv6_state *state = net_ipv6_state_get(NULL); while (state) { struct net_namespace *ns = net_namespace_get(state->net_ns); + net_interface_ipv4_poll(ns); ipv6_poll_state(state); struct net_ipv6_state *next = state->next; /* Read the successor before final put can unlink this state. */ diff --git a/net/link/arp.c b/net/link/arp.c index cf153c34..029b38a0 100644 --- a/net/link/arp.c +++ b/net/link/arp.c @@ -4,6 +4,26 @@ static struct net_arp_cache_entry net_arp_cache[NET_ARP_CACHE_SIZE]; static uint32_t net_arp_cache_next; +/** @copydoc net_ipv4_neighbors */ +uint32_t net_ipv4_neighbors(struct net_namespace *ns, struct net_ipv4_neighbor *out, + uint32_t capacity) +{ + if (ns) return 0; + uint32_t count = 0; + for (uint32_t i = 0; i < NET_ARP_CACHE_SIZE; ++i) { + const struct net_arp_cache_entry *entry = &net_arp_cache[i]; + if (!entry->ip || net_mac_is_zero(entry->mac) || + !net_interface_get(NULL, entry->ifindex)) continue; + if (out && count < capacity) { + out[count] = (struct net_ipv4_neighbor){ + .address = entry->ip, .ifindex = entry->ifindex}; + net_memcpy(out[count].mac, entry->mac, sizeof(entry->mac)); + } + ++count; + } + return count; +} + /** @brief Invalidate neighbors for one link without disturbing other links. * @param ifindex Interface, or zero for a complete reset. */ void net_arp_cache_clear_on(uint32_t ifindex) diff --git a/net/link/ethernet.c b/net/link/ethernet.c index 7403d68f..37ea0cd7 100644 --- a/net/link/ethernet.c +++ b/net/link/ethernet.c @@ -18,7 +18,8 @@ void net_write_eth_on(uint32_t ifindex, uint8_t *frame, const uint8_t *dst_mac, } /** - * @brief Accept local/broadcast Ethernet and IPv6 multicast for IP-level filtering. + * @brief Accept local/broadcast Ethernet and IP multicast for protocol filtering. + * @param ifindex Ingress interface. * @param frame Borrowed Ethernet header of at least 14 bytes. * @return Nonzero for a locally receivable destination. */ @@ -26,6 +27,8 @@ int net_frame_for_us_on(uint32_t ifindex, const uint8_t *frame) { return net_memeq(frame, netdev_mac(ifindex), 6) || net_memeq(frame, net_broadcast_mac, 6) || + (frame[0] == 1 && frame[1] == 0 && frame[2] == 0x5e && !(frame[3] & 0x80) && + net_get_u16(frame + 12) == ETH_TYPE_IPV4) || (frame[0] == 0x33 && frame[1] == 0x33 && net_get_u16(frame + 12) == 0x86dd); } diff --git a/net/namespace/namespace.c b/net/namespace/namespace.c index f5e77601..99c01327 100644 --- a/net/namespace/namespace.c +++ b/net/namespace/namespace.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include #include +#include #include #include #include @@ -46,6 +47,11 @@ void net_namespace_put(struct net_namespace *ns) ns->ipv4_routes = route->next; kernel_free(route); } + while (ns->nexthops) { + struct net_nexthop_node *entry = ns->nexthops; + ns->nexthops = entry->next; + kernel_free(entry); + } user_namespace_put(ns->user_ns); kernel_free(ns); } diff --git a/net/socket/netlink.c b/net/socket/netlink.c index 0e9aaad2..d4ac134b 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -22,8 +23,11 @@ #include #include #include +#include #include #include +#include +#include #include #include @@ -37,6 +41,8 @@ #define NL_UEVENT_KERNEL_GROUP 1u #define NL_UEVENT_UDEV_GROUP 2u #define NL_UEVENT_GROUPS (NL_UEVENT_KERNEL_GROUP | NL_UEVENT_UDEV_GROUP) +#define NL_CTRL_NOTIFY_GROUP 16u +#define NL_GENERIC_GROUPS (1ULL << (NL_CTRL_NOTIFY_GROUP - 1)) struct netlink_message { struct netlink_message *next; uint32_t length, groups, port; @@ -48,7 +54,8 @@ struct netlink_socket { struct net_namespace *net_ns; /* Owned creating scope, independent of the FD holder. */ struct netlink_message *head, *tail; struct socket_filter *filter; - uint32_t port, queued_bytes, groups; + uint32_t port, queued_bytes; + uint64_t groups; uint32_t sndbuf, rcvbuf; int type, protocol; bool bound, connected, overrun, passcred; @@ -66,6 +73,8 @@ static uint64_t netlink_ino; static uint64_t uevent_seqnum; struct nl_link_state { uint32_t index; + uint32_t address, mask, broadcast; + struct net_ipv4_address_state policy; char name[NET_IF_NAME_LEN]; uint8_t mac[6]; bool up, active; @@ -76,11 +85,14 @@ struct nl_snapshot { struct net_namespace *net_ns; struct net_ipv6_address *addresses; struct net_ipv6_route *routes; + struct net_ipv4_route *routes4; struct nl_link_state *links; - uint32_t address_count, route_count, link_count; + uint32_t address_count, route_count, route4_count, link_count; }; static struct nl_snapshot *nl_snapshots; -#define NL_SUPPORTED_GROUPS (RTMGRP_LINK|RTMGRP_IPV6_IFADDR|RTMGRP_IPV6_ROUTE) +#define NL_EVENT_GROUPS (RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV4_ROUTE | \ + RTMGRP_IPV6_IFADDR | RTMGRP_IPV6_ROUTE) +#define NL_ROUTE_GROUPS ((1ULL << RTNLGRP_MAX) - 1) /** @brief Resolve the netlink socket attached to an open description. * @param file Borrowed OFD. @return State or NULL for another kind. */ @@ -267,21 +279,33 @@ static int nl_link(struct nl_builder *b, uint32_t seq, int index, bool multi) return nl_link_snapshot(b,seq,multi,RTM_NEWLINK,&link); } -/** @brief Emit one IPv4 address using its actual configured mask. - * @param b Builder. @param seq Sequence. @param index Interface. @param address Host-order IP. - * @param prefix Prefix length. @param broadcast Host-order broadcast. @return Zero or errno. */ -static int nl_address4(struct nl_builder *b, uint32_t seq, uint32_t index, - uint32_t address, uint8_t prefix, uint32_t broadcast) +/** @brief Emit a copied IPv4 address even after its interface has been detached. + * @param b Builder. @param seq Sequence. @param link Copied interface and address. + * @param type NEWADDR or DELADDR. @param multi Multipart flag. + * @return Zero or ENOBUFS. */ +static int nl_address4(struct nl_builder *b, uint32_t seq, const struct nl_link_state *link, + uint16_t type, bool multi) { - uint32_t start = b->used, ip = __builtin_bswap32(address), br = __builtin_bswap32(broadcast); - struct ifaddrmsg *m = nl_begin(b, RTM_NEWADDR, NLM_F_MULTI, seq, sizeof(*m)); + uint32_t start = b->used, ip = __builtin_bswap32(link->address); + uint32_t br = __builtin_bswap32(link->broadcast), index = link->index; + const struct net_ipv4_address_state *policy = &link->policy; + uint32_t flags = policy->flags; + if (!policy->valid_until || policy->valid_until == UINT64_MAX) flags |= IFA_F_PERMANENT; + else flags &= ~IFA_F_PERMANENT; + struct ifa_cacheinfo cache = { + .ifa_prefered = flags & IFA_F_DEPRECATED ? 0 : + nl_lifetime(policy->preferred_until ? policy->preferred_until : UINT64_MAX), + .ifa_valid = nl_lifetime(policy->valid_until ? policy->valid_until : UINT64_MAX), + }; + struct ifaddrmsg *m = nl_begin(b, type, multi ? NLM_F_MULTI : 0, seq, sizeof(*m)); if (!m) return -LINUX_ENOBUFS; - *m = (struct ifaddrmsg){.ifa_family=AF_INET,.ifa_prefixlen=prefix,.ifa_flags=IFA_F_PERMANENT, - .ifa_scope=index==1 ? RT_SCOPE_HOST : RT_SCOPE_UNIVERSE,.ifa_index=index}; - char name[NET_IF_NAME_LEN]; - if (!net_interface_name(b->net_ns, index,name)) return -LINUX_ENODEV; + *m = (struct ifaddrmsg){.ifa_family=AF_INET,.ifa_prefixlen=nl_prefix4(link->mask),.ifa_flags=(uint8_t)flags, + .ifa_scope=index==1 ? RT_SCOPE_HOST : policy->scope,.ifa_index=index}; if (nl_attr(b,start,IFA_ADDRESS,&ip,4) || nl_attr(b,start,IFA_LOCAL,&ip,4) || - nl_attr(b,start,IFA_LABEL,name,__builtin_strlen(name)+1) || + nl_attr(b,start,IFA_FLAGS,&flags,sizeof(flags)) || + nl_attr(b,start,IFA_CACHEINFO,&cache,sizeof(cache)) || + (policy->metric && nl_attr(b,start,IFA_RT_PRIORITY,&policy->metric,4)) || + nl_attr(b,start,IFA_LABEL,link->name,__builtin_strlen(link->name)+1) || (index!=NET_IF_LOOPBACK && nl_attr(b,start,IFA_BROADCAST,&br,4))) return -LINUX_ENOBUFS; return 0; } @@ -300,7 +324,8 @@ static int nl_address6(struct nl_builder *b, uint32_t seq, const struct net_ipv6 struct ifa_cacheinfo cache = {.ifa_prefered=nl_lifetime(a->preferred_until), .ifa_valid=nl_lifetime(a->valid_until)}; if (nl_attr(b,start,IFA_ADDRESS,&a->address,16) || - nl_attr(b,start,IFA_FLAGS,&a->flags,4) || nl_attr(b,start,IFA_CACHEINFO,&cache,sizeof(cache))) + nl_attr(b,start,IFA_FLAGS,&a->flags,4) || nl_attr(b,start,IFA_CACHEINFO,&cache,sizeof(cache)) || + (a->route_metric && nl_attr(b,start,IFA_RT_PRIORITY,&a->route_metric,4))) return -LINUX_ENOBUFS; return 0; } @@ -317,31 +342,90 @@ static int nl_route6(struct nl_builder *b, uint32_t seq, const struct net_ipv6_r static const struct in6_addr zero; bool gateway = __builtin_memcmp(&route->gateway,&zero,sizeof(zero)) != 0; *m = (struct rtmsg){.rtm_family=AF_INET6,.rtm_dst_len=(uint8_t)route->prefix_length, - .rtm_table=RT_TABLE_MAIN,.rtm_protocol=(route->flags & RTF_ADDRCONF) ? RTPROT_RA : RTPROT_BOOT, - .rtm_scope=gateway ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK,.rtm_type=RTN_UNICAST}; + .rtm_table=RT_TABLE_MAIN,.rtm_protocol=route->protocol ? route->protocol : + (route->flags & RTF_ADDRCONF) ? RTPROT_RA : RTPROT_BOOT, + .rtm_scope=gateway ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK,.rtm_type=RTN_UNICAST, + .rtm_flags=route->onlink ? RTNH_F_ONLINK : 0}; if ((route->prefix_length && nl_attr(b,start,RTA_DST,&route->destination,16)) || - nl_attr(b,start,RTA_OIF,&route->ifindex,4) || - (gateway && nl_attr(b,start,RTA_GATEWAY,&route->gateway,16)) || + (route->nexthop_id ? nl_attr(b,start,RTA_NH_ID,&route->nexthop_id,4) : + (nl_attr(b,start,RTA_OIF,&route->ifindex,4) || + (gateway && nl_attr(b,start,RTA_GATEWAY,&route->gateway,16)))) || + (__builtin_memcmp(&route->preferred_source,&zero,16) && + nl_attr(b,start,RTA_PREFSRC,&route->preferred_source,16)) || + nl_attr(b,start,RTA_PREF,&route->preference,1) || nl_attr(b,start,RTA_PRIORITY,&route->metric,4)) return -LINUX_ENOBUFS; + if (route->valid_until != UINT64_MAX) { + uint32_t seconds = nl_lifetime(route->valid_until); + if (nl_attr(b,start,RTA_EXPIRES,&seconds,4)) return -LINUX_ENOBUFS; + } return 0; } -/** @brief Emit an IPv4 route from existing core configuration. - * @param b Builder. @param seq Sequence. @param destination Host-order network. - * @param prefix Prefix length. @param gateway Host-order gateway. @param index Interface. +/** @brief Emit a copied IPv4 route for a dump or multicast notification. + * @param b Builder. @param seq Sequence. @param route Host-order route snapshot. + * @param type NEWROUTE or DELROUTE. @param multi Multipart flag. * @return Zero or ENOBUFS. */ -static int nl_route4(struct nl_builder *b, uint32_t seq, uint32_t destination, - uint8_t prefix, uint32_t gateway, uint32_t index, uint32_t metric) +static int nl_route4(struct nl_builder *b, uint32_t seq, const struct net_ipv4_route *route, + uint16_t type, bool multi) { - uint32_t start=b->used, dst=__builtin_bswap32(destination), gw=__builtin_bswap32(gateway); - struct rtmsg *m=nl_begin(b,RTM_NEWROUTE,NLM_F_MULTI,seq,sizeof(*m)); + uint32_t start=b->used, dst=__builtin_bswap32(route->destination); + uint32_t gw=__builtin_bswap32(route->gateway); + uint32_t source=__builtin_bswap32(route->preferred_source); + uint8_t prefix=nl_prefix4(route->mask); + struct rtmsg *m=nl_begin(b,type,multi ? NLM_F_MULTI : 0,seq,sizeof(*m)); if (!m) return -LINUX_ENOBUFS; *m=(struct rtmsg){.rtm_family=AF_INET,.rtm_dst_len=prefix,.rtm_table=RT_TABLE_MAIN, - .rtm_protocol=RTPROT_KERNEL,.rtm_scope=gateway ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK, - .rtm_type=RTN_UNICAST}; - if ((prefix && nl_attr(b,start,RTA_DST,&dst,4)) || nl_attr(b,start,RTA_OIF,&index,4) || - (gateway && nl_attr(b,start,RTA_GATEWAY,&gw,4)) || - nl_attr(b,start,RTA_PRIORITY,&metric,4)) return -LINUX_ENOBUFS; + .rtm_protocol=route->protocol ? route->protocol : RTPROT_KERNEL,.rtm_scope=route->scope, + .rtm_type=RTN_UNICAST,.rtm_flags=route->onlink ? RTNH_F_ONLINK : 0}; + if ((prefix && nl_attr(b,start,RTA_DST,&dst,4)) || + (route->nexthop_id ? nl_attr(b,start,RTA_NH_ID,&route->nexthop_id,4) : + (nl_attr(b,start,RTA_OIF,&route->ifindex,4) || + (route->gateway && nl_attr(b,start,RTA_GATEWAY,&gw,4)))) || + (source && nl_attr(b,start,RTA_PREFSRC,&source,4)) || + nl_attr(b,start,RTA_PRIORITY,&route->metric,4)) return -LINUX_ENOBUFS; + return 0; +} + +/** @brief Emit a copied standalone nexthop with its namespace-local ID. + * @param b Builder. @param seq Sequence. @param value Borrowed copied state. + * @param type NEWNEXTHOP or DELNEXTHOP. @param multi Multipart flag. + * @return Zero or staging capacity error. No reference is retained. */ +static int nl_nexthop(struct nl_builder *b, uint32_t seq, const struct net_nexthop *value, + uint16_t type, bool multi) +{ + uint32_t start = b->used; + struct nhmsg *reply = nl_begin(b, type, multi ? NLM_F_MULTI : 0, seq, sizeof(*reply)); + if (!reply) return -LINUX_ENOBUFS; + *reply = (struct nhmsg){.nh_family = value->family, .nh_scope = value->scope, + .nh_protocol = value->protocol, .nh_flags = value->flags}; + if (nl_attr(b,start,NHA_ID,&value->id,4) || nl_attr(b,start,NHA_OIF,&value->ifindex,4)) + return -LINUX_ENOBUFS; + if (value->family == AF_INET) { + uint32_t gateway = __builtin_bswap32(value->gateway.ipv4); + if (gateway && nl_attr(b,start,NHA_GATEWAY,&gateway,4)) return -LINUX_ENOBUFS; + } else { + static const struct in6_addr zero; + if (__builtin_memcmp(&value->gateway.ipv6,&zero,16) && + nl_attr(b,start,NHA_GATEWAY,&value->gateway.ipv6,16)) return -LINUX_ENOBUFS; + } + return 0; +} + +/** @brief Copy connected, default and explicit IPv4 routes in one network. + * @param ns Borrowed scope. @param out Owned array output. @param count Element count output. + * @return Zero or negative errno. Failure frees the candidate array. */ +static int nl_routes4(struct net_namespace *ns, struct net_ipv4_route **out, uint32_t *count) +{ + *out = NULL; + *count = net_ipv4_routes(ns, NULL, 0); + if (!*count) return 0; + if (*count > NL_MESSAGE_MAX / sizeof(**out)) return -LINUX_ENOBUFS; + *out = kernel_malloc((size_t)*count * sizeof(**out)); + if (!*out) return -LINUX_ENOMEM; + if (net_ipv4_routes(ns, *out, *count) > *count) { + kernel_free(*out); *out = NULL; + return -LINUX_EAGAIN; + } return 0; } @@ -394,6 +478,12 @@ static int nl_links(struct net_namespace *ns, struct nl_link_state **out, uint32 struct nl_link_state *link=&links[used++]; __builtin_memset(link,0,sizeof(*link)); link->index=index; if (!net_interface_name(ns, index,link->name)) { kernel_free(links); return -LINUX_EAGAIN; } + struct net_interface *iface = net_interface_get(ns, index); + if (!iface) { kernel_free(links); return -LINUX_EAGAIN; } + link->address = iface->config.local_ip; + link->mask = iface->config.subnet_mask; + link->broadcast = iface->broadcast; + link->policy = iface->ipv4_address; link->up=net_interface_is_up(ns, index); if (index!=NET_IF_LOOPBACK) { struct e1000_info info={0}; netdev_get_info(index,&info); @@ -413,6 +503,30 @@ static struct nl_snapshot *nl_find_snapshot(struct net_namespace *ns) return NULL; } +/** @brief Release all arrays owned by one complete or partial route baseline. + * @param snapshot Borrowed baseline container, preserved by this call. */ +static void nl_free_snapshot_data(struct nl_snapshot *snapshot) +{ + kernel_free(snapshot->addresses); + kernel_free(snapshot->routes); + kernel_free(snapshot->routes4); + kernel_free(snapshot->links); +} + +/** @brief Capture all network state before publishing any baseline replacement. + * @param snapshot Zero-initialized candidate with borrowed network scope. + * @return Zero or negative errno. Failure releases all candidate allocations. */ +static int nl_capture_snapshot(struct nl_snapshot *snapshot) +{ + struct net_namespace *ns = snapshot->net_ns; + int rc = nl_addresses(ns, &snapshot->addresses, &snapshot->address_count); + if (!rc) rc = nl_routes(ns, &snapshot->routes, &snapshot->route_count); + if (!rc) rc = nl_routes4(ns, &snapshot->routes4, &snapshot->route4_count); + if (!rc) rc = nl_links(ns, &snapshot->links, &snapshot->link_count); + if (rc) nl_free_snapshot_data(snapshot); + return rc; +} + /** @brief Retire a namespace's owned baseline after its last subscriber leaves. * @param ns Borrowed scope, still retained by the departing socket. */ static void nl_forget_snapshot(struct net_namespace *ns) @@ -422,9 +536,7 @@ static void nl_forget_snapshot(struct net_namespace *ns) if (!*slot) return; struct nl_snapshot *snapshot = *slot; *slot = snapshot->next; - kernel_free(snapshot->addresses); - kernel_free(snapshot->routes); - kernel_free(snapshot->links); + nl_free_snapshot_data(snapshot); kernel_free(snapshot); } @@ -437,13 +549,8 @@ static int nl_initial_snapshot(struct net_namespace *ns) struct nl_snapshot *snapshot = kernel_malloc(sizeof(*snapshot)); if (!snapshot) return -LINUX_ENOMEM; *snapshot = (struct nl_snapshot){.net_ns = ns}; - int rc = nl_addresses(ns, &snapshot->addresses, &snapshot->address_count); - if (!rc) rc = nl_routes(ns, &snapshot->routes, &snapshot->route_count); - if (!rc) rc = nl_links(ns, &snapshot->links, &snapshot->link_count); + int rc = nl_capture_snapshot(snapshot); if (rc) { - kernel_free(snapshot->addresses); - kernel_free(snapshot->routes); - kernel_free(snapshot->links); kernel_free(snapshot); return rc; } @@ -464,8 +571,14 @@ static void nl_forget_unsubscribed(struct net_namespace *ns) /** @brief Change membership transactionally, retaining an initialized query bitmap. * Route subscribers share a baseline within their creating network. * @param s Subscriber. @param groups New Linux group mask. @return Zero or errno. */ -static int nl_set_groups(struct netlink_socket *s, uint32_t groups) +static int nl_set_groups(struct netlink_socket *s, uint64_t groups) { + if (s->protocol == NETLINK_GENERIC) { + if (groups & ~NL_GENERIC_GROUPS) return -LINUX_EINVAL; + s->groups = groups; + s->memberships_initialized |= groups != 0; + return 0; + } if (s->protocol == NETLINK_KOBJECT_UEVENT) { if (groups & ~NL_UEVENT_GROUPS) return -LINUX_EOPNOTSUPP; @@ -473,7 +586,7 @@ static int nl_set_groups(struct netlink_socket *s, uint32_t groups) s->memberships_initialized |= groups != 0; return 0; } - if (groups & ~NL_SUPPORTED_GROUPS) return -LINUX_EOPNOTSUPP; + if (groups & ~NL_ROUTE_GROUPS) return -LINUX_EOPNOTSUPP; if (groups) { int rc=nl_initial_snapshot(s->net_ns); if (rc) return rc; } s->groups=groups; s->memberships_initialized |= groups != 0; @@ -529,12 +642,14 @@ static int nl_queue_datagram(struct netlink_socket *s, uint32_t port, uint32_t g * @param data Validated datagram. @param length Datagram length. * @param sender Sending socket, excluded from fanout, or NULL for kernel. * @param credentials Sender's credential snapshot, or NULL for kernel. + * @param global_device_event Whether this untagged device event spans networks + * owned by the initial user namespace. */ static void nl_multicast(struct net_namespace *ns, int protocol, uint32_t group, const void *data, uint32_t length, - const struct netlink_socket *sender, const struct ucred *credentials) + const struct netlink_socket *sender, const struct ucred *credentials, + bool global_device_event) { bool notified = false; - bool global_device_event = !sender && protocol == NETLINK_KOBJECT_UEVENT; for (struct netlink_socket *s = netlink_sockets; s; s = s->next) { if (s == sender || s->protocol != protocol || !(s->groups & group)) continue; @@ -553,20 +668,26 @@ static void nl_multicast(struct net_namespace *ns, int protocol, uint32_t group, kernel_poll_readiness_notify(); } -/** @copydoc netlink_uevent_change */ -void netlink_uevent_change(const char *devpath, const char *subsystem, - const char *properties, uint32_t length) +/** @brief Encode one kobject event with an explicit network delivery policy. + * @param ns Destination network. @param global Whether initial-user networks receive it. + * @param action Kobject action. @param devpath Canonical path. + * @param subsystem Subsystem name. @param properties NUL-separated properties. + * @param length Property bytes, copied synchronously under execution ownership. + */ +static void nl_uevent(struct net_namespace *ns,bool global,const char *action, + const char *devpath,const char *subsystem, + const char *properties,uint32_t length) { - devtmpfs_notify(); char payload[512]; struct text_stream stream = {.buffer = payload, .capacity = sizeof(payload)}; - static const char action[] = "\0ACTION=change\0DEVPATH="; - static const char system[] = "\0SUBSYSTEM="; - text_string(&stream, "change@"); + text_string(&stream, action); + text_string(&stream, "@"); text_string(&stream, devpath); - text_bytes(&stream, action, sizeof(action) - 1); + text_bytes(&stream, "\0ACTION=", sizeof("\0ACTION=") - 1); + text_string(&stream, action); + text_bytes(&stream, "\0DEVPATH=", sizeof("\0DEVPATH=") - 1); text_string(&stream, devpath); - text_bytes(&stream, system, sizeof(system) - 1); + text_bytes(&stream, "\0SUBSYSTEM=", sizeof("\0SUBSYSTEM=") - 1); text_string(&stream, subsystem); text_bytes(&stream, "", 1); text_bytes(&stream, properties, length); @@ -574,10 +695,34 @@ void netlink_uevent_change(const char *devpath, const char *subsystem, text_unsigned(&stream, ++uevent_seqnum); text_bytes(&stream, "", 1); if (stream.position <= sizeof(payload)) - nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, NL_UEVENT_KERNEL_GROUP, payload, stream.written, NULL, NULL); + nl_multicast(ns, NETLINK_KOBJECT_UEVENT, NL_UEVENT_KERNEL_GROUP, + payload, stream.written, NULL, NULL, global); +} + +/** @copydoc netlink_uevent_change */ +void netlink_uevent_change(const char *devpath,const char *subsystem, + const char *properties,uint32_t length) +{ + devtmpfs_notify(); + netlink_uevent_device("change",devpath,subsystem,properties,length); } EXPORT_SYMBOL(netlink_uevent_change); +/** @copydoc netlink_uevent_device */ +void netlink_uevent_device(const char *action,const char *devpath,const char *subsystem, + const char *properties,uint32_t length) +{ + nl_uevent(NULL,true,action,devpath,subsystem,properties,length); +} + +/** @copydoc netlink_uevent_network */ +void netlink_uevent_network(struct net_namespace *ns,const char *action, + const char *devpath,const char *subsystem, + const char *properties,uint32_t length) +{ + nl_uevent(ns,false,action,devpath,subsystem,properties,length); +} + /** @brief Compare address identity independently of its mutable flags/lifetime. * @param a First snapshot. @param b Second snapshot. @return True for the same address. */ static bool nl_same_address(const struct net_ipv6_address *a,const struct net_ipv6_address *b) @@ -588,7 +733,8 @@ static bool nl_same_address(const struct net_ipv6_address *a,const struct net_ip static bool nl_equal_address(const struct net_ipv6_address *a,const struct net_ipv6_address *b) { return nl_same_address(a,b) && a->prefix_length==b->prefix_length && a->flags==b->flags && - a->scope==b->scope && a->preferred_until==b->preferred_until && a->valid_until==b->valid_until; + a->scope==b->scope && a->route_metric==b->route_metric && + a->preferred_until==b->preferred_until && a->valid_until==b->valid_until; } /** @brief Compare a route's table identity. @@ -603,7 +749,24 @@ static bool nl_same_route(const struct net_ipv6_route *a,const struct net_ipv6_r /** @brief Compare all exposed state of the same route. * @param a First snapshot. @param b Second snapshot. @return True if unchanged. */ static bool nl_equal_route(const struct net_ipv6_route *a,const struct net_ipv6_route *b) -{ return nl_same_route(a,b) && a->metric==b->metric && a->flags==b->flags && a->valid_until==b->valid_until; } +{ + return nl_same_route(a,b) && a->metric==b->metric && a->flags==b->flags && + a->valid_until==b->valid_until && a->nexthop_id==b->nexthop_id && + a->protocol==b->protocol && a->preference==b->preference && a->onlink==b->onlink && + !__builtin_memcmp(&a->preferred_source,&b->preferred_source,16); +} + +/** @brief Compare all exported IPv4 route fields, including priority. + * @param a First copied route. @param b Second copied route. + * @return True when the route records are equal. */ +static bool nl_equal_route4(const struct net_ipv4_route *a, const struct net_ipv4_route *b) +{ + return a->destination == b->destination && a->mask == b->mask && + a->gateway == b->gateway && a->ifindex == b->ifindex && + a->metric == b->metric && a->flags == b->flags && + a->preferred_source == b->preferred_source && a->nexthop_id == b->nexthop_id && + a->protocol == b->protocol && a->scope == b->scope && a->onlink == b->onlink; +} /** @brief Queue a bounded namespace-scoped event for its subscribed OFDs. * @param ns Borrowed network, NULL for the initial network. @@ -618,28 +781,80 @@ static void nl_publish(struct net_namespace *ns, uint32_t group,uint16_t type,co struct netlink_message *message=kernel_malloc(sizeof(*message)+NL_MESSAGE_MAX); if (!message) { nl_overrun(ns, group); return; } struct nl_builder b={.message=message,.net_ns=ns}; - int rc=group==RTMGRP_IPV6_IFADDR ? nl_address6(&b,0,value,type,false) : - group==RTMGRP_IPV6_ROUTE ? nl_route6(&b,0,value,type,false) : - nl_link_snapshot(&b,0,false,type,value); + int rc; + switch (group) { + case RTMGRP_IPV4_IFADDR: rc = nl_address4(&b, 0, value, type, false); break; + case RTMGRP_IPV4_ROUTE: rc = nl_route4(&b, 0, value, type, false); break; + case RTMGRP_IPV6_IFADDR: rc = nl_address6(&b, 0, value, type, false); break; + case RTMGRP_IPV6_ROUTE: rc = nl_route6(&b, 0, value, type, false); break; + case (1u << (RTNLGRP_NEXTHOP - 1)): rc = nl_nexthop(&b, 0, value, type, false); break; + default: rc = nl_link_snapshot(&b, 0, false, type, value); break; + } if (rc) { kernel_free(message); nl_overrun(ns, group); return; } - nl_multicast(ns, NETLINK_ROUTE, group, message->data, b.used, NULL, NULL); + nl_multicast(ns, NETLINK_ROUTE, group, message->data, b.used, NULL, NULL, false); kernel_free(message); } +/** @copydoc netlink_nexthop_changed */ +void netlink_nexthop_changed(struct net_namespace *ns, const struct net_nexthop *value, + bool remove) +{ + nl_publish(ns, 1u << (RTNLGRP_NEXTHOP - 1), + remove ? RTM_DELNEXTHOP : RTM_NEWNEXTHOP, value); +} + +/** @brief Render a checked standalone nexthop lookup or filtered multipart dump. + * @param b Request builder. @param h Complete GETNEXTHOP request. + * @return Zero or negative errno. Requires execution ownership. */ +static int nl_get_nexthop(struct nl_builder *b, const struct nlmsghdr *h); + /** @copydoc netlink_network_changed */ void netlink_network_changed(struct net_namespace *ns) { struct nl_snapshot *snapshot = nl_find_snapshot(ns); if (!snapshot) return; - struct net_ipv6_address *addresses; struct net_ipv6_route *routes; - struct nl_link_state *links; - uint32_t acount, rcount, lcount; - int rc=nl_addresses(ns, &addresses,&acount); - if (rc) { nl_overrun(ns, NL_SUPPORTED_GROUPS); return; } - rc=nl_routes(ns, &routes,&rcount); - if (rc) { kernel_free(addresses); nl_overrun(ns, NL_SUPPORTED_GROUPS); return; } - rc=nl_links(ns, &links,&lcount); - if (rc) { kernel_free(addresses); kernel_free(routes); nl_overrun(ns, NL_SUPPORTED_GROUPS); return; } + struct nl_snapshot next = {.net_ns = ns}; + int rc = nl_capture_snapshot(&next); + if (rc) { nl_overrun(ns, NL_EVENT_GROUPS); return; } + struct net_ipv6_address *addresses = next.addresses; + struct net_ipv6_route *routes = next.routes; + struct nl_link_state *links = next.links; + uint32_t acount = next.address_count, rcount = next.route_count, lcount = next.link_count; + for (uint32_t i = 0; i < snapshot->link_count; ++i) { + const struct nl_link_state *old = &snapshot->links[i]; + bool found = false; + for (uint32_t j = 0; j < lcount; ++j) + if (old->index == links[j].index && old->address == links[j].address && + old->mask == links[j].mask) { found = true; break; } + if (old->address && !found) nl_publish(ns, RTMGRP_IPV4_IFADDR, RTM_DELADDR, old); + } + for (uint32_t i = 0; i < lcount; ++i) { + const struct nl_link_state *link = &links[i]; + bool same = false; + for (uint32_t j = 0; j < snapshot->link_count; ++j) { + const struct nl_link_state *old = &snapshot->links[j]; + if (old->index == link->index && old->address == link->address && + old->mask == link->mask && old->broadcast == link->broadcast && + old->policy.flags == link->policy.flags && old->policy.scope == link->policy.scope && + old->policy.metric == link->policy.metric && + old->policy.preferred_until == link->policy.preferred_until && + old->policy.valid_until == link->policy.valid_until && + !__builtin_strcmp(old->name, link->name)) { same = true; break; } + } + if (link->address && !same) nl_publish(ns, RTMGRP_IPV4_IFADDR, RTM_NEWADDR, link); + } + for (uint32_t i = 0; i < snapshot->route4_count; ++i) { + bool found = false; + for (uint32_t j = 0; j < next.route4_count; ++j) + if (nl_equal_route4(&snapshot->routes4[i], &next.routes4[j])) { found = true; break; } + if (!found) nl_publish(ns, RTMGRP_IPV4_ROUTE, RTM_DELROUTE, &snapshot->routes4[i]); + } + for (uint32_t i = 0; i < next.route4_count; ++i) { + bool same = false; + for (uint32_t j = 0; j < snapshot->route4_count; ++j) + if (nl_equal_route4(&next.routes4[i], &snapshot->routes4[j])) { same = true; break; } + if (!same) nl_publish(ns, RTMGRP_IPV4_ROUTE, RTM_NEWROUTE, &next.routes4[i]); + } for (uint32_t i=0;iaddress_count;++i) { bool found=false; for (uint32_t j=0;jaddresses[i],&addresses[j])) { found=true; break; } @@ -676,10 +891,9 @@ void netlink_network_changed(struct net_namespace *ns) __builtin_strcmp(old->name,links[i].name)) nl_publish(ns, RTMGRP_LINK,RTM_NEWLINK,&links[i]); } - kernel_free(snapshot->addresses); kernel_free(snapshot->routes); kernel_free(snapshot->links); - snapshot->addresses=addresses; snapshot->address_count=acount; - snapshot->routes=routes; snapshot->route_count=rcount; - snapshot->links=links; snapshot->link_count=lcount; + nl_free_snapshot_data(snapshot); + next.next = snapshot->next; + *snapshot = next; } /** @copydoc netlink_ipv6_changed */ @@ -688,16 +902,96 @@ void netlink_ipv6_changed(struct net_namespace *ns) netlink_network_changed(ns); } -/** @brief Render a link, address or route dump from current network state. +/** @brief Append one copied neighbor with its address and available link-layer mapping. + * @param b Scoped reply builder. @param seq Request sequence. + * @param family IPv4 or IPv6. @param ifindex Owning interface. + * @param state Linux NUD state. @param address Borrowed network-order address. + * @param mac Borrowed six-byte mapping, zero bytes when unresolved. + * @return Zero or ENOBUFS. The caller discards partial replies on error. + */ +static int nl_neighbor(struct nl_builder *b, uint32_t seq, uint8_t family, + uint32_t ifindex, uint16_t state, const void *address, + const uint8_t mac[6]) +{ + uint32_t start = b->used; + struct ndmsg *reply = nl_begin(b, RTM_NEWNEIGH, NLM_F_MULTI, seq, sizeof(*reply)); + if (!reply) return -LINUX_ENOBUFS; + *reply = (struct ndmsg){.ndm_family = family, .ndm_ifindex = (int32_t)ifindex, + .ndm_state = state, .ndm_type = RTN_UNICAST}; + static const uint8_t zero[6]; + if (nl_attr(b, start, NDA_DST, address, family == AF_INET ? 4 : 16) || + (__builtin_memcmp(mac, zero, sizeof(zero)) && + nl_attr(b, start, NDA_LLADDR, mac, sizeof(zero)))) return -LINUX_ENOBUFS; + return 0; +} + +/** @brief Render actual ARP and NDP tables in the requesting socket's network. + * @param b Scoped reply builder. @param h Checked multipart request. + * @return Zero or negative errno. Allocation failure publishes no partial table. + * Bridge FDB and proxy tables are empty because their objects are unsupported. + */ +static int nl_dump_neighbors(struct nl_builder *b, const struct nlmsghdr *h) +{ + uint32_t payload = h->nlmsg_len - sizeof(*h); + if (!payload) return -LINUX_EINVAL; + struct ndmsg request = {0}; + __builtin_memcpy(&request, h + 1, payload < sizeof(request) ? payload : sizeof(request)); + if (request.ndm_family != AF_UNSPEC && request.ndm_family != AF_INET && + request.ndm_family != AF_INET6 && request.ndm_family != AF_BRIDGE) + return -LINUX_EAFNOSUPPORT; + if (request.ndm_ifindex < 0) return -LINUX_EINVAL; + if (request.ndm_family == AF_BRIDGE || (request.ndm_flags & NTF_PROXY)) + return nl_done(b, h->nlmsg_seq); + int rc = 0; + if (request.ndm_family != AF_INET6) { + uint32_t count = net_ipv4_neighbors(b->net_ns, NULL, 0); + if (count > NL_MESSAGE_MAX / sizeof(struct net_ipv4_neighbor)) return -LINUX_ENOBUFS; + struct net_ipv4_neighbor *entries = count ? kernel_malloc((size_t)count * sizeof(*entries)) : NULL; + if (count && !entries) return -LINUX_ENOMEM; + uint32_t copied = net_ipv4_neighbors(b->net_ns, entries, count); + if (copied > count) rc = -LINUX_EAGAIN; + count = copied; + for (uint32_t i = 0; i < count && !rc; ++i) { + if (request.ndm_ifindex && (uint32_t)request.ndm_ifindex != entries[i].ifindex) continue; + uint32_t address = __builtin_bswap32(entries[i].address); + rc = nl_neighbor(b, h->nlmsg_seq, AF_INET, entries[i].ifindex, + NUD_STALE, &address, entries[i].mac); + } + kernel_free(entries); + if (rc) return rc; + } + if (request.ndm_family != AF_INET) { + uint32_t count = net_ipv6_neighbors(b->net_ns, NULL, 0); + if (count > NL_MESSAGE_MAX / sizeof(struct net_ipv6_neighbor)) return -LINUX_ENOBUFS; + struct net_ipv6_neighbor *entries = count ? kernel_malloc((size_t)count * sizeof(*entries)) : NULL; + if (count && !entries) return -LINUX_ENOMEM; + uint32_t copied = net_ipv6_neighbors(b->net_ns, entries, count); + if (copied > count) rc = -LINUX_EAGAIN; + count = copied; + for (uint32_t i = 0; i < count && !rc; ++i) { + if (request.ndm_ifindex && (uint32_t)request.ndm_ifindex != entries[i].ifindex) continue; + rc = nl_neighbor(b, h->nlmsg_seq, AF_INET6, entries[i].ifindex, + (uint16_t)entries[i].state, &entries[i].address, entries[i].mac); + } + kernel_free(entries); + if (rc) return rc; + } + return nl_done(b, h->nlmsg_seq); +} + +/** @brief Render scoped links, addresses, routes, neighbors and standalone nexthops. * @param b Builder. @param h Checked request. @return Zero or negative errno. */ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) { uint32_t payload = h->nlmsg_len - sizeof(*h); bool multi = (h->nlmsg_flags & NLM_F_DUMP) == NLM_F_DUMP; + if (h->nlmsg_type == RTM_GETNEXTHOP) return nl_get_nexthop(b, h); if (h->nlmsg_type == RTM_GETLINK) { if (!payload || (!multi && payload < sizeof(struct ifinfomsg))) return -LINUX_EINVAL; struct ifinfomsg req={0}; __builtin_memcpy(&req,h+1,payload < sizeof(req) ? payload : sizeof(req)); + if (req.ifi_family == AF_BRIDGE) + return multi ? nl_done(b, h->nlmsg_seq) : -LINUX_EOPNOTSUPP; if (req.ifi_family != AF_UNSPEC && req.ifi_family != AF_PACKET && req.ifi_family != AF_INET && req.ifi_family != AF_INET6) return -LINUX_EAFNOSUPPORT; if (!multi) { @@ -710,6 +1004,7 @@ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) return nl_done(b,h->nlmsg_seq); } if (!multi) return -LINUX_EOPNOTSUPP; + if (h->nlmsg_type == RTM_GETNEIGH) return nl_dump_neighbors(b, h); if (h->nlmsg_type == RTM_GETADDR) { if (!payload) return -LINUX_EINVAL; struct ifaddrmsg req={0}; @@ -723,8 +1018,11 @@ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) if ((req.ifa_index && req.ifa_index!=index) || net_interface_get_config(b->net_ns, index,&config) || !config.local_ip) continue; struct net_interface *iface=net_interface_get(b->net_ns, index); - uint32_t broadcast=iface ? iface->broadcast : 0; - rc=nl_address4(b,h->nlmsg_seq,index,config.local_ip,nl_prefix4(config.subnet_mask),broadcast); + struct nl_link_state address = {.index = index, .address = config.local_ip, + .mask = config.subnet_mask, .broadcast = iface ? iface->broadcast : 0, + .policy = iface ? iface->ipv4_address : (struct net_ipv4_address_state){0}}; + if (!net_interface_name(b->net_ns, index, address.name)) return -LINUX_ENODEV; + rc=nl_address4(b,h->nlmsg_seq,&address,RTM_NEWADDR,true); if (rc) return rc; } } @@ -745,14 +1043,11 @@ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) return -LINUX_EAFNOSUPPORT; int rc=0; if (req.rtm_family != AF_INET6) { - uint32_t count=net_ipv4_routes(b->net_ns, NULL,0); - if (count > NL_MESSAGE_MAX / sizeof(struct net_ipv4_route)) return -LINUX_ENOBUFS; - struct net_ipv4_route *entries=count ? kernel_malloc((size_t)count*sizeof(*entries)) : NULL; - if (count && !entries) return -LINUX_ENOMEM; - if (net_ipv4_routes(b->net_ns, entries,count)>count) { kernel_free(entries); return -LINUX_EAGAIN; } + uint32_t count; + struct net_ipv4_route *entries; + rc=nl_routes4(b->net_ns, &entries, &count); if (rc) return rc; for (uint32_t i=0;inlmsg_seq,entries[i].destination,nl_prefix4(entries[i].mask), - entries[i].gateway,entries[i].ifindex,entries[i].metric); + rc=nl_route4(b,h->nlmsg_seq,&entries[i],RTM_NEWROUTE,true); kernel_free(entries); if (rc) return rc; } if (req.rtm_family != AF_INET) { @@ -794,6 +1089,73 @@ static int nl_copy_attr(const struct rtattr *a, void *out, uint32_t size) __builtin_memcpy(out,a+1,size); return 0; } +/** @copydoc nl_get_nexthop */ +static int nl_get_nexthop(struct nl_builder *b, const struct nlmsghdr *h) +{ + if (h->nlmsg_len < sizeof(*h)+sizeof(struct nhmsg)) return -LINUX_EINVAL; + const struct nhmsg *req = (const void *)(h+1); + if (req->nh_family != AF_UNSPEC && req->nh_family != AF_INET && req->nh_family != AF_INET6) + return -LINUX_EAFNOSUPPORT; + const struct rtattr *attrs[NHA_FDB+1] = {0}; + int rc = nl_parse_attrs((const uint8_t *)(req+1), h->nlmsg_len-sizeof(*h)-sizeof(*req), + attrs, NHA_FDB+1); + if (rc) return rc; + for (unsigned i=0;inlmsg_flags & NLM_F_DUMP)==NLM_F_DUMP; + if (!dump) { + if (!id) return -LINUX_EINVAL; + const struct net_nexthop *value = net_nexthop_get(b->net_ns,id); + if (!value || (req->nh_family && req->nh_family!=value->family) || + (ifindex && ifindex!=value->ifindex)) return -LINUX_ENOENT; + return nl_nexthop(b,h->nlmsg_seq,value,RTM_NEWNEXTHOP,false); + } + const struct net_nexthop *value; + uint32_t after=0; + while ((value=net_nexthop_next(b->net_ns,after))) { + after=value->id; + if ((id && id!=value->id) || (req->nh_family && req->nh_family!=value->family) || + (ifindex && ifindex!=value->ifindex)) continue; + rc=nl_nexthop(b,h->nlmsg_seq,value,RTM_NEWNEXTHOP,true); + if (rc) return rc; + } + return nl_done(b,h->nlmsg_seq); +} + +/** @brief Apply an authorized standalone nexthop creation, replacement or deletion. + * @param ns Borrowed creating network. @param h Checked native message. + * @param remove Select deletion. @return Zero or negative errno. + * Unsupported groups, encapsulation and blackholes leave routes unchanged. */ +static int nl_change_nexthop(struct net_namespace *ns, const struct nlmsghdr *h, bool remove) +{ + if (h->nlmsg_len < sizeof(*h)+sizeof(struct nhmsg)) return -LINUX_EINVAL; + const struct nhmsg *req = (const void *)(h+1); + if (req->resvd) return -LINUX_EINVAL; + const struct rtattr *attrs[NHA_FDB+1] = {0}; + int rc = nl_parse_attrs((const uint8_t *)(req+1), h->nlmsg_len-sizeof(*h)-sizeof(*req), + attrs,NHA_FDB+1); + if (rc) return rc; + for (unsigned i=0;inh_family,.scope=req->nh_scope, + .protocol=req->nh_protocol,.flags=req->nh_flags}; + if ((rc=nl_copy_attr(attrs[NHA_ID],&value.id,4))) return rc; + if (remove) return net_nexthop_update(ns,&value,true,false,false); + if ((rc=nl_copy_attr(attrs[NHA_OIF],&value.ifindex,4))) return rc; + if (value.family==AF_INET) { + rc=nl_copy_attr(attrs[NHA_GATEWAY],&value.gateway.ipv4,4); + value.gateway.ipv4=__builtin_bswap32(value.gateway.ipv4); + } else if (value.family==AF_INET6) { + rc=nl_copy_attr(attrs[NHA_GATEWAY],&value.gateway.ipv6,16); + } else return -LINUX_EAFNOSUPPORT; + if (rc) return rc; + bool replace=(h->nlmsg_flags & NLM_F_REPLACE)!=0 && !(h->nlmsg_flags & NLM_F_EXCL); + return net_nexthop_update(ns,&value,false,replace,(h->nlmsg_flags & NLM_F_CREATE)!=0); +} + /** @brief Apply an authorized administrative change to one network's interface. * @param ns Borrowed creating network, NULL for the initial network. * @param h Validated request header and bounded attributes. @@ -815,6 +1177,7 @@ static int nl_change_link(struct net_namespace *ns, const struct nlmsghdr *h) for (unsigned i=0;i<17;++i) if (attrs[i] && i!=IFLA_IFNAME && i!=IFLA_MTU) return -LINUX_EOPNOTSUPP; uint32_t index=(uint32_t)req.ifi_index; + char name[NET_IF_NAME_LEN]={0}; if (attrs[IFLA_IFNAME]) { uint32_t n=attrs[IFLA_IFNAME]->rta_len-sizeof(struct rtattr); const char *input=(const char *)(attrs[IFLA_IFNAME]+1); @@ -822,11 +1185,8 @@ static int nl_change_link(struct net_namespace *ns, const struct nlmsghdr *h) bool terminated=false; for (uint32_t i=0;iifa_index || req->ifa_prefixlen>32) return -LINUX_EINVAL; struct net_interface *iface=net_interface_get(ns, req->ifa_index); if (!iface) return req->ifa_index==NET_IF_LOOPBACK ? -LINUX_EOPNOTSUPP : -LINUX_ENODEV; - const struct rtattr *a[9]={0}; + const struct rtattr *a[10]={0}; int rc=nl_parse_attrs((const uint8_t *)(h+1)+sizeof(*req), - h->nlmsg_len-sizeof(*h)-sizeof(*req),a,9); + h->nlmsg_len-sizeof(*h)-sizeof(*req),a,10); if (rc) return rc; - for (unsigned i=0;i<9;++i) + for (unsigned i=0;i<10;++i) if (a[i] && i!=IFA_LOCAL && i!=IFA_ADDRESS && i!=IFA_FLAGS && - i!=IFA_BROADCAST && i!=IFA_LABEL && i!=IFA_CACHEINFO) return -LINUX_EOPNOTSUPP; + i!=IFA_BROADCAST && i!=IFA_LABEL && i!=IFA_CACHEINFO && + i!=IFA_RT_PRIORITY) return -LINUX_EOPNOTSUPP; if (!a[IFA_LOCAL] && !a[IFA_ADDRESS]) return -LINUX_EINVAL; uint32_t ip=0, peer=0, broadcast=0, flags=req->ifa_flags; rc=nl_copy_attr(a[IFA_LOCAL] ? a[IFA_LOCAL] : a[IFA_ADDRESS],&ip,4); if (rc) return rc; @@ -872,7 +1237,13 @@ static int nl_change_address4(struct net_namespace *ns, const struct nlmsghdr *h if (peer!=ip) return -LINUX_EOPNOTSUPP; } if (a[IFA_FLAGS]) { rc=nl_copy_attr(a[IFA_FLAGS],&flags,4); if (rc) return rc; } - if (flags & ~IFA_F_PERMANENT) return -LINUX_EOPNOTSUPP; + if (flags & ~(IFA_F_PERMANENT | IFA_F_NOPREFIXROUTE | IFA_F_DEPRECATED)) return -LINUX_EOPNOTSUPP; + struct net_ipv4_address_state policy = {.flags = flags, .scope = req->ifa_scope, + .preferred_until = UINT64_MAX, .valid_until = UINT64_MAX}; + if (a[IFA_RT_PRIORITY]) { + rc = nl_copy_attr(a[IFA_RT_PRIORITY], &policy.metric, 4); + if (rc) return rc; + } if (a[IFA_LABEL]) { char name[NET_IF_NAME_LEN]; if (!net_interface_name(ns, req->ifa_index,name)) return -LINUX_ENODEV; @@ -883,8 +1254,13 @@ static int nl_change_address4(struct net_namespace *ns, const struct nlmsghdr *h if (a[IFA_CACHEINFO]) { struct ifa_cacheinfo cache; rc=nl_copy_attr(a[IFA_CACHEINFO],&cache,sizeof(cache)); if (rc) return rc; - if (cache.ifa_prefered!=UINT32_MAX || cache.ifa_valid!=UINT32_MAX) return -LINUX_EOPNOTSUPP; + if (!cache.ifa_valid || cache.ifa_prefered > cache.ifa_valid) return -LINUX_EINVAL; + policy.preferred_until = nl_deadline(cache.ifa_prefered); + policy.valid_until = nl_deadline(cache.ifa_valid); + if (!cache.ifa_prefered) policy.flags |= IFA_F_DEPRECATED; } + if (policy.valid_until == UINT64_MAX) policy.flags |= IFA_F_PERMANENT; + else policy.flags &= ~IFA_F_PERMANENT; ip=__builtin_bswap32(ip); if (!ip || ip>=0xe0000000u) return -LINUX_EINVAL; uint32_t mask=req->ifa_prefixlen ? UINT32_MAX << (32u-req->ifa_prefixlen) : 0; @@ -896,10 +1272,10 @@ static int nl_change_address4(struct net_namespace *ns, const struct nlmsghdr *h if (!found) return -LINUX_EADDRNOTAVAIL; return net_interface_configure_ipv4(ns, req->ifa_index,0,0,0); } - if (iface->config.local_ip && !(h->nlmsg_flags & NLM_F_REPLACE)) return -LINUX_EEXIST; - if (!iface->config.local_ip && (h->nlmsg_flags & NLM_F_REPLACE) && - !(h->nlmsg_flags & NLM_F_CREATE)) return -LINUX_EADDRNOTAVAIL; - return net_interface_configure_ipv4(ns, req->ifa_index,ip,mask,broadcast); + if (iface->config.local_ip && + ((h->nlmsg_flags & NLM_F_EXCL) || !(h->nlmsg_flags & NLM_F_REPLACE))) + return -LINUX_EEXIST; + return net_interface_set_ipv4(ns, req->ifa_index,ip,mask,broadcast,&policy); } /** @brief Dispatch an authorized IPv4 or IPv6 address request to its network. @@ -912,11 +1288,12 @@ static int nl_change_address(struct net_namespace *ns, const struct nlmsghdr *h, if (req.ifa_family == AF_INET) return nl_change_address4(ns, h,&req,remove); if (req.ifa_family != AF_INET6) return -LINUX_EAFNOSUPPORT; if (!req.ifa_index || req.ifa_prefixlen > 128) return -LINUX_EINVAL; - const struct rtattr *a[9]={0}; + const struct rtattr *a[10]={0}; int rc=nl_parse_attrs((const uint8_t *)(h+1)+sizeof(req), - h->nlmsg_len-sizeof(*h)-sizeof(req),a,9); if (rc) return rc; - for (unsigned i=0;i<9;++i) - if (a[i] && i!=IFA_LOCAL && i!=IFA_ADDRESS && i!=IFA_FLAGS && i!=IFA_CACHEINFO && i!=IFA_LABEL) + h->nlmsg_len-sizeof(*h)-sizeof(req),a,10); if (rc) return rc; + for (unsigned i=0;i<10;++i) + if (a[i] && i!=IFA_LOCAL && i!=IFA_ADDRESS && i!=IFA_FLAGS && i!=IFA_CACHEINFO && + i!=IFA_LABEL && i!=IFA_RT_PRIORITY) return -LINUX_EOPNOTSUPP; if (!a[IFA_LOCAL] && !a[IFA_ADDRESS]) return -LINUX_EINVAL; struct net_ipv6_address entry={.ifindex=req.ifa_index,.prefix_length=req.ifa_prefixlen, @@ -924,10 +1301,15 @@ static int nl_change_address(struct net_namespace *ns, const struct nlmsghdr *h, rc=nl_copy_attr(a[IFA_LOCAL] ? a[IFA_LOCAL] : a[IFA_ADDRESS],&entry.address,16); if (rc) return rc; if (a[IFA_LOCAL] && a[IFA_ADDRESS]) { struct in6_addr peer; rc=nl_copy_attr(a[IFA_ADDRESS],&peer,16); if (rc) return rc; - if (__builtin_memcmp(&entry.address,&peer,16)) return -LINUX_EOPNOTSUPP; + static const struct in6_addr zero; + if (__builtin_memcmp(&entry.address,&peer,16) && __builtin_memcmp(&peer,&zero,16)) + return -LINUX_EOPNOTSUPP; } if (a[IFA_FLAGS]) { rc=nl_copy_attr(a[IFA_FLAGS],&entry.flags,4); if (rc) return rc; } - if (entry.flags & ~(NET_IPV6_ADDR_NODAD|NET_IPV6_ADDR_PERMANENT)) return -LINUX_EOPNOTSUPP; + if (entry.flags & ~(NET_IPV6_ADDR_NODAD|NET_IPV6_ADDR_PERMANENT|NET_IPV6_ADDR_DEPRECATED| + NET_IPV6_ADDR_NOPREFIXROUTE|NET_IPV6_ADDR_MANAGETEMPADDR)) return -LINUX_EOPNOTSUPP; + if ((entry.flags & NET_IPV6_ADDR_MANAGETEMPADDR) && entry.prefix_length!=64) return -LINUX_EINVAL; + if ((rc=nl_copy_attr(a[IFA_RT_PRIORITY],&entry.route_metric,4))) return rc; if (a[IFA_LABEL]) { const char *label=(const char *)(a[IFA_LABEL]+1); uint32_t n=a[IFA_LABEL]->rta_len-sizeof(struct rtattr); @@ -943,7 +1325,9 @@ static int nl_change_address(struct net_namespace *ns, const struct nlmsghdr *h, entry.preferred_until=nl_deadline(cache.ifa_prefered); entry.valid_until=nl_deadline(cache.ifa_valid); } + if (entry.preferred_until<=time_uptime_ms()) entry.flags|=NET_IPV6_ADDR_DEPRECATED; if (entry.valid_until==UINT64_MAX) entry.flags|=NET_IPV6_ADDR_PERMANENT; + else entry.flags &= ~NET_IPV6_ADDR_PERMANENT; struct net_ipv6_address *existing; uint32_t count; rc=nl_addresses(ns, &existing,&count); if (rc) return rc; bool found=false; @@ -951,9 +1335,9 @@ static int nl_change_address(struct net_namespace *ns, const struct nlmsghdr *h, if (existing[i].ifindex==entry.ifindex && !__builtin_memcmp(&existing[i].address,&entry.address,16)) { found=true; break; } kernel_free(existing); - if (!remove && found && (h->nlmsg_flags & NLM_F_EXCL)) return -LINUX_EEXIST; - if (!remove && !found && (h->nlmsg_flags & NLM_F_REPLACE) && !(h->nlmsg_flags & NLM_F_CREATE)) - return -LINUX_EADDRNOTAVAIL; + if (!remove && found && + ((h->nlmsg_flags & NLM_F_EXCL) || !(h->nlmsg_flags & NLM_F_REPLACE))) + return -LINUX_EEXIST; if (remove && !found) return -LINUX_EADDRNOTAVAIL; return net_ipv6_address_update(ns, &entry,remove); } @@ -967,25 +1351,42 @@ static int nl_change_address(struct net_namespace *ns, const struct nlmsghdr *h, */ static int nl_change_route4(struct net_namespace *ns, const struct nlmsghdr *h, const struct rtmsg *req, bool remove) { - if (req->rtm_dst_len>32 || req->rtm_src_len || req->rtm_tos || req->rtm_flags || + if (req->rtm_dst_len>32 || req->rtm_src_len || req->rtm_tos || (req->rtm_flags & ~RTNH_F_ONLINK) || (req->rtm_table && req->rtm_table!=RT_TABLE_MAIN) || (req->rtm_type && req->rtm_type!=RTN_UNICAST)) return -LINUX_EOPNOTSUPP; - const struct rtattr *a[16]={0}; + const struct rtattr *a[31]={0}; int rc=nl_parse_attrs((const uint8_t *)(h+1)+sizeof(*req), - h->nlmsg_len-sizeof(*h)-sizeof(*req),a,16); + h->nlmsg_len-sizeof(*h)-sizeof(*req),a,31); if (rc) return rc; - for (unsigned i=0;i<16;++i) + for (unsigned i=0;i<31;++i) if (a[i] && i!=RTA_DST && i!=RTA_GATEWAY && i!=RTA_OIF && - i!=RTA_PRIORITY && i!=RTA_TABLE) return -LINUX_EOPNOTSUPP; + i!=RTA_PRIORITY && i!=RTA_TABLE && i!=RTA_PREFSRC && i!=RTA_PREF && i!=RTA_NH_ID) return -LINUX_EOPNOTSUPP; if (req->rtm_dst_len && !a[RTA_DST]) return -LINUX_EINVAL; struct net_ipv4_route route={.mask=req->rtm_dst_len ? UINT32_MAX << (32u-req->rtm_dst_len) : 0, - .flags=RTF_UP}; + .flags=RTF_UP,.protocol=req->rtm_protocol,.scope=req->rtm_scope, + .onlink=(req->rtm_flags & RTNH_F_ONLINK)!=0}; if ((rc=nl_copy_attr(a[RTA_DST],&route.destination,4)) || (rc=nl_copy_attr(a[RTA_GATEWAY],&route.gateway,4)) || (rc=nl_copy_attr(a[RTA_OIF],&route.ifindex,4)) || - (rc=nl_copy_attr(a[RTA_PRIORITY],&route.metric,4))) return rc; + (rc=nl_copy_attr(a[RTA_PRIORITY],&route.metric,4)) || + (rc=nl_copy_attr(a[RTA_PREFSRC],&route.preferred_source,4)) || + (rc=nl_copy_attr(a[RTA_NH_ID],&route.nexthop_id,4))) return rc; route.destination=__builtin_bswap32(route.destination) & route.mask; route.gateway=__builtin_bswap32(route.gateway); + route.preferred_source=__builtin_bswap32(route.preferred_source); + uint8_t preference=0; + if ((rc=nl_copy_attr(a[RTA_PREF],&preference,1))) return rc; + if (preference) return -LINUX_EOPNOTSUPP; + if (a[RTA_NH_ID]) { + if (!route.nexthop_id || a[RTA_GATEWAY] || a[RTA_OIF]) return -LINUX_EINVAL; + const struct net_nexthop *next=net_nexthop_get(ns,route.nexthop_id); + if (!next) return -LINUX_ENOENT; + if (next->family!=AF_INET) return -LINUX_EINVAL; + route.ifindex=next->ifindex; + route.gateway=next->gateway.ipv4; + route.onlink=(next->flags & RTNH_F_ONLINK)!=0; + if (route.gateway) route.flags|=RTF_GATEWAY; + } if (a[RTA_TABLE]) { uint32_t table; rc=nl_copy_attr(a[RTA_TABLE],&table,4); if (rc) return rc; if (table!=RT_TABLE_MAIN) return -LINUX_EOPNOTSUPP; } if (a[RTA_GATEWAY]) { if (!route.gateway) return -LINUX_EINVAL; route.flags|=RTF_GATEWAY; } @@ -996,7 +1397,7 @@ static int nl_change_route4(struct net_namespace *ns, const struct nlmsghdr *h, if (rc) return rc; route.ifindex=path.ifindex; } - if (remove && !route.mask && !route.gateway) { + if (remove && !route.mask && !route.gateway && !route.nexthop_id) { struct net_interface *iface=net_interface_get(ns, route.ifindex); if (!iface || !iface->config.gateway_ip) return -LINUX_ESRCH; route.gateway=iface->config.gateway_ip; route.flags|=RTF_GATEWAY; @@ -1011,7 +1412,8 @@ static int nl_change_route4(struct net_namespace *ns, const struct nlmsghdr *h, bool found=false; for (uint32_t i=0;i 128 || req.rtm_src_len || req.rtm_tos || req.rtm_flags || + if (req.rtm_dst_len > 128 || req.rtm_src_len || req.rtm_tos || (req.rtm_flags & ~RTNH_F_ONLINK) || (req.rtm_table && req.rtm_table!=RT_TABLE_MAIN) || (req.rtm_type && req.rtm_type!=RTN_UNICAST)) return -LINUX_EOPNOTSUPP; - const struct rtattr *a[16]={0}; + const struct rtattr *a[31]={0}; int rc=nl_parse_attrs((const uint8_t *)(h+1)+sizeof(req), - h->nlmsg_len-sizeof(*h)-sizeof(req),a,16); if (rc) return rc; - for (unsigned i=0;i<16;++i) - if (a[i] && i!=RTA_DST && i!=RTA_GATEWAY && i!=RTA_OIF && i!=RTA_PRIORITY && i!=RTA_TABLE) + h->nlmsg_len-sizeof(*h)-sizeof(req),a,31); if (rc) return rc; + for (unsigned i=0;i<31;++i) + if (a[i] && i!=RTA_DST && i!=RTA_GATEWAY && i!=RTA_OIF && i!=RTA_PRIORITY && i!=RTA_TABLE && i!=RTA_PREFSRC && i!=RTA_PREF && + i!=RTA_NH_ID && i!=RTA_EXPIRES) return -LINUX_EOPNOTSUPP; - struct net_ipv6_route route={.prefix_length=req.rtm_dst_len,.metric=1024,.flags=RTF_UP,.valid_until=UINT64_MAX}; + struct net_ipv6_route route={.prefix_length=req.rtm_dst_len,.metric=1024,.flags=RTF_UP, + .protocol=req.rtm_protocol,.onlink=(req.rtm_flags & RTNH_F_ONLINK)!=0,.valid_until=UINT64_MAX}; if (req.rtm_dst_len && !a[RTA_DST]) return -LINUX_EINVAL; if ((rc=nl_copy_attr(a[RTA_DST],&route.destination,16)) || (rc=nl_copy_attr(a[RTA_GATEWAY],&route.gateway,16)) || (rc=nl_copy_attr(a[RTA_OIF],&route.ifindex,4)) || - (rc=nl_copy_attr(a[RTA_PRIORITY],&route.metric,4))) return rc; + (rc=nl_copy_attr(a[RTA_PRIORITY],&route.metric,4)) || + (rc=nl_copy_attr(a[RTA_PREFSRC],&route.preferred_source,16)) || + (rc=nl_copy_attr(a[RTA_PREF],&route.preference,1)) || + (rc=nl_copy_attr(a[RTA_NH_ID],&route.nexthop_id,4))) return rc; + if (route.preference==2 || route.preference>3) return -LINUX_EINVAL; + if (a[RTA_EXPIRES]) { + uint32_t seconds=0; + rc=nl_copy_attr(a[RTA_EXPIRES],&seconds,4); if (rc) return rc; + route.valid_until=nl_deadline(seconds); + } + if (a[RTA_NH_ID]) { + if (!route.nexthop_id || a[RTA_GATEWAY] || a[RTA_OIF]) return -LINUX_EINVAL; + const struct net_nexthop *next=net_nexthop_get(ns,route.nexthop_id); + if (!next) return -LINUX_ENOENT; + if (next->family!=AF_INET6) return -LINUX_EINVAL; + route.ifindex=next->ifindex; + route.gateway=next->gateway.ipv6; + route.onlink=(next->flags & RTNH_F_ONLINK)!=0; + static const struct in6_addr zero; + if (__builtin_memcmp(&route.gateway,&zero,16)) route.flags|=RTF_GATEWAY; + } if (!route.ifindex) return -LINUX_EINVAL; if (a[RTA_TABLE]) { uint32_t table; rc=nl_copy_attr(a[RTA_TABLE],&table,4); if (rc) return rc; if (table!=RT_TABLE_MAIN) return -LINUX_EOPNOTSUPP; } @@ -1057,9 +1481,12 @@ static int nl_change_route(struct net_namespace *ns, const struct nlmsghdr *h, b for (uint32_t i=0;inlmsg_flags & NLM_F_EXCL)) return -LINUX_EEXIST; + if (!remove && found && + ((h->nlmsg_flags & NLM_F_EXCL) || !(h->nlmsg_flags & NLM_F_REPLACE))) + return -LINUX_EEXIST; if (!remove && !found && (h->nlmsg_flags & NLM_F_REPLACE) && !(h->nlmsg_flags & NLM_F_CREATE)) return -LINUX_ESRCH; if (remove && !found) return -LINUX_ESRCH; @@ -1076,27 +1503,151 @@ static int nl_request(struct nl_builder *b, const struct nlmsghdr *h) struct net_namespace *ns = b->net_ns; int rc; if (!(h->nlmsg_flags & NLM_F_REQUEST)) rc=-LINUX_EINVAL; - else if (h->nlmsg_type==RTM_GETLINK || h->nlmsg_type==RTM_GETADDR || h->nlmsg_type==RTM_GETROUTE) + else if (h->nlmsg_type==RTM_GETLINK || h->nlmsg_type==RTM_GETADDR || h->nlmsg_type==RTM_GETROUTE || + h->nlmsg_type==RTM_GETNEIGH || h->nlmsg_type==RTM_GETNEXTHOP) rc=nl_dump(b,h); else if (h->nlmsg_type==RTM_NEWLINK || h->nlmsg_type==RTM_SETLINK || h->nlmsg_type==RTM_NEWADDR || h->nlmsg_type==RTM_DELADDR || - h->nlmsg_type==RTM_NEWROUTE || h->nlmsg_type==RTM_DELROUTE) { + h->nlmsg_type==RTM_NEWROUTE || h->nlmsg_type==RTM_DELROUTE || + h->nlmsg_type==RTM_NEWNEXTHOP || h->nlmsg_type==RTM_DELNEXTHOP) { struct task *task=sched_current_task(); if (!task_ns_capable(task, ns ? ns->user_ns : NULL, CAP_NET_ADMIN)) rc=-LINUX_EPERM; - else if (h->nlmsg_flags & (NLM_F_ECHO|NLM_F_APPEND)) rc=-LINUX_EOPNOTSUPP; + else if ((h->nlmsg_flags & NLM_F_ECHO) || + ((h->nlmsg_flags & NLM_F_APPEND) && h->nlmsg_type!=RTM_NEWROUTE)) + rc=-LINUX_EOPNOTSUPP; else if (h->nlmsg_type==RTM_NEWLINK || h->nlmsg_type==RTM_SETLINK) rc=nl_change_link(ns, h); else if (h->nlmsg_type==RTM_NEWADDR || h->nlmsg_type==RTM_DELADDR) rc=nl_change_address(ns, h,h->nlmsg_type==RTM_DELADDR); + else if (h->nlmsg_type==RTM_NEWNEXTHOP || h->nlmsg_type==RTM_DELNEXTHOP) + rc=nl_change_nexthop(ns, h,h->nlmsg_type==RTM_DELNEXTHOP); else rc=nl_change_route(ns, h,h->nlmsg_type==RTM_DELROUTE); } else rc=-LINUX_EOPNOTSUPP; if (rc) { b->used=original; return nl_error(b,h,rc); } - bool dump=(h->nlmsg_type==RTM_GETLINK || h->nlmsg_type==RTM_GETADDR || h->nlmsg_type==RTM_GETROUTE) && + bool dump=(h->nlmsg_type==RTM_GETLINK || h->nlmsg_type==RTM_GETADDR || h->nlmsg_type==RTM_GETROUTE || + h->nlmsg_type==RTM_GETNEIGH || h->nlmsg_type==RTM_GETNEXTHOP) && (h->nlmsg_flags & NLM_F_DUMP)==NLM_F_DUMP; if ((h->nlmsg_flags & NLM_F_ACK) && !dump) return nl_error(b,h,0); return 0; } +/** @brief Describe the registered control family and its supported operations. + * @param b Reply staging builder. @param h Checked GETFAMILY request. + * @param dump Select multipart flags. @return Zero or staging error. + * The static notify group uses Linux's reserved controller group ID. + */ +static int nl_ctrl_family(struct nl_builder *b, const struct nlmsghdr *h, bool dump) +{ + uint32_t start = b->used; + struct genlmsghdr *reply = nl_begin(b, GENL_ID_CTRL, dump ? NLM_F_MULTI : 0, + h->nlmsg_seq, sizeof(*reply)); + if (!reply) return -LINUX_ENOBUFS; + *reply = (struct genlmsghdr){.cmd = CTRL_CMD_NEWFAMILY, .version = 2}; + const uint16_t id = GENL_ID_CTRL; + const uint32_t version = 2, zero = 0; + const struct { + struct nlattr entry, id; + uint32_t command; + struct nlattr flags; + uint32_t capabilities; + } operations = { + .entry = {20, 1}, .id = {8, CTRL_ATTR_OP_ID}, .command = CTRL_CMD_GETFAMILY, + .flags = {8, CTRL_ATTR_OP_FLAGS}, .capabilities = GENL_CMD_CAP_DO | GENL_CMD_CAP_DUMP + }; + const struct { + struct nlattr entry, id; + uint32_t group; + struct nlattr name; + char value[8]; + } groups = { + .entry = {24, 1}, .id = {8, CTRL_ATTR_MCAST_GRP_ID}, .group = NL_CTRL_NOTIFY_GROUP, + .name = {11, CTRL_ATTR_MCAST_GRP_NAME}, .value = "notify" + }; + int rc = nl_attr(b, start, CTRL_ATTR_FAMILY_NAME, "nlctrl", sizeof("nlctrl")); + if (!rc) rc = nl_attr(b, start, CTRL_ATTR_FAMILY_ID, &id, sizeof(id)); + if (!rc) rc = nl_attr(b, start, CTRL_ATTR_VERSION, &version, sizeof(version)); + if (!rc) rc = nl_attr(b, start, CTRL_ATTR_HDRSIZE, &zero, sizeof(zero)); + if (!rc) rc = nl_attr(b, start, CTRL_ATTR_MAXATTR, &zero, sizeof(zero)); + if (!rc) rc = nl_attr(b, start, CTRL_ATTR_OPS, &operations, sizeof(operations)); + if (!rc) rc = nl_attr(b, start, CTRL_ATTR_MCAST_GROUPS, &groups, sizeof(groups)); + return rc; +} + +/** @brief Resolve a registered generic family using Linux controller attributes. + * @param b Reply builder. @param h Checked request. @return Zero or native errno. + * Unknown families return ENOENT without advertising unavailable protocols. + * Name lookup takes precedence when both name and ID attributes are supplied. + */ +static int nl_ctrl_getfamily(struct nl_builder *b, const struct nlmsghdr *h) +{ + bool dump = (h->nlmsg_flags & NLM_F_DUMP) == NLM_F_DUMP; + uint16_t id = 0; + const char *name = NULL; + bool has_id = false; + uint32_t offset = NLMSG_HDRLEN + GENL_HDRLEN; + while (h->nlmsg_len - offset >= NLA_HDRLEN) { + struct nlattr attr; + __builtin_memcpy(&attr, (const uint8_t *)h + offset, sizeof(attr)); + if (attr.nla_len < NLA_HDRLEN || attr.nla_len > h->nlmsg_len - offset) break; + uint32_t length = attr.nla_len - NLA_HDRLEN; + const void *value = (const uint8_t *)h + offset + NLA_HDRLEN; + switch (attr.nla_type & NLA_TYPE_MASK) { + case CTRL_ATTR_FAMILY_ID: + if (length < sizeof(id)) return -LINUX_ERANGE; + __builtin_memcpy(&id, value, sizeof(id)); + has_id = true; + break; + case CTRL_ATTR_FAMILY_NAME: + if (!length) return -LINUX_EINVAL; + uint32_t name_length = 0; + uint32_t limit = length < GENL_NAMSIZ ? length : GENL_NAMSIZ; + while (name_length < limit && ((const char *)value)[name_length]) ++name_length; + if (name_length == limit) return -LINUX_EINVAL; + if (length > GENL_NAMSIZ) return -LINUX_ERANGE; + name = value; + break; + default: + break; + } + uint32_t advance = NLA_ALIGN(attr.nla_len); + if (advance > h->nlmsg_len - offset) break; + offset += advance; + } + if (!dump) { + if (!name && !has_id) return -LINUX_EINVAL; + if (name ? __builtin_strcmp(name, "nlctrl") != 0 : id != GENL_ID_CTRL) + return -LINUX_ENOENT; + } + int rc = nl_ctrl_family(b, h, dump); + if (!rc && dump) rc = nl_done(b, h->nlmsg_seq); + return rc; +} + +/** @brief Dispatch generic control requests through the ordinary reply queue. + * @param b Reply builder. @param h Checked netlink frame. + * @return Zero or staging error. Semantic failures are queued NLMSG_ERROR replies. + */ +static int nl_generic_request(struct nl_builder *b, const struct nlmsghdr *h) +{ + if (!(h->nlmsg_flags & NLM_F_REQUEST) || h->nlmsg_type < NLMSG_MIN_TYPE) + return (h->nlmsg_flags & NLM_F_ACK) ? nl_error(b, h, 0) : 0; + uint32_t original = b->used; + int rc; + if (h->nlmsg_type != GENL_ID_CTRL) rc = -LINUX_ENOENT; + else if (h->nlmsg_len < NLMSG_HDRLEN + GENL_HDRLEN) rc = -LINUX_EINVAL; + else { + const struct genlmsghdr *request = (const void *)(h + 1); + rc = request->cmd == CTRL_CMD_GETFAMILY ? nl_ctrl_getfamily(b, h) : -LINUX_EOPNOTSUPP; + } + if (rc) { + b->used = original; + return nl_error(b, h, rc); + } + if ((h->nlmsg_flags & NLM_F_ACK) && (h->nlmsg_flags & NLM_F_DUMP) != NLM_F_DUMP) + return nl_error(b, h, 0); + return 0; +} + /** @brief Deliver a udev datagram within its socket's retained creating scope. * @param sender Sending socket under execution ownership. @param data Validated bytes. * @param length Nonzero bounded payload size. @param address Explicit user destination. @@ -1132,7 +1683,7 @@ static int nl_uevent_send(struct netlink_socket *sender, const void *data, uint3 return -LINUX_ENOBUFS; __builtin_memcpy(payload, data, length); if (dst.nl_groups) { - nl_multicast(sender->net_ns, NETLINK_KOBJECT_UEVENT, dst.nl_groups, payload, length, sender, &credentials); + nl_multicast(sender->net_ns, NETLINK_KOBJECT_UEVENT, dst.nl_groups, payload, length, sender, &credentials, false); rc = (int)length; } else { rc = -LINUX_ECONNREFUSED; @@ -1192,7 +1743,12 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui h.nlmsg_len-sizeof(struct nlmsghdr)); if (error_size > NL_MESSAGE_MAX-maximum_reply) return -LINUX_ENOBUFS; maximum_reply+=error_size; ++requests; - if (h.nlmsg_type==RTM_GETLINK || h.nlmsg_type==RTM_GETADDR || h.nlmsg_type==RTM_GETROUTE) { + bool dump_request = s->protocol == NETLINK_GENERIC ? + h.nlmsg_type == GENL_ID_CTRL && (h.nlmsg_flags & NLM_F_DUMP) == NLM_F_DUMP : + (h.nlmsg_type==RTM_GETLINK || h.nlmsg_type==RTM_GETADDR || + h.nlmsg_type==RTM_GETROUTE || h.nlmsg_type==RTM_GETNEIGH || + h.nlmsg_type==RTM_GETNEXTHOP); + if (dump_request) { has_dump=true; multipart |= (h.nlmsg_flags & NLM_F_DUMP)==NLM_F_DUMP; } @@ -1225,7 +1781,7 @@ int task_netlink_send(struct task_file *file,const void *data,uint32_t length,ui struct nl_builder builder={.message=message,.completion=completion,.net_ns=s->net_ns,.port=s->port}; for (pos=0;posprotocol == NETLINK_GENERIC ? nl_generic_request(&builder, h) : nl_request(&builder, h); if (rc) { s->queued_bytes-=reserved; kernel_free(completion); kernel_free(message); kernel_free(bytes); return rc; @@ -1415,9 +1971,12 @@ static int nl_protocol_option(struct task *task, struct netlink_socket *s, bool uint32_t group; int rc = socket_user_import(task, address, &group, sizeof(group)); if (rc) return rc; - if (!group || group > 32) return -LINUX_EINVAL; - uint32_t mask = 1u << (group - 1); - if (!(mask & (s->protocol == NETLINK_ROUTE ? NL_SUPPORTED_GROUPS : NL_UEVENT_GROUPS))) + uint32_t maximum = s->protocol == NETLINK_ROUTE ? RTNLGRP_MAX : 32; + if (!group || group > maximum) return -LINUX_EINVAL; + uint64_t mask = 1ULL << (group - 1); + if (s->protocol == NETLINK_GENERIC) + return nl_set_groups(s, option == NETLINK_ADD_MEMBERSHIP ? s->groups | mask : s->groups & ~mask); + if (!(mask & (s->protocol == NETLINK_ROUTE ? NL_ROUTE_GROUPS : NL_UEVENT_GROUPS))) return -LINUX_EOPNOTSUPP; rc = nl_set_groups(s, option == NETLINK_ADD_MEMBERSHIP ? s->groups | mask : s->groups & ~mask); if (!rc) s->memberships_initialized = true; @@ -1427,15 +1986,17 @@ static int nl_protocol_option(struct task *task, struct netlink_socket *s, bool int rc = socket_user_length(task, length, &capacity); if (rc) return rc; if ((int32_t)capacity < 0) return -LINUX_EINVAL; - uint32_t value, copied, required; + uint64_t value; + uint32_t copied, required; if (option == NETLINK_PKTINFO) { - if (capacity < sizeof(value)) return -LINUX_EINVAL; + if (capacity < sizeof(uint32_t)) return -LINUX_EINVAL; value = s->pktinfo; - copied = required = sizeof(value); + copied = required = sizeof(uint32_t); } else if (option == NETLINK_LIST_MEMBERSHIPS) { value = s->groups; - required = s->memberships_initialized ? sizeof(value) : 0; - copied = capacity >= required ? required : 0; + uint32_t bitmap_size = s->protocol == NETLINK_ROUTE ? sizeof(value) : sizeof(uint32_t); + required = s->memberships_initialized ? bitmap_size : 0; + copied = capacity < required ? capacity - capacity % sizeof(uint32_t) : required; } else return -LINUX_ENOPROTOOPT; rc = socket_user_prepare(task, address, copied, true); if (rc) return rc; @@ -1465,7 +2026,7 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, if (a0!=AF_NETLINK) return -LINUX_EAFNOSUPPORT; if (a1 & ~(uint64_t)(15|SOCK_NONBLOCK|SOCK_CLOEXEC)) return -LINUX_EINVAL; if (type!=SOCK_RAW && type!=SOCK_DGRAM) return -LINUX_ESOCKTNOSUPPORT; - if (a2 != NETLINK_ROUTE && a2 != NETLINK_KOBJECT_UEVENT) + if (a2 != NETLINK_ROUTE && a2 != NETLINK_KOBJECT_UEVENT && a2 != NETLINK_GENERIC) return -LINUX_EPROTONOSUPPORT; struct netlink_socket *s=kernel_malloc(sizeof(*s)); if (!s) return -LINUX_ENOMEM; struct task_file *file; int fd=task_allocate_fd(task,0,&file); diff --git a/net/socket/packet.c b/net/socket/packet.c index c89194a1..d0461be0 100644 --- a/net/socket/packet.c +++ b/net/socket/packet.c @@ -23,6 +23,7 @@ #include #include #include +#include "filter.h" #define PACKET_LIMIT 64u #define PACKET_QUEUE_LIMIT 32u @@ -34,6 +35,9 @@ struct packet_message { struct packet_message *next; uint32_t length; + uint32_t original_length; + struct linux_timeval timestamp; + bool timestamp_valid; struct sockaddr_ll link; struct sockaddr_in ip; struct sockaddr_in6 ip6; @@ -42,6 +46,11 @@ struct packet_message { uint8_t hops; uint8_t data[]; }; +struct packet_membership { + struct packet_membership *next; + struct packet_mreq request; + uint32_t references; +}; struct packet_socket { struct net_namespace *net_ns; int domain, type, protocol, ifindex; @@ -49,6 +58,11 @@ struct packet_socket { uint32_t uid; uint64_t ino; int error; + int priority; + uint32_t timestamp_option; + bool auxdata; + struct socket_filter *filter; + struct packet_membership *memberships; struct in6_addr local6, remote6; uint32_t scope6, remote_scope6, multicast_if; uint16_t ping_id; @@ -65,6 +79,87 @@ struct packet_socket { static struct packet_socket *sockets[PACKET_LIMIT]; static uint64_t packet_ino; +/** @brief Retain an enabled socket's realtime sample in its queued datagram. + * @param s Borrowed endpoint. @param m Owned queued or newly allocated packet. + * Lazy sampling also covers enabling timestamps after arrival and keeps PEEK stable. + */ +static void packet_timestamp(const struct packet_socket *s, struct packet_message *m) +{ + if (!s->timestamp_option || m->timestamp_valid) return; + struct linux_timespec now; + if (time_clock_get(LINUX_CLOCK_REALTIME, &now)) return; + m->timestamp = (struct linux_timeval){now.tv_sec, now.tv_nsec / 1000}; + m->timestamp_valid = true; +} + +/** @brief Admit extra link multicast through subscriptions shared by a device. + * @param ns Ingress network. @param ifindex Ingress device. @param frame Ethernet header. + * @param protocol Network-order EtherType. @return True for an admitted frame. + * Broad-multicast hardware is narrowed in software. Existing IPv4/IPv6 multicast + * reception remains available to their protocol stacks and packet taps. + */ +static bool packet_multicast_admitted(struct net_namespace *ns, uint32_t ifindex, + const uint8_t *frame, uint16_t protocol) +{ + static const uint8_t broadcast[6] = {255, 255, 255, 255, 255, 255}; + if (!(frame[0] & 1) || !__builtin_memcmp(frame, broadcast, sizeof(broadcast)) || + protocol == __builtin_bswap16(0x0800) || protocol == __builtin_bswap16(0x86dd)) return true; + for (unsigned i = 0; i < PACKET_LIMIT; ++i) { + const struct packet_socket *s = sockets[i]; + if (!s || s->net_ns != ns) continue; + for (const struct packet_membership *m = s->memberships; m; m = m->next) { + if ((uint32_t)m->request.mr_ifindex != ifindex) continue; + if (!__builtin_memcmp(m->request.mr_address, frame, 6)) return true; + } + } + return false; +} + +/** @brief Change one retained-network device subscription with duplicate references. + * @param s Endpoint owning the subscription. @param add True to acquire a reference. + * @param pointer User packet_mreq. @param length Native input size. + * @return Zero, errno, or a user-memory prerequisite marker. Failed additions are atomic. + */ +static int packet_membership_change(struct packet_socket *s, bool add, + uint64_t pointer, uint64_t length) +{ + if ((int32_t)length < (int32_t)sizeof(struct packet_mreq)) return -LINUX_EINVAL; + struct packet_mreq request; + int ret = socket_user_import(sched_current_task(), pointer, &request, sizeof(request)); + if (ret) return ret; + if (request.mr_alen > sizeof(request.mr_address)) return -LINUX_EINVAL; + if (add) { + if (request.mr_ifindex <= 0 || !net_interface_exists(s->net_ns, (uint32_t)request.mr_ifindex)) + return -LINUX_ENODEV; + if (request.mr_type != PACKET_MR_MULTICAST || request.mr_alen != 6 || + !(request.mr_address[0] & 1)) + return -LINUX_EINVAL; + } + struct packet_membership **link = &s->memberships; + while (*link) { + struct packet_membership *m = *link; + if (m->request.mr_ifindex == request.mr_ifindex && m->request.mr_type == request.mr_type && + m->request.mr_alen == request.mr_alen && + !__builtin_memcmp(m->request.mr_address, request.mr_address, request.mr_alen)) { + if (add) { + if (m->references == UINT32_MAX) return -LINUX_ENOBUFS; + ++m->references; + } else if (!--m->references) { + *link = m->next; + kernel_free(m); + } + return 0; + } + link = &m->next; + } + if (!add) return 0; + struct packet_membership *m = kernel_malloc(sizeof(*m)); + if (!m) return -LINUX_ENOBUFS; + *m = (struct packet_membership){.request = request, .references = 1}; + *link = m; + return 0; +} + /** @brief Test for an unspecified network-order IPv6 address. * @param address Address to inspect. @return True when all octets are zero. */ static bool packet6_any(const struct in6_addr *address) @@ -101,6 +196,7 @@ void net_packet_input_on(struct net_namespace *ns, uint32_t ifindex, const void const uint8_t *frame = input; uint16_t protocol; __builtin_memcpy(&protocol, frame + 12, 2); + if (!packet_multicast_admitted(ns, ifindex, frame, protocol)) return; for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *s = sockets[i]; if (!s || s->net_ns != ns || s->queued >= PACKET_QUEUE_LIMIT || @@ -122,15 +218,18 @@ void net_packet_input_on(struct net_namespace *ns, uint32_t ifindex, const void if ((s->local_ip && s->local_ip != destination) || (s->remote_ip && s->remote_ip != source)) continue; size = total; } - struct packet_message *m = kernel_malloc(sizeof(*m) + size); + uint32_t admitted = socket_filter_run(s->filter, frame + offset, size); + if (s->filter && !admitted) continue; + struct packet_message *m = kernel_malloc(sizeof(*m) + admitted); if (!m) continue; - *m = (struct packet_message){.length = size, + *m = (struct packet_message){.length = admitted, .original_length = size, .link = {.sll_family = AF_PACKET, .sll_protocol = protocol, .sll_ifindex = (int)ifindex, .sll_hatype = 1, .sll_halen = 6, .sll_pkttype = frame[0] == 255 ? PACKET_BROADCAST : frame[0] & 1 ? PACKET_MULTICAST : PACKET_HOST}, .ip = {.sin_family = AF_INET, .sin_addr.s_addr = source}}; __builtin_memcpy(m->link.sll_addr, frame + 6, 6); - __builtin_memcpy(m->data, frame + offset, size); + __builtin_memcpy(m->data, frame + offset, admitted); + packet_timestamp(s, m); if (s->tail) s->tail->next = m; else s->head = m; s->tail = m; @@ -167,12 +266,15 @@ void net_raw6_input(struct net_namespace *ns, const struct in6_addr *source, con !__builtin_memcmp(&s->groups[g].address, destination, sizeof(*destination))) joined = true; if (!joined) continue; } - struct packet_message *m = kernel_malloc(sizeof(*m) + length); + uint32_t admitted = socket_filter_run(s->filter, data, length); + if (s->filter && !admitted) continue; + struct packet_message *m = kernel_malloc(sizeof(*m) + admitted); if (!m) continue; - *m = (struct packet_message){.length = length, .destination6 = *destination, + *m = (struct packet_message){.length = admitted, .original_length = length, .destination6 = *destination, .ifindex = ifindex, .hops = hops, .ip6 = {.sin6_family = AF_INET6, .sin6_addr = *source, .sin6_scope_id = source->s6_addr[0] == 0xfe && (source->s6_addr[1] & 0xc0) == 0x80 ? ifindex : 0}}; - if (length) __builtin_memcpy(m->data, data, length); + __builtin_memcpy(m->data, data, admitted); + packet_timestamp(s, m); if (s->tail) s->tail->next = m; else s->head = m; s->tail = m; ++s->queued; kernel_poll_readiness_notify(); } @@ -328,6 +430,7 @@ static int packet_recv(struct task_file *file, void *data, uint32_t length, return KERNEL_SYSCALL_BLOCKED; } struct packet_message *m = s->head; + packet_timestamp(s, m); if(staged_source && staged_length) { const void *source=s->domain==AF_PACKET ? (const void *)&m->link : s->domain==AF_INET6 ? (const void *)&m->ip6 : (const void *)&m->ip; @@ -353,7 +456,11 @@ static int packet_recv(struct task_file *file, void *data, uint32_t length, if (info) *info = (struct net_udp_rx_info){.destination=m->destination6,.ifindex=m->ifindex, .hops=m->hops,.pktinfo=s->domain==AF_INET6 && s->recv_pktinfo, .hoplimit=s->domain==AF_INET6 && s->recv_hoplimit, - .old_hoplimit=s->domain==AF_INET6 && s->recv_old_hoplimit}; + .old_hoplimit=s->domain==AF_INET6 && s->recv_old_hoplimit, + .timestamp_option=m->timestamp_valid ? s->timestamp_option : 0, .timestamp=m->timestamp, + .packet_auxdata=s->domain==AF_PACKET && s->auxdata, + .auxdata={.tp_status=TP_STATUS_USER, .tp_len=m->original_length, .tp_snaplen=m->length, + .tp_net=s->domain==AF_PACKET && s->type==SOCK_RAW ? 14 : 0}}; uint32_t copied = length < m->length ? length : m->length; if (copied) __builtin_memcpy(data, m->data, copied); int result = flags & MSG_TRUNC ? (int)m->length : (int)copied; @@ -436,6 +543,12 @@ void task_packet_release(struct task_file *file) if (s->groups[i].used) (void)net_ipv6_multicast_change(s->net_ns, &s->groups[i].address, s->groups[i].ifindex, -1); while (s->head) { struct packet_message *m = s->head; s->head = m->next; kernel_free(m); } + while (s->memberships) { + struct packet_membership *m = s->memberships; + s->memberships = m->next; + kernel_free(m); + } + kernel_free(s->filter); net_namespace_put(s->net_ns); kernel_free(s); file->aux = 0; @@ -602,10 +715,10 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, struct packet_socket *s = packet_of(file); if (!s) return -LINUX_EBADF; if ((number == __NR_setsockopt || number == __NR_getsockopt) && - a1 == SOL_SOCKET && a2 == SO_BINDTODEVICE) { + a1 == SOL_SOCKET && (a2 == SO_BINDTODEVICE || a2 == SO_BINDTOIFINDEX)) { uint32_t index = (uint32_t)s->ifindex; bool set = number == __NR_setsockopt; - int result = net_interface_device_option(s->net_ns, set, a3, a4, &index); + int result = net_interface_device_option(s->net_ns, set, (uint32_t)a2, a3, a4, &index); if (!result && set) s->ifindex = (int)index; return result; } @@ -621,7 +734,7 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (address.sll_ifindex < 0 || (address.sll_ifindex && !net_interface_exists(s->net_ns, (uint32_t)address.sll_ifindex))) return -LINUX_ENODEV; s->ifindex = address.sll_ifindex; - s->protocol = address.sll_protocol; + if (address.sll_protocol) s->protocol = address.sll_protocol; } else if (s->domain == AF_INET6) { struct sockaddr_in6 address; int ret = packet6_import(a1, (uint32_t)a2, &address); @@ -710,6 +823,55 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, return packet6_option(s, set, (uint32_t)a1, (uint32_t)a2, a3, a4); if (a1 == PACKET_SOL_RAW) return -LINUX_ENOPROTOOPT; } + if (number == __NR_setsockopt && a1 == SOL_SOCKET && a2 == SO_ATTACH_FILTER) { + struct socket_filter *filter; + int ret = socket_filter_import(task, a3, a4, &filter); + if (ret) return ret; + kernel_free(s->filter); + s->filter = filter; + return 0; + } + if (number == __NR_setsockopt && a1 == SOL_SOCKET && a2 == SO_DETACH_FILTER) { + if (!s->filter) return -LINUX_ENOENT; + kernel_free(s->filter); + s->filter = NULL; + return 0; + } + if (number == __NR_setsockopt && a1 == SOL_PACKET && s->domain == AF_PACKET && + (a2 == PACKET_ADD_MEMBERSHIP || a2 == PACKET_DROP_MEMBERSHIP)) + return packet_membership_change(s, a2 == PACKET_ADD_MEMBERSHIP, a3, a4); + if ((number == __NR_setsockopt || number == __NR_getsockopt) && + ((a1 == SOL_SOCKET && (a2 == SO_TIMESTAMP_OLD || a2 == SO_TIMESTAMP_NEW || a2 == SO_PRIORITY)) || + (a1 == SOL_PACKET && s->domain == AF_PACKET && a2 == PACKET_AUXDATA))) { + bool set = number == __NR_setsockopt; + uint32_t length = (uint32_t)a4; + int value; + if (set) { + if ((int32_t)length < (int32_t)sizeof(value)) return -LINUX_EINVAL; + int ret = socket_user_import(task, a3, &value, sizeof(value)); + if (ret) return ret; + if (a1 == SOL_PACKET) s->auxdata = value != 0; + else if (a2 == SO_PRIORITY) { + if ((value < 0 || value > 6) && + !task_ns_capable(task, s->net_ns ? s->net_ns->user_ns : NULL, CAP_NET_RAW) && + !task_ns_capable(task, s->net_ns ? s->net_ns->user_ns : NULL, CAP_NET_ADMIN)) + return -LINUX_EPERM; + s->priority = value; + } else s->timestamp_option = value ? (uint32_t)a2 : 0; + return 0; + } + int ret = socket_user_length(task, a4, &length); + if (ret) return ret; + if ((int32_t)length < 0) return -LINUX_EINVAL; + if (length > sizeof(value)) length = sizeof(value); + value = a1 == SOL_PACKET ? s->auxdata : a2 == SO_PRIORITY ? s->priority : s->timestamp_option == a2; + ret = socket_user_prepare(task, a3, length, true); + if (ret) return ret; + if (length && !user_range_writable(a3, length)) return -LINUX_EFAULT; + if (length) __builtin_memcpy((void *)(uintptr_t)a3, &value, length); + *(uint32_t *)(uintptr_t)a4 = length; + return 0; + } if (number == __NR_getsockopt && a1 == SOL_SOCKET) { if (a2 == SO_RCVTIMEO || a2 == SO_RCVTIMEO_NEW) { int64_t timeout[2] = {(int64_t)(s->timeout / RELIEFNT_TICK_HZ), @@ -769,22 +931,21 @@ int64_t syscall_packet(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, return -LINUX_EOPNOTSUPP; } -/** @brief Report ICMPv6 errors to the socket owning the quoted protocol tuple. - * @param ns Borrowed network, NULL for the permanent initial network. - * @param ifindex Ingress link or zero for no link filter. - * @param packet Quoted original IPv6 packet. @param length Quote size. - * @param error Positive Linux errno. @param mtu Reported path MTU or zero. */ -void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex, const uint8_t *packet, uint32_t length, int error, uint32_t mtu) +/** @copydoc net_ipv6_socket_extended_error_on */ +void net_ipv6_socket_extended_error_on(struct net_namespace *ns, uint32_t ifindex, + const uint8_t *packet, uint32_t length, const struct sock_extended_err *error, + const struct sockaddr_storage *offender) { - if (!packet || length < 40 || packet[0] >> 4 != 6) return; + if (!packet || !error || !error->ee_errno || length < 40 || packet[0] >> 4 != 6) return; struct in6_addr source, destination; __builtin_memcpy(&source, packet + 8, 16); __builtin_memcpy(&destination, packet + 24, 16); uint8_t protocol = packet[6]; if ((protocol == 6 || protocol == 17) && length >= 48) { uint16_t source_port = ((uint16_t)packet[40] << 8) | packet[41]; uint16_t destination_port = ((uint16_t)packet[42] << 8) | packet[43]; - if (protocol == 6) net_tcp6_error_on(ns, ifindex, &source, &destination, source_port, destination_port, error, mtu); - else if (protocol == 17) net_udp6_error_on(ns, ifindex, &source, &destination, source_port, destination_port, error, mtu); + if (protocol == 6) net_tcp6_error_on(ns, ifindex, &source, &destination, + source_port, destination_port, (int)error->ee_errno, error->ee_info); + else net_udp_error_input(ns, ifindex, packet, length, error, offender); } for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *s = sockets[i]; @@ -794,11 +955,20 @@ void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex, const (s->remote_scope6 && s->remote_scope6 != ifindex))) || (!packet6_any(&s->local6) && __builtin_memcmp(&s->local6, &source, sizeof(source))) || (s->connected6 && __builtin_memcmp(&s->remote6, &destination, sizeof(destination)))) continue; - s->error = error; + s->error = (int)error->ee_errno; } kernel_poll_readiness_notify(); } +/** @copydoc net_ipv6_socket_error_on */ +void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex, + const uint8_t *packet, uint32_t length, int error, uint32_t mtu) +{ + struct sock_extended_err extended = {.ee_errno = (uint32_t)error, + .ee_origin = SO_EE_ORIGIN_LOCAL, .ee_info = mtu}; + net_ipv6_socket_extended_error_on(ns, ifindex, packet, length, &extended, NULL); +} + /** @brief Render one network's raw IPv6 endpoints and receive queue sizes. * @param ns Borrowed network, NULL for the permanent initial network. * @param stream Caller-owned proc output. */ @@ -853,6 +1023,16 @@ void net_packet_device_detached(uint32_t ifindex) { for (unsigned i = 0; i < PACKET_LIMIT; ++i) { struct packet_socket *socket = sockets[i]; + if (socket && !socket->net_ns) { + struct packet_membership **link = &socket->memberships; + while (*link) { + struct packet_membership *m = *link; + if ((uint32_t)m->request.mr_ifindex == ifindex) { + *link = m->next; + kernel_free(m); + } else link = &m->next; + } + } if (socket && !socket->net_ns && ((uint32_t)socket->ifindex == ifindex || socket->scope6 == ifindex || socket->remote_scope6 == ifindex)) socket->error = LINUX_ENETDOWN; } diff --git a/net/socket/udp.c b/net/socket/udp.c index f73e38cd..df244779 100644 --- a/net/socket/udp.c +++ b/net/socket/udp.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -39,6 +40,16 @@ struct udp_packet { uint8_t hops; bool ipv4; uint16_t port; + struct linux_timeval timestamp; + bool timestamp_valid; + unsigned char data[]; +}; +struct udp_error { + struct udp_error *next; + struct sockaddr_storage destination; + struct net_udp_error_info info; + uint32_t length; + bool ipv4; unsigned char data[]; }; struct udp_socket { @@ -47,6 +58,16 @@ struct udp_socket { struct in6_addr local6, remote6; uint32_t scope6, remote_scope6, multicast_if; int unicast_hops, multicast_hops, mtu_discover; + int ipv4_ttl, ipv4_multicast_ttl, ipv4_mtu_discover; + int priority; + uint32_t timestamp_option; + uint8_t ipv4_tos; + bool ipv4_pktinfo, ipv4_recvttl, ipv4_multicast_loop, ipv4_multicast_all; + bool ipv4_freebind; + bool ipv4_recverr, ipv6_recverr; + uint32_t ipv4_multicast_if, ipv4_multicast_source; + uint32_t ipv4_unicast_if, ipv6_unicast_if; + struct { uint32_t address, ifindex; } groups4[UDP6_GROUP_LIMIT]; uint32_t uid; uint64_t ino; uint16_t port, remote_port; @@ -59,6 +80,8 @@ struct udp_socket { uint64_t receive_timeout; uint32_t queued; struct udp_packet *head, *tail; + uint32_t errors_queued; + struct udp_error *errors_head, *errors_tail; struct udp_socket *registry_next; }; static struct udp_socket *sockets; @@ -69,6 +92,51 @@ static uint32_t swap32(uint32_t x) { return __builtin_bswap32(x); } static struct udp_socket *udp_from_file(struct task_file *file) { return file && file->kind == TASK_FILE_KIND_UDP ? (void *)(uintptr_t)file->aux : NULL; } +/** @brief Retain the enabled socket's realtime sample in one owned datagram. + * @param socket Borrowed UDP endpoint under execution ownership. + * @param packet Owned queued or newly allocated datagram. + * Lazy sampling covers enabling timestamps after arrival and keeps PEEK stable. + */ +static void udp_timestamp(const struct udp_socket *socket, struct udp_packet *packet) +{ + if (!socket->timestamp_option || packet->timestamp_valid) return; + struct linux_timespec now; + if (time_clock_get(LINUX_CLOCK_REALTIME, &now)) return; + packet->timestamp = (struct linux_timeval){now.tv_sec, now.tv_nsec / 1000}; + packet->timestamp_valid = true; +} + +/** @brief Test a host-order IPv4 destination for the multicast prefix. + * @param address IPv4 address. @return True within 224.0.0.0/4. */ +static bool udp4_multicast(uint32_t address) +{ + return (address & 0xf0000000u) == 0xe0000000u; +} + +/** @brief Match one socket's IPv4 group membership on the ingress link. + * @param s Borrowed socket. @param address Multicast destination. + * @param ifindex Ingress interface. @return True for a retained subscription. */ +static bool udp4_group_member(const struct udp_socket *s, uint32_t address, uint32_t ifindex) +{ + for (unsigned i = 0; i < UDP6_GROUP_LIMIT; ++i) + if (s->groups4[i].address == address && s->groups4[i].ifindex == ifindex) + return true; + return false; +} + +/** @brief Apply per-socket or creating-network-wide IPv4 multicast membership. + * @param s Receiving endpoint. @param address Multicast destination. + * @param ifindex Ingress link. @return True when delivery is subscribed. */ +static bool udp4_group_accepts(const struct udp_socket *s, uint32_t address, uint32_t ifindex) +{ + if (udp4_group_member(s, address, ifindex)) return true; + if (!s->ipv4_multicast_all) return false; + for (const struct udp_socket *other = sockets; other; other = other->registry_next) + if (other->net_ns == s->net_ns && udp4_group_member(other, address, ifindex)) + return true; + return false; +} + /** @copydoc task_udp_namespace */ struct net_namespace *task_udp_namespace(const struct task_file *file) { @@ -113,6 +181,117 @@ static struct in6_addr udp6_map(uint32_t ip) return address; } +/** @brief Read a network-order 16-bit field without alignment requirements. + * @param bytes Two readable bytes. @return Host-order value. */ +static uint16_t udp_read_u16(const uint8_t *bytes) +{ + return (uint16_t)((uint16_t)bytes[0] << 8) | bytes[1]; +} + +/** @brief Read a network-order IPv4 field without alignment requirements. + * @param bytes Four readable bytes. @return Host-order address. */ +static uint32_t udp_read_u32(const uint8_t *bytes) +{ + return ((uint32_t)bytes[0] << 24) | ((uint32_t)bytes[1] << 16) | + ((uint32_t)bytes[2] << 8) | bytes[3]; +} + +/** @brief Release all independently owned extended errors for one endpoint. + * @param s Execution-owned socket. The ordinary data queue and pending errno survive. */ +static void udp_errors_clear(struct udp_socket *s) +{ + while (s->errors_head) { + struct udp_error *error = s->errors_head; + s->errors_head = error->next; + kernel_free(error); + } + s->errors_tail = NULL; + s->errors_queued = 0; +} + +/** @copydoc net_udp_error_input */ +void net_udp_error_input(struct net_namespace *ns, uint32_t ifindex, + const uint8_t *packet, uint32_t length, + const struct sock_extended_err *error, + const struct sockaddr_storage *offender) +{ + if (!packet || !error || !error->ee_errno || length < 28) return; + bool ipv4 = packet[0] >> 4 == 4; + uint32_t header, total; + struct in6_addr source6, destination6; + uint32_t source4 = 0, destination4 = 0; + if (ipv4) { + header = (packet[0] & 15u) * 4u; + total = udp_read_u16(packet + 2); + if (header < 20 || length < header + 8 || total < header + 8 || + packet[9] != 17 || (udp_read_u16(packet + 6) & 0x1fffu)) return; + source4 = udp_read_u32(packet + 12); + destination4 = udp_read_u32(packet + 16); + source6 = udp6_map(source4); + destination6 = udp6_map(destination4); + } else { + if (packet[0] >> 4 != 6 || length < 48 || packet[6] != 17) return; + header = 40; + total = 40u + udp_read_u16(packet + 4); + if (total < 48) return; + __builtin_memcpy(&source6, packet + 8, sizeof(source6)); + __builtin_memcpy(&destination6, packet + 24, sizeof(destination6)); + } + uint32_t udp_length = udp_read_u16(packet + header + 4); + if (udp_length < 8 || udp_length > total - header) return; + if (length > header + udp_length) length = header + udp_length; + uint16_t source_port = udp_read_u16(packet + header); + uint16_t destination_port = udp_read_u16(packet + header + 2); + for (struct udp_socket *s = sockets; s; s = s->registry_next) { + if (s->net_ns != ns || !s->bound || s->port != source_port || + (s->ifindex && ifindex && (uint32_t)s->ifindex != ifindex)) continue; + bool recverr = ipv4 ? s->ipv4_recverr : s->ipv6_recverr; + if (ipv4) { + if ((s->ipv6 && (s->v6only || (!udp6_any(&s->local6) && !udp6_mapped(&s->local6)))) || + (s->local && s->local != source4) || + (s->connected && (s->remote != destination4 || s->remote_port != destination_port)) || + (!recverr && !s->connected)) continue; + } else if (!s->ipv6 || + (ifindex && ((s->scope6 && s->scope6 != ifindex) || + (s->remote_scope6 && s->remote_scope6 != ifindex))) || + (!udp6_any(&s->local6) && __builtin_memcmp(&s->local6, &source6, sizeof(source6))) || + (s->connected && (s->remote_port != destination_port || + __builtin_memcmp(&s->remote6, &destination6, sizeof(destination6))))) continue; + s->error = (int)error->ee_errno; + if (!recverr || s->errors_queued == UDP_QUEUE_LENGTH) continue; + uint32_t payload_length = length - header - 8; + struct udp_error *record = kernel_malloc(sizeof(*record) + payload_length); + if (!record) continue; + *record = (struct udp_error){.info.error = *error, + .length = payload_length, .ipv4 = !s->ipv6}; + if (offender) record->info.offender = *offender; + if (s->ipv6 && offender && offender->ss_family == AF_INET) { + const struct sockaddr_in *from = (const void *)offender; + struct sockaddr_in6 from6 = {.sin6_family = AF_INET6, + .sin6_addr = udp6_map(swap32(from->sin_addr.s_addr))}; + __builtin_memset(&record->info.offender, 0, sizeof(record->info.offender)); + __builtin_memcpy(&record->info.offender, &from6, sizeof(from6)); + } + if (s->ipv6) { + struct sockaddr_in6 to = {.sin6_family = AF_INET6, + .sin6_addr = destination6, .sin6_port = swap16(destination_port), + .sin6_scope_id = !ipv4 && destination6.s6_addr[0] == 0xfe && + (destination6.s6_addr[1] & 0xc0) == 0x80 ? ifindex : 0}; + __builtin_memcpy(&record->destination, &to, sizeof(to)); + } else { + struct sockaddr_in to = {.sin_family = AF_INET, + .sin_addr.s_addr = swap32(destination4), .sin_port = swap16(destination_port)}; + __builtin_memcpy(&record->destination, &to, sizeof(to)); + } + if (payload_length) __builtin_memcpy(record->data, packet + header + 8, payload_length); + if (s->errors_tail) s->errors_tail->next = record; + else s->errors_head = record; + s->errors_tail = record; + ++s->errors_queued; + } + kernel_poll_readiness_notify(); +} + /** @brief Check whether two bound sockets overlap in the IPv4 namespace. * @param s First socket. @param ip First socket's requested IPv4 address. * @param other Existing socket. @return True when both can receive the same IPv4 tuple. */ @@ -130,12 +309,15 @@ static bool udp_ipv4_overlap(const struct udp_socket *s, uint32_t ip, * @param ip Requested local IPv4 address, or zero for any address. * @param port Requested local port, or zero for automatic allocation. * @return Zero on success or a negative errno. + * IP_FREEBIND admits non-local IPv4 addresses within the creating network. * Binding a privileged port requires CAP_NET_BIND_SERVICE in the network owner. + * Port conflicts and interface overlap are checked after address admission. */ static int bind_port(struct udp_socket *s, uint32_t ip, uint16_t port) { if (s->bound) return -LINUX_EINVAL; - if (ip && !net_interface_for_ipv4(s->net_ns, ip)) return -LINUX_EADDRNOTAVAIL; + if (ip && !udp4_multicast(ip) && !s->ipv4_freebind && + !net_interface_for_ipv4(s->net_ns, ip)) return -LINUX_EADDRNOTAVAIL; struct task *task = sched_current_task(); if (port && port < 1024 && !task_ns_capable(task, s->net_ns ? s->net_ns->user_ns : NULL, CAP_NET_BIND_SERVICE)) @@ -173,11 +355,13 @@ static int bind_port(struct udp_socket *s, uint32_t ip, uint16_t port) * @param data Datagram payload. * @param length Payload bytes. * @param ifindex Incoming interface index. + * @param ttl Received IPv4 time to live. */ -void net_udp_input(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, - uint16_t destination_port, const void *data, uint32_t length, int ifindex) +void net_udp_input_ex(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, + uint16_t destination_port, const void *data, uint32_t length, int ifindex, uint8_t ttl) { if (length > UDP_MAX_PAYLOAD) return; + bool multicast = udp4_multicast(destination); for (struct udp_socket *s = sockets; s; s = s->registry_next) { if (s->net_ns != ns) continue; if (s->ipv6 && (s->v6only || @@ -187,20 +371,31 @@ void net_udp_input(struct net_namespace *ns, uint32_t source, uint32_t destinati (s->local && s->local != destination) || (s->connected && (s->remote != source || s->remote_port != source_port)) || s->queued >= UDP_QUEUE_LENGTH) continue; + if (multicast && !udp4_group_accepts(s, destination, (uint32_t)ifindex)) continue; struct udp_packet *packet = kernel_malloc(sizeof(*packet) + length); if (!packet) continue; *packet = (struct udp_packet){.source = source, .port = source_port, .length = length, - .source6 = udp6_map(source), .destination6 = udp6_map(destination), .ifindex = (uint32_t)ifindex, .ipv4 = true}; + .source6 = udp6_map(source), .destination6 = udp6_map(destination), + .ifindex = (uint32_t)ifindex, .hops = ttl, .ipv4 = true}; + udp_timestamp(s, packet); __builtin_memcpy(packet->data, data, length); if (s->tail) s->tail->next = packet; else s->head = packet; s->tail = packet; ++s->queued; kernel_poll_readiness_notify(); - if (destination != 0xffffffffu) break; + if (destination != 0xffffffffu && !multicast) break; } } +/** @copydoc net_udp_input */ +void net_udp_input(struct net_namespace *ns, uint32_t source, uint32_t destination, + uint16_t source_port, uint16_t destination_port, const void *data, + uint32_t length, int ifindex) +{ + net_udp_input_ex(ns, source, destination, source_port, destination_port, data, length, ifindex, 64); +} + /** @brief Queue a validated native IPv6 UDP datagram for a matching endpoint. * @param ns Borrowed network, NULL for the permanent initial network. * @param source Network-order source. @param destination Network-order destination. @@ -232,6 +427,7 @@ bool net_udp6_input(struct net_namespace *ns, const struct in6_addr *source, con if (!packet) continue; *packet = (struct udp_packet){.source6 = *source, .destination6 = *destination, .port = source_port, .length = length, .ifindex = ifindex, .hops = hops}; + udp_timestamp(s, packet); if (length) __builtin_memcpy(packet->data, data, length); if (s->tail) s->tail->next = packet; else s->head = packet; @@ -300,6 +496,50 @@ static int udp6_export(uint64_t pointer, uint64_t length_pointer, const struct s return 0; } +/** @brief Observe or consume an extended error independently of normal datagrams. + * @param s Execution-owned UDP socket. @param data Prepared output bytes. + * @param length Payload capacity. @param flags Receive flags, with internal PEEK support. + * @param address Optional prepared user destination. @param address_length User socklen. + * @param source Optional kernel destination sockaddr. @param source_length Native size output. + * @param info Optional owned metadata output. @return Bytes or EAGAIN, with no waiting. + * Final dequeue regenerates the pending errno from the next retained error. + */ +static int udp_error_recv(struct udp_socket *s, void *data, uint32_t length, uint32_t flags, + uint64_t address, uint64_t address_length, + void *source, uint32_t *source_length, struct net_udp_rx_info *info) +{ + net_poll_packets(); + struct udp_error *error = s->errors_head; + if (!error) return -LINUX_EAGAIN; + uint32_t native_size = s->ipv6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in); + if (address) { + int result; + if (s->ipv6) result = udp6_export(address, address_length, (void *)&error->destination); + else { + const struct sockaddr_in *to = (const void *)&error->destination; + result = export_address(address, address_length, swap32(to->sin_addr.s_addr), swap16(to->sin_port)); + } + if (result) return result; + } + if (source && source_length) { + __builtin_memcpy(source, &error->destination, native_size); + *source_length = native_size; + } + if (info) *info = (struct net_udp_rx_info){.ipv4 = error->ipv4, + .error_queue = true, .extended = error->info}; + uint32_t copied = length < error->length ? length : error->length; + if (copied) __builtin_memcpy(data, error->data, copied); + int result = (flags & MSG_TRUNC) ? (int)error->length : (int)copied; + if (!(flags & MSG_PEEK)) { + s->errors_head = error->next; + if (!s->errors_head) s->errors_tail = NULL; + --s->errors_queued; + s->error = s->errors_head ? (int)s->errors_head->info.error.ee_errno : 0; + kernel_free(error); + } + return result; +} + /** @brief Bind an IPv6 UDP socket with shared IPv4 port conflict checks. * @param s Unbound socket. @param address Checked native socket address. * @return Zero or negative errno; failed attempts do not alter the binding. */ @@ -334,20 +574,32 @@ static int udp6_bind(struct udp_socket *s, const struct sockaddr_in6 *address) /** @brief Send IPv4 UDP through the socket's retained network and route. * @param s Owning socket. @param ip Host-order destination. @param port Peer port. * @param data Borrowed payload. @param length Payload bytes. + * @param info Optional checked per-message routing and TTL hints. * @return Accepted bytes or negative errno. Local delivery requires a ready * interface and accounts traffic in the creating network under execution ownership. + * Hardware output carries the socket's complete IPv4 TOS byte. Per-message + * and bound-device selection precede the unicast or multicast output default. */ static int udp4_send(struct udp_socket *s, uint32_t ip, uint16_t port, - const void *data, uint32_t length) + const void *data, uint32_t length, const struct net_udp_tx_info *info) { if (!port) return -LINUX_EINVAL; if (ip == UINT32_MAX && !s->broadcast) return -LINUX_EACCES; + bool multicast = udp4_multicast(ip); + uint32_t scope = info && info->ifindex ? info->ifindex : (uint32_t)s->ifindex; + if (!scope) scope = multicast ? s->ipv4_multicast_if : s->ipv4_unicast_if; + if (s->ifindex && scope != (uint32_t)s->ifindex) return -LINUX_EINVAL; + uint32_t source = info && info->source4 ? info->source4 : s->local; + if (udp4_multicast(source)) source = 0; + if (!source && multicast) source = s->ipv4_multicast_source; + int ttl = info && info->ttl >= 0 ? info->ttl : + multicast ? s->ipv4_multicast_ttl : s->ipv4_ttl; if (!s->bound) { int ret = bind_port(s, 0, 0); if (ret < 0) return ret; } struct net_ipv4_path path; - int ret = net_ipv4_route_lookup(s->net_ns, ip, s->local, (uint32_t)s->ifindex, &path); + int ret = net_ipv4_route_lookup(s->net_ns, ip, source, scope, &path); if (ret < 0) return ret; if (net_interface_for_ipv4(s->net_ns, ip)) { if (!net_interface_is_ready(s->net_ns, path.ifindex)) return -LINUX_ENETDOWN; @@ -358,20 +610,29 @@ static int udp4_send(struct udp_socket *s, uint32_t ip, uint16_t port, loopback_bytes += length + 28; ++loopback_packets; } - net_udp_input(s->net_ns, path.source, ip, s->port, port, data, length, (int)path.ifindex); + net_udp_input_ex(s->net_ns, path.source, ip, s->port, port, data, length, + (int)path.ifindex, (uint8_t)ttl); return (int)length; } - ret = net_ipv4_send_udp_on(s->net_ns, path.ifindex, path.source, ip, - s->port, port, data, length); + if (multicast && (!ttl || path.ifindex == NET_IF_LOOPBACK)) ret = 0; + else ret = net_ipv4_send_udp_options_tos(s->net_ns, path.ifindex, path.source, ip, + s->port, port, data, length, (uint8_t)ttl, + s->ipv4_mtu_discover == IP_PMTUDISC_DO || + s->ipv4_mtu_discover == IP_PMTUDISC_PROBE, s->ipv4_tos); + if (ret >= 0 && multicast && s->ipv4_multicast_loop) + net_udp_input_ex(s->net_ns, path.source, ip, s->port, port, data, length, + (int)path.ifindex, (uint8_t)ttl); return ret < 0 ? ret : (int)length; } /** @brief Send native or mapped IPv6 UDP within the socket's creating network. * @param s Owning socket. @param data Borrowed payload. @param length Payload bytes. * @param address Optional user destination. @param address_length Destination bytes. - * @return Accepted payload bytes or a negative errno. */ + * @param info Optional checked per-message routing and hop-limit hints. + * @return Accepted payload bytes or a negative errno. Unicast output uses its + * own interface default after explicit scope, message and bound-device hints. */ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, - uint64_t address, uint32_t address_length) + uint64_t address, uint32_t address_length, const struct net_udp_tx_info *info) { struct sockaddr_in6 to = {.sin6_family = AF_INET6, .sin6_addr = s->remote6, .sin6_port = swap16(s->remote_port), .sin6_scope_id = s->remote_scope6}; @@ -382,15 +643,27 @@ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, if (udp6_mapped(&to.sin6_addr)) { if (length > UDP_MAX_PAYLOAD) return -LINUX_EMSGSIZE; if (s->v6only || (!udp6_any(&s->local6) && !udp6_mapped(&s->local6))) return -LINUX_ENETUNREACH; - return udp4_send(s, udp6_unmap(&to.sin6_addr), port, data, length); + struct net_udp_tx_info mapped = info ? *info : (struct net_udp_tx_info){.ttl = -1, .hops = -1}; + if (!udp6_any(&mapped.source6)) { + if (!udp6_mapped(&mapped.source6)) return -LINUX_EINVAL; + mapped.source4 = udp6_unmap(&mapped.source6); + } + return udp4_send(s, udp6_unmap(&to.sin6_addr), port, data, length, &mapped); } if (udp6_mapped(&s->local6)) return -LINUX_ENETUNREACH; if (to.sin6_scope_id && s->ifindex && to.sin6_scope_id != (uint32_t)s->ifindex) return -LINUX_EINVAL; uint32_t scope = to.sin6_scope_id ? to.sin6_scope_id : (uint32_t)s->ifindex; - if (!scope && to.sin6_addr.s6_addr[0] == 0xff) scope = s->multicast_if; + if (info && info->ifindex) { + if ((s->ifindex && info->ifindex != (uint32_t)s->ifindex) || + (to.sin6_scope_id && info->ifindex != to.sin6_scope_id)) return -LINUX_EINVAL; + scope = info->ifindex; + } + if (!scope) scope = to.sin6_addr.s6_addr[0] == 0xff ? + s->multicast_if : s->ipv6_unicast_if; + const struct in6_addr *source = info && !udp6_any(&info->source6) ? &info->source6 : &s->local6; struct net_ipv6_path path; - int ret = net_ipv6_route(s->net_ns, &to.sin6_addr, scope, &s->local6, &path); + int ret = net_ipv6_route(s->net_ns, &to.sin6_addr, scope, source, &path); if (ret < 0) return ret; if (!s->bound) { ret = bind_port(s, 0, 0); if (ret < 0) return ret; } uint8_t *packet = kernel_malloc(length + 8); @@ -404,26 +677,24 @@ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, if (!checksum) checksum = 0xffff; packet[6] = (uint8_t)(checksum >> 8); packet[7] = (uint8_t)checksum; int hops = to.sin6_addr.s6_addr[0] == 0xff ? s->multicast_hops : s->unicast_hops; + if (info && info->hops >= 0) hops = info->hops; ret = net_ipv6_output(s->net_ns, &path, 17, packet, length + 8, hops, to.sin6_flowinfo, s->dont_fragment || s->mtu_discover == IPV6_PMTUDISC_DO, s->multicast_loop); kernel_free(packet); return ret < 0 ? ret : (int)length; } -/** @brief Send one IPv4, IPv6 or mapped UDP datagram without retaining caller buffers. - * @param file Pinned UDP OFD. @param data Borrowed validated payload. - * @param length Payload bytes. @param flags Native send flags. - * @param address Optional user destination. @param address_length Destination size. - * @return Accepted bytes, negative errno, or user-memory prerequisite marker. */ -int task_udp_send(struct task_file *file, const void *data, uint32_t length, - uint32_t flags, uint64_t address, uint32_t address_length) +/** @copydoc task_udp_send_ex */ +int task_udp_send_ex(struct task_file *file, const void *data, uint32_t length, + uint32_t flags, uint64_t address, uint32_t address_length, + const struct net_udp_tx_info *info) { struct udp_socket *s = udp_from_file(file); if (!s) return -LINUX_EBADF; if (s->error) { int error = s->error; s->error = 0; return -error; } if (flags & ~(MSG_DONTWAIT | MSG_NOSIGNAL)) return -LINUX_EOPNOTSUPP; if (length > (s->ipv6 ? UDP6_MAX_PAYLOAD : UDP_MAX_PAYLOAD)) return -LINUX_EMSGSIZE; - if (s->ipv6) return udp6_send(s, data, length, address, address_length); + if (s->ipv6) return udp6_send(s, data, length, address, address_length, info); uint32_t ip = s->remote; uint16_t port = s->remote_port; if (address) { @@ -432,7 +703,19 @@ int task_udp_send(struct task_file *file, const void *data, uint32_t length, if (ret < 0) return ret; ip = swap32(to.sin_addr.s_addr); port = swap16(to.sin_port); } else if (!s->connected) return -LINUX_EDESTADDRREQ; - return udp4_send(s, ip, port, data, length); + return udp4_send(s, ip, port, data, length, info); +} + +/** @brief Send UDP using the persistent socket routing and IP options. + * @param file Pinned UDP OFD. @param data Borrowed payload. @param length Bytes. + * @param flags Native send flags. @param address Optional user destination. + * @param address_length Destination bytes. + * @return Accepted bytes, negative errno, or user-memory prerequisite marker. + */ +int task_udp_send(struct task_file *file, const void *data, uint32_t length, + uint32_t flags, uint64_t address, uint32_t address_length) +{ + return task_udp_send_ex(file, data, length, flags, address, address_length, NULL); } /** @@ -445,10 +728,11 @@ int task_udp_send(struct task_file *file, const void *data, uint32_t length, * @param address_length Optional source-address length pointer. * @param source Optional caller-owned native sockaddr output. * @param source_length Optional actual source-size output. - * @param info Optional caller-owned IPv6 ingress metadata output. + * @param info Optional caller-owned ingress metadata and realtime timestamp output. * @return Received length, zero for an empty datagram, or negative errno/status. * @note A negative timeval seconds value is stored as immediate timeout, distinct * from the all-zero value, which keeps the default infinite wait. + * Enabled timestamp delivery retains one sample across PEEK and format changes. */ static int udp_recv(struct task_file *file, void *data, uint32_t length, uint32_t flags, uint64_t address, uint64_t address_length, @@ -456,8 +740,12 @@ static int udp_recv(struct task_file *file, void *data, uint32_t length, { struct udp_socket *s = udp_from_file(file); if (!s) return -LINUX_EBADF; + if (flags & ~(MSG_DONTWAIT | MSG_PEEK | MSG_TRUNC | MSG_WAITALL | MSG_ERRQUEUE)) + return -LINUX_EOPNOTSUPP; + if (flags & MSG_ERRQUEUE) + return udp_error_recv(s, data, length, flags, address, address_length, + source, source_length, info); if (s->error) { int error = s->error; s->error = 0; return -error; } - if (flags & ~(MSG_DONTWAIT | MSG_PEEK | MSG_TRUNC | MSG_WAITALL)) return -LINUX_EOPNOTSUPP; net_poll_packets(); if (!s->head) { if ((file->flags & RELIEFOS_O_NONBLOCK) || (flags & MSG_DONTWAIT)) return -LINUX_EAGAIN; @@ -489,11 +777,15 @@ static int udp_recv(struct task_file *file, void *data, uint32_t length, *source_length = s->ipv6 ? sizeof(source6) : sizeof(source4); __builtin_memcpy(source, s->ipv6 ? (const void *)&source6 : (const void *)&source4, *source_length); } + udp_timestamp(s, packet); if (info) *info = (struct net_udp_rx_info){.destination = packet->destination6, .ifindex = packet->ifindex, .hops = packet->hops, - .pktinfo = s->ipv6 && !packet->ipv4 && s->recv_pktinfo, - .hoplimit = s->ipv6 && !packet->ipv4 && s->recv_hoplimit, - .old_hoplimit = s->ipv6 && !packet->ipv4 && s->recv_old_hoplimit}; + .ipv4 = packet->ipv4, + .pktinfo = packet->ipv4 ? s->ipv4_pktinfo : s->recv_pktinfo, + .hoplimit = packet->ipv4 ? s->ipv4_recvttl : s->recv_hoplimit, + .old_hoplimit = s->ipv6 && !packet->ipv4 && s->recv_old_hoplimit, + .timestamp_option = packet->timestamp_valid ? s->timestamp_option : 0, + .timestamp = packet->timestamp}; uint32_t copied = length < packet->length ? length : packet->length; __builtin_memcpy(data, packet->data, copied); int ret = (flags & MSG_TRUNC) ? (int)packet->length : (int)copied; @@ -506,6 +798,166 @@ static int udp_recv(struct task_file *file, void *data, uint32_t length, return ret; } +/** @brief Import and atomically apply an IPv4 multicast interface or subscription. + * @param s Retained creating-network endpoint. @param option Linux IP option. + * @param pointer User request. @param length Request bytes. + * @return Zero, negative errno or user-memory retry marker. Failed input preserves state. */ +static int udp4_group_option(struct udp_socket *s, uint32_t option, + uint64_t pointer, uint32_t length) +{ + bool interface = option == IP_MULTICAST_IF; + struct ip_mreqn request = {0}; + uint32_t bytes = length >= sizeof(request) ? sizeof(request) : sizeof(struct ip_mreq); + if (interface && length < sizeof(struct ip_mreq)) bytes = sizeof(struct in_addr); + if (length < bytes) return -LINUX_EINVAL; + int result = socket_user_prepare(sched_current_task(), pointer, bytes, false); + if (result) return result; + if (!user_range_ok(pointer, bytes)) return -LINUX_EFAULT; + if (bytes == sizeof(struct in_addr)) + __builtin_memcpy(&request.imr_address, (void *)(uintptr_t)pointer, bytes); + else __builtin_memcpy(&request, (void *)(uintptr_t)pointer, bytes); + if (request.imr_ifindex < 0) return -LINUX_EINVAL; + uint32_t group = swap32(request.imr_multiaddr.s_addr); + uint32_t source = swap32(request.imr_address.s_addr); + uint32_t index = (uint32_t)request.imr_ifindex; + if (!interface && !udp4_multicast(group)) return -LINUX_EINVAL; + if (!index && source) { + index = net_interface_for_ipv4(s->net_ns, source); + if (!index) return -LINUX_EADDRNOTAVAIL; + } + if (index && !net_interface_exists(s->net_ns, index)) return -LINUX_ENODEV; + if (interface) { + s->ipv4_multicast_if = index; + s->ipv4_multicast_source = source; + return 0; + } + if (option == IP_ADD_MEMBERSHIP && !index) { + struct net_ipv4_path path; + result = net_ipv4_route_lookup(s->net_ns, group, source, 0, &path); + if (result < 0) return result; + index = path.ifindex; + } + unsigned free_slot = UDP6_GROUP_LIMIT; + for (unsigned i = 0; i < UDP6_GROUP_LIMIT; ++i) { + if (s->groups4[i].address == group && (!index || s->groups4[i].ifindex == index)) { + if (option == IP_ADD_MEMBERSHIP) return -LINUX_EADDRINUSE; + s->groups4[i].address = 0; + s->groups4[i].ifindex = 0; + return 0; + } + if (!s->groups4[i].address) free_slot = i; + } + if (option == IP_DROP_MEMBERSHIP) return -LINUX_EADDRNOTAVAIL; + if (free_slot == UDP6_GROUP_LIMIT) return -LINUX_ENOBUFS; + s->groups4[free_slot].address = group; + s->groups4[free_slot].ifindex = index; + return 0; +} + +/** @brief Read or change IPv4 datagram options through checked user storage. + * @param s Retained UDP endpoint under execution ownership. + * @param set Select setsockopt. @param option Linux IPv4 option number. + * @param pointer User option storage. @param length_or_pointer Length or socklen_t pointer. + * @return Zero, negative errno, or a user-memory retry marker. Failed input preserves state. + * IP_TOS keeps the low byte, accepts an empty input as zero and updates priority + * when its integer input differs from the stored TOS. Short TOS queries return + * one unsigned byte, while integer queries return the zero-extended TOS. + * IP_FREEBIND normalizes nonzero input to true and permits non-local IPv4 bind. + * Its short queries return one byte, and disabling it preserves an existing bind. + * IP_UNICAST_IF stores a network-order interface index from the creating network, + * affects output only, and requires exactly four input bytes. Zero clears it. + */ +static int udp4_option(struct udp_socket *s, bool set, uint32_t option, + uint64_t pointer, uint64_t length_or_pointer) +{ + uint32_t length = (uint32_t)length_or_pointer; + struct task *task = sched_current_task(); + if (!set) { + int result = socket_user_length(task, length_or_pointer, &length); + if (result) return result; + } + if ((int32_t)length < 0) return -LINUX_EINVAL; + if (set && (option == IP_ADD_MEMBERSHIP || option == IP_DROP_MEMBERSHIP || option == IP_MULTICAST_IF)) + return udp4_group_option(s, option, pointer, length); + int value = 0; + if (set) { + if (option == IP_UNICAST_IF && length != sizeof(value)) return -LINUX_EINVAL; + if (!length && option != IP_TOS) return -LINUX_EINVAL; + if (length) { + uint32_t bytes = length < sizeof(value) ? 1 : sizeof(value); + int result = socket_user_prepare(task, pointer, bytes, false); + if (result) return result; + if (!user_range_ok(pointer, bytes)) return -LINUX_EFAULT; + __builtin_memcpy(&value, (void *)(uintptr_t)pointer, bytes); + } + switch (option) { + case IP_TOS: + if (s->ipv4_tos != value) { + static const uint8_t priorities[4] = {0, 2, 6, 4}; + s->ipv4_tos = (uint8_t)value; + s->priority = priorities[((unsigned)value >> 3) & 3u]; + } + break; + case IP_UNICAST_IF: { + uint32_t index = swap32((uint32_t)value); + if (index && !net_interface_exists(s->net_ns, index)) return -LINUX_EADDRNOTAVAIL; + if (index && s->ifindex) return -LINUX_EINVAL; + s->ipv4_unicast_if = index; + break; + } + case IP_FREEBIND: s->ipv4_freebind = value != 0; break; + case IP_RECVERR: + s->ipv4_recverr = value != 0; + if (!value) udp_errors_clear(s); + break; + case IP_TTL: + if (value != -1 && (value < 1 || value > 255)) return -LINUX_EINVAL; + s->ipv4_ttl = value == -1 ? 64 : value; + break; + case IP_MULTICAST_TTL: + if (value < -1 || value > 255) return -LINUX_EINVAL; + s->ipv4_multicast_ttl = value == -1 ? 1 : value; + break; + case IP_MULTICAST_LOOP: s->ipv4_multicast_loop = value != 0; break; + case IP_MULTICAST_ALL: + if (value != 0 && value != 1) return -LINUX_EINVAL; + s->ipv4_multicast_all = value != 0; + break; + case IP_PKTINFO: s->ipv4_pktinfo = value != 0; break; + case IP_RECVTTL: s->ipv4_recvttl = value != 0; break; + case IP_MTU_DISCOVER: + if (value < IP_PMTUDISC_DONT || value > IP_PMTUDISC_OMIT) return -LINUX_EINVAL; + s->ipv4_mtu_discover = value; + break; + default: return -LINUX_ENOPROTOOPT; + } + return 0; + } + switch (option) { + case IP_TOS: value = s->ipv4_tos; break; + case IP_UNICAST_IF: value = (int)swap32(s->ipv4_unicast_if); break; + case IP_FREEBIND: value = s->ipv4_freebind; break; + case IP_RECVERR: value = s->ipv4_recverr; break; + case IP_TTL: value = s->ipv4_ttl; break; + case IP_MULTICAST_TTL: value = s->ipv4_multicast_ttl; break; + case IP_MULTICAST_LOOP: value = s->ipv4_multicast_loop; break; + case IP_MULTICAST_ALL: value = s->ipv4_multicast_all; break; + case IP_MULTICAST_IF: value = (int)swap32(s->ipv4_multicast_source); break; + case IP_PKTINFO: value = s->ipv4_pktinfo; break; + case IP_RECVTTL: value = s->ipv4_recvttl; break; + case IP_MTU_DISCOVER: value = s->ipv4_mtu_discover; break; + default: return -LINUX_ENOPROTOOPT; + } + if ((option == IP_TOS || option == IP_FREEBIND) && length && length < sizeof(value)) length = 1; + if (length > sizeof(value)) length = sizeof(value); + int result = socket_user_prepare(task, pointer, length, true); + if (result) return result; + if (length && !user_range_writable(pointer, length)) return -LINUX_EFAULT; + if (length) __builtin_memcpy((void *)(uintptr_t)pointer, &value, length); + *(uint32_t *)(uintptr_t)length_or_pointer = length; + return 0; +} + /** @brief Receive one datagram after validating any user source address. * @param file Pinned UDP OFD. @param data Validated output. @param length Capacity. * @param flags Receive flags. @param address Optional user sockaddr output. @@ -513,7 +965,10 @@ static int udp_recv(struct task_file *file, void *data, uint32_t length, * @return Bytes, negative errno, or blocked marker. */ int task_udp_recv(struct task_file *file, void *data, uint32_t length, uint32_t flags, uint64_t address, uint64_t address_length) -{ return udp_recv(file,data,length,flags,address,address_length,NULL,NULL,NULL); } +{ + if (flags & MSG_ERRQUEUE) flags &= ~MSG_PEEK; + return udp_recv(file,data,length,flags,address,address_length,NULL,NULL,NULL); +} /** @brief Return the native UDP source address size. * @param file Pinned UDP OFD. @return Size or zero for an invalid description. */ @@ -526,11 +981,16 @@ uint32_t task_udp_address_size(const struct task_file *file) /** @brief Receive a datagram into owned storage together with source and metadata. * @param file Pinned UDP OFD. @param data Kernel destination. @param length Capacity. * @param flags Receive flags. @param source Optional sockaddr storage. - * @param source_length Optional source-size output. @param info Optional metadata output. - * @return Bytes, errno, or blocked sentinel; PEEK preserves the queue entry. */ + * @param source_length Optional source-size output. @param info Optional ingress + * metadata and retained realtime timestamp output. + * @return Bytes, errno, or blocked sentinel. Ordinary PEEK retains the packet and + * timestamp. MSG_ERRQUEUE consumes one error even with external MSG_PEEK. */ int task_udp_recv_ex(struct task_file *file, void *data, uint32_t length, uint32_t flags, void *source, uint32_t *source_length, struct net_udp_rx_info *info) -{ return udp_recv(file,data,length,flags,0,0,source,source_length,info); } +{ + if (flags & MSG_ERRQUEUE) flags &= ~MSG_PEEK; + return udp_recv(file,data,length,flags,0,0,source,source_length,info); +} #ifdef CONFIG_SWAP /** @brief Receive one datagram into owned kernel payload and source buffers. @@ -554,7 +1014,8 @@ short task_udp_poll(struct task_file *file, short events) struct udp_socket *s = udp_from_file(file); if (!s) return POLLNVAL; net_poll_packets(); - return (events & POLLOUT) | (s->head ? (events & POLLIN) : 0) | (s->error ? POLLERR : 0); + return (events & POLLOUT) | (s->head ? (events & POLLIN) : 0) | + (s->error || s->errors_head ? POLLERR : 0); } int task_udp_available(struct task_file *file) @@ -582,6 +1043,7 @@ void task_udp_release(struct task_file *file) s->head = p->next; kernel_free(p); } + udp_errors_clear(s); net_namespace_put(s->net_ns); kernel_free(s); file->aux = 0; @@ -590,7 +1052,9 @@ void task_udp_release(struct task_file *file) /** @brief Read or change implemented IPv6 datagram options using checked user storage. * @param s UDP endpoint. @param set True for setsockopt. @param option IPv6 option number. * @param pointer User value. @param length_or_pointer Input length or user socklen_t. - * @return Zero or a negative Linux errno. */ + * @return Zero or a negative Linux errno. IPV6_UNICAST_IF uses a network-order + * interface index and requires exactly four input bytes. Its creating-network + * output selection leaves receive filtering intact. Zero clears it. */ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, uint64_t pointer, uint64_t length_or_pointer) { @@ -626,17 +1090,29 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, } int value = 0; if (set) { - if (length < sizeof(value)) return -LINUX_EINVAL; + if (length < sizeof(value) || + (option == IPV6_UNICAST_IF && length != sizeof(value))) return -LINUX_EINVAL; int ret = socket_user_prepare(task, pointer, sizeof(value), false); if (ret) return ret; if (!user_range_ok(pointer, sizeof(value))) return -LINUX_EFAULT; __builtin_memcpy(&value, (void *)(uintptr_t)pointer, sizeof(value)); switch (option) { + case IPV6_UNICAST_IF: { + uint32_t index = swap32((uint32_t)value); + if (index && !net_interface_exists(s->net_ns, index)) return -LINUX_EADDRNOTAVAIL; + if (index && s->ifindex) return -LINUX_EINVAL; + s->ipv6_unicast_if = index; + break; + } case IPV6_V6ONLY: if (s->bound) return -LINUX_EINVAL; s->v6only = value != 0; break; case IPV6_UNICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->unicast_hops = value; break; case IPV6_MULTICAST_HOPS: if (value < -1 || value > 255) return -LINUX_EINVAL; s->multicast_hops = value; break; case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists(s->net_ns, (uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; case IPV6_MULTICAST_LOOP: if (value != 0 && value != 1) return -LINUX_EINVAL; s->multicast_loop = value != 0; break; case IPV6_RECVPKTINFO: s->recv_pktinfo = value != 0; break; + case IPV6_RECVERR: + s->ipv6_recverr = value != 0; + if (!value) udp_errors_clear(s); + break; case IPV6_RECVHOPLIMIT: s->recv_hoplimit = value != 0; break; case IPV6_2292HOPLIMIT: s->recv_old_hoplimit = value != 0; break; case IPV6_DONTFRAG: s->dont_fragment = value != 0; break; @@ -649,12 +1125,14 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, return 0; } switch (option) { + case IPV6_UNICAST_IF: value = (int)swap32(s->ipv6_unicast_if); break; case IPV6_V6ONLY: value = s->v6only; break; case IPV6_UNICAST_HOPS: value = s->unicast_hops; break; case IPV6_MULTICAST_HOPS: value = s->multicast_hops; break; case IPV6_MULTICAST_IF: value = (int)s->multicast_if; break; case IPV6_MULTICAST_LOOP: value = s->multicast_loop; break; case IPV6_RECVPKTINFO: value = s->recv_pktinfo; break; + case IPV6_RECVERR: value = s->ipv6_recverr; break; case IPV6_RECVHOPLIMIT: value = s->recv_hoplimit; break; case IPV6_2292HOPLIMIT: value = s->recv_old_hoplimit; break; case IPV6_DONTFRAG: value = s->dont_fragment; break; @@ -662,7 +1140,8 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, case IPV6_MTU: { struct net_ipv6_path path; if (!s->connected || udp6_mapped(&s->remote6)) return -LINUX_ENOTCONN; - int ret = net_ipv6_route(s->net_ns, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path); + int ret = net_ipv6_route(s->net_ns, &s->remote6, s->remote_scope6 ? s->remote_scope6 : + s->ifindex ? (uint32_t)s->ifindex : s->ipv6_unicast_if, &s->local6, &path); if (ret < 0) return ret; value = (int)path.mtu; break; @@ -687,6 +1166,9 @@ static int udp6_option(struct udp_socket *s, bool set, uint32_t option, * @param a4 Fifth syscall argument. * @param a5 Sixth syscall argument. * @return Syscall result or negative errno. + * SO_PRIORITY accepts 0 through 6 without privileges. Other signed values + * require CAP_NET_RAW or CAP_NET_ADMIN in the socket's creating network owner. + * SO_TIMESTAMP_OLD/NEW select mutually exclusive timeval control-message formats. */ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5) @@ -705,7 +1187,10 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, *s = (struct udp_socket){.net_ns = net_namespace_get(task->net_ns), .uid = task->euid, .ino = (3ULL << 60) | ++proc_udp_ino, .ipv6 = (int)a0 == AF_INET6, .unicast_hops = -1, .multicast_hops = 1, - .mtu_discover = IPV6_PMTUDISC_WANT, .multicast_loop = true}; + .mtu_discover = IPV6_PMTUDISC_WANT, .multicast_loop = true, + .ipv4_ttl = 64, .ipv4_multicast_ttl = 1, + .ipv4_mtu_discover = IP_PMTUDISC_WANT, .ipv4_multicast_loop = true, + .ipv4_multicast_all = true}; if (!sockets) sockets = s; else { struct udp_socket *tail = sockets; @@ -772,11 +1257,14 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, if (udp6_mapped(&s->remote6)) { struct net_ipv4_path path; if (!net_ipv4_route_lookup(s->net_ns, s->remote, s->local, - (uint32_t)s->ifindex, &path)) + s->ifindex ? (uint32_t)s->ifindex : s->ipv4_unicast_if, &path)) address.sin6_addr = udp6_map(path.source); } else { struct net_ipv6_path path; - if (!net_ipv6_route(s->net_ns, &s->remote6, s->remote_scope6 ? s->remote_scope6 : (uint32_t)s->ifindex, &s->local6, &path)) address.sin6_addr = path.source; + uint32_t scope = s->remote_scope6 ? s->remote_scope6 : + s->ifindex ? (uint32_t)s->ifindex : s->ipv6_unicast_if; + if (!net_ipv6_route(s->net_ns, &s->remote6, scope, &s->local6, &path)) + address.sin6_addr = path.source; } } return udp6_export(a1, a2, &address); @@ -784,13 +1272,16 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, uint32_t local = s->local; if (!local && s->connected) { struct net_ipv4_path path; - if (!net_ipv4_route_lookup(s->net_ns, s->remote, 0, (uint32_t)s->ifindex, &path)) + if (!net_ipv4_route_lookup(s->net_ns, s->remote, 0, + s->ifindex ? (uint32_t)s->ifindex : s->ipv4_unicast_if, &path)) local = path.source; } return export_address(a1, a2, number == __NR_getsockname ? local : s->remote, number == __NR_getsockname ? s->port : s->remote_port); } if (number == __NR_setsockopt || number == __NR_getsockopt) { + if (a1 == SOL_IP) + return udp4_option(s, number == __NR_setsockopt, (uint32_t)a2, a3, a4); if (s->ipv6 && a1 == SOL_IPV6) return udp6_option(s, number == __NR_setsockopt, (uint32_t)a2, a3, a4); if (a1 != SOL_SOCKET) return -LINUX_ENOPROTOOPT; @@ -801,9 +1292,9 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, int prep=socket_user_length(task,a4,&length);if(prep)return prep; } if ((int32_t)length < 0) return -LINUX_EINVAL; - if (a2 == SO_BINDTODEVICE) { + if (a2 == SO_BINDTODEVICE || a2 == SO_BINDTOIFINDEX) { uint32_t index = (uint32_t)s->ifindex; - int result = net_interface_device_option(s->net_ns, set, a3, a4, &index); + int result = net_interface_device_option(s->net_ns, set, (uint32_t)a2, a3, a4, &index); if (!result && set) s->ifindex = (int)index; return result; } @@ -845,6 +1336,15 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, value = *(int *)(uintptr_t)a3; if (a2 == SO_REUSEADDR) s->reuse = value != 0; else if (a2 == UDP_SO_BROADCAST) s->broadcast = value != 0; + else if (a2 == SO_TIMESTAMP_OLD || a2 == SO_TIMESTAMP_NEW) + s->timestamp_option = value ? (uint32_t)a2 : 0; + else if (a2 == SO_PRIORITY) { + struct user_namespace *owner = s->net_ns ? s->net_ns->user_ns : NULL; + if ((value < 0 || value > 6) && + !task_ns_capable(task, owner, CAP_NET_RAW) && + !task_ns_capable(task, owner, CAP_NET_ADMIN)) return -LINUX_EPERM; + s->priority = value; + } else return -LINUX_ENOPROTOOPT; return 0; } @@ -854,11 +1354,14 @@ int64_t syscall_udp(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2, else if (a2 == SO_ERROR) value = s->error; else if (a2 == SO_REUSEADDR) value = s->reuse; else if (a2 == UDP_SO_BROADCAST) value = s->broadcast; + else if (a2 == SO_PRIORITY) value = s->priority; + else if (a2 == SO_TIMESTAMP_OLD || a2 == SO_TIMESTAMP_NEW) + value = s->timestamp_option == a2; else return -LINUX_ENOPROTOOPT; if (length > 4) length = 4; int prep=socket_user_prepare(task,a3,length,true);if(prep)return prep; if (length && !user_range_writable(a3, length)) return -LINUX_EFAULT; - __builtin_memcpy((void *)(uintptr_t)a3, &value, length); + if (length) __builtin_memcpy((void *)(uintptr_t)a3, &value, length); *(uint32_t *)(uintptr_t)a4 = length; if (a2 == SO_ERROR) s->error = 0; return 0; diff --git a/net/tcp/output.c b/net/tcp/output.c index 4a0528dd..d4d9c85f 100644 --- a/net/tcp/output.c +++ b/net/tcp/output.c @@ -84,6 +84,8 @@ uint32_t net_socket_select_window(const struct net_socket *socket) * @param flags TCP control flags. * @param payload Segment payload, or null for no payload. * @param payload_len Payload byte count. + * @param ttl IPv4 time to live. + * @param dont_fragment Set the IPv4 DF flag. * @return Driver result, or a negative error when the frame cannot be sent. * @note The receiver window is read from the matching stable socket under the * network execution transaction, then published only after successful transmit. @@ -93,7 +95,7 @@ static int net_send_tcp_to_mac_on(struct net_namespace *ns, uint32_t ifindex, co uint16_t dst_port, uint32_t seq, uint32_t ack, uint8_t flags, const uint8_t *payload, - uint32_t payload_len) + uint32_t payload_len, uint8_t ttl, bool dont_fragment) { uint8_t frame[NET_FRAME_MAX]; uint8_t *ip = frame + 14; @@ -117,8 +119,8 @@ static int net_send_tcp_to_mac_on(struct net_namespace *ns, uint32_t ifindex, co ip[1] = 0; net_put_u16(ip + 2, total_len); net_put_u16(ip + 4, net_ipv4_id++); - net_put_u16(ip + 6, 0); - ip[8] = 64; + net_put_u16(ip + 6, dont_fragment ? 0x4000 : 0); + ip[8] = ttl; ip[9] = IPV4_PROTO_TCP; net_put_u32(ip + 12, src_ip); net_put_u32(ip + 16, dst_ip); @@ -212,7 +214,9 @@ int net_send_tcp_socket(struct net_socket *socket, uint32_t seq, uint32_t ack, socket->next_hop = path.next_hop; return net_send_tcp_to_mac_on(socket->net_ns, path.ifindex, socket->dst_mac, socket->local_ip, socket->remote_ip, socket->local_port, socket->remote_port, - seq, ack, flags, payload, length); + seq, ack, flags, payload, length, (uint8_t)socket->ipv4_ttl, + socket->ipv4_mtu_discover == IP_PMTUDISC_DO || + socket->ipv4_mtu_discover == IP_PMTUDISC_PROBE); } if (socket->remote_scope6 && socket->bound_ifindex && socket->remote_scope6 != socket->bound_ifindex) return -LINUX_EINVAL; @@ -259,5 +263,5 @@ int net_send_tcp_to_mac(const uint8_t *mac, uint32_t source, uint32_t destinatio int result = net_ipv4_route_lookup(NULL, destination, source, 0, &path); if (result < 0) return result; return net_send_tcp_to_mac_on(NULL, path.ifindex, mac, source, destination, source_port, - destination_port, seq, ack, flags, data, length); + destination_port, seq, ack, flags, data, length, 64, false); } diff --git a/net/tcp/socket.c b/net/tcp/socket.c index 3e5b218d..54421ab0 100644 --- a/net/tcp/socket.c +++ b/net/tcp/socket.c @@ -331,6 +331,8 @@ static struct net_socket *net_socket_alloc(struct net_namespace *ns, uint32_t ow slot->tx_rto_ms = NET_TCP_INITIAL_RTO_MS; slot->unicast_hops = -1; slot->mtu_discover = IPV6_PMTUDISC_WANT; + slot->ipv4_ttl = 64; + slot->ipv4_mtu_discover = IP_PMTUDISC_WANT; slot->created_ms = net_now32(); slot->changed_ms = slot->created_ms; if (!net_sockets) net_sockets = slot; @@ -1312,7 +1314,7 @@ void net_socket_release_fd(int32_t handle) struct reliefos_net_socket_close request = {.socket = handle}; (void)net_socket_close(&request, 0); s->fd_owned = false; - if (!s->bound && s->state == RELIEFOS_NET_TCP_CLOSED) net_socket_clear(s); + if (s->state == RELIEFOS_NET_TCP_CLOSED && (!s->bound || !s->remote_port)) net_socket_clear(s); } /** @copydoc net_socket_namespace */ @@ -1582,6 +1584,40 @@ void net_tcp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) } } +/** @copydoc net_socket_ipv4_option */ +int net_socket_ipv4_option(int32_t handle, bool set, uint32_t option, int *value) +{ + struct net_socket *socket = net_socket_find(handle, 0, 1); + if (!socket || !value) return -LINUX_EBADF; + if (set) { + switch (option) { + case IP_TTL: + if (*value != -1 && (*value < 1 || *value > 255)) return -LINUX_EINVAL; + socket->ipv4_ttl = *value == -1 ? 64 : *value; + return 0; + case IP_PKTINFO: + socket->ipv4_pktinfo = *value != 0; + return 0; + case IP_RECVTTL: + socket->ipv4_recvttl = *value != 0; + return 0; + case IP_MTU_DISCOVER: + if (*value < IP_PMTUDISC_DONT || *value > IP_PMTUDISC_OMIT) return -LINUX_EINVAL; + socket->ipv4_mtu_discover = *value; + return 0; + default: + return -LINUX_ENOPROTOOPT; + } + } + switch (option) { + case IP_TTL: *value = socket->ipv4_ttl; return 0; + case IP_PKTINFO: *value = socket->ipv4_pktinfo; return 0; + case IP_RECVTTL: *value = socket->ipv4_recvttl; return 0; + case IP_MTU_DISCOVER: *value = socket->ipv4_mtu_discover; return 0; + default: return -LINUX_ENOPROTOOPT; + } +} + /** @brief Read or update implemented IPv6 stream options. * @param handle Socket handle. @param set Select setter. @param option Native option. * @param value Kernel integer input/output. @return Zero or negative errno. */ @@ -1594,6 +1630,8 @@ int net_socket_ipv6_option(int32_t handle, bool set, uint32_t option, int *value switch (option) { case IPV6_V6ONLY: if (s->bound) return -LINUX_EINVAL; s->v6only = *value != 0; return 0; case IPV6_UNICAST_HOPS: if (*value < -1 || *value > 255) return -LINUX_EINVAL; s->unicast_hops = *value; return 0; + case IPV6_RECVPKTINFO: s->recv_pktinfo = *value != 0; return 0; + case IPV6_RECVHOPLIMIT: s->recv_hoplimit = *value != 0; return 0; case IPV6_DONTFRAG: s->dont_fragment = *value != 0; return 0; case IPV6_MTU_DISCOVER: if (*value != IPV6_PMTUDISC_DONT && *value != IPV6_PMTUDISC_WANT && *value != IPV6_PMTUDISC_DO) return -LINUX_EINVAL; @@ -1604,6 +1642,8 @@ int net_socket_ipv6_option(int32_t handle, bool set, uint32_t option, int *value switch (option) { case IPV6_V6ONLY: *value = s->v6only; return 0; case IPV6_UNICAST_HOPS: *value = s->unicast_hops; return 0; + case IPV6_RECVPKTINFO: *value = s->recv_pktinfo; return 0; + case IPV6_RECVHOPLIMIT: *value = s->recv_hoplimit; return 0; case IPV6_DONTFRAG: *value = s->dont_fragment; return 0; case IPV6_MTU_DISCOVER: *value = s->mtu_discover; return 0; case IPV6_MTU: if (!s->remote_port || s->mapped) return -LINUX_ENOTCONN; *value = (int)s->mtu6; return 0; @@ -1650,6 +1690,12 @@ struct net_socket *net_tcp_passive6(struct net_socket *listener,const struct in6 s->ifindex = ifindex; s->bound_ifindex = listener->bound_ifindex; s->ipv6 = true; s->v6only = listener->v6only; s->bound = true; s->listener = listener; s->nodelay = listener->nodelay; + s->ipv4_ttl = listener->ipv4_ttl; + s->ipv4_mtu_discover = listener->ipv4_mtu_discover; + s->ipv4_pktinfo = listener->ipv4_pktinfo; + s->ipv4_recvttl = listener->ipv4_recvttl; + s->recv_pktinfo = listener->recv_pktinfo; + s->recv_hoplimit = listener->recv_hoplimit; s->local6 = *destination; s->remote6 = *source; s->remote_scope6 = scope; s->mtu6 = path.mtu; s->local_port = listener->local_port; s->remote_port = source_port; s->peer_mss = mss; s->remote_seq = seq + 1; s->peer_window = window; s->peer_window_seq = seq; s->peer_window_valid = true; @@ -1681,6 +1727,12 @@ struct net_socket *net_tcp_passive4_on(uint32_t ifindex, struct net_socket *list s->ifindex = ifindex; s->bound_ifindex = listener->bound_ifindex; s->ipv6 = listener->ipv6; s->mapped = listener->ipv6; s->v6only = listener->v6only; s->nodelay = listener->nodelay; + s->ipv4_ttl = listener->ipv4_ttl; + s->ipv4_mtu_discover = listener->ipv4_mtu_discover; + s->ipv4_pktinfo = listener->ipv4_pktinfo; + s->ipv4_recvttl = listener->ipv4_recvttl; + s->recv_pktinfo = listener->recv_pktinfo; + s->recv_hoplimit = listener->recv_hoplimit; s->next_hop = source; s->bound = true; s->listener = listener; s->local_ip = destination; s->remote_ip = source; s->local6 = tcp6_map(destination); s->remote6 = tcp6_map(source); @@ -1915,14 +1967,15 @@ void net_tcp6_error(const struct in6_addr *source, const struct in6_addr *destin } /** @brief Read or change a stream endpoint's bound output device. * @param handle Socket handle. @param set Select update. @param index Input/output index. - * @return Zero or negative errno. Caller authorizes and validates user memory. */ + * @return Zero or negative errno. Numeric bindings may name absent devices. + * Caller authorizes, resolves named devices and validates user memory. */ int net_socket_bound_device(int32_t handle, bool set, uint32_t *index) { struct net_socket *socket = net_socket_find(handle, 0, 1); if (!socket) return -LINUX_EBADF; if (!index) return -LINUX_EINVAL; if (set) { - if (*index && !net_interface_exists(socket->net_ns, *index)) return -LINUX_ENODEV; + if (*index > INT32_MAX) return -LINUX_EINVAL; socket->bound_ifindex = *index; } else *index = socket->bound_ifindex; return 0; diff --git a/tools/test_ipv6_control.py b/tools/test_ipv6_control.py index 7b19a467..02c8f5cb 100644 --- a/tools/test_ipv6_control.py +++ b/tools/test_ipv6_control.py @@ -13,6 +13,6 @@ "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", "tools/tests/ipv6_control_test.c", "net/socket/filter.c", - "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/sched/user_namespace.c", + "net/namespace/namespace.c", "net/interface/nexthop.c", "net/ipv6/state.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) diff --git a/tools/test_ipv6_protocol.py b/tools/test_ipv6_protocol.py index d7c395f3..2de46362 100644 --- a/tools/test_ipv6_protocol.py +++ b/tools/test_ipv6_protocol.py @@ -14,7 +14,8 @@ str(root / "tools/tests/ipv6_protocol_test.c")] if source.exists(): cmd += [str(source), str(root / "net/link/ethernet.c"), str(root / "net/input.c"), - str(root / "net/namespace/namespace.c"), str(root / "net/ipv6/state.c")] + str(root / "net/namespace/namespace.c"), str(root / "net/ipv6/state.c"), + str(root / "net/interface/nexthop.c")] else: cmd += ["-DIPV6_NO_IMPLEMENTATION"] cmd += ["-o", str(output / "ipv6_protocol_test")] diff --git a/tools/test_ipv6_transport.py b/tools/test_ipv6_transport.py index f3b6f5da..2dacc361 100644 --- a/tools/test_ipv6_transport.py +++ b/tools/test_ipv6_transport.py @@ -12,7 +12,7 @@ "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", "tools/tests/ipv6_transport_test.c", "net/proc.c", "net/namespace/namespace.c", - "net/ipv6/state.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=root, check=True) + "net/ipv6/state.c", "net/socket/filter.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) binary = out / "ipv6_vector_test" subprocess.run(["clang", "-std=c11", "-g", "-O1", "-DCONFIG_SWAP", @@ -31,6 +31,6 @@ "-Wl,--gc-sections", "-fno-pie", "-no-pie", "-Iinclude", "-Iinclude/uapi", "tools/tests/ipv6_tcp_test.c", "net/tcp/input.c", "net/tcp/output.c", "net/tcp/socket.c", "net/utility.c", "net/proc.c", "net/socket/packet.c", - "net/namespace/namespace.c", + "net/namespace/namespace.c", "net/socket/filter.c", "net/ipv6/state.c", "kernel/sched/user_namespace.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) diff --git a/tools/test_linux_inventory.py b/tools/test_linux_inventory.py index 48c73d95..30dbc0a3 100644 --- a/tools/test_linux_inventory.py +++ b/tools/test_linux_inventory.py @@ -2,8 +2,9 @@ """Run kernel CPU, SMBIOS, sysfs and procfs inventory parsers on the host.""" from pathlib import Path import subprocess +import os ROOT = Path(__file__).resolve().parents[1] -WORK = ROOT / "out/linux-inventory" +WORK = Path(os.environ.get("RELIEFNT_TEST_OUT", ROOT / "out/linux-inventory")) def run(command, **kwargs): return subprocess.run([str(x) for x in command], cwd=ROOT, check=True, **kwargs) def host(): @@ -12,7 +13,7 @@ def host(): '-Iinclude','-Iinclude','-Iinclude/uapi', '-Iinclude','tools/tests/linux_inventory_test.c','fs/vfs/mount_tree.c', 'fs/vfs/lookup_cache.c', 'fs/vfs/path.c','fs/vfs/mount_table.c','fs/vfs/file.c','fs/vfs/open.c','fs/vfs/pseudo.c', 'fs/vfs/attributes.c','fs/proc/mount.c','fs/nsfs/namespace.c','fs/proc/views.c','kernel/syscall/fd/proc.c','fs/vfs/exec_file.c', - 'fs/sysfs/mount.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','kernel/sched/user_namespace.c','kernel/init/uts.c','net/namespace/namespace.c','net/ipv6/state.c','fs/security/access.c','-o',executable]) + 'fs/sysfs/mount.c','fs/sysfs/network.c','fs/sysfs/uevent.c','net/interface/state.c','fs/sysfs/parameters.c','kernel/params/value.c','kernel/params/arguments.c','kernel/params/builtin.c','kernel/params/registry.c','kernel/sched/identity.c','kernel/sched/user_namespace.c','kernel/init/uts.c','net/namespace/namespace.c','net/ipv6/state.c','fs/security/access.c','-o',executable]) run([executable]) if __name__ == "__main__": diff --git a/tools/test_net_multinic_data.py b/tools/test_net_multinic_data.py index a538fb41..020d422f 100644 --- a/tools/test_net_multinic_data.py +++ b/tools/test_net_multinic_data.py @@ -18,7 +18,7 @@ def main(): "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude/uapi", f"tools/tests/{name}_test.c", - *(["net/namespace/namespace.c", "net/ipv6/state.c", + *(["net/socket/filter.c", "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/sched/user_namespace.c"] if name == "net_packet" else []), "-o", str(binary)], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=15) diff --git a/tools/test_openrc_network.py b/tools/test_openrc_network.py index bdd64ef0..8c0d7e7a 100644 --- a/tools/test_openrc_network.py +++ b/tools/test_openrc_network.py @@ -14,7 +14,7 @@ def main(): "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", f"tools/tests/{name}_test.c", - *(["net/namespace/namespace.c", "net/ipv6/state.c", + *(["net/socket/filter.c", "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/sched/user_namespace.c"] if name == "net_packet" else []), *(["kernel/time/time_discipline.c"] if name == "timekeeper_discipline" else []), "-o", str(binary)], cwd=ROOT, check=True) diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 8df1edd2..8e0f8696 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -4,6 +4,8 @@ #include #include #include +#include +#include #include #if __has_include("../../net/socket/netlink.c") #include "../../net/socket/netlink.c" @@ -20,6 +22,7 @@ static int allocation_fail_after = -1; static bool additional_address; static bool nic_ready=true; static bool nic_present=true; +static bool neighbor_entries; /* Enabled only by the scoped control regression. */ static struct { struct net_namespace *ns; @@ -40,7 +43,8 @@ void *kernel_malloc(size_t bytes) } void kernel_free(void *p) { if (p) { assert(allocations); --allocations; free(p); } } uint64_t time_ticks(void) { return 100; } -uint64_t time_uptime_ms(void) { return 1000; } +static uint64_t uptime_ms = 1000; +uint64_t time_uptime_ms(void) { return uptime_ms; } void sched_sleep_current_until(uint64_t tick) { (void)tick; } void kernel_poll_readiness_notify(void) {} bool user_range_ok(uint64_t address, uint64_t size) { (void)size; return address > 4096; } @@ -71,6 +75,25 @@ uint32_t net_get_u32(const uint8_t *p) { return ((uint32_t)p[0]<<24)|((uint32_t) void net_put_u32(uint8_t *p,uint32_t value) { p[0]=value>>24;p[1]=value>>16;p[2]=value>>8;p[3]=value; } void net_arp_cache_clear(void) {} void net_arp_cache_clear_on(uint32_t index) { (void)index; } +/** @brief Supply copied IPv4 neighbor data for the scoped dump fixture. */ +uint32_t net_ipv4_neighbors(struct net_namespace *ns, struct net_ipv4_neighbor *out, + uint32_t capacity) +{ + if (ns || !neighbor_entries) return 0; + if (out && capacity) *out = (struct net_ipv4_neighbor){ + .address = 0x0a000202, .ifindex = 2, .mac = {2,3,4,5,6,7}}; + return 1; +} +/** @brief Supply copied IPv6 neighbor data for the scoped dump fixture. */ +uint32_t net_ipv6_neighbors(struct net_namespace *ns, struct net_ipv6_neighbor *out, + uint32_t capacity) +{ + if (ns || !neighbor_entries) return 0; + if (out && capacity) *out = (struct net_ipv6_neighbor){ + .address.s6_addr = {0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,2}, + .ifindex = 2, .state = NUD_STALE, .mac = {2,3,4,5,6,7}}; + return 1; +} void net_ipv6_link_changed(bool up) { (void)up; ++link_changes; } int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index,bool up) { (void)ns; (void)index; (void)up; ++link_changes; return 0; } void net_device_counters(struct net_proc_counters *out) { memset(out,0,sizeof(*out)); } @@ -148,6 +171,21 @@ int net_ipv6_route_update(struct net_namespace *ns, const struct net_ipv6_route return 0; } +/** @brief Model IPv6 route-table mutation below the real scoped nexthop and socket entry. */ +void net_ipv6_nexthop_changed(struct net_namespace *ns, uint32_t id, + const struct net_nexthop *next) +{ + for (unsigned i=0;i<2;++i) { + if (scoped_ipv6[i].ns!=ns || !scoped_ipv6[i].has_route || + scoped_ipv6[i].route.nexthop_id!=id) continue; + if (!next) scoped_ipv6[i].has_route=false; + else { + scoped_ipv6[i].route.gateway=next->gateway.ipv6; + scoped_ipv6[i].route.ifindex=next->ifindex; + } + } +} + static long call(uint64_t nr, uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { return syscall_netlink(nr,a,b,c,d,e,0); } static int send_req(int fd, const void *message, unsigned length) @@ -257,6 +295,118 @@ static void check_netlink_datagram_tail(int fd) puts("PASS netlink datagram valid prefix, padded reserve, ignored invalid tail and final alignment"); } +/** @brief Complete the bridge-specific device dump with an empty table. */ +static void check_bridge_dump(int fd) +{ + struct { struct nlmsghdr header; struct ifinfomsg link; } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_GETLINK, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP | NLM_F_ACK, .nlmsg_seq = 95}, + .link = {.ifi_family = AF_BRIDGE}}; + unsigned char output[256]; + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + assert(receive(fd, output, sizeof(output)) == NLMSG_LENGTH(sizeof(int))); + const struct nlmsghdr *reply = (const void *)output; + assert(reply->nlmsg_type == NLMSG_DONE && reply->nlmsg_seq == 95); + assert(reply->nlmsg_flags == NLM_F_MULTI && *(const int *)(reply + 1) == 0); + assert(receive(fd, output, sizeof(output)) == -LINUX_EAGAIN); + puts("PASS bridge-specific link dump completes an empty bridge table"); +} + +/** @brief Check real neighbor snapshots, family filters and creating-network scope. */ +static void check_neighbor_dumps(int fd) +{ + struct { struct nlmsghdr header; struct ndmsg neighbor; } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_GETNEIGH, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP | NLM_F_ACK, .nlmsg_seq = 96}}; + unsigned char output[8192]; + neighbor_entries = true; + const uint8_t families[] = {AF_UNSPEC, AF_INET, AF_INET6, AF_BRIDGE}; + for (unsigned i = 0; i < sizeof(families); ++i) { + request.neighbor.ndm_family = families[i]; + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + if (families[i] == AF_BRIDGE) { + assert(receive(fd, output, sizeof(output)) == NLMSG_LENGTH(sizeof(int))); + assert(((struct nlmsghdr *)output)->nlmsg_type == NLMSG_DONE); + continue; + } + int bytes = receive_dump(fd, output, sizeof(output)); + assert(bytes > 0); + unsigned count = 0; + for (unsigned offset = 0; offset < (unsigned)bytes;) { + const struct nlmsghdr *header = (const void *)(output + offset); + assert(header->nlmsg_type == RTM_NEWNEIGH && header->nlmsg_seq == 96); + assert(header->nlmsg_flags == NLM_F_MULTI); + const struct ndmsg *neighbor = (const void *)(header + 1); + assert(neighbor->ndm_ifindex == 2 && neighbor->ndm_type == RTN_UNICAST); + assert(!neighbor->ndm_flags && !neighbor->ndm_pad1 && !neighbor->ndm_pad2); + assert(neighbor->ndm_family == (count || families[i] == AF_INET6 ? AF_INET6 : AF_INET)); + assert(neighbor->ndm_state == NUD_STALE); + unsigned attrs = offset + NLMSG_HDRLEN + sizeof(*neighbor); + const struct rtattr *destination = (const void *)(output + attrs); + assert(destination->rta_type == NDA_DST); + if (neighbor->ndm_family == AF_INET) { + const uint8_t address[] = {10,0,2,2}; + assert(destination->rta_len == RTA_LENGTH(4)); + assert(!memcmp(destination + 1, address, sizeof(address))); + } else { + const uint8_t address[16] = {0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,2}; + assert(destination->rta_len == RTA_LENGTH(16)); + assert(!memcmp(destination + 1, address, sizeof(address))); + } + attrs += RTA_ALIGN(destination->rta_len); + const struct rtattr *mac = (const void *)(output + attrs); + const uint8_t expected_mac[] = {2,3,4,5,6,7}; + assert(mac->rta_type == NDA_LLADDR && mac->rta_len == RTA_LENGTH(6)); + assert(!memcmp(mac + 1, expected_mac, sizeof(expected_mac))); + assert(attrs + RTA_ALIGN(mac->rta_len) == offset + header->nlmsg_len); + offset += NLMSG_ALIGN(header->nlmsg_len); + ++count; + } + assert(count == (families[i] == AF_UNSPEC ? 2u : 1u)); + assert(receive(fd, output, sizeof(output)) == -LINUX_EAGAIN); + } + request.neighbor.ndm_family = AF_UNSPEC; + request.neighbor.ndm_ifindex = 77; + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + assert(receive(fd, output, sizeof(output)) == NLMSG_LENGTH(sizeof(int))); + assert(((struct nlmsghdr *)output)->nlmsg_type == NLMSG_DONE); + request.neighbor.ndm_ifindex = 0; + request.neighbor.ndm_flags = NTF_PROXY; + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + assert(receive(fd, output, sizeof(output)) == NLMSG_LENGTH(sizeof(int))); + assert(((struct nlmsghdr *)output)->nlmsg_type == NLMSG_DONE); + request.neighbor.ndm_flags = 0; + struct net_namespace *scope; + assert(!net_namespace_create(NULL, &scope)); + current.net_ns = scope; + int isolated = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_ROUTE, 0, 0); + assert(isolated >= 0); + current.net_ns = NULL; + assert(send_req(isolated, &request, sizeof(request)) == sizeof(request)); + assert(receive(isolated, output, sizeof(output)) == NLMSG_LENGTH(sizeof(int))); + assert(((struct nlmsghdr *)output)->nlmsg_type == NLMSG_DONE); + task_netlink_release(&files[isolated]); files[isolated] = (struct task_file){0}; + net_namespace_put(scope); + neighbor_entries = false; + puts("PASS neighbor dump snapshots, byte order, family/interface/proxy filters and creating scope"); +} + +/** @brief Complete the empty standalone nexthop table independently of inline routes. */ +static void check_nexthop_dump(int fd) +{ + struct { struct nlmsghdr header; struct nhmsg nexthop; } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_GETNEXTHOP, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP | NLM_F_ACK, .nlmsg_seq = 97}}; + unsigned char output[256]; + assert(send_req(fd, &request, sizeof(request)) == sizeof(request)); + assert(receive(fd, output, sizeof(output)) == NLMSG_LENGTH(sizeof(int))); + const struct nlmsghdr *reply = (const void *)output; + assert(reply->nlmsg_type == NLMSG_DONE && reply->nlmsg_seq == 97); + assert(reply->nlmsg_flags == NLM_F_MULTI && *(const int *)(reply + 1) == 0); + assert(receive(fd, output, sizeof(output)) == -LINUX_EAGAIN); + puts("PASS standalone nexthop table completes without inventing route objects"); +} + static void check_dump_boundaries(int fd) { struct { struct nlmsghdr h; struct ifaddrmsg m; } request = { @@ -288,7 +438,7 @@ static void check_dump_boundaries(int fd) /** @brief Keep explicit and automatic netlink port bindings in their creating scope. */ static void check_netlink_namespace_ports(void) { - const int protocols[] = {NETLINK_ROUTE, NETLINK_KOBJECT_UEVENT}; + const int protocols[] = {NETLINK_ROUTE, NETLINK_KOBJECT_UEVENT, NETLINK_GENERIC}; for (unsigned i = 0; i < sizeof(protocols) / sizeof(protocols[0]); ++i) { struct net_namespace *scope; assert(!net_namespace_create(NULL, &scope)); @@ -382,6 +532,35 @@ static void check_netlink_namespace_delivery(void) puts("PASS netlink namespace delivery: same-port unicast, multicast and moved sender FD"); } +/** @brief Preserve the 32-bit address flags consumed by systemd-resolved. */ +static void check_ipv4_address_flags(void) +{ + struct netlink_message *message=calloc(1,sizeof(*message)+NL_MESSAGE_MAX); + assert(message); + struct nl_builder builder={.message=message}; + const struct nl_link_state link={.index=1,.address=0x7f000001, + .mask=0xff000000,.name="lo"}; + assert(!nl_address4(&builder,1,&link,RTM_NEWADDR,true)); + const struct nlmsghdr *header=(const void *)message->data; + uint32_t position=NLMSG_ALIGN(sizeof(*header)+sizeof(struct ifaddrmsg)); + bool found=false; + while(position+sizeof(struct rtattr)<=header->nlmsg_len) { + const struct rtattr *attribute=(const void *)(message->data+position); + assert(attribute->rta_len>=sizeof(*attribute)); + if(attribute->rta_type==IFA_FLAGS) { + uint32_t flags; + assert(attribute->rta_len==sizeof(*attribute)+sizeof(flags)); + memcpy(&flags,attribute+1,sizeof(flags)); + assert(flags==IFA_F_PERMANENT); + found=true; + } + position+=RTA_ALIGN(attribute->rta_len); + } + free(message); + assert(found); + puts("PASS IPv4 address flags: 32-bit IFA_FLAGS for resolved initialization"); +} + /** @brief Scope route events and global device events to their actual owners. */ static void check_netlink_namespace_events(void) { @@ -405,6 +584,36 @@ static void check_netlink_namespace_events(void) assert(receive(subscribers[0], output, sizeof(output)) > 0); assert(receive(subscribers[1], output, sizeof(output)) > 0); assert(receive(subscribers[2], output, sizeof(output)) == -LINUX_EAGAIN); + netlink_uevent_device("add", "/devices/test", "block", "SYNTH_UUID=0\0", sizeof("SYNTH_UUID=0\0") - 1); + static const char device_event[] = "add@/devices/test\0ACTION=add\0DEVPATH=/devices/test\0" + "SUBSYSTEM=block\0SYNTH_UUID=0\0SEQNUM="; + for (unsigned i = 0; i < 3; ++i) { + int count = receive(subscribers[i], output, sizeof(output)); + if (i == 2) assert(count == -LINUX_EAGAIN); + else assert(count > (int)sizeof(device_event) && !memcmp(output, device_event, sizeof(device_event) - 1)); + } + for(unsigned scope=0;scope<3;++scope) { + net_interface_uevent(scopes[scope],NET_IF_LOOPBACK,"add","01234567-89ab-cdef-0123-456789abcdef"); + for(unsigned i=0;i<3;++i) { + struct sockaddr_nl source={0};uint32_t source_length=sizeof(source); + struct ucred credentials={0}; + int count=task_netlink_recv_staged(&files[subscribers[i]],output,sizeof(output), + MSG_DONTWAIT,&source,&source_length,&credentials); + if(i!=scope){assert(count==-LINUX_EAGAIN);continue;} + assert(count>0 && source.nl_pid==0 && source.nl_groups==1); + assert(!credentials.pid && !credentials.uid && !credentials.gid); + static const char expected[]="add@/devices/virtual/net/lo\0ACTION=add\0" + "DEVPATH=/devices/virtual/net/lo\0SUBSYSTEM=net\0INTERFACE=lo\0IFINDEX=1\0" + "SYNTH_UUID=01234567-89ab-cdef-0123-456789abcdef\0SEQNUM="; + assert(count>(int)sizeof(expected) && !memcmp(output,expected,sizeof(expected)-1)); + } + } + allocation_fail_after=0; + net_interface_uevent(user_owned,NET_IF_LOOPBACK,"remove",NULL); + allocation_fail_after=-1; + assert(receive(subscribers[0],output,sizeof(output))==-LINUX_EAGAIN); + assert(receive(subscribers[1],output,sizeof(output))==-LINUX_EAGAIN); + assert(receive(subscribers[2],output,sizeof(output))==-LINUX_ENOBUFS); for (unsigned i = 0; i < 3; ++i) { task_netlink_release(&files[subscribers[i]]); files[subscribers[i]] = (struct task_file){0}; @@ -612,6 +821,45 @@ static void check_netlink_reuseaddr(void) puts("PASS route and kobject netlink SO_REUSEADDR: state and exclusive port binding"); } +/** @brief Admit official network services' route groups and a second bitmap word. */ +static void check_network_service_groups(void) +{ + unsigned baseline = allocations; + int fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(fd >= 0); + struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_groups = 1361}; + assert(!call(__NR_bind, fd, (uintptr_t)&address, sizeof(address), 0, 0)); + const uint32_t subscriptions[] = {3, 4, 8, 19, 32, 36}; + uint64_t expected = address.nl_groups; + for (unsigned i = 0; i < sizeof(subscriptions) / sizeof(subscriptions[0]); ++i) { + uint32_t group = subscriptions[i]; + assert(!call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group))); + expected |= 1ULL << (group - 1); + } + uint32_t invalid = 37; + assert(call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, + (uintptr_t)&invalid, sizeof(invalid)) == -LINUX_EINVAL); + uint64_t groups = 0; + uint32_t size = sizeof(groups); + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, + (uintptr_t)&groups, (uintptr_t)&size)); + assert(size == sizeof(groups) && groups == expected); + size = sizeof(address); + assert(!call(__NR_getsockname, fd, (uintptr_t)&address, (uintptr_t)&size, 0, 0)); + assert(address.nl_groups == (uint32_t)expected); + uint32_t high = 36; + assert(!call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, + (uintptr_t)&high, sizeof(high))); + size = sizeof(groups); + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, + (uintptr_t)&groups, (uintptr_t)&size)); + assert(groups == (uint32_t)expected); + task_netlink_release(&files[fd]); files[fd] = (struct task_file){0}; + assert(!nl_snapshots && allocations == baseline); + puts("PASS official network service route groups and 64-bit membership query"); +} + /** @brief Verify packet-info state and multicast membership query boundaries. */ static void check_netlink_metadata_options(void) { @@ -647,19 +895,20 @@ static void check_netlink_metadata_options(void) assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, (uintptr_t)groups, (uintptr_t)&size) && !size && groups[0] == UINT32_MAX); uint32_t group = i ? 2 : 1; + uint32_t bitmap_size = i ? sizeof(uint32_t) : sizeof(groups); assert(!call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, (uintptr_t)&group, sizeof(group))); for (unsigned capacity = 0; capacity <= sizeof(groups); ++capacity) { groups[0] = groups[1] = UINT32_MAX; size = capacity; assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, - (uintptr_t)groups, (uintptr_t)&size) && size == sizeof(uint32_t)); + (uintptr_t)groups, (uintptr_t)&size) && size == bitmap_size); assert(groups[0] == (capacity >= sizeof(uint32_t) ? 1u << (group - 1) : UINT32_MAX)); - assert(groups[1] == UINT32_MAX); + assert(groups[1] == (!i && capacity == sizeof(groups) ? 0 : UINT32_MAX)); } size = 0; assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, - 0, (uintptr_t)&size) && size == sizeof(uint32_t)); + 0, (uintptr_t)&size) && size == bitmap_size); size = sizeof(groups); assert(call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, 0, (uintptr_t)&size) == -LINUX_EFAULT); @@ -667,7 +916,7 @@ static void check_netlink_metadata_options(void) (uintptr_t)&group, sizeof(group))); size = sizeof(groups); assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, - (uintptr_t)groups, (uintptr_t)&size) && size == sizeof(uint32_t) && !groups[0]); + (uintptr_t)groups, (uintptr_t)&size) && size == bitmap_size && !groups[0]); size = UINT32_MAX; assert(call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, (uintptr_t)groups, (uintptr_t)&size) == -LINUX_EINVAL); @@ -758,7 +1007,7 @@ static void check_uevent_userspace_delivery(void) (uintptr_t)&udev_address, sizeof(udev_address)) == sizeof(payload)); assert(receive(monitor, output, sizeof(output)) == sizeof(payload)); - nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL, true); assert(task_netlink_recv_staged(&files[kernel], output, sizeof(output), MSG_DONTWAIT, &from, &from_size, &credentials) == sizeof(payload)); assert(!from.nl_pid && from.nl_groups == 1 && @@ -807,13 +1056,13 @@ static void check_netlink_filter(void) uint8_t payload[] = {0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0xaa, 0xbb, 0xcc, 0xdd}; uint8_t output[64]; - nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL, true); assert(receive(monitor, output, sizeof(output)) == 9); assert(!memcmp(output, payload, 9)); - nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, 7, NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, 7, NULL, NULL, true); assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); payload[4] = 0x21; - nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL, true); assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); payload[4] = 0x12; @@ -830,7 +1079,7 @@ static void check_netlink_filter(void) }; struct sock_fprog expression = {.len = sizeof(arithmetic) / sizeof(arithmetic[0]), .filter = arithmetic}; assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&expression, sizeof(expression))); - nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL, true); assert(receive(monitor, output, sizeof(output)) == 9); struct sock_filter invalid_path[] = { BPF_STMT(BPF_LD | BPF_W | BPF_IMM, 0), @@ -855,7 +1104,7 @@ static void check_netlink_filter(void) }; struct sock_fprog zero_divisor = {.len = 4, .filter = divide}; assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, (uintptr_t)&zero_divisor, sizeof(zero_divisor))); - nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL, true); assert(receive(monitor, output, sizeof(output)) == -LINUX_EAGAIN); assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program))); @@ -867,10 +1116,10 @@ static void check_netlink_filter(void) assert(call(__NR_setsockopt, monitor, SOL_SOCKET, SO_ATTACH_FILTER, data, sizeof(program)) == -LINUX_ENOMEM); allocation_fail_after = -1; } - nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL, true); assert(receive(monitor, output, sizeof(output)) == 9); assert(!call(__NR_setsockopt, monitor, SOL_SOCKET, SO_DETACH_FILTER, (uintptr_t)&value, sizeof(value))); - nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL); + nl_multicast(NULL, NETLINK_KOBJECT_UEVENT, 1, payload, sizeof(payload), NULL, NULL, true); assert(receive(monitor, output, sizeof(output)) == (int)sizeof(payload)); struct sock_filter reject[] = {BPF_STMT(BPF_RET | BPF_K, 0)}; @@ -1115,7 +1364,7 @@ static void check_scoped_link_events(void) sockets[i] = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); assert(sockets[i] >= 0); unsigned before = allocations; - int capture_allocations = scopes[i] ? 2 : 4; + int capture_allocations = scopes[i] ? 2 : 5; for (int fail = 0; fail < capture_allocations; ++fail) { allocation_fail_after = fail; assert(call(__NR_bind, sockets[i], (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_ENOMEM); @@ -1164,6 +1413,109 @@ static void check_scoped_link_events(void) puts("PASS scoped link events: capture rollback, delivery, overrun, retry and last subscriber"); } +/** @brief Validate one IPv4 notification's serialized value and source group. */ +static void check_ipv4_event(int fd, uint16_t type, uint32_t expected, uint32_t index) +{ + unsigned char output[512]; + struct sockaddr_nl source; + uint32_t size = sizeof(source); + int bytes = task_netlink_recv(&files[fd], output, sizeof(output), MSG_DONTWAIT, + (uintptr_t)&source, (uintptr_t)&size); + const struct nlmsghdr *header = (const void *)output; + assert(bytes > 0 && header->nlmsg_len == (uint32_t)bytes); + assert(header->nlmsg_type == type && !header->nlmsg_flags && !header->nlmsg_seq); + bool address = type == RTM_NEWADDR || type == RTM_DELADDR; + uint32_t payload = address ? sizeof(struct ifaddrmsg) : sizeof(struct rtmsg); + assert(!source.nl_pid && source.nl_groups == (address ? 0x10u : 0x40u)); + if (address) { + const struct ifaddrmsg *message = (const void *)(header + 1); + assert(message->ifa_family == AF_INET && message->ifa_index == index); + } else { + assert(((const struct rtmsg *)(header + 1))->rtm_family == AF_INET); + } + const struct rtattr *attrs[RTA_NH_ID + 1] = {0}; + assert(!nl_parse_attrs((const uint8_t *)(header + 1) + payload, + bytes - sizeof(*header) - payload, attrs, RTA_NH_ID + 1)); + uint32_t actual = 0; + assert(!nl_copy_attr(attrs[address ? IFA_LOCAL : RTA_DST], &actual, sizeof(actual))); + assert(__builtin_bswap32(actual) == expected); + if (address) assert(attrs[IFA_LABEL]); + else { + assert(!nl_copy_attr(attrs[RTA_OIF], &actual, sizeof(actual))); + assert(actual == index); + } +} + +/** @brief Keep IPv4 notifications scoped and preserve snapshots across capture OOM. */ +static void check_scoped_ipv4_events(void) +{ + unsigned baseline = allocations; + struct net_namespace *first, *second; + assert(!net_namespace_create(NULL, &first)); + assert(!net_namespace_create(NULL, &second)); + assert(!net_interface_set_up(first, NET_IF_LOOPBACK, true)); + assert(!net_interface_set_up(second, NET_IF_LOOPBACK, true)); + struct net_namespace *scopes[] = {first, second, NULL}; + int sockets[3]; + struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_groups = 0x50}; + for (unsigned i = 0; i < 3; ++i) { + current.net_ns = scopes[i]; + sockets[i] = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(sockets[i] >= 0); + assert(!call(__NR_bind, sockets[i], (uintptr_t)&address, sizeof(address), 0, 0)); + } + current.net_ns = second; + assert(!net_interface_configure_ipv4(first, 1, 0xc6336401u, 0xffffff00u, 0xc63364ffu)); + check_ipv4_event(sockets[0], RTM_DELADDR, 0x7f000001u, 1); + check_ipv4_event(sockets[0], RTM_NEWADDR, 0xc6336401u, 1); + check_ipv4_event(sockets[0], RTM_DELROUTE, 0x7f000000u, 1); + check_ipv4_event(sockets[0], RTM_NEWROUTE, 0xc6336400u, 1); + unsigned char output[512]; + for (unsigned i = 0; i < 3; ++i) + assert(receive(sockets[i], output, sizeof(output)) == -LINUX_EAGAIN); + struct net_ipv4_route route = {.destination = 0xcb007100u, .mask = 0xffffff00u, + .ifindex = 1, .metric = 7, .flags = RTF_UP}; + assert(!net_ipv4_route_update(first, &route, false, false)); + netlink_network_changed(first); + check_ipv4_event(sockets[0], RTM_NEWROUTE, route.destination, 1); + route.metric = 8; + assert(!net_ipv4_route_update(first, &route, false, true)); + netlink_network_changed(first); + check_ipv4_event(sockets[0], RTM_DELROUTE, route.destination, 1); + check_ipv4_event(sockets[0], RTM_NEWROUTE, route.destination, 1); + for (int fail = 0; fail < 2; ++fail) { + uint32_t next = 0xc6336402u + (uint32_t)fail; + unsigned before = allocations; + allocation_fail_after = fail; + assert(!net_interface_configure_ipv4(first, 1, next, 0xffffff00u, 0xc63364ffu)); + allocation_fail_after = -1; + assert(allocations == before); + assert(receive(sockets[0], output, sizeof(output)) == -LINUX_ENOBUFS); + for (unsigned i = 1; i < 3; ++i) + assert(receive(sockets[i], output, sizeof(output)) == -LINUX_EAGAIN); + netlink_network_changed(first); + check_ipv4_event(sockets[0], RTM_DELADDR, next - 1, 1); + check_ipv4_event(sockets[0], RTM_NEWADDR, next, 1); + assert(receive(sockets[0], output, sizeof(output)) == -LINUX_EAGAIN); + } + assert(!net_interface_register(3)); + assert(!net_interface_configure_ipv4(NULL, 3, 0xc0000201u, 0xffffff00u, 0xc00002ffu)); + check_ipv4_event(sockets[2], RTM_NEWADDR, 0xc0000201u, 3); + check_ipv4_event(sockets[2], RTM_NEWROUTE, 0xc0000200u, 3); + net_interface_remove(3); + netlink_network_changed(NULL); + check_ipv4_event(sockets[2], RTM_DELADDR, 0xc0000201u, 3); + check_ipv4_event(sockets[2], RTM_DELROUTE, 0xc0000200u, 3); + for (unsigned i = 0; i < 3; ++i) { + assert(receive(sockets[i], output, sizeof(output)) == -LINUX_EAGAIN); + task_netlink_release(&files[sockets[i]]); files[sockets[i]] = (struct task_file){0}; + } + current = (struct task){0}; + net_namespace_put(first); net_namespace_put(second); + assert(!nl_snapshots && allocations == baseline); + puts("PASS IPv4 notifications: scope, address/route replacement, OOM retry and detached interface"); +} + /* Check the actual serialized address in both dumps and multicast messages. */ static void check_ipv6_record(const void *buffer, unsigned bytes, uint16_t type, const struct in6_addr *expected) @@ -1182,9 +1534,9 @@ static void check_ipv6_record(const void *buffer, unsigned bytes, uint16_t type, const struct rtmsg *message = (const void *)(header + 1); assert(message->rtm_family == AF_INET6 && message->rtm_dst_len == 64); } - const struct rtattr *attrs[16] = {0}; + const struct rtattr *attrs[RTA_NH_ID + 1] = {0}; assert(!nl_parse_attrs((const uint8_t *)(header + 1) + payload, - bytes - sizeof(*header) - payload, attrs, 16)); + bytes - sizeof(*header) - payload, attrs, RTA_NH_ID + 1)); struct in6_addr actual = {0}; unsigned kind = address ? IFA_ADDRESS : RTA_DST; assert(attrs[kind] && !nl_copy_attr(attrs[kind], &actual, sizeof(actual))); @@ -1198,6 +1550,10 @@ static void check_ipv6_ack(int fd, const void *request, unsigned bytes, int erro assert(receive(fd, output, sizeof(output)) >= (int)(sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr))); const struct nlmsghdr *header = (const void *)output; assert(header->nlmsg_type == NLMSG_ERROR); + if (((const struct nlmsgerr *)(header + 1))->error != error) + fprintf(stderr, "netlink request %u returned %d, expected %d\n", + ((const struct nlmsghdr *)request)->nlmsg_type, + ((const struct nlmsgerr *)(header + 1))->error, error); assert(((const struct nlmsgerr *)(header + 1))->error == error); assert(receive(fd, output, sizeof(output)) == -LINUX_EAGAIN); } @@ -1314,13 +1670,14 @@ static void check_scoped_ipv6_control(void) assert(!scoped_ipv6[0].has_route && scoped_ipv6[1].has_route); check_ipv6_event(listeners, RTM_DELROUTE, &route.ip); address.h.nlmsg_type = RTM_NEWADDR; - address.h.nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL; + address.h.nlmsg_flags |= NLM_F_REPLACE; route.h.nlmsg_type = RTM_NEWROUTE; - route.h.nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL; + route.h.nlmsg_flags |= NLM_F_CREATE | NLM_F_APPEND; check_ipv6_ack(command, &address, sizeof(address), 0); check_ipv6_event(listeners, RTM_NEWADDR, &address.ip); check_ipv6_ack(command, &route, sizeof(route), 0); check_ipv6_event(listeners, RTM_NEWROUTE, &route.ip); + check_ipv6_ack(command, &route, sizeof(route), -LINUX_EEXIST); assert(!net_ipv6_interface_ioctl(scopes[0], SIOCDIFADDR, (uintptr_t)&in6)); check_ipv6_event(listeners, RTM_DELADDR, &address.ip); assert(!net_ipv6_interface_ioctl(scopes[0], SIOCDELRT, (uintptr_t)&in6route)); @@ -1345,28 +1702,492 @@ static void check_scoped_ipv6_control(void) puts("PASS scoped IPv6 control dumps, mutations, notifications, proc and owner authority"); } +/** @brief Check controller replies using their public wire attributes. */ +static void check_ctrl_reply(const unsigned char *output, unsigned bytes, uint32_t port, bool dump) +{ + const struct nlmsghdr *header = (const void *)output; + assert(bytes >= NLMSG_HDRLEN + GENL_HDRLEN && header->nlmsg_len == bytes); + assert(header->nlmsg_type == GENL_ID_CTRL && header->nlmsg_seq == 901); + assert(header->nlmsg_pid == port && header->nlmsg_flags == (dump ? NLM_F_MULTI : 0)); + const struct genlmsghdr *body = (const void *)(header + 1); + assert(body->cmd == CTRL_CMD_NEWFAMILY && body->version == 2 && !body->reserved); + unsigned found = 0; + for (unsigned offset = NLMSG_HDRLEN + GENL_HDRLEN; offset < bytes;) { + const struct nlattr *attr = (const void *)(output + offset); + assert(bytes - offset >= NLA_HDRLEN && attr->nla_len >= NLA_HDRLEN); + assert(attr->nla_len <= bytes - offset); + const void *value = attr + 1; + uint32_t number; + switch (attr->nla_type) { + case CTRL_ATTR_FAMILY_NAME: + assert(attr->nla_len == 11 && !memcmp(value, "nlctrl", 7)); found |= 1; break; + case CTRL_ATTR_FAMILY_ID: { + uint16_t id; + assert(attr->nla_len == 6); memcpy(&id, value, sizeof(id)); + assert(id == 16); found |= 2; break; + } + case CTRL_ATTR_VERSION: + case CTRL_ATTR_HDRSIZE: + case CTRL_ATTR_MAXATTR: + assert(attr->nla_len == 8); memcpy(&number, value, sizeof(number)); + assert(number == (attr->nla_type == CTRL_ATTR_VERSION ? 2u : 0u)); + found |= 1u << attr->nla_type; break; + case CTRL_ATTR_OPS: { + const struct nlattr *entry = value; + assert(entry->nla_len == 20 && entry->nla_type == 1); + const struct nlattr *id = entry + 1; + assert(id->nla_len == 8 && id->nla_type == CTRL_ATTR_OP_ID); + memcpy(&number, id + 1, sizeof(number)); assert(number == CTRL_CMD_GETFAMILY); + const struct nlattr *flags = (const void *)((const unsigned char *)id + 8); + assert(flags->nla_len == 8 && flags->nla_type == CTRL_ATTR_OP_FLAGS); + memcpy(&number, flags + 1, sizeof(number)); + assert(number == (GENL_CMD_CAP_DO | GENL_CMD_CAP_DUMP)); found |= 64; break; + } + case CTRL_ATTR_MCAST_GROUPS: { + const struct nlattr *entry = value; + assert(entry->nla_len == 24 && entry->nla_type == 1); + const struct nlattr *id = entry + 1; + assert(id->nla_len == 8 && id->nla_type == CTRL_ATTR_MCAST_GRP_ID); + memcpy(&number, id + 1, sizeof(number)); assert(number == 16); + const struct nlattr *name = (const void *)((const unsigned char *)id + 8); + assert(name->nla_len == 11 && name->nla_type == CTRL_ATTR_MCAST_GRP_NAME); + assert(!memcmp(name + 1, "notify", 7)); found |= 128; break; + } + default: assert(false); + } + offset += NLA_ALIGN(attr->nla_len); + } + assert(found == (1u | 2u | 8u | 16u | 32u | 64u | 128u)); +} + +/** @brief Preserve Linux error payloads and sequence for generic control failures. */ +static void check_ctrl_error(int fd, const void *request, unsigned length, int error) +{ + assert(send_req(fd, request, length) == (int)length); + unsigned char output[8192]; + int count = receive(fd, output, sizeof(output)); + assert(count == (int)(NLMSG_HDRLEN + sizeof(int32_t) + length)); + const struct nlmsghdr *header = (const void *)output; + const struct nlmsghdr *original = request; + assert(header->nlmsg_type == NLMSG_ERROR && header->nlmsg_seq == original->nlmsg_seq); + const struct nlmsgerr *reply = (const void *)(header + 1); + assert(reply->error == error && !memcmp(&reply->msg, request, length)); + assert(receive(fd, output, sizeof(output)) == -LINUX_EAGAIN); +} + +/** @brief Exercise real generic controller lookup, dump, queue rollback and retained scope. */ +static void check_generic_netlink(void) +{ + unsigned baseline = allocations; + struct net_namespace *scope; + assert(!net_namespace_create(NULL, &scope)); + current.net_ns = scope; + int fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, + NETLINK_GENERIC, 0, 0); + assert(fd >= 0 && (files[fd].fd_flags & RELIEFOS_FD_CLOEXEC)); + assert(scope->references == 2); + const struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_pid = 901}; + assert(!call(__NR_bind, fd, (uintptr_t)&address, sizeof(address), 0, 0)); + current.net_ns = NULL; + struct { + struct nlmsghdr header; + struct genlmsghdr body; + struct nlattr attr; + char name[16]; + } query = { + .header = {.nlmsg_len = 32, .nlmsg_type = GENL_ID_CTRL, + .nlmsg_flags = NLM_F_REQUEST, .nlmsg_seq = 901}, + .body = {.cmd = CTRL_CMD_GETFAMILY, .version = 1}, + .attr = {.nla_len = 11, .nla_type = CTRL_ATTR_FAMILY_NAME}, .name = "nlctrl" + }; + unsigned char output[8192]; + assert(send_req(fd, &query, 32) == 32); + struct sockaddr_nl source = {0}; uint32_t source_size = sizeof(source); + int count = task_netlink_recv(&files[fd], output, sizeof(output), MSG_DONTWAIT, + (uintptr_t)&source, (uintptr_t)&source_size); + assert(count > 0 && source.nl_family == AF_NETLINK && !source.nl_pid && !source.nl_groups); + check_ctrl_reply(output, (unsigned)count, 901, false); + assert(!nl_snapshots); /* Generic membership must never capture route baselines. */ + /* A final attribute needs no trailing alignment bytes, and reserved tail bytes are ignored. */ + query.header.nlmsg_len = 31; + assert(send_req(fd, &query, 31) == 31); + count = receive(fd, output, sizeof(output)); + assert(count > 0); check_ctrl_reply(output, (unsigned)count, 901, false); + unsigned char padded[152] = {0}; + memcpy(padded, &query, 31); + assert(send_req(fd, padded, sizeof(padded)) == sizeof(padded)); + count = receive(fd, output, sizeof(output)); + assert(count > 0); check_ctrl_reply(output, (unsigned)count, 901, false); + query.header.nlmsg_len = 32; + unsigned char batch[64]; + memcpy(batch, &query, 32); memcpy(batch + 32, &query, 32); + assert(send_req(fd, batch, sizeof(batch)) == sizeof(batch)); + count = receive(fd, output, sizeof(output)); + assert(count > 0); + unsigned first_size = ((struct nlmsghdr *)(void *)output)->nlmsg_len; + assert((unsigned)count == first_size * 2); + check_ctrl_reply(output, first_size, 901, false); + check_ctrl_reply(output + first_size, first_size, 901, false); + query.header.nlmsg_flags |= NLM_F_ACK; + query.header.nlmsg_len = 28; query.attr.nla_type = CTRL_ATTR_FAMILY_ID; query.attr.nla_len = 6; + uint16_t id = GENL_ID_CTRL; memcpy(query.name, &id, sizeof(id)); + assert(send_req(fd, &query, 28) == 28); + count = receive(fd, output, sizeof(output)); + struct nlmsghdr *reply = (void *)output; + unsigned family_size = NLMSG_ALIGN(reply->nlmsg_len); + assert(count == (int)(family_size + NLMSG_HDRLEN + sizeof(struct nlmsgerr))); + check_ctrl_reply(output, family_size, 901, false); + reply = (void *)(output + family_size); + assert(reply->nlmsg_type == NLMSG_ERROR && !((struct nlmsgerr *)(reply + 1))->error); + query.header.nlmsg_flags = NLM_F_REQUEST; + id = 1023; memcpy(query.name, &id, sizeof(id)); + check_ctrl_error(fd, &query, 28, -LINUX_ENOENT); + query.header.nlmsg_len = 32; query.attr.nla_type = CTRL_ATTR_FAMILY_NAME; query.attr.nla_len = 12; + memcpy(query.name, "nl80211", 8); + check_ctrl_error(fd, &query, 32, -LINUX_ENOENT); + query.attr.nla_len = 10; memcpy(query.name, "nlctrl", 6); + check_ctrl_error(fd, &query, 32, -LINUX_EINVAL); + query.header.nlmsg_flags |= NLM_F_DUMP; + check_ctrl_error(fd, &query, 32, -LINUX_EINVAL); + query.header.nlmsg_flags = NLM_F_REQUEST; + query.attr.nla_len = 4; + check_ctrl_error(fd, &query, 32, -LINUX_EINVAL); + query.attr.nla_len = 5; query.attr.nla_type = CTRL_ATTR_FAMILY_ID; + check_ctrl_error(fd, &query, 32, -LINUX_ERANGE); + query.header.nlmsg_len = 20; + check_ctrl_error(fd, &query, 20, -LINUX_EINVAL); + query.header.nlmsg_type = 1023; + check_ctrl_error(fd, &query, 20, -LINUX_ENOENT); + query.header.nlmsg_type = GENL_ID_CTRL; query.body.cmd = CTRL_CMD_DELFAMILY; + check_ctrl_error(fd, &query, 20, -LINUX_EOPNOTSUPP); + query.body.cmd = CTRL_CMD_GETFAMILY; + query.header.nlmsg_len = 16; + check_ctrl_error(fd, &query, 16, -LINUX_EINVAL); + query.header.nlmsg_len = 20; + const uint16_t ignored_types[] = {GENL_ID_CTRL, NLMSG_NOOP}; + for (unsigned i = 0; i < 2; ++i) { + query.header.nlmsg_type = ignored_types[i]; + query.header.nlmsg_flags = i ? NLM_F_REQUEST | NLM_F_ACK : NLM_F_ACK; + assert(send_req(fd, &query, 20) == 20); + count = receive(fd, output, sizeof(output)); + assert(count == (int)(NLMSG_HDRLEN + sizeof(struct nlmsgerr))); + reply = (void *)output; + assert(reply->nlmsg_type == NLMSG_ERROR && !((struct nlmsgerr *)(reply + 1))->error); + } + query.header.nlmsg_type = GENL_ID_CTRL; + query.header.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; + for (int failure = 0; failure < 3; ++failure) { + unsigned before = allocations; + allocation_fail_after = failure; + assert(send_req(fd, &query, 20) == -LINUX_ENOMEM); + allocation_fail_after = -1; + assert(allocations == before && !nl_socket(&files[fd])->queued_bytes); + assert(receive(fd, output, sizeof(output)) == -LINUX_EAGAIN); + } + int budget = 8192; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_RCVBUF, (uintptr_t)&budget, sizeof(budget))); + assert(send_req(fd, &query, 20) == 20); + assert(send_req(fd, &query, 20) == -LINUX_ENOBUFS); + count = receive_dump(fd, output, sizeof(output)); + check_ctrl_reply(output, (unsigned)count, 901, true); + assert(receive(fd, output, sizeof(output)) == -LINUX_EAGAIN); + assert(send_req(fd, &query, 20) == 20); + assert(receive_dump(fd, output, sizeof(output)) > 0); + uint32_t group = 16; + assert(!call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group))); + assert(!nl_snapshots); + group = 1; + assert(call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group)) == -LINUX_EINVAL); + uint32_t memberships = 0, size = sizeof(memberships); + assert(!call(__NR_getsockopt, fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, + (uintptr_t)&memberships, (uintptr_t)&size)); + assert(size == 4 && memberships == 0x8000); + group = 16; + assert(!call(__NR_setsockopt, fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, + (uintptr_t)&group, sizeof(group))); + /* Final close also releases a pending multipart reply and the creating scope. */ + assert(send_req(fd, &query, 20) == 20); + net_namespace_put(scope); + task_netlink_release(&files[fd]); files[fd] = (struct task_file){0}; + assert(allocations == baseline && !netlink_sockets && !nl_snapshots); + puts("PASS generic netlink nlctrl lookup/dump, Linux errors, ACK, groups, queues and creating scope"); +} + +/** @brief Reproduce udev's indexed rename and observe the public name and move events. */ +static void check_link_rename(void) +{ + unsigned baseline = allocations; + current = (struct task){.cap_effective = 1ULL << CAP_NET_ADMIN}; + int command = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + int listener = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + int events = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT, 0, 0); + assert(command >= 0 && listener >= 0 && events >= 0); + struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_groups = RTMGRP_LINK}; + assert(!call(__NR_bind, listener, (uintptr_t)&address, sizeof(address), 0, 0)); + address.nl_groups = 1; + assert(!call(__NR_bind, events, (uintptr_t)&address, sizeof(address), 0, 0)); + struct { + struct nlmsghdr header; + struct ifinfomsg link; + struct rtattr attribute; + char name[NET_IF_NAME_LEN]; + } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_SETLINK, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK}, + .link = {.ifi_index = 2}, + .attribute = {.rta_len = sizeof(struct rtattr) + NET_IF_NAME_LEN, .rta_type = IFLA_IFNAME}, + .name = "enp0s3"}; + current.cap_effective = 0; + check_ipv6_ack(command, &request, sizeof(request), -LINUX_EPERM); + current.cap_effective = 1ULL << CAP_NET_ADMIN; + check_ipv6_ack(command, &request, sizeof(request), 0); + assert(net_interface_index(NULL, "enp0s3") == 2 && !net_interface_index(NULL, "eth0")); + char name[NET_IF_NAME_LEN]; + assert(net_interface_name(NULL, 2, name) && !strcmp(name, "enp0s3")); + struct ifreq ifr = {.ifr_name = "enp0s3"}; + assert(!net_interface_ioctl(NULL, SIOCGIFINDEX, (uintptr_t)&ifr) && ifr.data.value == 2); + memset(&ifr, 0, sizeof(ifr)); + ifr.data.value = 2; + assert(!net_interface_ioctl(NULL, SIOCGIFNAME, (uintptr_t)&ifr) && !strcmp(ifr.ifr_name, "enp0s3")); + unsigned char output[1024]; + int bytes = receive(listener, output, sizeof(output)); + assert(bytes > 0); + const struct nlmsghdr *header = (const void *)output; + assert(header->nlmsg_type == RTM_NEWLINK && !header->nlmsg_seq); + const struct ifinfomsg *link = (const void *)(header + 1); + assert(link->ifi_index == 2); + const struct rtattr *attrs[17] = {0}; + assert(!nl_parse_attrs((const uint8_t *)(link + 1), bytes - sizeof(*header) - sizeof(*link), attrs, 17)); + assert(attrs[IFLA_IFNAME] && !strcmp((const char *)(attrs[IFLA_IFNAME] + 1), "enp0s3")); + bytes = receive(events, output, sizeof(output)); + static const char expected[] = "move@/devices/pci0000:00/0000:00:00.0/net/enp0s3\0ACTION=move\0" + "DEVPATH=/devices/pci0000:00/0000:00:00.0/net/enp0s3\0SUBSYSTEM=net\0" + "INTERFACE=enp0s3\0IFINDEX=2\0DEVPATH_OLD=/devices/pci0000:00/0000:00:00.0/net/eth0\0SEQNUM="; + assert(bytes > (int)sizeof(expected) && !memcmp(output, expected, sizeof(expected) - 1)); + check_ipv6_ack(command, &request, sizeof(request), 0); + assert(receive(listener, output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(events, output, sizeof(output)) == -LINUX_EAGAIN); + const char *invalid[] = {"", ".", "..", "bad/name", "bad:name", "bad name", "bad\tname", + "lo", "bad%q", "bad%d%d", "12345678901234%"}; + for (unsigned i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { + memset(request.name, 0, sizeof(request.name)); + strcpy(request.name, invalid[i]); + int error = i == 0 ? 0 : i == 7 ? -LINUX_EEXIST : -LINUX_EINVAL; + check_ipv6_ack(command, &request, sizeof(request), error); + assert(net_interface_index(NULL, "enp0s3") == 2); + assert(receive(listener, output, sizeof(output)) == -LINUX_EAGAIN); + assert(receive(events, output, sizeof(output)) == -LINUX_EAGAIN); + } + memset(request.name, 'x', sizeof(request.name)); + check_ipv6_ack(command, &request, sizeof(request), -LINUX_EINVAL); + strcpy(ifr.ifr_name, "enp0s3"); + strcpy((char *)ifr.data.pad, "nic%d"); + current.cap_effective = 0; + assert(net_interface_ioctl(NULL, SIOCSIFNAME, (uintptr_t)&ifr) == -LINUX_EPERM); + current.cap_effective = 1ULL << CAP_NET_ADMIN; + assert(!net_interface_ioctl(NULL, SIOCSIFNAME, (uintptr_t)&ifr)); + assert(net_interface_index(NULL, "nic0") == 2 && !net_interface_index(NULL, "enp0s3")); + assert(net_interface_is_up(NULL, 2)); + strcpy(request.name, "eth0"); + check_ipv6_ack(command, &request, sizeof(request), 0); + for (unsigned i = 0; i < 4; ++i) if (files[i].used) { + task_netlink_release(&files[i]); + files[i] = (struct task_file){0}; + } + struct net_namespace *first, *second; + assert(!net_namespace_create(NULL, &first) && !net_namespace_create(NULL, &second)); + current.net_ns = first; + command = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(command >= 0); + current.net_ns = second; + request.link.ifi_index = NET_IF_LOOPBACK; + strcpy(request.name, "eth0"); + check_ipv6_ack(command, &request, sizeof(request), 0); + assert(net_interface_index(first, "eth0") == 1 && !net_interface_index(first, "lo")); + assert(net_interface_index(second, "lo") == 1 && !net_interface_index(second, "eth0")); + assert(net_interface_index(NULL, "eth0") == 2 && net_interface_index(NULL, "lo") == 1); + task_netlink_release(&files[command]); + files[command] = (struct task_file){0}; + current = (struct task){0}; + net_namespace_put(first); + net_namespace_put(second); + assert(allocations == baseline); + puts("PASS indexed interface rename: permission, ioctl, name collision and route/move notifications"); +} + +/** @brief Exercise networkd's DHCP address lifetime and prefix-route metric through rtnetlink. */ +static void check_networkd_address(void) +{ + struct net_interface *iface = net_interface_get(NULL, 2); + struct net_interface saved = *iface; + struct task saved_task = current; + current = (struct task){.cap_effective = 1ULL << CAP_NET_ADMIN}; + int fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(fd >= 0); + struct { + struct nlmsghdr header; + struct ifaddrmsg address; + struct { struct rtattr attr; uint32_t value; } local, flags, metric; + struct { struct rtattr attr; struct ifa_cacheinfo value; } cache; + } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_NEWADDR, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_REPLACE}, + .address = {.ifa_family = AF_INET, .ifa_prefixlen = 24, .ifa_index = 2}, + .local = {{8, IFA_LOCAL}, __builtin_bswap32(0x0a00020f)}, + .flags = {{8, IFA_FLAGS}, 0x200}, /* IFA_F_NOPREFIXROUTE */ + .metric = {{8, 9}, 1024}, /* IFA_RT_PRIORITY */ + .cache = {{20, IFA_CACHEINFO}, {.ifa_prefered = 10, .ifa_valid = 20}}, + }; + check_ipv6_ack(fd, &request, sizeof(request), 0); + assert(iface->config.local_ip == 0x0a00020f); + struct { struct nlmsghdr header; struct ifaddrmsg address; } dump = { + .header = {.nlmsg_len = sizeof(dump), .nlmsg_type = RTM_GETADDR, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP}, + .address = {.ifa_family = AF_INET, .ifa_index = 2}, + }; + assert(send_req(fd, &dump, sizeof(dump)) == sizeof(dump)); + unsigned char output[512]; + int bytes = receive_dump(fd, output, sizeof(output)); + struct nlmsghdr *header = (void *)output; + assert(header->nlmsg_type == RTM_NEWADDR && bytes == (int)header->nlmsg_len); + const struct rtattr *attrs[16] = {0}; + assert(!nl_parse_attrs(output + 24, header->nlmsg_len - 24, attrs, 16)); + uint32_t flags = 0, metric = 0; + struct ifa_cacheinfo cache = {0}; + assert(attrs[IFA_FLAGS] && !nl_copy_attr(attrs[IFA_FLAGS], &flags, 4) && flags == 0x200); + assert(attrs[9] && !nl_copy_attr(attrs[9], &metric, 4) && metric == 1024); + assert(attrs[IFA_CACHEINFO] && !nl_copy_attr(attrs[IFA_CACHEINFO], &cache, sizeof(cache))); + assert(cache.ifa_prefered == 10 && cache.ifa_valid == 20); + struct net_ipv4_route routes[8]; + unsigned count = net_ipv4_routes(NULL, routes, 8); + for (unsigned i = 0; i < count; ++i) + assert(routes[i].ifindex != 2 || routes[i].mask != 0xffffff00); + struct { + struct nlmsghdr header; + struct rtmsg route; + struct { struct rtattr attr; uint32_t value; } gateway, interface, metric, source; + } gateway = { + .header = {.nlmsg_len = sizeof(gateway), .nlmsg_type = RTM_NEWROUTE, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_APPEND}, + .route = {.rtm_family = AF_INET, .rtm_table = RT_TABLE_MAIN, + .rtm_protocol = 16, .rtm_type = RTN_UNICAST, .rtm_flags = RTNH_F_ONLINK}, /* RTPROT_DHCP */ + .gateway = {{8, RTA_GATEWAY}, __builtin_bswap32(0x0a000202)}, + .interface = {{8, RTA_OIF}, 2}, .metric = {{8, RTA_PRIORITY}, 1024}, + .source = {{8, RTA_PREFSRC}, __builtin_bswap32(0x0a00020f)}, + }; + check_ipv6_ack(fd, &gateway, sizeof(gateway), 0); + check_ipv6_ack(fd, &gateway, sizeof(gateway), -LINUX_EEXIST); + struct net_ipv4_path path; + assert(!net_ipv4_route_lookup(NULL, 0x08080808, 0, 0, &path)); + assert(path.ifindex == 2 && path.source == 0x0a00020f && path.next_hop == 0x0a000202); + gateway.header.nlmsg_type = RTM_DELROUTE; + gateway.header.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; + check_ipv6_ack(fd, &gateway, sizeof(gateway), 0); + request.cache.value.ifa_prefered = 21; + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_EINVAL); + assert(iface->config.local_ip == 0x0a00020f); + uint64_t saved_time=uptime_ms; + uptime_ms+=10000; + net_interface_ipv4_poll(NULL); + assert(iface->config.local_ip==0x0a00020f && (iface->ipv4_address.flags & IFA_F_DEPRECATED)); + uptime_ms+=10000; + net_interface_ipv4_poll(NULL); + assert(!iface->config.local_ip && !iface->config.gateway_ip); + uptime_ms=saved_time; + *iface = saved; + task_netlink_release(&files[fd]); files[fd] = (struct task_file){0}; + current = saved_task; + puts("PASS networkd DHCP address lifetime, flags, metric and atomic validation"); +} + +/** @brief Exercise networkd's standalone IPv6 gateway creation through its actual socket entry. */ +static void check_networkd_nexthop(void) +{ + struct task saved = current; + current = (struct task){.cap_effective = 1ULL << CAP_NET_ADMIN}; + int fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(fd >= 0); + struct { + struct nlmsghdr header; + struct nhmsg nexthop; + struct { struct rtattr attr; uint32_t value; } id, interface; + struct { struct rtattr attr; struct in6_addr value; } gateway; + } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_NEWNEXTHOP, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL}, + .nexthop = {.nh_family = AF_INET6, .nh_protocol = RTPROT_RA}, + .id = {{8, 1}, 42}, .interface = {{8, 5}, 2}, + .gateway = {{20, 6}, {.s6_addr = {0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,2}}}, + }; + check_ipv6_ack(fd, &request, sizeof(request), 0); + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_EEXIST); + struct { + struct nlmsghdr header; + struct nhmsg nexthop; + struct { struct rtattr attr; uint32_t value; } id; + } get = { + .header = {.nlmsg_len=sizeof(get),.nlmsg_type=RTM_GETNEXTHOP,.nlmsg_flags=NLM_F_REQUEST}, + .id={{8,NHA_ID},42}, + }; + assert(send_req(fd,&get,sizeof(get))==sizeof(get)); + unsigned char output[256]; + int bytes=receive(fd,output,sizeof(output)); + struct nlmsghdr *header=(void *)output; + assert(bytes>24 && header->nlmsg_type==RTM_NEWNEXTHOP); + const struct rtattr *attrs[NHA_FDB+1]={0}; + assert(!nl_parse_attrs(output+24,header->nlmsg_len-24,attrs,NHA_FDB+1)); + struct in6_addr gateway={0}; + uint32_t id=0; + assert(attrs[NHA_ID] && !nl_copy_attr(attrs[NHA_ID],&id,4) && id==42); + assert(attrs[NHA_GATEWAY] && !nl_copy_attr(attrs[NHA_GATEWAY],&gateway,16)); + assert(gateway.s6_addr[15]==2); + request.header.nlmsg_flags=NLM_F_REQUEST|NLM_F_ACK|NLM_F_REPLACE; + request.gateway.value.s6_addr[15]=3; + check_ipv6_ack(fd,&request,sizeof(request),0); + assert(net_nexthop_get(NULL,42)->gateway.ipv6.s6_addr[15]==3); + request.header.nlmsg_type = RTM_DELNEXTHOP; + request.header.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; + check_ipv6_ack(fd, &request, sizeof(request), 0); + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_ENOENT); + task_netlink_release(&files[fd]); files[fd] = (struct task_file){0}; + current = saved; + puts("PASS networkd standalone nexthop creation and removal"); +} + int main(void) { + check_generic_netlink(); check_netlink_buffers(); check_netlink_buffer_limits(); check_netlink_namespace_ports(); check_netlink_namespace_delivery(); + check_ipv4_address_flags(); check_netlink_namespace_events(); check_netlink_namespace_failures(); check_netlink_reuseaddr(); check_uevent_userspace_delivery(); assert(!net_interface_register(2)); + check_networkd_address(); + check_networkd_nexthop(); + check_network_service_groups(); check_netlink_interface_scopes(); check_netlink_interface_authority(); check_scoped_ipv4_routes(); check_scoped_link_events(); + check_scoped_ipv4_events(); check_scoped_ipv6_control(); check_netlink_metadata_options(); check_netlink_filter(); + check_link_rename(); net_config.local_ip=0x0a00020f; net_config.subnet_mask=0xffffff00; int fd = (int)call(__NR_socket,AF_NETLINK,SOCK_RAW|SOCK_NONBLOCK,NETLINK_ROUTE,0,0); assert(fd >= 0 && files[fd].socket_ino); check_route_completion(fd); + check_bridge_dump(fd); + check_neighbor_dumps(fd); + check_nexthop_dump(fd); check_dump_boundaries(fd); check_netlink_datagram_tail(fd); struct { struct nlmsghdr h; struct ifinfomsg m; } link = { diff --git a/tools/tests/ipv6_protocol_test.c b/tools/tests/ipv6_protocol_test.c index fd008a17..afb91c95 100644 --- a/tools/tests/ipv6_protocol_test.c +++ b/tools/tests/ipv6_protocol_test.c @@ -4,10 +4,13 @@ #include #include #include +#include #include #include "../../net/internal.h" #include #include +#include +#include #include #include #include @@ -36,6 +39,8 @@ static uint32_t sent_ifindex[128]; static unsigned sent_count, udp_count, raw_count; static uint32_t last_udp_ifindex, last_error_ifindex; static unsigned socket_error_count; +static struct sock_extended_err last_extended_error; +static struct sockaddr_storage last_error_offender; static uint8_t queued_frame[1536]; static uint32_t queued_length; const uint8_t net_broadcast_mac[6]={255,255,255,255,255,255}; @@ -82,6 +87,19 @@ bool net_interface_is_up(struct net_namespace *ns, uint32_t index) { return ns ? index==1 && ns->loopback.up : index==1 || (net_interface_exists(NULL, index) && net_interface_up); } bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return net_interface_is_up(ns, index) && (index==1 || netdev_is_ready(index)); } +/** @brief This IPv6 fixture has no configured IPv4 interface state. */ +struct net_interface *net_interface_get(struct net_namespace *ns, uint32_t index) +{ return ns && index == NET_IF_LOOPBACK ? &ns->loopback : NULL; } +/** @brief The fixture clock drives real IPv6 maintenance without IPv4 leases. */ +void net_interface_ipv4_poll(struct net_namespace *ns) { (void)ns; } +/** @brief Record scoped notifications while the real nexthop table updates IPv6. */ +void netlink_network_changed(struct net_namespace *ns) { last_change_ns = ns; } +/** @brief Nexthop wire serialization is covered by the control fixture. */ +void netlink_nexthop_changed(struct net_namespace *ns, const struct net_nexthop *value, bool remove) +{ (void)ns; (void)value; (void)remove; } +/** @brief IPv4 route mutation is covered independently by the control fixture. */ +void net_ipv4_nexthop_changed(struct net_namespace *ns, uint32_t id, const struct net_nexthop *value) +{ (void)ns; (void)id; (void)value; } bool net_device_registration_pending(void) { return false; } void net_device_retry_registration(void) { } /** @brief Allocate kernel fixture memory. @param size Requested bytes. @return Owned memory. */ @@ -121,6 +139,15 @@ void net_ipv6_socket_error(const uint8_t *p,uint32_t n,int e,uint32_t m) { (void)p;(void)n;(void)e;(void)m; } void net_ipv6_socket_error_on(struct net_namespace *ns,uint32_t i,const uint8_t *p,uint32_t n,int e,uint32_t m) { last_error_ns=ns;last_error_ifindex=i;++socket_error_count;net_ipv6_socket_error(p,n,e,m); } +/** @brief Record detailed protocol metadata at the transport boundary. */ +void net_ipv6_socket_extended_error_on(struct net_namespace *ns, uint32_t index, + const uint8_t *packet, uint32_t length, const struct sock_extended_err *error, + const struct sockaddr_storage *offender) +{ + last_extended_error = *error; + last_error_offender = *offender; + net_ipv6_socket_error_on(ns, index, packet, length, (int)error->ee_errno, error->ee_info); +} /** @brief Copy bytes. @param d Destination. @param s Source. @param n Length. */ void net_memcpy(void *d,const void *s,uint32_t n) { memcpy(d,s,n); } /** @brief Clear bytes. @param d Destination. @param n Length. */ @@ -204,6 +231,52 @@ static uint32_t packet(uint8_t *out,const struct in6_addr *src,const struct in6_ { memset(out,0,54+n);memcpy(out,nic_mac,6);out[6]=0x02;out[11]=1;net_put_u16(out+12,0x86dd); out[14]=0x60;net_put_u16(out+18,(uint16_t)n);out[20]=next;out[21]=hop; memcpy(out+22,src->s6_addr,16);memcpy(out+38,dst->s6_addr,16);memcpy(out+54,payload,n);return 54+n; } +/** @brief Deliver real ICMPv6 errors and verify Linux errno and offender metadata. + * @param local Configured receiving address. @param peer Link-local reporting router. */ +static void test_icmp_error_metadata(const struct in6_addr *local, const struct in6_addr *peer) +{ + static const struct { + uint8_t type, code; + int error; + } cases[] = { + {1, 4, LINUX_ECONNREFUSED}, {1, 0, LINUX_ENETUNREACH}, + {1, 1, LINUX_EACCES}, {1, 2, LINUX_EHOSTUNREACH}, + {1, 3, LINUX_EHOSTUNREACH}, {1, 5, LINUX_EACCES}, + {1, 6, LINUX_EACCES}, {1, 7, LINUX_EPROTO}, + {2, 0, LINUX_EMSGSIZE}, {3, 0, LINUX_EHOSTUNREACH}, + {3, 1, LINUX_EHOSTUNREACH}, {4, 2, LINUX_EPROTO} + }; + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + uint8_t message[60] = {0}, frame[114]; + message[0] = cases[i].type; + message[1] = cases[i].code; + uint32_t mtu = cases[i].type == 2 ? 1500 : 0; + net_put_u32(message + 4, mtu); + message[8] = 0x60; + net_put_u16(message + 12, 12); + message[14] = 17; + message[15] = 64; + memcpy(message + 16, local, 16); + memcpy(message + 32, peer, 16); + udp(message + 48, local, peer, 9000, (const uint8_t *)"dns!", 4); + net_put_u16(message + 2, net_ipv6_checksum(peer, local, 58, message, sizeof(message))); + uint32_t length = packet(frame, peer, local, 58, 64, message, sizeof(message)); + unsigned before = socket_error_count; + net_ipv6_input_on(NULL, 2, frame, length); + assert(socket_error_count == before + 1 && !last_error_ns && last_error_ifindex == 2); + assert(last_extended_error.ee_errno == (uint32_t)cases[i].error); + assert(last_extended_error.ee_origin == SO_EE_ORIGIN_ICMP6); + assert(last_extended_error.ee_type == cases[i].type && last_extended_error.ee_code == cases[i].code); + assert(last_extended_error.ee_info == mtu && !last_extended_error.ee_data && !last_extended_error.ee_pad); + const struct sockaddr_in6 *offender = (const void *)&last_error_offender; + assert(offender->sin6_family == AF_INET6 && !offender->sin6_port && offender->sin6_scope_id == 2); + assert(!memcmp(&offender->sin6_addr, peer, sizeof(*peer))); + frame[56] ^= 1; + net_ipv6_input_on(NULL, 2, frame, length); + assert(socket_error_count == before + 1); + } + puts("PASS real IPv6 ICMP error errno, type/code, MTU, scoped offender and checksum rejection"); +} /** @brief Find the latest sent ICMPv6 message of a type. @param type ICMPv6 type. * @return Captured index or -1. */ static int last_icmp(uint8_t type) @@ -476,6 +549,132 @@ static void test_link_allocation_retry(void) second_nic=false;net_ipv6_detached_on(NULL, second_index); } +/** @brief Check networkd address policy and route priority using the real IPv6 core. */ +static void test_networkd_route_policy(void) +{ + first_nic = true; + nic_ready = true; + fixture_interface_up = true; + net_ipv6_init(); + sent_count = 0; + struct net_ipv6_address local = { + .address.s6_addr = {0x20,1,0x0d,0xb8,0,1,0,0,0,0,0,0,0,0,0,10}, + .ifindex = 2, .prefix_length = 64, .route_metric = 4096, + .flags = NET_IPV6_ADDR_NODAD | NET_IPV6_ADDR_NOPREFIXROUTE | NET_IPV6_ADDR_MANAGETEMPADDR, + .preferred_until = UINT64_MAX, .valid_until = UINT64_MAX}; + unsigned baseline = net_ipv6_routes(NULL, NULL, 0); + assert(!net_ipv6_address_update(NULL, &local, false)); + assert(net_ipv6_routes(NULL, NULL, 0) == baseline); + local.flags &= ~NET_IPV6_ADDR_NOPREFIXROUTE; + assert(!net_ipv6_address_update(NULL, &local, false)); + assert(net_ipv6_routes(NULL, NULL, 0) == baseline + 1); + struct net_ipv6_route snapshot[64]; + unsigned count = net_ipv6_routes(NULL, snapshot, 64); + bool found = false; + for (unsigned i = 0; i < count; ++i) + if (snapshot[i].ifindex == 2 && snapshot[i].prefix_length == 64 && + !memcmp(snapshot[i].destination.s6_addr, local.address.s6_addr, 8)) { + assert(snapshot[i].metric == 4096 && snapshot[i].protocol == RTPROT_KERNEL); + found = true; + } + assert(found); + local.flags |= NET_IPV6_ADDR_NOPREFIXROUTE; + assert(!net_ipv6_address_update(NULL, &local, false)); + assert(net_ipv6_routes(NULL, NULL, 0) == baseline); + struct net_ipv6_address alternate = local; + alternate.address.s6_addr[15] = 11; + assert(!net_ipv6_address_update(NULL, &alternate, false)); + struct net_ipv6_route low = { + .destination.s6_addr = {0x20,1,0x0d,0xb8,0,2}, .ifindex = 2, + .gateway.s6_addr = {0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + .preferred_source = local.address, .prefix_length = 64, .metric = 200, + .preference = 3, .flags = RTF_UP | RTF_GATEWAY, .valid_until = UINT64_MAX}; + struct in6_addr destination = low.destination; + destination.s6_addr[15] = 42; + assert(!net_ipv6_route_update(NULL, &low, false)); + struct net_ipv6_path path; + assert(!net_ipv6_route(NULL, &destination, 0, NULL, &path)); + assert(!memcmp(&path.source, &local.address, 16) && !memcmp(&path.next_hop, &low.gateway, 16)); + struct net_ipv6_route high = low; + high.gateway.s6_addr[15] = 2; + high.preference = 1; + assert(!net_ipv6_route_update(NULL, &high, false)); + assert(!net_ipv6_route(NULL, &destination, 0, NULL, &path)); + assert(!memcmp(&path.next_hop, &high.gateway, 16)); + struct net_ipv6_route priority = high; + priority.metric = 100; + priority.preferred_source = alternate.address; + priority.valid_until = now_ms + 1000; + assert(!net_ipv6_route_update(NULL, &priority, false)); + assert(net_ipv6_routes(NULL, NULL, 0) == baseline + 3); + assert(!net_ipv6_route(NULL, &destination, 0, NULL, &path)); + assert(!memcmp(&path.source, &alternate.address, 16)); + now_ms += 1000; + net_ipv6_poll(); + assert(net_ipv6_routes(NULL, NULL, 0) == baseline + 2); + assert(!net_ipv6_route(NULL, &destination, 0, NULL, &path)); + assert(!memcmp(&path.source, &local.address, 16)); + assert(!net_ipv6_route_update(NULL, &low, true)); + struct net_ipv6_route appended = high; + appended.gateway.s6_addr[15] = 3; + assert(!net_ipv6_route_update(NULL, &appended, false)); + assert(!net_ipv6_route(NULL, &destination, 0, NULL, &path)); + assert(!memcmp(&path.next_hop, &high.gateway, 16)); + net_ipv6_init(); + puts("PASS real IPv6 address flags, prefix metric, preferred source, preference, expires and append order"); +} + +/** @brief Check namespace-owned nexthop replacement, dependent routes and failed creation. */ +static void test_networkd_nexthop_lifecycle(void) +{ + size_t baseline = live_allocations; + struct net_namespace *scopes[2]; + for (unsigned i = 0; i < 2; ++i) { + assert(!net_namespace_create(NULL, &scopes[i])); + scopes[i]->loopback.up = true; + assert(!net_ipv6_link_changed_on(scopes[i], 1, true)); + } + struct net_nexthop next = {.id = 42, .ifindex = 1, .family = AF_INET6, + .gateway.ipv6.s6_addr = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2}}; + size_t before = live_allocations; + allocation_budget = 0; + assert(net_nexthop_update(scopes[0], &next, false, false, true) == -LINUX_ENOMEM); + assert(!net_nexthop_get(scopes[0], 42) && live_allocations == before); + allocation_budget = -1; + assert(!net_nexthop_update(scopes[0], &next, false, false, true)); + assert(!net_nexthop_update(scopes[1], &next, false, false, true)); + assert(!net_nexthop_get(NULL, 42)); + struct net_ipv6_route route = {.destination.s6_addr = {0x20,1,0x0d,0xb8}, + .prefix_length = 64, .ifindex = 1, .gateway = next.gateway.ipv6, + .nexthop_id = 42, .flags = RTF_UP | RTF_GATEWAY, .valid_until = UINT64_MAX}; + assert(!net_ipv6_route_update(scopes[0], &route, false)); + next.gateway.ipv6.s6_addr[15] = 3; + next.flags = RTNH_F_ONLINK; + allocation_budget = 0; + assert(!net_nexthop_update(scopes[0], &next, false, true, false)); + allocation_budget = -1; + struct net_ipv6_route snapshot[4]; + unsigned count = net_ipv6_routes(scopes[0], snapshot, 4); + bool found = false; + for (unsigned i = 0; i < count; ++i) + if (snapshot[i].nexthop_id == 42) { + assert(snapshot[i].onlink && !memcmp(&snapshot[i].gateway, &next.gateway.ipv6, 16)); + found = true; + } + assert(found && net_nexthop_get(scopes[1], 42)->gateway.ipv6.s6_addr[15] == 2); + struct net_nexthop invalid = next; + invalid.ifindex = 2; + assert(net_nexthop_update(scopes[0], &invalid, false, true, false) == -LINUX_ENODEV); + assert(net_nexthop_get(scopes[0], 42)->ifindex == 1); + assert(!net_nexthop_update(scopes[0], &next, true, false, false)); + assert(!net_nexthop_get(scopes[0], 42) && net_ipv6_routes(scopes[0], NULL, 0) == 1); + assert(net_nexthop_get(scopes[1], 42)); + net_namespace_put(scopes[0]); + net_namespace_put(scopes[1]); + assert(live_allocations == baseline); + puts("PASS real nexthop isolation, atomic OOM, replacement, dependent-route deletion and final cleanup"); +} + /** @brief Exercise independent IPv6 tables, deferred work and namespace retirement. */ static void test_namespace_addresses(void) { @@ -640,6 +839,7 @@ int main(void) for(uint32_t i=0;ibefore && last_icmp(135)>=0); @@ -839,6 +1039,8 @@ int main(void) test_many_interfaces(); test_link_allocation_retry(); test_namespace_addresses(); + test_networkd_route_policy(); + test_networkd_nexthop_lifecycle(); puts("PASS IPv6 protocol: loopback, DAD/NDP, checksums, fragments, RA/SLAAC, MLD and timer pump"); #endif return 0; diff --git a/tools/tests/ipv6_tcp_test.c b/tools/tests/ipv6_tcp_test.c index 7ba4f3a5..6e9b55ae 100644 --- a/tools/tests/ipv6_tcp_test.c +++ b/tools/tests/ipv6_tcp_test.c @@ -222,7 +222,9 @@ static void test_tcp6_creating_network(bool mapped) assert(!net_socket_listen_fd(listeners[i], 2)); assert(!net_socket_bind6_fd(clients[i], &local)); uint32_t physical = 2; - assert(net_socket_bound_device(clients[i], true, &physical) == -LINUX_ENODEV); + assert(!net_socket_bound_device(clients[i], true, &physical)); + physical = 0; + assert(!net_socket_bound_device(clients[i], true, &physical)); } current.net_ns = NULL; for (unsigned i = 0; i < 2; ++i) @@ -396,6 +398,10 @@ void net_udp6_error_on(struct net_namespace *ns, uint32_t index, const struct in6_addr *src, const struct in6_addr *dst, uint16_t sport, uint16_t dport, int error, uint32_t mtu) { (void)ns; (void)index; (void)src; (void)dst; (void)sport; (void)dport; (void)error; (void)mtu; abort(); } +void net_udp_error_input(struct net_namespace *ns, uint32_t index, + const uint8_t *packet, uint32_t length, const struct sock_extended_err *error, + const struct sockaddr_storage *offender) +{ (void)ns; (void)index; (void)packet; (void)length; (void)error; (void)offender; abort(); } void netdev_counters(uint32_t index, struct net_proc_counters *out) { (void)index; *out = (struct net_proc_counters){0}; } diff --git a/tools/tests/ipv6_transport_test.c b/tools/tests/ipv6_transport_test.c index 605a2d14..ccca99bc 100644 --- a/tools/tests/ipv6_transport_test.c +++ b/tools/tests/ipv6_transport_test.c @@ -172,11 +172,13 @@ static void test_udp6_namespace_bind(bool mapped) current.net_ns = NULL; uint8_t quote[48] = {0}; quote[0] = 0x60; + net_put_u16(quote + 4, 8); quote[6] = 17; memcpy(quote + 8, &loop6, 16); memcpy(quote + 24, &loop6, 16); net_put_u16(quote + 40, 55111); net_put_u16(quote + 42, 55112); + net_put_u16(quote + 44, 8); net_ipv6_socket_error_on(first, NET_IF_LOOPBACK, quote, sizeof(quote), LINUX_ECONNREFUSED, 0); assert(udp_from_file(&files[a])->error == LINUX_ECONNREFUSED); assert(!udp_from_file(&files[b])->error && !udp_from_file(&files[initial])->error); @@ -252,6 +254,14 @@ static void test_raw6_creating_network(void) (uintptr_t)physical, sizeof(physical), 0) == -LINUX_ENODEV); assert(!syscall_packet(__NR_setsockopt, raw[i], SOL_SOCKET, SO_BINDTODEVICE, (uintptr_t)loopback, sizeof(loopback), 0)); + int selected = NET_IF_LOOPBACK; + assert(!syscall_packet(__NR_setsockopt, raw[i], SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&selected, sizeof(selected), 0)); + selected = -1; + uint32_t option_length = sizeof(selected); + assert(!syscall_packet(__NR_getsockopt, raw[i], SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&selected, (uintptr_t)&option_length, 0)); + assert(selected == NET_IF_LOOPBACK && option_length == sizeof(selected)); uint8_t echo[8] = {128}; assert(task_packet_send(&files[raw[i]], echo, sizeof(echo), 0, 0, 0) == 8); assert(task_packet_available(&files[raw[i]]) == 8); @@ -334,11 +344,21 @@ int main(void) assert(receiver >= 0); struct sockaddr_in6 local = {.sin6_family = AF_INET6, .sin6_port = swap16(55001), .sin6_addr = loop6}; assert(call(__NR_bind, receiver, (uintptr_t)&local, sizeof(local), 0, 0) == 0); + uint32_t output_index = swap32(2); + assert(!call(__NR_setsockopt, fd, SOL_IPV6, IPV6_UNICAST_IF, + (uintptr_t)&output_index, sizeof(output_index))); + assert(task_udp_send(&files[fd], "wrong-link", 10, 0, + (uintptr_t)&local, sizeof(local)) == -LINUX_ENETUNREACH); + assert(!call(__NR_setsockopt, receiver, SOL_IPV6, IPV6_UNICAST_IF, + (uintptr_t)&output_index, sizeof(output_index))); + output_index = swap32(NET_IF_LOOPBACK); + assert(!call(__NR_setsockopt, fd, SOL_IPV6, IPV6_UNICAST_IF, + (uintptr_t)&output_index, sizeof(output_index))); assert(call(__NR_connect, fd, (uintptr_t)&local, sizeof(local), 0, 0) == 0); assert(task_udp_send(&files[fd], "hello6", 6, 0, 0, 0) == 6); struct udp_socket conflict = {.ipv6=true,.ifindex=2,.connected=true, .remote6=loop6,.remote_scope6=1,.remote_port=55001}; - assert(udp6_send(&conflict, "scope", 5, 0, 0) == -LINUX_EINVAL); + assert(udp6_send(&conflict, "scope", 5, 0, 0, NULL) == -LINUX_EINVAL); char payload[16] = {0}; struct sockaddr_in6 source = {0}; uint32_t source_length = sizeof(source); diff --git a/tools/tests/ipv6_vector_stubs.c b/tools/tests/ipv6_vector_stubs.c index f4ddaf59..5a63a46a 100644 --- a/tools/tests/ipv6_vector_stubs.c +++ b/tools/tests/ipv6_vector_stubs.c @@ -1,6 +1,4 @@ /* Unused fixture dependencies trap if reached. */ -/** @brief Fail if this INET-only fixture enters UNIX timestamp collection. */ -__attribute__((noreturn)) void time_clock_get(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_recv(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_recv_staged(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_send(void) { __builtin_trap(); } diff --git a/tools/tests/ipv6_vector_test.c b/tools/tests/ipv6_vector_test.c index 3d92f504..194ed24e 100644 --- a/tools/tests/ipv6_vector_test.c +++ b/tools/tests/ipv6_vector_test.c @@ -66,9 +66,310 @@ static int64_t vector_call(uint64_t number,int fd,struct iovec *iov,uint64_t cou task_lookup_scope_begin(¤t,&frame); return syscall_vector_io(¤t,number,fd,(uintptr_t)iov,count,0,0,0); } + +/** @brief Enter the production native-message path with an owned UDP descriptor. */ +static int64_t message_call(int fd, struct msghdr *message, uint32_t flags, bool receiving) +{ + struct trap_frame frame = {.rax = receiving ? __NR_recvmsg : __NR_sendmsg, + .rdi = (uint64_t)fd, .rsi = (uintptr_t)message, .rdx = flags}; + struct socket_message_result result = {0}; + task_lookup_scope_begin(¤t, &frame); + return task_socket_message(¤t, &files[fd], (uintptr_t)message, + flags, receiving, false, &result); +} + +/** @brief Verify native and mapped error controls through swap-aware recvmsg. */ +static void test_udp_error_recvmsg(void) +{ + for (unsigned variant = 0; variant < 3; ++variant) { + bool ipv4 = variant != 1; + bool socket6 = variant != 0; + int fd = (int)call(__NR_socket, socket6 ? AF_INET6 : AF_INET, + SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + int enabled = 1; + assert(!call(__NR_setsockopt, fd, ipv4 ? SOL_IP : SOL_IPV6, + ipv4 ? IP_RECVERR : IPV6_RECVERR, (uintptr_t)&enabled, sizeof(enabled))); + struct sockaddr_in local4 = {.sin_family = AF_INET, .sin_port = swap16(55132), + .sin_addr.s_addr = swap32(0x7f000001)}; + struct sockaddr_in6 local6 = {.sin6_family = AF_INET6, .sin6_port = local4.sin_port, + .sin6_addr = ipv4 ? udp6_map(0x7f000001) : loop6}; + assert(!call(__NR_bind, fd, socket6 ? (uintptr_t)&local6 : (uintptr_t)&local4, + socket6 ? sizeof(local6) : sizeof(local4), 0, 0)); + uint8_t quote[52] = {0}; + uint32_t header = ipv4 ? 20 : 40; + quote[0] = ipv4 ? 0x45 : 0x60; + if (ipv4) { + net_put_u16(quote + 2, 32); quote[9] = 17; + net_put_u32(quote + 12, 0x7f000001); net_put_u32(quote + 16, 0x7f000002); + } else { + net_put_u16(quote + 4, 12); quote[6] = 17; + memcpy(quote + 8, &loop6, 16); memcpy(quote + 24, &loop6, 16); + } + net_put_u16(quote + header, 55132); net_put_u16(quote + header + 2, 53); + net_put_u16(quote + header + 4, 12); memcpy(quote + header + 8, "dns!", 4); + struct sock_extended_err error = {.ee_errno = LINUX_ECONNREFUSED, + .ee_origin = ipv4 ? SO_EE_ORIGIN_ICMP : SO_EE_ORIGIN_ICMP6, + .ee_type = ipv4 ? 3 : 1, .ee_code = ipv4 ? 3 : 4}; + struct sockaddr_storage offender = {0}; + if (ipv4) memcpy(&offender, &local4, sizeof(local4)); + else memcpy(&offender, &local6, sizeof(local6)); + net_udp_error_input(NULL, 1, quote, header + 12, &error, &offender); + char bytes[8] = {0}; + struct iovec vector = {.iov_base = bytes, .iov_len = sizeof(bytes)}; + union { struct cmsghdr align; unsigned char bytes[80]; } control = {0}; + struct sockaddr_storage destination = {0}; + struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_name = &destination, .msg_namelen = sizeof(destination), + .msg_control = control.bytes, .msg_controllen = sizeof(control.bytes)}; + blocked = (uintptr_t)bytes; + contended = true; + assert(message_call(fd, &message, MSG_ERRQUEUE, true) == KERNEL_SYSCALL_SWAP_CONTENDED); + assert(!bytes[0] && udp_from_file(&files[fd])->errors_queued == 1); + contended = false; + assert(message_call(fd, &message, MSG_ERRQUEUE | MSG_PEEK, true) == 4); + assert(!memcmp(bytes, "dns!", 4) && message.msg_flags == MSG_ERRQUEUE); + uint32_t address_size = socket6 ? sizeof(local6) : sizeof(local4); + assert(message.msg_namelen == address_size); + assert(message.msg_controllen == CMSG_SPACE(sizeof(error) + address_size)); + struct cmsghdr *cmsg = (void *)control.bytes; + assert(cmsg->cmsg_level == (socket6 ? SOL_IPV6 : SOL_IP)); + assert(cmsg->cmsg_type == (socket6 ? IPV6_RECVERR : IP_RECVERR)); + assert(!memcmp(control.bytes + CMSG_LEN(0), &error, sizeof(error))); + const struct sockaddr *from = (const void *)(control.bytes + CMSG_LEN(sizeof(error))); + assert(from->sa_family == (socket6 ? AF_INET6 : AF_INET)); + if (socket6) { + const struct sockaddr_in6 *to = (const void *)&destination; + const struct sockaddr_in6 *source = (const void *)from; + assert(to->sin6_port == swap16(53)); + assert(!memcmp(&to->sin6_addr, ipv4 ? &(struct in6_addr){.s6_addr = + {0,0,0,0,0,0,0,0,0,0,255,255,127,0,0,2}} : &loop6, 16)); + assert(!memcmp(&source->sin6_addr, &local6.sin6_addr, 16)); + } else { + const struct sockaddr_in *to = (const void *)&destination; + assert(to->sin_port == swap16(53) && to->sin_addr.s_addr == swap32(0x7f000002)); + } + task_lookup_scope_cancel(¤t); + message.msg_controllen = sizeof(control.bytes); + assert(message_call(fd, &message, MSG_ERRQUEUE, true) == -LINUX_EAGAIN); + task_lookup_scope_cancel(¤t); + net_udp_error_input(NULL, 1, quote, header + 12, &error, &offender); + message.msg_controllen = CMSG_LEN(2); + assert(message_call(fd, &message, MSG_ERRQUEUE, true) == 4); + assert(message.msg_flags == (MSG_ERRQUEUE | MSG_CTRUNC)); + assert(message.msg_controllen == CMSG_LEN(2)); + task_lookup_scope_cancel(¤t); + close_udp(fd); + } + puts("PASS UDP recvmsg extended errors for IPv4, IPv6 and mapped IPv6 with swap-safe dequeue and CTRUNC"); +} + +/** @brief Verify IPv4 recvmsg ancillary encoding and preparation before dequeue. */ +static void test_ipv4_recvmsg_metadata(void) +{ + int sender = open_socket(), receiver = open_socket(); + int enabled = 1, ttl = 251; + assert(!call(__NR_setsockopt, receiver, SOL_IP, IP_PKTINFO, (uintptr_t)&enabled, sizeof(enabled))); + assert(!call(__NR_setsockopt, receiver, SOL_IP, IP_RECVTTL, (uintptr_t)&enabled, sizeof(enabled))); + assert(!call(__NR_setsockopt, sender, SOL_IP, IP_TTL, (uintptr_t)&ttl, sizeof(ttl))); + assert(!call(__NR_setsockopt, receiver, SOL_SOCKET, SO_TIMESTAMP_NEW, (uintptr_t)&enabled, sizeof(enabled))); + struct sockaddr_in to = {.sin_family = AF_INET, .sin_port = swap16(55121), + .sin_addr.s_addr = swap32(0x7f000001)}; + assert(!call(__NR_bind, receiver, (uintptr_t)&to, sizeof(to), 0, 0)); + struct linux_timespec expected; + assert(!time_clock_get(LINUX_CLOCK_REALTIME, &expected)); + assert(task_udp_send(&files[sender], "meta", 4, 0, (uintptr_t)&to, sizeof(to)) == 4); + ticks += RELIEFNT_TICK_HZ; + char output[8] = {0}; + struct iovec vector = {.iov_base = output, .iov_len = sizeof(output)}; + union { struct cmsghdr align; unsigned char bytes[128]; } control = {0}; + struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_control = control.bytes, .msg_controllen = sizeof(control.bytes)}; + blocked = (uintptr_t)control.bytes + CMSG_SPACE(sizeof(struct in_pktinfo)) + CMSG_SPACE(sizeof(int)) + 4; + contended = true; + assert(message_call(receiver, &message, MSG_PEEK, true) == KERNEL_SYSCALL_SWAP_CONTENDED); + assert(task_udp_available(&files[receiver]) == 4 && !output[0]); + contended = false; + assert(message_call(receiver, &message, MSG_PEEK, true) == 4); + assert(!memcmp(output, "meta", 4) && !message.msg_flags); + assert(message.msg_controllen == CMSG_SPACE(sizeof(struct in_pktinfo)) + CMSG_SPACE(sizeof(int)) + + CMSG_SPACE(sizeof(struct linux_timeval))); + struct cmsghdr *header = (void *)control.bytes; + assert(header->cmsg_level == SOL_IP && header->cmsg_type == IP_PKTINFO); + struct in_pktinfo packet; + memcpy(&packet, control.bytes + CMSG_LEN(0), sizeof(packet)); + assert(packet.ipi_ifindex == 1 && packet.ipi_addr.s_addr == swap32(0x7f000001)); + assert(packet.ipi_spec_dst.s_addr == swap32(0x7f000001)); + header = (void *)(control.bytes + CMSG_SPACE(sizeof(packet))); + int received_ttl; + memcpy(&received_ttl, (unsigned char *)header + CMSG_LEN(0), sizeof(received_ttl)); + assert(header->cmsg_level == SOL_IP && header->cmsg_type == IP_TTL && received_ttl == 251); + header = (void *)(control.bytes + CMSG_SPACE(sizeof(packet)) + CMSG_SPACE(sizeof(int))); + struct linux_timeval timestamp, repeated; + memcpy(×tamp, (unsigned char *)header + CMSG_LEN(0), sizeof(timestamp)); + assert(header->cmsg_level == SOL_SOCKET && header->cmsg_type == SO_TIMESTAMP_NEW); + assert(header->cmsg_len == CMSG_LEN(sizeof(timestamp)) && timestamp.tv_sec == expected.tv_sec); + assert(timestamp.tv_usec == expected.tv_nsec / 1000); + message.msg_controllen = sizeof(control.bytes); + task_lookup_scope_cancel(¤t); + ticks += RELIEFNT_TICK_HZ; + assert(message_call(receiver, &message, MSG_PEEK, true) == 4); + memcpy(&repeated, (unsigned char *)header + CMSG_LEN(0), sizeof(repeated)); + assert(!memcmp(×tamp, &repeated, sizeof(timestamp)) && task_udp_available(&files[receiver]) == 4); + task_lookup_scope_cancel(¤t); + message.msg_controllen = CMSG_LEN(2); + assert(message_call(receiver, &message, 0, true) == 4); + assert(message.msg_flags == MSG_CTRUNC && message.msg_controllen == CMSG_LEN(2)); + assert(task_udp_available(&files[receiver]) == 0); + task_lookup_scope_cancel(¤t); + close_udp(sender); + close_udp(receiver); + puts("PASS IPv4 recvmsg packet info, TTL, timestamp, control truncation and swap-safe PEEK"); +} + +/** @brief Verify IPv6 late timestamp enable, format switching and stable PEEK. */ +static void test_ipv6_timestamp(void) +{ + int sender = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + int receiver = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + struct sockaddr_in6 to = {.sin6_family = AF_INET6, .sin6_port = swap16(55124), .sin6_addr = loop6}; + assert(!call(__NR_bind, receiver, (uintptr_t)&to, sizeof(to), 0, 0)); + assert(task_udp_send(&files[sender], "late", 4, 0, (uintptr_t)&to, sizeof(to)) == 4); + ticks += RELIEFNT_TICK_HZ; + int enabled = 1; + assert(!call(__NR_setsockopt, receiver, SOL_SOCKET, SO_TIMESTAMP_OLD, (uintptr_t)&enabled, sizeof(enabled))); + char bytes[8]; + struct net_udp_rx_info first, repeated; + struct linux_timespec expected; + assert(!time_clock_get(LINUX_CLOCK_REALTIME, &expected)); + assert(task_udp_recv_ex(&files[receiver], bytes, sizeof(bytes), MSG_PEEK, NULL, NULL, &first) == 4); + assert(!first.ipv4 && first.timestamp_option == SO_TIMESTAMP_OLD); + assert(first.timestamp.tv_sec == expected.tv_sec && first.timestamp.tv_usec == expected.tv_nsec / 1000); + ticks += RELIEFNT_TICK_HZ; + assert(!call(__NR_setsockopt, receiver, SOL_SOCKET, SO_TIMESTAMP_NEW, (uintptr_t)&enabled, sizeof(enabled))); + assert(task_udp_recv_ex(&files[receiver], bytes, sizeof(bytes), MSG_PEEK, NULL, NULL, &repeated) == 4); + assert(repeated.timestamp_option == SO_TIMESTAMP_NEW); + assert(!memcmp(&first.timestamp, &repeated.timestamp, sizeof(first.timestamp))); + int state = -1; + uint32_t size = sizeof(state); + assert(!call(__NR_getsockopt, receiver, SOL_SOCKET, SO_TIMESTAMP_OLD, (uintptr_t)&state, (uintptr_t)&size)); + assert(!state && size == sizeof(state)); + enabled = 0; + assert(!call(__NR_setsockopt, receiver, SOL_SOCKET, SO_TIMESTAMP_NEW, (uintptr_t)&enabled, sizeof(enabled))); + assert(task_udp_recv_ex(&files[receiver], bytes, sizeof(bytes), 0, NULL, NULL, &repeated) == 4); + assert(!repeated.timestamp_option && !memcmp(bytes, "late", 4)); + close_udp(sender); + close_udp(receiver); + puts("PASS IPv6 UDP late timestamps, format switching, PEEK stability and disable"); +} + +/** @brief Verify per-message IPv4 routing and TTL without changing socket defaults. */ +static void test_ipv4_sendmsg_metadata(void) +{ + int sender = open_socket(), receiver = open_socket(); + int enabled = 1; + assert(!call(__NR_setsockopt, receiver, SOL_IP, IP_RECVTTL, (uintptr_t)&enabled, sizeof(enabled))); + struct sockaddr_in to = {.sin_family = AF_INET, .sin_port = swap16(55122), + .sin_addr.s_addr = swap32(0x7f000001)}; + assert(!call(__NR_bind, receiver, (uintptr_t)&to, sizeof(to), 0, 0)); + union { struct cmsghdr align; unsigned char bytes[64]; } control = {0}; + struct cmsghdr header = {.cmsg_level = SOL_IP, .cmsg_type = IP_PKTINFO, + .cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo))}; + struct in_pktinfo packet = {.ipi_ifindex = 1, .ipi_spec_dst.s_addr = swap32(0x7f000002)}; + memcpy(control.bytes, &header, sizeof(header)); + memcpy(control.bytes + CMSG_LEN(0), &packet, sizeof(packet)); + size_t offset = CMSG_SPACE(sizeof(packet)); + header = (struct cmsghdr){.cmsg_level = SOL_IP, .cmsg_type = IP_TTL, + .cmsg_len = CMSG_LEN(sizeof(int))}; + int ttl = 247; + memcpy(control.bytes + offset, &header, sizeof(header)); + memcpy(control.bytes + offset + CMSG_LEN(0), &ttl, sizeof(ttl)); + struct iovec vector = {.iov_base = "hint", .iov_len = 4}; + struct msghdr message = {.msg_name = &to, .msg_namelen = sizeof(to), + .msg_iov = &vector, .msg_iovlen = 1, .msg_control = control.bytes, + .msg_controllen = offset + CMSG_SPACE(sizeof(ttl))}; + blocked = (uintptr_t)control.bytes; + contended = true; + assert(message_call(sender, &message, 0, false) == KERNEL_SYSCALL_SWAP_CONTENDED); + assert(!task_udp_available(&files[receiver])); + contended = false; + assert(message_call(sender, &message, 0, false) == 4); + task_lookup_scope_cancel(¤t); + char bytes[8]; + struct sockaddr_in from; + uint32_t from_size; + struct net_udp_rx_info info; + assert(task_udp_recv_ex(&files[receiver], bytes, sizeof(bytes), 0, &from, &from_size, &info) == 4); + assert(!memcmp(bytes, "hint", 4) && from.sin_addr.s_addr == swap32(0x7f000002) && info.hops == 247); + assert(task_udp_send(&files[sender], "base", 4, 0, (uintptr_t)&to, sizeof(to)) == 4); + assert(task_udp_recv_ex(&files[receiver], bytes, sizeof(bytes), 0, &from, &from_size, &info) == 4); + assert(from.sin_addr.s_addr == swap32(0x7f000001) && info.hops == 64); + header.cmsg_len = CMSG_LEN(sizeof(int)) - 1; + memcpy(control.bytes + offset, &header, sizeof(header)); + assert(message_call(sender, &message, 0, false) == -LINUX_EINVAL); + assert(!task_udp_available(&files[receiver])); + task_lookup_scope_cancel(¤t); + packet.ipi_ifindex = -1; + memcpy(control.bytes + CMSG_LEN(0), &packet, sizeof(packet)); + assert(message_call(sender, &message, 0, false) == -LINUX_EINVAL); + task_lookup_scope_cancel(¤t); + close_udp(sender); + close_udp(receiver); + puts("PASS IPv4 sendmsg source/interface/TTL, swap retry and malformed-control rollback"); +} + +/** @brief Verify native IPv6 sendmsg controls and independent socket defaults. */ +static void test_ipv6_sendmsg_metadata(void) +{ + int sender = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + int receiver = (int)call(__NR_socket, AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + int enabled = 1; + assert(!call(__NR_setsockopt, receiver, SOL_IPV6, IPV6_RECVHOPLIMIT, + (uintptr_t)&enabled, sizeof(enabled))); + struct sockaddr_in6 to = {.sin6_family = AF_INET6, .sin6_port = swap16(55123), .sin6_addr = loop6}; + assert(!call(__NR_bind, receiver, (uintptr_t)&to, sizeof(to), 0, 0)); + union { struct cmsghdr align; unsigned char bytes[72]; } control = {0}; + struct cmsghdr header = {.cmsg_level = SOL_IPV6, .cmsg_type = IPV6_PKTINFO, + .cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo))}; + struct in6_pktinfo packet = {.ipi6_addr = loop6, .ipi6_ifindex = 1}; + memcpy(control.bytes, &header, sizeof(header)); + memcpy(control.bytes + CMSG_LEN(0), &packet, sizeof(packet)); + size_t offset = CMSG_SPACE(sizeof(packet)); + header = (struct cmsghdr){.cmsg_level = SOL_IPV6, .cmsg_type = IPV6_HOPLIMIT, + .cmsg_len = CMSG_LEN(sizeof(int))}; + int hops = 249; + memcpy(control.bytes + offset, &header, sizeof(header)); + memcpy(control.bytes + offset + CMSG_LEN(0), &hops, sizeof(hops)); + struct iovec vector = {.iov_base = "ipv6", .iov_len = 4}; + struct msghdr message = {.msg_name = &to, .msg_namelen = sizeof(to), + .msg_iov = &vector, .msg_iovlen = 1, .msg_control = control.bytes, + .msg_controllen = offset + CMSG_SPACE(sizeof(hops))}; + assert(message_call(sender, &message, 0, false) == 4); + task_lookup_scope_cancel(¤t); + char bytes[8]; + struct net_udp_rx_info info; + assert(task_udp_recv_ex(&files[receiver], bytes, sizeof(bytes), 0, NULL, NULL, &info) == 4); + assert(!memcmp(bytes, "ipv6", 4) && info.hops == 249 && info.ifindex == 1); + assert(task_udp_send(&files[sender], "base", 4, 0, (uintptr_t)&to, sizeof(to)) == 4); + assert(task_udp_recv_ex(&files[receiver], bytes, sizeof(bytes), 0, NULL, NULL, &info) == 4); + assert(info.hops == 64); + hops = 256; + memcpy(control.bytes + offset + CMSG_LEN(0), &hops, sizeof(hops)); + assert(message_call(sender, &message, 0, false) == -LINUX_EINVAL); + assert(!task_udp_available(&files[receiver])); + task_lookup_scope_cancel(¤t); + close_udp(sender); + close_udp(receiver); + puts("PASS IPv6 sendmsg interface/source/hop limit and invalid-control rollback"); +} + int main(void) { current=(struct task){.pid=92,.kind=TASK_KIND_USER,.cap_effective=1ULL< #include #include +#include +#include + +static unsigned network_events; +static struct net_namespace *event_scope; +static char event_action[8], event_path[NET_IF_DEVICE_PATH_LEN], event_properties[384]; +static uint32_t event_length; +static unsigned device_events; +static char event_subsystem[16]; + +/** @brief Capture global device publication below the real sysfs provider. */ +void netlink_uevent_device(const char *action, const char *path, const char *subsystem, + const char *properties, uint32_t length) +{ + assert(length <= sizeof(event_properties)); + ++device_events; + snprintf(event_action, sizeof(event_action), "%s", action); + snprintf(event_path, sizeof(event_path), "%s", path); + snprintf(event_subsystem, sizeof(event_subsystem), "%s", subsystem); + memcpy(event_properties, properties, length); + event_length = length; +} + +/** @brief Model the hardware identity copied by the real interface registry. */ +void netdev_get_info(uint32_t index, struct e1000_info *out) +{ + *out = (struct e1000_info){0}; + if (index == 2) + *out = (struct e1000_info){.present = 1, .active = 1, + .vendor_id = 0x8086, .device_id = 0x100e, .slot = 4, + .mac = {2, 0, 0, 0, 0, 2}}; +} + +int netdev_is_ready(uint32_t index) { return index == 2; } + +/** @brief Record copied network events at the netlink boundary. */ +void netlink_uevent_network(struct net_namespace *ns, const char *action, + const char *path, const char *subsystem, + const char *properties, uint32_t length) +{ + assert(!strcmp(subsystem, "net") && length <= sizeof(event_properties)); + ++network_events; + event_scope = ns; + snprintf(event_action, sizeof(event_action), "%s", action); + snprintf(event_path, sizeof(event_path), "%s", path); + memcpy(event_properties, properties, length); + event_length = length; +} + +/** @brief IPv4 route removal and IPv6 setup are outside this inventory fixture. */ +void net_ipv4_routes_remove_interface(struct net_namespace *ns, uint32_t index) +{ assert(!ns && index == 2); } + +int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index, bool up) +{ (void)ns; (void)index; (void)up; return 0; } + +/** @brief Route subscribers are exercised by the dedicated real netlink fixture. */ +void netlink_network_changed(struct net_namespace *ns) { (void)ns; } static unsigned fixture_cpus=1; static uint32_t fixture_foreground; @@ -122,8 +180,13 @@ const struct framebuffer *framebuffer_get(void) } int pci_read_device(uint8_t bus, uint8_t slot, uint8_t fn, struct pci_device *out) { - if (bus || (slot != 2 && slot != 3) || fn) + if (bus || (slot != 2 && slot != 3 && slot != 4) || fn) return -1; + if (slot == 4) { + *out = (struct pci_device){.slot = 4, .vendor_id = 0x8086, + .device_id = 0x100e, .class_code = 2}; + return 0; + } if (slot==3) { *out=(struct pci_device){.bus=bus,.slot=slot,.function=fn, .class_code=1,.subclass=6,.prog_if=1}; @@ -139,7 +202,7 @@ int pci_read_device(uint8_t bus, uint8_t slot, uint8_t fn, struct pci_device *ou } uint32_t pci_config_read32(uint8_t b, uint8_t s, uint8_t f, uint8_t o) { - assert(!b && (s == 2 || s == 3) && !f); + assert(!b && (s == 2 || s == 3 || s == 4) && !f); return o == 0x2c ? 0x11001af4 : 0; } int graphics_service_pci_identity(struct pci_device *out) @@ -301,12 +364,221 @@ static void check_block_subsystem(const char *device, const char *expected) assert(!vfs_namespace_destroy(&ns)); } +/** @brief Exercise retained network views through the real sysfs VFS provider. */ +static void check_network_sysfs(void) +{ + unsigned baseline = proc_allocations; + struct net_namespace *net = NULL; + assert(!net_namespace_create(NULL, &net)); + assert(net->references == 1); + /* Every failed mount allocation must release its captured network. */ + bool mounted = false; + for (int budget = 0; budget < 32; ++budget) { + unsigned allocated = proc_allocations; + struct vfs_mount *attempt = NULL; + proc_allocation_budget = budget; + int rc = sysfs_create_vfs_mount_in_net(net, &attempt); + proc_allocation_budget = -1; + if (!rc) { + vfs_mount_put(attempt); + mounted = true; + } else { + assert(rc == -ENOMEM && !attempt); + } + assert(net->references == 1 && proc_allocations == allocated); + if (mounted) break; + } + assert(mounted); + assert(!net_interface_register(2)); + struct vfs_mount *mount = NULL; + struct vfs_namespace initial = {0}, isolated = {0}; + struct vfs_path root = {0}, other = {0}, alias = {0}, canonical = {0}; + struct vfs_path lo = {0}, event = {0}, stale = {0}, device = {0}, pci = {0}; + assert(!sysfs_create_vfs_mount_in_net(NULL, &mount)); + assert(!vfs_namespace_init(&initial, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&initial, &root)); + assert(!sysfs_create_vfs_mount_in_net(net, &mount)); + assert(net->references == 2); + assert(!vfs_namespace_init(&isolated, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&isolated, &other)); + unsigned failed = 0, passed = 0; + for (int budget = 0; budget < 64; ++budget) { + struct vfs_path attempt = {0}; + proc_allocation_budget = budget; + int rc = vfs_path_lookup(&isolated, &other, &other, + "class/net/lo/ifindex", VFS_LOOKUP_FOLLOW, &attempt); + proc_allocation_budget = -1; + if (rc) { + assert(rc == -ENOMEM && !attempt.mount); + ++failed; + } else { + vfs_path_put(&attempt); + ++passed; + } + assert(net->references == 2); + } + assert(failed && passed); + assert(!vfs_path_lookup(&initial, &root, &root, "class/net/eth0", + VFS_LOOKUP_FOLLOW, &alias)); + assert(!vfs_path_lookup(&initial, &root, &root, + "devices/pci0000:00/0000:00:04.0/net/eth0", VFS_LOOKUP_FOLLOW, &canonical)); + assert(vfs_path_same_inode(&alias, &canonical)); + assert(!vfs_path_lookup(&initial, &root, &canonical, "device", VFS_LOOKUP_FOLLOW, &device)); + assert(!vfs_path_lookup(&initial, &root, &root, "devices/pci0000:00/0000:00:04.0", + VFS_LOOKUP_FOLLOW, &pci)); + assert(vfs_path_same_inode(&device, &pci)); + assert(!vfs_path_lookup(&isolated, &other, &other, "class/net/lo/flags", + VFS_LOOKUP_FOLLOW, &lo)); + char value[128]; + uint32_t got = 0, written = 0; + assert(!vfs_path_read(&lo, 0, value, sizeof(value), &got)); + assert(got == 7 && !memcmp(value, "0x0008\n", 7)); + struct vfs_path missing = {0}; + assert(vfs_path_lookup(&isolated, &other, &other, "class/net/eth0", + VFS_LOOKUP_FOLLOW, &missing) == -ENOENT); + current.net_ns = net; + struct storage_node node; + assert(sysfs_lookup("/sys/class/net/eth0", &node) == -ENOENT); + assert(vfs_path_read(&canonical, 0, value, sizeof(value), &got) == -EISDIR); + assert(!vfs_path_lookup(&initial, &root, &canonical, "ifindex", VFS_LOOKUP_FOLLOW, &stale)); + assert(!vfs_path_read(&stale, 0, value, sizeof(value), &got)); + assert(got == 2 && !memcmp(value, "2\n", 2)); + current.net_ns = NULL; + assert(!vfs_path_lookup(&isolated, &other, &other, "class/net/lo/uevent", + VFS_LOOKUP_FOLLOW, &event)); + struct reliefos_permissions mode; + assert(!vfs_path_permissions(&event, &mode, false) && mode.mode == 0644); + uint32_t saved_fsuid = current.fsuid; + current.fsuid = 1000; + assert(fs_permissions_check_path(¤t, &event, FS_ACCESS_WRITE, false) == -EACCES); + assert(!network_events); + current.fsuid = 0; + assert(!fs_permissions_check_path(¤t, &event, FS_ACCESS_WRITE, false)); + assert(!vfs_path_write(&event, 0, "add\n", 4, &written) && written == 4); + assert(network_events == 1 && event_scope == net && !strcmp(event_action, "add")); + assert(!strcmp(event_path, "/devices/virtual/net/lo")); + const char expected[] = "INTERFACE=lo\0IFINDEX=1\0SYNTH_UUID=0\0"; + assert(event_length == sizeof(expected) - 1 && !memcmp(event_properties, expected, event_length)); + const char trigger[] = "change 12345678-1234-ABCD-1234-123456789abc\n"; + assert(!vfs_path_write(&event, 0, trigger, sizeof(trigger) - 1, &written)); + assert(network_events == 2 && !strcmp(event_action, "change")); + const char uuid_properties[] = "INTERFACE=lo\0IFINDEX=1\0SYNTH_UUID=12345678-1234-ABCD-1234-123456789abc\0"; + assert(event_length == sizeof(uuid_properties) - 1 && + !memcmp(event_properties, uuid_properties, event_length)); + const char *invalid[] = {"bad", "add broken", "add\0x", "change 12345678-1234-ABCD-1234-123456789abz"}; + const uint32_t lengths[] = {3, 10, 5, 43}; + for (unsigned i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { + assert(vfs_path_write(&event, 0, invalid[i], lengths[i], &written) == -EINVAL && !written); + assert(network_events == 2); + } + assert(!vfs_path_remount_options(&other, MS_RDONLY, "")); + assert(vfs_path_write(&event, 0, "add", 3, &written) == -EROFS && !written); + current.fsuid = saved_fsuid; + assert(!net_interface_rename(NULL, 2, "enp0s3")); + assert(network_events == 3 && !event_scope && !strcmp(event_action, "move")); + assert(!strcmp(event_path, "/devices/pci0000:00/0000:00:04.0/net/enp0s3")); + const char renamed[] = "INTERFACE=enp0s3\0IFINDEX=2\0" + "DEVPATH_OLD=/devices/pci0000:00/0000:00:04.0/net/eth0\0"; + assert(event_length == sizeof(renamed) - 1 && !memcmp(event_properties, renamed, event_length)); + assert(vfs_path_lookup(&initial, &root, &root, "class/net/eth0", + VFS_LOOKUP_FOLLOW, &missing) == -ENOENT); + struct vfs_path renamed_type = {0}; + assert(!vfs_path_lookup(&initial, &root, &root, "class/net/enp0s3/name_assign_type", + VFS_LOOKUP_FOLLOW, &renamed_type)); + assert(!vfs_path_read(&renamed_type, 0, value, sizeof(value), &got)); + assert(got == 2 && !memcmp(value, "4\n", 2)); + vfs_path_put(&renamed_type); + net_interface_remove(2); + assert(vfs_path_read(&stale, 0, value, sizeof(value), &got) == -ENOENT); + struct vfs_open_file *opened = NULL; + assert(vfs_file_open(&stale, 0, &opened) == -ENOENT && !opened); + vfs_path_put(&pci); + vfs_path_put(&device); + vfs_path_put(&stale); + vfs_path_put(&event); + vfs_path_put(&lo); + vfs_path_put(&canonical); + vfs_path_put(&alias); + vfs_path_put(&other); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&isolated)); + assert(!vfs_namespace_destroy(&initial)); + assert(net->references == 1); + net_namespace_put(net); + assert(proc_allocations == baseline); + puts("PASS sysfs network alias, PCI identity, retained scope, uevents, removal and OOM cleanup"); +} + +/** @brief Trigger real generated device controls with atomic input validation. */ +static void check_device_uevent(const char *path, const char *subsystem, + const char *properties, uint32_t length) +{ + unsigned baseline = proc_allocations, events = device_events; + struct vfs_mount *mount = NULL; + struct vfs_namespace ns = {0}; + struct vfs_path root = {0}, control = {0}; + assert(!sysfs_create_vfs_mount(&mount)); + assert(!vfs_namespace_init(&ns, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns, &root)); + assert(!vfs_path_lookup(&ns, &root, &root, path, VFS_LOOKUP_FOLLOW, &control)); + assert(!vfs_path_truncate(&control, 0)); + assert(vfs_path_truncate(&control, 1) == -EINVAL); + struct reliefos_permissions mode; + assert(!vfs_path_permissions(&control, &mode, false)); + assert(mode.mode == 0644 && !mode.uid && !mode.gid); + uint32_t saved_fsuid = current.fsuid; + current.fsuid = 1000; + assert(fs_permissions_check_path(¤t, &control, FS_ACCESS_WRITE, false) == -EACCES); + current.fsuid = 0; + assert(!fs_permissions_check_path(¤t, &control, FS_ACCESS_WRITE, false)); + uint32_t written = 0; + assert(!vfs_path_write(&control, 0, "add\n", 4, &written) && written == 4); + assert(!vfs_path_sync_after_write(&control, false)); + assert(device_events == ++events && !strcmp(event_action, "add")); + assert(!strcmp(event_subsystem, subsystem)); + char canonical[RELIEFOS_FS_PATH_LEN]; + assert(!vfs_path_backend_name(&control, canonical, sizeof(canonical))); + canonical[strlen(canonical) - strlen("/uevent")] = 0; + assert(!strcmp(event_path, canonical)); + assert(event_length == length + sizeof("SYNTH_UUID=0")); + assert(!memcmp(event_properties, properties, length)); + assert(!memcmp(event_properties + length, "SYNTH_UUID=0", sizeof("SYNTH_UUID=0"))); + const char trigger[] = "change 12345678-1234-ABCD-1234-123456789abc\n"; + assert(!vfs_path_write(&control, 19, trigger, sizeof(trigger) - 1, &written)); + assert(device_events == ++events && !strcmp(event_action, "change")); + const char uuid[] = "SYNTH_UUID=12345678-1234-ABCD-1234-123456789abc"; + assert(event_length == length + sizeof(uuid)); + assert(!memcmp(event_properties + length, uuid, sizeof(uuid))); + const char *invalid[] = {"", "bad", "add broken", "add\0x"}; + const uint32_t sizes[] = {0, 3, 10, 5}; + for (unsigned i = 0; i < sizeof(sizes) / sizeof(sizes[0]); ++i) { + assert(vfs_path_write(&control, 0, invalid[i], sizes[i], &written) == -EINVAL); + assert(!written && device_events == events); + } + assert(!vfs_path_remount_options(&root, MS_RDONLY, "")); + assert(vfs_path_write(&control, 0, "add", 3, &written) == -EROFS && !written); + assert(vfs_path_truncate(&control, 0) == -EROFS); + assert(device_events == events); + current.fsuid = saved_fsuid; + vfs_path_put(&control); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns)); + assert(proc_allocations == baseline); +} + int main(void) { cpu_inventory_capture(0); check_foreground_sysfs(); + check_network_sysfs(); char value[16384]; struct storage_node node; + assert(!sysfs_lookup("/sys/class/net", &node) && node.type == RELIEFOS_FS_TYPE_DIR); + read_value("/sys/devices/virtual/net/lo/ifindex", value, sizeof(value)); + assert(!strcmp(value, "1\n")); assert(proc_lookup("/sys/dev/block", &node) == 0 && node.type == RELIEFOS_FS_TYPE_DIR); read_value("/sys/devices/platform/leonos-block/sda/dev", value, sizeof(value)); assert(!strcmp(value, "259:0\n")); @@ -316,6 +588,8 @@ int main(void) assert(!strcmp(value, "32768\n")); read_value("/sys/devices/platform/leonos-block/sda/uevent", value, sizeof(value)); assert(!strcmp(value, "MAJOR=259\nMINOR=0\nDEVNAME=sda\nDEVTYPE=disk\nDISKSEQ=16\n")); + const char disk_properties[] = "MAJOR=259\0MINOR=0\0DEVNAME=sda\0DEVTYPE=disk\0DISKSEQ=16\0"; + check_device_uevent("class/block/sda/uevent", "block", disk_properties, sizeof(disk_properties) - 1); assert(proc_readlink("/sys/dev/block/259:1", value, sizeof(value)) > 0); check_block_subsystem("dev/block/259:0", "/devices/platform/leonos-block/sda"); check_block_subsystem("dev/block/259:1", "/devices/platform/leonos-block/sda/sda1"); @@ -402,6 +676,11 @@ int main(void) read_value("/sys/devices/pci0000:00/0000:00:02.0/uevent", value, sizeof(value)); assert(strstr(value, "PCI_SUBSYS_ID=1AF4:1100\n")); assert(strstr(value,"MODALIAS=pci:v00001234d00001111sv00001AF4sd00001100bc03sc00i00\n")); + const char pci_properties[] = "PCI_CLASS=030000\0PCI_ID=1234:1111\0" + "PCI_SUBSYS_ID=1AF4:1100\0PCI_SLOT_NAME=0000:00:02.0\0" + "MODALIAS=pci:v00001234d00001111sv00001AF4sd00001100bc03sc00i00\0"; + check_device_uevent("bus/pci/devices/0000:00:02.0/uevent", "pci", + pci_properties, sizeof(pci_properties) - 1); assert(proc_lookup("/sys/class/drm/card0", &node) == -2); read_value("/sys/devices/virtual/graphics/fb0/virtual_size", value, sizeof(value)); assert(!strcmp(value, "1280,720\n")); @@ -474,6 +753,11 @@ int main(void) value, sizeof(value)) == (int)strlen("../..")); value[strlen("../..")]=0; assert(!strcmp(value, "../..")); + const char card_properties[] = "MAJOR=226\0MINOR=0\0DEVNAME=dri/card0\0DEVTYPE=drm_minor\0"; + check_device_uevent("class/drm/card0/uevent", "drm", card_properties, sizeof(card_properties) - 1); + const char render_properties[] = "MAJOR=226\0MINOR=128\0DEVNAME=dri/renderD128\0DEVTYPE=drm_minor\0"; + check_device_uevent("class/drm/renderD128/uevent", "drm", render_properties, sizeof(render_properties) - 1); + puts("PASS sysfs block, PCI and DRM coldplug: actions, properties, UUID, permissions and readonly"); fixture_render_present = false; assert(proc_lookup("/sys/class/drm/renderD128", &node) == -2); fixture_drm_present = false; diff --git a/tools/tests/modules/network.h b/tools/tests/modules/network.h index d0a2db13..dd08cb95 100644 --- a/tools/tests/modules/network.h +++ b/tools/tests/modules/network.h @@ -6,6 +6,7 @@ #include "../../../net/interface/config.c" #include "../../../net/interface/state.c" #include "../../../net/interface/routes.c" +#include "../../../net/interface/nexthop.c" #include "../../../net/interface/ioctl.c" #include "../../../net/interface/socket.c" #include "../../../net/ipv4/core.c" diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 613ddbe4..6637f75e 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -1607,12 +1607,19 @@ int proc_create_vfs_mount_options(const char *options,struct vfs_mount **out) } int proc_create_vfs_mount(struct vfs_mount **out) {return proc_create_vfs_mount_options("",out);} -int sysfs_create_vfs_mount(struct vfs_mount **out) +static struct net_namespace *sysfs_fixture_network; +int sysfs_create_vfs_mount_in_net(struct net_namespace *network,struct vfs_mount **out) { assert(!vfs_system_namespace()); + sysfs_fixture_network=network; if(initial_sysfs_error){*out=NULL;return -EIO;} return storage_create_vfs_mount(&g_volumes[5],NULL,out); } +int sysfs_create_vfs_mount(struct vfs_mount **out) +{ + const struct task *task=sched_current_task(); + return sysfs_create_vfs_mount_in_net(task ? task->net_ns : NULL,out); +} /** @brief Verify default and explicit access policy on actual boot attachments. * @return None. Uses the production bootstrap/tmpfs graph, restores raw volume * flags and wall clock, and retires every new namespace and volatile shm. @@ -3169,7 +3176,7 @@ static void runtime_sysfs_owner_mount_api(struct vfs_namespace *ns,const struct assert(owner->references==references && network->references==1); } } - assert(opened && owner->references==references+1); + assert(opened && owner->references==references+1 && network->references==2); assert(!(task_descriptor_for_fd(&actor,context)->fd_flags & RELIEFOS_FD_CLOEXEC)); actor.cap_effective=0; assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,6,0,0,0)==-EPERM); @@ -3183,7 +3190,9 @@ static void runtime_sysfs_owner_mount_api(struct vfs_namespace *ns,const struct assert(scoped_mount_call(owned,&actor,__NR_fsconfig,context,6,0,0,0)==-EIO); initial_sysfs_error=false; assert(owner->references==references+1); + assert(sysfs_fixture_network==network && network->references==2); assert(!scoped_mount_call(owned,&actor,__NR_fsconfig,context,6,0,0,0)); + assert(sysfs_fixture_network==network); int mountfd=scoped_mount_call(owned,&actor,__NR_fsmount,context,0,0,0,0); assert(mountfd>=0); struct task_file *mount_file=task_file_for_fd(&actor,mountfd); diff --git a/tools/tests/net_interface_test.c b/tools/tests/net_interface_test.c index de988ae3..274383af 100644 --- a/tools/tests/net_interface_test.c +++ b/tools/tests/net_interface_test.c @@ -18,6 +18,29 @@ void net_ipv6_link_changed(bool up) { (void)up; } int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index, bool up) { (void)ns; (void)index; (void)up; return 0; } void netlink_network_changed(struct net_namespace *ns) { (void)ns; } void netlink_ipv6_changed(struct net_namespace *ns) { (void)ns; } +/** @brief Accept interface notifications at the ioctl fixture's event boundary. + * @param ns Borrowed network. @param action Kernel action. @param devpath Device path. + * @param subsystem Expected network class. @param properties Copied environment. + * @param length Environment bytes including the final terminator. + */ +void netlink_uevent_network(struct net_namespace *ns, const char *action, + const char *devpath, const char *subsystem, + const char *properties, uint32_t length) +{ + (void)ns; + assert(action && devpath && !strcmp(subsystem, "net")); + assert(properties && length && properties[length - 1] == 0); +} +void net_ipv6_nexthop_changed(struct net_namespace *ns, uint32_t id, + const struct net_nexthop *value) +{ (void)ns; (void)id; (void)value; } +void netlink_nexthop_changed(struct net_namespace *ns, const struct net_nexthop *value, bool deleted) +{ (void)ns; (void)value; (void)deleted; } +void net_udp_error_input(struct net_namespace *ns, uint32_t index, + const uint8_t *packet, uint32_t length, + const struct sock_extended_err *error, + const struct sockaddr_storage *offender) +{ (void)ns; (void)index; (void)packet; (void)length; (void)error; (void)offender; abort(); } const uint8_t *e1000_mac(void) { static const uint8_t mac[6] = {2,3,4,5,6,7}; return mac; } uint32_t netdev_next(uint32_t after) { return nic_present && after < 2 ? 2 : 0; } int netdev_is_ready(uint32_t index) { return index == 2 && e1000_is_ready(); } diff --git a/tools/tests/net_multi_interface_test.c b/tools/tests/net_multi_interface_test.c index 9b073fe7..9523d719 100644 --- a/tools/tests/net_multi_interface_test.c +++ b/tools/tests/net_multi_interface_test.c @@ -31,6 +31,18 @@ uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *o { (void)ns; (void)out; (void)capacity; return 0; } uint32_t net_ipv6_routes(struct net_namespace *ns, struct net_ipv6_route *out, uint32_t capacity) { (void)ns; (void)out; (void)capacity; return 0; } + +/** @brief Model an empty IPv4 neighbor snapshot for interface and netlink tests. + * @param ns Borrowed network scope. @param out Optional snapshot storage. + * @param capacity Available entries. @return Zero entries without writing storage. */ +uint32_t net_ipv4_neighbors(struct net_namespace *ns, struct net_ipv4_neighbor *out, uint32_t capacity) +{ (void)ns; (void)out; (void)capacity; return 0; } + +/** @brief Model an empty IPv6 neighbor snapshot for interface and netlink tests. + * @param ns Borrowed network scope. @param out Optional snapshot storage. + * @param capacity Available entries. @return Zero entries without writing storage. */ +uint32_t net_ipv6_neighbors(struct net_namespace *ns, struct net_ipv6_neighbor *out, uint32_t capacity) +{ (void)ns; (void)out; (void)capacity; return 0; } int net_ipv6_address_update(struct net_namespace *ns, const struct net_ipv6_address *address, bool remove) { (void)ns; (void)address; (void)remove; return 0; } int net_ipv6_route_update(struct net_namespace *ns, const struct net_ipv6_route *route, bool remove) @@ -180,7 +192,9 @@ int main(void) net_interface_get(NULL, 2)->config.local_ip = 0; assert(!net_ipv4_route_lookup(NULL, UINT32_MAX, 0, 2, &path)); assert(path.ifindex == 2 && path.source == 0); - struct netlink_socket listener={.groups=RTMGRP_LINK}; + assert(!net_ipv4_route_lookup(NULL, 0xe00000fb, 0, 2, &path)); + assert(path.ifindex == 2 && path.source == 0 && path.next_hop == 0xe00000fb); + struct netlink_socket listener={.groups=RTMGRP_LINK,.rcvbuf=NL_BUFFER_DEFAULT}; netlink_sockets=&listener; assert(!nl_initial_snapshot(NULL)); net_interface_remove(3); diff --git a/tools/tests/net_multinic_data_test.c b/tools/tests/net_multinic_data_test.c index 291a7b34..3303fc64 100644 --- a/tools/tests/net_multinic_data_test.c +++ b/tools/tests/net_multinic_data_test.c @@ -52,9 +52,9 @@ int net_ipv4_route_lookup(struct net_namespace *ns, uint32_t destination, uint32 void net_poll_once(struct net_arp_wait *arp, struct net_ping_wait *ping, struct net_udp_wait *udp, struct net_tcp_wait *tcp) { (void)arp; (void)ping; (void)udp; (void)tcp; ++clock_ms; } -void net_udp_input(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, - uint16_t destination_port, const void *data, uint32_t length, int index) -{ (void)ns; (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; (void)index; } +void net_udp_input_ex(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, + uint16_t destination_port, const void *data, uint32_t length, int index, uint8_t ttl) +{ (void)ns; (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; (void)index; (void)ttl; } static void neighbor(uint32_t index, uint32_t ip, const uint8_t mac[6], uint16_t operation) { @@ -72,11 +72,21 @@ int main(void) const uint32_t peer=0x0a000002; neighbor(2,peer,peer_macs[0],ARP_OPER_REPLY); neighbor(3,peer,peer_macs[1],ARP_OPER_REPLY); + struct net_ipv4_neighbor snapshot[2]; + assert(net_ipv4_neighbors(NULL, NULL, 0) == 2); + assert(net_ipv4_neighbors(NULL, snapshot, 1) == 2); + assert(snapshot[0].ifindex == 2 && snapshot[0].address == peer); + assert(!memcmp(snapshot[0].mac, peer_macs[0], 6)); + assert(net_ipv4_neighbors(NULL, snapshot, 2) == 2); + assert(snapshot[1].ifindex == 3 && snapshot[1].address == peer); + assert(!memcmp(snapshot[1].mac, peer_macs[1], 6)); + assert(!net_ipv4_neighbors((struct net_namespace *)(uintptr_t)1, snapshot, 2)); uint8_t mac[6]; assert(!net_resolve_mac_on(2,peer,20,mac) && !memcmp(mac,peer_macs[0],6)); assert(!net_resolve_mac_on(3,peer,20,mac) && !memcmp(mac,peer_macs[1],6)); assert(!transmissions); net_arp_cache_clear_on(2); + assert(net_ipv4_neighbors(NULL, snapshot, 2) == 1 && snapshot[0].ifindex == 3); assert(!net_resolve_mac_on(3,peer,20,mac) && !memcmp(mac,peer_macs[1],6)); assert(!transmissions); neighbor(3,peer,peer_macs[1],ARP_OPER_REQUEST); @@ -87,11 +97,21 @@ int main(void) assert(!net_ipv4_send_udp_on(NULL,3,0,0x0a000302,55000,55001,"second",6)); assert(wire_index==3 && wire_length==48 && !memcmp(wire,peer_macs[1],6)); assert(!memcmp(wire+6,device_macs[1],6) && net_get_u32(wire+26)==devices[1].config.local_ip); + assert(!net_ipv4_send_udp_options(NULL, 3, 0, 0x0a000302, 55000, 55001, "ttl", 3, 253, true)); + assert(wire[22] == 253 && net_get_u16(wire + 20) == 0x4000); + assert(!net_checksum(wire + 14, 20)); + const uint8_t multicast_mac[6] = {1, 0, 0x5e, 0, 0, 0xfb}; + assert(!net_ipv4_send_udp_options(NULL, 3, 0, 0xe00000fb, 5353, 5353, "mdns", 4, 255, false)); + assert(wire_index == 3 && !memcmp(wire, multicast_mac, sizeof(multicast_mac))); + assert(wire[22] == 255 && !net_get_u16(wire + 20) && !net_checksum(wire + 14, 20)); + assert(net_frame_for_us_on(3, wire)); + wire[3] |= 0x80; + assert(!net_frame_for_us_on(3, wire)); uint32_t before=transmissions; ready[0]=false; assert(net_resolve_mac_on(2,peer,20,mac)==-LINUX_ENETDOWN); assert(!net_ipv4_send_udp_on(NULL,3,0,0x0a000302,55000,55001,"ok",2)); assert(transmissions==before+1 && wire_index==3); - puts("PASS per-interface ARP neighbors, reply identity, UDP output and independent link failure"); + puts("PASS per-interface ARP, UDP TTL/DF, multicast MAC/filter and independent link failure"); return 0; } diff --git a/tools/tests/net_packet_test.c b/tools/tests/net_packet_test.c index c7bc93cf..ee46313e 100644 --- a/tools/tests/net_packet_test.c +++ b/tools/tests/net_packet_test.c @@ -4,6 +4,7 @@ #include #include #include +#include #include "../../net/socket/packet.c" #include "../../net/interface/socket.c" static struct task current; @@ -13,6 +14,7 @@ static uint32_t sent_length; static unsigned allocations; static int allocation_fail_after = -1; static bool fail_fd; +static int64_t realtime_seconds = 123; struct task *sched_current_task(void) { return ¤t; } void *kernel_malloc(size_t n) { @@ -33,6 +35,8 @@ struct task_file *task_file_for_fd(struct task *t, int fd) bool user_range_ok(uint64_t p, uint64_t n) { return p >= 4096 && n < 65536; } bool user_range_writable(uint64_t p, uint64_t n) { return user_range_ok(p,n); } uint64_t time_ticks(void) { return 1; } +int time_clock_get(int clock, struct linux_timespec *value) +{ assert(clock == LINUX_CLOCK_REALTIME); *value = (struct linux_timespec){realtime_seconds, 456789000}; return 0; } void sched_sleep_current_until(uint64_t deadline) { (void)deadline; } void net_poll_packets(void) {} void kernel_poll_readiness_notify(void) {} @@ -196,8 +200,154 @@ static void test_packet_creating_network(int family) puts("PASS IPv4 raw/AF_PACKET creating-net ingress, OFD device scope, detach and queued release"); } +/** @brief Exercise the LLDP socket's zero-protocol bind and multicast setup. */ +static void test_lldp_socket(void) +{ + struct task saved = current; + current.cap_effective = 1ULL << CAP_NET_RAW; + assert(syscall_packet(__NR_socket, AF_PACKET, SOCK_RAW | SOCK_NONBLOCK, + __builtin_bswap16(0x88cc), 0, 0, 0) == 3); + struct sockaddr_ll address = {.sll_family = AF_PACKET, .sll_ifindex = 2}; + assert(!syscall_packet(__NR_bind, 3, (uintptr_t)&address, sizeof(address), 0, 0, 0)); + assert(packet_of(&description)->protocol == __builtin_bswap16(0x88cc)); + struct sock_filter code[] = { + BPF_STMT(BPF_LD | BPF_H | BPF_ABS, 12), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x88cc, 0, 1), + BPF_STMT(BPF_RET | BPF_K, 24), + BPF_STMT(BPF_RET | BPF_K, 0), + }; + struct sock_fprog filter = {.len = 4, .filter = code}; + assert(!syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_ATTACH_FILTER, + (uintptr_t)&filter, sizeof(filter), 0)); + struct packet_mreq group = {.mr_ifindex = 2, .mr_type = PACKET_MR_MULTICAST, + .mr_alen = 6, .mr_address = {1, 0x80, 0xc2, 0, 0, 0x0e}}; + uint8_t frame[32] = {1, 0x80, 0xc2, 0, 0, 0x0e}; + frame[12] = 0x88; + frame[13] = 0xcc; + net_packet_input_on(NULL, 2, frame, sizeof(frame)); + assert(!task_packet_available(&description)); + allocation_fail_after = 0; + assert(syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group), 0) == -LINUX_ENOBUFS); + allocation_fail_after = -1; + assert(!packet_of(&description)->memberships); + group.mr_ifindex = 9; + assert(syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group), 0) == -LINUX_ENODEV); + group.mr_ifindex = 2; + group.mr_alen = 5; + assert(syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group), 0) == -LINUX_EINVAL); + group.mr_alen = 6; + for (unsigned i = 0; i < 2; ++i) + assert(!syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group), 0)); + assert(packet_of(&description)->memberships->references == 2); + allocation_fail_after = 0; + assert(syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_ATTACH_FILTER, + (uintptr_t)&filter, sizeof(filter), 0) == -LINUX_ENOMEM); + allocation_fail_after = -1; + code[3].code = 0xffff; + assert(syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_ATTACH_FILTER, + (uintptr_t)&filter, sizeof(filter), 0) == -LINUX_EINVAL); + net_packet_input_on(NULL, 3, frame, sizeof(frame)); + frame[5] = 3; + net_packet_input_on(NULL, 2, frame, sizeof(frame)); + assert(!task_packet_available(&description)); + frame[5] = 0x0e; + net_packet_input_on(NULL, 2, frame, sizeof(frame)); + assert(task_packet_available(&description) == 24); + uint8_t received[32]; + assert(task_packet_recv(&description, received, sizeof(received), 0, 0, 0) == 24); + assert(!memcmp(frame, received, 24)); + struct task_file subscriber = description; + assert(syscall_packet(__NR_socket, AF_PACKET, SOCK_RAW | SOCK_NONBLOCK, + __builtin_bswap16(3), 0, 0, 0) == 3); + struct task_file observer = description; + description = subscriber; + assert(!syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_DROP_MEMBERSHIP, + (uintptr_t)&group, sizeof(group), 0)); + net_packet_input_on(NULL, 2, frame, sizeof(frame)); + assert(task_packet_recv(&description, received, sizeof(received), 0, 0, 0) == 24); + assert(task_packet_recv(&observer, received, sizeof(received), 0, 0, 0) == 32); + assert(!syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_DROP_MEMBERSHIP, + (uintptr_t)&group, sizeof(group), 0)); + assert(!syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_DROP_MEMBERSHIP, + (uintptr_t)&group, sizeof(group), 0)); + net_packet_input_on(NULL, 2, frame, sizeof(frame)); + assert(!task_packet_available(&observer) && !task_packet_available(&description)); + assert(!syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group), 0)); + task_packet_release(&description); + net_packet_input_on(NULL, 2, frame, sizeof(frame)); + assert(!task_packet_available(&observer)); + task_packet_release(&observer); + assert(!allocations); + current = saved; + puts("PASS LLDP zero-protocol bind, classic BPF and multicast socket initialization"); +} + +/** @brief Verify packet timestamp/auxdata snapshots, truncation and detach cleanup. */ +static void test_packet_metadata(void) +{ + struct task saved = current; + current.cap_effective = 1ULL << CAP_NET_RAW; + for (unsigned raw = 0; raw < 2; ++raw) { + assert(syscall_packet(__NR_socket, AF_PACKET, (raw ? SOCK_RAW : SOCK_DGRAM) | SOCK_NONBLOCK, + __builtin_bswap16(0x0800), 0, 0, 0) == 3); + int enabled = 1; + int priority = 7; + assert(!syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&priority, sizeof(priority), 0)); + current.cap_effective = 0; + priority = 8; + assert(syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&priority, sizeof(priority), 0) == -LINUX_EPERM); + assert(packet_of(&description)->priority == 7); + current.cap_effective = 1ULL << CAP_NET_RAW; + assert(!syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_TIMESTAMP_NEW, + (uintptr_t)&enabled, sizeof(enabled), 0)); + assert(!syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_AUXDATA, + (uintptr_t)&enabled, sizeof(enabled), 0)); + int queried = 0; + uint32_t length = sizeof(queried); + assert(!syscall_packet(__NR_getsockopt, 3, SOL_PACKET, PACKET_AUXDATA, + (uintptr_t)&queried, (uintptr_t)&length, 0)); + assert(queried == 1 && length == sizeof(queried)); + uint8_t frame[42] = {255, 255, 255, 255, 255, 255}; + frame[12] = 8; + realtime_seconds = 123; + net_packet_input_on(NULL, 2, frame, sizeof(frame)); + realtime_seconds = 321; + struct net_udp_rx_info info = {0}; + uint8_t received[16]; + for (unsigned peek = 0; peek < 2; ++peek) { + assert(task_packet_recv_ex(&description, received, sizeof(received), + MSG_TRUNC | (peek ? 0 : MSG_PEEK), NULL, NULL, &info) == (raw ? 42 : 28)); + assert(info.timestamp_option == SO_TIMESTAMP_NEW && info.timestamp.tv_sec == 123 && + info.timestamp.tv_usec == 456789); + assert(info.packet_auxdata && info.auxdata.tp_status == TP_STATUS_USER); + assert(info.auxdata.tp_len == (raw ? 42u : 28u) && info.auxdata.tp_snaplen == info.auxdata.tp_len); + assert(info.auxdata.tp_mac == 0 && info.auxdata.tp_net == (raw ? 14 : 0)); + } + struct packet_mreq group = {.mr_ifindex = 2, .mr_type = PACKET_MR_MULTICAST, + .mr_alen = 6, .mr_address = {1, 0x80, 0xc2, 0, 0, 0x0e}}; + assert(!syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group), 0)); + net_packet_device_detached(2); + assert(!packet_of(&description)->memberships); + task_packet_release(&description); + } + realtime_seconds = 123; + current = saved; + assert(!allocations); + puts("PASS RAW/DGRAM receive timestamp, PEEK, packet auxdata and detach cleanup"); +} + int main(void) { + test_lldp_socket(); + test_packet_metadata(); test_packet_namespace_owner(); test_packet_creating_network(AF_INET); test_packet_creating_network(AF_PACKET); diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 3265d2a1..9706010e 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -1550,6 +1550,7 @@ "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/sched/user_namespace.c", + "net/socket/filter.c", "-o", "{tmp}/packet-user-candidate-1" ] @@ -2247,6 +2248,8 @@ "tools/tests/task8_host_stubs/inet_available_unreached.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "kernel/sched/user_namespace.c", + "net/namespace/namespace.c", + "net/ipv6/state.c", "-o", "{tmp}/socket-receive-collector-green-2" ] @@ -2431,6 +2434,34 @@ "{tmp}/timerfd-user-green-1" ] }, + { + "name": "timerfd-clock", + "commands": [ + [ + "clang", + "-std=c11", + "-O1", + "-g", + "-DCONFIG_SWAP=1", + "-fsanitize=address,undefined", + "-fno-sanitize-recover=all", + "-fno-pie", + "-no-pie", + "-ffunction-sections", + "-fdata-sections", + "-Wl,--gc-sections", + "-Iinclude", + "-Iinclude/uapi", + "tools/tests/task8_timerfd_clock_test.c", + "tools/tests/task8_host_stubs/unscoped_lookup.c", + "-o", + "{tmp}/timerfd-clock" + ] + ], + "run": [ + "{tmp}/timerfd-clock" + ] + }, { "name": "transfer-signal", "commands": [ @@ -4331,6 +4362,8 @@ "tools/tests/task8_host_stubs/device_page_unreached.c", "kernel/device/mapping.c", "kernel/sched/user_namespace.c", + "net/namespace/namespace.c", + "net/ipv6/state.c", "-o", "{tmp}/fix1-device-socket" ] @@ -4602,6 +4635,7 @@ "kernel/sched/user_namespace.c", "net/namespace/namespace.c", "net/ipv6/state.c", + "net/socket/filter.c", "-o", "{tmp}/fix1-inet-packet-probe" ] diff --git a/tools/tests/task8_host_stubs/descriptor_unreached.c b/tools/tests/task8_host_stubs/descriptor_unreached.c index 55ad46c6..e7d6482c 100644 --- a/tools/tests/task8_host_stubs/descriptor_unreached.c +++ b/tools/tests/task8_host_stubs/descriptor_unreached.c @@ -29,6 +29,7 @@ UNREACHED(net_socket_bound_device) UNREACHED(net_interface_device_option) UNREACHED(net_socket_nodelay) UNREACHED(net_socket_ipv6_option) +UNREACHED(net_socket_ipv4_option) UNREACHED(net_socket_is_listening) UNREACHED(net_socket_wait_readable) UNREACHED(net_socket_reuse) diff --git a/tools/tests/task8_host_stubs/fix1-packet-front-unreached.c b/tools/tests/task8_host_stubs/fix1-packet-front-unreached.c index 01d230d7..6fb48155 100644 --- a/tools/tests/task8_host_stubs/fix1-packet-front-unreached.c +++ b/tools/tests/task8_host_stubs/fix1-packet-front-unreached.c @@ -113,4 +113,6 @@ UNREACHED(task_netlink_recv_staged) UNREACHED(task_netlink_send) UNREACHED(task_udp_address_size) UNREACHED(task_udp_recv_ex) -UNREACHED(time_clock_get) +UNREACHED(task_udp_send_ex) +UNREACHED(task_udp_namespace) +UNREACHED(net_interface_get_config) diff --git a/tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c b/tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c index 60656db2..f232905e 100644 --- a/tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c +++ b/tools/tests/task8_host_stubs/fix1-tcp-front-unreached.c @@ -67,8 +67,6 @@ __attribute__((noreturn)) void task_file_put(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void task_file_reference(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ -__attribute__((noreturn)) void task_lookup_user_bytes(void) { __builtin_trap(); } -/** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void task_packet_address_size(void) { __builtin_trap(); } /** @brief Trap an unrelated branch. */ __attribute__((noreturn)) void task_pty_export_fd(void) { __builtin_trap(); } @@ -95,3 +93,7 @@ __attribute__((noreturn)) void task_packet_recv_ex(void) { __builtin_trap(); } __attribute__((noreturn)) void task_udp_recv_ex(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_cancel_wait(void) { __builtin_trap(); } __attribute__((noreturn)) void syscall_netlink(void) { __builtin_trap(); } +/** @brief Trap UDP ancillary sending in the TCP-only syscall fixture. */ +__attribute__((noreturn)) void task_udp_send_ex(void) { __builtin_trap(); } +/** @brief Trap UDP scope lookup in the TCP-only syscall fixture. */ +__attribute__((noreturn)) void task_udp_namespace(void) { __builtin_trap(); } diff --git a/tools/tests/task8_host_stubs/fix1-timerfd-entry.c b/tools/tests/task8_host_stubs/fix1-timerfd-entry.c index d0feb97a..9a7a72c7 100644 --- a/tools/tests/task8_host_stubs/fix1-timerfd-entry.c +++ b/tools/tests/task8_host_stubs/fix1-timerfd-entry.c @@ -45,3 +45,14 @@ __attribute__((noreturn)) void syscall_mm_mincore_reclaim(void) { __builtin_trap __attribute__((noreturn)) void syscall_open_path_reclaim(void) { __builtin_trap(); } /** @brief Trap ordinary read reclaim in this unrelated entry fixture. */ __attribute__((noreturn)) void syscall_regular_read_reclaim(void) { __builtin_trap(); } + +/** @brief Trap unrelated pipe admission in the timer-only fixture. */ +__attribute__((noreturn)) void kernel_execution_try_read_lock_irqsave(void) { __builtin_trap(); } +/** @brief Trap unrelated pipe unlock in the timer-only fixture. */ +__attribute__((noreturn)) void kernel_execution_read_unlock_irqrestore(void) { __builtin_trap(); } +/** @brief Trap unrelated pipe CPU lookup in the timer-only fixture. */ +__attribute__((noreturn)) void smp_current_cpu(void) { __builtin_trap(); } +/** @brief Trap unrelated pipe page checks in the timer-only fixture. */ +__attribute__((noreturn)) void address_space_user_page_copyable(void) { __builtin_trap(); } +/** @brief Trap unrelated pipe transfer in the timer-only fixture. */ +__attribute__((noreturn)) void task_pipe_try_io(void) { __builtin_trap(); } diff --git a/tools/tests/task8_host_stubs/inet-message-user-candidate-3-inet-message-user-candidate-3.stub.c b/tools/tests/task8_host_stubs/inet-message-user-candidate-3-inet-message-user-candidate-3.stub.c index 6535bdfe..ff24067e 100644 --- a/tools/tests/task8_host_stubs/inet-message-user-candidate-3-inet-message-user-candidate-3.stub.c +++ b/tools/tests/task8_host_stubs/inet-message-user-candidate-3-inet-message-user-candidate-3.stub.c @@ -1,5 +1,7 @@ /* SPDX-License-Identifier: Apache-2.0 */ /* Unreached host-fixture dependencies trap if invoked. */ +/** @brief Trap TCP namespace lookup outside the datagram fixture. */ +__attribute__((noreturn)) void net_socket_namespace(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled address_space_user_page_flags. */ __attribute__((noreturn)) void address_space_user_page_flags(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled address_space_user_page_phys. */ @@ -154,6 +156,8 @@ int net_socket_family(int handle) } /** @brief Trap if the fixture reaches unmodeled net_socket_ipv6_option. */ __attribute__((noreturn)) void net_socket_ipv6_option(void) { __builtin_trap(); } +/** @brief Trap IPv4 TCP options outside the UDP fixture. */ +__attribute__((noreturn)) void net_socket_ipv4_option(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled net_socket_is_listening. */ __attribute__((noreturn)) void net_socket_is_listening(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled net_socket_listen_fd. */ @@ -182,5 +186,3 @@ __attribute__((noreturn)) void task_netlink_recv_staged(void) { __builtin_trap() __attribute__((noreturn)) void task_netlink_send(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled task_packet_recv_ex. */ __attribute__((noreturn)) void task_packet_recv_ex(void) { __builtin_trap(); } -/** @brief Trap if the fixture reaches unmodeled time_clock_get. */ -__attribute__((noreturn)) void time_clock_get(void) { __builtin_trap(); } diff --git a/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c b/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c index dfe817d0..fc8cfc33 100644 --- a/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c +++ b/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c @@ -1,6 +1,8 @@ /* SPDX-License-Identifier: Apache-2.0 */ /* Unreached host-fixture dependencies trap if invoked. */ #include +#include +#include struct net_namespace; struct in6_addr; @@ -86,13 +88,13 @@ __attribute__((noreturn)) int net_ipv6_output(struct net_namespace *ns, (void)multicast_loop; __builtin_trap(); } -/** @brief Trap if the fixture reaches unmodeled net_udp_input. */ -__attribute__((noreturn)) void net_udp_input(struct net_namespace *ns, +/** @brief Trap if the ioctl-only fixture receives a UDP datagram. */ +__attribute__((noreturn)) void net_udp_input_ex(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, uint16_t destination_port, - const void *data, uint32_t length, int ifindex) + const void *data, uint32_t length, int ifindex, uint8_t ttl) { (void)ns; (void)source; (void)destination; (void)source_port; - (void)destination_port; (void)data; (void)length; (void)ifindex; + (void)destination_port; (void)data; (void)length; (void)ifindex; (void)ttl; __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled sched_sleep_current_until. */ @@ -104,9 +106,11 @@ __attribute__((noreturn)) void storage_inode_get(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled task_packet_available. */ __attribute__((noreturn)) void task_packet_available(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled task_udp_available. */ -__attribute__((noreturn)) void task_udp_available(void) { __builtin_trap(); } +__attribute__((noreturn)) int task_udp_available(struct task_file *file) +{ (void)file; __builtin_trap(); } /** @brief Trap if the ioctl-only fixture queries netlink receive bytes. */ -__attribute__((noreturn)) void task_netlink_available(void) { __builtin_trap(); } +__attribute__((noreturn)) int task_netlink_available(const struct task_file *file) +{ (void)file; __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled time_set_wall_clock. */ __attribute__((noreturn)) void time_set_wall_clock(void) { __builtin_trap(); } /** @brief Trap if the fixture reaches unmodeled time_ticks. */ diff --git a/tools/tests/task8_host_stubs/packet_tcp_unreached.c b/tools/tests/task8_host_stubs/packet_tcp_unreached.c index 17cd4d52..55e0eade 100644 --- a/tools/tests/task8_host_stubs/packet_tcp_unreached.c +++ b/tools/tests/task8_host_stubs/packet_tcp_unreached.c @@ -15,6 +15,7 @@ UNREACHED(net_socket_bound_device) UNREACHED(net_socket_connect6_fd) UNREACHED(net_socket_family) UNREACHED(net_socket_ipv6_option) +UNREACHED(net_socket_ipv4_option) UNREACHED(net_socket_is_listening) UNREACHED(net_socket_listen_fd) UNREACHED(net_socket_namespace) diff --git a/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c b/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c index 15700c39..34668a00 100644 --- a/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c +++ b/tools/tests/task8_host_stubs/socket-receive-collector-green-2-socket_dispatch_stubs.c @@ -12,5 +12,8 @@ TRAP(net_interface_device_option) TRAP(net_socket_accept_commit) TRAP(net_socket_accept_peek) TRAP(net_socket_address6) TRAP(net_socket_bind6_fd) TRAP(net_socket_bound_device) TRAP(net_socket_connect6_fd) TRAP(net_socket_family) TRAP(net_socket_ipv6_option) TRAP(net_socket_is_listening) TRAP(net_socket_listen_fd) +TRAP(net_socket_ipv4_option) +TRAP(net_socket_namespace) TRAP(task_udp_namespace) TRAP(task_udp_send_ex) +TRAP(net_interface_get_config) TRAP(net_interface_for_ipv4) TRAP(net_socket_nodelay) TRAP(net_socket_reuse) TRAP(net_socket_set_ipv6) TRAP(net_socket_wait_readable) diff --git a/tools/tests/task8_inet_packet_probe_test.c b/tools/tests/task8_inet_packet_probe_test.c index 23f08c7c..34aae357 100644 --- a/tools/tests/task8_inet_packet_probe_test.c +++ b/tools/tests/task8_inet_packet_probe_test.c @@ -12,6 +12,74 @@ int task_udp_recv_staged(struct task_file *file,void *data,uint32_t length,uint3 int task_udp_recv(struct task_file *file,void *data,uint32_t length,uint32_t flags,uint64_t address,uint64_t address_length) { (void)file;(void)data;(void)length;(void)flags;(void)address;(void)address_length;abort(); } +/** @brief Check real recvmsg ancillary output before the queued frame is consumed. + * @param destination Bound link destination used to inject a DHCP-sized frame. */ +static void test_packet_ancillary(const struct sockaddr_ll *destination) +{ + int enabled = 1; + assert(!syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_TIMESTAMP_OLD, + (uintptr_t)&enabled, sizeof(enabled), 0)); + assert(!syscall_packet(__NR_setsockopt, 3, SOL_PACKET, PACKET_AUXDATA, + (uintptr_t)&enabled, sizeof(enabled), 0)); + realtime_seconds = 444; + assert(task_packet_send(&description, "dhcp", 4, 0, + (uintptr_t)destination, sizeof(*destination)) == 4); + net_packet_input(sent, sent_length); + realtime_seconds = 555; + char payload[8] = {0}; + uint8_t control[CMSG_SPACE(sizeof(struct linux_timeval)) + CMSG_SPACE(sizeof(struct tpacket_auxdata))] = {0}; + struct iovec vector = {.iov_base = payload, .iov_len = sizeof(payload)}; + struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_control = control, .msg_controllen = sizeof(control)}; + struct msghdr returned = {0}; + struct socket_message_result result = {0}; + blocked = (uintptr_t)control + CMSG_SPACE(sizeof(struct linux_timeval)) + 4; + contended = true; + assert(inet_message(&description, (uintptr_t)&returned, message, 0, true, + sizeof(payload), &result) == KERNEL_SYSCALL_SWAP_CONTENDED); + assert(task_packet_available(&description) == 4); + contended = false; + for (unsigned peek = 0; peek < 2; ++peek) { + result = (struct socket_message_result){0}; + assert(inet_message(&description, (uintptr_t)&returned, message, MSG_PEEK, true, + sizeof(payload), &result) == 4); + assert(!memcmp(payload, "dhcp", 4) && returned.msg_controllen == sizeof(control)); + assert(!(returned.msg_flags & MSG_CTRUNC) && task_packet_available(&description) == 4); + struct cmsghdr header; + struct linux_timeval timestamp; + memcpy(&header, control, sizeof(header)); + memcpy(×tamp, control + CMSG_LEN(0), sizeof(timestamp)); + assert(header.cmsg_level == SOL_SOCKET && header.cmsg_type == SO_TIMESTAMP_OLD); + assert(header.cmsg_len == CMSG_LEN(sizeof(timestamp))); + assert(timestamp.tv_sec == 444 && timestamp.tv_usec == 456789); + struct tpacket_auxdata auxdata; + memcpy(&header, control + CMSG_SPACE(sizeof(timestamp)), sizeof(header)); + memcpy(&auxdata, control + CMSG_SPACE(sizeof(timestamp)) + CMSG_LEN(0), sizeof(auxdata)); + assert(header.cmsg_level == SOL_PACKET && header.cmsg_type == PACKET_AUXDATA); + assert(header.cmsg_len == CMSG_LEN(sizeof(auxdata))); + assert(auxdata.tp_status == TP_STATUS_USER && auxdata.tp_len == 4 && auxdata.tp_snaplen == 4); + assert(!auxdata.tp_mac && !auxdata.tp_net && !auxdata.tp_vlan_tci && !auxdata.tp_vlan_tpid); + } + assert(!syscall_packet(__NR_setsockopt, 3, SOL_SOCKET, SO_TIMESTAMP_NEW, + (uintptr_t)&enabled, sizeof(enabled), 0)); + message.msg_controllen = CMSG_LEN(4); + result = (struct socket_message_result){0}; + assert(inet_message(&description, (uintptr_t)&returned, message, MSG_PEEK, true, + sizeof(payload), &result) == 4); + assert(returned.msg_controllen == CMSG_LEN(4) && (returned.msg_flags & MSG_CTRUNC)); + struct cmsghdr header; + memcpy(&header, control, sizeof(header)); + assert(header.cmsg_type == SO_TIMESTAMP_NEW && header.cmsg_len == CMSG_LEN(4)); + message.msg_control = NULL; + message.msg_controllen = 0; + result = (struct socket_message_result){0}; + assert(inet_message(&description, (uintptr_t)&returned, message, 0, true, + sizeof(payload), &result) == 4); + assert(!returned.msg_controllen && (returned.msg_flags & MSG_CTRUNC)); + assert(!(task_packet_poll(&description, POLLIN) & POLLIN)); + puts("PASS packet recvmsg timestamp/auxdata, stable PEEK, CTRUNC and pre-dequeue user wait"); +} + int main(void) { current=(struct task){.pid=93,.kind=TASK_KIND_USER,.cap_effective=1ULL<ipv6 = family != 0; + int index = NET_IF_LOOPBACK; + current_task.cap_effective |= 1ULL << CAP_NET_RAW; + assert(!syscall_socket_dispatch(__NR_setsockopt, 3, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index), 0)); + index = -1; + uint32_t index_length = sizeof(index); + assert(!syscall_socket_dispatch(__NR_getsockopt, 3, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, (uintptr_t)&index_length, 0)); + assert(index == NET_IF_LOOPBACK && index_length == sizeof(index)); + index = 99; + assert(!syscall_socket_dispatch(__NR_setsockopt, 3, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index), 0)); + index = 0; + assert(!syscall_socket_dispatch(__NR_setsockopt, 3, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index), 0)); + int ttl = 241; + assert(!syscall_socket_dispatch(__NR_setsockopt, 3, SOL_IP, IP_TTL, + (uintptr_t)&ttl, sizeof(ttl), 0)); + unsigned char short_value[3] = {73, 0xaa, 0xbb}; + assert(!syscall_socket_dispatch(__NR_setsockopt, 3, SOL_IP, IP_TTL, + (uintptr_t)short_value, sizeof(short_value), 0)); + uint32_t length = sizeof(short_value); + memset(short_value, 0xcc, sizeof(short_value)); + assert(!syscall_socket_dispatch(__NR_getsockopt, 3, SOL_IP, IP_TTL, + (uintptr_t)short_value, (uintptr_t)&length, 0)); + assert(length == 1 && short_value[0] == 73 && short_value[1] == 0xcc); + int modes[] = {IP_PKTINFO, IP_RECVTTL, IP_MTU_DISCOVER}; + for (unsigned i = 0; i < sizeof(modes) / sizeof(modes[0]); ++i) { + int value = i == 2 ? IP_PMTUDISC_PROBE : 1; + assert(!syscall_socket_dispatch(__NR_setsockopt, 3, SOL_IP, modes[i], + (uintptr_t)&value, sizeof(value), 0)); + int actual = -1; + length = sizeof(actual); + assert(!syscall_socket_dispatch(__NR_getsockopt, 3, SOL_IP, modes[i], + (uintptr_t)&actual, (uintptr_t)&length, 0)); + assert(actual == value && length == sizeof(actual)); + } + ttl = 256; + assert(syscall_socket_dispatch(__NR_setsockopt, 3, SOL_IP, IP_TTL, + (uintptr_t)&ttl, sizeof(ttl), 0) == -LINUX_EINVAL); + length = sizeof(ttl); + assert(!syscall_socket_dispatch(__NR_getsockopt, 3, SOL_IP, IP_TTL, + (uintptr_t)&ttl, (uintptr_t)&length, 0)); + assert(ttl == 73); + assert(syscall_socket_dispatch(__NR_setsockopt, 3, SOL_IP, IP_TTL, + (uintptr_t)&ttl, 0, 0) == -LINUX_EINVAL); + } + socket->ipv6 = false; + puts("PASS native and mapped TCP SOL_IP scalar sizes, TTL, receive options and PMTU"); +} + int main(void) { current_task.kind=TASK_KIND_USER;current_task.pid=7; @@ -63,6 +133,7 @@ int main(void) struct task_file *file=&tcp_file; *file=(struct task_file){.flags=TASK_FILE_FLAG_SOCKET|TASK_FILE_FLAG_SOCKET_INET|RELIEFOS_O_NONBLOCK, .aux=socket->handle}; + test_tcp_ipv4_option_frontdoor(socket); uint32_t count=99;char out[16]={0};blocked_byte=(uintptr_t)out; assert(inet_receive_probe(file,sizeof(out),0,&count)==-LINUX_EAGAIN); socket->rx_head=0;socket->rx_len=3;memcpy(socket->rx,"abc",3);blocked_byte=(uintptr_t)out+3; diff --git a/tools/tests/task8_timerfd_clock_test.c b/tools/tests/task8_timerfd_clock_test.c new file mode 100644 index 00000000..f3cd803c --- /dev/null +++ b/tools/tests/task8_timerfd_clock_test.c @@ -0,0 +1,84 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +/** @file + * @brief Exercise timerfd clock selection, expiry and absolute disarming. + * The real timerfd syscalls use controlled time, allocation and FD boundaries. + */ +#define main task8_inherited_timerfd_user_main +#include "task8_timerfd_user_test.c" +#undef main +#include + +static unsigned heap_allocations, heap_frees; + +void *kernel_malloc(size_t size) +{ + void *result = malloc(size); + if (result) ++heap_allocations; + return result; +} + +void kernel_free(void *pointer) +{ + if (pointer) ++heap_frees; + free(pointer); +} + +/** @brief Check relative and absolute timers against the selected clock. */ +static void check_clock(int32_t clock) +{ + uint32_t flags = TFD_CLOEXEC | TFD_NONBLOCK; + assert(syscall_timerfd_create(clock, flags) == 3); + struct task_timerfd *created = (void *)(uintptr_t)file.aux; + assert(created && created->clockid == clock && created->flags == flags); + file.flags = TASK_FILE_FLAG_TIMERFD; + current_tick = 100; + clock_now = (struct linux_timespec){.tv_sec = 10, .tv_nsec = 250000000}; + struct linux_itimerspec input = { + .it_value = {.tv_sec = 2}, + .it_interval = {.tv_nsec = 500000000}, + }; + struct linux_itimerspec output = {0}; + assert(!syscall_timerfd_settime(3, 0, (uintptr_t)&input, 0)); + assert(created->expiry_tick == 300 && created->interval_ticks == 50); + assert(!syscall_timerfd_gettime(3, (uintptr_t)&output)); + assert(output.it_value.tv_sec == 2 && !output.it_value.tv_nsec); + current_tick = 350; + task_timerfd_update(created); + assert(created->expirations == 2 && created->expiry_tick == 400); + + current_tick = 100; + input = (struct linux_itimerspec){.it_value = {.tv_sec = 12}}; + last_clock = -1; + assert(!syscall_timerfd_settime(3, TFD_TIMER_ABSTIME, (uintptr_t)&input, 0)); + assert(last_clock == clock && created->expiry_tick == 275); + assert(!syscall_timerfd_gettime(3, (uintptr_t)&output)); + assert(output.it_value.tv_sec == 1 && output.it_value.tv_nsec == 750000000); + assert(!created->interval_ticks && !created->expirations); + + input.it_value.tv_sec = 9; + assert(!syscall_timerfd_settime(3, TFD_TIMER_ABSTIME, (uintptr_t)&input, 0)); + assert(created->expiry_tick == 101); + current_tick = 101; + task_timerfd_update(created); + assert(!created->expiry_tick && created->expirations == 1); + + input = (struct linux_itimerspec){0}; + assert(!syscall_timerfd_settime(3, TFD_TIMER_ABSTIME, (uintptr_t)&input, 0)); + assert(!created->expiry_tick && !created->expirations); + kernel_free(created); + file = (struct task_file){0}; +} + +int main(void) +{ + current.kind = TASK_KIND_USER; + check_clock(LINUX_CLOCK_BOOTTIME); + check_clock(LINUX_CLOCK_MONOTONIC); + check_clock(LINUX_CLOCK_REALTIME); + assert(syscall_timerfd_create(LINUX_CLOCK_MONOTONIC_RAW, 0) == -RELIEFOS_EINVAL); + assert(syscall_timerfd_create(UINT64_MAX, 0) == -RELIEFOS_EINVAL); + assert(syscall_timerfd_create(LINUX_CLOCK_BOOTTIME, 1) == -RELIEFOS_EINVAL); + assert(heap_allocations == 3 && heap_frees == heap_allocations); + puts("PASS timerfd clocks: BOOTTIME, MONOTONIC, REALTIME, expiry and disarm"); + return 0; +} diff --git a/tools/tests/task8_timerfd_entry_test.c b/tools/tests/task8_timerfd_entry_test.c index f010ad31..fed02e68 100644 --- a/tools/tests/task8_timerfd_entry_test.c +++ b/tools/tests/task8_timerfd_entry_test.c @@ -21,6 +21,8 @@ static uint64_t blocked; static unsigned sleeps,releases; struct task *sched_current_task(void){return ¤t;} uint32_t sched_current_pid(void){return current.pid;} +void sched_account_mode(bool kernel){(void)kernel;} +uint64_t storage_wait_begin(void){assert(locked);return 0;} struct task *sched_exec_staged(const struct task *t){(void)t;return NULL;} void kernel_execution_lock_irqsave(uint64_t *flags){assert(!locked);locked=true;*flags=0;} void kernel_execution_unlock_irqrestore(uint64_t flags){(void)flags;assert(locked);locked=false;} @@ -37,6 +39,8 @@ void task_lookup_scope_begin(struct task *t,const struct trap_frame *f){assert(t void storage_set_io_async_context(bool value){assert(locked);(void)value;} uint64_t time_ticks(void){return 100;} void sched_sleep_current_until(uint64_t t){assert(locked && t==101);current.state=TASK_BLOCKED;++sleeps;} +void storage_wait_sleep(uint64_t generation) +{ assert(locked && !generation);sched_sleep_current_until(time_ticks()+1); } void storage_release_task_io(uint32_t pid){assert(locked && pid==current.pid);} void task_release_syscall_file(struct task *t) { diff --git a/tools/tests/task8_timerfd_snapshot_test.c b/tools/tests/task8_timerfd_snapshot_test.c index 71404916..3a634153 100644 --- a/tools/tests/task8_timerfd_snapshot_test.c +++ b/tools/tests/task8_timerfd_snapshot_test.c @@ -8,6 +8,8 @@ #undef main #include static unsigned frees; +int user_range_readable(uint64_t address, uint64_t length) +{ return user_range_ok(address, length) ? 0 : -RELIEFOS_EFAULT; } void *kernel_malloc(size_t size){void *p=malloc(size);if(p)++allocations;return p;} void kernel_free(void *p){if(p){++frees;free(p);}} void storage_drain_task_io(uint32_t pid){assert(pid==current.pid);} diff --git a/tools/tests/task8_timerfd_user_test.c b/tools/tests/task8_timerfd_user_test.c index c4f7c015..40b3b416 100644 --- a/tools/tests/task8_timerfd_user_test.c +++ b/tools/tests/task8_timerfd_user_test.c @@ -17,14 +17,17 @@ static uint64_t unmapped; static bool contended; static unsigned prepares, allocations; static char saved_name[250]; +static uint64_t current_tick = 100; +static struct linux_timespec clock_now; +static int32_t last_clock; struct task *sched_current_task(void) { return ¤t; } struct task_file *task_file_for_fd(struct task *task,int fd) { assert(task==¤t); return fd==3 ? &file : NULL; } struct task_file *task_file_for_io(struct task *task,int fd) { return task->syscall_file && task->syscall_fd==fd ? task->syscall_file : task_file_for_fd(task,fd); } -uint64_t time_ticks(void) { return 100; } +uint64_t time_ticks(void) { return current_tick; } int time_clock_get(int32_t clock,struct linux_timespec *value) -{ (void)clock; *value=(struct linux_timespec){0}; return 0; } +{ last_clock=clock; *value=clock_now; return 0; } int swap_prepare_user_range(struct task *task,uint64_t address,uint64_t length,bool writing) { (void)writing; assert(task==¤t && length<=250); ++prepares; diff --git a/tools/tests/tcp_state_test.c b/tools/tests/tcp_state_test.c index c2db0d7c..9e0719e4 100644 --- a/tools/tests/tcp_state_test.c +++ b/tools/tests/tcp_state_test.c @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -8,6 +9,8 @@ #include "../../kernel/syscall/ipc/socket.c" #include "../../net/proc.c" +/* Native IPv6 routing is enabled only for passive option inheritance checks. */ +static bool ipv6_passive_options; /* IPv4-only legacy state fixture: native IPv6 transport has its own link model. */ __attribute__((weak)) uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out,uint32_t cap) { (void)ns; (void)out; (void)cap; return 0; } @@ -15,13 +18,18 @@ __attribute__((weak)) uint32_t net_ipv6_routes(struct net_namespace *ns, struct { (void)ns; (void)out; (void)cap; return 0; } __attribute__((weak)) int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *dst,uint32_t scope, const struct in6_addr *bound,struct net_ipv6_path *path) -{ (void)ns; (void)dst; (void)scope; (void)bound; (void)path; return -LINUX_ENETUNREACH; } +{ + (void)ns; (void)scope; + if (!ipv6_passive_options) return -LINUX_ENETUNREACH; + *path = (struct net_ipv6_path){.source = *bound, .destination = *dst, .ifindex = 2, .mtu = 1280}; + return 0; +} __attribute__((weak)) uint16_t net_ipv6_checksum(const struct in6_addr *src,const struct in6_addr *dst, uint8_t protocol,const void *data,uint32_t length) { (void)src; (void)dst; (void)protocol; (void)data; (void)length; return 0; } __attribute__((weak)) int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,uint8_t protocol,const void *data, uint32_t length,int hops,uint32_t flowinfo,bool df,bool loop) -{ (void)ns; (void)path; (void)protocol; (void)data; (void)length; (void)hops; (void)flowinfo; (void)df; (void)loop; return -LINUX_ENETUNREACH; } +{ (void)ns; (void)path; (void)protocol; (void)data; (void)length; (void)hops; (void)flowinfo; (void)df; (void)loop; return ipv6_passive_options ? 0 : -LINUX_ENETUNREACH; } __attribute__((weak)) bool net_ipv6_maintenance_pending(void) { return false; } __attribute__((weak)) void net_ipv6_poll(void) {} __attribute__((weak)) void net_ipv6_input(const uint8_t *frame,uint32_t length) { (void)frame; (void)length; } @@ -102,9 +110,9 @@ int e1000_poll(void *frame, uint32_t capacity, uint32_t *length) *length = 42; return 1; } -void net_udp_input(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, - uint16_t destination_port, const void *data, uint32_t length, int ifindex) -{ (void)ns; (void)ifindex; (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; } +void net_udp_input_ex(struct net_namespace *ns, uint32_t source, uint32_t destination, uint16_t source_port, + uint16_t destination_port, const void *data, uint32_t length, int ifindex, uint8_t ttl) +{ (void)ns; (void)ifindex; (void)source; (void)destination; (void)source_port; (void)destination_port; (void)data; (void)length; (void)ttl; } void net_packet_input(const void *frame, uint32_t length) { (void)frame; (void)length; } void console_printf(const char *format, ...) { (void)format; } @@ -130,6 +138,10 @@ uint32_t kernel_wait_queue_wake_all(struct kernel_wait_queue *queue) void kernel_wait_queue_init(struct kernel_wait_queue *queue) { __builtin_memset(queue, 0, sizeof(*queue)); } void kernel_poll_readiness_notify(void) { } +/** @brief Discard sysfs events outside this TCP-only fixture's receive model. */ +__attribute__((weak)) void netlink_uevent_network(struct net_namespace *ns, const char *action, + const char *devpath, const char *subsystem, const char *properties, uint32_t length) +{ (void)ns; (void)action; (void)devpath; (void)subsystem; (void)properties; (void)length; } int task_packet_send(struct task_file *file, const void *buffer, uint32_t length, uint32_t flags, uint64_t address, uint32_t address_length) { (void)file; (void)buffer; (void)length; (void)flags; (void)address; (void)address_length; return -LINUX_EOPNOTSUPP; } @@ -1217,7 +1229,9 @@ static void test_tcp_creating_network(void) assert(!net_socket_listen_fd(listeners[i]->handle, 2)); assert(!tcp_bind_port(clients[i], 0x7f000001, 55101)); uint32_t physical = 2; - assert(net_socket_bound_device(clients[i]->handle, true, &physical) == -LINUX_ENODEV); + assert(!net_socket_bound_device(clients[i]->handle, true, &physical)); + physical = 0; + assert(!net_socket_bound_device(clients[i]->handle, true, &physical)); } current_task.net_ns = NULL; for (unsigned i = 0; i < 2; ++i) { @@ -1383,8 +1397,9 @@ static void test_tcp_namespace_failures_and_owner(void) net_socket_release_fd(handle); assert(!net_socket_find(handle, 0, 1)); net_socket_release_fd(initial->handle); - net_socket_release_fd(allowed->handle); - assert(net_socket_find(allowed->handle, 0, 1)); /* Bound endpoint uses existing GC. */ + handle = allowed->handle; + net_socket_release_fd(handle); + assert(!net_socket_find(handle, 0, 1)); now_ms += NET_SOCKET_CLOSE_HOLD_MS + 1; net_socket_gc(); assert(!net_sockets && ns->references == 1 && buffers == before_socket); @@ -1396,6 +1411,215 @@ static void test_tcp_namespace_failures_and_owner(void) puts("PASS TCP owner CAP_NET_BIND_SERVICE, staged ENOMEM and release/GC references"); } +/* Holding a closed listener's port until GC makes each resolved restart + * report a spurious second LLMNR responder. No clock advance is allowed here. */ +static void test_tcp_listener_restart_releases_binding(void) +{ + int baseline = buffers; + struct task saved = current_task; + struct net_namespace *isolated; + assert(!net_namespace_create(NULL, &isolated)); + struct net_namespace *spaces[] = {NULL, isolated}; + for (unsigned scope = 0; scope < 2; ++scope) { + for (unsigned family = 0; family < 2; ++family) { + for (unsigned listening = 0; listening < 2; ++listening) { + struct net_namespace *ns = spaces[scope]; + int before_socket = buffers; + uint64_t references = isolated->references; + struct sockaddr_in6 address = {.sin6_family = AF_INET6, + .sin6_port = __builtin_bswap16(5355)}; + struct net_socket *original = open_scoped_tcp(ns); + int old_handle = original->handle; + assert(!net_socket_set_ipv6(old_handle, family != 0)); + assert(!net_socket_bind6_fd(old_handle, &address)); + int reuse = 1; + assert(!net_socket_reuse(old_handle, true, &reuse)); + if (listening) assert(!net_socket_listen_fd(old_handle, 8)); + + struct net_socket *replacement = open_scoped_tcp(ns); + int new_handle = replacement->handle; + assert(!net_socket_set_ipv6(new_handle, family != 0)); + assert(net_socket_bind6_fd(new_handle, &address) == -LINUX_EADDRINUSE); + /* A live original description keeps its port reserved. */ + assert(net_socket_find(old_handle, 0, 1)); + net_socket_release_fd(old_handle); + assert(!net_socket_bind6_fd(new_handle, &address)); + assert(!net_socket_find(old_handle, 0, 1)); + assert(!net_socket_listen_fd(new_handle, 8)); + net_socket_release_fd(new_handle); + assert(!net_socket_find(new_handle, 0, 1)); + assert(isolated->references == references && buffers == before_socket); + } + } + } + current_task = saved; + net_namespace_put(isolated); + assert(buffers == baseline); + puts("PASS TCP IPv4/IPv6 listener restart releases ports, buffers and network references immediately"); +} + +/* Rejecting receive options, conflating their flags, or leaking reused state + * breaks the stream socket contract used by systemd's IPv6 listeners. */ +static void test_tcp_ipv6_receive_options(void) +{ + int baseline = buffers; + struct net_socket *socket = net_socket_alloc(NULL, 7, 1000); + assert(socket); + int value = 1; + assert(net_socket_ipv6_option(socket->handle, true, IPV6_RECVPKTINFO, &value) == -LINUX_ENOPROTOOPT); + socket->ipv6 = true; + const uint32_t options[] = {IPV6_RECVPKTINFO, IPV6_RECVHOPLIMIT}; + for (unsigned i = 0; i < 2; ++i) { + value = -7; + assert(!net_socket_ipv6_option(socket->handle, false, options[i], &value) && value == 0); + const int inputs[] = {-3, 2, 0}; + const int expected[] = {1, 1, 0}; + for (unsigned j = 0; j < 3; ++j) { + value = inputs[j]; + assert(!net_socket_ipv6_option(socket->handle, true, options[i], &value)); + assert(!net_socket_ipv6_option(socket->handle, false, options[i], &value)); + assert(value == expected[j]); + assert(!net_socket_ipv6_option(socket->handle, false, options[1 - i], &value) && value == 0); + } + } + value = 1; + assert(!net_socket_ipv6_option(socket->handle, true, IPV6_RECVPKTINFO, &value)); + assert(!net_socket_ipv6_option(socket->handle, true, IPV6_RECVHOPLIMIT, &value)); + net_socket_clear(socket); + socket = net_socket_alloc(NULL, 7, 1000); + assert(socket); + socket->ipv6 = true; + for (unsigned i = 0; i < 2; ++i) + assert(!net_socket_ipv6_option(socket->handle, false, options[i], &value) && value == 0); + net_socket_clear(socket); + assert(buffers == baseline); + puts("PASS TCP IPv6 receive options default, normalize, remain independent and reset on reuse"); +} + +/** @brief Check IPv4 options through real TCP output and passive child allocation. */ +static void test_tcp_ipv4_options(void) +{ + int baseline = buffers; + struct net_socket *socket = net_socket_alloc(NULL, 7, 1000); + assert(socket); + int handle = socket->handle, value = -7; + assert(!net_socket_ipv4_option(handle, false, IP_TTL, &value) && value == 64); + assert(!net_socket_ipv4_option(handle, false, IP_MTU_DISCOVER, &value) && value == 1); + assert(!net_socket_ipv4_option(handle, false, IP_PKTINFO, &value) && !value); + assert(!net_socket_ipv4_option(handle, false, IP_RECVTTL, &value) && !value); + assert(net_socket_ipv4_option(-1, false, IP_TTL, &value) == -LINUX_EBADF); + assert(net_socket_ipv4_option(handle, true, IP_TTL, NULL) == -LINUX_EBADF); + assert(net_socket_ipv4_option(handle, false, 999, &value) == -LINUX_ENOPROTOOPT); + assert(net_socket_ipv4_option(handle, true, 999, &value) == -LINUX_ENOPROTOOPT); + const int invalid_ttls[] = {-2, 0, 256}; + for (unsigned i = 0; i < 3; ++i) { + value = invalid_ttls[i]; + assert(net_socket_ipv4_option(handle, true, IP_TTL, &value) == -LINUX_EINVAL); + assert(!net_socket_ipv4_option(handle, false, IP_TTL, &value) && value == 64); + } + const int ttls[] = {1, 255, -1, 37}; + for (unsigned i = 0; i < 4; ++i) { + value = ttls[i]; + assert(!net_socket_ipv4_option(handle, true, IP_TTL, &value)); + assert(!net_socket_ipv4_option(handle, false, IP_TTL, &value)); + assert(value == (ttls[i] == -1 ? 64 : ttls[i])); + } + value = -4; + assert(!net_socket_ipv4_option(handle, true, IP_PKTINFO, &value)); + assert(!net_socket_ipv4_option(handle, false, IP_PKTINFO, &value) && value == 1); + value = 2; + assert(!net_socket_ipv4_option(handle, true, IP_RECVTTL, &value)); + assert(!net_socket_ipv4_option(handle, false, IP_RECVTTL, &value) && value == 1); + socket->local_ip = net_config.local_ip; socket->remote_ip = 0x0a250002; + socket->local_port = 55100; socket->remote_port = 80; + socket->ifindex = 2; socket->next_hop = socket->remote_ip; + memcpy(socket->dst_mac, e1000_mac(), 6); + for (unsigned mapped = 0; mapped < 2; ++mapped) { + socket->ipv6 = socket->mapped = mapped; + for (int mode = 0; mode <= 5; ++mode) { + value = mode; + assert(!net_socket_ipv4_option(handle, true, IP_MTU_DISCOVER, &value)); + assert(!net_socket_ipv4_option(handle, false, IP_MTU_DISCOVER, &value) && value == mode); + unsigned before = sent_count; + assert(net_send_tcp_socket(socket, 1, 1, TCP_FLAG_ACK, NULL, 0) >= 0); + assert(sent_count == before + 1 && sent_frame[22] == 37); + assert(net_get_u16(sent_frame + 20) == ((mode == 2 || mode == 3) ? 0x4000 : 0)); + assert(!net_checksum(sent_frame + 14, 20)); + } + } + const int invalid_modes[] = {-1, 6}; + for (unsigned i = 0; i < 2; ++i) { + value = invalid_modes[i]; + assert(net_socket_ipv4_option(handle, true, IP_MTU_DISCOVER, &value) == -LINUX_EINVAL); + assert(!net_socket_ipv4_option(handle, false, IP_MTU_DISCOVER, &value) && value == 5); + } + value = 0; + assert(!net_socket_ipv6_option(handle, true, IPV6_MTU_DISCOVER, &value)); + assert(!net_socket_ipv4_option(handle, false, IP_MTU_DISCOVER, &value) && value == 5); + value = 17; + assert(!net_socket_ipv6_option(handle, true, IPV6_UNICAST_HOPS, &value)); + assert(!net_socket_ipv4_option(handle, false, IP_TTL, &value) && value == 37); + socket->state = NET_TCP_LISTEN; socket->backlog = 4; + for (unsigned family = 0; family < 3; ++family) { + socket->ipv6 = family != 0; socket->mapped = false; + if (family) { + value = family == 1 ? -2 : 0; + assert(!net_socket_ipv6_option(handle, true, IPV6_RECVPKTINFO, &value)); + value = family == 2 ? 4 : 0; + assert(!net_socket_ipv6_option(handle, true, IPV6_RECVHOPLIMIT, &value)); + } + struct net_socket *child; + if (family == 2) { + const struct in6_addr peer = {.s6_addr = {0x20, 1, 0xdb, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}}; + const struct in6_addr local = {.s6_addr = {0x20, 1, 0xdb, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}; + ipv6_passive_options = true; + child = net_tcp_passive6(socket, &peer, &local, 50001, 2, 1, 65535, 1000); + ipv6_passive_options = false; + } else { + child = net_tcp_passive4_on(2, socket, 0x0a250002, net_config.local_ip, + 50001, e1000_mac(), 1, 65535, 1000); + } + assert(child); + const uint32_t options[] = {IP_TTL, IP_MTU_DISCOVER, IP_PKTINFO, IP_RECVTTL}; + const int expected[] = {37, 5, 1, 1}; + for (unsigned i = 0; i < 4; ++i) { + assert(!net_socket_ipv4_option(child->handle, false, options[i], &value)); + assert(value == expected[i]); + } + if (family) { + assert(!net_socket_ipv6_option(child->handle, false, IPV6_RECVPKTINFO, &value)); + assert(value == (family == 1)); + assert(!net_socket_ipv6_option(child->handle, false, IPV6_RECVHOPLIMIT, &value)); + assert(value == (family == 2)); + value = family == 2; + assert(!net_socket_ipv6_option(handle, true, IPV6_RECVPKTINFO, &value)); + value = family == 1; + assert(!net_socket_ipv6_option(handle, true, IPV6_RECVHOPLIMIT, &value)); + assert(!net_socket_ipv6_option(child->handle, false, IPV6_RECVPKTINFO, &value)); + assert(value == (family == 1)); + assert(!net_socket_ipv6_option(child->handle, false, IPV6_RECVHOPLIMIT, &value)); + assert(value == (family == 2)); + } + if (family < 2) { + assert(sent_frame[22] == 37 && !net_get_u16(sent_frame + 20)); + value = 2; + assert(!net_socket_ipv4_option(child->handle, true, IP_MTU_DISCOVER, &value)); + assert(net_send_tcp_socket(child, 2, 2, TCP_FLAG_ACK, NULL, 0) >= 0); + assert(net_get_u16(sent_frame + 20) == 0x4000); + assert(!net_socket_ipv4_option(handle, false, IP_MTU_DISCOVER, &value) && value == 5); + } + net_socket_clear(child); + } + value = 0; + assert(!net_socket_ipv4_option(handle, true, IP_PKTINFO, &value)); + assert(!net_socket_ipv4_option(handle, true, IP_RECVTTL, &value)); + assert(!net_socket_ipv4_option(handle, false, IP_PKTINFO, &value) && !value); + assert(!net_socket_ipv4_option(handle, false, IP_RECVTTL, &value) && !value); + net_socket_clear(socket); + assert(buffers == baseline); + puts("PASS TCP IPv4 options, TTL/DF/checksum, mapped output and passive inheritance"); +} + int main(void) { static struct net_interface test_interface = {.index=2, .up=true, @@ -1468,6 +1692,9 @@ int main(void) net_socket_clear(s); assert(buffers == 0); net_config = (struct reliefos_net_config){.local_ip=0x0a25000f,.subnet_mask=0xffffff00,.gateway_ip=0x0a250002}; + test_tcp_listener_restart_releases_binding(); + test_tcp_ipv6_receive_options(); + test_tcp_ipv4_options(); test_tcp_route_gateway_change(); test_tcp_bound_device_local_delivery(); test_tcp_matching_and_scope_isolation(); @@ -1515,6 +1742,17 @@ void net_packet_input_on(struct net_namespace *ns, uint32_t index, const void *f int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index, bool up) { (void)ns; (void)index; (void)up; return 0; } void net_ipv6_detached_on(struct net_namespace *ns, uint32_t index) { (void)ns; (void)index; } void netlink_ipv6_changed(struct net_namespace *ns) { (void)ns; } +void netlink_network_changed(struct net_namespace *ns) { (void)ns; } +void net_ipv6_nexthop_changed(struct net_namespace *ns, uint32_t id, + const struct net_nexthop *value) +{ (void)ns; (void)id; (void)value; } +void netlink_nexthop_changed(struct net_namespace *ns, const struct net_nexthop *value, bool deleted) +{ (void)ns; (void)value; (void)deleted; } +void net_udp_error_input(struct net_namespace *ns, uint32_t index, + const uint8_t *packet, uint32_t length, + const struct sock_extended_err *error, + const struct sockaddr_storage *offender) +{ (void)ns; (void)index; (void)packet; (void)length; (void)error; (void)offender; abort(); } void net_udp_device_detached(struct net_namespace *ns, uint32_t index) { assert(!ns); (void)index; } diff --git a/tools/tests/udp_socket_test.c b/tools/tests/udp_socket_test.c index c4e9eb17..f5b3c83b 100644 --- a/tools/tests/udp_socket_test.c +++ b/tools/tests/udp_socket_test.c @@ -3,15 +3,56 @@ #include #include #include +#include #include "../../net/socket/udp.c" #include "../../net/interface/socket.c" #include "../../net/utility.c" +/** @brief Capture a real UDP wire frame on a modeled hardware link. + * @param index Output interface. @param frame Borrowed frame. @param length Bytes. + * @return Zero during capture or ENETDOWN for the default disconnected fixture. */ +static int fixture_udp_wire_send(uint32_t index, const void *frame, uint32_t length); +/** @brief Supply a deterministic Ethernet header for the wire builder. + * @param index Output interface. @param frame Writable Ethernet header. + * @param mac Destination MAC. @param type Host-order EtherType. */ +static void fixture_udp_write_eth(uint32_t index, uint8_t *frame, const uint8_t *mac, uint16_t type); +/** @brief Borrow the modeled hardware interface for IPv4 broadcast selection. + * @param ns Creating network. @param index Requested link. @return Interface or NULL. */ +static struct net_interface *fixture_udp_interface_get(struct net_namespace *ns, uint32_t index); +/** @brief Resolve a peer on one of the two modeled Ethernet links. + * @param index Output link. @param ip Peer address. @param timeout_ms Bounded wait. + * @param mac Writable six-byte result. @return Zero or ENETUNREACH. */ +static int fixture_udp_resolve_mac(uint32_t index, uint32_t ip, uint32_t timeout_ms, uint8_t mac[6]); +static uint16_t fixture_udp_ipv4_id; +static const uint8_t fixture_udp_broadcast_mac[6] = {255,255,255,255,255,255}; /* Keep hardware receive parsing real alongside controlled transmit routing. */ #define net_ipv4_send_udp_on fixture_hardware_send_udp_on #define net_ipv4_send_udp fixture_hardware_send_udp +#define net_ipv4_send_udp_options fixture_hardware_send_udp_options +#define netdev_send fixture_udp_wire_send +#define net_write_eth_on fixture_udp_write_eth +#define net_interface_get fixture_udp_interface_get +#define net_resolve_mac_on fixture_udp_resolve_mac +#define net_ipv4_id fixture_udp_ipv4_id +#define net_broadcast_mac fixture_udp_broadcast_mac #include "../../net/ipv4/udp.c" #undef net_ipv4_send_udp #undef net_ipv4_send_udp_on +#undef net_ipv4_send_udp_options +#undef netdev_send +#undef net_write_eth_on +#undef net_interface_get +#undef net_resolve_mac_on +#undef net_ipv4_id +#undef net_broadcast_mac + +#ifndef IPV6_TRANSPORT_FIXTURE +#include "../../net/ipv4/core.c" +/* TCP ingress has its own real transport fixture. */ +void net_handle_tcp_on(struct net_namespace *ns, uint32_t index, const uint8_t *ip, + uint32_t length, uint32_t header, uint32_t source, + const uint8_t *mac, struct net_tcp_wait *wait) +{ (void)ns; (void)index; (void)ip; (void)length; (void)header; (void)source; (void)mac; (void)wait; abort(); } +#endif static struct task current; static struct task_file files[80]; @@ -20,6 +61,9 @@ static int allocation_fail_after = -1; static bool fail_fd; static unsigned sleeps; static uint64_t ticks = 100; +static bool capture_udp_wire; +static uint8_t udp_wire_frame[NET_FRAME_MAX]; +static uint32_t udp_wire_length, udp_wire_ifindex; struct task *sched_current_task(void) { return ¤t; } void *kernel_malloc(size_t bytes) { @@ -31,6 +75,28 @@ void *kernel_malloc(size_t bytes) } void kernel_free(void *p) { if (p) { assert(allocations); --allocations; free(p); } } uint64_t time_ticks(void) { return ticks; } +/** @brief Model wall and boot clocks deterministically from fixture ticks. + * @param clock Linux non-CPU clock selector. @param value Writable timespec. + * @return Zero or EINVAL for an unsupported selector, preserving failed output. + * Wall clocks use Unix epoch 1700000000 and all results have normalized nanoseconds. */ +int time_clock_get(int clock, struct linux_timespec *value) +{ + int64_t epoch = 0; + switch (clock) { + case LINUX_CLOCK_REALTIME: + case LINUX_CLOCK_REALTIME_COARSE: epoch = 1700000000; break; + case LINUX_CLOCK_MONOTONIC: + case LINUX_CLOCK_MONOTONIC_RAW: + case LINUX_CLOCK_MONOTONIC_COARSE: + case LINUX_CLOCK_BOOTTIME: break; + default: return -LINUX_EINVAL; + } + assert(value); + *value = (struct linux_timespec){ + .tv_sec = epoch + (int64_t)(ticks / RELIEFNT_TICK_HZ), + .tv_nsec = (int64_t)(ticks % RELIEFNT_TICK_HZ * (1000000000ULL / RELIEFNT_TICK_HZ))}; + return 0; +} void sched_sleep_current_until(uint64_t tick) { assert(tick == ticks + 1); ++sleeps; } bool user_range_ok(uint64_t address, uint64_t size) { (void)size; return address > 4096; } bool user_range_writable(uint64_t address, uint64_t size) { return user_range_ok(address, size); } @@ -92,6 +158,13 @@ bool net_interface_exists(struct net_namespace *ns, uint32_t index) { return index == NET_IF_LOOPBACK || (!ns && index >= 2 && index <= 3); } bool net_interface_is_ready(struct net_namespace *ns, uint32_t index) { return net_interface_exists(ns, index) && (!ns || ns->loopback.up); } +int net_interface_get_config(struct net_namespace *ns, uint32_t index, struct reliefos_net_config *config) +{ + if (!net_interface_exists(ns, index)) return -LINUX_ENODEV; + *config = (struct reliefos_net_config){.local_ip = index == NET_IF_LOOPBACK ? + 0x7f000001 : index == 3 ? 0x0a00030f : 0x0a00020f}; + return 0; +} uint32_t net_interface_index(struct net_namespace *ns, const char *name) { if (!strcmp(name, "lo")) return NET_IF_LOOPBACK; @@ -137,6 +210,55 @@ int net_ipv4_send_udp_on(struct net_namespace *ns, uint32_t index, uint32_t sour return net_ipv4_send_udp(path.source, destination, source_port, destination_port, data, length); } +int net_ipv4_send_udp_options(struct net_namespace *ns, uint32_t index, uint32_t source, + uint32_t destination, uint16_t source_port, uint16_t destination_port, + const void *data, uint32_t length, uint8_t ttl, bool dont_fragment) +{ + (void)ttl; + (void)dont_fragment; + return net_ipv4_send_udp_on(ns, index, source, destination, source_port, destination_port, data, length); +} + +/** @copydoc fixture_udp_wire_send */ +static int fixture_udp_wire_send(uint32_t index, const void *frame, uint32_t length) +{ + if (!capture_udp_wire) return -LINUX_ENETDOWN; + assert(index >= 2 && index <= 3 && length <= sizeof(udp_wire_frame)); + memcpy(udp_wire_frame, frame, length); + udp_wire_length = length; + udp_wire_ifindex = index; + return 0; +} + +/** @copydoc fixture_udp_write_eth */ +static void fixture_udp_write_eth(uint32_t index, uint8_t *frame, const uint8_t *mac, uint16_t type) +{ + const uint8_t source[6] = {2, 0, 0, 0, 0, (uint8_t)index}; + memcpy(frame, mac, 6); + memcpy(frame + 6, source, 6); + net_put_u16(frame + 12, type); +} + +/** @copydoc fixture_udp_interface_get */ +static struct net_interface *fixture_udp_interface_get(struct net_namespace *ns, uint32_t index) +{ + static struct net_interface interfaces[2] = { + {.index = 2, .broadcast = 0x0a0002ff, .up = true}, + {.index = 3, .broadcast = 0x0a0003ff, .up = true}}; + return !ns && index >= 2 && index <= 3 ? &interfaces[index - 2] : NULL; +} + +/** @copydoc fixture_udp_resolve_mac */ +static int fixture_udp_resolve_mac(uint32_t index, uint32_t ip, uint32_t timeout_ms, uint8_t mac[6]) +{ + (void)ip; + (void)timeout_ms; + if (index < 2 || index > 3) return -LINUX_ENETUNREACH; + const uint8_t peer[6] = {2, 0, 0, 0, 1, (uint8_t)index}; + memcpy(mac, peer, sizeof(peer)); + return 0; +} + static long call(uint64_t nr, uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { return syscall_udp(nr, a, b, c, d, e, 0); } static int open_socket(void) @@ -170,6 +292,369 @@ static void close_udp(int fd) files[fd] = (struct task_file){0}; } +/** @brief Read a scalar option through the UDP syscall entry point. + * @param fd Open datagram descriptor. @param level Linux option level. + * @param option Linux option selector. @return Returned integer value. */ +static int udp_option_get_int(int fd, int level, int option) +{ + int value = -99; + uint32_t length = sizeof(value); + assert(!call(__NR_getsockopt, fd, level, option, + (uintptr_t)&value, (uintptr_t)&length)); + assert(length == sizeof(value)); + return value; +} + +/** @brief Check Linux priority values, both capabilities and failed-input rollback. */ +static void test_udp_priority(void) +{ + struct task saved = current; + const int privileged[] = {7, -1, INT32_MIN, INT32_MAX}; + const unsigned capabilities[] = {CAP_NET_RAW, CAP_NET_ADMIN}; + for (unsigned family = 0; family < 2; ++family) { + current.cap_effective = 0; + int fd = (int)call(__NR_socket, family ? AF_INET6 : AF_INET, + SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + assert(fd >= 0); + assert(udp_option_get_int(fd, SOL_SOCKET, SO_PRIORITY) == 0); + for (int value = 0; value <= 6; ++value) { + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, sizeof(value))); + assert(udp_option_get_int(fd, SOL_SOCKET, SO_PRIORITY) == value); + } + for (unsigned i = 0; i < sizeof(privileged) / sizeof(privileged[0]); ++i) { + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&privileged[i], sizeof(int)) == -LINUX_EPERM); + assert(udp_option_get_int(fd, SOL_SOCKET, SO_PRIORITY) == 6); + } + for (unsigned cap = 0; cap < sizeof(capabilities) / sizeof(capabilities[0]); ++cap) { + current.cap_effective = 1ULL << capabilities[cap]; + for (unsigned i = 0; i < sizeof(privileged) / sizeof(privileged[0]); ++i) { + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&privileged[i], sizeof(int))); + assert(udp_option_get_int(fd, SOL_SOCKET, SO_PRIORITY) == privileged[i]); + } + } + int value = 5; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, sizeof(value))); + for (uint32_t length = 0; length < sizeof(value); ++length) + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, length) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_PRIORITY, + 0, sizeof(value)) == -LINUX_EFAULT); + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, UINT32_MAX) == -LINUX_EINVAL); + assert(udp_option_get_int(fd, SOL_SOCKET, SO_PRIORITY) == 5); + unsigned char output[8]; + for (uint32_t capacity = 1; capacity <= sizeof(output); ++capacity) { + memset(output, 0xcc, sizeof(output)); + uint32_t length = capacity; + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)output, (uintptr_t)&length)); + uint32_t copied = capacity < sizeof(value) ? capacity : sizeof(value); + assert(length == copied && !memcmp(output, &value, copied)); + for (uint32_t i = copied; i < sizeof(output); ++i) assert(output[i] == 0xcc); + } + uint32_t length = 0; + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_PRIORITY, 0, (uintptr_t)&length)); + assert(!length); + length = sizeof(value); + assert(call(__NR_getsockopt, fd, SOL_SOCKET, SO_PRIORITY, + 0, (uintptr_t)&length) == -LINUX_EFAULT); + assert(length == sizeof(value)); + assert(call(__NR_getsockopt, fd, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, 0) == -LINUX_EFAULT); + length = UINT32_MAX; + assert(call(__NR_getsockopt, fd, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, (uintptr_t)&length) == -LINUX_EINVAL); + close_udp(fd); + } + current = saved; + puts("PASS UDP priority signed values, RAW/ADMIN capabilities, lengths and rollback"); +} + +/** @brief Keep priority authorization attached to the creating network owner. */ +static void test_udp_priority_owner(void) +{ + struct task saved = current; + unsigned baseline = allocations; + struct user_namespace *owner, *sibling; + struct net_namespace *ns; + assert(!user_namespace_create(¤t, &owner)); + assert(!user_namespace_create(¤t, &sibling)); + assert(!net_namespace_create(owner, &ns)); + current.user_ns = owner; + current.net_ns = ns; + int owned = open_socket(); + current.net_ns = NULL; + int initial = open_socket(); + assert(owned >= 0 && initial >= 0); + const unsigned capabilities[] = {CAP_NET_RAW, CAP_NET_ADMIN}; + for (unsigned i = 0; i < sizeof(capabilities) / sizeof(capabilities[0]); ++i) { + current.cap_effective = 1ULL << capabilities[i]; + current.user_ns = owner; + current.net_ns = NULL; + int value = -1; + assert(!call(__NR_setsockopt, owned, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, sizeof(value))); + current.net_ns = ns; + assert(call(__NR_setsockopt, initial, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, sizeof(value)) == -LINUX_EPERM); + current.user_ns = sibling; + value = 7; + assert(call(__NR_setsockopt, owned, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, sizeof(value)) == -LINUX_EPERM); + assert(udp_option_get_int(owned, SOL_SOCKET, SO_PRIORITY) == -1); + value = 6; + assert(!call(__NR_setsockopt, owned, SOL_SOCKET, SO_PRIORITY, + (uintptr_t)&value, sizeof(value))); + } + current = saved; + close_udp(owned); + close_udp(initial); + net_namespace_put(ns); + user_namespace_put(owner); + user_namespace_put(sibling); + assert(allocations == baseline); + puts("PASS UDP priority creating-network owner and sibling namespace authority"); +} + +/** @brief Retain all UDP TOS bits and update priority through Linux socket options. */ +static void test_udp_tos(void) +{ + struct task saved = current; + current.cap_effective = 0; + int fd = open_socket(); + assert(fd >= 0); + assert(udp_option_get_int(fd, SOL_IP, IP_TOS) == 0); + const struct { int input, tos, priority; } cases[] = { + {2, 2, 0}, {4, 4, 0}, {8, 8, 2}, {16, 16, 6}, {24, 24, 4}, + {47, 47, 2}, {184, 184, 4}, {-1, 255, 4}, {256, 0, 0}, {443, 187, 4}}; + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_TOS, + (uintptr_t)&cases[i].input, sizeof(int))); + assert(udp_option_get_int(fd, SOL_IP, IP_TOS) == cases[i].tos); + assert(udp_option_get_int(fd, SOL_SOCKET, SO_PRIORITY) == cases[i].priority); + } + int value = 5; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_PRIORITY, (uintptr_t)&value, sizeof(value))); + value = 187; + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_TOS, (uintptr_t)&value, sizeof(value))); + assert(udp_option_get_int(fd, SOL_SOCKET, SO_PRIORITY) == 5); + value = 443; + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_TOS, (uintptr_t)&value, sizeof(value))); + assert(udp_option_get_int(fd, SOL_IP, IP_TOS) == 187); + assert(udp_option_get_int(fd, SOL_SOCKET, SO_PRIORITY) == 4); + const unsigned char bytes[3] = {0x83, 0xff, 0xff}; + for (uint32_t length = 1; length <= sizeof(bytes); ++length) { + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_TOS, (uintptr_t)bytes, length)); + assert(udp_option_get_int(fd, SOL_IP, IP_TOS) == 0x83); + } + unsigned char output[8]; + for (uint32_t capacity = 1; capacity <= sizeof(output); ++capacity) { + memset(output, 0xcc, sizeof(output)); + uint32_t length = capacity; + assert(!call(__NR_getsockopt, fd, SOL_IP, IP_TOS, + (uintptr_t)output, (uintptr_t)&length)); + uint32_t copied = capacity < sizeof(int) ? 1 : sizeof(int); + int expected = 0x83; + assert(length == copied && !memcmp(output, &expected, copied)); + for (uint32_t i = copied; i < sizeof(output); ++i) assert(output[i] == 0xcc); + } + value = 0; + assert(call(__NR_setsockopt, fd, SOL_IP, IP_TOS, 0, sizeof(value)) == -LINUX_EFAULT); + assert(call(__NR_setsockopt, fd, SOL_IP, IP_TOS, + (uintptr_t)&value, UINT32_MAX) == -LINUX_EINVAL); + assert(udp_option_get_int(fd, SOL_IP, IP_TOS) == 0x83); + uint32_t length = 0; + assert(!call(__NR_getsockopt, fd, SOL_IP, IP_TOS, 0, (uintptr_t)&length)); + assert(!length); + length = 3; + assert(call(__NR_getsockopt, fd, SOL_IP, IP_TOS, 0, (uintptr_t)&length) == -LINUX_EFAULT); + assert(length == 3); + assert(call(__NR_getsockopt, fd, SOL_IP, IP_TOS, (uintptr_t)&value, 0) == -LINUX_EFAULT); + length = UINT32_MAX; + assert(call(__NR_getsockopt, fd, SOL_IP, IP_TOS, + (uintptr_t)&value, (uintptr_t)&length) == -LINUX_EINVAL); + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_TOS, 0, 0)); + assert(udp_option_get_int(fd, SOL_IP, IP_TOS) == 0); + assert(udp_option_get_int(fd, SOL_SOCKET, SO_PRIORITY) == 0); + close_udp(fd); + current = saved; + puts("PASS UDP TOS byte/int/empty values, ECN, priority mapping, lengths and rollback"); +} + +/** @brief Carry socket TOS into a real IPv4 header and retain old helper defaults. */ +static void test_udp_tos_wire(void) +{ + int fd = open_socket(); + assert(fd >= 0); + int index = 3, tos = 0xbb, ttl = 41, pmtu = IP_PMTUDISC_DO; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, (uintptr_t)&index, sizeof(index))); + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_TOS, (uintptr_t)&tos, sizeof(tos))); + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_TTL, (uintptr_t)&ttl, sizeof(ttl))); + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_MTU_DISCOVER, (uintptr_t)&pmtu, sizeof(pmtu))); + struct sockaddr_in peer = {.sin_family = AF_INET, .sin_port = swap16(55130), + .sin_addr.s_addr = swap32(0x0a000302)}; + capture_udp_wire = true; + udp_wire_length = 0; + assert(task_udp_send(&files[fd], "tos", 3, 0, (uintptr_t)&peer, sizeof(peer)) == 3); + const uint8_t *ip = udp_wire_frame + 14; + assert(udp_wire_ifindex == 3 && udp_wire_length == 45); + assert(net_get_u16(udp_wire_frame + 12) == ETH_TYPE_IPV4); + assert(ip[0] == 0x45 && ip[1] == 0xbb && ip[8] == 41 && ip[9] == 17); + assert(net_get_u16(ip + 2) == 31 && net_get_u16(ip + 6) == 0x4000); + assert(net_get_u32(ip + 12) == 0x0a00030f && net_get_u32(ip + 16) == 0x0a000302); + assert(!net_checksum(ip, 20)); + assert(net_get_u16(ip + 22) == 55130 && !memcmp(ip + 28, "tos", 3)); + assert(!fixture_hardware_send_udp_options(NULL, 3, 0, 0x0a000302, + 55131, 55130, "old", 3, 37, true)); + assert(ip[1] == 0 && ip[8] == 37 && net_get_u16(ip + 6) == 0x4000 && !net_checksum(ip, 20)); + const uint8_t peer_mac[6] = {2, 0, 0, 0, 1, 3}; + assert(!net_send_udp_to_mac_on(3, peer_mac, 0x0a00030f, 0x0a000302, 55131, 55130, + (const uint8_t *)"old", 3)); + assert(ip[1] == 0 && ip[8] == 64 && !net_get_u16(ip + 6) && !net_checksum(ip, 20)); + capture_udp_wire = false; + close_udp(fd); + puts("PASS UDP socket TOS on IPv4 wire, checksum, TTL/DF and legacy helper defaults"); +} + +/** @brief Restrict freebind to address admission while retaining tuple and route rules. */ +static void test_udp_freebind(void) +{ + struct task saved = current; + current.cap_effective = 0; + int fd = open_socket(), conflict = open_socket(), wildcard = open_socket(); + assert(fd >= 0 && conflict >= 0 && wildcard >= 0); + struct sockaddr_in address = {.sin_family = AF_INET, .sin_port = swap16(55140), + .sin_addr.s_addr = swap32(0xc0000263)}; + assert(call(__NR_bind, fd, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EADDRNOTAVAIL); + assert(udp_option_get_int(fd, SOL_IP, IP_FREEBIND) == 0); + int enabled = -1, disabled = 0; + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_FREEBIND, (uintptr_t)&enabled, sizeof(enabled))); + assert(udp_option_get_int(fd, SOL_IP, IP_FREEBIND) == 1); + assert(call(__NR_setsockopt, fd, SOL_IP, IP_FREEBIND, 0, 0) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, fd, SOL_IP, IP_FREEBIND, 0, sizeof(enabled)) == -LINUX_EFAULT); + assert(call(__NR_setsockopt, fd, SOL_IP, IP_FREEBIND, + (uintptr_t)&disabled, UINT32_MAX) == -LINUX_EINVAL); + assert(udp_option_get_int(fd, SOL_IP, IP_FREEBIND) == 1); + const unsigned char bytes[3] = {2, 0, 0}; + for (uint32_t size = 1; size <= sizeof(bytes); ++size) { + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_FREEBIND, (uintptr_t)bytes, size)); + assert(udp_option_get_int(fd, SOL_IP, IP_FREEBIND) == 1); + unsigned char output[4] = {0xcc, 0xcc, 0xcc, 0xcc}; + uint32_t length = size; + assert(!call(__NR_getsockopt, fd, SOL_IP, IP_FREEBIND, + (uintptr_t)output, (uintptr_t)&length)); + assert(length == 1 && output[0] == 1 && output[1] == 0xcc); + } + uint32_t length = 0; + assert(!call(__NR_getsockopt, fd, SOL_IP, IP_FREEBIND, 0, (uintptr_t)&length)); + assert(!length); + length = sizeof(enabled); + assert(call(__NR_getsockopt, fd, SOL_IP, IP_FREEBIND, 0, (uintptr_t)&length) == -LINUX_EFAULT); + assert(length == sizeof(enabled)); + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_FREEBIND, (uintptr_t)&disabled, sizeof(disabled))); + assert(call(__NR_bind, fd, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EADDRNOTAVAIL); + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_FREEBIND, (uintptr_t)&enabled, sizeof(enabled))); + assert(!call(__NR_bind, fd, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_FREEBIND, (uintptr_t)&disabled, sizeof(disabled))); + assert(udp_option_get_int(fd, SOL_IP, IP_FREEBIND) == 0); + struct sockaddr_in bound = {0}; + length = sizeof(bound); + assert(!call(__NR_getsockname, fd, (uintptr_t)&bound, (uintptr_t)&length, 0, 0)); + assert(bound.sin_addr.s_addr == address.sin_addr.s_addr && bound.sin_port == address.sin_port); + assert(call(__NR_bind, fd, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EINVAL); + assert(!call(__NR_setsockopt, conflict, SOL_IP, IP_FREEBIND, (uintptr_t)&enabled, sizeof(enabled))); + assert(call(__NR_bind, conflict, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EADDRINUSE); + struct sockaddr_in any = address; + any.sin_addr.s_addr = 0; + assert(call(__NR_bind, wildcard, (uintptr_t)&any, sizeof(any), 0, 0) == -LINUX_EADDRINUSE); + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_REUSEADDR, (uintptr_t)&enabled, sizeof(enabled))); + assert(!call(__NR_setsockopt, conflict, SOL_SOCKET, SO_REUSEADDR, (uintptr_t)&enabled, sizeof(enabled))); + assert(!call(__NR_bind, conflict, (uintptr_t)&address, sizeof(address), 0, 0)); + struct sockaddr_in peer = {.sin_family = AF_INET, .sin_port = swap16(55141), + .sin_addr.s_addr = swap32(0x08080808)}; + assert(task_udp_send(&files[fd], "route", 5, 0, (uintptr_t)&peer, sizeof(peer)) == -LINUX_EADDRNOTAVAIL); + assert(!call(__NR_setsockopt, conflict, SOL_IP, IP_FREEBIND, (uintptr_t)&enabled, sizeof(enabled))); + assert(task_udp_send(&files[conflict], "route", 5, 0, (uintptr_t)&peer, sizeof(peer)) == -LINUX_EADDRNOTAVAIL); + int devices[2] = {open_socket(), open_socket()}; + address.sin_port = swap16(55141); + for (int i = 0; i < 2; ++i) { + assert(devices[i] >= 0); + int index = i + 2; + assert(!call(__NR_setsockopt, devices[i], SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index))); + assert(!call(__NR_setsockopt, devices[i], SOL_IP, IP_FREEBIND, + (uintptr_t)&enabled, sizeof(enabled))); + assert(!call(__NR_bind, devices[i], (uintptr_t)&address, sizeof(address), 0, 0)); + } + int index = 2; + assert(!call(__NR_setsockopt, wildcard, SOL_SOCKET, SO_BINDTOIFINDEX, (uintptr_t)&index, sizeof(index))); + assert(!call(__NR_setsockopt, wildcard, SOL_IP, IP_FREEBIND, (uintptr_t)&enabled, sizeof(enabled))); + assert(call(__NR_bind, wildcard, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EADDRINUSE); + close_udp(devices[0]); + close_udp(devices[1]); + close_udp(fd); + close_udp(conflict); + close_udp(wildcard); + current = saved; + puts("PASS UDP freebind address admission, bool/lengths, disable, conflicts, reuse, devices and routing"); +} + +/** @brief Preserve freebind's creating-network conflicts and low-port owner checks. */ +static void test_udp_freebind_owner(void) +{ + struct task saved = current; + unsigned baseline = allocations; + struct user_namespace *owner, *sibling; + struct net_namespace *first, *second; + assert(!user_namespace_create(¤t, &owner)); + assert(!user_namespace_create(¤t, &sibling)); + assert(!net_namespace_create(owner, &first)); + assert(!net_namespace_create(owner, &second)); + current.user_ns = owner; + current.cap_effective = 0; + current.net_ns = first; + int fd = open_socket(), conflict = open_socket(), low = open_socket(); + current.net_ns = second; + int isolated = open_socket(); + current.net_ns = NULL; + int initial = open_socket(); + assert(fd >= 0 && conflict >= 0 && low >= 0 && isolated >= 0 && initial >= 0); + struct sockaddr_in address = {.sin_family = AF_INET, .sin_port = swap16(55142), + .sin_addr.s_addr = swap32(0x0a00020f)}; + assert(call(__NR_bind, fd, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EADDRNOTAVAIL); + int enabled = 1; + const int descriptions[] = {fd, conflict, low, isolated, initial}; + for (unsigned i = 0; i < sizeof(descriptions) / sizeof(descriptions[0]); ++i) + assert(!call(__NR_setsockopt, descriptions[i], SOL_IP, IP_FREEBIND, + (uintptr_t)&enabled, sizeof(enabled))); + assert(!call(__NR_bind, fd, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(!call(__NR_bind, isolated, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(call(__NR_bind, conflict, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EADDRINUSE); + address.sin_port = swap16(100); + assert(call(__NR_bind, low, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EACCES); + current.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; + assert(!call(__NR_bind, low, (uintptr_t)&address, sizeof(address), 0, 0)); + current.net_ns = first; + assert(call(__NR_bind, initial, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EACCES); + current.user_ns = sibling; + address.sin_port = swap16(101); + assert(call(__NR_bind, conflict, (uintptr_t)&address, sizeof(address), 0, 0) == -LINUX_EACCES); + current.user_ns = owner; + assert(!call(__NR_bind, conflict, (uintptr_t)&address, sizeof(address), 0, 0)); + current = saved; + for (unsigned i = 0; i < sizeof(descriptions) / sizeof(descriptions[0]); ++i) close_udp(descriptions[i]); + net_namespace_put(first); + net_namespace_put(second); + user_namespace_put(owner); + user_namespace_put(sibling); + assert(allocations == baseline); + puts("PASS UDP freebind creating-network isolation and privileged-port owner authority"); +} + /* Unrelated proc tables stay empty, while the real dispatcher selects scope. */ struct net_socket; struct net_socket *net_sockets; @@ -357,6 +842,21 @@ static void test_udp_namespace_failures_and_owner(int domain) current.user_ns = owner; current.cap_effective = 0; assert(call(__NR_bind, no_cap, (uintptr_t)bind_address, bind_length, 0, 0) == -LINUX_EACCES); + int index = NET_IF_LOOPBACK; + assert(!call(__NR_setsockopt, local, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index))); + assert(!call(__NR_setsockopt, initial, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index))); + index = 0; + current.cap_effective = 1ULL << CAP_NET_RAW; + current.user_ns = sibling; + assert(call(__NR_setsockopt, local, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index)) == -LINUX_EPERM); + current.user_ns = owner; + assert(!call(__NR_setsockopt, local, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index))); + assert(call(__NR_setsockopt, initial, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index)) == -LINUX_EPERM); current = saved; close_udp(local); close_udp(initial); @@ -370,10 +870,360 @@ static void test_udp_namespace_failures_and_owner(int domain) printf("PASS UDP family %d owner CAP_NET_BIND_SERVICE and ENOMEM/EMFILE rollback\n", domain); } +/** @brief Exercise IPv4 options through Linux entry points and received metadata. */ +static void test_ipv4_packet_options(void) +{ + int sender = open_socket(), receiver = open_socket(); + assert(sender >= 0 && receiver >= 0); + int enabled = 1; + assert(!call(__NR_setsockopt, receiver, SOL_IP, IP_PKTINFO, + (uintptr_t)&enabled, sizeof(enabled))); + assert(!call(__NR_setsockopt, receiver, SOL_IP, IP_RECVTTL, + (uintptr_t)&enabled, sizeof(enabled))); + int ttl = 253; + assert(!call(__NR_setsockopt, sender, SOL_IP, IP_TTL, + (uintptr_t)&ttl, sizeof(ttl))); + int value = 0; + uint32_t size = sizeof(value); + assert(!call(__NR_getsockopt, sender, SOL_IP, IP_TTL, + (uintptr_t)&value, (uintptr_t)&size)); + assert(value == 253 && size == sizeof(value)); + struct sockaddr_in address = {.sin_family = AF_INET, .sin_port = swap16(55120), + .sin_addr.s_addr = swap32(0x7f000001)}; + assert(!call(__NR_bind, receiver, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(task_udp_send(&files[sender], "ttl", 3, 0, (uintptr_t)&address, sizeof(address)) == 3); + struct net_udp_rx_info info = {0}; + char data[8]; + assert(task_udp_recv_ex(&files[receiver], data, sizeof(data), MSG_PEEK, + NULL, NULL, &info) == 3); + assert(!memcmp(data, "ttl", 3) && info.pktinfo && info.hoplimit); + assert(info.ifindex == NET_IF_LOOPBACK && info.hops == 253); + assert(udp6_unmap(&info.destination) == 0x7f000001); + assert(task_udp_recv_ex(&files[receiver], data, sizeof(data), 0, NULL, NULL, &info) == 3); + ttl = 0; + assert(call(__NR_setsockopt, sender, SOL_IP, IP_TTL, + (uintptr_t)&ttl, sizeof(ttl)) == -LINUX_EINVAL); + ttl = -1; + assert(!call(__NR_setsockopt, sender, SOL_IP, IP_TTL, + (uintptr_t)&ttl, sizeof(ttl))); + size = sizeof(value); + assert(!call(__NR_getsockopt, sender, SOL_IP, IP_TTL, + (uintptr_t)&value, (uintptr_t)&size) && value == 64); + unsigned char multicast_ttl = 255; + assert(!call(__NR_setsockopt, sender, SOL_IP, IP_MULTICAST_TTL, + (uintptr_t)&multicast_ttl, sizeof(multicast_ttl))); + ttl = 256; + assert(call(__NR_setsockopt, sender, SOL_IP, IP_MULTICAST_TTL, + (uintptr_t)&ttl, sizeof(ttl)) == -LINUX_EINVAL); + size = sizeof(value); + assert(!call(__NR_getsockopt, sender, SOL_IP, IP_MULTICAST_TTL, + (uintptr_t)&value, (uintptr_t)&size) && value == 255); + assert(call(__NR_setsockopt, sender, SOL_IP, IP_TTL, 1, sizeof(ttl)) == -LINUX_EFAULT); + assert(call(__NR_setsockopt, sender, SOL_IP, IP_RECVTTL, + (uintptr_t)&ttl, 0) == -LINUX_EINVAL); + close_udp(sender); + close_udp(receiver); + loopback_bytes = loopback_packets = 0; + puts("PASS IPv4 UDP options, loopback TTL, packet metadata and invalid option rollback"); +} + +/** @brief Check IPv4 group subscriptions, fanout, all-groups policy and release. */ +static void test_ipv4_multicast_membership(void) +{ + int first = open_socket(), second = open_socket(); + int enabled = 1; + assert(!call(__NR_setsockopt, first, SOL_SOCKET, SO_REUSEADDR, (uintptr_t)&enabled, sizeof(enabled))); + assert(!call(__NR_setsockopt, second, SOL_SOCKET, SO_REUSEADDR, (uintptr_t)&enabled, sizeof(enabled))); + struct sockaddr_in address = {.sin_family = AF_INET, .sin_port = swap16(5353)}; + assert(!call(__NR_bind, first, (uintptr_t)&address, sizeof(address), 0, 0)); + assert(!call(__NR_bind, second, (uintptr_t)&address, sizeof(address), 0, 0)); + struct ip_mreqn group = {.imr_multiaddr.s_addr = swap32(0xe00000fb), .imr_ifindex = 2}; + assert(!call(__NR_setsockopt, first, SOL_IP, IP_ADD_MEMBERSHIP, (uintptr_t)&group, sizeof(group))); + assert(call(__NR_setsockopt, first, SOL_IP, IP_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group)) == -LINUX_EADDRINUSE); + net_udp_input_ex(NULL, 0x0a000202, 0xe00000fb, 5353, 5353, "mdns", 4, 2, 255); + assert(task_udp_available(&files[first]) == 4 && task_udp_available(&files[second]) == 4); + char bytes[8]; + struct net_udp_rx_info info; + assert(task_udp_recv_ex(&files[first], bytes, sizeof(bytes), 0, NULL, NULL, &info) == 4); + assert(info.hops == 255 && info.ifindex == 2); + assert(task_udp_recv(&files[second], bytes, sizeof(bytes), 0, 0, 0) == 4); + enabled = 0; + assert(!call(__NR_setsockopt, second, SOL_IP, IP_MULTICAST_ALL, (uintptr_t)&enabled, sizeof(enabled))); + net_udp_input_ex(NULL, 0x0a000202, 0xe00000fb, 5353, 5353, "mdns", 4, 2, 255); + assert(task_udp_available(&files[first]) == 4 && !task_udp_available(&files[second])); + assert(task_udp_recv(&files[first], bytes, sizeof(bytes), 0, 0, 0) == 4); + assert(!call(__NR_setsockopt, first, SOL_IP, IP_DROP_MEMBERSHIP, (uintptr_t)&group, sizeof(group))); + assert(call(__NR_setsockopt, first, SOL_IP, IP_DROP_MEMBERSHIP, + (uintptr_t)&group, sizeof(group)) == -LINUX_EADDRNOTAVAIL); + net_udp_input_ex(NULL, 0x0a000202, 0xe00000fb, 5353, 5353, "none", 4, 2, 255); + assert(!task_udp_available(&files[first]) && !task_udp_available(&files[second])); + group.imr_multiaddr.s_addr = swap32(0x0a000202); + assert(call(__NR_setsockopt, first, SOL_IP, IP_ADD_MEMBERSHIP, + (uintptr_t)&group, sizeof(group)) == -LINUX_EINVAL); + close_udp(first); + close_udp(second); + puts("PASS IPv4 multicast membership, fanout, policy, leave and validation"); +} + +/** @brief Check numeric device binding, lengths, permissions and creating scope. */ +static void test_udp_interface_index(void) +{ + struct task saved = current; + struct net_namespace *other; + assert(!net_namespace_create(NULL, &other)); + for (unsigned family = 0; family < 2; ++family) { + current = saved; + current.cap_effective &= ~(1ULL << CAP_NET_RAW); + int fd = (int)call(__NR_socket, family ? AF_INET6 : AF_INET, + SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + assert(fd >= 0); + int index = 2; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index))); + current.net_ns = other; + int selected = -1; + uint32_t length = sizeof(selected); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&selected, (uintptr_t)&length)); + assert(selected == 2 && length == sizeof(selected)); + char name[NET_IF_NAME_LEN]; + length = sizeof(name); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_BINDTODEVICE, + (uintptr_t)name, (uintptr_t)&length)); + assert(!strcmp(name, "eth0")); + index = 0; + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index)) == -LINUX_EPERM); + current.cap_effective |= 1ULL << CAP_NET_RAW; + index = -1; + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index)) == -LINUX_EINVAL); + index = 99; + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, 3) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + 0, sizeof(index)) == -LINUX_EFAULT); + length = sizeof(selected); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&selected, (uintptr_t)&length)); + assert(selected == 2); + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index))); + unsigned char short_value[2] = {0xcc, 0xdd}; + length = 1; + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)short_value, (uintptr_t)&length)); + assert(length == 1 && short_value[0] == 99 && short_value[1] == 0xdd); + length = 0; + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + 0, (uintptr_t)&length)); + assert(!length); + length = UINT32_MAX; + assert(call(__NR_getsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&selected, (uintptr_t)&length) == -LINUX_EINVAL); + index = 0; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&index, sizeof(index))); + close_udp(fd); + } + current = saved; + assert(other->references == 1); + net_namespace_put(other); + puts("PASS numeric device binding, creating network, permissions, stale indices and user lengths"); +} + +/** @brief Check network-order unicast selection without receive device binding. */ +static void test_udp_unicast_interface(void) +{ + struct task saved = current; + struct net_namespace *isolated; + assert(!net_namespace_create(NULL, &isolated)); + current.cap_effective = 0; + for (unsigned family = 0; family < 2; ++family) { + current.net_ns = NULL; + int fd = (int)call(__NR_socket, family ? AF_INET6 : AF_INET, + SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + assert(fd >= 0); + int level = family ? SOL_IPV6 : SOL_IP; + int option = family ? IPV6_UNICAST_IF : IP_UNICAST_IF; + uint32_t selected = swap32(2), value = 0, length = sizeof(value); + assert(!call(__NR_setsockopt, fd, level, option, (uintptr_t)&selected, sizeof(selected))); + current.net_ns = isolated; + assert(!call(__NR_getsockopt, fd, level, option, (uintptr_t)&value, (uintptr_t)&length)); + assert(value == selected && length == sizeof(value)); + assert(udp_from_file(&files[fd])->ifindex == 0); + selected = swap32(99); + assert(call(__NR_setsockopt, fd, level, option, (uintptr_t)&selected, + sizeof(selected)) == -LINUX_EADDRNOTAVAIL); + selected = swap32(2); + assert(call(__NR_setsockopt, fd, level, option, (uintptr_t)&selected, 3) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, fd, level, option, (uintptr_t)&selected, 5) == -LINUX_EINVAL); + assert(call(__NR_setsockopt, fd, level, option, 1, sizeof(selected)) == -LINUX_EFAULT); + int bound = NET_IF_LOOPBACK; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&bound, sizeof(bound))); + assert(call(__NR_setsockopt, fd, level, option, (uintptr_t)&selected, + sizeof(selected)) == -LINUX_EINVAL); + selected = 0; + assert(!call(__NR_setsockopt, fd, level, option, (uintptr_t)&selected, sizeof(selected))); + current.cap_effective = 1ULL << CAP_NET_RAW; + bound = 0; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, + (uintptr_t)&bound, sizeof(bound))); + close_udp(fd); + current.cap_effective = 0; + fd = (int)call(__NR_socket, family ? AF_INET6 : AF_INET, + SOCK_DGRAM | SOCK_NONBLOCK, 0, 0, 0); + selected = swap32(2); + current.net_ns = NULL; + assert(call(__NR_setsockopt, fd, level, option, (uintptr_t)&selected, + sizeof(selected)) == -LINUX_EADDRNOTAVAIL); + close_udp(fd); + } + current = saved; + int sender = open_socket(), receiver = open_socket(); + uint32_t selected = swap32(2); + assert(!call(__NR_setsockopt, sender, SOL_IP, IP_UNICAST_IF, (uintptr_t)&selected, sizeof(selected))); + struct sockaddr_in local = {.sin_family = AF_INET, .sin_port = swap16(55131), + .sin_addr.s_addr = swap32(0x7f000001)}; + assert(!call(__NR_bind, receiver, (uintptr_t)&local, sizeof(local), 0, 0)); + assert(task_udp_send(&files[sender], "uif", 3, 0, (uintptr_t)&local, sizeof(local)) == -LINUX_ENETUNREACH); + struct net_udp_tx_info override = {.ifindex = NET_IF_LOOPBACK, .ttl = -1, .hops = -1}; + assert(task_udp_send_ex(&files[sender], "uif", 3, 0, (uintptr_t)&local, sizeof(local), &override) == 3); + char bytes[4]; + assert(task_udp_recv(&files[receiver], bytes, sizeof(bytes), 0, 0, 0) == 3); + selected = swap32(NET_IF_LOOPBACK); + assert(!call(__NR_setsockopt, sender, SOL_IP, IP_UNICAST_IF, (uintptr_t)&selected, sizeof(selected))); + assert(task_udp_send(&files[sender], "uif", 3, 0, (uintptr_t)&local, sizeof(local)) == 3); + assert(task_udp_recv(&files[receiver], bytes, sizeof(bytes), 0, 0, 0) == 3); + close_udp(sender); + close_udp(receiver); + net_namespace_put(isolated); + loopback_bytes = loopback_packets = 0; + puts("PASS UDP unicast interface byte order, creating network, validation and send override"); +} + +/** @brief Require the DNS socket error option and independent nonblocking queue. */ +static void test_udp_receive_error_option(void) +{ + int fd = open_socket(); + int enabled = 1; + assert(!call(__NR_setsockopt, fd, SOL_IP, 11, (uintptr_t)&enabled, sizeof(enabled))); + enabled = -1; + uint32_t size = sizeof(enabled); + assert(!call(__NR_getsockopt, fd, SOL_IP, 11, (uintptr_t)&enabled, (uintptr_t)&size)); + assert(enabled == 1 && size == sizeof(enabled)); + char data[16]; + assert(task_udp_recv(&files[fd], data, sizeof(data), MSG_ERRQUEUE, 0, 0) == -LINUX_EAGAIN); + close_udp(fd); +} + +#ifndef IPV6_TRANSPORT_FIXTURE +/** @brief Deliver real ICMP errors and verify queue ownership, metadata and cleanup. */ +static void test_udp_icmp_error_queue(void) +{ + uint64_t capabilities = current.cap_effective; + current.cap_effective |= 1ULL << CAP_NET_RAW; + int fd = open_socket(), enabled = 1; + struct sockaddr_in local = {.sin_family = AF_INET, .sin_port = swap16(55131), + .sin_addr.s_addr = swap32(0x0a00020f)}; + assert(!call(__NR_bind, fd, (uintptr_t)&local, sizeof(local), 0, 0)); + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_RECVERR, (uintptr_t)&enabled, sizeof(enabled))); + struct net_namespace *other; + assert(!net_namespace_create(NULL, &other)); + current.net_ns = other; + int isolated = open_socket(); + struct sockaddr_in any = {.sin_family = AF_INET, .sin_port = local.sin_port}; + assert(!call(__NR_bind, isolated, (uintptr_t)&any, sizeof(any), 0, 0)); + assert(!call(__NR_setsockopt, isolated, SOL_IP, IP_RECVERR, (uintptr_t)&enabled, sizeof(enabled))); + current.net_ns = NULL; + uint8_t frame[14 + 20 + 8 + 20 + 8 + 4] = {0}; + uint8_t *ip = frame + 14, *icmp = ip + 20, *quote = icmp + 8; + ip[0] = quote[0] = 0x45; + ip[8] = quote[8] = 64; + ip[9] = 1; quote[9] = 17; + net_put_u16(ip + 2, sizeof(frame) - 14); + net_put_u32(ip + 12, 0x0a000202); net_put_u32(ip + 16, 0x0a00020f); + net_put_u16(ip + 10, net_checksum(ip, 20)); + icmp[0] = 3; icmp[1] = 3; + net_put_u16(quote + 2, 32); + net_put_u32(quote + 12, 0x0a00020f); net_put_u32(quote + 16, 0x0a000203); + net_put_u16(quote + 10, net_checksum(quote, 20)); + net_put_u16(quote + 20, 55131); net_put_u16(quote + 22, 53); + net_put_u16(quote + 24, 12); memcpy(quote + 28, "dns!", 4); + net_put_u16(icmp + 2, net_checksum(icmp, 40)); + unsigned retained = allocations; + net_handle_ipv4_on(2, frame, sizeof(frame), NULL, NULL, NULL); + assert(task_udp_poll(&files[fd], 0) & POLLERR); + assert(!(task_udp_poll(&files[isolated], 0) & POLLERR)); + char bytes[8] = {0}; + struct sockaddr_storage destination; + uint32_t size; + struct net_udp_rx_info info; + int error = 0; size = sizeof(error); + assert(!call(__NR_getsockopt, fd, SOL_SOCKET, SO_ERROR, (uintptr_t)&error, (uintptr_t)&size)); + assert(error == LINUX_ECONNREFUSED && (task_udp_poll(&files[fd], 0) & POLLERR)); + assert(task_udp_recv_ex(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE | MSG_PEEK, + &destination, &size, &info) == 4); + assert(info.error_queue && info.ipv4 && !memcmp(bytes, "dns!", 4)); + assert(info.extended.error.ee_errno == LINUX_ECONNREFUSED); + assert(info.extended.error.ee_origin == SO_EE_ORIGIN_ICMP); + assert(info.extended.error.ee_type == 3 && info.extended.error.ee_code == 3); + const struct sockaddr_in *offender = (const void *)&info.extended.offender; + const struct sockaddr_in *to = (const void *)&destination; + assert(offender->sin_family == AF_INET && offender->sin_addr.s_addr == swap32(0x0a000202)); + assert(size == sizeof(*to) && to->sin_addr.s_addr == swap32(0x0a000203) && to->sin_port == swap16(53)); + assert(task_udp_recv(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE, 0, 0) == -LINUX_EAGAIN); + assert(!(task_udp_poll(&files[fd], 0) & POLLERR) && allocations == retained); + /* Corrupt checksums and wrong ingress links cannot inject errors. */ + icmp[2] ^= 1; + net_handle_ipv4_on(2, frame, sizeof(frame), NULL, NULL, NULL); + assert(!(task_udp_poll(&files[fd], 0) & POLLERR)); + icmp[2] ^= 1; + int index = 3; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, (uintptr_t)&index, sizeof(index))); + net_handle_ipv4_on(2, frame, sizeof(frame), NULL, NULL, NULL); + assert(!(task_udp_poll(&files[fd], 0) & POLLERR)); + index = 0; + assert(!call(__NR_setsockopt, fd, SOL_SOCKET, SO_BINDTOIFINDEX, (uintptr_t)&index, sizeof(index))); + allocation_fail_after = 0; + net_handle_ipv4_on(2, frame, sizeof(frame), NULL, NULL, NULL); + allocation_fail_after = -1; + assert(allocations == retained && (task_udp_poll(&files[fd], 0) & POLLERR)); + assert(task_udp_recv(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE, 0, 0) == -LINUX_EAGAIN); + /* Disabling error delivery frees records while preserving pending SO_ERROR. */ + net_handle_ipv4_on(2, frame, sizeof(frame), NULL, NULL, NULL); + enabled = 0; + assert(!call(__NR_setsockopt, fd, SOL_IP, IP_RECVERR, (uintptr_t)&enabled, sizeof(enabled))); + assert(allocations == retained && (task_udp_poll(&files[fd], 0) & POLLERR)); + close_udp(fd); + close_udp(isolated); + assert(other->references == 1); + net_namespace_put(other); + current.cap_effective = capabilities; + puts("PASS IPv4 ICMP error queue, original destination, PEEK consumption, SO_ERROR and OOM cleanup"); +} +#endif + int main(void) { + test_udp_unicast_interface(); + test_udp_receive_error_option(); +#ifndef IPV6_TRANSPORT_FIXTURE + test_udp_icmp_error_queue(); +#endif current.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; current.euid = 1234; + test_udp_priority(); + test_udp_priority_owner(); + test_udp_tos(); + test_udp_tos_wire(); + test_udp_freebind(); + test_udp_freebind_owner(); + test_udp_interface_index(); + test_ipv4_packet_options(); + test_ipv4_multicast_membership(); test_udp_namespace_bind(); test_udp_namespace_failures_and_owner(AF_INET); test_udp_device_local_delivery(); From ff6840a0e392223b103f78806d4f2105b457d09a Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 12:34:26 +0800 Subject: [PATCH 79/97] feat(net): integrate networkd IPv6 controls and ping error queues --- Documentation/core-api/network-devices.rst | 28 ++ .../LC_MESSAGES/core-api/network-devices.po | 39 +++ .../LC_MESSAGES/core-api/network-devices.po | 39 +++ fs/proc/Kbuild | 2 +- fs/proc/internal.h | 59 ++++- fs/proc/mount.c | 3 +- fs/proc/network.c | 240 ++++++++++++++++++ fs/proc/procfs.c | 49 +++- fs/proc/views.c | 10 + fs/vfs/pseudo.c | 8 +- include/reliefnt/net_ipv6.h | 39 ++- include/reliefnt/net_packet.h | 12 +- include/reliefnt/pseudo_fs.h | 8 +- include/uapi/linux/if_link.h | 8 + kernel/syscall/ipc/socket.c | 7 +- net/ipv6/core.c | 239 +++++++++++++++-- net/ipv6/internal.h | 5 + net/ipv6/state.c | 10 +- net/socket/netlink.c | 79 +++++- net/socket/packet.c | 124 ++++++++- tools/test_ipv6_transport.py | 1 + tools/test_net_multi_interface.py | 3 +- tools/test_procfs.py | 5 +- tools/tests/ipv6_control_test.c | 113 ++++++++- tools/tests/ipv6_protocol_test.c | 144 +++++++++++ tools/tests/ipv6_tcp_test.c | 1 + tools/tests/ipv6_transport_test.c | 113 +++++++++ tools/tests/ipv6_vector_stubs.c | 5 - tools/tests/ipv6_vector_test.c | 78 ++++++ tools/tests/net_multi_interface_test.c | 15 ++ tools/tests/procfs_network_test.c | 187 ++++++++++++++ 31 files changed, 1598 insertions(+), 75 deletions(-) create mode 100644 fs/proc/network.c create mode 100644 tools/tests/procfs_network_test.c diff --git a/Documentation/core-api/network-devices.rst b/Documentation/core-api/network-devices.rst index 8c610a88..ad96d2e5 100644 --- a/Documentation/core-api/network-devices.rst +++ b/Documentation/core-api/network-devices.rst @@ -55,6 +55,30 @@ Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路 ``SIOCGIFCONF`` 按 Linux 的 IPv4 地址列表语义输出 loopback 和有地址的接口。 枚举硬件接口可使用 rtnetlink 或 ``/proc/net/dev``,并按名称查询 ifindex。 +IPv6 host controls +================== + +``/proc/sys/net/ipv6/conf//`` 提供 ``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode`` 和 ``use_tempaddr``。配置和协议状态由网络空间持有。打开的文件保留目标网络和稳定 ifindex,接口改名或调用者切换网络后继续操作原目标,接口移除后返回 ``ENODEV``。 + +控制文件为 0644,读取公开,写入按当前凭据检查全局 root 身份或目标网络 user owner 的 ``CAP_NET_ADMIN``,只读挂载仍拒绝写入。整数输入接受符号、十六进制、八进制及首尾 ASCII 空白,溢出和非法输入返回 ``EINVAL``。非零偏移写入消耗输入而不改变配置。 + +默认值为启用 IPv6、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0`` 和 ``use_tempaddr=0``。修改 ``default`` 影响随后创建的接口,已有接口包括行政关闭的接口保留原值。写入 ``all/disable_ipv6`` 或 ``all/addr_gen_mode`` 同时更新默认值和现存接口,其他 ``all`` 控制保留独立值。 + +``disable_ipv6`` 接受 0 和 1,禁用时清理链路 IPv6 状态并停止收发。重新启用时按链路配置恢复自动地址。``accept_ra`` 接受 0、1 和 2,0 停止内核 RA 处理和 RS,1 与 2 启用当前主机模式的 RA 处理。官方 networkd 将该值设为 0 后,通过自己的发现协议处理 RA。``hop_limit`` 接受 1 至 255,供未指定跳数的实际发包使用,内核接收的有效 RA 可以更新该值。 + +``addr_gen_mode`` 支持 EUI64 模式 0 和关闭自动链路本地地址的模式 1,切换为 1 保留已有地址。模式 2、3 和正数 ``use_tempaddr`` 返回 ``EOPNOTSUPP``,稳定隐私地址和临时地址生成仍待实现。``RTM_SETLINK`` 和 ``RTM_NEWLINK`` 接受 ``IFLA_AF_SPEC`` 下的 ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE``,查询和链路通知回报实际模式,嵌套属性允许 ``NLA_F_NESTED`` 标记。 + +启用控制先检查地址、路由和多播容量,再更新配置及协议表。分配或容量失败保留可见配置和协议状态,可在资源释放后重试。普通 Ethernet 链路在自动地址表耗尽时仍可用于手动地址配置。IPv4 次地址提升控制 ``promote_secondaries`` 仍待接入。 + +IPv6 raw and ping errors +======================== + +IPv6 raw socket 和 ICMPv6 ping socket 支持 ``IPV6_RECVERR``,每个 socket 独立保存最多 32 条扩展错误。错误记录持有被引用报文的上层载荷、原目标地址、``sock_extended_err`` 和产生错误的节点地址,按创建网络、接口、作用域、本地地址及连接目标匹配。ping socket 还校验 Echo Request 类型、code 和 identifier。 + +``recvmsg(MSG_ERRQUEUE)`` 返回扩展错误控制消息,``recvfrom(MSG_ERRQUEUE)`` 返回载荷和原目标地址。外部 ``MSG_PEEK`` 仍消费一条错误,空错误队列返回 ``EAGAIN``。内部换页探测保留记录,输出内存准备成功后才消费。普通收包队列独立保留。``SO_ERROR`` 清除待报告 errno 后,未读扩展错误仍产生 ``POLLERR``。 + +关闭 ``IPV6_RECVERR`` 清理扩展错误队列并保留待报告 errno。队列满或分配失败保留已有记录及待报告错误,最后关闭 socket 时释放全部队列和网络引用。 + Validation ========== @@ -63,6 +87,10 @@ Validation ``tools/test_net_multinic_data.py`` 验证 ARP、UDP 输出和 AF_PACKET 隔离。 既有 TCP、UDP 和 IPv6 定向套件覆盖对应传输的设备绑定、作用域与资源清理。 +``tools/test_ipv6_protocol.py`` 覆盖控制值、协议副作用、默认继承、网络隔离和容量失败重试。``tools/test_ipv6_control.py`` 覆盖 networkd 嵌套地址生成属性、查询及权限。``tools/test_procfs.py`` 覆盖控制文件的 VFS 生命周期、当前凭据、解析、只读挂载、改名、移除和内存失败。 + +``tools/test_ipv6_transport.py`` 使用实际 raw/ping 实现验证扩展错误、identifier 和网络隔离、队列容量、分配失败与关闭清理,并通过实际 ``recvmsg`` 入口验证辅助数据和换页重试期间的安全消费。 + ``tools/tests/multinic_guest.c`` 是标准 socket 用户程序探针,由 ReliefOS 的 ``tools/test_multi_nic_qemu.py`` 放入私有来宾执行。来宾使用两张 e1000 和 一张 e1000e,验证独立 DHCP、IPv4/IPv6、并发 TCP/UDP,以及模块卸载期间 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po index ee099196..a67196cb 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po @@ -167,3 +167,42 @@ msgid "" msgstr "" "`IPv6 scoped address architecture, RFC 4007 `_" + +msgid "IPv6 host controls" +msgstr "IPv6 host controls" + +msgid "``/proc/sys/net/ipv6/conf//`` 提供 ``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode`` 和 ``use_tempaddr``。配置和协议状态由网络空间持有。打开的文件保留目标网络和稳定 ifindex,接口改名或调用者切换网络后继续操作原目标,接口移除后返回 ``ENODEV``。" +msgstr "``/proc/sys/net/ipv6/conf//`` provides ``disable_ipv6``, ``accept_ra``, ``hop_limit``, ``addr_gen_mode`` and ``use_tempaddr``. The network namespace owns configuration and protocol state. An open file retains its target network and stable ifindex across interface renames and caller network changes. Interface removal returns ``ENODEV``." + +msgid "控制文件为 0644,读取公开,写入按当前凭据检查全局 root 身份或目标网络 user owner 的 ``CAP_NET_ADMIN``,只读挂载仍拒绝写入。整数输入接受符号、十六进制、八进制及首尾 ASCII 空白,溢出和非法输入返回 ``EINVAL``。非零偏移写入消耗输入而不改变配置。" +msgstr "Control files have mode 0644 and are publicly readable. Writes check current credentials for global root identity or ``CAP_NET_ADMIN`` in the target network's user owner. Read-only mounts reject writes. Integer input accepts signs, hexadecimal, octal and surrounding ASCII whitespace. Overflow and malformed input return ``EINVAL``. Writes at nonzero offsets consume input without changing configuration." + +msgid "默认值为启用 IPv6、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0`` 和 ``use_tempaddr=0``。修改 ``default`` 影响随后创建的接口,已有接口包括行政关闭的接口保留原值。写入 ``all/disable_ipv6`` 或 ``all/addr_gen_mode`` 同时更新默认值和现存接口,其他 ``all`` 控制保留独立值。" +msgstr "Defaults enable IPv6 with ``accept_ra=1``, ``hop_limit=64``, ``addr_gen_mode=0`` and ``use_tempaddr=0``. Changing ``default`` affects interfaces created afterwards. Existing interfaces, including administratively down interfaces, retain their values. Writes to ``all/disable_ipv6`` or ``all/addr_gen_mode`` update defaults and existing interfaces together. Other ``all`` controls retain independent values." + +msgid "``disable_ipv6`` 接受 0 和 1,禁用时清理链路 IPv6 状态并停止收发。重新启用时按链路配置恢复自动地址。``accept_ra`` 接受 0、1 和 2,0 停止内核 RA 处理和 RS,1 与 2 启用当前主机模式的 RA 处理。官方 networkd 将该值设为 0 后,通过自己的发现协议处理 RA。``hop_limit`` 接受 1 至 255,供未指定跳数的实际发包使用,内核接收的有效 RA 可以更新该值。" +msgstr "``disable_ipv6`` accepts 0 and 1. Disabling clears link IPv6 state and stops transmission and reception. Re-enabling restores automatic addresses according to link policy. ``accept_ra`` accepts 0, 1 and 2. Zero stops kernel RA processing and RS. Values 1 and 2 enable RA processing in the current host mode. Official networkd sets this value to zero and processes RA with its own discovery protocol. ``hop_limit`` accepts 1 through 255 and supplies the actual packet hop limit when none is specified. Valid RA received by the kernel can update it." + +msgid "``addr_gen_mode`` 支持 EUI64 模式 0 和关闭自动链路本地地址的模式 1,切换为 1 保留已有地址。模式 2、3 和正数 ``use_tempaddr`` 返回 ``EOPNOTSUPP``,稳定隐私地址和临时地址生成仍待实现。``RTM_SETLINK`` 和 ``RTM_NEWLINK`` 接受 ``IFLA_AF_SPEC`` 下的 ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE``,查询和链路通知回报实际模式,嵌套属性允许 ``NLA_F_NESTED`` 标记。" +msgstr "``addr_gen_mode`` supports EUI64 mode 0 and mode 1, which disables automatic link-local addresses. Switching to mode 1 retains existing addresses. Modes 2 and 3 and positive ``use_tempaddr`` values return ``EOPNOTSUPP``. Stable-privacy and temporary address generation remain pending. ``RTM_SETLINK`` and ``RTM_NEWLINK`` accept ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE`` under ``IFLA_AF_SPEC``. Queries and link notifications report the actual mode. Nested attributes accept ``NLA_F_NESTED`` markers." + +msgid "启用控制先检查地址、路由和多播容量,再更新配置及协议表。分配或容量失败保留可见配置和协议状态,可在资源释放后重试。普通 Ethernet 链路在自动地址表耗尽时仍可用于手动地址配置。IPv4 次地址提升控制 ``promote_secondaries`` 仍待接入。" +msgstr "Enable controls check address, route and multicast capacity before updating configuration and protocol tables. Allocation or capacity failure preserves visible controls and protocol state, allowing a retry after resources are released. Ordinary Ethernet links remain available for manual addresses when automatic-address tables are exhausted. IPv4 secondary-address promotion through ``promote_secondaries`` remains pending." + +msgid "``tools/test_ipv6_protocol.py`` 覆盖控制值、协议副作用、默认继承、网络隔离和容量失败重试。``tools/test_ipv6_control.py`` 覆盖 networkd 嵌套地址生成属性、查询及权限。``tools/test_procfs.py`` 覆盖控制文件的 VFS 生命周期、当前凭据、解析、只读挂载、改名、移除和内存失败。" +msgstr "``tools/test_ipv6_protocol.py`` covers control values, protocol effects, default inheritance, network isolation and capacity-failure retry. ``tools/test_ipv6_control.py`` covers networkd nested address-generation attributes, queries and authority. ``tools/test_procfs.py`` covers control-file VFS lifetime, current credentials, parsing, read-only mounts, rename, removal and allocation failure." + +msgid "IPv6 raw and ping errors" +msgstr "IPv6 raw and ping errors" + +msgid "IPv6 raw socket 和 ICMPv6 ping socket 支持 ``IPV6_RECVERR``,每个 socket 独立保存最多 32 条扩展错误。错误记录持有被引用报文的上层载荷、原目标地址、``sock_extended_err`` 和产生错误的节点地址,按创建网络、接口、作用域、本地地址及连接目标匹配。ping socket 还校验 Echo Request 类型、code 和 identifier。" +msgstr "IPv6 raw and ICMPv6 ping sockets support ``IPV6_RECVERR``, retaining up to 32 extended errors per socket. Each record owns the quoted upper-layer payload, original destination, ``sock_extended_err`` and offender address. Matching uses the creating network, interface, scope, local address and connected destination. Ping sockets also validate the Echo Request type, code and identifier." + +msgid "``recvmsg(MSG_ERRQUEUE)`` 返回扩展错误控制消息,``recvfrom(MSG_ERRQUEUE)`` 返回载荷和原目标地址。外部 ``MSG_PEEK`` 仍消费一条错误,空错误队列返回 ``EAGAIN``。内部换页探测保留记录,输出内存准备成功后才消费。普通收包队列独立保留。``SO_ERROR`` 清除待报告 errno 后,未读扩展错误仍产生 ``POLLERR``。" +msgstr "``recvmsg(MSG_ERRQUEUE)`` returns extended-error control messages, while ``recvfrom(MSG_ERRQUEUE)`` returns the payload and original destination. External ``MSG_PEEK`` still consumes one error. An empty error queue returns ``EAGAIN``. Internal swap probes retain the record until output memory is prepared successfully. The ordinary receive queue remains independent. Unread extended errors continue to report ``POLLERR`` after ``SO_ERROR`` clears the pending errno." + +msgid "关闭 ``IPV6_RECVERR`` 清理扩展错误队列并保留待报告 errno。队列满或分配失败保留已有记录及待报告错误,最后关闭 socket 时释放全部队列和网络引用。" +msgstr "Disabling ``IPV6_RECVERR`` clears the extended-error queue and preserves the pending errno. A full queue or allocation failure preserves existing records and the pending error. Final socket close releases all queues and network references." + +msgid "``tools/test_ipv6_transport.py`` 使用实际 raw/ping 实现验证扩展错误、identifier 和网络隔离、队列容量、分配失败与关闭清理,并通过实际 ``recvmsg`` 入口验证辅助数据和换页重试期间的安全消费。" +msgstr "``tools/test_ipv6_transport.py`` exercises the real raw/ping implementation for extended errors, identifier and network isolation, queue bounds, allocation failures and close cleanup. The real ``recvmsg`` entry validates ancillary data and safe consumption across swap retries." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po index c30a0014..13ac0179 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po @@ -145,3 +145,42 @@ msgid "" "editor.org/rfc/rfc4007>`_" msgstr "" "`IPv6 スコープ付きアドレスアーキテクチャ、RFC 4007 `_" + +msgid "IPv6 host controls" +msgstr "IPv6 ホスト制御" + +msgid "``/proc/sys/net/ipv6/conf//`` 提供 ``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode`` 和 ``use_tempaddr``。配置和协议状态由网络空间持有。打开的文件保留目标网络和稳定 ifindex,接口改名或调用者切换网络后继续操作原目标,接口移除后返回 ``ENODEV``。" +msgstr "``/proc/sys/net/ipv6/conf//`` は ``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode``、``use_tempaddr`` を提供します。設定とプロトコル状態はネットワーク名前空間が所有します。開いたファイルは対象ネットワークと固定 ifindex を保持し、インターフェース名や呼び出し元ネットワークが変わっても元の対象を操作します。インターフェース削除後は ``ENODEV`` を返します。" + +msgid "控制文件为 0644,读取公开,写入按当前凭据检查全局 root 身份或目标网络 user owner 的 ``CAP_NET_ADMIN``,只读挂载仍拒绝写入。整数输入接受符号、十六进制、八进制及首尾 ASCII 空白,溢出和非法输入返回 ``EINVAL``。非零偏移写入消耗输入而不改变配置。" +msgstr "制御ファイルのモードは 0644 で、読み取りは公開されています。書き込み時は現在の資格情報でグローバル root、または対象ネットワークの user owner における ``CAP_NET_ADMIN`` を確認します。読み取り専用マウントは書き込みを拒否します。整数入力は符号、16 進数、8 進数、前後の ASCII 空白を受け付け、オーバーフローや不正入力は ``EINVAL`` を返します。ゼロ以外のオフセットへの書き込みは入力を消費し、設定を維持します。" + +msgid "默认值为启用 IPv6、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0`` 和 ``use_tempaddr=0``。修改 ``default`` 影响随后创建的接口,已有接口包括行政关闭的接口保留原值。写入 ``all/disable_ipv6`` 或 ``all/addr_gen_mode`` 同时更新默认值和现存接口,其他 ``all`` 控制保留独立值。" +msgstr "既定では IPv6 が有効で、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0``、``use_tempaddr=0`` です。``default`` の変更は以後作成するインターフェースに適用します。管理上停止したものを含む既存インターフェースは元の値を保持します。``all/disable_ipv6`` または ``all/addr_gen_mode`` への書き込みは既定値と既存インターフェースを同時に更新します。他の ``all`` 制御は独立した値を保持します。" + +msgid "``disable_ipv6`` 接受 0 和 1,禁用时清理链路 IPv6 状态并停止收发。重新启用时按链路配置恢复自动地址。``accept_ra`` 接受 0、1 和 2,0 停止内核 RA 处理和 RS,1 与 2 启用当前主机模式的 RA 处理。官方 networkd 将该值设为 0 后,通过自己的发现协议处理 RA。``hop_limit`` 接受 1 至 255,供未指定跳数的实际发包使用,内核接收的有效 RA 可以更新该值。" +msgstr "``disable_ipv6`` は 0 と 1 を受け付け、無効化時はリンクの IPv6 状態を消去して送受信を停止します。再有効化時はリンク設定に従って自動アドレスを復元します。``accept_ra`` は 0、1、2 を受け付け、0 はカーネルの RA 処理と RS を停止し、1 と 2 は現在のホストモードの RA 処理を有効にします。公式 networkd はこの値を 0 に設定し、独自の探索プロトコルで RA を処理します。``hop_limit`` は 1 から 255 を受け付け、指定のない実際の送信パケットに使います。カーネルが受信した有効な RA はこの値を更新できます。" + +msgid "``addr_gen_mode`` 支持 EUI64 模式 0 和关闭自动链路本地地址的模式 1,切换为 1 保留已有地址。模式 2、3 和正数 ``use_tempaddr`` 返回 ``EOPNOTSUPP``,稳定隐私地址和临时地址生成仍待实现。``RTM_SETLINK`` 和 ``RTM_NEWLINK`` 接受 ``IFLA_AF_SPEC`` 下的 ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE``,查询和链路通知回报实际模式,嵌套属性允许 ``NLA_F_NESTED`` 标记。" +msgstr "``addr_gen_mode`` は EUI64 モード 0 と、自動リンクローカルアドレスを無効にするモード 1 に対応します。1 への変更時も既存アドレスを保持します。モード 2、3 と正の ``use_tempaddr`` は ``EOPNOTSUPP`` を返します。安定プライバシーアドレスと一時アドレスの生成は実装予定です。``RTM_SETLINK`` と ``RTM_NEWLINK`` は ``IFLA_AF_SPEC`` 内の ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE`` を受け付けます。照会とリンク通知は実際のモードを返し、ネスト属性は ``NLA_F_NESTED`` を受け付けます。" + +msgid "启用控制先检查地址、路由和多播容量,再更新配置及协议表。分配或容量失败保留可见配置和协议状态,可在资源释放后重试。普通 Ethernet 链路在自动地址表耗尽时仍可用于手动地址配置。IPv4 次地址提升控制 ``promote_secondaries`` 仍待接入。" +msgstr "有効化制御は設定とプロトコルテーブルを更新する前にアドレス、経路、マルチキャストの容量を確認します。割り当てや容量の失敗時は可視設定とプロトコル状態を保持し、資源解放後に再試行できます。通常の Ethernet リンクは自動アドレステーブルが満杯でも手動アドレスに利用できます。IPv4 の ``promote_secondaries`` による副アドレス昇格は実装予定です。" + +msgid "``tools/test_ipv6_protocol.py`` 覆盖控制值、协议副作用、默认继承、网络隔离和容量失败重试。``tools/test_ipv6_control.py`` 覆盖 networkd 嵌套地址生成属性、查询及权限。``tools/test_procfs.py`` 覆盖控制文件的 VFS 生命周期、当前凭据、解析、只读挂载、改名、移除和内存失败。" +msgstr "``tools/test_ipv6_protocol.py`` は制御値、プロトコルへの効果、既定値の継承、ネットワーク分離、容量不足後の再試行を検証します。``tools/test_ipv6_control.py`` は networkd のネストしたアドレス生成属性、照会、権限を検証します。``tools/test_procfs.py`` は制御ファイルの VFS ライフサイクル、現在の資格情報、解析、読み取り専用マウント、改名、削除、メモリー割り当て失敗を検証します。" + +msgid "IPv6 raw and ping errors" +msgstr "IPv6 raw と ping のエラー" + +msgid "IPv6 raw socket 和 ICMPv6 ping socket 支持 ``IPV6_RECVERR``,每个 socket 独立保存最多 32 条扩展错误。错误记录持有被引用报文的上层载荷、原目标地址、``sock_extended_err`` 和产生错误的节点地址,按创建网络、接口、作用域、本地地址及连接目标匹配。ping socket 还校验 Echo Request 类型、code 和 identifier。" +msgstr "IPv6 raw socket と ICMPv6 ping socket は ``IPV6_RECVERR`` に対応し、socket ごとに最大 32 件の拡張エラーを保持します。各レコードは引用パケットの上位層ペイロード、元の宛先、``sock_extended_err`` とエラー発生元アドレスを所有します。作成元ネットワーク、インターフェース、スコープ、ローカルアドレスと接続先で照合し、ping socket は Echo Request の型、code と identifier も検証します。" + +msgid "``recvmsg(MSG_ERRQUEUE)`` 返回扩展错误控制消息,``recvfrom(MSG_ERRQUEUE)`` 返回载荷和原目标地址。外部 ``MSG_PEEK`` 仍消费一条错误,空错误队列返回 ``EAGAIN``。内部换页探测保留记录,输出内存准备成功后才消费。普通收包队列独立保留。``SO_ERROR`` 清除待报告 errno 后,未读扩展错误仍产生 ``POLLERR``。" +msgstr "``recvmsg(MSG_ERRQUEUE)`` は拡張エラー制御メッセージを返し、``recvfrom(MSG_ERRQUEUE)`` はペイロードと元の宛先を返します。外部の ``MSG_PEEK`` でもエラーを 1 件消費し、空のエラーキューは ``EAGAIN`` を返します。内部のスワップ用プローブは出力メモリの準備が成功するまでレコードを保持します。通常の受信キューは独立して保持されます。``SO_ERROR`` が保留中の errno を消去しても、未読の拡張エラーは ``POLLERR`` を通知します。" + +msgid "关闭 ``IPV6_RECVERR`` 清理扩展错误队列并保留待报告 errno。队列满或分配失败保留已有记录及待报告错误,最后关闭 socket 时释放全部队列和网络引用。" +msgstr "``IPV6_RECVERR`` を無効にすると拡張エラーキューを解放し、保留中の errno を保持します。キューの満杯や割り当て失敗時も既存レコードと保留中のエラーを保持し、socket の最終クローズで全キューとネットワーク参照を解放します。" + +msgid "``tools/test_ipv6_transport.py`` 使用实际 raw/ping 实现验证扩展错误、identifier 和网络隔离、队列容量、分配失败与关闭清理,并通过实际 ``recvmsg`` 入口验证辅助数据和换页重试期间的安全消费。" +msgstr "``tools/test_ipv6_transport.py`` は実際の raw/ping 実装で拡張エラー、identifier とネットワークの分離、キュー上限、割り当て失敗とクローズ時の解放を検証します。実際の ``recvmsg`` 入口で補助データとスワップ再試行時の安全な消費を確認します。" diff --git a/fs/proc/Kbuild b/fs/proc/Kbuild index 37bda605..668dcf77 100644 --- a/fs/proc/Kbuild +++ b/fs/proc/Kbuild @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 # Objects are owned by this directory; child modules own their own lists. -obj-y := mount.o procfs.o memory.o views.o inotify.o +obj-y := mount.o procfs.o memory.o views.o inotify.o network.o include $(srctree)/scripts/Makefile.module diff --git a/fs/proc/internal.h b/fs/proc/internal.h index b63d607f..14f11494 100644 --- a/fs/proc/internal.h +++ b/fs/proc/internal.h @@ -51,6 +51,55 @@ int proc_control_truncate(const char *name, uint64_t length); bool proc_control_immediate(const char *name); struct task; struct text_stream; +/* Production always links network.o. Older standalone proc fixtures may omit it. */ +#ifdef RELIEFNT_PROC_NETWORK_IMPLEMENTATION +#define PROC_NETWORK_LINKAGE +#else +#define PROC_NETWORK_LINKAGE __attribute__((weak)) +#endif +/** @brief Identify supported network sysctl keys in the current network. + * @param name Nullable intrinsic key. @return File=1, directory=2, absent=0. + * Execution ownership pins the live interface registry. No references escape. + */ +int proc_network_kind(const char *name) PROC_NETWORK_LINKAGE; +/** @brief Apply current-credential DAC and target-owner CAP_NET_ADMIN access. + * @param name Intrinsic key. @param task Borrowed caller. @param access FS_ACCESS mask. + * @return Zero, EACCES, or EOPNOTSUPP for unrelated nodes. No allocation. + */ +int proc_network_access(const char *name, const struct task *task, uint32_t access) PROC_NETWORK_LINKAGE; +/** @brief Capture the current network and stable interface index for a control. + * @param name Intrinsic key. @param flags Sanitized open flags. @param out Owned capture. + * @return Zero or negative errno. Failure leaves no retained references. + */ +int proc_network_open(const char *name, uint32_t flags, void **out) PROC_NETWORK_LINKAGE; +/** @brief Render a retained control using current credentials and live policy. + * @param value Borrowed capture. @param stream Validated output slice. + * @return Zero or negative errno. Interface removal returns ENODEV. + */ +int proc_network_read(void *value, struct text_stream *stream) PROC_NETWORK_LINKAGE; +/** @brief Render a control in the caller's current network without retaining it. + * @param name Intrinsic key. @param stream Output slice. @return Zero or errno. + */ +int proc_network_emit(const char *name, struct text_stream *stream) PROC_NETWORK_LINKAGE; +/** @brief Write a captured control after rechecking current target authority. + * @param value Borrowed capture. @param offset Byte position. @param buffer Input bytes. + * @param length Byte count. @param written Required actual output, zero on failure. + * @return Zero or negative errno. Nonzero offsets consume input without applying it. + * Execution ownership serializes protocol effects. VFS enforces mount read-only policy. + */ +int proc_network_write(void *value, uint64_t offset, const void *buffer, + uint32_t length, uint32_t *written) PROC_NETWORK_LINKAGE; +/** @brief Release an owned capture and its network reference under execution ownership. + * @param value Owned capture, nullable. No references survive final release. + */ +void proc_network_close(void *value) PROC_NETWORK_LINKAGE; +/** @brief Enumerate current-network controls and interfaces with rewindable cookies. + * @param name Intrinsic directory key. @param offset In/out cookie. @param entry Output. + * @return Entry=1, EOF=0, or ENOTDIR. No allocation or ownership transfer. + */ +int proc_network_readdir(const char *name, uint64_t *offset, + struct reliefos_dir_entry *entry) PROC_NETWORK_LINKAGE; +#undef PROC_NETWORK_LINKAGE /* Standalone legacy proc fixtures omit optional producers. Production Kbuild * always links inotify.o and the fs/notify core; its definitions are strong. */ #ifdef RELIEFNT_PROC_INOTIFY_IMPLEMENTATION @@ -140,10 +189,16 @@ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,ui * @param value Borrowed open capture. @param offset Required zero position. * @param buffer Validated bytes. @param length Byte count. * @param written Required actual output, cleared before validation. - * @return Namespace status or EOPNOTSUPP for live stateless write fallback. - * Execution ownership serializes publication and preserves both credentials. + * @return Captured namespace/network status or EOPNOTSUPP for other captures. + * proc_file_owns_write distinguishes terminal captured errors from stateless fallback. + * Execution ownership serializes publication and current credential checks. */ int proc_file_write(void *value,uint64_t offset,const void *buffer,uint32_t length,uint32_t *written); +/** @brief Test whether a capture owns every write result, including EOPNOTSUPP. + * @param value Borrowed optional open capture. @return True for namespace/network controls. + * Execution-owned, no allocation. Prevents fallback from retargeting a retained control. + */ +bool proc_file_owns_write(void *value); /** @brief Poll a captured mount view without retargeting its namespace. * @param value Borrowed open capture. @param events Requested poll bits. * @param consume Acknowledge a pending graph change when true. diff --git a/fs/proc/mount.c b/fs/proc/mount.c index ccc26734..d4735ed2 100644 --- a/fs/proc/mount.c +++ b/fs/proc/mount.c @@ -147,7 +147,8 @@ int proc_create_vfs_mount_options(const char *options,struct vfs_mount **out) .get_identity=proc_key_identity,.identity_alive=proc_key_alive,.put_identity=proc_key_put, .follow=proc_mount_magic_target,.stat_link=proc_mount_magic_stat, .permissions=proc_control_permissions,.access=proc_control_access,.getattr=proc_getattr, - .open=proc_file_open,.read_open=proc_file_read,.write_open=proc_file_write,.close=proc_file_close, + .open=proc_file_open,.read_open=proc_file_read,.write_open=proc_file_write, + .owns_write_open=proc_file_owns_write,.close=proc_file_close, .poll_open=proc_file_poll,.authorize=proc_key_authorize, .entry_visible=proc_entry_visible,.reconfigure=proc_reconfigure}; if(!out)return -EINVAL; diff --git a/fs/proc/network.c b/fs/proc/network.c new file mode 100644 index 00000000..66d1d3a8 --- /dev/null +++ b/fs/proc/network.c @@ -0,0 +1,240 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#define RELIEFNT_PROC_NETWORK_IMPLEMENTATION +#include "internal.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char root[] = "/proc/sys/net"; +static const char conf[] = "/proc/sys/net/ipv6/conf"; +static const char *const controls[NET_IPV6_CONTROL_COUNT] = { + [NET_IPV6_DISABLE] = "disable_ipv6", + [NET_IPV6_ACCEPT_RA] = "accept_ra", + [NET_IPV6_HOP_LIMIT] = "hop_limit", + [NET_IPV6_ADDR_GEN_MODE] = "addr_gen_mode", + [NET_IPV6_USE_TEMPADDR] = "use_tempaddr", +}; + +struct proc_network_control { + struct net_namespace *ns; + uint32_t ifindex; + enum net_ipv6_control control; +}; + +/** @brief Resolve one intrinsic key inside a borrowed network. + * @param name Nullable key. @param ns Borrowed scope. + * @param out Optional target, without taking references. + * @return File=1, directory=2, absent=0. Execution ownership pins interfaces. + */ +static int resolve(const char *name, struct net_namespace *ns, + struct proc_network_control *out) +{ + if (!name) return 0; + if (!__builtin_strcmp(name, root) || !__builtin_strcmp(name, "/proc/sys/net/ipv6") || + !__builtin_strcmp(name, conf)) return 2; + if (__builtin_strncmp(name, conf, sizeof(conf) - 1) || name[sizeof(conf) - 1] != '/') return 0; + const char *interface = name + sizeof(conf); + const char *end = interface; + while (*end && *end != '/') ++end; + size_t length = end - interface; + if (!length || length >= NET_IF_NAME_LEN) return 0; + char device[NET_IF_NAME_LEN]; + __builtin_memcpy(device, interface, length); + device[length] = 0; + uint32_t index; + if (!__builtin_strcmp(device, "all")) index = NET_IPV6_CONF_ALL; + else if (!__builtin_strcmp(device, "default")) index = NET_IPV6_CONF_DEFAULT; + else { + index = net_interface_index(ns, device); + if (!index) return 0; + } + if (!*end) return 2; + for (unsigned i = 0; i < NET_IPV6_CONTROL_COUNT; ++i) { + if (__builtin_strcmp(end + 1, controls[i])) continue; + if (out) *out = (struct proc_network_control){.ns = ns, .ifindex = index, .control = i}; + return 1; + } + return 0; +} + +/** @brief Apply Linux network-sysctl root-equivalent access in the target scope. + * @param target Borrowed network. @param task Current credentials. + * @param access FS_ACCESS mask. @return Zero or EACCES, with no retained state. + */ +static int authorize(const struct net_namespace *target, const struct task *task, + uint32_t access) +{ + if (access & FS_ACCESS_EXEC) return -EACCES; + if ((access & FS_ACCESS_WRITE) && (!task || + (task->euid && !task_ns_capable(task, target ? target->user_ns : NULL, CAP_NET_ADMIN)))) + return -EACCES; + return 0; +} + +/** @copydoc proc_network_kind */ +int proc_network_kind(const char *name) +{ + struct task *task = sched_current_task(); + return resolve(name, task ? task->net_ns : NULL, NULL); +} + +/** @copydoc proc_network_access */ +int proc_network_access(const char *name, const struct task *task, uint32_t access) +{ + struct net_namespace *ns = task ? task->net_ns : NULL; + if (resolve(name, ns, NULL) != 1) return -EOPNOTSUPP; + return authorize(ns, task, access); +} + +/** @copydoc proc_network_open */ +int proc_network_open(const char *name, uint32_t flags, void **out) +{ + if (!out) return -EINVAL; + *out = NULL; + struct task *task = sched_current_task(); + struct proc_network_control target; + if (resolve(name, task ? task->net_ns : NULL, &target) != 1) return -ENOENT; + uint32_t access = (flags & LINUX_O_ACCMODE) == LINUX_O_RDONLY ? FS_ACCESS_READ : FS_ACCESS_WRITE; + int rc = authorize(target.ns, task, access); + if (rc) return rc; + struct proc_network_control *state = kernel_malloc(sizeof(*state)); + if (!state) return -ENOMEM; + *state = target; + state->ns = net_namespace_get(target.ns); + *out = state; + return 0; +} + +/** @copydoc proc_network_read */ +int proc_network_read(void *value, struct text_stream *stream) +{ + const struct proc_network_control *state = value; + int rc = authorize(state->ns, sched_current_task(), FS_ACCESS_READ); + int number; + if (!rc) rc = net_ipv6_control_get(state->ns, state->ifindex, state->control, &number); + if (!rc) { + text_signed(stream, number); + text_string(stream, "\n"); + } + return rc; +} + +/** @copydoc proc_network_emit */ +int proc_network_emit(const char *name, struct text_stream *stream) +{ + struct task *task = sched_current_task(); + struct proc_network_control target; + if (resolve(name, task ? task->net_ns : NULL, &target) != 1) return -ENOENT; + return proc_network_read(&target, stream); +} + +/** @brief Accept the whitespace delimiters used by Linux integer sysctls. + * @param byte Input byte. @return True for ASCII whitespace. + */ +static bool space(unsigned char byte) +{ + return byte == ' ' || byte == '\t' || byte == '\n' || byte == '\r' || byte == '\v' || byte == '\f'; +} + +/** @brief Parse a complete signed base-zero sysctl integer without overflow. + * @param buffer Borrowed input. @param length Byte count. @param out Required output. + * @return Zero or EINVAL. Failed parsing leaves the output unchanged. + */ +static int parse(const void *buffer, uint32_t length, int *out) +{ + if (!buffer || !length || length > 64) return -EINVAL; + const unsigned char *bytes = buffer; + uint32_t first = 0, last = length; + while (first < last && space(bytes[first])) ++first; + while (last > first && space(bytes[last - 1])) --last; + bool negative = false; + if (first < last && (bytes[first] == '+' || bytes[first] == '-')) negative = bytes[first++] == '-'; + if (first == last) return -EINVAL; + unsigned base = 10; + if (bytes[first] == '0') { + base = 8; + if (first + 1 < last && (bytes[first + 1] == 'x' || bytes[first + 1] == 'X')) { + base = 16; + first += 2; + } + } + if (first == last) return -EINVAL; + uint32_t number = 0, limit = (uint32_t)INT32_MAX + negative; + for (; first < last; ++first) { + unsigned byte = bytes[first], digit; + if (byte >= '0' && byte <= '9') digit = byte - '0'; + else if (byte >= 'a' && byte <= 'f') digit = byte - 'a' + 10; + else if (byte >= 'A' && byte <= 'F') digit = byte - 'A' + 10; + else return -EINVAL; + if (digit >= base || number > (limit - digit) / base) return -EINVAL; + number = number * base + digit; + } + *out = negative ? -(int64_t)number : number; + return 0; +} + +/** @copydoc proc_network_write */ +int proc_network_write(void *value, uint64_t offset, const void *buffer, + uint32_t length, uint32_t *written) +{ + if (!written) return -EINVAL; + *written = 0; + const struct proc_network_control *state = value; + int rc = authorize(state->ns, sched_current_task(), FS_ACCESS_WRITE); + if (rc) return rc; + if (offset || !length) { *written = length; return 0; } + int number; + rc = parse(buffer, length, &number); + if (!rc) rc = net_ipv6_control_set(state->ns, state->ifindex, state->control, number); + if (!rc) *written = length; + return rc; +} + +/** @copydoc proc_network_close */ +void proc_network_close(void *value) +{ + struct proc_network_control *state = value; + if (!state) return; + net_namespace_put(state->ns); + kernel_free(state); +} + +/** @copydoc proc_network_readdir */ +int proc_network_readdir(const char *name, uint64_t *offset, struct reliefos_dir_entry *entry) +{ + if (proc_network_kind(name) != 2) return -ENOTDIR; + *entry = (struct reliefos_dir_entry){.type = RELIEFOS_FS_TYPE_DIR}; + const char *leaf; + if (!__builtin_strcmp(name, root)) { + if (*offset) return 0; + leaf = "ipv6"; + } else if (!__builtin_strcmp(name, "/proc/sys/net/ipv6")) { + if (*offset) return 0; + leaf = "conf"; + } else if (!__builtin_strcmp(name, conf)) { + if (*offset < 2) leaf = *offset ? "default" : "all"; + else { + struct task *task = sched_current_task(); + struct net_namespace *ns = task ? task->net_ns : NULL; + if (*offset - 2 > UINT32_MAX) return 0; + uint32_t index = net_interface_next(ns, (uint32_t)(*offset - 2)); + if (!index || !net_interface_name(ns, index, entry->name)) return 0; + *offset = (uint64_t)index + 2; + return 1; + } + } else { + if (*offset >= NET_IPV6_CONTROL_COUNT) return 0; + leaf = controls[*offset]; + entry->type = RELIEFOS_FS_TYPE_FILE; + } + __builtin_memcpy(entry->name, leaf, __builtin_strlen(leaf) + 1); + ++*offset; + return 1; +} diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index 96fc9213..e555ff16 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -518,6 +518,7 @@ struct proc_open_view { uint64_t mount_generation; void *memory; const char *inotify_control; + void *network_control; bool namespace_control; struct user_namespace_file namespace_file; bool score_valid; int score; @@ -536,6 +537,8 @@ struct proc_open_view { * retain the target's graph and root; namespace controls retain the credential * scope and opener authority; generated leaves and diagnostics capture bytes, * while inotify controls retain a static key and read the current policy. + * Network controls retain the opening network and stable interface index, + * with current credentials checked against that target on each operation. * Namespace ownership outlives its retained paths; final release drops this * path even after task exit. Execution-owned, without graph locks across * renderers; partition metadata may perform I/O and return its native errno. @@ -585,6 +588,15 @@ int proc_file_open(const char *name,uint32_t flags,void **out) #endif if (((flags & LINUX_O_ACCMODE) != LINUX_O_RDONLY || (flags & LINUX_O_TRUNC)) && !proc_control_immediate(name)) return -RELIEFOS_EROFS; + if (proc_network_kind && proc_network_kind(name) == 1) { + struct proc_open_view *state = kernel_malloc(sizeof(*state)); + if (!state) return -ENOMEM; + *state = (struct proc_open_view){0}; + int rc = proc_network_open(name, flags, &state->network_control); + if (rc) { kernel_free(state); return rc; } + *out = state; + return 0; + } const char *inotify_key = proc_inotify_key ? proc_inotify_key(name) : NULL; if (inotify_key) { if ((flags & LINUX_O_ACCMODE) == LINUX_O_WRONLY) return 0; @@ -660,6 +672,13 @@ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,ui { if(!read)return -RELIEFOS_EINVAL;*read=0; struct proc_open_view *state=value;if(!state)return -RELIEFOS_EINVAL; + if (state->network_control) { + if (!buffer && capacity) return -EINVAL; + struct text_stream stream = {.offset = offset, .buffer = buffer, .capacity = capacity}; + int rc = proc_network_read(state->network_control, &stream); + if (!rc) *read = stream.written; + return rc; + } if (state->namespace_control) return user_namespace_file_read(&state->namespace_file, offset, buffer, capacity, read); if (state->inotify_control) { @@ -697,19 +716,28 @@ int proc_file_read(void *value,uint64_t offset,void *buffer,uint32_t capacity,ui * @param value Borrowed open capture, independent of subsequent PID reuse. * @param offset Byte position. @param buffer Validated input bytes. * @param length Byte count. @param written Required count output, cleared. - * @return Namespace status, or EOPNOTSUPP to request the live stateless - * control provider. Execution ownership serializes map/policy publication. + * @return Captured status. EOPNOTSUPP requests stateless fallback only when + * proc_file_owns_write is false. Execution ownership serializes publication. */ int proc_file_write(void *value,uint64_t offset,const void *buffer,uint32_t length,uint32_t *written) { if (!written) return -EINVAL; *written = 0; struct proc_open_view *state = value; + if (state && state->network_control) + return proc_network_write(state->network_control, offset, buffer, length, written); if (!state || !state->namespace_control) return -EOPNOTSUPP; return user_namespace_file_write(&state->namespace_file, sched_current_task(), offset, buffer, length, written); } +/** @copydoc proc_file_owns_write */ +bool proc_file_owns_write(void *value) +{ + const struct proc_open_view *state = value; + return state && (state->namespace_control || state->network_control); +} + /** @brief Report mount graph readiness for one captured open description. * @param value Borrowed capture, including non-mount generated files. * @param events Requested poll bits. @param consume Acknowledge graph changes. @@ -741,6 +769,11 @@ bool proc_file_poll(void *value,short events,bool consume,uint64_t *generation,s void proc_file_close(void *value) { struct proc_open_view *state=value;if(!state)return; + if (state->network_control) { + proc_network_close(state->network_control); + kernel_free(state); + return; + } if (state->namespace_control) { user_namespace_file_close(&state->namespace_file); kernel_free(state); @@ -1480,9 +1513,10 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * #endif }; int parent = proc_text_eq(path, "/proc/sys"); - if (*offset >= (parent ? 2 : sizeof(values) / sizeof(values[0]))) + static const char *const directories[] = {"kernel", "fs", "net"}; + if (*offset >= (parent ? sizeof(directories) / sizeof(*directories) : sizeof(values) / sizeof(values[0]))) return 0; - const char *name = parent ? (*offset ? "fs" : "kernel") : values[*offset]; + const char *name = parent ? directories[*offset] : values[*offset]; entry->type = parent || proc_text_eq(name, "seccomp") || proc_text_eq(name, "random") ? RELIEFOS_FS_TYPE_DIR : RELIEFOS_FS_TYPE_FILE; proc_copy(entry->name, sizeof(entry->name), name); @@ -1630,6 +1664,7 @@ int proc_control_permissions(const char *name, const struct storage_node *node, } } if (proc_uts_key(name) || (proc_inotify_key && proc_inotify_key(name))) value->mode = 0644; + if (proc_network_kind && proc_network_kind(name) == 1) value->mode = 0644; if (node->type == RELIEFOS_FS_TYPE_DIR || node->type == RELIEFOS_FS_TYPE_SYMLINK) { const char *leaf = NULL; struct task *owner = proc_view_task(name, &leaf); @@ -1656,6 +1691,10 @@ int proc_control_permissions(const char *name, const struct storage_node *node, /** @copydoc proc_control_access */ int proc_control_access(const char *name,const struct task *task,uint32_t access) { + if (proc_network_access) { + int rc = proc_network_access(name, task, access); + if (rc != -EOPNOTSUPP) return rc; + } if (!proc_uts_key(name)) return -EOPNOTSUPP; if (access & FS_ACCESS_EXEC) return -EACCES; if ((access & FS_ACCESS_WRITE) && (!task || task->euid)) return -EACCES; @@ -1710,6 +1749,7 @@ bool proc_control_immediate(const char *name) if (proc_userns_key(name, NULL)) return true; if (proc_uts_key(name)) return true; if (proc_inotify_key && proc_inotify_key(name)) return true; + if (proc_network_kind && proc_network_kind(name) == 1) return true; if (proc_oom_key(name, NULL) == 1) return true; #ifdef CONFIG_LOCK_STAT if (proc_text_eq(name, "/proc/reliefnt/lock_stats")) return true; @@ -1726,6 +1766,7 @@ int proc_control_truncate(const char *name, uint64_t length) if (proc_userns_key(name, NULL)) return length ? -EINVAL : 0; if (proc_uts_key(name)) return length ? -EINVAL : 0; if (proc_inotify_key && proc_inotify_key(name)) return length ? -EINVAL : 0; + if (proc_network_kind && proc_network_kind(name) == 1) return length ? -EINVAL : 0; if (proc_oom_key(name, NULL) == 1) return length ? -EINVAL : 0; #ifdef CONFIG_LOCK_STAT return proc_lock_stats_truncate(name, length); diff --git a/fs/proc/views.c b/fs/proc/views.c index a1dcefe5..21a3c09a 100644 --- a/fs/proc/views.c +++ b/fs/proc/views.c @@ -75,6 +75,10 @@ int proc_extra_kind(const char *path) int kind = proc_inotify_kind(path); if (kind) return kind; } + if (proc_network_kind) { + int kind = proc_network_kind(path); + if (kind) return kind; + } if (!__builtin_strcmp(path, "/proc/self") || !__builtin_strcmp(path, "/proc/thread-self")) return sched_current_task() ? 3 : 0; if (!__builtin_strcmp(path, "/proc/net") || !__builtin_strcmp(path, "/proc/sys/fs")) @@ -607,6 +611,8 @@ static int maps(struct task *t, const char *leaf, struct text_stream *s) */ int proc_extra_emit(const char *path, struct text_stream *s) { + if (proc_network_kind && proc_network_kind(path) == 1) + return proc_network_emit(path, s); if (!__builtin_strncmp(path, "/proc/net/", 10)) return net_proc_emit(s, path + 10); if (!__builtin_strcmp(path, "/proc/loadavg")) { @@ -850,6 +856,10 @@ static int entries(const char *const *names, size_t count, uint64_t *offset, */ int proc_extra_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry *entry) { + if (proc_network_readdir) { + int rc = proc_network_readdir(path, offset, entry); + if (rc != -ENOTDIR) return rc; + } if (!__builtin_strcmp(path, "/proc/net")) return entries(net_leaves, sizeof(net_leaves) / sizeof(*net_leaves), offset, entry); if (!__builtin_strcmp(path, "/proc/sys/fs")) { diff --git a/fs/vfs/pseudo.c b/fs/vfs/pseudo.c index 8a62e6ef..d27e28b0 100644 --- a/fs/vfs/pseudo.c +++ b/fs/vfs/pseudo.c @@ -192,8 +192,9 @@ static int pseudo_node_write(void *value,struct storage_node *node,uint64_t offs * @param state Borrowed capture. @param offset Byte position. * @param buffer Validated input bytes. @param length Byte count. * @param written Required output, cleared before dispatch. - * @return Provider status; absent or unsupported captured writes fall back to - * the live stateless provider. Execution-owned, without graph/module locks. + * @return Provider status. Captures identified by owns_write_open retain every + * result. Other absent or unsupported captures use the live stateless provider. + * Execution-owned, without graph/module locks. */ static int pseudo_file_write(void *value,struct storage_node *node,void *state, uint64_t offset,const void *buffer,uint32_t length,uint32_t *written) @@ -203,7 +204,8 @@ static int pseudo_file_write(void *value,struct storage_node *node,void *state, if (state && context->provider->write_open) { if (!pseudo_key_find(context, node->entry_id)) return -EINVAL; int rc = context->provider->write_open(state, offset, buffer, length, written); - if (rc != -EOPNOTSUPP) return rc; + if (rc != -EOPNOTSUPP || (context->provider->owns_write_open && + context->provider->owns_write_open(state))) return rc; } return pseudo_node_write(value, node, offset, buffer, length, written); } diff --git a/include/reliefnt/net_ipv6.h b/include/reliefnt/net_ipv6.h index 8a25837f..27a9a830 100644 --- a/include/reliefnt/net_ipv6.h +++ b/include/reliefnt/net_ipv6.h @@ -30,6 +30,40 @@ void net_ipv6_state_destroy(struct net_ipv6_state *state); #define NET_IPV6_ADDR_MANAGETEMPADDR 0x100u #define NET_IPV6_ADDR_NOPREFIXROUTE 0x200u +#define NET_IPV6_CONF_ALL 0u +#define NET_IPV6_CONF_DEFAULT UINT32_MAX + +/** @brief Namespace-local IPv6 host controls using Linux sysctl value semantics. */ +enum net_ipv6_control { + NET_IPV6_DISABLE, + NET_IPV6_ACCEPT_RA, + NET_IPV6_HOP_LIMIT, + NET_IPV6_ADDR_GEN_MODE, + NET_IPV6_USE_TEMPADDR, + NET_IPV6_CONTROL_COUNT +}; + +/** @brief Read an IPv6 host control under network execution ownership. + * @param ns Borrowed network, NULL for the initial network. + * @param ifindex Stable live interface index, CONF_ALL or CONF_DEFAULT. + * @param control Checked control selector. @param value Required copied output. + * @return Zero or negative errno. Does not allocate or retain references. + */ +int net_ipv6_control_get(struct net_namespace *ns, uint32_t ifindex, + enum net_ipv6_control control, int *value); +/** @brief Apply an authorized IPv6 host control and its protocol side effects. + * @param ns Borrowed network, NULL for the initial network. + * @param ifindex Stable live interface index, CONF_ALL or CONF_DEFAULT. + * @param control Checked control selector. @param value Requested signed value. + * @return Zero or negative errno. Unsupported privacy modes return EOPNOTSUPP. + * Requires execution ownership. The default affects future interfaces. All + * propagates disable_ipv6 and addr_gen_mode to defaults and existing links. + * Allocation or capacity failure preserves visible controls and protocol state. + * Authorization belongs to the caller and must use the target network owner. + */ +int net_ipv6_control_set(struct net_namespace *ns, uint32_t ifindex, + enum net_ipv6_control control, int value); + /** @brief Test whether Linux bind uses an address's interface scope ID. * @param address Borrowed network-order IPv6 address. * @return True for link-local unicast and interface/link-local multicast. @@ -208,8 +242,9 @@ void net_ipv6_socket_error_on(struct net_namespace *ns, uint32_t ifindex,const u * @param packet Borrowed original IPv6 quote. @param length Available quote bytes. * @param error Positive errno, ICMP origin/type/code and MTU under execution ownership. * @param offender Borrowed native ICMP source, or NULL for a locally generated error. - * UDP retains owned metadata when IPV6_RECVERR is enabled. TCP and raw sockets - * receive the existing pending-error notification. No borrowed storage escapes. + * UDP and raw/ping retain owned metadata when IPV6_RECVERR is enabled. Ping + * quotes must match the echo identifier. TCP receives pending-error notification. + * Queue allocation failure preserves pending errno. No borrowed storage escapes. */ void net_ipv6_socket_extended_error_on(struct net_namespace *ns, uint32_t ifindex, const uint8_t *packet, uint32_t length, const struct sock_extended_err *error, diff --git a/include/reliefnt/net_packet.h b/include/reliefnt/net_packet.h index da79b72d..85eec474 100644 --- a/include/reliefnt/net_packet.h +++ b/include/reliefnt/net_packet.h @@ -41,21 +41,23 @@ int task_packet_send(struct task_file *file, const void *data, uint32_t length, * @param file Socket description under the execution lock. * @param data Validated writable destination. * @param length Destination capacity. - * @param flags Linux receive flags. + * @param flags Linux receive flags. MSG_ERRQUEUE selects IPv6 errors. * @param address Optional user source-address destination. * @param address_length User socklen_t address when address is nonzero. * @return Byte count, negative errno, or the interruptible blocking sentinel. + * MSG_ERRQUEUE consumes one error even with MSG_PEEK. Empty queues return EAGAIN. */ int task_packet_recv(struct task_file *file, void *data, uint32_t length, uint32_t flags, uint64_t address, uint64_t address_length); /** @brief Return this packet OFD's native source-address size, or zero. */ uint32_t task_packet_address_size(const struct task_file *file); struct net_udp_rx_info; -/** @brief Receive a packet and its native source and IPv6 ancillary metadata. +/** @brief Receive a packet or IPv6 error and its native address and metadata. * @param file Retained OFD. @param data Kernel buffer. @param length Capacity. * @param flags Receive flags. @param source Optional sockaddr storage. - * @param source_length Optional source size. @param info Optional IPv6 metadata. - * @return Bytes, negative errno, or blocked sentinel. */ + * @param source_length Optional source size. @param info Optional IPv6/error metadata. + * @return Bytes, negative errno, or blocked sentinel. MSG_ERRQUEUE consumes one + * error even with external MSG_PEEK. An empty error queue returns EAGAIN. */ int task_packet_recv_ex(struct task_file *file,void *data,uint32_t length,uint32_t flags, void *source,uint32_t *source_length,struct net_udp_rx_info *info); #ifdef CONFIG_SWAP @@ -75,7 +77,7 @@ int task_packet_recv_staged(struct task_file *file,void *data,uint32_t length, * @return Ready event bits. */ short task_packet_poll(struct task_file *file, short events); -/** @brief Release the final raw/packet description, queue, multicast and network. +/** @brief Release the final raw/packet description, data/errors, multicast and network. * @param file Owned description under the execution lock. */ void task_packet_release(struct task_file *file); diff --git a/include/reliefnt/pseudo_fs.h b/include/reliefnt/pseudo_fs.h index 0e16724e..1819127d 100644 --- a/include/reliefnt/pseudo_fs.h +++ b/include/reliefnt/pseudo_fs.h @@ -38,10 +38,16 @@ struct vfs_pseudo_provider { /* Optional nonblocking per-open capture. An owned state is consumed by * close even on failed open; NULL means ordinary stateless reads. Reads * through captured state remain valid after the inode identity retires. - * write_open is optional; EOPNOTSUPP selects the live stateless write. */ + * write_open is optional; EOPNOTSUPP selects the live stateless write + * unless owns_write_open identifies this capture as the write target. */ int (*open)(const char *intrinsic,uint32_t flags,void **state); int (*read_open)(void *state,uint64_t offset,void *buffer,uint32_t capacity,uint32_t *read); int (*write_open)(void *state,uint64_t offset,const void *buffer,uint32_t length,uint32_t *written); + /** @brief Identify captures whose write results are terminal, including EOPNOTSUPP. + * @param state Borrowed non-NULL capture. @return True to prevent stateless fallback. + * Optional, execution-owned, without allocation or ownership transfer. + */ + bool (*owns_write_open)(void *state); void (*close)(void *state); /* Optional per-open poll state, valid after the inode identity retires. */ bool (*poll_open)(void *state,short events,bool consume,uint64_t *generation,short *ready); diff --git a/include/uapi/linux/if_link.h b/include/uapi/linux/if_link.h index e694727a..f21c1450 100644 --- a/include/uapi/linux/if_link.h +++ b/include/uapi/linux/if_link.h @@ -8,4 +8,12 @@ struct ifinfomsg { uint8_t ifi_family, __ifi_pad; uint16_t ifi_type; int32_t ifi #define IFLA_IFNAME 3 #define IFLA_MTU 4 #define IFLA_OPERSTATE 16 +#define IFLA_AF_SPEC 26 +#define IFLA_INET6_ADDR_GEN_MODE 8 +enum in6_addr_gen_mode { + IN6_ADDR_GEN_MODE_EUI64, + IN6_ADDR_GEN_MODE_NONE, + IN6_ADDR_GEN_MODE_STABLE_PRIVACY, + IN6_ADDR_GEN_MODE_RANDOM, +}; #endif diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 26dba7f6..580d2240 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -2665,8 +2665,8 @@ static int udp_message_control(struct task_file *file, const struct msghdr *mess * UDP and packet ancillary output includes enabled realtime timestamps. Packet * sockets also expose enabled AUXDATA. All emitted control bytes are prepared * before dequeue, so output-memory failure preserves the queued datagram. - * UDP MSG_ERRQUEUE returns the original destination, quoted payload and a native - * extended-error control message. Internal receive probing preserves that queue. + * UDP and IPv6 raw/ping MSG_ERRQUEUE return the original destination, quoted + * payload and a native extended-error control. Internal probing preserves the queue. */ static int64_t inet_message(struct task_file *file, uint64_t user_header, struct msghdr message, uint32_t flags, bool receiving, @@ -2678,8 +2678,9 @@ static int64_t inet_message(struct task_file *file, uint64_t user_header, bool netlink_pktinfo = receiving && netlink && task_netlink_pktinfo(file); bool udp = file->kind == TASK_FILE_KIND_UDP; bool datagram = udp || packet || netlink; + bool error_queue = udp || (packet && task_packet_address_size(file) == sizeof(struct sockaddr_in6)); if (flags & ~(MSG_DONTWAIT | MSG_NOSIGNAL | MSG_PEEK | MSG_TRUNC | MSG_WAITALL | MSG_CMSG_CLOEXEC | - (receiving && udp ? MSG_ERRQUEUE : 0))) + (receiving && error_queue ? MSG_ERRQUEUE : 0))) return -LINUX_EOPNOTSUPP; struct net_udp_tx_info tx_info = {.ttl = -1, .hops = -1}; if (!receiving && message.msg_controllen) { diff --git a/net/ipv6/core.c b/net/ipv6/core.c index 746f7b50..6a1741d7 100644 --- a/net/ipv6/core.c +++ b/net/ipv6/core.c @@ -3,6 +3,7 @@ #include "../internal.h" #include "internal.h" #include +#include #include #include #include @@ -46,10 +47,38 @@ static struct ipv6_link *ipv6_link(struct net_ipv6_state *state, uint32_t ifinde if(!create)return 0; struct ipv6_link *link=kernel_malloc(sizeof(*link));if(!link)return 0; net_memzero(link,sizeof(*link));link->ifindex=ifindex; + net_memcpy(link->controls, state->default_controls, sizeof(link->controls)); link->mtu=IPV6_LINK_MTU;link->base_reachable_ms=30000;link->retrans_ms=1000; link->next=state->links;state->links=link; return link; } + +/** @copydoc net_ipv6_control_get */ +int net_ipv6_control_get(struct net_namespace *ns, uint32_t ifindex, + enum net_ipv6_control control, int *value) +{ + if (!value || (unsigned)control >= NET_IPV6_CONTROL_COUNT) return -LINUX_EINVAL; + struct net_ipv6_state *state = net_ipv6_state_get(ns); + if (ifindex == NET_IPV6_CONF_ALL) *value = state->all_controls[control]; + else if (ifindex == NET_IPV6_CONF_DEFAULT) *value = state->default_controls[control]; + else { + if (!net_interface_exists(ns, ifindex)) return -LINUX_ENODEV; + struct ipv6_link *link = ipv6_link(state, ifindex, false); + *value = link ? link->controls[control] : state->default_controls[control]; + } + return 0; +} + +/** @brief Borrow a live interface's IPv6 control without allocating state. + * @param state Borrowed network state. @param ifindex Live interface index. + * @param control Internal validated selector. @return Current host policy. + */ +static int ipv6_control(struct net_ipv6_state *state, uint32_t ifindex, + enum net_ipv6_control control) +{ + struct ipv6_link *link = ipv6_link(state, ifindex, false); + return link ? link->controls[control] : state->default_controls[control]; +} /** @brief Select the historical default NIC, including in legacy white-box fixtures. * @param state Borrowed protocol owner under network execution ownership. * @return First non-loopback index, the initial-network fallback, or zero. @@ -238,6 +267,7 @@ int net_ipv6_route_update(struct net_namespace *ns, const struct net_ipv6_route struct net_ipv6_state *state = net_ipv6_state_get(ns); if(!route || route->prefix_length>128 || !net_interface_exists(state->net_ns, route->ifindex) || ipv6_multicast(&route->gateway) || route->preference==2 || route->preference>3)return -LINUX_EINVAL; + if (!remove && ipv6_control(state, route->ifindex, NET_IPV6_DISABLE)) return -LINUX_EACCES; if(!remove && !ipv6_unspecified(&route->preferred_source) && !ipv6_find_address(state,&route->preferred_source,0))return -LINUX_EADDRNOTAVAIL; struct net_ipv6_route normalized=*route;ipv6_mask(&normalized.destination,normalized.prefix_length); @@ -326,6 +356,7 @@ static int ipv6_address_set(struct net_ipv6_state *state, const struct net_ipv6_ if(!address || address->prefix_length>128 || !net_interface_exists(state->net_ns, address->ifindex) || ipv6_multicast(&address->address) || ipv6_unspecified(&address->address) || address->preferred_until>address->valid_until)return -LINUX_EINVAL; + if (!remove && ipv6_control(state, address->ifindex, NET_IPV6_DISABLE)) return -LINUX_EACCES; struct ipv6_address_slot *slot=ipv6_find_address(state,&address->address,address->ifindex); if(remove){if(!slot)return -LINUX_EADDRNOTAVAIL; if(slot->value.ifindex==1 && ipv6_equal(&slot->value.address,&ipv6_loop))return -LINUX_EPERM; @@ -542,7 +573,7 @@ static int ipv6_transmit(struct net_ipv6_state *state, const struct net_ipv6_pat if(!link || !link->up)return -LINUX_ENETDOWN; uint32_t mtu=path->mtu;if(mtu>link->mtu)mtu=link->mtu; if(mtucontrols[NET_IPV6_HOP_LIMIT]:hops); if(length+40<=mtu){int rc=ipv6_send_frame(state,path->ifindex,mac,&path->source,&path->destination,protocol,hop,flowinfo,data,length); return rc<0?rc:(int)length;} if(dont_fragment)return -LINUX_EMSGSIZE; @@ -586,6 +617,7 @@ int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,u if(!path || (!data && length) || hops < -1 || hops>255 || !net_interface_exists(state->net_ns, path->ifindex))return -LINUX_EINVAL; if(!net_interface_is_ready(ns, path->ifindex))return -LINUX_ENETDOWN; + if (ipv6_control(state, path->ifindex, NET_IPV6_DISABLE)) return -LINUX_ENETDOWN; struct ipv6_link *link=path->ifindex==1?0:ipv6_link(state,path->ifindex,false); if(path->ifindex!=1 && (!link || !link->up || !net_interface_is_ready(state->net_ns, path->ifindex)))return -LINUX_ENETDOWN; if(dont_fragment && length+40>path->mtu)return -LINUX_EMSGSIZE; @@ -759,10 +791,11 @@ static void ipv6_slaac(struct net_ipv6_state *state, uint32_t ifindex,const uint static void ipv6_router_advertisement(struct net_ipv6_state *state, uint32_t ifindex,const struct in6_addr *source,const uint8_t *icmp,uint32_t length) { struct ipv6_link *link=ipv6_link(state,ifindex,false); - if(!link || !ipv6_linklocal(source) || length<16 || icmp[1])return; + if(!link || !link->controls[NET_IPV6_ACCEPT_RA] || !ipv6_linklocal(source) || length<16 || icmp[1])return; /* Validate the entire option sequence before applying any changes. */ for(uint32_t off=16;offlength-off)return;off+=n;} + if (icmp[4]) link->controls[NET_IPV6_HOP_LIMIT] = icmp[4]; uint32_t reachable=net_get_u32(icmp+8),retrans=net_get_u32(icmp+12); if(reachable && reachable!=link->base_reachable_ms){link->base_reachable_ms=reachable;ipv6_refresh_reachable(link);} if(retrans)link->retrans_ms=retrans; @@ -1060,6 +1093,7 @@ static void ipv6_mld_query(struct net_ipv6_state *state, uint32_t ifindex,const * @param mac Ethernet source or NULL. @param reassembled True for a reconstructed packet. */ static void ipv6_receive_ip(struct net_ipv6_state *state, const uint8_t *ip,uint32_t length,uint32_t ifindex,const uint8_t *mac,bool reassembled) { + if (ipv6_control(state, ifindex, NET_IPV6_DISABLE)) return; if(length<40 || ip[0]>>4!=6)return; uint32_t total=40u+net_get_u16(ip+4);if(total>length)return; struct in6_addr src,dst;net_memcpy(src.s6_addr,ip+8,16);net_memcpy(dst.s6_addr,ip+24,16); @@ -1197,40 +1231,199 @@ static int ipv6_loopback_up(struct net_ipv6_state *state) return net_ipv6_route_update(state->net_ns, &route, false); } +/** @brief Build the EUI64 link-local address for one Ethernet interface. + * @param ifindex Live Ethernet index. @return Copied permanent address with DAD. + */ +static struct net_ipv6_address ipv6_link_local(uint32_t ifindex) +{ + const uint8_t *mac = netdev_mac(ifindex); + struct net_ipv6_address address = {.address = {.s6_addr = {0xfe, 0x80}}, + .ifindex = ifindex, .prefix_length = 64, .flags = NET_IPV6_ADDR_PERMANENT, + .preferred_until = IPV6_FOREVER, .valid_until = IPV6_FOREVER}; + uint8_t *bytes = address.address.s6_addr; + bytes[8] = mac[0] ^ 2; bytes[9] = mac[1]; bytes[10] = mac[2]; + bytes[11] = 0xff; bytes[12] = 0xfe; + bytes[13] = mac[3]; bytes[14] = mac[4]; bytes[15] = mac[5]; + return address; +} + +/** @brief Accumulate capacity needed to activate one interface without mutation. + * @param state Borrowed network. @param ifindex Live interface. + * @param mode Candidate address-generation mode. @param needed Three in/out counts + * for addresses, routes and multicast groups. Existing matching entries are reused. + */ +static void ipv6_activation_needs(struct net_ipv6_state *state, uint32_t ifindex, + int mode, uint32_t needed[3]) +{ + bool loopback = ifindex == NET_IPV6_IF_LOOPBACK; + if (!loopback && mode == 1) return; + struct net_ipv6_address address = loopback ? + (struct net_ipv6_address){.address = ipv6_loop, .prefix_length = 128} : + ipv6_link_local(ifindex); + if (!ipv6_find_address(state, &address.address, ifindex)) { + ++needed[0]; + struct in6_addr group; + ipv6_solicited(&group, &address.address); + if (!loopback && !ipv6_find_group(state, &group, ifindex)) ++needed[2]; + } + struct in6_addr prefix = address.address; + ipv6_mask(&prefix, address.prefix_length); + for (uint32_t i = 0; i < IPV6_ROUTE_MAX; ++i) { + struct net_ipv6_route *route = &state->routes[i].value; + if (state->routes[i].used && route->ifindex == ifindex && + route->prefix_length == address.prefix_length && + route->metric == (loopback ? 0u : 256u) && !route->nexthop_id && + ipv6_equal(&route->destination, &prefix) && ipv6_unspecified(&route->gateway)) return; + } + ++needed[1]; +} + +/** @brief Check a complete activation batch before changing controls or tables. + * @param state Borrowed network. @param needed Address, route and group counts. + * @return Zero or ENOBUFS. Requires network execution ownership. + */ +static int ipv6_activation_capacity(struct net_ipv6_state *state, const uint32_t needed[3]) +{ + uint32_t available[3] = {0}; + for (uint32_t i = 0; i < IPV6_ADDR_MAX; ++i) available[0] += !state->addresses[i].used; + for (uint32_t i = 0; i < IPV6_ROUTE_MAX; ++i) available[1] += !state->routes[i].used; + for (uint32_t i = 0; i < IPV6_GROUP_MAX; ++i) available[2] += !state->groups[i].used; + for (unsigned i = 0; i < 3; ++i) + if (needed[i] > available[i]) return -LINUX_ENOBUFS; + return 0; +} + +/** @brief Publish an automatic link-local address after activation preflight. + * @param state Borrowed network. @param link Live enabled Ethernet link. + * @return Zero or a protocol error. Preserves existing address metadata. + */ +static int ipv6_configure_link_local(struct net_ipv6_state *state, struct ipv6_link *link) +{ + if (link->controls[NET_IPV6_ADDR_GEN_MODE] == 1) return 0; + struct net_ipv6_address address = ipv6_link_local(link->ifindex); + if (ipv6_find_address(state, &address.address, link->ifindex)) return 0; + return net_ipv6_address_update(state->net_ns, &address, false); +} + /** @brief Apply administrative/carrier state to this network's loopback or Ethernet link. * @param ns Borrowed network, NULL for the permanent initial network. * @param ifindex Stable index in this network. @param up New administrative state. - * @return Zero or negative errno, leaving loopback tables intact on capacity failure. + * @return Zero or negative errno. Disabled IPv6 remains down. Loopback capacity + * failure preserves its tables. Ethernet remains usable for manually assigned + * addresses when the bounded automatic-address tables are full. */ int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t ifindex,bool up) { struct net_ipv6_state *state = net_ipv6_state_get(ns); if(!state->initialized)return 0; if(!net_interface_exists(state->net_ns, ifindex))return -LINUX_ENODEV; - if (ifindex == NET_IPV6_IF_LOOPBACK) { - if (up) return ipv6_loopback_up(state); - ipv6_clear_link_state(state, ifindex); - return 0; - } - bool enabled=up && netdev_is_ready(ifindex); + bool enabled=up && (ifindex == NET_IPV6_IF_LOOPBACK || netdev_is_ready(ifindex)); struct ipv6_link *link=ipv6_link(state,ifindex,enabled); if(!link)return enabled?-LINUX_ENOMEM:0; + enabled = enabled && !link->controls[NET_IPV6_DISABLE]; if(enabled==link->up)return 0; - link->up=enabled; - if(!enabled){ipv6_clear_link_state(state,ifindex);return 0;} + if(!enabled){link->up=false;ipv6_clear_link_state(state,ifindex);return 0;} + uint32_t needed[3] = {0}; + ipv6_activation_needs(state, ifindex, link->controls[NET_IPV6_ADDR_GEN_MODE], needed); + int rc = ipv6_activation_capacity(state, needed); + if (ifindex == NET_IPV6_IF_LOOPBACK) { + if (rc) return rc; + rc = ipv6_loopback_up(state); + if (!rc) link->up = true; + return rc; + } link->mtu=IPV6_LINK_MTU;link->rng_state=0;link->mld_v1_until=0; ipv6_reset_timing(link); - const uint8_t *mac=netdev_mac(ifindex);struct net_ipv6_address a={0};a.address.s6_addr[0]=0xfe;a.address.s6_addr[1]=0x80; - a.address.s6_addr[8]=mac[0]^2;a.address.s6_addr[9]=mac[1];a.address.s6_addr[10]=mac[2]; - a.address.s6_addr[11]=0xff;a.address.s6_addr[12]=0xfe;a.address.s6_addr[13]=mac[3]; - a.address.s6_addr[14]=mac[4];a.address.s6_addr[15]=mac[5];a.ifindex=ifindex;a.prefix_length=64; - a.flags=NET_IPV6_ADDR_PERMANENT;a.preferred_until=a.valid_until=IPV6_FOREVER; - (void)net_ipv6_address_update(state->net_ns, &a,false); - struct in6_addr prefix={.s6_addr={0xfe,0x80}}; - ipv6_auto_route(state,ifindex,&prefix,64,&ipv6_zero,IPV6_FOREVER,256,false); + if (!rc) { + rc = ipv6_configure_link_local(state, link); + if (rc) return rc; + } + link->up = true; link->rs_at=IPV6_FOREVER;link->rs_sent=0; return 0; } + +/** @brief Validate host control ranges and reject unimplemented privacy algorithms. + * @param control Valid selector. @param value Proposed signed value. + * @return Zero, EINVAL for invalid ranges, or EOPNOTSUPP for privacy modes. + */ +static int ipv6_control_validate(enum net_ipv6_control control, int value) +{ + switch (control) { + case NET_IPV6_DISABLE: return value < 0 || value > 1 ? -LINUX_EINVAL : 0; + case NET_IPV6_ACCEPT_RA: return value < 0 || value > 2 ? -LINUX_EINVAL : 0; + case NET_IPV6_HOP_LIMIT: return value < 1 || value > 255 ? -LINUX_EINVAL : 0; + case NET_IPV6_ADDR_GEN_MODE: + if (value < 0 || value > 3) return -LINUX_EINVAL; + return value > 1 ? -LINUX_EOPNOTSUPP : 0; + case NET_IPV6_USE_TEMPADDR: return value > 0 ? -LINUX_EOPNOTSUPP : 0; + default: return -LINUX_EINVAL; + } +} + +/** @brief Determine whether a candidate control activates address configuration. + * @param link Borrowed link. @param control Valid selector. @param value New value. + * @return True when enabling IPv6 or EUI64 requires activation preflight. + */ +static bool ipv6_control_activates(const struct ipv6_link *link, + enum net_ipv6_control control, int value) +{ + return !value && link->controls[control] != value && + (control == NET_IPV6_DISABLE || + (control == NET_IPV6_ADDR_GEN_MODE && !link->controls[NET_IPV6_DISABLE])); +} + +/** @copydoc net_ipv6_control_set */ +int net_ipv6_control_set(struct net_namespace *ns, uint32_t ifindex, + enum net_ipv6_control control, int value) +{ + int rc = ipv6_control_validate(control, value); + if (rc) return rc; + struct net_ipv6_state *state = net_ipv6_state_get(ns); + bool all = ifindex == NET_IPV6_CONF_ALL; + bool defaults = ifindex == NET_IPV6_CONF_DEFAULT; + bool propagate = all && (control == NET_IPV6_DISABLE || control == NET_IPV6_ADDR_GEN_MODE); + if (all && !propagate) { state->all_controls[control] = value; return 0; } + if (!all && !defaults && !net_interface_exists(ns, ifindex)) return -LINUX_ENODEV; + if (propagate || defaults) { + /* Freeze old defaults for every existing interface, including down links. */ + for (uint32_t index = net_interface_next(ns, 0); index; index = net_interface_next(ns, index)) + if (!ipv6_link(state, index, true)) return -LINUX_ENOMEM; + } else if (!ipv6_link(state, ifindex, true)) return -LINUX_ENOMEM; + if (defaults) { state->default_controls[control] = value; return 0; } + uint32_t needed[3] = {0}; + for (struct ipv6_link *link = state->links; link; link = link->next) { + if ((!propagate && link->ifindex != ifindex) || !state->initialized || + !net_interface_is_ready(ns, link->ifindex) || !ipv6_control_activates(link, control, value)) continue; + int mode = control == NET_IPV6_ADDR_GEN_MODE ? value : link->controls[NET_IPV6_ADDR_GEN_MODE]; + ipv6_activation_needs(state, link->ifindex, mode, needed); + } + rc = ipv6_activation_capacity(state, needed); + if (rc) return rc; + if (propagate) { + state->all_controls[control] = value; + state->default_controls[control] = value; + } + for (struct ipv6_link *link = state->links; link; link = link->next) { + if (!propagate && link->ifindex != ifindex) continue; + bool activate = ipv6_control_activates(link, control, value); + link->controls[control] = value; + if (!state->initialized) continue; + if (control == NET_IPV6_DISABLE && value) { + link->up = false; + ipv6_clear_link_state(state, link->ifindex); + } else if (activate && net_interface_is_ready(ns, link->ifindex)) { + if (!link->up) (void)net_ipv6_link_changed_on(ns, link->ifindex, true); + else if (link->ifindex != NET_IPV6_IF_LOOPBACK) (void)ipv6_configure_link_local(state, link); + } + if (control == NET_IPV6_ACCEPT_RA) { + link->rs_sent = 0; + link->rs_at = IPV6_FOREVER; + } + } + if (control == NET_IPV6_ADDR_GEN_MODE) netlink_network_changed(ns); + return 0; +} /** @copydoc net_ipv6_link_changed */ void net_ipv6_link_changed(bool up) { (void)net_ipv6_link_changed_on(NULL, ipv6_default_interface(net_ipv6_state_get(NULL)),up); } @@ -1256,7 +1449,7 @@ void net_ipv6_init(void) struct net_ipv6_state *state = net_ipv6_state_get(NULL); net_ipv6_state_reset(state); state->initialized = true; - if (net_interface_is_up(NULL, NET_IPV6_IF_LOOPBACK)) (void)ipv6_loopback_up(state); + if (net_interface_is_up(NULL, NET_IPV6_IF_LOOPBACK)) (void)net_ipv6_link_changed_on(NULL, NET_IPV6_IF_LOOPBACK, true); for(uint32_t i=netdev_next(0);i;i=netdev_next(i))(void)net_ipv6_link_changed_on(state->net_ns, i,net_interface_is_up(NULL, i)); } /** @copydoc net_ipv6_maintenance_pending */ @@ -1284,7 +1477,7 @@ static void ipv6_loop_deliver(struct net_ipv6_state *state, struct ipv6_pending { uint8_t *packet=kernel_malloc(40u+p->length);if(!packet){ipv6_pending_error(state,p,LINUX_ENOMEM);return;} net_memzero(packet,40);packet[0]=0x60;net_put_u16(packet+4,(uint16_t)p->length);packet[6]=p->protocol; - packet[7]=(uint8_t)(p->hops<0?64:p->hops);net_memcpy(packet+8,p->path.source.s6_addr,16); + packet[7]=(uint8_t)(p->hops<0?ipv6_control(state,p->path.ifindex,NET_IPV6_HOP_LIMIT):p->hops);net_memcpy(packet+8,p->path.source.s6_addr,16); net_memcpy(packet+24,p->path.destination.s6_addr,16);if(p->length)net_memcpy(packet+40,p->data,p->length); ipv6_receive_ip(state,packet,40u+p->length,p->path.ifindex,0,false);kernel_free(packet); } @@ -1296,7 +1489,7 @@ static void ipv6_poll_state(struct net_ipv6_state *state) if(!state->initialized)return; for(uint32_t i=state->net_ns?0:netdev_next(0);i;i=netdev_next(i)){ struct ipv6_link *link=ipv6_link(state,i,false); - bool up=net_interface_is_ready(state->net_ns, i); + bool up=net_interface_is_ready(state->net_ns, i) && !ipv6_control(state,i,NET_IPV6_DISABLE); if((link && link->up)!=up)(void)net_ipv6_link_changed_on(state->net_ns, i,up); } uint64_t now=time_uptime_ms(); @@ -1337,7 +1530,7 @@ static void ipv6_poll_state(struct net_ipv6_state *state) for(uint32_t i=0;ireassembly[i].used && ipv6_expired(state->reassembly[i].deadline,now)) ipv6_reassembly_expire(state,&state->reassembly[i]); for(struct ipv6_link *link=state->links;link;link=link->next){ - if(!link->up)continue; + if(!link->up || !link->controls[NET_IPV6_ACCEPT_RA])continue; const struct in6_addr *source=ipv6_link_source(state,link->ifindex); if(source && !link->rs_sent && link->rs_at==IPV6_FOREVER)link->rs_at=now+ipv6_jitter(link,1000); if(source && link->rs_sent<3 && now>=link->rs_at && ipv6_send_rs(state,link->ifindex,source)>=0){ diff --git a/net/ipv6/internal.h b/net/ipv6/internal.h index 921719a8..16486f0b 100644 --- a/net/ipv6/internal.h +++ b/net/ipv6/internal.h @@ -13,6 +13,8 @@ #define IPV6_REASM_MAX 4u #define IPV6_PMTU_MAX 8u +#define IPV6_CONTROL_DEFAULTS { [NET_IPV6_ACCEPT_RA] = 1, [NET_IPV6_HOP_LIMIT] = 64 } + struct ipv6_address_slot { struct net_ipv6_address value; uint64_t dad_at; @@ -66,6 +68,7 @@ struct ipv6_link { uint64_t reachable_ms, reachable_refresh, rs_at, mld_v1_until; uint8_t rs_sent; bool up; + int controls[NET_IPV6_CONTROL_COUNT]; }; /** @brief Protocol tables and deferred work owned by one network namespace. * Execution ownership serializes the borrowed namespace and maintenance links. @@ -82,6 +85,8 @@ struct net_ipv6_state { struct ipv6_reassembly reassembly[IPV6_REASM_MAX]; struct ipv6_pmtu pmtu[IPV6_PMTU_MAX]; struct ipv6_link *links; + int all_controls[NET_IPV6_CONTROL_COUNT]; + int default_controls[NET_IPV6_CONTROL_COUNT]; uint64_t error_at; uint32_t frag_id; uint8_t error_count; diff --git a/net/ipv6/state.c b/net/ipv6/state.c index 4609ffb4..50d6f8c8 100644 --- a/net/ipv6/state.c +++ b/net/ipv6/state.c @@ -2,7 +2,10 @@ #include "internal.h" #include -static struct net_ipv6_state initial_state; +static struct net_ipv6_state initial_state = { + .all_controls = IPV6_CONTROL_DEFAULTS, + .default_controls = IPV6_CONTROL_DEFAULTS, +}; /** @copydoc net_ipv6_state_get */ struct net_ipv6_state *net_ipv6_state_get(struct net_namespace *ns) @@ -16,6 +19,8 @@ struct net_ipv6_state *net_ipv6_state_create(struct net_namespace *ns) struct net_ipv6_state *state = kernel_malloc(sizeof(*state)); if (!state) return NULL; *state = (struct net_ipv6_state){.net_ns = ns, .initialized = true, + .all_controls = IPV6_CONTROL_DEFAULTS, + .default_controls = IPV6_CONTROL_DEFAULTS, .next = initial_state.next}; initial_state.next = state; return state; @@ -36,7 +41,8 @@ void net_ipv6_state_reset(struct net_ipv6_state *state) state->links = link->next; kernel_free(link); } - *state = (struct net_ipv6_state){.net_ns = state->net_ns, .next = state->next}; + *state = (struct net_ipv6_state){.net_ns = state->net_ns, .next = state->next, + .all_controls = IPV6_CONTROL_DEFAULTS, .default_controls = IPV6_CONTROL_DEFAULTS}; } /** @copydoc net_ipv6_state_destroy */ diff --git a/net/socket/netlink.c b/net/socket/netlink.c index d4ac134b..6e5403be 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -77,6 +77,7 @@ struct nl_link_state { struct net_ipv4_address_state policy; char name[NET_IF_NAME_LEN]; uint8_t mac[6]; + uint8_t addr_gen_mode; bool up, active; }; /** @brief Change baseline borrowed from a namespace's retained route subscribers. */ @@ -236,9 +237,9 @@ static uint8_t nl_prefix4(uint32_t mask) } /** @brief Emit one interface from a copied link state. - * @param b Builder. @param seq Sequence. @param index Interface index. + * @param b Builder. @param seq Sequence. * @param multi Multipart flag. @param type Native event. @param link Copied link. - * @return Zero or ENOBUFS. */ + * @return Zero or ENOBUFS. Emits the captured IPv6 address-generation mode. */ static int nl_link_snapshot(struct nl_builder *b, uint32_t seq, bool multi, uint16_t type, const struct nl_link_state *link) { @@ -260,7 +261,14 @@ static int nl_link_snapshot(struct nl_builder *b, uint32_t seq, bool multi, nl_attr(b,start,IFLA_MTU,&mtu,sizeof(mtu)) || nl_attr(b,start,IFLA_ADDRESS,index == 1 ? zero : link->mac,6) || nl_attr(b,start,IFLA_BROADCAST,index == 1 ? zero : broadcast,6)) return -LINUX_ENOBUFS; - return 0; + struct { + struct rtattr family, mode; + uint8_t value, padding[3]; + } ipv6 = { + .family = {.rta_len = sizeof(ipv6), .rta_type = AF_INET6 | NLA_F_NESTED}, + .mode = {.rta_len = sizeof(struct rtattr) + 1, .rta_type = IFLA_INET6_ADDR_GEN_MODE}, + .value = link->addr_gen_mode}; + return nl_attr(b, start, IFLA_AF_SPEC | NLA_F_NESTED, &ipv6, sizeof(ipv6)); } /** @brief Emit a live interface with current hardware state. @@ -270,6 +278,10 @@ static int nl_link(struct nl_builder *b, uint32_t seq, int index, bool multi) { struct nl_link_state link = {.index=(uint32_t)index}; if (!net_interface_name(b->net_ns, link.index,link.name)) return -LINUX_ENODEV; + int mode; + int rc = net_ipv6_control_get(b->net_ns, link.index, NET_IPV6_ADDR_GEN_MODE, &mode); + if (rc) return rc; + link.addr_gen_mode = (uint8_t)mode; link.up = net_interface_is_up(b->net_ns, link.index); if (link.index != NET_IF_LOOPBACK) { struct e1000_info info = {0}; netdev_get_info(link.index,&info); @@ -484,6 +496,10 @@ static int nl_links(struct net_namespace *ns, struct nl_link_state **out, uint32 link->mask = iface->config.subnet_mask; link->broadcast = iface->broadcast; link->policy = iface->ipv4_address; + int mode; + int rc = net_ipv6_control_get(ns, index, NET_IPV6_ADDR_GEN_MODE, &mode); + if (rc) { kernel_free(links); return rc; } + link->addr_gen_mode = (uint8_t)mode; link->up=net_interface_is_up(ns, index); if (index!=NET_IF_LOOPBACK) { struct e1000_info info={0}; netdev_get_info(index,&info); @@ -887,6 +903,7 @@ void netlink_network_changed(struct net_namespace *ns) for (uint32_t j=0;jlink_count;++j) if (snapshot->links[j].index==links[i].index) { old=&snapshot->links[j]; break; } if (!old || old->up!=links[i].up || old->active!=links[i].active || + old->addr_gen_mode!=links[i].addr_gen_mode || __builtin_memcmp(old->mac,links[i].mac,sizeof(old->mac)) || __builtin_strcmp(old->name,links[i].name)) nl_publish(ns, RTMGRP_LINK,RTM_NEWLINK,&links[i]); @@ -1059,7 +1076,7 @@ static int nl_dump(struct nl_builder *b, const struct nlmsghdr *h) return nl_done(b,h->nlmsg_seq); } -/** @brief Decode a fully bounded attribute sequence and reject duplicates. +/** @brief Decode bounded attributes, accepting nested markers and rejecting duplicates. * @param data Attribute bytes. @param length Available bytes. @param attrs Output pointer table. * @param slots Table capacity. @return Zero or EINVAL for malformed/duplicate attributes. */ static int nl_parse_attrs(const uint8_t *data, uint32_t length, @@ -1071,9 +1088,10 @@ static int nl_parse_attrs(const uint8_t *data, uint32_t length, if (a->rta_len < sizeof(*a) || a->rta_len > length) return -LINUX_EINVAL; uint32_t advance=RTA_ALIGN(a->rta_len); if (advance > length) return -LINUX_EINVAL; - if (a->rta_type >= slots) return -LINUX_EOPNOTSUPP; - if (attrs[a->rta_type]) return -LINUX_EINVAL; - attrs[a->rta_type]=a; + uint16_t type = a->rta_type & ~NLA_F_NESTED; + if (type >= slots) return -LINUX_EOPNOTSUPP; + if (attrs[type]) return -LINUX_EINVAL; + attrs[type]=a; data+=advance; length-=advance; } return 0; @@ -1089,6 +1107,38 @@ static int nl_copy_attr(const struct rtattr *a, void *out, uint32_t size) __builtin_memcpy(out,a+1,size); return 0; } +/** @brief Decode networkd's nested IPv6 link policy before applying mutations. + * @param af Nullable AF_SPEC attribute. @param mode Required output, -1 if absent. + * @return Zero, EINVAL for malformed input or EOPNOTSUPP for other policies. + * Native-endian attributes accept optional NLA_F_NESTED markers. + */ +static int nl_link_addrgen(const struct rtattr *af, int *mode) +{ + *mode = -1; + if (!af) return 0; + const struct rtattr *families[AF_INET6 + 1] = {0}; + int rc = nl_parse_attrs((const void *)(af + 1), af->rta_len - sizeof(*af), + families, AF_INET6 + 1); + if (rc) return rc; + for (unsigned i = 0; i <= AF_INET6; ++i) + if (families[i] && i != AF_INET6) return -LINUX_EOPNOTSUPP; + const struct rtattr *ipv6 = families[AF_INET6]; + if (!ipv6) return 0; + const struct rtattr *attrs[IFLA_INET6_ADDR_GEN_MODE + 1] = {0}; + rc = nl_parse_attrs((const void *)(ipv6 + 1), ipv6->rta_len - sizeof(*ipv6), + attrs, IFLA_INET6_ADDR_GEN_MODE + 1); + if (rc) return rc; + for (unsigned i = 0; i <= IFLA_INET6_ADDR_GEN_MODE; ++i) + if (attrs[i] && i != IFLA_INET6_ADDR_GEN_MODE) return -LINUX_EOPNOTSUPP; + if (attrs[IFLA_INET6_ADDR_GEN_MODE]) { + uint8_t value; + rc = nl_copy_attr(attrs[IFLA_INET6_ADDR_GEN_MODE], &value, sizeof(value)); + if (rc) return rc; + *mode = value; + } + return 0; +} + /** @copydoc nl_get_nexthop */ static int nl_get_nexthop(struct nl_builder *b, const struct nlmsghdr *h) { @@ -1170,12 +1220,15 @@ static int nl_change_link(struct net_namespace *ns, const struct nlmsghdr *h) req.ifi_family!=AF_INET && req.ifi_family!=AF_INET6) return -LINUX_EAFNOSUPPORT; if (req.ifi_index<0) return -LINUX_EINVAL; if (req.ifi_change & ~IFF_UP) return -LINUX_EOPNOTSUPP; - const struct rtattr *attrs[17]={0}; + const struct rtattr *attrs[IFLA_AF_SPEC + 1]={0}; int rc=nl_parse_attrs((const uint8_t *)(h+1)+sizeof(req), - h->nlmsg_len-sizeof(*h)-sizeof(req),attrs,17); + h->nlmsg_len-sizeof(*h)-sizeof(req),attrs,IFLA_AF_SPEC + 1); + if (rc) return rc; + for (unsigned i=0;i<=IFLA_AF_SPEC;++i) + if (attrs[i] && i!=IFLA_IFNAME && i!=IFLA_MTU && i!=IFLA_AF_SPEC) return -LINUX_EOPNOTSUPP; + int addr_gen_mode; + rc = nl_link_addrgen(attrs[IFLA_AF_SPEC], &addr_gen_mode); if (rc) return rc; - for (unsigned i=0;i<17;++i) - if (attrs[i] && i!=IFLA_IFNAME && i!=IFLA_MTU) return -LINUX_EOPNOTSUPP; uint32_t index=(uint32_t)req.ifi_index; char name[NET_IF_NAME_LEN]={0}; if (attrs[IFLA_IFNAME]) { @@ -1195,6 +1248,10 @@ static int nl_change_link(struct net_namespace *ns, const struct nlmsghdr *h) rc=nl_copy_attr(attrs[IFLA_MTU],&mtu,sizeof(mtu)); if (rc) return rc; if (mtu!=(index==NET_IF_LOOPBACK ? 65536u : 1500u)) return -LINUX_EOPNOTSUPP; } + if (addr_gen_mode >= 0) { + rc = net_ipv6_control_set(ns, index, NET_IPV6_ADDR_GEN_MODE, addr_gen_mode); + if (rc) return rc; + } if (req.ifi_index && name[0]) { rc=net_interface_rename(ns,index,name); if (rc) return rc; diff --git a/net/socket/packet.c b/net/socket/packet.c index d0461be0..3dc82225 100644 --- a/net/socket/packet.c +++ b/net/socket/packet.c @@ -51,6 +51,13 @@ struct packet_membership { struct packet_mreq request; uint32_t references; }; +struct packet_error { + struct packet_error *next; + struct net_udp_error_info info; + struct sockaddr_in6 destination; + uint32_t length; + uint8_t data[]; +}; struct packet_socket { struct net_namespace *net_ns; int domain, type, protocol, ifindex; @@ -68,6 +75,7 @@ struct packet_socket { uint16_t ping_id; int checksum_offset, unicast_hops, multicast_hops, mtu_discover; bool bound6, connected6, recv_pktinfo, recv_hoplimit, recv_old_hoplimit, dont_fragment, multicast_loop; + bool recv_error; bool timeout_immediate; uint32_t icmp6_filter[8]; struct { struct in6_addr address; uint32_t ifindex; bool used; } groups[16]; @@ -75,10 +83,70 @@ struct packet_socket { uint64_t timeout; unsigned queued; struct packet_message *head, *tail; + unsigned errors_queued; + struct packet_error *errors_head, *errors_tail; }; static struct packet_socket *sockets[PACKET_LIMIT]; static uint64_t packet_ino; +/** @brief Release an endpoint's error queue while preserving its pending errno. + * @param s Execution-owned socket. Ordinary received packets survive. */ +static void packet_errors_clear(struct packet_socket *s) +{ + while (s->errors_head) { + struct packet_error *error = s->errors_head; + s->errors_head = error->next; + kernel_free(error); + } + s->errors_tail = NULL; + s->errors_queued = 0; +} + +/** @brief Receive owned IPv6 error metadata independently of the data queue. + * @param s Execution-owned IPv6 endpoint. @param data Writable payload buffer. + * @param length Buffer capacity. @param flags Receive flags, with internal PEEK supported. + * @param address Optional user destination sockaddr. @param address_length User socklen pointer. + * @param source Optional kernel sockaddr output. @param source_length Optional native size output. + * @param info Optional extended-error output. @return Copied/full length or negative errno. + * All user outputs are prepared before consuming an error. Empty queues return EAGAIN. + */ +static int packet_error_recv(struct packet_socket *s, void *data, uint32_t length, + uint32_t flags, uint64_t address, uint64_t address_length, + void *source, uint32_t *source_length, struct net_udp_rx_info *info) +{ + net_poll_packets(); + struct packet_error *error = s->errors_head; + if (!error) return -LINUX_EAGAIN; + if (address) { + uint32_t capacity; + int result = socket_user_length(sched_current_task(), address_length, &capacity); + if (result) return result; + if ((int32_t)capacity < 0) return -LINUX_EINVAL; + uint32_t copied = capacity < sizeof(error->destination) ? capacity : sizeof(error->destination); + result = socket_user_prepare(sched_current_task(), address, copied, true); + if (result) return result; + if (copied && !user_range_writable(address, copied)) return -LINUX_EFAULT; + if (copied) __builtin_memcpy((void *)(uintptr_t)address, &error->destination, copied); + *(uint32_t *)(uintptr_t)address_length = sizeof(error->destination); + } + if (source && source_length) { + __builtin_memcpy(source, &error->destination, sizeof(error->destination)); + *source_length = sizeof(error->destination); + } + if (info) *info = (struct net_udp_rx_info){.error_queue = true, .extended = error->info}; + uint32_t copied = length < error->length ? length : error->length; + if (copied) __builtin_memcpy(data, error->data, copied); + int result = flags & MSG_TRUNC ? (int)error->length : (int)copied; + if (!(flags & MSG_PEEK)) { + s->errors_head = error->next; + if (!s->errors_head) s->errors_tail = NULL; + --s->errors_queued; + s->error = s->errors_head ? (int)s->errors_head->info.error.ee_errno : 0; + kernel_free(error); + } + return result; +} + /** @brief Retain an enabled socket's realtime sample in its queued datagram. * @param s Borrowed endpoint. @param m Owned queued or newly allocated packet. * Lazy sampling also covers enabling timestamps after arrival and keeps PEEK stable. @@ -406,6 +474,7 @@ int task_packet_send(struct task_file *file, const void *data, uint32_t length, * @param address Optional user source sockaddr destination. * @param address_length User socklen_t pointer. * @return Message bytes, negative errno or KERNEL_SYSCALL_BLOCKED. + * MSG_ERRQUEUE selects the independent IPv6 error queue before pending errno. */ static int packet_recv(struct task_file *file, void *data, uint32_t length, uint32_t flags, uint64_t address, uint64_t address_length, @@ -413,8 +482,12 @@ static int packet_recv(struct task_file *file, void *data, uint32_t length, { struct packet_socket *s = packet_of(file); if (!s) return -LINUX_EBADF; + if (flags & ~(MSG_DONTWAIT | MSG_PEEK | MSG_TRUNC | MSG_WAITALL | + (s->domain == AF_INET6 ? MSG_ERRQUEUE : 0))) return -LINUX_EOPNOTSUPP; + if (flags & MSG_ERRQUEUE) + return packet_error_recv(s, data, length, flags, address, address_length, + staged_source, staged_length, info); if (s->error) { int error=s->error; s->error=0; return -error; } - if (flags & ~(MSG_DONTWAIT | MSG_PEEK | MSG_TRUNC | MSG_WAITALL)) return -LINUX_EOPNOTSUPP; net_poll_packets(); if (!s->head) { if ((file->flags & RELIEFOS_O_NONBLOCK) || (flags & MSG_DONTWAIT)) return -LINUX_EAGAIN; @@ -473,9 +546,18 @@ static int packet_recv(struct task_file *file, void *data, uint32_t length, return result; } +/** @brief Receive one packet or IPv6 error with validated user address outputs. + * @param file Pinned OFD. @param data Validated writable payload destination. + * @param length Capacity. @param flags External Linux receive flags. + * @param address Optional user sockaddr. @param address_length User socklen pointer. + * @return Bytes, errno or blocked sentinel. MSG_ERRQUEUE consumes one error + * even with MSG_PEEK. Internal swap probes use task_packet_recv_staged. */ int task_packet_recv(struct task_file *file,void *data,uint32_t length, uint32_t flags,uint64_t address,uint64_t address_length) -{ return packet_recv(file,data,length,flags,address,address_length,NULL,NULL,NULL); } +{ + if (flags & MSG_ERRQUEUE) flags &= ~MSG_PEEK; + return packet_recv(file,data,length,flags,address,address_length,NULL,NULL,NULL); +} /** @brief Determine the native source sockaddr size for a packet endpoint. * @param file Pinned packet OFD. @return Native size, or zero for invalid OFD. @@ -491,10 +573,14 @@ uint32_t task_packet_address_size(const struct task_file *file) * @param file Pinned OFD. @param data Kernel destination. @param length Capacity. * @param flags Receive flags. @param source Optional native source output. * @param source_length Optional size output. @param info Optional ingress metadata. - * @return Bytes, errno or the blocked sentinel. */ + * @return Bytes, errno or the blocked sentinel. External MSG_ERRQUEUE consumes + * an error even with MSG_PEEK, while the staged internal probe retains it. */ int task_packet_recv_ex(struct task_file *file,void *data,uint32_t length,uint32_t flags, void *source,uint32_t *source_length,struct net_udp_rx_info *info) -{ return packet_recv(file,data,length,flags,0,0,source,source_length,info); } +{ + if (flags & MSG_ERRQUEUE) flags &= ~MSG_PEEK; + return packet_recv(file,data,length,flags,0,0,source,source_length,info); +} #ifdef CONFIG_SWAP /** @brief Receive packet bytes and source into caller-owned kernel storage. @@ -511,14 +597,15 @@ int task_packet_recv_staged(struct task_file *file,void *data,uint32_t length, /** @brief Query packet readiness under the execution lock. * @param file Pinned socket. * @param events Requested readiness bits. - * @return Readiness bits or POLLNVAL. + * @return Readiness bits or POLLNVAL. Queued errors retain POLLERR after SO_ERROR. */ short task_packet_poll(struct task_file *file, short events) { struct packet_socket *s = packet_of(file); if (!s) return POLLNVAL; net_poll_packets(); - return (events & POLLOUT) | (s->head ? events & POLLIN : 0) | (s->error ? POLLERR : 0); + return (events & POLLOUT) | (s->head ? events & POLLIN : 0) | + (s->error || s->errors_head ? POLLERR : 0); } /** @brief Query the next datagram length. @@ -531,7 +618,7 @@ int task_packet_available(struct task_file *file) return !s ? -LINUX_EBADF : s->head ? (int)s->head->length : 0; } -/** @brief Remove a final socket, release its multicast groups, queue and network. +/** @brief Remove a final socket, release multicast, data/error queues and network. * @param file Owned description under the execution lock. */ void task_packet_release(struct task_file *file) @@ -543,6 +630,7 @@ void task_packet_release(struct task_file *file) if (s->groups[i].used) (void)net_ipv6_multicast_change(s->net_ns, &s->groups[i].address, s->groups[i].ifindex, -1); while (s->head) { struct packet_message *m = s->head; s->head = m->next; kernel_free(m); } + packet_errors_clear(s); while (s->memberships) { struct packet_membership *m = s->memberships; s->memberships = m->next; @@ -607,6 +695,10 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin case IPV6_MULTICAST_IF: if (value < 0 || (value && !net_interface_exists(s->net_ns, (uint32_t)value))) return -LINUX_ENODEV; s->multicast_if = (uint32_t)value; break; case IPV6_MULTICAST_LOOP: if (value != 0 && value != 1) return -LINUX_EINVAL; s->multicast_loop = value != 0; break; case IPV6_RECVPKTINFO: s->recv_pktinfo = value != 0; break; + case IPV6_RECVERR: + s->recv_error = value != 0; + if (!value) packet_errors_clear(s); + break; case IPV6_RECVHOPLIMIT: s->recv_hoplimit = value != 0; break; case IPV6_2292HOPLIMIT: s->recv_old_hoplimit = value != 0; break; case IPV6_DONTFRAG: s->dont_fragment = value != 0; break; @@ -624,6 +716,7 @@ static int packet6_option(struct packet_socket *s, bool set, uint32_t level, uin case IPV6_MULTICAST_IF: value = (int)s->multicast_if; break; case IPV6_MULTICAST_LOOP: value = s->multicast_loop; break; case IPV6_RECVPKTINFO: value = s->recv_pktinfo; break; + case IPV6_RECVERR: value = s->recv_error; break; case IPV6_RECVHOPLIMIT: value = s->recv_hoplimit; break; case IPV6_2292HOPLIMIT: value = s->recv_old_hoplimit; break; case IPV6_DONTFRAG: value = s->dont_fragment; break; @@ -937,6 +1030,8 @@ void net_ipv6_socket_extended_error_on(struct net_namespace *ns, uint32_t ifinde const struct sockaddr_storage *offender) { if (!packet || !error || !error->ee_errno || length < 40 || packet[0] >> 4 != 6) return; + uint32_t total = 40u + ((uint32_t)packet[4] << 8) + packet[5]; + if (length > total) length = total; struct in6_addr source, destination; __builtin_memcpy(&source, packet + 8, 16); __builtin_memcpy(&destination, packet + 24, 16); uint8_t protocol = packet[6]; @@ -955,7 +1050,22 @@ void net_ipv6_socket_extended_error_on(struct net_namespace *ns, uint32_t ifinde (s->remote_scope6 && s->remote_scope6 != ifindex))) || (!packet6_any(&s->local6) && __builtin_memcmp(&s->local6, &source, sizeof(source))) || (s->connected6 && __builtin_memcmp(&s->remote6, &destination, sizeof(destination)))) continue; + if (s->type == SOCK_DGRAM && (length < 48 || packet[40] != 128 || packet[41] || + (((uint16_t)packet[44] << 8) | packet[45]) != s->ping_id)) continue; s->error = (int)error->ee_errno; + if (!s->recv_error || s->errors_queued == PACKET_QUEUE_LIMIT) continue; + uint32_t payload_length = length - 40; + struct packet_error *record = kernel_malloc(sizeof(*record) + payload_length); + if (!record) continue; + *record = (struct packet_error){.info.error = *error, .length = payload_length, + .destination = {.sin6_family = AF_INET6, .sin6_addr = destination, + .sin6_scope_id = net_ipv6_needs_scope_id(&destination) ? ifindex : 0}}; + if (offender) record->info.offender = *offender; + if (payload_length) __builtin_memcpy(record->data, packet + 40, payload_length); + if (s->errors_tail) s->errors_tail->next = record; + else s->errors_head = record; + s->errors_tail = record; + ++s->errors_queued; } kernel_poll_readiness_notify(); } diff --git a/tools/test_ipv6_transport.py b/tools/test_ipv6_transport.py index 2dacc361..8f470732 100644 --- a/tools/test_ipv6_transport.py +++ b/tools/test_ipv6_transport.py @@ -23,6 +23,7 @@ "kernel/syscall/io/vector.c", "kernel/syscall/ipc/socket.c", "kernel/sched/user_namespace.c", "net/namespace/namespace.c", "net/ipv6/state.c", + "net/socket/filter.c", "kernel/syscall/fs/lookup_state.c", "-o", str(binary)], cwd=root, check=True) subprocess.run([str(binary)], cwd=root, check=True, timeout=20) binary = out / "ipv6_tcp_test" diff --git a/tools/test_net_multi_interface.py b/tools/test_net_multi_interface.py index fb10cdc2..e4e2ae02 100644 --- a/tools/test_net_multi_interface.py +++ b/tools/test_net_multi_interface.py @@ -11,6 +11,7 @@ "-fno-sanitize-recover=all", "-fno-pie", "-no-pie", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude/uapi", "tools/tests/net_multi_interface_test.c", "net/interface/state.c", - "net/interface/routes.c", "net/interface/ioctl.c", "net/utility.c", "net/socket/filter.c", + "net/interface/routes.c", "net/interface/nexthop.c", "net/interface/ioctl.c", + "net/utility.c", "net/socket/filter.c", "-o", str(binary)], cwd=ROOT, check=True) subprocess.run([str(binary)], check=True, timeout=15) diff --git a/tools/test_procfs.py b/tools/test_procfs.py index e69eed3a..70064735 100644 --- a/tools/test_procfs.py +++ b/tools/test_procfs.py @@ -12,7 +12,8 @@ class ProcfsTests(unittest.TestCase): def test_real_procfs_directory_lookup_and_enumeration(self): with tempfile.TemporaryDirectory(prefix="reliefos-procfs-") as directory: executable = str(Path(directory) / "procfs") - for fixture in ("procfs_directories_test", "procfs_views_test"): + for fixture in ("procfs_directories_test", "procfs_views_test", "procfs_network_test"): + network_sources = ["fs/proc/network.c"] if fixture == "procfs_network_test" else [] subprocess.run(["cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude/uapi", @@ -22,7 +23,7 @@ def test_real_procfs_directory_lookup_and_enumeration(self): "kernel/syscall/fd/proc.c", "fs/vfs/exec_file.c", "kernel/sched/identity.c", "kernel/sched/user_namespace.c", "kernel/init/uts.c", "fs/security/access.c", "net/namespace/namespace.c", - "net/ipv6/state.c", "-o", executable], + "net/ipv6/state.c", *network_sources, "-o", executable], cwd=ROOT, check=True) subprocess.run([executable], check=True, timeout=10) diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 8e0f8696..08c4f1ac 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -23,6 +23,36 @@ static bool additional_address; static bool nic_ready=true; static bool nic_present=true; static bool neighbor_entries; +static struct { + struct net_namespace *ns; + uint32_t ifindex; + int mode, error; + unsigned updates; +} addrgen_control; + +/** @brief Model address-generation controls while exercising real rtnetlink dispatch. */ +int net_ipv6_control_get(struct net_namespace *ns, uint32_t index, + enum net_ipv6_control control, int *value) +{ + assert(control == NET_IPV6_ADDR_GEN_MODE); + *value = ns == addrgen_control.ns && index == addrgen_control.ifindex ? addrgen_control.mode : 0; + return 0; +} + +/** @brief Capture the creating network selected by the rtnetlink control request. */ +int net_ipv6_control_set(struct net_namespace *ns, uint32_t index, + enum net_ipv6_control control, int value) +{ + assert(control == NET_IPV6_ADDR_GEN_MODE); + if (value > 3) return -LINUX_EINVAL; + if (value > 1) return -LINUX_EOPNOTSUPP; + if (addrgen_control.error) return addrgen_control.error; + addrgen_control.ns = ns; + addrgen_control.ifindex = index; + addrgen_control.mode = value; + ++addrgen_control.updates; + return 0; +} /* Enabled only by the scoped control regression. */ static struct { struct net_namespace *ns; @@ -1958,8 +1988,8 @@ static void check_link_rename(void) assert(header->nlmsg_type == RTM_NEWLINK && !header->nlmsg_seq); const struct ifinfomsg *link = (const void *)(header + 1); assert(link->ifi_index == 2); - const struct rtattr *attrs[17] = {0}; - assert(!nl_parse_attrs((const uint8_t *)(link + 1), bytes - sizeof(*header) - sizeof(*link), attrs, 17)); + const struct rtattr *attrs[IFLA_AF_SPEC + 1] = {0}; + assert(!nl_parse_attrs((const uint8_t *)(link + 1), bytes - sizeof(*header) - sizeof(*link), attrs, IFLA_AF_SPEC + 1)); assert(attrs[IFLA_IFNAME] && !strcmp((const char *)(attrs[IFLA_IFNAME] + 1), "enp0s3")); bytes = receive(events, output, sizeof(output)); static const char expected[] = "move@/devices/pci0000:00/0000:00:00.0/net/enp0s3\0ACTION=move\0" @@ -2156,6 +2186,84 @@ static void check_networkd_nexthop(void) puts("PASS networkd standalone nexthop creation and removal"); } +/** @brief Exercise networkd's nested IPv6 link policy and retained socket scope. */ +static void check_link_addrgen(void) +{ + unsigned baseline = allocations; + struct task saved = current; + struct net_namespace *scope = NULL; + assert(!net_namespace_create(NULL, &scope)); + current = (struct task){.net_ns = scope, .cap_effective = 1ULL << CAP_NET_ADMIN}; + int fd = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, 0, 0); + assert(fd >= 0); + current.net_ns = NULL; + struct { + struct nlmsghdr header; + struct ifinfomsg link; + struct rtattr af, ipv6, mode; + uint8_t value, padding[3]; + } request = { + .header = {.nlmsg_len = sizeof(request), .nlmsg_type = RTM_SETLINK, + .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK}, + .link = {.ifi_index = NET_IF_LOOPBACK}, + .af = {.rta_len = 16, .rta_type = IFLA_AF_SPEC | NLA_F_NESTED}, + .ipv6 = {.rta_len = 12, .rta_type = AF_INET6 | NLA_F_NESTED}, + .mode = {.rta_len = 5, .rta_type = IFLA_INET6_ADDR_GEN_MODE}, + .value = IN6_ADDR_GEN_MODE_NONE}; + check_ipv6_ack(fd, &request, sizeof(request), 0); + assert(addrgen_control.ns == scope && addrgen_control.ifindex == NET_IF_LOOPBACK && + addrgen_control.mode == IN6_ADDR_GEN_MODE_NONE && addrgen_control.updates == 1); + unsigned char output[1024]; + struct { struct nlmsghdr header; struct ifinfomsg link; } query = { + .header = {.nlmsg_len = sizeof(query), .nlmsg_type = RTM_GETLINK, .nlmsg_flags = NLM_F_REQUEST}, + .link = {.ifi_index = NET_IF_LOOPBACK}}; + assert(send_req(fd, &query, sizeof(query)) == sizeof(query)); + int bytes = receive(fd, output, sizeof(output)); + assert(bytes > (int)sizeof(query)); + const struct rtattr *attrs[IFLA_AF_SPEC + 1] = {0}, *families[AF_INET6 + 1] = {0}; + const struct rtattr *modes[IFLA_INET6_ADDR_GEN_MODE + 1] = {0}; + assert(!nl_parse_attrs(output + sizeof(query), bytes - sizeof(query), attrs, IFLA_AF_SPEC + 1)); + assert(attrs[IFLA_AF_SPEC]); + assert(!nl_parse_attrs((const void *)(attrs[IFLA_AF_SPEC] + 1), + attrs[IFLA_AF_SPEC]->rta_len - sizeof(struct rtattr), families, AF_INET6 + 1)); + assert(families[AF_INET6]); + assert(!nl_parse_attrs((const void *)(families[AF_INET6] + 1), + families[AF_INET6]->rta_len - sizeof(struct rtattr), modes, IFLA_INET6_ADDR_GEN_MODE + 1)); + assert(modes[IFLA_INET6_ADDR_GEN_MODE] && + *(const uint8_t *)(modes[IFLA_INET6_ADDR_GEN_MODE] + 1) == IN6_ADDR_GEN_MODE_NONE); + current.cap_effective = 0; + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_EPERM); + current.cap_effective = 1ULL << CAP_NET_ADMIN; + request.mode.rta_len = 4; + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_EINVAL); + request.mode.rta_len = 5; + request.value = IN6_ADDR_GEN_MODE_STABLE_PRIVACY; + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_EOPNOTSUPP); + request.value = 255; + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_EINVAL); + request.value = IN6_ADDR_GEN_MODE_EUI64; + request.ipv6.rta_type = AF_INET; + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_EOPNOTSUPP); + request.ipv6.rta_type = AF_INET6; + request.af.rta_type = IFLA_AF_SPEC; + addrgen_control.error = -LINUX_ENOMEM; + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_ENOMEM); + addrgen_control.error = 0; + assert(addrgen_control.updates == 1 && addrgen_control.mode == IN6_ADDR_GEN_MODE_NONE); + check_ipv6_ack(fd, &request, sizeof(request), 0); + assert(addrgen_control.updates == 2 && !addrgen_control.mode); + request.link.ifi_index = 2; + check_ipv6_ack(fd, &request, sizeof(request), -LINUX_ENODEV); + task_netlink_release(&files[fd]); + files[fd] = (struct task_file){0}; + addrgen_control.ns = NULL; + addrgen_control.ifindex = 0; + net_namespace_put(scope); + current = saved; + assert(allocations == baseline); + puts("PASS nested IPv6 link policy: networkd wire format, dump, socket scope, errors and authority"); +} + int main(void) { check_generic_netlink(); @@ -2181,6 +2289,7 @@ int main(void) check_netlink_metadata_options(); check_netlink_filter(); check_link_rename(); + check_link_addrgen(); net_config.local_ip=0x0a00020f; net_config.subnet_mask=0xffffff00; int fd = (int)call(__NR_socket,AF_NETLINK,SOCK_RAW|SOCK_NONBLOCK,NETLINK_ROUTE,0,0); assert(fd >= 0 && files[fd].socket_ino); diff --git a/tools/tests/ipv6_protocol_test.c b/tools/tests/ipv6_protocol_test.c index afb91c95..68d9bbc4 100644 --- a/tools/tests/ipv6_protocol_test.c +++ b/tools/tests/ipv6_protocol_test.c @@ -811,6 +811,148 @@ static void test_namespace_addresses(void) } #endif +#ifndef IPV6_NO_IMPLEMENTATION +/** @brief Exercise namespace-local host controls against real IPv6 packet processing. */ +static void test_ipv6_host_controls(void) +{ + now_ms = 0; + sent_count = 0; + random_word = 0; + first_nic = true; + second_nic = false; + extra_nics = 0; + nic_ready = true; + net_interface_up = true; + net_ipv6_init(); + int value; + assert(!net_ipv6_control_get(NULL, 2, NET_IPV6_HOP_LIMIT, &value) && value == 64); + assert(net_ipv6_control_set(NULL, 2, NET_IPV6_HOP_LIMIT, 0) == -LINUX_EINVAL); + assert(net_ipv6_control_set(NULL, 2, NET_IPV6_HOP_LIMIT, 256) == -LINUX_EINVAL); + assert(!net_ipv6_control_set(NULL, 2, NET_IPV6_HOP_LIMIT, 37)); + assert(!net_ipv6_control_set(NULL, NET_IPV6_CONF_DEFAULT, NET_IPV6_HOP_LIMIT, 42)); + assert(!net_ipv6_control_get(NULL, 2, NET_IPV6_HOP_LIMIT, &value) && value == 37); + second_nic = true; + assert(!net_ipv6_link_changed_on(NULL, second_index, true)); + assert(!net_ipv6_control_get(NULL, second_index, NET_IPV6_HOP_LIMIT, &value) && value == 42); + assert(!net_ipv6_control_set(NULL, NET_IPV6_CONF_ALL, NET_IPV6_HOP_LIMIT, 55)); + assert(!net_ipv6_control_get(NULL, second_index, NET_IPV6_HOP_LIMIT, &value) && value == 42); + net_ipv6_poll(); + now_ms = 1000; + net_ipv6_poll(); + struct in6_addr group = {.s6_addr = {0xff, 2, [15] = 1}}; + struct in6_addr router = {.s6_addr = {0xfe, 0x80, [15] = 0x42}}; + struct net_ipv6_path path; + assert(!net_ipv6_route(NULL, &group, 2, NULL, &path)); + uint8_t message[8] = {0}; + assert(net_ipv6_output(NULL, &path, 253, message, sizeof(message), -1, 0, false, false) == 8); + assert(sent[sent_count - 1][21] == 37); + + uint8_t ra[48] = {134, 0, 0, 0, 99, 0, 0, 30}; + ra[16] = 3; ra[17] = 4; ra[18] = 64; ra[19] = 0xc0; + net_put_u32(ra + 20, 86400); + net_put_u32(ra + 24, 3600); + ra[32] = 0x20; ra[33] = 1; ra[34] = 0x0d; ra[35] = 0xb8; + net_put_u16(ra + 2, net_ipv6_checksum(&router, &group, 58, ra, sizeof(ra))); + uint8_t frame[256]; + uint32_t length = packet(frame, &router, &group, 58, 255, ra, sizeof(ra)); + assert(!net_ipv6_control_set(NULL, 2, NET_IPV6_ACCEPT_RA, 0)); + uint32_t addresses = net_ipv6_addresses(NULL, NULL, 0); + uint32_t routes = net_ipv6_routes(NULL, NULL, 0); + unsigned raw = raw_count; + net_ipv6_input_on(NULL, 2, frame, length); + assert(raw_count == raw + 1); + assert(net_ipv6_addresses(NULL, NULL, 0) == addresses); + assert(net_ipv6_routes(NULL, NULL, 0) == routes); + assert(!net_ipv6_control_get(NULL, 2, NET_IPV6_HOP_LIMIT, &value) && value == 37); + assert(!net_ipv6_control_set(NULL, 2, NET_IPV6_ACCEPT_RA, 2)); + net_ipv6_input_on(NULL, 2, frame, length); + assert(net_ipv6_addresses(NULL, NULL, 0) == addresses + 1); + assert(!net_ipv6_control_get(NULL, 2, NET_IPV6_HOP_LIMIT, &value) && value == 99); + + assert(!net_ipv6_control_set(NULL, 2, NET_IPV6_DISABLE, 1)); + struct net_ipv6_address entries[16]; + uint32_t count = net_ipv6_addresses(NULL, entries, 16); + for (uint32_t i = 0; i < count; ++i) assert(entries[i].ifindex != 2); + struct net_ipv6_address manual = {.address = router, .ifindex = 2, .prefix_length = 64, + .flags = NET_IPV6_ADDR_NODAD, .preferred_until = UINT64_MAX, .valid_until = UINT64_MAX}; + assert(net_ipv6_address_update(NULL, &manual, false) == -LINUX_EACCES); + raw = raw_count; + net_ipv6_input_on(NULL, 2, frame, length); + assert(raw_count == raw); + now_ms += 10000; + net_ipv6_poll(); + count = net_ipv6_addresses(NULL, entries, 16); + for (uint32_t i = 0; i < count; ++i) assert(entries[i].ifindex != 2); + assert(!net_ipv6_control_set(NULL, 2, NET_IPV6_ADDR_GEN_MODE, 1)); + assert(!net_ipv6_control_set(NULL, 2, NET_IPV6_DISABLE, 0)); + count = net_ipv6_addresses(NULL, entries, 16); + for (uint32_t i = 0; i < count; ++i) assert(entries[i].ifindex != 2); + assert(!net_ipv6_control_set(NULL, 2, NET_IPV6_ADDR_GEN_MODE, 0)); + assert(net_ipv6_addresses(NULL, NULL, 0) == count + 1); + assert(net_ipv6_control_set(NULL, 2, NET_IPV6_ADDR_GEN_MODE, 2) == -LINUX_EOPNOTSUPP); + assert(net_ipv6_control_set(NULL, 2, NET_IPV6_USE_TEMPADDR, 1) == -LINUX_EOPNOTSUPP); + assert(!net_ipv6_control_set(NULL, 2, NET_IPV6_USE_TEMPADDR, -1)); + assert(!net_ipv6_control_set(NULL, NET_IPV6_CONF_ALL, NET_IPV6_DISABLE, 1)); + assert(!net_ipv6_addresses(NULL, NULL, 0) && !net_ipv6_routes(NULL, NULL, 0)); + assert(!net_ipv6_control_get(NULL, NET_IPV6_CONF_DEFAULT, NET_IPV6_DISABLE, &value) && value == 1); + assert(!net_ipv6_control_set(NULL, NET_IPV6_CONF_ALL, NET_IPV6_DISABLE, 0)); + + struct net_namespace *isolated = NULL; + assert(!net_namespace_create(NULL, &isolated) && isolated); + assert(!net_ipv6_control_get(isolated, NET_IPV6_CONF_DEFAULT, NET_IPV6_HOP_LIMIT, &value) && value == 64); + assert(!net_ipv6_control_set(isolated, 1, NET_IPV6_DISABLE, 1)); + assert(!net_ipv6_control_get(NULL, 1, NET_IPV6_DISABLE, &value) && !value); + net_namespace_put(isolated); + net_ipv6_detached_on(NULL, second_index); + second_nic = false; + net_ipv6_init(); + puts("PASS IPv6 host controls: packet effects, all/default, namespaces and unsupported modes"); +} + +/** @brief Preserve visible controls and protocol state on activation or allocation failure. */ +static void test_ipv6_control_failures(void) +{ + first_nic = true; + second_nic = false; + extra_nics = 0; + net_interface_up = true; + net_ipv6_init(); + uint32_t addresses = net_ipv6_addresses(NULL, NULL, 0); + uint32_t routes = net_ipv6_routes(NULL, NULL, 0); + size_t before = live_allocations; + second_nic = true; + net_interface_up = false; + allocation_budget = 0; + assert(net_ipv6_control_set(NULL, NET_IPV6_CONF_DEFAULT, NET_IPV6_HOP_LIMIT, 33) == -LINUX_ENOMEM); + assert(live_allocations == before); + int value; + assert(!net_ipv6_control_get(NULL, NET_IPV6_CONF_DEFAULT, NET_IPV6_HOP_LIMIT, &value) && value == 64); + assert(!net_ipv6_control_get(NULL, second_index, NET_IPV6_HOP_LIMIT, &value) && value == 64); + assert(net_ipv6_addresses(NULL, NULL, 0) == addresses && net_ipv6_routes(NULL, NULL, 0) == routes); + allocation_budget = -1; + assert(!net_ipv6_control_set(NULL, NET_IPV6_CONF_DEFAULT, NET_IPV6_HOP_LIMIT, 33)); + assert(!net_ipv6_control_get(NULL, second_index, NET_IPV6_HOP_LIMIT, &value) && value == 64); + + assert(!net_ipv6_control_set(NULL, NET_IPV6_CONF_ALL, NET_IPV6_DISABLE, 1)); + extra_nics = 17; + net_interface_up = true; + assert(net_ipv6_control_set(NULL, NET_IPV6_CONF_ALL, NET_IPV6_DISABLE, 0) == -LINUX_ENOBUFS); + assert(!net_ipv6_addresses(NULL, NULL, 0) && !net_ipv6_routes(NULL, NULL, 0)); + assert(!net_ipv6_control_get(NULL, NET_IPV6_CONF_ALL, NET_IPV6_DISABLE, &value) && value == 1); + assert(!net_ipv6_control_get(NULL, NET_IPV6_CONF_DEFAULT, NET_IPV6_DISABLE, &value) && value == 1); + for (uint32_t index = net_interface_next(NULL, 0); index; index = net_interface_next(NULL, index)) + assert(!net_ipv6_control_get(NULL, index, NET_IPV6_DISABLE, &value) && value == 1); + for (uint32_t index = 100; index < 117; ++index) net_ipv6_detached_on(NULL, index); + extra_nics = 0; + assert(!net_ipv6_control_set(NULL, NET_IPV6_CONF_ALL, NET_IPV6_DISABLE, 0)); + assert(net_ipv6_addresses(NULL, NULL, 0) == 3); + net_ipv6_detached_on(NULL, second_index); + second_nic = false; + net_ipv6_init(); + puts("PASS IPv6 control failure atomicity: down-link defaults, ENOMEM and all-enable capacity"); +} +#endif + /** @brief Exercise real host packet/state processing with deterministic NIC and time. * @return Zero on success. */ int main(void) @@ -1041,6 +1183,8 @@ int main(void) test_namespace_addresses(); test_networkd_route_policy(); test_networkd_nexthop_lifecycle(); + test_ipv6_host_controls(); + test_ipv6_control_failures(); puts("PASS IPv6 protocol: loopback, DAD/NDP, checksums, fragments, RA/SLAAC, MLD and timer pump"); #endif return 0; diff --git a/tools/tests/ipv6_tcp_test.c b/tools/tests/ipv6_tcp_test.c index 6e9b55ae..ed3bd8f8 100644 --- a/tools/tests/ipv6_tcp_test.c +++ b/tools/tests/ipv6_tcp_test.c @@ -250,6 +250,7 @@ static void test_tcp6_creating_network(bool mapped) } if (!mapped) { uint8_t quote[48] = {0x60}; + net_put_u16(quote + 4, 20); quote[6] = IPV4_PROTO_TCP; memcpy(quote + 8, &loop6, 16); memcpy(quote + 24, &loop6, 16); diff --git a/tools/tests/ipv6_transport_test.c b/tools/tests/ipv6_transport_test.c index ccca99bc..9665115d 100644 --- a/tools/tests/ipv6_transport_test.c +++ b/tools/tests/ipv6_transport_test.c @@ -213,6 +213,117 @@ static void close_packet(int fd) files[fd].used = 0; } +/** @brief Exercise bounded raw/ping error delivery without consuming ordinary data. */ +static void test_packet6_error_queue(void) +{ + unsigned baseline = allocations; + uint64_t capabilities = current.cap_effective; + current.cap_effective |= 1ULL << CAP_NET_RAW; + for (unsigned variant = 0; variant < 2; ++variant) { + int fd = (int)syscall_packet(__NR_socket, AF_INET6, + (variant ? SOCK_DGRAM : SOCK_RAW) | SOCK_NONBLOCK, IPPROTO_ICMPV6, 0, 0, 0); + assert(fd >= 0); + int enabled = 1; + assert(!syscall_packet(__NR_setsockopt, fd, SOL_IPV6, IPV6_RECVERR, + (uintptr_t)&enabled, sizeof(enabled), 0)); + int value = -1; + uint32_t size = sizeof(value); + assert(!syscall_packet(__NR_getsockopt, fd, SOL_IPV6, IPV6_RECVERR, + (uintptr_t)&value, (uintptr_t)&size, 0)); + assert(value == 1 && size == sizeof(value)); + struct sockaddr_in6 address = {.sin6_family = AF_INET6, + .sin6_addr = loop6, .sin6_port = swap16(55301)}; + assert(!syscall_packet(__NR_bind, fd, (uintptr_t)&address, sizeof(address), 0, 0, 0)); + uint8_t quote[52] = {0x60}; + quote[6] = IPPROTO_ICMPV6; + net_put_u16(quote + 4, 12); + memcpy(quote + 8, &loop6, 16); + memcpy(quote + 24, &loop6, 16); + quote[40] = 128; + net_put_u16(quote + 44, 55301); + memcpy(quote + 48, "echo", 4); + struct sock_extended_err error = {.ee_errno = LINUX_EHOSTUNREACH, + .ee_origin = SO_EE_ORIGIN_ICMP6, .ee_type = 1, .ee_code = 3}; + struct sockaddr_storage offender = {0}; + struct sockaddr_in6 router = {.sin6_family = AF_INET6, .sin6_addr = loop6}; + memcpy(&offender, &router, sizeof(router)); + char bytes[16]; + struct sockaddr_in6 destination; + struct net_udp_rx_info info; + assert(task_packet_recv_ex(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE, + &destination, &size, &info) == -LINUX_EAGAIN); + if (variant) { + net_put_u16(quote + 44, 55302); + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, &offender); + assert(!(task_packet_poll(&files[fd], POLLIN) & POLLERR)); + net_put_u16(quote + 44, 55301); + } + struct net_namespace *other; + assert(!net_namespace_create(NULL, &other)); + net_ipv6_socket_extended_error_on(other, 1, quote, sizeof(quote), &error, &offender); + assert(!(task_packet_poll(&files[fd], POLLIN) & POLLERR)); + net_namespace_put(other); + uint8_t reply[8] = {129, 0, 0, 0, 55301 >> 8, 55301 & 255}; + net_raw6_input(NULL, &loop6, &loop6, IPPROTO_ICMPV6, reply, sizeof(reply), 1, 64); + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, &offender); + assert(task_packet_poll(&files[fd], POLLIN) == (POLLIN | POLLERR)); + assert(task_packet_recv_ex(&files[fd], bytes, 4, MSG_ERRQUEUE | MSG_PEEK | MSG_TRUNC, + &destination, &size, &info) == 12); + assert(!memcmp(bytes, quote + 40, 4)); + assert(info.error_queue && !info.ipv4 && info.extended.error.ee_errno == LINUX_EHOSTUNREACH); + assert(info.extended.error.ee_origin == SO_EE_ORIGIN_ICMP6 && + info.extended.error.ee_type == 1 && info.extended.error.ee_code == 3); + assert(!memcmp(&info.extended.offender, &offender, sizeof(offender))); + assert(size == sizeof(destination) && destination.sin6_family == AF_INET6 && + !destination.sin6_port && !memcmp(&destination.sin6_addr, &loop6, 16)); + assert(task_packet_recv_ex(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE, + NULL, NULL, &info) == -LINUX_EAGAIN); + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, &offender); + size = sizeof(destination); + assert(task_packet_recv(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE | MSG_PEEK, + (uintptr_t)&destination, (uintptr_t)&size) == 12); + assert(size == sizeof(destination) && destination.sin6_family == AF_INET6 && + !memcmp(&destination.sin6_addr, &loop6, 16)); + assert(task_packet_recv(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE, 0, 0) + == -LINUX_EAGAIN); + assert(task_packet_recv(&files[fd], bytes, sizeof(bytes), 0, 0, 0) == 8); + assert(!memcmp(bytes, reply, sizeof(reply))); + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, NULL); + allocation_fail_after = 0; + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, NULL); + allocation_fail_after = -1; + assert(task_packet_recv_ex(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE, + NULL, NULL, &info) == 12); + assert(task_packet_recv_ex(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE, + NULL, NULL, &info) == -LINUX_EAGAIN); + allocation_fail_after = 0; + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, NULL); + allocation_fail_after = -1; + assert(task_packet_recv(&files[fd], bytes, sizeof(bytes), 0, 0, 0) == -LINUX_EHOSTUNREACH); + for (unsigned i = 0; i < 40; ++i) + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, NULL); + unsigned queued = 0; + while (task_packet_recv_ex(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE, + NULL, NULL, &info) == 12) ++queued; + assert(queued == 32 && !(task_packet_poll(&files[fd], POLLIN) & POLLERR)); + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, NULL); + enabled = 0; + assert(!syscall_packet(__NR_setsockopt, fd, SOL_IPV6, IPV6_RECVERR, + (uintptr_t)&enabled, sizeof(enabled), 0)); + assert(task_packet_recv_ex(&files[fd], bytes, sizeof(bytes), MSG_ERRQUEUE, + NULL, NULL, &info) == -LINUX_EAGAIN); + assert(task_packet_recv(&files[fd], bytes, sizeof(bytes), 0, 0, 0) == -LINUX_EHOSTUNREACH); + enabled = 1; + assert(!syscall_packet(__NR_setsockopt, fd, SOL_IPV6, IPV6_RECVERR, + (uintptr_t)&enabled, sizeof(enabled), 0)); + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, NULL); + close_packet(fd); + assert(allocations == baseline); + } + current.cap_effective = capabilities; + puts("PASS raw/ping IPv6 error queue, ID/network isolation, metadata, bounds, OOM and cleanup"); +} + static void test_raw6_creating_network(void) { struct task saved = current; @@ -286,6 +397,7 @@ static void test_raw6_creating_network(void) spaces[i]->loopback.up = true; } uint8_t quote[48] = {0x60}; + net_put_u16(quote + 4, 8); quote[6] = IPPROTO_ICMPV6; memcpy(quote + 8, &loop6, 16); memcpy(quote + 24, &loop6, 16); @@ -328,6 +440,7 @@ static void test_raw6_creating_network(void) int main(void) { current.cap_effective = 1ULL << CAP_NET_BIND_SERVICE; + test_packet6_error_queue(); test_raw6_creating_network(); test_udp6_namespace_bind(false); test_udp6_namespace_bind(true); diff --git a/tools/tests/ipv6_vector_stubs.c b/tools/tests/ipv6_vector_stubs.c index 5a63a46a..06b5d45f 100644 --- a/tools/tests/ipv6_vector_stubs.c +++ b/tools/tests/ipv6_vector_stubs.c @@ -5,11 +5,6 @@ __attribute__((noreturn)) void task_netlink_send(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_cancel_wait(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_passcred(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_pktinfo(void) { __builtin_trap(); } -__attribute__((noreturn)) void task_packet_recv(void) { __builtin_trap(); } -__attribute__((noreturn)) void task_packet_recv_ex(void) { __builtin_trap(); } -__attribute__((noreturn)) void task_packet_recv_staged(void) { __builtin_trap(); } -__attribute__((noreturn)) void task_packet_send(void) { __builtin_trap(); } -__attribute__((noreturn)) void task_packet_address_size(void) { __builtin_trap(); } __attribute__((noreturn)) void net_socket_available(void) { __builtin_trap(); } __attribute__((noreturn)) void net_socket_poll_fd(void) { __builtin_trap(); } __attribute__((noreturn)) void net_socket_recv(void) { __builtin_trap(); } diff --git a/tools/tests/ipv6_vector_test.c b/tools/tests/ipv6_vector_test.c index 194ed24e..c67857f4 100644 --- a/tools/tests/ipv6_vector_test.c +++ b/tools/tests/ipv6_vector_test.c @@ -3,6 +3,9 @@ #define IPV6_TRANSPORT_FIXTURE 1 #include "task8_inet_message_user_test.c" #include +#define sockets packet_sockets +#include "../../net/socket/packet.c" +#undef sockets static const struct in6_addr loop6={.s6_addr={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; void kernel_poll_readiness_notify(void) {} @@ -38,6 +41,20 @@ int net_ipv6_output(struct net_namespace *ns, const struct net_ipv6_path *path,u } int net_ipv6_multicast_change(struct net_namespace *ns, const struct in6_addr *address,uint32_t ifindex,int delta) { (void)ns; (void)address;(void)ifindex;(void)delta;return 0; } +bool net_interface_ready(void) { return true; } +const uint8_t *e1000_mac(void) { static const uint8_t mac[6]; return mac; } +const uint8_t *netdev_mac(uint32_t index) { (void)index; return e1000_mac(); } +int netdev_send(uint32_t index, const void *frame, uint32_t length) +{ (void)index; (void)frame; (void)length; abort(); } +int net_ipv4_send_raw_on(struct net_namespace *ns, uint32_t index, uint32_t destination, + uint32_t source, uint8_t protocol, bool hdrincl, const void *data, uint32_t length) +{ (void)ns; (void)index; (void)destination; (void)source; (void)protocol; + (void)hdrincl; (void)data; (void)length; abort(); } +void net_tcp6_error_on(struct net_namespace *ns, uint32_t index, const struct in6_addr *source, + const struct in6_addr *destination, uint16_t source_port, uint16_t destination_port, + int error, uint32_t mtu) +{ (void)ns; (void)index; (void)source; (void)destination; (void)source_port; + (void)destination_port; (void)error; (void)mtu; abort(); } int file_can_read(const struct task_file *file) { return file != NULL; } int file_can_write(const struct task_file *file) { return file != NULL; } @@ -78,6 +95,66 @@ static int64_t message_call(int fd, struct msghdr *message, uint32_t flags, bool flags, receiving, false, &result); } +/** @brief Verify real raw/ping recvmsg error metadata and swap-safe consumption. */ +static void test_packet6_error_recvmsg(void) +{ + unsigned baseline = allocations; + current.cap_effective |= 1ULL << CAP_NET_RAW; + for (unsigned variant = 0; variant < 2; ++variant) { + int fd = (int)syscall_packet(__NR_socket, AF_INET6, + (variant ? SOCK_DGRAM : SOCK_RAW) | SOCK_NONBLOCK, IPPROTO_ICMPV6, 0, 0, 0); + assert(fd >= 0); + int enabled = 1; + assert(!syscall_packet(__NR_setsockopt, fd, SOL_IPV6, IPV6_RECVERR, + (uintptr_t)&enabled, sizeof(enabled), 0)); + struct sockaddr_in6 local = {.sin6_family = AF_INET6, .sin6_addr = loop6, + .sin6_port = swap16(55303)}; + assert(!syscall_packet(__NR_bind, fd, (uintptr_t)&local, sizeof(local), 0, 0, 0)); + uint8_t quote[52] = {0x60}; + quote[6] = IPPROTO_ICMPV6; + net_put_u16(quote + 4, 12); + memcpy(quote + 8, &loop6, 16); + memcpy(quote + 24, &loop6, 16); + quote[40] = 128; + net_put_u16(quote + 44, 55303); + memcpy(quote + 48, "ping", 4); + struct sock_extended_err error = {.ee_errno = LINUX_EHOSTUNREACH, + .ee_origin = SO_EE_ORIGIN_ICMP6, .ee_type = 1, .ee_code = 3}; + struct sockaddr_storage offender = {0}; + memcpy(&offender, &local, sizeof(local)); + net_ipv6_socket_extended_error_on(NULL, 1, quote, sizeof(quote), &error, &offender); + char bytes[16] = {0}; + struct iovec vector = {.iov_base = bytes, .iov_len = sizeof(bytes)}; + union { struct cmsghdr align; unsigned char bytes[80]; } control = {0}; + struct sockaddr_in6 destination = {0}; + struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, + .msg_name = &destination, .msg_namelen = sizeof(destination), + .msg_control = control.bytes, .msg_controllen = sizeof(control.bytes)}; + blocked = (uintptr_t)bytes; + contended = true; + assert(message_call(fd, &message, MSG_ERRQUEUE, true) == KERNEL_SYSCALL_SWAP_CONTENDED); + assert(!bytes[0] && (task_packet_poll(&files[fd], 0) & POLLERR)); + contended = false; + assert(message_call(fd, &message, MSG_ERRQUEUE | MSG_PEEK, true) == 12); + assert(!memcmp(bytes, quote + 40, 12) && message.msg_flags == MSG_ERRQUEUE); + assert(message.msg_namelen == sizeof(destination) && destination.sin6_family == AF_INET6); + assert(!destination.sin6_port && !memcmp(&destination.sin6_addr, &loop6, 16)); + assert(message.msg_controllen == CMSG_SPACE(sizeof(error) + sizeof(local))); + const struct cmsghdr *cmsg = (const void *)control.bytes; + assert(cmsg->cmsg_level == SOL_IPV6 && cmsg->cmsg_type == IPV6_RECVERR); + assert(!memcmp(control.bytes + CMSG_LEN(0), &error, sizeof(error))); + assert(!memcmp(control.bytes + CMSG_LEN(sizeof(error)), &local, sizeof(local))); + assert(message_call(fd, &message, MSG_ERRQUEUE, true) == -LINUX_EAGAIN); + task_lookup_scope_cancel(¤t); + task_packet_release(&files[fd]); + files[fd].used = 0; + } + current.cap_effective &= ~(1ULL << CAP_NET_RAW); + blocked = 0; + assert(allocations == baseline); + puts("PASS raw/ping recvmsg extended errors with swap-safe probing and native ancillary data"); +} + /** @brief Verify native and mapped error controls through swap-aware recvmsg. */ static void test_udp_error_recvmsg(void) { @@ -365,6 +442,7 @@ static void test_ipv6_sendmsg_metadata(void) int main(void) { current=(struct task){.pid=92,.kind=TASK_KIND_USER,.cap_effective=1ULL<mac, netdev_mac(index), 6); } int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t index, bool up) { (void)ns; (void)index; (void)up; return 0; } +/** @brief Supply the default IPv6 policy for the interface-only netlink fixture. */ +int net_ipv6_control_get(struct net_namespace *ns, uint32_t index, + enum net_ipv6_control control, int *value) +{ (void)ns; (void)index; (void)control; *value = 0; return 0; } +/** @brief Leave protocol policy to the dedicated IPv6 core fixture. */ +int net_ipv6_control_set(struct net_namespace *ns, uint32_t index, + enum net_ipv6_control control, int value) +{ (void)ns; (void)index; (void)control; (void)value; return 0; } uint64_t time_uptime_ms(void) { return 1000; } void kernel_poll_readiness_notify(void) { } uint32_t net_ipv6_addresses(struct net_namespace *ns, struct net_ipv6_address *out, uint32_t capacity) @@ -47,6 +55,13 @@ int net_ipv6_address_update(struct net_namespace *ns, const struct net_ipv6_addr { (void)ns; (void)address; (void)remove; return 0; } int net_ipv6_route_update(struct net_namespace *ns, const struct net_ipv6_route *route, bool remove) { (void)ns; (void)route; (void)remove; return 0; } +/** @brief Model the fixture's empty IPv6 route table during nexthop changes. + * @param ns Borrowed network. @param id Changed nexthop ID. + * @param value Nullable replacement. No protocol routes are retained here. + */ +void net_ipv6_nexthop_changed(struct net_namespace *ns, uint32_t id, + const struct net_nexthop *value) +{ (void)ns; (void)id; (void)value; } void net_arp_cache_clear_on(uint32_t index) { (void)index; } static int call(unsigned command, struct ifreq *req) diff --git a/tools/tests/procfs_network_test.c b/tools/tests/procfs_network_test.c new file mode 100644 index 00000000..9343ff9c --- /dev/null +++ b/tools/tests/procfs_network_test.c @@ -0,0 +1,187 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#define main proc_directory_fixture_main +#include "procfs_directories_test.c" +#undef main +#include + +struct network_fixture { + struct net_namespace *ns; + char name[NET_IF_NAME_LEN]; + bool present; + int controls[4][NET_IPV6_CONTROL_COUNT]; +}; +static struct network_fixture networks[2] = { + {.name = "eth0", .present = true}, {.name = "eth0", .present = true} +}; + +/** @brief Select one typed network substitute by its retained identity. */ +static struct network_fixture *network_for(struct net_namespace *ns) +{ + for (unsigned i = 0; i < 2; ++i) + if (networks[i].ns == ns) return &networks[i]; + abort(); +} + +uint32_t net_interface_next(struct net_namespace *ns, uint32_t after) +{ + if (!after) return 1; + return after < 2 && network_for(ns)->present ? 2 : 0; +} + +bool net_interface_name(struct net_namespace *ns, uint32_t index, char out[NET_IF_NAME_LEN]) +{ + if (index == 1) strcpy(out, "lo"); + else if (index == 2 && network_for(ns)->present) strcpy(out, network_for(ns)->name); + else return false; + return true; +} + +uint32_t net_interface_index(struct net_namespace *ns, const char *name) +{ + if (!strcmp(name, "lo")) return 1; + struct network_fixture *network = network_for(ns); + return network->present && !strcmp(name, network->name) ? 2 : 0; +} + +/** @brief Model protocol controls while testing the real proc/VFS ownership. */ +int net_ipv6_control_get(struct net_namespace *ns, uint32_t index, + enum net_ipv6_control control, int *value) +{ + struct network_fixture *network = network_for(ns); + if (index == 2 && !network->present) return -ENODEV; + unsigned slot = index == NET_IPV6_CONF_DEFAULT ? 3 : index; + assert(slot < 4 && control < NET_IPV6_CONTROL_COUNT); + *value = network->controls[slot][control]; + return 0; +} + +int net_ipv6_control_set(struct net_namespace *ns, uint32_t index, + enum net_ipv6_control control, int value) +{ + int old; + int rc = net_ipv6_control_get(ns, index, control, &old); + if (rc) return rc; + if (value == INT32_MAX) return -EOPNOTSUPP; + unsigned slot = index == NET_IPV6_CONF_DEFAULT ? 3 : index; + network_for(ns)->controls[slot][control] = value; + return 0; +} + +/** @brief Check namespace capture, current authority, parsing and release via VFS. */ +int main(void) +{ + unsigned before = proc_allocations; + struct storage_node node; + assert(!proc_lookup("/proc/sys/net/ipv6/conf/eth0/hop_limit", &node)); + assert(node.type == RELIEFOS_FS_TYPE_FILE); + assert(proc_lookup("/proc/sys/net/ipv6/conf/missing/hop_limit", &node) == -ENOENT); + assert(proc_lookup("/proc/sys/net/ipv6/conf/eth0/unknown", &node) == -ENOENT); + uint64_t offset = 0; + struct reliefos_dir_entry entry; + bool found = false; + while (proc_readdir("/proc/sys", &offset, &entry) == 1) + if (!strcmp(entry.name, "net")) found = entry.type == RELIEFOS_FS_TYPE_DIR; + assert(found); + offset = 0; + const char *names[] = {"all", "default", "lo", "eth0"}; + for (unsigned i = 0; i < 4; ++i) { + assert(proc_readdir("/proc/sys/net/ipv6/conf", &offset, &entry) == 1); + assert(!strcmp(entry.name, names[i]) && entry.type == RELIEFOS_FS_TYPE_DIR); + } + assert(!proc_readdir("/proc/sys/net/ipv6/conf", &offset, &entry)); + + struct vfs_mount *mount = NULL; + struct vfs_namespace ns = {0}; + struct vfs_path root = {0}, path = {0}; + struct vfs_open_file *file = NULL; + assert(!proc_create_vfs_mount(&mount)); + assert(!vfs_namespace_init(&ns, mount)); + vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns, &root)); + assert(!vfs_path_lookup(&ns, &root, &root, "sys/net/ipv6/conf/eth0/hop_limit", 0, &path)); + struct reliefos_permissions permissions; + assert(!vfs_path_permissions(&path, &permissions, false) && permissions.mode == 0644); + assert(!fs_permissions_check_path(¤t, &path, FS_ACCESS_WRITE, false)); + for (int budget = 0; budget < 4; ++budget) { + unsigned baseline = proc_allocations; + proc_allocation_budget = budget; + int rc = vfs_file_open(&path, LINUX_O_RDWR, &file); + proc_allocation_budget = -1; + assert(!rc || rc == -ENOMEM); + vfs_file_close(file); + file = NULL; + assert(proc_allocations == baseline); + } + assert(!vfs_file_open(&path, LINUX_O_RDWR, &file) && file); + uint32_t written, got; + char output[32]; + const char number[] = " \t+0x2a\n"; + assert(!vfs_file_write(file, 0, number, sizeof(number) - 1, &written)); + assert(written == sizeof(number) - 1 && networks[0].controls[2][NET_IPV6_HOP_LIMIT] == 42); + assert(!vfs_file_read(file, 0, output, sizeof(output), &got)); + assert(got == 3 && !memcmp(output, "42\n", 3)); + assert(!vfs_file_read(file, 1, output, 1, &got) && got == 1 && *output == '2'); + assert(!vfs_file_write(file, 3, "bad", 3, &written) && written == 3); + const char *invalid[] = {"", " ", "0x", "08", "1x", "1 2", "2147483648", "-2147483649"}; + for (unsigned i = 0; i < sizeof(invalid) / sizeof(*invalid); ++i) { + uint32_t length = strlen(invalid[i]); + int rc = vfs_file_write(file, 0, invalid[i], length, &written); + assert(length ? rc == -EINVAL && !written : !rc && !written); + assert(networks[0].controls[2][NET_IPV6_HOP_LIMIT] == 42); + } + assert(!vfs_path_bind_remount(&root, MS_RDONLY)); + assert(vfs_file_write(file, 0, "41", 2, &written) == -EROFS && !written); + assert(!vfs_path_bind_remount(&root, 0)); + current.euid = current.fsuid = 1000; + assert(fs_permissions_check_path(¤t, &path, FS_ACCESS_WRITE, false) == -EACCES); + assert(vfs_file_write(file, 0, "41", 2, &written) == -EACCES && !written); + assert(!vfs_file_read(file, 0, output, sizeof(output), &got) && got == 3); + + struct task creator = {.euid = 1000, .cap_effective = UINT64_MAX}; + struct user_namespace *owner = NULL; + assert(!user_namespace_create(&creator, &owner)); + struct net_namespace *child = NULL; + assert(!net_namespace_create(owner, &child)); + networks[1].ns = child; + current.net_ns = child; + current.user_ns = owner; + current.cap_effective = UINT64_C(1) << CAP_NET_ADMIN; + assert(vfs_file_write(file, 0, "41", 2, &written) == -EACCES); + current.euid = current.fsuid = 0; + assert(!vfs_file_write(file, 0, "41", 2, &written)); + assert(networks[0].controls[2][NET_IPV6_HOP_LIMIT] == 41); + assert(!networks[1].controls[2][NET_IPV6_HOP_LIMIT]); + current.euid = current.fsuid = 1000; + struct vfs_open_file *child_file = NULL; + assert(!fs_permissions_check_path(¤t, &path, FS_ACCESS_WRITE, false)); + assert(!vfs_file_open(&path, LINUX_O_RDWR, &child_file) && child_file); + assert(child->references == 2); + current.net_ns = NULL; + net_namespace_put(child); + assert(!vfs_file_write(child_file, 0, "-2147483648", 11, &written)); + assert(networks[1].controls[2][NET_IPV6_HOP_LIMIT] == INT32_MIN); + current.cap_effective = 0; + assert(vfs_file_write(child_file, 0, "1", 1, &written) == -EACCES && !written); + current.user_ns = NULL; + user_namespace_put(owner); + current.euid = current.fsuid = 0; + vfs_file_close(child_file); + networks[1].ns = NULL; + + strcpy(networks[0].name, "ens0"); + assert(vfs_file_write(file, 0, "2147483647", 10, &written) == -EOPNOTSUPP && !written); + assert(!vfs_file_read(file, 0, output, sizeof(output), &got) && got == 3); + assert(!vfs_file_write(file, 0, "44", 2, &written)); + assert(networks[0].controls[2][NET_IPV6_HOP_LIMIT] == 44); + assert(proc_lookup("/proc/sys/net/ipv6/conf/eth0/hop_limit", &node) == -ENOENT); + networks[0].present = false; + assert(vfs_file_read(file, 0, output, sizeof(output), &got) == -ENODEV && !got); + assert(vfs_file_write(file, 0, "45", 2, &written) == -ENODEV && !written); + vfs_file_close(file); + vfs_path_put(&path); + vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns)); + assert(proc_allocations == before); + puts("PASS proc network controls: captures, authority, parsing, readonly, rename, removal and OOM"); + return 0; +} From 60699b310b919e25d3f943c74277cb603b1e9a21 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 14:00:32 +0800 Subject: [PATCH 80/97] fix(video): establish native VBE format before exposing fbdev --- Documentation/core-api/drivers.rst | 4 ++ .../locale/en/LC_MESSAGES/core-api/drivers.po | 3 + .../locale/ja/LC_MESSAGES/core-api/drivers.po | 3 + drivers/video/framebuffer/core.c | 9 ++- tools/test_vbe_boot_surface.py | 2 + tools/tests/vbe_boot_surface_test.c | 72 ++++++++++++++++--- 6 files changed, 82 insertions(+), 11 deletions(-) diff --git a/Documentation/core-api/drivers.rst b/Documentation/core-api/drivers.rst index 87063472..759be210 100644 --- a/Documentation/core-api/drivers.rst +++ b/Documentation/core-api/drivers.rst @@ -116,3 +116,7 @@ FAT 目录按需有界分配,长文件名按 UTF-16 wire 数据处理,不能 framebuffer 提供基本显示。DRM 的 VirtIO-GPU 后端使用现代 VirtIO PCI、 2D/VirGL 协议及 Linux VirtGPU UAPI。 未得到设备能力时不能伪造 render 节点或成功状态。 + +Bochs VBE 后端在启动初始化时将可编程的 24 位表面切换为原尺寸的 XRGB8888, +使 fbdev 首次公布的像素布局与后续模式设置保持一致。固定固件表面保留原生 +24 位布局。原启动表面与 VBE 显存的物理预留范围均保留到稀疏映射完成。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/drivers.po b/Documentation/locale/en/LC_MESSAGES/core-api/drivers.po index be63db59..e1d13cc4 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/drivers.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/drivers.po @@ -328,3 +328,6 @@ msgid "现代 VirtIO PCI 块设备,提供 ``/dev/vd*``。传输、4Kn 与根 msgstr "" "Modern VirtIO PCI block devices, exposed as ``/dev/vd*``. See :doc" ":`virtio-blk` for the transport, 4Kn, and root-device support boundaries." + +msgid "Bochs VBE 后端在启动初始化时将可编程的 24 位表面切换为原尺寸的 XRGB8888, 使 fbdev 首次公布的像素布局与后续模式设置保持一致。固定固件表面保留原生 24 位布局。原启动表面与 VBE 显存的物理预留范围均保留到稀疏映射完成。" +msgstr "During boot initialization the Bochs VBE backend changes a programmable 24-bit surface to XRGB8888 at the same dimensions, keeping the initial fbdev pixel layout consistent with subsequent mode setting. Fixed firmware surfaces retain their native 24-bit layout. Physical reservations for both the original boot surface and VBE video memory survive sparse-map construction." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/drivers.po b/Documentation/locale/ja/LC_MESSAGES/core-api/drivers.po index f63cc0fb..4a80d089 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/drivers.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/drivers.po @@ -294,3 +294,6 @@ msgid "现代 VirtIO PCI 块设备,提供 ``/dev/vd*``。传输、4Kn 与根 msgstr "" "モダン VirtIO PCI ブロックデバイスを ``/dev/vd*`` として公開します。トランスポート、4Kn、ルートデバイスの対応範囲は " ":doc:`virtio-blk` を参照してください。" + +msgid "Bochs VBE 后端在启动初始化时将可编程的 24 位表面切换为原尺寸的 XRGB8888, 使 fbdev 首次公布的像素布局与后续模式设置保持一致。固定固件表面保留原生 24 位布局。原启动表面与 VBE 显存的物理预留范围均保留到稀疏映射完成。" +msgstr "Bochs VBE バックエンドは起動時の初期化で、プログラム可能な 24 ビット表面を同じ寸法の XRGB8888 に切り替え、fbdev が最初に公開するピクセル配置を後続のモード設定と一致させます。固定ファームウェア表面はネイティブの 24 ビット配置を保持します。元の起動表面と VBE ビデオメモリの物理予約領域は、スパースマップの構築後も維持されます。" diff --git a/drivers/video/framebuffer/core.c b/drivers/video/framebuffer/core.c index dd2ed00f..b7271b5a 100644 --- a/drivers/video/framebuffer/core.c +++ b/drivers/video/framebuffer/core.c @@ -170,9 +170,11 @@ void framebuffer_capture_gop(uint64_t system_table_addr) kernel_irq_restore(irq_flags); } -/** @brief Record the boot display and select its supported framebuffer backend. +/** @brief Select the boot display and its native userspace framebuffer format. * @param boot Borrowed boot description; construction of the shared map follows. * Captured physical display ranges are mapped before the pixels are accessed. + * A programmable VBE backend adopts XRGB8888 before clients inspect fbdev. + * Fixed firmware surfaces retain their original packed pixel format. */ void framebuffer_init(const struct boot_info *boot) { @@ -211,6 +213,11 @@ void framebuffer_init(const struct boot_info *boot) } framebuffer_set_boot_limits(); (void)framebuffer_vbe_probe(); + /* fbdev clients choose their shadow conversion from the first advertised + * format. Establish VBE's native storage before exposing the device so + * their initial layout also matches later mode-setting requests. */ + if (fb.bpp == 24u && (fb.capabilities & FRAMEBUFFER_CAP_MODE_SET)) + (void)framebuffer_set_mode(fb.width, fb.height); if (fb.available) { console_info("[reliefnt] framebuffer %ux%u pitch=%u bpp=%u bytespp=%u type=%u " diff --git a/tools/test_vbe_boot_surface.py b/tools/test_vbe_boot_surface.py index be505d6f..83eda31b 100644 --- a/tools/test_vbe_boot_surface.py +++ b/tools/test_vbe_boot_surface.py @@ -14,3 +14,5 @@ "-o", binary], cwd=root, check=True) subprocess.run([binary], cwd=root, check=True, timeout=20) subprocess.run([binary, "high"], cwd=root, check=True, timeout=20) + subprocess.run([binary, "packed"], cwd=root, check=True, timeout=20) + subprocess.run([binary, "fixed"], cwd=root, check=True, timeout=20) diff --git a/tools/tests/vbe_boot_surface_test.c b/tools/tests/vbe_boot_surface_test.c index 613dca73..ad10fb38 100644 --- a/tools/tests/vbe_boot_surface_test.c +++ b/tools/tests/vbe_boot_surface_test.c @@ -13,6 +13,11 @@ #define ARENA_BYTES (128ULL * 4096) #define VBE_BASE 0x70000000ULL static uint16_t selected_register; +static uint16_t vbe_registers[16] = { + [VBE_DISPI_INDEX_ID] = VBE_DISPI_ID5, + [VBE_DISPI_INDEX_VIDEO_MEMORY_64K] = 1, +}; +static unsigned mode_writes; static uint64_t (*published_branches)[512]; static bool vbe_claimed; static struct efi_graphics_output_protocol fixture_gop; @@ -32,11 +37,27 @@ static efi_status_t __attribute__((ms_abi)) fixture_protocol(efi_handle_t handle { (void)protocol; assert(handle == fixture_handle); *interface = &fixture_gop; return 0; } /** @brief Ignore fixture logs. @param level Severity. @param format Format string. */ void console_log(enum console_log_level level, const char *format, ...) { (void)level; (void)format; } -/** @brief Select a VBE register. @param value Register index. @param port Output port. */ -void x86_64_outw(uint16_t value, uint16_t port) { (void)port; selected_register = value; } -/** @brief Return a compatible VBE ID and 64 KiB aperture. @param port Input port. @return Register value. */ +/** @brief Model VBE register selection and writes. @param value Register index or value. + * @param port Index or data port. */ +void x86_64_outw(uint16_t value, uint16_t port) +{ + if (port == VBE_DISPI_IOPORT_INDEX) { + selected_register = value; + return; + } + assert(port == VBE_DISPI_IOPORT_DATA && selected_register < 16); + ++mode_writes; + vbe_registers[selected_register] = value; + if (selected_register == VBE_DISPI_INDEX_XRES) + vbe_registers[VBE_DISPI_INDEX_VIRT_WIDTH] = value; +} +/** @brief Read one emulated VBE register. @param port Data port. @return Register value. */ uint16_t x86_64_inw(uint16_t port) -{ (void)port; return selected_register == VBE_DISPI_INDEX_ID ? VBE_DISPI_ID5 : 1; } +{ assert(port == VBE_DISPI_IOPORT_DATA && selected_register < 16); return vbe_registers[selected_register]; } +/** @brief Resolve the admitted VBE aperture without touching its pixels. + * @param physical Physical aperture address. @return Early direct-map alias. */ +void *mm_phys_to_virt(uint64_t physical) +{ assert(vbe_claimed && physical == VBE_BASE); return (void *)(uintptr_t)(RELIEFNT_KERNEL_DIRECT_MAP_BASE + physical); } /** @brief Identify the emulated VBE device. @param vendor Vendor. @param device Device. * @param out Writable PCI identity. @return Zero for the expected device. */ int pci_find_device(uint16_t vendor, uint16_t device, struct pci_device *out) @@ -104,7 +125,7 @@ uint32_t power_acpi_resource_count(void) { return 0; } bool power_acpi_resource(uint32_t i, uint64_t *p, uint64_t *n) { (void)i; (void)p; (void)n; return false; } /** @brief Exercise GOP capture, VBE probe, bootstrap and sparse-map staging. - * @param argc Argument count. @param argv Optional "high" selects an unmapped high GOP. + * @param argc Argument count. @param argv Optional high, packed or fixed scenario. * @return Zero when disjoint GOP pixels and VBE BAR have retained UC/NX leaves. */ int main(int argc, char **argv) @@ -113,6 +134,8 @@ int main(int argc, char **argv) MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0); assert(arena != MAP_FAILED); bool high = argc > 1 && !strcmp(argv[1], "high"); + bool packed = argc > 1 && !strcmp(argv[1], "packed"); + bool fixed = argc > 1 && !strcmp(argv[1], "fixed"); uint64_t gop = high ? (32ULL << 30) : ARENA + 4096; assert(paging_kernel_direct_map_range(gop, 4096) == !high); struct efi_gop_mode_info info = {.horizontal_resolution=1024, .vertical_resolution=1, @@ -125,11 +148,39 @@ int main(int argc, char **argv) assert(gop_framebuffer.available && gop_framebuffer.reservation_start == gop && gop_framebuffer.reservation_bytes == 4096); if (high) assert(!paging_kernel_direct_map(gop)); - struct boot_info no_framebuffer_tag = {0}; - framebuffer_init(&no_framebuffer_tag); - assert(fb.available && (uintptr_t)fb.pixels == RELIEFNT_KERNEL_DIRECT_MAP_BASE + gop); + struct boot_info boot_display = {0}; + if (packed || fixed) { + boot_display.framebuffer_addr = gop; + boot_display.framebuffer_width = 1024; + boot_display.framebuffer_height = 1; + boot_display.framebuffer_pitch = 3072; + boot_display.framebuffer_bpp = 24; + boot_display.framebuffer_type = MULTIBOOT2_FRAMEBUFFER_TYPE_RGB; + boot_display.framebuffer_red_field_position = 16; + boot_display.framebuffer_red_mask_size = 8; + boot_display.framebuffer_green_field_position = 8; + boot_display.framebuffer_green_mask_size = 8; + boot_display.framebuffer_blue_mask_size = 8; + } + if (fixed) vbe_registers[VBE_DISPI_INDEX_ID] = 0; + framebuffer_init(&boot_display); + assert(fb.available); + if (packed) { + assert(fb.bpp == 32 && fb.bytes_per_pixel == 4 && fb.pitch == 4096); + assert((uintptr_t)fb.pixels == RELIEFNT_KERNEL_DIRECT_MAP_BASE + VBE_BASE); + assert(vbe_registers[VBE_DISPI_INDEX_BPP] == 32 && mode_writes == 5); + } else { + assert((uintptr_t)fb.pixels == RELIEFNT_KERNEL_DIRECT_MAP_BASE + gop); + assert(fb.bpp == (fixed ? 24 : 32) && mode_writes == 0); + } + if (fixed) { + assert(fb.backend == FRAMEBUFFER_BACKEND_BOOT && fb.capabilities == 0); + assert(fb.reservation_start == gop && fb.reservation_bytes == 3072); + puts("PASS fixed firmware framebuffer retains packed 24bpp"); + return 0; + } assert(fb.reservation_start == VBE_BASE && fb.auxiliary_reservation_start == gop && - fb.auxiliary_reservation_bytes == 4096); + fb.auxiliary_reservation_bytes == (packed ? 3072u : 4096u)); struct multiboot2_mmap_entry *map = (void *)(arena + 0x8000); *map = (struct multiboot2_mmap_entry){ARENA, ARENA_BYTES, 1, 0}; struct boot_info boot = {.mmap_addr=(uintptr_t)map, .mmap_entry_count=1, .mmap_entry_size=sizeof(*map)}; @@ -147,7 +198,8 @@ int main(int argc, char **argv) assert((gop_leaf & uc_nx) == uc_nx && (vbe_leaf & uc_nx) == uc_nx); assert((gop_leaf & RELIEFNT_PHYS_ADDR_MASK) == gop); assert((vbe_leaf & RELIEFNT_PHYS_ADDR_MASK) == VBE_BASE); - puts(high ? "PASS unmapped high GOP fallback retained through VBE and UC/NX staging" : + puts(packed ? "PASS packed boot framebuffer adopts XRGB8888 before userspace with reservations retained" : + high ? "PASS unmapped high GOP fallback retained through VBE and UC/NX staging" : "PASS GOP RAM retained through VBE, bootstrap and UC/NX staging"); return 0; } From f59d67a31815e955763e88a7b57c4f26401f91e2 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 15:18:52 +0800 Subject: [PATCH 81/97] feat(fs): support block filesystem contexts for dracut boot --- .../en/LC_MESSAGES/userspace-api/abi.po | 3 + .../userspace-api/device-filesystems.po | 3 + .../ja/LC_MESSAGES/userspace-api/abi.po | 3 + .../userspace-api/device-filesystems.po | 3 + Documentation/userspace-api/abi.rst | 9 ++ .../userspace-api/device-filesystems.rst | 3 + drivers/tty/pty/keyboard.c | 7 +- kernel/syscall/fs/mount_api.c | 91 ++++++++++++++++--- tools/tests/linux_pty_test.c | 2 + tools/tests/mount_backend_test.c | 88 ++++++++++++++++++ 10 files changed, 198 insertions(+), 14 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 600e3e0c..10ba2333 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -630,3 +630,6 @@ msgstr "``timerfd_create()`` supports ``CLOCK_REALTIME``, ``CLOCK_MONOTONIC`` an msgid "``CLOCK_BOOTTIME`` 使用现有启动时间时钟,当前与单调时钟共用计时来源。 官方 systemd 的 DHCP 重传定时器通过该接口运行。" msgstr "``CLOCK_BOOTTIME`` uses the existing boot-time clock, which currently shares its time source with the monotonic clock. Official systemd DHCP retransmission timers use this interface." + +msgid "已注册的块文件系统也支持 ``fsopen``、``fsconfig``、``fsmount`` 和 ``move_mount``。 上下文持有文件系统提供者引用,CREATE 要求初始用户空间的 ``CAP_SYS_ADMIN``。 ``source`` 必须为非空设备路径,在 CREATE 时按调用者的实际 root、cwd 和目录搜索权限 解析并跟随符号链接;非块设备返回 ``ENOTBLK``。支持 ``ro``、``rw``,vfat/exfat 接受既有 ``uid``、``gid``、``umask``、``fmask`` 和 ``dmask`` 参数,ext3 接受 ``data=ordered``。只读设备拒绝可写创建,调用者可在同一上下文设置 ``ro`` 后重试。 创建或描述符安装失败保留配置,释放所有候选挂载;``fsmount`` 的独立挂载属性继续 受共享后端只读状态约束。最后一个上下文引用关闭时释放提供者引用。" +msgstr "Registered block filesystems also support ``fsopen``, ``fsconfig``, ``fsmount`` and ``move_mount``. The context retains its filesystem provider, and CREATE requires ``CAP_SYS_ADMIN`` in the initial user namespace. ``source`` must be a nonempty device path resolved at CREATE using the caller's actual root, cwd and directory-search permissions, following symbolic links. A non-block device returns ``ENOTBLK``. ``ro`` and ``rw`` are supported. vfat/exfat accept the existing ``uid``, ``gid``, ``umask``, ``fmask`` and ``dmask`` parameters, and ext3 accepts ``data=ordered``. A read-only device rejects writable creation. The caller can set ``ro`` on the same context and retry. Creation or descriptor-installation failure preserves the configuration and releases every candidate mount. Independent ``fsmount`` attributes remain subject to the shared backend's read-only state. Closing the final context reference releases the provider reference." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index c3b19df3..5dc557f3 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -371,3 +371,6 @@ msgstr "" msgid "可写控制文件在打开时检查其精确 inode 的权限,成功打开的描述符保留写入授权。 随后更改权限或调用者凭据不撤销该描述符的授权;重新打开及直接路径写入检查 当时的权限。非法配额命令返回 ``EINVAL`` 并保留原上限,只读挂载返回 ``EROFS``。" msgstr "Opening a writable control checks permissions on its exact inode; a successful descriptor retains its write authorization. Later mode or caller credential changes preserve that authorization. New opens and direct path writes check the permissions at the time of the operation. Invalid quota commands return ``EINVAL`` and preserve the existing limit; read-only mounts return ``EROFS``." + +msgid "文本虚拟终端的 ``K_XLATE`` 和 ``K_UNICODE`` 键盘模式均支持 ``Ctrl+Alt+F1`` 至 ``Ctrl+Alt+F6`` 切换,遵循既有终端交接流程。Unicode 模式保留 UTF-8 输入。" +msgstr "Text virtual terminals support switching with ``Ctrl+Alt+F1`` through ``Ctrl+Alt+F6`` in both ``K_XLATE`` and ``K_UNICODE`` keyboard modes, using the existing terminal handoff protocol. Unicode mode preserves UTF-8 input." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 422cc34b..35b8ecd8 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -559,3 +559,6 @@ msgstr "``timerfd_create()`` は ``CLOCK_REALTIME``、``CLOCK_MONOTONIC``、``CL msgid "``CLOCK_BOOTTIME`` 使用现有启动时间时钟,当前与单调时钟共用计时来源。 官方 systemd 的 DHCP 重传定时器通过该接口运行。" msgstr "``CLOCK_BOOTTIME`` は既存の起動時刻クロックを使用し、現在は単調クロックと時刻源を共有します。公式 systemd の DHCP 再送タイマーはこのインターフェースを使用します。" + +msgid "已注册的块文件系统也支持 ``fsopen``、``fsconfig``、``fsmount`` 和 ``move_mount``。 上下文持有文件系统提供者引用,CREATE 要求初始用户空间的 ``CAP_SYS_ADMIN``。 ``source`` 必须为非空设备路径,在 CREATE 时按调用者的实际 root、cwd 和目录搜索权限 解析并跟随符号链接;非块设备返回 ``ENOTBLK``。支持 ``ro``、``rw``,vfat/exfat 接受既有 ``uid``、``gid``、``umask``、``fmask`` 和 ``dmask`` 参数,ext3 接受 ``data=ordered``。只读设备拒绝可写创建,调用者可在同一上下文设置 ``ro`` 后重试。 创建或描述符安装失败保留配置,释放所有候选挂载;``fsmount`` 的独立挂载属性继续 受共享后端只读状态约束。最后一个上下文引用关闭时释放提供者引用。" +msgstr "登録済みのブロックファイルシステムも ``fsopen``、``fsconfig``、``fsmount``、``move_mount`` に対応します。コンテキストはファイルシステム提供者への参照を保持し、CREATE には初期ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要です。``source`` は空でないデバイスパスで、CREATE 時に呼び出し元の実際の root、cwd、ディレクトリ検索権限を使い、シンボリックリンクをたどって解決します。ブロックデバイス以外は ``ENOTBLK`` を返します。``ro`` と ``rw`` に対応し、vfat/exfat は既存の ``uid``、``gid``、``umask``、``fmask``、``dmask`` を、ext3 は ``data=ordered`` を受け付けます。読み取り専用デバイスへの書き込み可能な作成は拒否されます。同じコンテキストで ``ro`` を設定して再試行できます。作成や記述子登録に失敗すると設定を保持して候補マウントをすべて解放します。``fsmount`` の独立属性にも共有バックエンドの読み取り専用状態が適用されます。最後のコンテキスト参照を閉じると提供者参照を解放します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index b6278e2f..f5842677 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -328,3 +328,6 @@ msgstr "" msgid "可写控制文件在打开时检查其精确 inode 的权限,成功打开的描述符保留写入授权。 随后更改权限或调用者凭据不撤销该描述符的授权;重新打开及直接路径写入检查 当时的权限。非法配额命令返回 ``EINVAL`` 并保留原上限,只读挂载返回 ``EROFS``。" msgstr "書き込み可能な制御ファイルを開くと、対象 inode の権限が確認され、成功した記述子は書き込みの許可を保持します。その後のモードや呼び出し元の資格情報の変更でも、その許可は保持されます。再度開く操作とパスへの直接書き込みでは、その時点の権限を確認します。不正な上限コマンドは既存の上限を保持して ``EINVAL`` を返し、読み取り専用マウントでは ``EROFS`` を返します。" + +msgid "文本虚拟终端的 ``K_XLATE`` 和 ``K_UNICODE`` 键盘模式均支持 ``Ctrl+Alt+F1`` 至 ``Ctrl+Alt+F6`` 切换,遵循既有终端交接流程。Unicode 模式保留 UTF-8 输入。" +msgstr "テキスト仮想端末は ``K_XLATE`` と ``K_UNICODE`` の両キーボードモードで、既存の端末引き渡し手順に従い ``Ctrl+Alt+F1`` から ``Ctrl+Alt+F6`` による切り替えに対応します。Unicode モードでは UTF-8 入力を維持します。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 9779dcb7..1a961906 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -261,6 +261,15 @@ inode 引用释放且相关缓存回收后,设备号才能重用。 sysfs 已公开的 block、PCI 和 DRM 设备 ``uevent`` 控制由 kernel UID 0 所有,模式为 0644,权限检查沿用现有 DAC 与 kernel UID 语义。支持 ``O_TRUNC`` 的零长度截断,截断本身不发布事件。写入直接提交事件,action 与可选 UUID 的格式同网络 ``uevent``,见 :doc:`ipv6`。非法输入、只读挂载或权限检查失败均不发布事件。 +已注册的块文件系统也支持 ``fsopen``、``fsconfig``、``fsmount`` 和 ``move_mount``。 +上下文持有文件系统提供者引用,CREATE 要求初始用户空间的 ``CAP_SYS_ADMIN``。 +``source`` 必须为非空设备路径,在 CREATE 时按调用者的实际 root、cwd 和目录搜索权限 +解析并跟随符号链接;非块设备返回 ``ENOTBLK``。支持 ``ro``、``rw``,vfat/exfat +接受既有 ``uid``、``gid``、``umask``、``fmask`` 和 ``dmask`` 参数,ext3 接受 +``data=ordered``。只读设备拒绝可写创建,调用者可在同一上下文设置 ``ro`` 后重试。 +创建或描述符安装失败保留配置,释放所有候选挂载;``fsmount`` 的独立挂载属性继续 +受共享后端只读状态约束。最后一个上下文引用关闭时释放提供者引用。 + tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 1afaaa5b..e16f83fc 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -111,6 +111,9 @@ devpts 挂载选项 前台虚拟终端 ============ +文本虚拟终端的 ``K_XLATE`` 和 ``K_UNICODE`` 键盘模式均支持 ``Ctrl+Alt+F1`` +至 ``Ctrl+Alt+F6`` 切换,遵循既有终端交接流程。Unicode 模式保留 UTF-8 输入。 + 有虚拟终端时,只读的 ``/sys/class/tty/tty0/active`` 通过类链接访问 ``/sys/devices/virtual/tty/tty0/active``,读取返回当前前台终端的名称,如 ``tty1`` 加换行。前台实际切换时唤醒等待者;仅修改图形模式、仅请求切换 diff --git a/drivers/tty/pty/keyboard.c b/drivers/tty/pty/keyboard.c index da5ee29b..3c50d0a9 100644 --- a/drivers/tty/pty/keyboard.c +++ b/drivers/tty/pty/keyboard.c @@ -158,8 +158,9 @@ static void console_update_modifier(uint32_t held, uint8_t pressed) * @param pressed Non-zero for a make code, zero for a break code. * @return Nothing. * - * Keyboard translation is independent of KD display mode. OFF and raw modes - * suppress cooked shortcuts; raw streams include modifiers and supported E0 + * Keyboard translation is independent of KD display mode. Both XLATE and + * UNICODE modes support console switching. OFF and raw modes suppress cooked + * shortcuts; raw streams include modifiers and supported E0 * extensions. The deferred input consumer still forwards the physical * Ctrl+Alt+Fn chord while a graphical evdev grab is active, so this handler * can complete a VT switch without leaking printable keys to the console. @@ -189,7 +190,7 @@ void pty_console_key_event(uint8_t keycode, uint8_t pressed) /* VT switching is handled by the console controller before keyboard * translation. K_RAW/K_MEDIUMRAW must not make Ctrl+Alt+F1..F6 vanish * when an evdev client still owns the device grab. */ - if (vt_ready && (keyboard_mode == K_XLATE || + if (vt_ready && (keyboard_mode == K_XLATE || keyboard_mode == K_UNICODE || vt_graphical[pty_id - 1u]) && pressed && console_ctrl_down && console_alt_down && keycode >= 59u && keycode <= 64u) { diff --git a/kernel/syscall/fs/mount_api.c b/kernel/syscall/fs/mount_api.c index 09337e15..492b5fe0 100644 --- a/kernel/syscall/fs/mount_api.c +++ b/kernel/syscall/fs/mount_api.c @@ -1,5 +1,8 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" +#include +#include +#include #include #include #include @@ -9,6 +12,7 @@ enum syscall_fs_type { SYSCALL_FS_TMPFS, SYSCALL_FS_PROC, SYSCALL_FS_SYSFS, + SYSCALL_FS_BLOCK, }; /* A context belongs to one open-file description, including its duplicates. */ @@ -16,6 +20,7 @@ struct syscall_fs_context { struct vfs_path root; struct user_namespace *user_ns; struct net_namespace *net_ns; + struct fs_type_ref registered; char *source; uint32_t uid, gid; enum syscall_fs_type type; @@ -32,6 +37,7 @@ void syscall_fs_context_release(void *object) vfs_path_put(&context->root); user_namespace_put(context->user_ns); net_namespace_put(context->net_ns); + fs_type_put(&context->registered); kernel_free(context->source); kernel_free(context); } @@ -40,8 +46,9 @@ void syscall_fs_context_release(void *object) * @param task Calling descriptor-table owner. @param type_user User filesystem name. * @param flags Native fsopen flags. @return Descriptor or negative errno. * Captures tmpfs user ownership and sysfs network view and authority at fsopen. - * proc keeps the initial PID-view owner. sysfs admission also checks its - * network owner. Failure leaves no descriptor or namespace reference. + * proc and registered block filesystems keep the initial resource owner. + * sysfs admission also checks its network owner. A block context pins its + * registered provider until final close. Failure releases every reference. */ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t flags) { @@ -50,9 +57,14 @@ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t fl int rc = task_lookup_user_text(task, type_user, VFS_NAME_MAX + 1, false, &type); if (rc) return rc; enum syscall_fs_type filesystem = SYSCALL_FS_TMPFS; + struct fs_type_ref registered = {0}; if (!__builtin_strcmp(type.text, "proc")) filesystem = SYSCALL_FS_PROC; else if (!__builtin_strcmp(type.text, "sysfs")) filesystem = SYSCALL_FS_SYSFS; - else if (__builtin_strcmp(type.text, "tmpfs")) rc = -RELIEFOS_ENODEV; + else if (__builtin_strcmp(type.text, "tmpfs")) { + filesystem = SYSCALL_FS_BLOCK; + rc = fs_type_get(type.text, ®istered); + if (!rc && !(registered.type->flags & FS_REQUIRES_DEV)) rc = -RELIEFOS_ENODEV; + } struct user_namespace *owner = NULL; if (filesystem == SYSCALL_FS_TMPFS) owner = task->user_ns; else if (filesystem == SYSCALL_FS_SYSFS) { @@ -67,7 +79,9 @@ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t fl if (!rc) { *context = (struct syscall_fs_context){.uid = task->fsuid, .gid = task->fsgid, .type = filesystem, .user_ns = user_namespace_get(owner), + .registered = registered, .net_ns = filesystem == SYSCALL_FS_SYSFS ? net_namespace_get(task->net_ns) : NULL}; + registered = (struct fs_type_ref){0}; struct task_file *file = NULL; int fd = task_allocate_fd(task, 0, &file); if (fd < 0) rc = fd; @@ -80,6 +94,7 @@ static int64_t mount_api_open(struct task *task, uint64_t type_user, uint32_t fl } if (rc < 0) syscall_fs_context_release(context); } + fs_type_put(®istered); kernel_free(type.allocation); return rc; } @@ -160,11 +175,20 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con __builtin_memcpy(option, key.text, key_length); option[key_length] = '='; __builtin_memcpy(option + key_length + 1, value.text, value_length + 1); - rc = syscall_mount_options(task, context->user_ns, - context->type == SYSCALL_FS_PROC ? "proc" : "tmpfs", option, &mapped); + const char *filesystem = context->type == SYSCALL_FS_BLOCK ? context->registered.type->name : + context->type == SYSCALL_FS_PROC ? "proc" : "tmpfs"; + rc = syscall_mount_options(task, context->user_ns, filesystem, option, &mapped); const char *normalized = mapped ? mapped : option; - if (!rc) rc = context->type == SYSCALL_FS_PROC ? proc_validate_mount_options(normalized) : - tmpfs_validate_options(normalized); + if (!rc && context->type == SYSCALL_FS_BLOCK) { + if (!__builtin_strcmp(filesystem, "vfat") || !__builtin_strcmp(filesystem, "exfat")) { + struct fat_mount_options parsed; + rc = fat_options_parse(normalized, &parsed); + } else if (__builtin_strcmp(filesystem, "ext3") || __builtin_strcmp(normalized, "data=ordered")) + rc = -RELIEFOS_EINVAL; + } else if (!rc) { + rc = context->type == SYSCALL_FS_PROC ? proc_validate_mount_options(normalized) : + tmpfs_validate_options(normalized); + } if (rc) goto done; size_t used = __builtin_strlen(context->options); size_t extra = __builtin_strlen(normalized); @@ -181,14 +205,56 @@ static int mount_api_parameter(struct task *task, struct syscall_fs_context *con return rc; } +/** @brief Resolve a configured block source and invoke the pinned filesystem factory. + * @param ns Caller graph under execution ownership and retry-stable lookup. + * @param task Caller supplying current root, cwd and directory-search credentials. + * @param context Block context with an owned provider reference and copied source. + * @param flags Requested shared filesystem policy. + * @param out Empty output receiving one detached mount on success. + * @return Zero or negative source/type/provider/resource errno, including I/O retry. + * The resolved source path pins its objects across the factory call. Every + * failure leaves the context parameters available for another CREATE attempt. + */ +static int mount_api_block_tree(struct vfs_namespace *ns, struct task *task, + struct syscall_fs_context *context, uint64_t flags, + struct vfs_mount **out) +{ + if (!context->source || !context->source[0]) return -RELIEFOS_EINVAL; + struct vfs_lookup_result found = {0}; + int rc = resolve_kernel_object_at_flags(ns, task, LINUX_AT_FDCWD, context->source, + false, false, VFS_LOOKUP_FOLLOW, &found); + if (!rc) { + const struct storage_node *node = vfs_path_node(&found.path); + struct storage_node device; + if (node->flags & STORAGE_NODE_FLAG_RDEV) { + struct linux_stat_abi status; + rc = vfs_path_stat(&found.path, &status); + if (!rc && (status.st_mode & LINUX_S_IFMT) != LINUX_S_IFBLK) rc = -LINUX_ENOTBLK; + if (!rc) rc = devfs_lookup_rdev(LINUX_S_IFBLK, status.st_rdev, &device); + if (!rc) node = &device; + } + if (!rc && !(node->flags & STORAGE_NODE_FLAG_DEV_BLOCK)) rc = -LINUX_ENOTBLK; + if (!rc) { + struct fs_mount_request request = {.source = context->source, + .source_node = node, .options = context->options, .flags = flags, + .uid = context->uid, .gid = context->gid}; + rc = fs_type_get_tree(&context->registered, &request, out); + } + } + vfs_path_put(&found.path); + return rc; +} + /** @brief Create or reconfigure the context's filesystem transactionally. + * @param ns Caller graph supplying retry-stable block-source lookup. * @param task Borrowed caller with stable user-namespace authority. * @param context Borrowed context. @param command CREATE or RECONFIGURE. * @return Zero or negative state, option, busy or resource errno. * CREATE requires context-owner ADMIN, RECONFIGURE checks the actual backend * owner. Pending parameters are consumed only after a successful operation. */ -static int mount_api_commit(struct task *task,struct syscall_fs_context *context, uint32_t command) +static int mount_api_commit(struct vfs_namespace *ns, struct task *task, + struct syscall_fs_context *context, uint32_t command) { int rc; if (command == FSCONFIG_CMD_CREATE) { @@ -201,6 +267,8 @@ static int mount_api_commit(struct task *task,struct syscall_fs_context *context rc = proc_create_vfs_mount_options(context->options,&mount); else if (context->type == SYSCALL_FS_SYSFS) rc = sysfs_create_vfs_mount_in_net(context->net_ns,&mount); + else if (context->type == SYSCALL_FS_BLOCK) + rc = mount_api_block_tree(ns, task, context, flags, &mount); else rc = storage_new_tmpfs_mount("none", flags, context->options, context->uid, context->gid, &mount); @@ -237,12 +305,13 @@ static int mount_api_commit(struct task *task,struct syscall_fs_context *context } /** @brief Process one filesystem configuration request. + * @param ns Caller graph for resolving a registered block source at CREATE. * @param task Calling task. @param fd Context descriptor. * @param command Native fsconfig command. @param key User key or NULL. * @param value User value or NULL. @param aux Auxiliary argument, required zero. * @return Zero, negative errno or retry status, preserving state on failure. */ -static int64_t mount_api_config(struct task *task, int32_t fd, uint32_t command, +static int64_t mount_api_config(struct vfs_namespace *ns, struct task *task, int32_t fd, uint32_t command, uint64_t key, uint64_t value, int32_t aux) { struct syscall_fs_context *context; @@ -257,7 +326,7 @@ static int64_t mount_api_config(struct task *task, int32_t fd, uint32_t command, } if (command == FSCONFIG_CMD_CREATE || command == FSCONFIG_CMD_RECONFIGURE) { if (key || value) return -RELIEFOS_EINVAL; - return mount_api_commit(task,context, command); + return mount_api_commit(ns, task, context, command); } return -RELIEFOS_EOPNOTSUPP; } @@ -343,7 +412,7 @@ int64_t syscall_new_mount_control(struct vfs_namespace *ns, struct task *task, u uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4) { if (number == __NR_fsopen) return mount_api_open(task, a0, (uint32_t)a1); - if (number == __NR_fsconfig) return mount_api_config(task, (int32_t)a0, (uint32_t)a1, a2, a3, (int32_t)a4); + if (number == __NR_fsconfig) return mount_api_config(ns, task, (int32_t)a0, (uint32_t)a1, a2, a3, (int32_t)a4); if (number == __NR_fsmount) return mount_api_mount(task, (int32_t)a0, (uint32_t)a1, (uint32_t)a2); if (number == __NR_move_mount) return mount_api_move(ns, task, (int32_t)a0, a1, (int32_t)a2, a3, (uint32_t)a4); return -RELIEFOS_ENOSYS; diff --git a/tools/tests/linux_pty_test.c b/tools/tests/linux_pty_test.c index d9da4e56..3a06046d 100644 --- a/tools/tests/linux_pty_test.c +++ b/tools/tests/linux_pty_test.c @@ -453,6 +453,8 @@ int main(void) node.first_cluster == (uint32_t)last_user_pty); assert(pty_lookup_path("/dev/pts/33", &node) == 0 && node.first_cluster == (uint32_t)last_user_pty); + /* vconsole-setup selects Unicode before the console keymap is loaded. */ + assert(pty_vt_set_keyboard_mode(1, K_UNICODE) == 0); pty_console_key_event(29, 1); /* Ctrl */ pty_console_key_event(56, 1); /* Alt */ pty_console_key_event(60, 1); /* F2 */ diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 6637f75e..6c7e27b0 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -56,6 +56,8 @@ int kernel_signal_queue_task(struct task *task,int signal_number) #include "../../fs/operations.h" #include "cluster_provider_trace.h" +static void runtime_block_mount_api(const uint8_t *bytes, uint32_t sectors, const char *type); + /** @brief Model the absent audio registry in this filesystem-only fixture. * @param token Unmodelled card identity. * @return ENODEV; no card discovery or audio I/O is part of this fixture. @@ -1956,6 +1958,7 @@ static void cluster_filesystem(const char *input,const char *output,bool extende uint8_t *image=calloc(1,(size_t)bytes+512);assert(image); test_memory_bind(volume,image,(uint64_t)bytes+512); assert(fread(test_memory_bytes(volume)+512,1,(size_t)bytes,file)==(size_t)bytes && !fclose(file)); + runtime_block_mount_api(image+512, (uint32_t)((uint64_t)bytes/512), extended ? "exfat" : "vfat"); if(!extended)readonly_fat_mounts(image+512,(uint32_t)((uint64_t)bytes/512)); g_active_volume=volume;assert(!(extended ? exfat_mount() : fat32_mount())); volume->fs_ops=extended ? &storage_exfat_ops : &storage_fat_ops; @@ -2238,6 +2241,8 @@ static void ext_family(const char *input,const char *output) { load_volume(input,0); struct storage_volume *volume=&g_volumes[0]; + runtime_block_mount_api(test_memory_bytes(volume), (uint32_t)(test_memory_length(volume)/512), + volume->filesystem==STORAGE_FILESYSTEM_EXT4 ? "ext4" : "ext2"); assert(!storage_ext4_ops.mkdir(volume,"/kept")); struct storage_node created; assert(!storage_ext4_ops.create(volume,"/kept/file",0100644,1000,1000,&created)); @@ -2723,6 +2728,89 @@ static int64_t scoped_mount_call(struct vfs_namespace *ns,struct task *task,uint return rc; } +/** @brief Mount a real registered read-only block image through fsopen and move_mount. + * @param bytes Borrowed native filesystem image. @param sectors Image size in sectors. + * @param type Registered filesystem name. All descriptors, devices and mounts retire. + */ +static void runtime_block_mount_api(const uint8_t *bytes, uint32_t sectors, const char *type) +{ + static const struct block_device_operations operations={.read=readonly_fat_read}; + struct readonly_fat_image image={.bytes=bytes,.sectors=sectors}; + struct block_device_registration device={.info={.device=block_device_allocate_number(false), + .blocks=sectors,.block_size=512,.max_blocks=128,.flags=BLOCK_DEVICE_READ_ONLY, + .transport=BLOCK_TRANSPORT_USB},.operations=&operations,.context=&image}; + assert(!register_block_device(&device)); + uint32_t disk=readonly_disk_slot(device.info.device); + struct vfs_mount *mount=NULL; + struct vfs_namespace ns={0}; + struct vfs_path root={0},node={0}; + assert(!storage_new_tmpfs_mount("none",0,"",0,0,&mount)); + assert(!vfs_namespace_init(&ns,mount));vfs_mount_put(mount); + assert(!vfs_namespace_root(&ns,&root)); + struct reliefos_permissions mode={0755,0,0}; + assert(!vfs_path_create_node(&root,"target",LINUX_S_IFDIR,&mode,NULL,&node));vfs_path_put(&node); + assert(!vfs_path_create_device(&root,"source",LINUX_S_IFBLK,&mode, + storage_block_rdev(STORAGE_BLOCK_VOLUME_ID(disk,-1)),&node));vfs_path_put(&node); + assert(!vfs_path_create_node(&root,"disk",LINUX_S_IFLNK,&mode,"source",&node));vfs_path_put(&node); + assert(!vfs_path_create_device(&root,"character",LINUX_S_IFCHR,&mode,0x103,&node));vfs_path_put(&node); + struct { + char type[16],source[8],device[16],ro[4],rw[4],uid[4],value[8],unknown[16],empty[1],target[16]; + } user={"","source","/disk","ro","rw","uid","42","unknown","","/target"}; + strcpy(user.type,type); + struct task actor={.pid=913,.cap_effective=1ULL<nofile.rlim_cur=32; + vfs_path_get(&root,&actor.fs_paths.root);vfs_path_get(&root,&actor.fs_paths.cwd); + lookup_user_base=(uintptr_t)&user;lookup_user_bytes=sizeof(user); + sched_task_limits(&actor)->nofile.rlim_cur=0; + assert(scoped_mount_call(&ns,&actor,__NR_fsopen,(uintptr_t)user.type,0,0,0,0)==-EMFILE); + sched_task_limits(&actor)->nofile.rlim_cur=32; + int context=scoped_mount_call(&ns,&actor,__NR_fsopen,(uintptr_t)user.type,1,0,0,0); + assert(context>=0); + assert(scoped_mount_call(&ns,&actor,__NR_fsconfig,context,6,0,0,0)==-EINVAL); + assert(!scoped_mount_call(&ns,&actor,__NR_fsconfig,context,1,(uintptr_t)user.source,(uintptr_t)user.device,0)); + assert(scoped_mount_call(&ns,&actor,__NR_fsconfig,context,1, + (uintptr_t)user.source,(uintptr_t)user.device,0)==-EINVAL); + assert(scoped_mount_call(&ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.unknown,0,0)==-EINVAL); + if(!strcmp(type,"vfat") || !strcmp(type,"exfat")) + assert(!scoped_mount_call(&ns,&actor,__NR_fsconfig,context,1,(uintptr_t)user.uid,(uintptr_t)user.value,0)); + /* A read-only transport rejects rw; the same context can then be retried ro. */ + assert(scoped_mount_call(&ns,&actor,__NR_fsconfig,context,6,0,0,0)==-EROFS); + assert(!scoped_mount_call(&ns,&actor,__NR_fsconfig,context,0,(uintptr_t)user.ro,0,0)); + test_fail_heap_after=0; + assert(scoped_mount_call(&ns,&actor,__NR_fsconfig,context,6,0,0,0)==-ENOMEM); + test_fail_heap_after=-1; + assert(!scoped_mount_call(&ns,&actor,__NR_fsconfig,context,6,0,0,0)); + sched_task_limits(&actor)->nofile.rlim_cur=0; + assert(scoped_mount_call(&ns,&actor,__NR_fsmount,context,0,0,0,0)==-EMFILE); + sched_task_limits(&actor)->nofile.rlim_cur=32; + int fd=scoped_mount_call(&ns,&actor,__NR_fsmount,context,1,0,0,0); + assert(fd>=0); + struct task_file *file=task_file_for_fd(&actor,fd); + struct linux_statfs_abi status; + assert(!vfs_path_statfs(&file->path_ref,&status) && (status.f_flags&LINUX_ST_RDONLY)); + assert(!strcmp(file->path_ref.mount->source,"/disk")); + if(!strcmp(type,"vfat") || !strcmp(type,"exfat")) { + struct reliefos_permissions permissions; + assert(!vfs_path_permissions(&file->path_ref,&permissions,false) && permissions.uid==42); + } + assert(!scoped_mount_call(&ns,&actor,__NR_move_mount,fd,(uintptr_t)user.empty, + (uint32_t)LINUX_AT_FDCWD,(uintptr_t)user.target,4)); + task_discard_file_fd(&actor,context);task_discard_file_fd(&actor,fd); + assert(!scoped_mount_call(&ns,&actor,LINUX_SYS_UMOUNT2,(uintptr_t)user.target,0,0,0,0)); + context=scoped_mount_call(&ns,&actor,__NR_fsopen,(uintptr_t)user.type,0,0,0,0); + assert(context>=0); + strcpy(user.device,"/character"); + assert(!scoped_mount_call(&ns,&actor,__NR_fsconfig,context,1,(uintptr_t)user.source,(uintptr_t)user.device,0)); + assert(scoped_mount_call(&ns,&actor,__NR_fsconfig,context,6,0,0,0)==-ENOTBLK); + task_discard_file_fd(&actor,context); + lookup_user_base=lookup_user_bytes=0; + sched_task_fs_release(&actor);vfs_path_put(&root); + assert(!vfs_namespace_destroy(&ns)); + while(vfs_reclaim_pending())vfs_reclaim_mounts(UINT32_MAX); + assert(!unregister_block_device(&device)); + printf("PASS %s filesystem context: real block source, symlink, options, readonly, retries and lifetime\n",type); +} + /** @brief Check graph-owner authority through real mount syscall entry points. * @param ns Borrowed initial-scope graph. @param root Retained graph root. * @param fs Initial graph's writable tmpfs, used for fixture directories. From 0d5aa84daafb02b25fed2952b0123ca492996cb7 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Mon, 30 Nov 2026 19:26:34 +0800 Subject: [PATCH 82/97] feat(ipc): retain anonymous pipe inode identities --- Documentation/userspace-api/descriptors.rst | 6 + fs/vfs/mount_tree.c | 5 +- include/reliefnt/mount.h | 10 +- include/reliefnt/storage.h | 2 + include/reliefnt/syscall_internal.h | 8 + kernel/syscall/fd/open.c | 9 +- kernel/syscall/fs/stat.c | 2 +- kernel/syscall/ipc/ipc.c | 203 +++++++++++++++++++- tools/test_pipe_capacity.py | 4 +- tools/tests/descriptor_table_test.c | 13 ++ tools/tests/mount_backend_test.c | 2 + tools/tests/pipe_capacity_test.c | 119 +++++++++++- tools/tests/pipe_parallel_test.c | 3 + tools/tests/pipe_wake_test.c | 4 + tools/tests/task8_host_fixtures.json | 3 + 15 files changed, 373 insertions(+), 20 deletions(-) diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index 04719d5c..50e91fe2 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -68,6 +68,12 @@ eventfd 与 timerfd 读取 管道可读字节数 ============== +匿名管道的两个端点共享稳定的 FIFO inode。``/proc//fd/`` 显示 +``pipe:[inode]``,并允许按 inode 权限以只读、只写或读写方式重新打开。 +新打开的端点共享当前管道缓冲区,不等待另一端建立连接。保留 ``O_PATH`` +描述符时,即使所有读写端点关闭,inode 身份仍然有效;此后重新打开会建立 +空缓冲区。管道 inode 初始属于创建者的文件系统 UID 和 GID,权限为 ``0600``。 + 匿名管道和命名 FIFO 的读端、写端均支持 ``ioctl(fd, FIONREAD, int *)``, 返回当前缓冲区内的未读字节数,不消费数据、不等待新的输入。空管道返回零; 写端关闭后,读端仍报告尚未读完的数据。查询与并行管道传输使用同一数据锁。 diff --git a/fs/vfs/mount_tree.c b/fs/vfs/mount_tree.c index 681cf9fd..fbf20572 100644 --- a/fs/vfs/mount_tree.c +++ b/fs/vfs/mount_tree.c @@ -110,6 +110,9 @@ const struct storage_node *vfs_path_node(const struct vfs_path *path) {return vfs_path_valid(path) ? &path->dentry->node : NULL;} void *vfs_path_context(const struct vfs_path *path) {return vfs_path_valid(path) ? path->mount->context : NULL;} +/** @copydoc vfs_path_backend_context */ +void *vfs_path_backend_context(const struct vfs_path *path,const struct vfs_backend_ops *ops) +{return vfs_path_valid(path) && path->mount->ops==ops ? path->mount->context : NULL;} /** @copydoc vfs_path_user_namespace */ struct user_namespace *vfs_path_user_namespace(const struct vfs_path *path) @@ -265,7 +268,7 @@ int vfs_mount_new(const struct vfs_backend_ops *ops,void *context,struct module int vfs_path_anonymous(struct vfs_mount *mount,const struct storage_node *node,struct vfs_path *out) { if(!out)return -EINVAL;*out=(struct vfs_path){0}; - if(!mount || !node || node->type!=RELIEFOS_FS_TYPE_FILE)return -EINVAL; + if(!mount || !node || (node->type!=RELIEFOS_FS_TYPE_FILE && node->type!=RELIEFOS_FS_TYPE_FIFO))return -EINVAL; struct vfs_dentry *dentry=kernel_malloc(sizeof(*dentry));if(!dentry)return -ENOMEM; *dentry=(struct vfs_dentry){.parent=mount->root,.node=*node,.disconnected=true}; int rc=mount->ops->retain(mount->context,node,&dentry->backend_pin); diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index cb7ce73c..0453fa61 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -861,6 +861,12 @@ const char *vfs_path_name(const struct vfs_path *path); * @return Backend context or NULL. No ownership transfer. */ void *vfs_path_context(const struct vfs_path *path); +/** @brief Borrow a backend context only when its operations match the provider. + * @param path Retained path under execution ownership, nullable. + * @param ops Expected immutable backend operations, required. + * @return Borrowed context, or NULL for an invalid path or different provider. + */ +void *vfs_path_backend_context(const struct vfs_path *path,const struct vfs_backend_ops *ops); /** @brief Borrow the immutable filesystem authority retained by a path. * @param path Retained path, nullable, under execution ownership. * @return Borrowed user namespace; NULL represents the initial scope or an @@ -1028,9 +1034,9 @@ int vfs_path_rename(struct vfs_namespace *ns,const struct vfs_path *source, */ int vfs_path_link(struct vfs_namespace *ns,const struct vfs_path *source, const struct vfs_path *parent,const char *name); -/** @brief Retain an anonymous regular inode without inventing a directory name. +/** @brief Retain an anonymous regular or FIFO inode without inventing a directory name. * @param mount Held backend mount, detached or attached; borrowed. - * @param node Existing regular inode metadata, borrowed and retained on success. + * @param node Existing regular-file or FIFO inode metadata, borrowed and retained on success. * @param out Empty output receiving one owned mount/dentry pair. * @return Zero or negative errno without leaked pins on allocation/retain * failure. Execution transaction required; backend retain may perform I/O. diff --git a/include/reliefnt/storage.h b/include/reliefnt/storage.h index 36e91068..4906d5d1 100644 --- a/include/reliefnt/storage.h +++ b/include/reliefnt/storage.h @@ -306,6 +306,8 @@ struct storage_read_cursor { #define STORAGE_NODE_FLAG_CGROUP 0x00800000u /* Metadata-only nsfs inode. Authority to join comes from the held VFS path. */ #define STORAGE_NODE_FLAG_NSFS 0x01000000u +/* Anonymous pipe inode, whose retained backend owns its stream identity. */ +#define STORAGE_NODE_FLAG_PIPEFS 0x02000000u #define STORAGE_SYSFS_DEVICE 202u #define STORAGE_NODE_FLAG_DEV_LINK 0x00000200u /* Anonymous filesystem device numbers, also exported in proc mountinfo. */ diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index 86ea06ac..fd61cef9 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -499,6 +499,14 @@ int storage_errno(int ret); * @return Descriptor, negative errno, or KERNEL_SYSCALL_BLOCKED for an interruptible wait. */ int task_fifo_open(struct task *task, const struct storage_node *node, uint32_t flags, const char *path); +/** @brief Open an authorized anonymous pipe through its retained VFS identity. + * @param task Current descriptor owner under execution ownership. + * @param path Held anonymous-pipe inode, already access checked by the caller. + * @param flags Linux open flags, excluding O_PATH. + * @return New descriptor or negative errno. No FIFO partner rendezvous occurs. + * A metadata-only retained inode can start a new, empty pipe after last close. + */ +int task_pipe_open(struct task *task, const struct vfs_path *path, uint32_t flags); /** * @brief Cancel an unpublished FIFO endpoint on signal, exit or failed open. * @param task Task whose pending FIFO open should be released; may be NULL. diff --git a/kernel/syscall/fd/open.c b/kernel/syscall/fd/open.c index 6e9e7d95..92e08dc7 100644 --- a/kernel/syscall/fd/open.c +++ b/kernel/syscall/fd/open.c @@ -151,9 +151,12 @@ int64_t syscall_open_object(struct vfs_namespace *ns,struct task *task,int32_t d * the resolved inode so named pipes retain their rendezvous and * stream semantics on both memory and disk filesystems. */ else if(node->type==RELIEFOS_FS_TYPE_FIFO) { - rc=task_fifo_open(task,node,flags,diagnostic); - if(task->fifo_open_file)task_file_bind_path(task->fifo_open_file,&found.path); - else if(rc>=0)task_file_bind_path(task_file_for_fd(task,rc),&found.path); + if(node->flags&STORAGE_NODE_FLAG_PIPEFS)rc=task_pipe_open(task,&found.path,flags); + else { + rc=task_fifo_open(task,node,flags,diagnostic); + if(task->fifo_open_file)task_file_bind_path(task->fifo_open_file,&found.path); + else if(rc>=0)task_file_bind_path(task_file_for_fd(task,rc),&found.path); + } } else rc=open_inode_path(task,&found.path,flags,diagnostic); } if(rc >= 0)inotify_open_published(task,rc); diff --git a/kernel/syscall/fs/stat.c b/kernel/syscall/fs/stat.c index 9f5b03d7..96b04972 100644 --- a/kernel/syscall/fs/stat.c +++ b/kernel/syscall/fs/stat.c @@ -114,7 +114,7 @@ void linux_stat_fd_type(struct linux_stat_abi *out, const struct task_file *file } /* The legacy SDK labels anonymous pipes as devices. Linux get_pipe_inode() * creates S_IFIFO | 0600; it must not look like a terminal to libc/sudo. */ - if (file && (file->flags & TASK_FILE_FLAG_PIPE) && !file->inode) { + if (file && (file->flags & TASK_FILE_FLAG_PIPE) && !file->inode && !file->path_ref.mount) { out->st_mode = LINUX_S_IFIFO | 0600u; out->st_rdev = 0; } diff --git a/kernel/syscall/ipc/ipc.c b/kernel/syscall/ipc/ipc.c index 2a672e90..c9e1ed90 100644 --- a/kernel/syscall/ipc/ipc.c +++ b/kernel/syscall/ipc/ipc.c @@ -11,7 +11,12 @@ #include #include #include +#include +#include #include +#include +#include +#include #ifdef CONFIG_SWAP #include #endif @@ -32,6 +37,8 @@ struct pipe_user { static struct pipe_user *pipe_users; +struct pipe_path; + struct task_pipe { struct kernel_spinlock data_lock; uint8_t used; @@ -48,12 +55,155 @@ struct task_pipe { uint8_t *data; struct task_pipe *next; struct pipe_user *owner; + struct pipe_path *path; struct kernel_wait_queue wait_read; struct kernel_wait_queue wait_write; }; static struct task_pipe *task_pipes; +/** @brief Identity and metadata retained independently of live pipe endpoints. */ +struct pipe_path { + uint64_t inode; + struct reliefos_permissions permissions; + struct task_pipe *pipe; +}; + +static uint64_t next_pipe_inode = 1; +static const struct vfs_backend_ops pipe_path_ops; + +/** @brief Anonymous pipe mounts have no named children. */ +static int pipe_path_lookup(void *context, const struct storage_node *parent, + const char *name, struct storage_node *out) +{ + (void)context; (void)parent; (void)name; (void)out; + return -ENOENT; +} + +/** @brief Check the retained inode against its pipe-owned identity. */ +static bool pipe_path_inode(const struct pipe_path *path, const struct storage_node *node) +{ + return path && node && node->type == RELIEFOS_FS_TYPE_FIFO && + node->flags == STORAGE_NODE_FLAG_PIPEFS && node->entry_id == path->inode; +} + +/** @brief Retain only the private root and its single anonymous FIFO. */ +static int pipe_path_retain(void *context, const struct storage_node *node, void **pin) +{ + *pin = NULL; + if (node->type == RELIEFOS_FS_TYPE_DIR && !node->entry_id) return 0; + if (!pipe_path_inode(context, node)) return -ENOENT; + *pin = context; + return 0; +} + +/** @brief The mount owns the shared metadata until every path is released. */ +static void pipe_path_release(void *context, const struct storage_node *node, void *pin) +{ + (void)context; (void)node; (void)pin; +} + +/** @brief Compare identities within the same retained backend. */ +static bool pipe_path_same(void *context, const struct storage_node *left, + const struct storage_node *right) +{ + (void)context; + return left->type == right->type && left->entry_id == right->entry_id; +} + +/** @brief Free metadata after the last path and endpoint have been retired. */ +static void pipe_path_destroy(void *context) +{ + kernel_free(context); +} + +/** @brief Read or update the anonymous inode's owner and permission bits. */ +static int pipe_path_permissions(void *context, const struct vfs_path *path, + struct reliefos_permissions *value, bool write) +{ + struct pipe_path *identity = context; + if (!pipe_path_inode(identity, vfs_path_node(path))) return -ENOENT; + if (write) { + identity->permissions = *value; + identity->permissions.mode &= 07777; + } else *value = identity->permissions; + return 0; +} + +/** @brief Report stable pipefs inode and current permission metadata. */ +static int pipe_path_getattr(void *context, const struct vfs_path *path, + struct linux_stat_abi *out) +{ + struct pipe_path *identity = context; + if (!pipe_path_inode(identity, vfs_path_node(path))) return -ENOENT; + *out = (struct linux_stat_abi){ + .st_dev = 205, .st_ino = identity->inode, .st_nlink = 1, + .st_mode = LINUX_S_IFIFO | identity->permissions.mode, + .st_uid = identity->permissions.uid, .st_gid = identity->permissions.gid, + .st_blksize = 4096, + }; + return 0; +} + +/** @brief Report Linux pipefs type for the retained anonymous inode. */ +static int pipe_path_statfs(void *context, const struct storage_node *node, + struct linux_statfs_abi *out) +{ + if (!pipe_path_inode(context, node)) return -ENOENT; + *out = (struct linux_statfs_abi){.f_type = 0x50495045, .f_bsize = 4096, + .f_frsize = 4096, .f_namelen = VFS_NAME_MAX, .f_fsid = {205, 0}}; + return 0; +} + +/** @brief Render the anonymous inode as a procfs pipe link target. */ +static int pipe_path_display(void *context, const struct storage_node *node, + char *buffer, size_t capacity) +{ + struct pipe_path *identity = context; + if (!pipe_path_inode(identity, node)) return -ENOENT; + char label[sizeof("pipe:[]") + 20]; + struct text_stream text = {.buffer = label, .capacity = sizeof(label)}; + text_string(&text, "pipe:["); + text_unsigned(&text, identity->inode); + text_string(&text, "]"); + if (text.written >= capacity) return -ENAMETOOLONG; + __builtin_memcpy(buffer, label, text.written); + buffer[text.written] = 0; + return 0; +} + +static const struct vfs_backend_ops pipe_path_ops = { + .lookup = pipe_path_lookup, .retain = pipe_path_retain, .release = pipe_path_release, + .same_node = pipe_path_same, .destroy = pipe_path_destroy, + .permissions = pipe_path_permissions, .getattr = pipe_path_getattr, + .statfs = pipe_path_statfs, .display_name = pipe_path_display, +}; + +/** @brief Create the detached VFS identity for one live anonymous pipe. + * @param pipe Live pipe without a path, held by the caller. + * @param task Creator whose filesystem credentials own the new inode. + * @param out Empty output receiving one owned path. + * @return Zero or negative errno. Failure leaves pipe and output unchanged. + */ +static int pipe_path_new(struct task_pipe *pipe, const struct task *task, struct vfs_path *out) +{ + if (!next_pipe_inode) return -EOVERFLOW; + struct pipe_path *identity = kernel_malloc(sizeof(*identity)); + if (!identity) return -ENOMEM; + *identity = (struct pipe_path){.inode = next_pipe_inode++, + .permissions = {0600, task->fsuid, task->fsgid}, .pipe = pipe}; + struct storage_node root = {.type = RELIEFOS_FS_TYPE_DIR}; + struct storage_node node = {.type = RELIEFOS_FS_TYPE_FIFO, + .flags = STORAGE_NODE_FLAG_PIPEFS, .entry_id = identity->inode}; + struct vfs_mount *mount; + int rc = vfs_mount_new(&pipe_path_ops, identity, NULL, &root, &mount); + if (rc) { kernel_free(identity); return rc; } + rc = vfs_path_anonymous(mount, &node, out); + if (!rc) pipe->path = identity; + vfs_mount_put(mount); + return rc; +} + /** @brief Check Linux pipe resource-limit privilege in the current credentials. * @return True for CAP_SYS_RESOURCE or CAP_SYS_ADMIN, false without a current task. * Only the initial user namespace may override the shared pipe quota. @@ -112,6 +262,7 @@ static struct task_pipe *task_pipe_create(const struct storage_node *node, int * */ static void task_pipe_destroy(struct task_pipe *pipe) { + if (pipe->path) pipe->path->pipe = NULL; struct task_pipe **link = &task_pipes; while (*link && *link != pipe) link = &(*link)->next; if (*link) *link = pipe->next; @@ -226,23 +377,52 @@ void task_pipe_release(struct task_file *file) /** @brief Allocate one descriptor and retain its pipe endpoint on success. * @param task Owning task under execution ownership. * @param pipe_handle Live generation-checked pipe handle. - * @param write_end Nonzero for the write endpoint, zero for the read endpoint. + * @param flags Linux access and status flags for the new endpoint. + * @param path Borrowed retained anonymous pipe inode. * @return New descriptor or negative EINVAL/descriptor-allocation error. */ -static int alloc_task_pipe_fd(struct task *task, uint32_t pipe_handle, int write_end) +static int alloc_task_pipe_fd(struct task *task, uint32_t pipe_handle, uint32_t flags, + const struct vfs_path *path) { if (!task || !kernel_object_lookup(kernel_objects(), pipe_handle, KERNEL_OBJECT_PIPE)) return -RELIEFOS_EINVAL; struct task_file *file; int fd = task_allocate_fd(task, 0, &file); if (fd < 0) return fd; - file->flags = TASK_FILE_FLAG_PIPE | (write_end ? TASK_FILE_FLAG_PIPE_WRITE : 0) | - (write_end ? RELIEFOS_O_WRONLY : RELIEFOS_O_RDONLY); + file->flags = TASK_FILE_FLAG_PIPE | flags; + if ((flags & RELIEFOS_O_ACCMODE) != RELIEFOS_O_RDONLY) + file->flags |= TASK_FILE_FLAG_PIPE_WRITE; + file->fd_flags = (flags & RELIEFOS_O_CLOEXEC) ? RELIEFOS_FD_CLOEXEC : 0; file->aux = pipe_handle; + file->node = *vfs_path_node(path); + vfs_path_get(path, &file->path_ref); task_pipe_retain(file); return fd; } +/** @copydoc task_pipe_open */ +int task_pipe_open(struct task *task, const struct vfs_path *path, uint32_t flags) +{ + if (!task) return -RELIEFOS_ESRCH; + if ((flags & RELIEFOS_O_ACCMODE) == RELIEFOS_O_ACCMODE) return -RELIEFOS_EINVAL; + struct pipe_path *identity = vfs_path_backend_context(path, &pipe_path_ops); + if (!pipe_path_inode(identity, vfs_path_node(path))) return -ENXIO; + + struct task_pipe *pipe = identity->pipe; + bool created = false; + if (!pipe) { + int error = 0; + pipe = task_pipe_create(NULL, &error); + if (!pipe) return error; + identity->pipe = pipe; + pipe->path = identity; + created = true; + } + int fd = alloc_task_pipe_fd(task, pipe->handle, flags, path); + if (fd < 0 && created) task_pipe_destroy(pipe); + return fd; +} + /** @brief Count buffered bytes with the pipe data lock held. * @param pipe Live pipe protected by execution ownership and data_lock. * @return Current buffered byte count; no waits or reference changes. @@ -557,14 +737,23 @@ int syscall_ipc_pipe(uint64_t user_ptr) int error = 0; struct task_pipe *pipe = task_pipe_create(NULL, &error); if (!pipe) return error; - int read_fd = alloc_task_pipe_fd(task, pipe->handle, 0); - if (read_fd < 0) { task_pipe_destroy(pipe); return read_fd; } - int write_fd = alloc_task_pipe_fd(task, pipe->handle, 1); + struct vfs_path path = {0}; + error = pipe_path_new(pipe, task, &path); + if (error) { task_pipe_destroy(pipe); return error; } + int read_fd = alloc_task_pipe_fd(task, pipe->handle, RELIEFOS_O_RDONLY, &path); + if (read_fd < 0) { + task_pipe_destroy(pipe); + vfs_path_put(&path); + return read_fd; + } + int write_fd = alloc_task_pipe_fd(task, pipe->handle, RELIEFOS_O_WRONLY, &path); if (write_fd < 0) { /* Releasing the single endpoint also destroys the pipe. */ task_discard_file_fd(task, read_fd); + vfs_path_put(&path); return write_fd; } + vfs_path_put(&path); ((int *)(uintptr_t)user_ptr)[0] = read_fd; ((int *)(uintptr_t)user_ptr)[1] = write_fd; return 0; diff --git a/tools/test_pipe_capacity.py b/tools/test_pipe_capacity.py index e59ade6e..f2ee2584 100644 --- a/tools/test_pipe_capacity.py +++ b/tools/test_pipe_capacity.py @@ -13,7 +13,9 @@ subprocess.run(["cc", "-std=gnu11", "-Wall", "-Wextra", "-g", "-O1", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-fsanitize=address,undefined", "-Iinclude", "-Iinclude/uapi", - "tools/tests/pipe_capacity_test.c", "fs/vfs/object.c", "-o", binary], + "tools/tests/pipe_capacity_test.c", "fs/vfs/object.c", + "fs/vfs/mount_tree.c", "fs/vfs/file.c", "fs/vfs/attributes.c", + "-o", binary], cwd=root, check=True) subprocess.run([binary], check=True, timeout=20) probe = str(Path(work) / "fionread") diff --git a/tools/tests/descriptor_table_test.c b/tools/tests/descriptor_table_test.c index f03733a0..2f98d5f6 100644 --- a/tools/tests/descriptor_table_test.c +++ b/tools/tests/descriptor_table_test.c @@ -463,6 +463,8 @@ int pty_lookup_vt_path(const char *path, struct storage_node *node) int task_fifo_open(struct task *task, const struct storage_node *node, uint32_t flags, const char *path) { (void)task; (void)node; (void)flags; (void)path; abort(); } +int task_pipe_open(struct task *task, const struct vfs_path *path, uint32_t flags) +{ (void)task; (void)path; (void)flags; abort(); } int syscall_ipc_pipe(uint64_t user_ptr) { (void)user_ptr; abort(); } int syscall_ipc_pipe2(uint64_t user_ptr, uint64_t flags) { (void)user_ptr; (void)flags; abort(); } @@ -496,6 +498,17 @@ int task_udp_recv(struct task_file *file, void *data, uint32_t length, int task_udp_send(struct task_file *file, const void *data, uint32_t length, uint32_t flags, uint64_t address, uint32_t address_length) { (void)file; (void)data; (void)length; (void)flags; (void)address; (void)address_length; abort(); } +int task_udp_send_ex(struct task_file *file, const void *data, uint32_t length, + uint32_t flags, uint64_t address, uint32_t address_length, + const struct net_udp_tx_info *info) +{ (void)file; (void)data; (void)length; (void)flags; (void)address; (void)address_length; (void)info; abort(); } +struct net_namespace *task_udp_namespace(const struct task_file *file) +{ (void)file; abort(); } +uint32_t net_interface_for_ipv4(struct net_namespace *ns, uint32_t ip) +{ (void)ns; (void)ip; abort(); } +int net_interface_get_config(struct net_namespace *ns, uint32_t index, + struct reliefos_net_config *out) +{ (void)ns; (void)index; (void)out; abort(); } short net_socket_poll_fd(int32_t handle, uint32_t owner, short events) { (void)handle; (void)owner; (void)events; abort(); } uint32_t drm_prime_file_poll(const struct task_file *file, uint32_t events) diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 6c7e27b0..96bb58ff 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -297,6 +297,8 @@ int task_shm_reopen(struct task_file *file,const struct vfs_path *path) */ int task_fifo_open(struct task *task,const struct storage_node *node,uint32_t flags,const char *path) { (void)task; (void)node; (void)flags; (void)path; abort(); } +int task_pipe_open(struct task *task,const struct vfs_path *path,uint32_t flags) +{ (void)task; (void)path; (void)flags; abort(); } uint64_t input_evdev_cursor_now(void) { abort(); } uint32_t task_evdev_vt_hint(const struct task *task) { (void)task; abort(); } diff --git a/tools/tests/pipe_capacity_test.c b/tools/tests/pipe_capacity_test.c index bbefef5a..30999c67 100644 --- a/tools/tests/pipe_capacity_test.c +++ b/tools/tests/pipe_capacity_test.c @@ -3,13 +3,32 @@ #include #include #include +#include +#include #include "../../kernel/syscall/ipc/ipc.c" static struct task current; static struct task_file descriptors[640]; +static unsigned descriptor_limit = 640; +static int allocation_budget = -1; +static unsigned live_allocations; extern int64_t task_pipe_capacity(struct task_file *file, bool setting, uint32_t bytes); -void *kernel_malloc(size_t size) { return malloc(size); } -void kernel_free(void *memory) { free(memory); } +void *kernel_malloc(size_t size) +{ + if (allocation_budget == 0) return NULL; + if (allocation_budget > 0) --allocation_budget; + void *memory = malloc(size); + if (memory) ++live_allocations; + return memory; +} +void kernel_free(void *memory) +{ + if (memory) { + assert(live_allocations); + --live_allocations; + } + free(memory); +} void console_log(enum console_log_level level, const char *format, ...) { (void)level; (void)format; } void kernel_spin_init(struct kernel_spinlock *lock) { lock->state = 0; } void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) { (void)lock; *flags = 0; } @@ -23,6 +42,8 @@ uint32_t kernel_wait_queue_wake_satisfied(struct kernel_wait_queue *queue, uint3 void kernel_wait_queue_block_current(struct kernel_wait_queue *queue) { (void)queue; abort(); } void kernel_wait_queue_block_current_minimum(struct kernel_wait_queue *queue, uint32_t minimum) { (void)queue; (void)minimum; abort(); } +void vfs_lookup_cache_purge(struct vfs_mount *mount) { (void)mount; } +void user_namespace_put(struct user_namespace *ns) { (void)ns; } uint32_t sched_current_pid(void) { return 17; } int sched_signal_user_task(uint32_t pid, int signal) { (void)pid; (void)signal; return 0; } struct task *sched_current_task(void) { return ¤t; } @@ -30,7 +51,7 @@ bool user_range_writable(uint64_t address, uint64_t bytes) { return address && b int task_allocate_fd(struct task *task, int minimum, struct task_file **out) { (void)task; - for (unsigned i = minimum; i < 640; ++i) { + for (unsigned i = minimum; i < descriptor_limit; ++i) { if (descriptors[i].used) continue; descriptors[i] = (struct task_file){.used = 1}; *out = &descriptors[i]; @@ -42,13 +63,15 @@ void task_discard_file_fd(struct task *task, int fd) { (void)task; task_pipe_release(&descriptors[fd]); + vfs_path_put(&descriptors[fd].path_ref); descriptors[fd] = (struct task_file){0}; } int main(void) { kernel_objects_init(); - current.uid = 1000; + current.uid = current.fsuid = 1000; + current.fsgid = 1001; for (unsigned i = 0; i < 300; ++i) { int pair[2] = {-1, -1}; int ret = syscall_ipc_pipe((uintptr_t)pair); @@ -56,6 +79,29 @@ int main(void) assert(!ret && pair[0] == (int)i * 2 && pair[1] == (int)i * 2 + 1); } struct task_file *read_end = &descriptors[0], *write_end = &descriptors[1]; + assert(read_end->path_ref.mount && write_end->path_ref.mount); + assert(vfs_path_equal(&read_end->path_ref, &write_end->path_ref)); + struct linux_stat_abi stat; + struct linux_statfs_abi statfs; + assert(!vfs_path_stat(&read_end->path_ref, &stat)); + assert((stat.st_mode & (LINUX_S_IFMT | 07777)) == (LINUX_S_IFIFO | 0600)); + assert(stat.st_uid == 1000 && stat.st_gid == 1001 && stat.st_ino); + char label[64]; + assert(!pipe_path_display(vfs_path_context(&read_end->path_ref), + vfs_path_node(&read_end->path_ref), label, sizeof(label))); + assert(!strcmp(label, "pipe:[1]")); + assert(!vfs_path_statfs(&read_end->path_ref, &statfs) && statfs.f_type == 0x50495045); + struct reliefos_permissions permissions = {0640, 1000, 1001}; + assert(!vfs_path_permissions(&read_end->path_ref, &permissions, true)); + assert(!vfs_path_stat(&write_end->path_ref, &stat) && (stat.st_mode & 07777) == 0640); + struct vfs_path retained = {0}; + vfs_path_get(&read_end->path_ref, &retained); + int reopened = task_pipe_open(¤t, &retained, RELIEFOS_O_RDWR); + assert(reopened == 600 && vfs_path_equal(&retained, &descriptors[reopened].path_ref)); + assert(task_pipe_write(&descriptors[reopened], "p", 1) == 1); + char reopened_byte; + assert(task_pipe_read(read_end, &reopened_byte, 1) == 1 && reopened_byte == 'p'); + task_discard_file_fd(¤t, reopened); assert(task_pipe_capacity(read_end, false, 0) == 65536); assert(task_pipe_capacity(write_end, true, 5000) == 8192); assert(task_pipe_available(read_end) == 0 && task_pipe_available(write_end) == 0); @@ -89,6 +135,69 @@ int main(void) assert(task_pipe_available(read_end) == 3000); assert(task_pipe_read(read_end, result, sizeof(result)) == 3000); assert(task_pipe_available(read_end) == 0); - for (unsigned i = 0; i < 600; ++i) task_discard_file_fd(¤t, (int)i); + assert(task_pipe_write(write_end, "x", 1) == 1); + task_discard_file_fd(¤t, 0); + task_discard_file_fd(¤t, 1); + descriptor_limit = 0; + assert(task_pipe_open(¤t, &retained, RELIEFOS_O_RDWR) == -RELIEFOS_EMFILE); + assert(!((struct pipe_path *)vfs_path_context(&retained))->pipe); + descriptor_limit = 2; + assert(task_pipe_open(¤t, &retained, RELIEFOS_O_RDWR) == 0); + assert(task_pipe_available(&descriptors[0]) == 0); + assert(task_pipe_write(&descriptors[0], "y", 1) == 1); + assert(task_pipe_read(&descriptors[0], &reopened_byte, 1) == 1 && reopened_byte == 'y'); + assert(task_pipe_open(¤t, &retained, RELIEFOS_O_RDONLY | RELIEFOS_O_NONBLOCK | + RELIEFOS_O_CLOEXEC) == 1); + assert((descriptors[1].flags & RELIEFOS_O_NONBLOCK) && + (descriptors[1].fd_flags & RELIEFOS_FD_CLOEXEC)); + assert(task_pipe_open(¤t, &retained, RELIEFOS_O_WRONLY) == -RELIEFOS_EMFILE); + task_discard_file_fd(¤t, 0); + task_discard_file_fd(¤t, 1); + vfs_path_put(&retained); + descriptor_limit = 640; + for (unsigned i = 2; i < 600; ++i) task_discard_file_fd(¤t, (int)i); + unsigned baseline = live_allocations; + unsigned failed = 0, succeeded = 0; + for (int budget = 0; budget < 12; ++budget) { + int pair[2] = {-1, -1}; + allocation_budget = budget; + int rc = syscall_ipc_pipe((uintptr_t)pair); + allocation_budget = -1; + if (rc == 0) { + ++succeeded; + task_discard_file_fd(¤t, pair[0]); + task_discard_file_fd(¤t, pair[1]); + } else { + ++failed; + assert(rc == -RELIEFOS_ENOMEM); + assert(pair[0] == -1 && pair[1] == -1); + } + assert(!task_pipes && !pipe_users && live_allocations == baseline); + } + assert(failed && succeeded); + + int pair[2]; + assert(!syscall_ipc_pipe((uintptr_t)pair)); + vfs_path_get(&descriptors[pair[0]].path_ref, &retained); + task_discard_file_fd(¤t, pair[0]); + task_discard_file_fd(¤t, pair[1]); + baseline = live_allocations; + failed = succeeded = 0; + for (int budget = 0; budget < 5; ++budget) { + allocation_budget = budget; + int fd = task_pipe_open(¤t, &retained, RELIEFOS_O_RDWR); + allocation_budget = -1; + if (fd >= 0) { + ++succeeded; + task_discard_file_fd(¤t, fd); + } else { + ++failed; + assert(fd == -RELIEFOS_ENOMEM); + } + assert(!((struct pipe_path *)vfs_path_context(&retained))->pipe); + assert(!task_pipes && !pipe_users && live_allocations == baseline); + } + assert(failed && succeeded); + vfs_path_put(&retained); puts("PASS pipe resources: 300 live pipes and final-close reclamation"); } diff --git a/tools/tests/pipe_parallel_test.c b/tools/tests/pipe_parallel_test.c index a19c4431..d0fda8ed 100644 --- a/tools/tests/pipe_parallel_test.c +++ b/tools/tests/pipe_parallel_test.c @@ -43,6 +43,9 @@ struct kernel_object_table *kernel_objects(void) { return &objects; } void *kernel_object_lookup(struct kernel_object_table *table,uint32_t handle,enum kernel_object_type type) { assert(table==&objects && type==KERNEL_OBJECT_PIPE);return handle>=1 && handle<=2 ? &pipes[handle-1] : NULL; } void kernel_free(void *pointer) { free(pointer); } +/** @brief Reject VFS access in the ring-concurrency fixture. */ +const struct storage_node *vfs_path_node(const struct vfs_path *path) +{ (void)path; abort(); } struct task_file *task_file_for_fd(struct task *task,int fd) { assert(task==&owner && execution_readers && !irq);return fd>=3 && fd<7 ? &ends[(fd-3)/2][(fd-3)%2] : NULL; } bool address_space_user_page_copyable(const struct address_space *as,uint64_t page,bool writing) diff --git a/tools/tests/pipe_wake_test.c b/tools/tests/pipe_wake_test.c index d2d9c7e4..8726477b 100644 --- a/tools/tests/pipe_wake_test.c +++ b/tools/tests/pipe_wake_test.c @@ -88,6 +88,10 @@ void kernel_free(void *memory) (void)memory; } +/** @brief Reject VFS access in the wait-queue fixture. */ +const struct storage_node *vfs_path_node(const struct vfs_path *path) +{ (void)path; abort(); } + int storage_inode_put(struct storage_inode_ref *reference) { (void)reference; diff --git a/tools/tests/task8_host_fixtures.json b/tools/tests/task8_host_fixtures.json index 9706010e..036c9174 100644 --- a/tools/tests/task8_host_fixtures.json +++ b/tools/tests/task8_host_fixtures.json @@ -1579,6 +1579,9 @@ "-Iinclude/uapi", "tools/tests/task8_pipe_create_test.c", "fs/vfs/object.c", + "fs/vfs/mount_tree.c", + "fs/vfs/file.c", + "fs/vfs/attributes.c", "-o", "{tmp}/pipe-create-candidate-1" ] From e30ee2a234f01b5a9374bb41f5952edaaee49b0d Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Tue, 1 Dec 2026 01:10:35 +0800 Subject: [PATCH 83/97] fix(storage): complete native mounts and retain coherent journal cache --- Documentation/core-api/storage-completion.rst | 4 ++++ .../core-api/storage-completion.po | 3 +++ .../LC_MESSAGES/userspace-api/descriptors.po | 15 ++++++++++++ .../core-api/storage-completion.po | 3 +++ .../LC_MESSAGES/userspace-api/descriptors.po | 14 +++++++++++ fs/ext_common/journal.c | 11 +++++++-- fs/vfs/filesystem_instance.c | 12 ++++++++-- tools/tests/ext4_crash_replay_test.py | 3 ++- tools/tests/ext4_journal_test.c | 8 +++++++ tools/tests/mount_backend_test.c | 23 +++++++++++++++++++ 10 files changed, 91 insertions(+), 5 deletions(-) diff --git a/Documentation/core-api/storage-completion.rst b/Documentation/core-api/storage-completion.rst index b9a3f9f9..f8f672ae 100644 --- a/Documentation/core-api/storage-completion.rst +++ b/Documentation/core-api/storage-completion.rst @@ -63,6 +63,10 @@ ext 连续读取在单次调用内复用已验证的逻辑/物理映射值,跨 批量读取只有在全部未缓存数据能由一条原生请求覆盖时保留异步接续。超过设备上限、超过 32 块工作区或混合缓存命中/缺失的范围,临时使用同步上下文,返回后恢复调用方原状态。这样重试前的 inode/extent 缓存驱逐或低内存不会导致已完成前缀反复重读,也不依赖跨 syscall 保留调用者缓冲。真实块层回归覆盖小请求上限、缓存耗尽、脏页、错误及上下文恢复。 +解析块设备来源后,挂载的原生解析、日志恢复及根 inode 读取在同一同步上下文完成。 +这样设备的可重试读取不会被 ext4 误记为日志损坏。已提交日志完成 checkpoint 后, +仅失效覆盖已清除恢复位的超级块缓存,保留其他一致的磁盘块缓存;刷盘顺序不变。 + 不可重放的写入、刷盘、启动及 reclaim/swap 路径保持同步。错误恢复先 证明控制器/端口 STOP,再重置队列或重用 DMA;STOP 失败保留 backing、 BAR 和模块。卸载先关闭新用户并禁用/排空 IRQ,再 STOP、释放资源。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po b/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po index 0c68e040..260c97ed 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po @@ -104,6 +104,9 @@ msgstr "" "drains and discards old results; exit cancels/drains without writing " "through retired task pointers." +msgid "解析块设备来源后,挂载的原生解析、日志恢复及根 inode 读取在同一同步上下文完成。 这样设备的可重试读取不会被 ext4 误记为日志损坏。已提交日志完成 checkpoint 后, 仅失效覆盖已清除恢复位的超级块缓存,保留其他一致的磁盘块缓存;刷盘顺序不变。" +msgstr "After the block source is resolved, native mount parsing, journal recovery and the root inode read complete in the same synchronous context. This prevents ext4 from mistaking a resumable device read for journal corruption. After a committed journal is checkpointed, only the cached superblock covering the cleared recovery bit is invalidated; other coherent blocks remain cached. Flush ordering is unchanged." + msgid "" "不可重放的写入、刷盘、启动及 reclaim/swap 路径保持同步。错误恢复先 证明控制器/端口 STOP,再重置队列或重用 DMA;STOP " "失败保留 backing、 BAR 和模块。卸载先关闭新用户并禁用/排空 IRQ,再 STOP、释放资源。 没有在自旋锁或共享文件系统事务内保留 " diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index 7181e62e..b5841fce 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -132,6 +132,21 @@ msgstr "" msgid "管道可读字节数" msgstr "Readable bytes in pipes" +msgid "" +"匿名管道的两个端点共享稳定的 FIFO inode。``/proc//fd/`` 显示 " +"``pipe:[inode]``,并允许按 inode 权限以只读、只写或读写方式重新打开。 " +"新打开的端点共享当前管道缓冲区,不等待另一端建立连接。保留 ``O_PATH`` " +"描述符时,即使所有读写端点关闭,inode 身份仍然有效;此后重新打开会建立 " +"空缓冲区。管道 inode 初始属于创建者的文件系统 UID 和 GID,权限为 ``0600``。" +msgstr "" +"Both ends of an anonymous pipe share a stable FIFO inode. " +"``/proc//fd/`` displays ``pipe:[inode]`` and can be reopened for " +"reading, writing, or both according to the inode permissions. The new end " +"shares the current pipe buffer and does not wait for a peer. An ``O_PATH`` " +"descriptor keeps the inode alive after all read and write ends close; " +"reopening it then creates an empty buffer. The pipe inode starts with the " +"creator's filesystem UID and GID and mode ``0600``." + msgid "" "匿名管道和命名 FIFO 的读端、写端均支持 ``ioctl(fd, FIONREAD, int *)``, " "返回当前缓冲区内的未读字节数,不消费数据、不等待新的输入。空管道返回零; 写端关闭后,读端仍报告尚未读完的数据。查询与并行管道传输使用同一数据锁。" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po b/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po index a34b6586..10bc5183 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po @@ -95,6 +95,9 @@ msgstr "" "を維持します。保存した CPU " "バッファーポインターは再試行の識別だけに使用し、完了時のコピーは現在有効な呼び出し元メモリーだけを対象にします。要求変更時は古い結果を排出・破棄し、終了時は取り消し・排出して、終了済みタスクのポインターには書き込みません。" +msgid "解析块设备来源后,挂载的原生解析、日志恢复及根 inode 读取在同一同步上下文完成。 这样设备的可重试读取不会被 ext4 误记为日志损坏。已提交日志完成 checkpoint 后, 仅失效覆盖已清除恢复位的超级块缓存,保留其他一致的磁盘块缓存;刷盘顺序不变。" +msgstr "ブロックデバイスを解決した後、マウントの解析、ジャーナルの復旧、ルート inode の読み取りを同じ同期コンテキストで完了します。これにより、ext4 が再開可能なデバイス読み取りをジャーナルの破損と誤認しなくなります。コミット済みジャーナルのチェックポイント後は、復旧ビットをクリアしたスーパーブロックのキャッシュだけを無効化し、整合性のある他のブロックはキャッシュに保持します。フラッシュの順序は変わりません。" + msgid "" "不可重放的写入、刷盘、启动及 reclaim/swap 路径保持同步。错误恢复先 证明控制器/端口 STOP,再重置队列或重用 DMA;STOP " "失败保留 backing、 BAR 和模块。卸载先关闭新用户并禁用/排空 IRQ,再 STOP、释放资源。 没有在自旋锁或共享文件系统事务内保留 " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index c3804e1b..391d544d 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -117,6 +117,20 @@ msgstr "" msgid "管道可读字节数" msgstr "パイプの読み取り可能バイト数" +msgid "" +"匿名管道的两个端点共享稳定的 FIFO inode。``/proc//fd/`` 显示 " +"``pipe:[inode]``,并允许按 inode 权限以只读、只写或读写方式重新打开。 " +"新打开的端点共享当前管道缓冲区,不等待另一端建立连接。保留 ``O_PATH`` " +"描述符时,即使所有读写端点关闭,inode 身份仍然有效;此后重新打开会建立 " +"空缓冲区。管道 inode 初始属于创建者的文件系统 UID 和 GID,权限为 ``0600``。" +msgstr "" +"匿名パイプの両端は安定した FIFO inode を共有します。``/proc//fd/`` " +"には ``pipe:[inode]`` と表示され、inode の権限に従って読み取り専用、書き込み専用、" +"または読み書き用に開き直せます。新しい端点は既存のパイプバッファーを共有し、" +"反対側の接続を待ちません。``O_PATH`` 記述子が残っていれば、読み書きの端点がすべて閉じた後も " +"inode は有効です。その後に開き直すと空のバッファーが作られます。パイプの inode には作成者の" +"ファイルシステム UID と GID、および初期モード ``0600`` が設定されます。" + msgid "" "匿名管道和命名 FIFO 的读端、写端均支持 ``ioctl(fd, FIONREAD, int *)``, " "返回当前缓冲区内的未读字节数,不消费数据、不等待新的输入。空管道返回零; 写端关闭后,读端仍报告尚未读完的数据。查询与并行管道传输使用同一数据锁。" diff --git a/fs/ext_common/journal.c b/fs/ext_common/journal.c index 3dd621e3..69986bd5 100644 --- a/fs/ext_common/journal.c +++ b/fs/ext_common/journal.c @@ -339,6 +339,12 @@ int storage_ext4_journal_commit(struct storage_volume *v,bool wait) ret=storage_ext4_device_flush(v); if (ret<0) return ej_fail(v,ret); j->head=ej_next(j,pos); j->committed=true; ++v->ext4.journal_commits; return 0; } +/** + * @brief Flush committed metadata and retire only the stale superblock cache. + * @param v Live ext-family volume under storage execution ownership. + * @return Zero or the journal/transport error. Successful checkpointing keeps + * coherent data and metadata blocks cached; flush ordering is unchanged. + */ int storage_ext4_journal_checkpoint(struct storage_volume *v) { if (!v) return -RELIEFOS_EINVAL; @@ -354,8 +360,9 @@ int storage_ext4_journal_checkpoint(struct storage_volume *v) ret=storage_ext4_device_flush(v); if (ret<0) return ej_fail(v,ret); ret=ej_recover_flag(v,false); if (ret<0) return ej_fail(v,ret); for (uint32_t i=0;icount;i++) storage_ext4_cache_finish(v,j->images[i].block,j->images[i].after); - /* The superblock cache must reflect the final clean recovery bit. */ - storage_ext4_cache_invalidate(v); + /* Home images may still contain RECOVER. Invalidate the block covering + * the just-cleared 1024-byte superblock, not unrelated clean blocks. */ + storage_ext4_cache_invalidate_write(v,NULL,v->ext_start_lba+2,2); ++j->sequence; j->start=0; j->count=0; j->committed=false; return 0; } diff --git a/fs/vfs/filesystem_instance.c b/fs/vfs/filesystem_instance.c index b2a9b18c..085c8fb6 100644 --- a/fs/vfs/filesystem_instance.c +++ b/fs/vfs/filesystem_instance.c @@ -2,6 +2,7 @@ #include "../../block/core/storage_internal.h" #include "../operations.h" #include +#include #include /** @brief Retire a fully quiesced native codec before dropping its code owner. @@ -89,7 +90,9 @@ int storage_mount_whole_filesystem(struct storage_volume *volume,uint32_t disk,c * @param request Borrowed validated kernel operands with actual block source. * @param out Required owned detached mount output, cleared on failure. * @return Zero or negative type/unsupported/provider errno. Task context under - * execution ownership; no pathname-to-device parsing or registry callback lock. + * execution ownership; parser and detached-root reads complete synchronously + * because recovery and rollback cannot be resumed from an arbitrary block. + * The caller's retry flags are restored; no pathname or registry callback lock. */ int storage_block_get_tree(const char *name,const struct fs_mount_request *request, struct vfs_mount **out) @@ -105,10 +108,15 @@ int storage_block_get_tree(const char *name,const struct fs_mount_request *reque const struct storage_node *node=request->source_node; if(!(node->flags&STORAGE_NODE_FLAG_DEV_BLOCK))return -ENOTBLK; int32_t partition=STORAGE_BLOCK_PARTITION(node->volume_id); - int rc=storage_new_block_mount(STORAGE_BLOCK_DISK_ID(node->volume_id),(uint32_t)partition, + int rc=storage_acquire_task_io(); + if(rc)return rc; + struct storage_io_context saved; + storage_kernel_context_enter(&saved); + rc=storage_new_block_mount(STORAGE_BLOCK_DISK_ID(node->volume_id),(uint32_t)partition, name,request->flags,out); if (!rc) rc=storage_mount_fat_options(*out,request->options); if (rc && *out) { vfs_mount_put(*out); *out=NULL; } + storage_kernel_context_leave(&saved); return rc; } EXPORT_SYMBOL(storage_mount_filesystem); diff --git a/tools/tests/ext4_crash_replay_test.py b/tools/tests/ext4_crash_replay_test.py index f2e5c79d..0ac628ae 100644 --- a/tools/tests/ext4_crash_replay_test.py +++ b/tools/tests/ext4_crash_replay_test.py @@ -41,7 +41,8 @@ def main(): "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", "tools/tests/ext4_vfs_read_test.c", - "fs/tmpfs/core.c", "mm/physical/proc.c", "lib/text_utf16.c", "-o", str(vfs)]) + "fs/tmpfs/core.c", "mm/physical/proc.c", "lib/text_utf16.c", + "drivers/storage/nvme/queue.c", "-o", str(vfs)]) stage = work / "stage" stage.mkdir() (stage / "payload").write_bytes(b"original" * 1024) diff --git a/tools/tests/ext4_journal_test.c b/tools/tests/ext4_journal_test.c index 73d61e4c..0238c19c 100644 --- a/tools/tests/ext4_journal_test.c +++ b/tools/tests/ext4_journal_test.c @@ -216,7 +216,15 @@ int main(int argc,char **argv) assert(storage_ext4_alloc_blocks(&volume,target+16,3,&allocated_first,&allocated_count)==0); assert(storage_ext4_free_blocks(&volume,allocated_first,allocated_count)==0); assert(storage_ext4_journal_commit(&volume,true)==0); + /* The data block is not part of the allocation transaction. Checkpoint + * must preserve its cache hit but not the superblock's stale RECOVER bit. */ + assert(storage_ext4_cache_read(&volume,target,next)==0 && !memcmp(old,next,bs)); assert(storage_ext4_journal_checkpoint(&volume)==0); + uint64_t read_before=reads; + assert(storage_ext4_cache_read(&volume,target,next)==0 && !memcmp(old,next,bs)); + assert(reads==read_before); + assert(storage_ext4_cache_read(&volume,1024/bs,next)==0); + assert(!(ext4_get_le32(next+1024%bs+96)&4)); assert(volume.ext4.super_view.free_blocks_count==free_before); char clean[4096]; assert(snprintf(clean,sizeof(clean),"%s.clean",argv[4])<(int)sizeof(clean)); save(clean); diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 96bb58ff..1e3a2937 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -380,6 +380,9 @@ static struct block_device_registration retirement_registration={ * all disk-format, journal, cache and metadata code remains production code. */ static bool metadata_async_read_probe; static unsigned metadata_commit_reads,metadata_resumable_reads; +/* With a virtio-style resumable read, journal loading must not fall back to read-only. */ +static bool mount_journal_read_probe; +static unsigned mount_journal_reads; static bool access_stat_failure; static unsigned access_stat_failures; int __real_storage_inode_stat(const struct storage_node *node,struct linux_stat_abi *value); @@ -395,6 +398,10 @@ int __wrap_storage_read_device(const struct storage_volume *volume,uint64_t lba, ++metadata_commit_reads; if(storage_async_can_yield()){++metadata_resumable_reads;return -EAGAIN;} } + if(mount_journal_read_probe && volume->ext4.journal) { + ++mount_journal_reads; + if(storage_async_can_yield())return -EAGAIN; + } return __real_storage_read_device(volume,lba,count,buffer); } int __real_storage_cluster_write(struct storage_node *node,uint64_t offset,const void *data,uint32_t length,uint32_t *written); @@ -2781,7 +2788,18 @@ static void runtime_block_mount_api(const uint8_t *bytes, uint32_t sectors, cons test_fail_heap_after=0; assert(scoped_mount_call(&ns,&actor,__NR_fsconfig,context,6,0,0,0)==-ENOMEM); test_fail_heap_after=-1; + bool journaled=!strcmp(type,"ext4"); + if(journaled) { + mount_journal_read_probe=true; + mount_journal_reads=0; + storage_set_io_async_context(true); + } assert(!scoped_mount_call(&ns,&actor,__NR_fsconfig,context,6,0,0,0)); + if(journaled) { + assert(mount_journal_reads && storage_async_can_yield()); + mount_journal_read_probe=false; + storage_set_io_async_context(false); + } sched_task_limits(&actor)->nofile.rlim_cur=0; assert(scoped_mount_call(&ns,&actor,__NR_fsmount,context,0,0,0,0)==-EMFILE); sched_task_limits(&actor)->nofile.rlim_cur=32; @@ -2791,6 +2809,11 @@ static void runtime_block_mount_api(const uint8_t *bytes, uint32_t sectors, cons struct linux_statfs_abi status; assert(!vfs_path_statfs(&file->path_ref,&status) && (status.f_flags&LINUX_ST_RDONLY)); assert(!strcmp(file->path_ref.mount->source,"/disk")); + if(journaled) { + const struct storage_volume *mounted=vfs_path_context(&file->path_ref); + assert(mounted && !mounted->read_only_reason && mounted->ext4.journal); + puts("PASS ext4 fsconfig: no false journal corruption under resumable transport"); + } if(!strcmp(type,"vfat") || !strcmp(type,"exfat")) { struct reliefos_permissions permissions; assert(!vfs_path_permissions(&file->path_ref,&permissions,false) && permissions.uid==42); From f4880f5b02f1645ffce7c0c91f6f2a7e9ac05c89 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Tue, 1 Dec 2026 01:32:19 +0800 Subject: [PATCH 84/97] fix(block): publish partition nodes after a table reread --- .../userspace-api/device-filesystems.po | 3 + .../userspace-api/device-filesystems.po | 3 + .../userspace-api/device-filesystems.rst | 4 + block/partition/disk_io.c | 15 ++-- include/reliefnt/storage.h | 2 +- tools/tests/mount_backend_test.c | 76 +++++++++++++++++++ 6 files changed, 95 insertions(+), 8 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 5dc557f3..0b83f0ba 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -74,6 +74,9 @@ msgstr "" "filesystem survives the last public unmount, so later mounts see the same" " contents and permissions." +msgid "用户态直接写入磁盘分区表后,可以调用整盘设备的 ``BLKRRPART``。 成功时内核清除旧分区缓存并通知 VFS worker,随后在现有 devtmpfs 挂载中 创建或移除分区节点;不需要重新挂载或手动创建设备节点。" +msgstr "After writing a partition table directly to disk, userspace can issue ``BLKRRPART`` on the whole-disk device. On success, the kernel invalidates the old partition cache and notifies the VFS worker, which adds or removes partition nodes on existing devtmpfs mounts. No remount or manual device node creation is required." + msgid "" "设备默认归 root,权限为 ``0600``。``null``、``zero``、``full``、``random``、 " "``urandom``、``tty`` 和 ``ptmx`` 为 ``0666``。``fd``、``stdin``、``stdout``、 " diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index f5842677..adab9c6f 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -67,6 +67,9 @@ msgstr "" " や ``chown`` を保持し、ユーザーによる名前の削除、置換、使用を尊重します。デバイスの削除ではカーネルが保持する元の inode " "のみを削除し、空でないディレクトリは残します。メモリ不足時は公開済みノードを残し、更新を再試行待ちにします。最後の公開マウントを解除した後も内部のファイルシステムは存続し、再マウント時には元の内容と権限が見えます。" +msgid "用户态直接写入磁盘分区表后,可以调用整盘设备的 ``BLKRRPART``。 成功时内核清除旧分区缓存并通知 VFS worker,随后在现有 devtmpfs 挂载中 创建或移除分区节点;不需要重新挂载或手动创建设备节点。" +msgstr "ユーザー空間からディスクにパーティションテーブルを直接書き込んだ後は、ディスク全体のデバイスに対して ``BLKRRPART`` を実行できます。成功するとカーネルは古いパーティションキャッシュを無効化し、VFS ワーカーに通知します。ワーカーは既存の devtmpfs マウントのパーティションノードを追加または削除します。再マウントや手動でのデバイスノード作成は不要です。" + msgid "" "设备默认归 root,权限为 ``0600``。``null``、``zero``、``full``、``random``、 " "``urandom``、``tty`` 和 ``ptmx`` 为 ``0666``。``fd``、``stdin``、``stdout``、 " diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index e16f83fc..8bd6fc56 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -35,6 +35,10 @@ tmpfs 挂载,根目录归 root,权限为 ``01777``。初始命名空间组 内存不足时保留已发布节点与待重试状态。最后一个公开挂载卸载后,私有 backing 继续保留,后续挂载可看到原有内容及权限。 +用户态直接写入磁盘分区表后,可以调用整盘设备的 ``BLKRRPART``。 +成功时内核清除旧分区缓存并通知 VFS worker,随后在现有 devtmpfs 挂载中 +创建或移除分区节点;不需要重新挂载或手动创建设备节点。 + 设备默认归 root,权限为 ``0600``。``null``、``zero``、``full``、``random``、 ``urandom``、``tty`` 和 ``ptmx`` 为 ``0666``。``fd``、``stdin``、``stdout``、 ``stderr`` 使用指向 ``/proc/self/fd`` 及对应描述符的符号链接。 diff --git a/block/partition/disk_io.c b/block/partition/disk_io.c index 1699a7ec..3921e64e 100644 --- a/block/partition/disk_io.c +++ b/block/partition/disk_io.c @@ -1,4 +1,5 @@ #include "internal.h" +#include #include #include #ifdef CONFIG_SWAP @@ -616,7 +617,7 @@ static int storage_disk_block_write_owned(uint32_t disk_id, int32_t partition_in * @return Zero or negative ownership/discovery/protected-root/busy errno. * Storage execution ownership required; no namespace or module lock spans * preparation I/O. Actual volume memberships, including detached held ones, - * keep the disk busy. Cache invalidation does not transfer device ownership. + * keep the disk busy. A successful reread queues shared devtmpfs reconciliation. */ static int storage_disk_block_reread_owned(uint32_t disk_id) { @@ -638,6 +639,7 @@ static int storage_disk_block_reread_owned(uint32_t disk_id) } storage_cache_invalidate(); disk_block_cache_invalidate(disk_id); + devtmpfs_notify(); return 0; } @@ -713,12 +715,11 @@ int storage_disk_block_write(uint32_t disk_id, int32_t partition_index, block_device_put(&ref);return rc; } -/** @brief Retain the exact block/code identity for a complete disk transaction. - * @param disk_id Stable inventory identity, never a native pointer. - * @return Zero or existing validation/lookup/native errno, including EAGAIN. - * Caller holds execution ownership. The token spans every GPT/data/cache step - * and all worker exits, with no registry/module lock over native I/O. Failed - * writes never release code/backing early or resolve a reloaded device identity. +/** @brief Invalidate partition geometry and schedule node reconciliation. + * @param disk_id Stable whole-disk inventory identity. + * @return Zero or negative ownership/discovery/protected-root/busy errno. + * The exact block reference spans cache invalidation. Execution ownership + * required; no namespace or module lock spans preparation I/O. */ int storage_disk_block_reread(uint32_t disk_id) { diff --git a/include/reliefnt/storage.h b/include/reliefnt/storage.h index 4906d5d1..5f83a12b 100644 --- a/include/reliefnt/storage.h +++ b/include/reliefnt/storage.h @@ -535,7 +535,7 @@ int storage_disk_block_write(uint32_t disk_id, int32_t partition_index, * @return Zero or negative ownership/discovery/protected-root/busy errno. * Storage execution ownership required; no namespace or module lock spans * preparation I/O. Actual volume memberships, including detached held ones, - * keep the disk busy. Cache invalidation does not transfer device ownership. + * keep the disk busy. A successful reread queues shared devtmpfs reconciliation. */ int storage_disk_block_reread(uint32_t disk_id); /** diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 1e3a2937..343a2e7f 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -3805,6 +3805,81 @@ static void devtmpfs_device_lifecycle(struct vfs_namespace *ns,const struct vfs_ assert(!devtmpfs_refresh()); puts("PASS devtmpfs lifecycle: hotplug, stable metadata, snapshot OOM retry, user deletion and replacement"); } +#define REREAD_FIXTURE_SECTORS 128u + +/** @brief Read registered memory-disk sectors without using the host's devices. + * @param media Borrowed fixed-size disk image. @param first First sector. + * @param count Number of sectors. @param out Writable sector buffer. + * @return Zero after a bounded copy. + */ +static int reread_fixture_read(void *media,uint64_t first,uint32_t count,void *out) +{ + assert(first+count<=REREAD_FIXTURE_SECTORS); + memcpy(out,(uint8_t *)media+first*512,count*512); + return 0; +} + +/** @brief Write registered memory-disk sectors through the raw block path. + * @param media Borrowed fixed-size disk image. @param first First sector. + * @param count Number of sectors. @param in Readable sector data. + * @return Zero after a bounded copy. + */ +static int reread_fixture_write(void *media,uint64_t first,uint32_t count,const void *in) +{ + assert(first+count<=REREAD_FIXTURE_SECTORS); + memcpy((uint8_t *)media+first*512,in,count*512); + return 0; +} + +/** @brief Publish a new GPT partition on an existing devtmpfs after a reread. + * @param devices Existing mounted devtmpfs root, not a fresh snapshot. + */ +static void devtmpfs_block_reread(const struct vfs_path *devices) +{ + static const struct block_device_operations ops={.read=reread_fixture_read,.write=reread_fixture_write}; + uint8_t *media=calloc(REREAD_FIXTURE_SECTORS,512);assert(media); + struct block_device_registration device={.info={ + .device=block_device_allocate_number(false),.blocks=REREAD_FIXTURE_SECTORS, + .block_size=512,.max_blocks=32,.flags=BLOCK_DEVICE_WRITE_THROUGH, + .transport=BLOCK_TRANSPORT_USB},.operations=&ops,.context=media}; + assert(!register_block_device(&device)); + uint32_t disk=readonly_disk_slot(device.info.device),done; + char name[64]; + assert(!storage_disk_device_name(disk,0,name,sizeof(name))); + assert(!devtmpfs_refresh() && !devtmpfs_pending()); + struct vfs_path node={0}; + assert(vfs_path_lookup_child(devices,name+5,&node)==-ENOENT); + + /* Userspace writes a GPT to the raw disk, not via the native GPT editor. */ + uint8_t gpt[2][512]={0}; + const struct gpt_entry entry={.type_guid={1},.unique_guid={2},.first_lba=34,.last_lba=63}; + struct gpt_header header={.signature=0x5452415020494645ULL,.revision=0x00010000, + .header_size=sizeof(header),.current_lba=1,.backup_lba=127, + .first_usable_lba=34,.last_usable_lba=94,.disk_guid={3}, + .partition_entries_lba=2,.partition_entry_count=1,.partition_entry_size=sizeof(entry), + .partition_entries_crc32=storage_crc32(&entry,sizeof(entry))}; + header.header_crc32=storage_crc32(&header,sizeof(header)); + memcpy(gpt[0],&header,sizeof(header)); + memcpy(gpt[1],&entry,sizeof(entry)); + assert(!storage_disk_block_write(disk,-1,512,gpt,sizeof(gpt),&done) && done==sizeof(gpt)); + assert(!storage_disk_block_reread(disk)); + assert(!devtmpfs_refresh()); + assert(!vfs_path_lookup_child(devices,name+5,&node)); + struct linux_stat_abi stat; + assert(!vfs_path_stat(&node,&stat) && stat.st_mode==(LINUX_S_IFBLK|0600)); + assert(stat.st_rdev==storage_block_rdev(STORAGE_BLOCK_VOLUME_ID(disk,0))); + vfs_path_put(&node); + + /* A second reread must retire the stale node even while the disk remains. */ + memset(gpt,0,sizeof(gpt)); + assert(!storage_disk_block_write(disk,-1,512,gpt,sizeof(gpt),&done) && done==sizeof(gpt)); + assert(!storage_disk_block_reread(disk) && !devtmpfs_refresh()); + assert(vfs_path_lookup_child(devices,name+5,&node)==-ENOENT); + assert(!unregister_block_device(&device) && !devtmpfs_refresh()); + free(media); + puts("PASS GPT reread: existing devtmpfs publishes and retires raw-written partition nodes"); +} + /* udev needs real writable inodes, shared across independent devtmpfs mounts. */ static void devtmpfs_mount_syscalls(struct vfs_namespace *ns,const struct vfs_path *root,struct tmpfs_super *fs) { @@ -3847,6 +3922,7 @@ static void devtmpfs_mount_syscalls(struct vfs_namespace *ns,const struct vfs_pa assert(!vfs_path_new_file(&one,"udev-data",&mode,&node)); vfs_path_put(&node); devtmpfs_device_lifecycle(ns,root); + devtmpfs_block_reread(&one); assert(!vfs_mount_unmount(ns,&one));vfs_path_put(&one); assert(!vfs_path_lookup(ns,root,root,"/devtmp-two/udev-data",0,&node)); vfs_path_put(&node); From 1f9f942ad9b0d86eacf8c789dd3c703c833a7c77 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Tue, 1 Dec 2026 06:55:01 +0800 Subject: [PATCH 85/97] perf(ext4): reduce journal I/O for metadata-heavy writes --- Documentation/core-api/storage-completion.rst | 7 +- .../core-api/storage-completion.po | 4 +- .../core-api/storage-completion.po | 4 +- fs/ext_common/internal.h | 9 +- fs/ext_common/journal.c | 181 ++++++++++++++---- tools/tests/ext4_journal_test.c | 41 +++- 6 files changed, 197 insertions(+), 49 deletions(-) diff --git a/Documentation/core-api/storage-completion.rst b/Documentation/core-api/storage-completion.rst index f8f672ae..17dcd0e5 100644 --- a/Documentation/core-api/storage-completion.rst +++ b/Documentation/core-api/storage-completion.rst @@ -64,8 +64,11 @@ ext 连续读取在单次调用内复用已验证的逻辑/物理映射值,跨 批量读取只有在全部未缓存数据能由一条原生请求覆盖时保留异步接续。超过设备上限、超过 32 块工作区或混合缓存命中/缺失的范围,临时使用同步上下文,返回后恢复调用方原状态。这样重试前的 inode/extent 缓存驱逐或低内存不会导致已完成前缀反复重读,也不依赖跨 syscall 保留调用者缓冲。真实块层回归覆盖小请求上限、缓存耗尽、脏页、错误及上下文恢复。 解析块设备来源后,挂载的原生解析、日志恢复及根 inode 读取在同一同步上下文完成。 -这样设备的可重试读取不会被 ext4 误记为日志损坏。已提交日志完成 checkpoint 后, -仅失效覆盖已清除恢复位的超级块缓存,保留其他一致的磁盘块缓存;刷盘顺序不变。 +这样设备的可重试读取不会被 ext4 误记为日志损坏。ext4 在连续元数据事务之间保留 +超级块恢复位,在显式同步或卸载时才清除健康空日志的恢复位,避免每次小写入都更新 +超级块并额外刷盘。连续日志块按最多 8 块提交,在 extent 或日志环边界拆分。 +数据与日志内容仍先于提交记录持久化,元数据仍先于清空日志持久化。恢复位改变时 +仅失效重叠的超级块缓存,一致的其他缓存不变。 不可重放的写入、刷盘、启动及 reclaim/swap 路径保持同步。错误恢复先 证明控制器/端口 STOP,再重置队列或重用 DMA;STOP 失败保留 backing、 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po b/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po index 260c97ed..c176ba62 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po @@ -104,8 +104,8 @@ msgstr "" "drains and discards old results; exit cancels/drains without writing " "through retired task pointers." -msgid "解析块设备来源后,挂载的原生解析、日志恢复及根 inode 读取在同一同步上下文完成。 这样设备的可重试读取不会被 ext4 误记为日志损坏。已提交日志完成 checkpoint 后, 仅失效覆盖已清除恢复位的超级块缓存,保留其他一致的磁盘块缓存;刷盘顺序不变。" -msgstr "After the block source is resolved, native mount parsing, journal recovery and the root inode read complete in the same synchronous context. This prevents ext4 from mistaking a resumable device read for journal corruption. After a committed journal is checkpointed, only the cached superblock covering the cleared recovery bit is invalidated; other coherent blocks remain cached. Flush ordering is unchanged." +msgid "解析块设备来源后,挂载的原生解析、日志恢复及根 inode 读取在同一同步上下文完成。 这样设备的可重试读取不会被 ext4 误记为日志损坏。ext4 在连续元数据事务之间保留 超级块恢复位,在显式同步或卸载时才清除健康空日志的恢复位,避免每次小写入都更新 超级块并额外刷盘。连续日志块按最多 8 块提交,在 extent 或日志环边界拆分。 数据与日志内容仍先于提交记录持久化,元数据仍先于清空日志持久化。恢复位改变时 仅失效重叠的超级块缓存,一致的其他缓存不变。" +msgstr "After resolving the block source, native mount parsing, journal recovery and the root inode read share one synchronous context so ext4 does not mistake resumable reads for corruption. Ext4 keeps the superblock recovery bit set between successive metadata transactions and clears it for a healthy, empty log on explicit synchronization or unmount. This avoids rewriting the superblock and flushing on each small write. Contiguous log blocks are submitted in batches of up to eight and split at extent or ring boundaries. File data and log contents still reach disk before the commit record, and home metadata reaches disk before retiring the log. Changing the recovery bit invalidates only the overlapping cached superblock, leaving other coherent blocks cached." msgid "" "不可重放的写入、刷盘、启动及 reclaim/swap 路径保持同步。错误恢复先 证明控制器/端口 STOP,再重置队列或重用 DMA;STOP " diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po b/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po index 10bc5183..5c765012 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po @@ -95,8 +95,8 @@ msgstr "" "を維持します。保存した CPU " "バッファーポインターは再試行の識別だけに使用し、完了時のコピーは現在有効な呼び出し元メモリーだけを対象にします。要求変更時は古い結果を排出・破棄し、終了時は取り消し・排出して、終了済みタスクのポインターには書き込みません。" -msgid "解析块设备来源后,挂载的原生解析、日志恢复及根 inode 读取在同一同步上下文完成。 这样设备的可重试读取不会被 ext4 误记为日志损坏。已提交日志完成 checkpoint 后, 仅失效覆盖已清除恢复位的超级块缓存,保留其他一致的磁盘块缓存;刷盘顺序不变。" -msgstr "ブロックデバイスを解決した後、マウントの解析、ジャーナルの復旧、ルート inode の読み取りを同じ同期コンテキストで完了します。これにより、ext4 が再開可能なデバイス読み取りをジャーナルの破損と誤認しなくなります。コミット済みジャーナルのチェックポイント後は、復旧ビットをクリアしたスーパーブロックのキャッシュだけを無効化し、整合性のある他のブロックはキャッシュに保持します。フラッシュの順序は変わりません。" +msgid "解析块设备来源后,挂载的原生解析、日志恢复及根 inode 读取在同一同步上下文完成。 这样设备的可重试读取不会被 ext4 误记为日志损坏。ext4 在连续元数据事务之间保留 超级块恢复位,在显式同步或卸载时才清除健康空日志的恢复位,避免每次小写入都更新 超级块并额外刷盘。连续日志块按最多 8 块提交,在 extent 或日志环边界拆分。 数据与日志内容仍先于提交记录持久化,元数据仍先于清空日志持久化。恢复位改变时 仅失效重叠的超级块缓存,一致的其他缓存不变。" +msgstr "ブロックデバイス解決後、マウント時の解析、ジャーナルの復旧、ルート inode の読み取りを同じ同期コンテキストで行い、再試行可能な読み取りを ext4 が破損と誤認するのを防ぎます。連続するメタデータトランザクション間ではスーパーブロックの復旧ビットを維持し、明示的な同期またはアンマウントで正常かつ空のログの復旧ビットを消去します。これにより小さな書き込みごとのスーパーブロックの更新と追加のフラッシュを省きます。連続するログブロックは最大 8 ブロックずつ送信し、extent またはリングの境界で分割します。データとログはコミットレコードより先に、本来の位置のメタデータはログの消去より先に永続化します。復旧ビットの変更時は、重なるスーパーブロックのキャッシュだけを無効化します。" msgid "" "不可重放的写入、刷盘、启动及 reclaim/swap 路径保持同步。错误恢复先 证明控制器/端口 STOP,再重置队列或重用 DMA;STOP " diff --git a/fs/ext_common/internal.h b/fs/ext_common/internal.h index 15204aae..f8364108 100644 --- a/fs/ext_common/internal.h +++ b/fs/ext_common/internal.h @@ -27,13 +27,20 @@ int storage_ext4_journal_open(struct storage_volume *); * span this call. Admission latches storage mutation before any old-journal * read or write: a resumable read must not be mistaken for journal corruption. * The latch stays set on failure; native metadata is not replayed after yield. + * Checkpoint the prior transaction without clearing the live recovery flag. */ int storage_ext4_journal_start(struct storage_volume *v, uint32_t credits, struct storage_ext4_handle *h); int storage_ext4_journal_dirty(struct storage_ext4_handle *, uint64_t); int storage_ext4_journal_stop(struct storage_ext4_handle *); void storage_ext4_journal_abort(struct storage_ext4_handle *, int); int storage_ext4_journal_commit(struct storage_volume *, bool); -int storage_ext4_journal_checkpoint(struct storage_volume *); +/** + * @brief Checkpoint committed metadata and mark a healthy empty journal clean. + * @param v Live ext-family volume under storage execution ownership. + * @return Zero or the journal/transport error. Explicit synchronization may + * clear RECOVER only after the home metadata and empty log are durable. + */ +int storage_ext4_journal_checkpoint(struct storage_volume *v); int storage_ext4_journal_replay(struct storage_volume *); void storage_ext4_journal_close(struct storage_volume *); /* Cache integration: capture before exposing writable bytes, publish after diff --git a/fs/ext_common/journal.c b/fs/ext_common/journal.c index 69986bd5..5e52c519 100644 --- a/fs/ext_common/journal.c +++ b/fs/ext_common/journal.c @@ -9,6 +9,10 @@ #define EJ_CSUM2 8u #define EJ_CSUM3 16u #define EJ_REVOKES 512u +#define EJ_BATCH_BLOCKS 8u + +/* CPU-only staging; the storage execution lock serializes all journal I/O. */ +static uint8_t ej_payload[EJ_BATCH_BLOCKS * EXT4_MAX_BLOCK_SIZE]; struct ext4_journal_image { uint64_t block; @@ -56,26 +60,81 @@ static uint32_t ej_zero_csum(uint32_t seed, uint8_t *raw, uint32_t n, uint32_t o uint32_t saved=ej_be32(raw+off); ej_put32(raw+off,0); uint32_t crc=storage_ext4_crc32c(seed,raw,n); ej_put32(raw+off,saved); return crc; } -static int ej_io(struct storage_volume *v,uint64_t block,void *data,bool write) +/** + * @brief Transfer a validated contiguous journal or home-block range. + * @param v Mounted ext volume under storage execution ownership. + * @param block First filesystem block. @param count Nonzero number of blocks. + * @param data Caller buffer covering count filesystem blocks. + * @param write True to write, false to read. + * @return Zero or negative bounds/transport errno. The transport owns DMA. + */ +static int ej_io(struct storage_volume *v,uint64_t block,uint32_t count,void *data,bool write) { uint32_t sectors=v->ext4.block_size/SECTOR_SIZE; - if (!sectors || block>=v->ext4.blocks_count || block>UINT64_MAX/sectors) + if (!sectors || !count || block>=v->ext4.blocks_count || + count>v->ext4.blocks_count-block || block>UINT64_MAX/sectors || + count>UINT32_MAX/sectors) return -RELIEFOS_EIO; uint64_t offset=block*sectors; - if (offset>v->ext_sector_count || sectors>v->ext_sector_count-offset || + uint32_t transfer=count*sectors; + if (offset>v->ext_sector_count || transfer>v->ext_sector_count-offset || v->ext_start_lba>UINT64_MAX-offset) return -RELIEFOS_EIO; - return write ? storage_write_device(v,v->ext_start_lba+offset,sectors,data) : - storage_read_device(v,v->ext_start_lba+offset,sectors,data); + return write ? storage_write_device(v,v->ext_start_lba+offset,transfer,data) : + storage_read_device(v,v->ext_start_lba+offset,transfer,data); } -static int ej_log_io(struct storage_volume *v,uint32_t logical,void *data,bool write) + +/** + * @brief Resolve a log slot to the journal inode's valid on-disk block run. + * @param v Live ext-family volume with an open journal. + * @param logical Journal block index, including zero for the journal superblock. + * @param map Required destination for the mapped physical run. + * @return Zero or negative mapping/format errno; holes and unwritten runs fail. + */ +static int ej_log_map(struct storage_volume *v,uint32_t logical,struct storage_ext4_map_result *map) { - struct storage_ext4_map_result map; struct storage_ext4_journal *j=v->ext4.journal; if ((uint64_t)logical*v->ext4.block_size>=j->inode.size) return -RELIEFOS_EIO; - int ret=storage_ext4_map_block(v,v->ext4.super_view.journal_inum,&j->inode,logical,false,&map); + int ret=storage_ext4_map_block(v,v->ext4.super_view.journal_inum,&j->inode,logical,false,map); if (ret<0) return ret; - if (map.hole || map.unwritten) return -RELIEFOS_EIO; - return ej_io(v,map.physical,data,write); + return (map->hole || map->unwritten || !map->length) ? -RELIEFOS_EIO : 0; +} + +/** + * @brief Transfer a single mapped journal block without touching home metadata. + * @param v Live ext-family volume under storage execution ownership. + * @param logical Journal inode block index. @param data One filesystem block. + * @param write True to write, false to read. + * @return Zero or negative mapping/device errno. + */ +static int ej_log_io(struct storage_volume *v,uint32_t logical,void *data,bool write) +{ + struct storage_ext4_map_result map; + int ret=ej_log_map(v,logical,&map); + return ret<0 ? ret : ej_io(v,map.physical,1,data,write); +} + +/** + * @brief Write staged log payload, splitting at extents and the ring boundary. + * @param v Live ext-family volume under storage execution ownership. + * @param pos Journal ring cursor, advanced after every successful submission. + * @param count Number of prepared contiguous blocks in ej_payload. + * @return Zero or negative mapping/device errno. The caller orders the payload + * before its separate commit record; failed runs never publish that record. + */ +static int ej_write_payload(struct storage_volume *v,uint32_t *pos,uint32_t count) +{ + const struct storage_ext4_journal *j=v->ext4.journal; + for (uint32_t done=0;donemaxlen-*pos; + if (run>map.length) run=map.length; + if (run>tail) run=tail; + ret=ej_io(v,map.physical,run,ej_payload+(size_t)done*v->ext4.block_size,true); + if (ret<0) return ret; + done+=run; *pos=run==tail ? j->first : *pos+run; + } + return 0; } static bool ej_target_ok(struct storage_volume *v,uint64_t block) { @@ -103,10 +162,18 @@ static int ej_super_write(struct storage_volume *v,uint32_t start,uint32_t seque static void ej_recover_flag_bytes(struct storage_volume *v,uint8_t *sb,bool recover) { uint32_t features=ext4_get_le32(sb+96); - features=recover ? features|4u : features&~4u; ext4_put_le32(sb+96,features); + const uint32_t bit=EXT4_FEATURE_INCOMPAT_RECOVER; + features=recover ? features|bit : features&~bit; ext4_put_le32(sb+96,features); if (v->ext4.super_view.feature_ro_compat & EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) (void)storage_ext4_update_super_checksum(sb,1024); } +/** + * @brief Persist a transition of the filesystem's journal recovery flag. + * @param v Live ext-family volume with an open journal and execution ownership. + * @param recover True before the first log publication, false only with no live log. + * @return Zero or the device read, write or flush error. + * Invalidate only cached blocks overlapping the changed on-disk superblock. + */ static int ej_recover_flag(struct storage_volume *v,bool recover) { uint8_t *raw=v->ext4.journal->scan.data; @@ -114,9 +181,10 @@ static int ej_recover_flag(struct storage_volume *v,bool recover) ej_recover_flag_bytes(v,raw,recover); ret=storage_write_device(v,v->ext_start_lba+2,2,raw); if (!ret) { - if (recover) v->ext4.super_view.feature_incompat|=4; - else v->ext4.super_view.feature_incompat&=~4u; + if (recover) v->ext4.super_view.feature_incompat|=EXT4_FEATURE_INCOMPAT_RECOVER; + else v->ext4.super_view.feature_incompat&=~EXT4_FEATURE_INCOMPAT_RECOVER; ret=storage_ext4_device_flush(v); + if (!ret) storage_ext4_cache_invalidate_write(v,NULL,v->ext_start_lba+2,2); } return ret; } @@ -212,6 +280,10 @@ int storage_ext4_journal_publish(struct storage_volume *v,uint64_t block,const u } return j->error=-RELIEFOS_EIO; } + +/** @brief Retire committed log contents without clearing recovery state. */ +static int ej_checkpoint(struct storage_volume *v); + /** * @brief Admit a non-replayable metadata transaction and finish prior journal work. * @param v Borrowed live ext-family instance under storage execution ownership. @@ -222,6 +294,7 @@ int storage_ext4_journal_publish(struct storage_volume *v,uint64_t block,const u * span this call. Admission latches storage mutation before any old-journal * read or write: a resumable read must not be mistaken for journal corruption. * The latch stays set on failure; native metadata is not replayed after yield. + * Checkpoint the prior transaction without clearing the live recovery flag. */ int storage_ext4_journal_start(struct storage_volume *v,uint32_t credits,struct storage_ext4_handle *h) { @@ -235,7 +308,7 @@ int storage_ext4_journal_start(struct storage_volume *v,uint32_t credits,struct if (j) { if (!j->active) { int ret=storage_ext4_journal_commit(v,true); if (ret<0) return ret; - ret=storage_ext4_journal_checkpoint(v); if (ret<0) return ret; + ret=ej_checkpoint(v); if (ret<0) return ret; j->before_super=v->ext4.super_view; j->before_goal=v->ext4.next_goal_block; j->before_window=v->ext4.reserved_window_end; j->credits=credits; j->error=0; } else if (credits>j->credits) { @@ -277,6 +350,14 @@ static void ej_header(uint8_t *raw,uint32_t type,uint32_t seq) static uint32_t ej_data_csum(struct storage_ext4_journal *j,uint32_t seq,const uint8_t *raw,uint32_t bs) { uint8_t word[4]; ej_put32(word,seq); return storage_ext4_crc32c(storage_ext4_crc32c(j->seed,word,4),raw,bs); } +/** + * @brief Durably commit one ordered-data metadata transaction to the journal. + * @param v Live ext-family volume under storage execution ownership. + * @param wait Retained interface flag; sector completion is always synchronous. + * @return Zero or a state, capacity or device error; no home metadata is + * written here. Publish the recovery flag before the first active log, then + * order file data, journal start and log payload before the commit record. + */ int storage_ext4_journal_commit(struct storage_volume *v,bool wait) { (void)wait; /* This backend has synchronous sector completion. */ @@ -292,19 +373,21 @@ int storage_ext4_journal_commit(struct storage_volume *v,bool wait) j->count=0; return 0; } if (tags+2>=j->maxlen-j->first) return -RELIEFOS_ENOSPC; - /* Publish recovery requirement and journal start before any home metadata. - * The flush also orders caller data writes before the metadata transaction. */ - int ret=ej_recover_flag(v,true); if (ret<0) return ej_fail(v,ret); + /* Keep RECOVER set between transactions. A clean journal with RECOVER + * still set is recoverable; a live journal without it must not be exposed. */ + int ret; + if (!(v->ext4.super_view.feature_incompat&EXT4_FEATURE_INCOMPAT_RECOVER)) { + ret=ej_recover_flag(v,true); if (ret<0) return ej_fail(v,ret); + } j->start=j->head; ret=ej_super_write(v,j->start,j->sequence,j->head); if (ret<0) return ej_fail(v,ret); - ret=storage_ext4_device_flush(v); if (ret<0) return ej_fail(v,ret); - uint8_t *desc=j->scan.descriptor, *data=j->scan.data; + uint8_t *desc=ej_payload, *data=j->scan.data; storage_memzero(desc,bs); ej_header(desc,1,j->sequence); uint32_t at=12, nr=0, tag_size=ej_tag_size(j); - for (uint32_t i=0;icount;i++) if (j->images[i].dirty) { + for (uint32_t i=0;icount;i++) { struct ext4_journal_image *image=&j->images[i]; - uint64_t sb_block=1024/bs; - if (image->block==sb_block) ej_recover_flag_bytes(v,image->after+1024%bs,true); + if (image->block==1024/bs) ej_recover_flag_bytes(v,image->after+1024%bs,true); + if (!image->dirty) continue; storage_memcpy(data,image->after,bs); uint32_t flags=nr ? 2 : 0; if (ej_be32(data)==EJ_MAGIC) { flags|=1; ej_put32(data,0); } @@ -323,49 +406,69 @@ int storage_ext4_journal_commit(struct storage_volume *v,bool wait) if (nr==1) { storage_memcpy(desc+at,j->uuid,16); at+=16; } } if (ej_csum(j)) ej_put32(desc+bs-4,ej_zero_csum(j->seed,desc,bs,bs-4)); - uint32_t crc=ej_crc32_be(~0u,desc,bs), pos=j->head; - ret=ej_log_io(v,pos,desc,true); if (ret<0) return ej_fail(v,ret); pos=ej_next(j,pos); + bool legacy_csum=j->compat&1; + uint32_t crc=legacy_csum ? ej_crc32_be(~0u,desc,bs) : ~0u; + uint32_t pos=j->head, buffered=1; for (uint32_t i=0;icount;i++) if (j->images[i].dirty) { - storage_memcpy(data,j->images[i].after,bs); - if (ej_be32(data)==EJ_MAGIC) ej_put32(data,0); - crc=ej_crc32_be(crc,data,bs); - ret=ej_log_io(v,pos,data,true); if (ret<0) return ej_fail(v,ret); pos=ej_next(j,pos); + uint8_t *slot=ej_payload+(size_t)buffered*bs; + storage_memcpy(slot,j->images[i].after,bs); + if (ej_be32(slot)==EJ_MAGIC) ej_put32(slot,0); + if (legacy_csum) crc=ej_crc32_be(crc,slot,bs); + if (++buffered==EJ_BATCH_BLOCKS) { + ret=ej_write_payload(v,&pos,buffered); if (ret<0) return ej_fail(v,ret); + buffered=0; + } + } + if (buffered) { + ret=ej_write_payload(v,&pos,buffered); if (ret<0) return ej_fail(v,ret); } + /* The journal start, descriptor/payload and earlier file data must all + * reach disk before a matching commit record can be written. */ ret=storage_ext4_device_flush(v); if (ret<0) return ej_fail(v,ret); storage_memzero(data,bs); ej_header(data,2,j->sequence); if (ej_csum(j)) ej_put32(data+16,ej_zero_csum(j->seed,data,bs,16)); - else if (j->compat&1) { data[12]=1; data[13]=4; ej_put32(data+16,crc); } + else if (legacy_csum) { data[12]=1; data[13]=4; ej_put32(data+16,crc); } ret=ej_log_io(v,pos,data,true); if (ret<0) return ej_fail(v,ret); ret=storage_ext4_device_flush(v); if (ret<0) return ej_fail(v,ret); j->head=ej_next(j,pos); j->committed=true; ++v->ext4.journal_commits; return 0; } /** - * @brief Flush committed metadata and retire only the stale superblock cache. + * @brief Write committed home metadata before durably retiring its log. * @param v Live ext-family volume under storage execution ownership. - * @return Zero or the journal/transport error. Successful checkpointing keeps - * coherent data and metadata blocks cached; flush ordering is unchanged. + * @return Zero or the journal/transport error. Leaves RECOVER set so that the + * next transaction need not repeat the filesystem-superblock transition. */ -int storage_ext4_journal_checkpoint(struct storage_volume *v) +static int ej_checkpoint(struct storage_volume *v) { if (!v) return -RELIEFOS_EINVAL; struct storage_ext4_journal *j=v->ext4.journal; if (!j || !j->committed) return 0; if (j->active || j->error) return -RELIEFOS_EBUSY; for (uint32_t i=0;icount;i++) if (j->images[i].dirty) { - int ret=ej_io(v,j->images[i].block,j->images[i].after,true); + int ret=ej_io(v,j->images[i].block,1,j->images[i].after,true); if (ret<0) return ej_fail(v,ret); } int ret=storage_ext4_device_flush(v); if (ret<0) return ej_fail(v,ret); ret=ej_super_write(v,0,j->sequence+1,j->head); if (ret<0) return ej_fail(v,ret); ret=storage_ext4_device_flush(v); if (ret<0) return ej_fail(v,ret); - ret=ej_recover_flag(v,false); if (ret<0) return ej_fail(v,ret); for (uint32_t i=0;icount;i++) storage_ext4_cache_finish(v,j->images[i].block,j->images[i].after); - /* Home images may still contain RECOVER. Invalidate the block covering - * the just-cleared 1024-byte superblock, not unrelated clean blocks. */ - storage_ext4_cache_invalidate_write(v,NULL,v->ext_start_lba+2,2); ++j->sequence; j->start=0; j->count=0; j->committed=false; return 0; } +/** @copydoc storage_ext4_journal_checkpoint */ +int storage_ext4_journal_checkpoint(struct storage_volume *v) +{ + int ret=ej_checkpoint(v); + if (ret<0) return ret; + struct storage_ext4_journal *j=v->ext4.journal; + if (!j || j->active || j->count || j->start || j->error || + v->ext4.fs_error || v->read_only_reason || + !(v->ext4.super_view.feature_incompat&EXT4_FEATURE_INCOMPAT_RECOVER)) + return 0; + ret=ej_recover_flag(v,false); + return ret<0 ? ej_fail(v,ret) : 0; +} + enum ej_pass { EJ_SCAN, EJ_COLLECT, EJ_REPLAY, EJ_FIND_REVOKE }; static int ej_walk(struct storage_volume *,struct ext4_journal_scan *,enum ej_pass, uint32_t,uint32_t *,uint32_t *,uint32_t *,uint64_t,uint32_t,bool *); @@ -430,7 +533,7 @@ static int ej_walk(struct storage_volume *v,struct ext4_journal_scan *w,enum ej_ ret=ej_revoked(v,target,seq,limit,&revoked); if (ret<0) return ret; if (!revoked) { if (flags&1) ej_put32(w->data,EJ_MAGIC); - ret=ej_io(v,target,w->data,true); if (ret<0) return ret; + ret=ej_io(v,target,1,w->data,true); if (ret<0) return ret; ++v->ext4.journal_replays; } else ++v->ext4.journal_revoke_hits; } diff --git a/tools/tests/ext4_journal_test.c b/tools/tests/ext4_journal_test.c index 0238c19c..e48698c9 100644 --- a/tools/tests/ext4_journal_test.c +++ b/tools/tests/ext4_journal_test.c @@ -10,6 +10,7 @@ static int fail_write_at = -1, device_failed; static int fail_flush_at = -1; static uint64_t flushes, last_flushed_writes; +static uint32_t descriptor_sectors; static uint8_t *durable; int storage_write_device(const struct storage_volume *v, uint64_t lba, uint32_t n, const void *in) @@ -19,8 +20,10 @@ int storage_write_device(const struct storage_volume *v, uint64_t lba, } const uint8_t *raw = in; if (n && raw[0]==0xc0 && raw[1]==0x3b && raw[2]==0x39 && raw[3]==0x98 && - raw[4]==0 && raw[5]==0 && raw[6]==0 && raw[7]==2) - assert(last_flushed_writes == writes); /* Data barrier precedes commit. */ + raw[4]==0 && raw[5]==0 && raw[6]==0) { + if (raw[7]==1) descriptor_sectors=n; + if (raw[7]==2) assert(last_flushed_writes == writes); /* Before commit. */ + } return ext4_fixture_write_device(v, lba, n, in); } int storage_ext4_device_flush(const struct storage_volume *v) @@ -92,6 +95,7 @@ int main(int argc,char **argv) disk=load(argv[1],&disk_len); load_geometry(); uint64_t payload_ino=strtoull(argv[2],NULL,10); uint64_t target=file_block(payload_ino,0); + uint64_t across_ring=argc==5 ? file_block(payload_ino,1) : 0; uint64_t jb=file_block(volume.ext4.super_view.journal_inum,0); uint32_t bs=volume.ext4.block_size; uint8_t *js=disk+jb*bs; @@ -115,10 +119,20 @@ int main(int argc,char **argv) memcpy(cache,next,bs); assert(storage_ext4_cache_mark_dirty(&volume,target)==0); assert(storage_ext4_journal_dirty(&handle,target)==0); + if (across_ring) { + /* Unchanged data still occupies a log slot. The first write batches + * the descriptor and first block; this slot lies beyond ring wrap. */ + assert(storage_ext4_cache_get(&volume,across_ring,&cache,true)==0); + assert(storage_ext4_cache_mark_dirty(&volume,across_ring)==0); + } assert(storage_ext4_cache_flush(&volume)==0); assert(memcmp(disk+target*bs,old,bs)==0); /* No home write before commit. */ assert(storage_ext4_journal_stop(&handle)==0); assert(storage_ext4_journal_commit(&volume,true)==0); + if (across_ring) { + assert(descriptor_sectors==2*(bs/512)); /* Adjacent descriptor and image. */ + assert(!memcmp(log_block(be32(js+20)),disk+across_ring*bs,bs)); + } assert(flushes>=3 && memcmp(disk+target*bs,old,bs)==0); assert(ext4_get_le32(disk+1024+96)&4); /* RECOVER is durable. */ save(argv[4]); /* e2fsck independently replays this exact committed log. */ @@ -146,7 +160,7 @@ int main(int argc,char **argv) memcpy(disk,committed_image,disk_len); load_geometry(); js=disk+jb*bs; if (argc==6) b32(js+40,1); /* Only the synthetic revoke test enables revokes. */ uint32_t pos=be32(js+28), sequence=be32(js+24)+1; - for (unsigned i=0;i<3;i++) pos=next_log(js,pos); /* after first commit */ + for (unsigned i=0;i<(across_ring ? 4u : 3u);i++) pos=next_log(js,pos); /* after first commit */ unsigned revoked=0, record_size=(profile&2)?8:4; while (revoked<600) { uint8_t *raw=log_block(pos); log_header(raw,5,sequence); @@ -193,6 +207,27 @@ int main(int argc,char **argv) } storage_ext4_journal_close(&volume); invalidate(); } + /* Model consecutive small-file metadata changes. A new operation still + * checkpoints the previous one, but does not mark a live volume clean. */ + memcpy(disk,initial,disk_len); load_geometry(); + memcpy(durable,initial,disk_len); writes=flushes=last_flushed_writes=0; + assert(storage_ext4_journal_open(&volume)==0); + assert(storage_ext4_journal_start(&volume,2,&handle)==0); + for (unsigned i=0;i<2;i++) { + assert(storage_ext4_cache_get(&volume,target,&cache,true)==0); + cache[0]=(uint8_t)(0x40+i); + assert(storage_ext4_cache_mark_dirty(&volume,target)==0); + assert(storage_ext4_journal_stop(&handle)==0); + assert(storage_ext4_journal_start(&volume,2,&handle)==0); + assert(flushes==5+4*i); + assert(durable[target*bs]==0x40+i && !be32(durable+jb*bs+28)); + assert(ext4_get_le32(durable+1024+96)&EXT4_FEATURE_INCOMPAT_RECOVER); + } + assert(storage_ext4_journal_stop(&handle)==0); + assert(storage_ext4_journal_checkpoint(&volume)==0); + assert(flushes==10 && !be32(durable+jb*bs+28)); + assert(!(ext4_get_le32(durable+1024+96)&EXT4_FEATURE_INCOMPAT_RECOVER)); + storage_ext4_journal_close(&volume); invalidate(); memcpy(disk,initial,disk_len); load_geometry(); assert(storage_ext4_journal_open(&volume)==0); assert(storage_ext4_journal_start(&volume,1,&handle)==0); From 1d27b9652184a4d99f8db1b8fcde441f55c9bdb3 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Tue, 1 Dec 2026 07:47:57 +0800 Subject: [PATCH 86/97] perf(kernel): batch ext4 metadata and sample NIC carrier --- Documentation/core-api/network-devices.rst | 3 + Documentation/core-api/storage-completion.rst | 7 + .../LC_MESSAGES/core-api/network-devices.po | 3 + .../core-api/storage-completion.po | 6 + .../LC_MESSAGES/core-api/network-devices.po | 3 + .../core-api/storage-completion.po | 6 + block/core/storage_sync.c | 17 ++ drivers/net/e1000e/internal.h | 4 +- drivers/net/e1000e/main.c | 20 +- fs/ext_common/alloc.c | 59 ++++- fs/ext_common/cache.c | 15 +- fs/ext_common/internal.h | 60 +++-- fs/ext_common/journal.c | 205 ++++++++++++++---- fs/ext_common/native.c | 1 + fs/ext_common/ops.c | 1 + fs/ext_common/storage_ext4_types.h | 12 + fs/operations.h | 3 + include/reliefnt/storage.h | 6 + kernel/workqueue/services.c | 14 +- tools/tests/e1000e_test.c | 13 +- tools/tests/ext4_dma_read_test.c | 2 + tools/tests/ext4_journal_test.c | 70 +++++- tools/tests/ext4_read_batch_resume_test.c | 2 + tools/tests/ext4_write_batch_transport_test.c | 2 + tools/tests/storage_codec_context_fixture.h | 3 + tools/tests/storage_mkdir_mount_test.c | 7 +- 26 files changed, 459 insertions(+), 85 deletions(-) diff --git a/Documentation/core-api/network-devices.rst b/Documentation/core-api/network-devices.rst index ad96d2e5..6f364aac 100644 --- a/Documentation/core-api/network-devices.rst +++ b/Documentation/core-api/network-devices.rst @@ -19,6 +19,9 @@ Device identity 驱动关闭回调接入、排空引用并停止自身全部设备后,管理器移除对应接口。 停止失败的设备保留 DMA 和模块代码,后续卸载可以重试。 +e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO +寄存器。实际发送仍检查当前链路,驱动没有关闭收包轮询或协议定时器。 + 旧 ``e1000_*`` 服务入口和 ReliefOS 旧网络管理请求查询首个存活接口。 旧驱动 API 表和公开用户结构继续使用原布局。新设备接口属于 ReliefNT 私有 内核接口,原生模块通过精确构建 ABI 关联。 diff --git a/Documentation/core-api/storage-completion.rst b/Documentation/core-api/storage-completion.rst index 17dcd0e5..c8dbb184 100644 --- a/Documentation/core-api/storage-completion.rst +++ b/Documentation/core-api/storage-completion.rst @@ -70,6 +70,13 @@ ext 连续读取在单次调用内复用已验证的逻辑/物理映射值,跨 数据与日志内容仍先于提交记录持久化,元数据仍先于清空日志持久化。恢复位改变时 仅失效重叠的超级块缓存,一致的其他缓存不变。 +常规 ext4 挂载将连续元数据操作合并到有界 JBD2 +提交组。共享块缓存驱逐时仍从日志组读取最新镜像;单次操作失败只撤销该操作,不丢弃较早的成功操作。块或 inode +释放在资源可被下一操作重用之前建立持久化边界。 + +待提交组在约五秒后到期,空闲时由后台工作定期处理;占用中的存储事务优先完成。显式同步、同步挂载和卸载仍等待对应写入。checkpoint +合批只合并至多八个相邻目标块,不省略原有刷盘屏障。 + 不可重放的写入、刷盘、启动及 reclaim/swap 路径保持同步。错误恢复先 证明控制器/端口 STOP,再重置队列或重用 DMA;STOP 失败保留 backing、 BAR 和模块。卸载先关闭新用户并禁用/排空 IRQ,再 STOP、释放资源。 diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po index a67196cb..216cea5d 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po @@ -206,3 +206,6 @@ msgstr "Disabling ``IPV6_RECVERR`` clears the extended-error queue and preserves msgid "``tools/test_ipv6_transport.py`` 使用实际 raw/ping 实现验证扩展错误、identifier 和网络隔离、队列容量、分配失败与关闭清理,并通过实际 ``recvmsg`` 入口验证辅助数据和换页重试期间的安全消费。" msgstr "``tools/test_ipv6_transport.py`` exercises the real raw/ping implementation for extended errors, identifier and network isolation, queue bounds, allocation failures and close cleanup. The real ``recvmsg`` entry validates ancillary data and safe consumption across swap retries." + +msgid "e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO 寄存器。实际发送仍检查当前链路,驱动没有关闭收包轮询或协议定时器。" +msgstr "e1000e carrier queries reuse one hardware sample per device per tick instead of repeatedly reading the same MMIO register. Transmit still checks the live link; receive polling and protocol timers remain enabled." diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po b/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po index c176ba62..19edeabf 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po @@ -218,3 +218,9 @@ msgstr "``tools/test_fat_read_split.py`` uses the production FAT directory, bloc msgid "FAT32 大于预读缓存的合法簇通过现有簇缓冲区逐簇读取,保留碎片链游标、部分读取和错误语义,不扩大预读缓存。" msgstr "Legal FAT32 clusters larger than the read-ahead cache are read individually through the existing cluster buffer. Fragmented-chain cursors, partial-read and error semantics are retained without enlarging the read-ahead cache." + +msgid "常规 ext4 挂载将连续元数据操作合并到有界 JBD2 提交组。共享块缓存驱逐时仍从日志组读取最新镜像;单次操作失败只撤销该操作,不丢弃较早的成功操作。块或 inode 释放在资源可被下一操作重用之前建立持久化边界。" +msgstr "Ordinary ext4 mounts combine consecutive metadata operations into bounded JBD2 groups. Reads still see the latest journal image after shared-cache eviction. A failed operation rolls back only its own changes; successful earlier operations remain. Freed blocks and inodes cross a durability barrier before a later operation can reuse them." + +msgid "待提交组在约五秒后到期,空闲时由后台工作定期处理;占用中的存储事务优先完成。显式同步、同步挂载和卸载仍等待对应写入。checkpoint 合批只合并至多八个相邻目标块,不省略原有刷盘屏障。" +msgstr "A pending group becomes eligible after about five seconds; periodic background work handles it when storage is idle. Explicit sync, synchronous mounts, and unmount still wait for their writes. Checkpoint batching merges at most eight adjacent home blocks without removing existing flush barriers." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po index 13ac0179..99520bed 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po @@ -184,3 +184,6 @@ msgstr "``IPV6_RECVERR`` を無効にすると拡張エラーキューを解放 msgid "``tools/test_ipv6_transport.py`` 使用实际 raw/ping 实现验证扩展错误、identifier 和网络隔离、队列容量、分配失败与关闭清理,并通过实际 ``recvmsg`` 入口验证辅助数据和换页重试期间的安全消费。" msgstr "``tools/test_ipv6_transport.py`` は実際の raw/ping 実装で拡張エラー、identifier とネットワークの分離、キュー上限、割り当て失敗とクローズ時の解放を検証します。実際の ``recvmsg`` 入口で補助データとスワップ再試行時の安全な消費を確認します。" + +msgid "e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO 寄存器。实际发送仍检查当前链路,驱动没有关闭收包轮询或协议定时器。" +msgstr "e1000e のリンク状態の問い合わせでは、同じ MMIO レジスタを繰り返し読まず、デバイスごとに同一 tick 内のハードウェア測定値を再利用します。実際の送信では現在のリンクを確認し、受信ポーリングとプロトコルタイマーも有効なままです。" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po b/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po index 5c765012..6cf0f283 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po @@ -194,3 +194,9 @@ msgstr "``tools/test_fat_read_split.py`` は実際の FAT ディレクトリー msgid "FAT32 大于预读缓存的合法簇通过现有簇缓冲区逐簇读取,保留碎片链游标、部分读取和错误语义,不扩大预读缓存。" msgstr "FAT32 の有効なクラスタが先読みキャッシュより大きい場合、既存のクラスタバッファーを使って一つずつ読み取ります。先読みキャッシュを拡大せず、断片化チェーンのカーソル、部分読み取りとエラーの意味を維持します。" + +msgid "常规 ext4 挂载将连续元数据操作合并到有界 JBD2 提交组。共享块缓存驱逐时仍从日志组读取最新镜像;单次操作失败只撤销该操作,不丢弃较早的成功操作。块或 inode 释放在资源可被下一操作重用之前建立持久化边界。" +msgstr "通常の ext4 マウントでは、連続するメタデータ操作を上限のある JBD2 グループにまとめます。共有キャッシュから追い出されたブロックも、ロググループの最新イメージから読み取ります。失敗した操作だけを取り消し、先に成功した操作は維持します。解放したブロックや inode を後続の操作で再利用する前に、永続化バリアを通過させます。" + +msgid "待提交组在约五秒后到期,空闲时由后台工作定期处理;占用中的存储事务优先完成。显式同步、同步挂载和卸载仍等待对应写入。checkpoint 合批只合并至多八个相邻目标块,不省略原有刷盘屏障。" +msgstr "保留中のグループは約 5 秒で期限に達し、ストレージが空いたときに定期バックグラウンド処理で書き戻されます。明示的な同期、同期マウント、アンマウントは引き続き対応する書き込みを待ちます。チェックポイントで結合するのは隣接する最大 8 個の書き込み先ブロックだけで、既存のフラッシュバリアは省略しません。" diff --git a/block/core/storage_sync.c b/block/core/storage_sync.c index 7f509a7c..e765c876 100644 --- a/block/core/storage_sync.c +++ b/block/core/storage_sync.c @@ -1,4 +1,6 @@ #include +#include +#include #include "storage_internal.h" /** @brief Flush a held block identity after native writeback, retaining errors. * @param volume Stable instance retaining its device reference, required. @@ -80,6 +82,21 @@ int storage_sync_all(void) return result; } +/** @copydoc storage_writeback_expired */ +void storage_writeback_expired(uint64_t now) +{ + if (storage_task_io_owner) return; + struct storage_io_context saved; + storage_kernel_context_enter(&saved); + if (!storage_acquire_task_io()) for (uint32_t i=0;ifs_ops || !volume->fs_ops->writeback) continue; + int rc=volume->fs_ops->writeback(volume,now); + if (rc<0) console_error("[storage] background writeback volume=%u rc=%d\n",i,rc); + } + storage_kernel_context_leave(&saved); +} + /* Native filesystem modules share this core-owned interface; CRC/release * checks bind it to the exact kernel, without a stable cross-release API. */ EXPORT_SYMBOL(storage_ext4_device_flush); diff --git a/drivers/net/e1000e/internal.h b/drivers/net/e1000e/internal.h index b3a7f646..24eac446 100644 --- a/drivers/net/e1000e/internal.h +++ b/drivers/net/e1000e/internal.h @@ -73,7 +73,9 @@ struct e1k_device { volatile struct e1k_tx_descriptor *tx; uint8_t *rx_data, *tx_data; unsigned rx_next, tx_next, tx_clean; - struct kernel_spinlock rx_lock, tx_lock; + uint64_t carrier_tick; + bool carrier_valid, carrier_up; + struct kernel_spinlock rx_lock, tx_lock, carrier_lock; }; /** @brief Read one aligned device register through the owned UC mapping. diff --git a/drivers/net/e1000e/main.c b/drivers/net/e1000e/main.c index 18811dbe..5aa206f2 100644 --- a/drivers/net/e1000e/main.c +++ b/drivers/net/e1000e/main.c @@ -5,13 +5,27 @@ static struct e1k_device *devices; -/** @brief Report carrier of the specific controller. - * @param context Pinned controller. @return Nonzero when the link is up. +/** @brief Reuse one carrier sample per tick instead of repeatedly reading MMIO. + * @param context Pinned controller. @return Nonzero when sampled link is up. + * A carrier change is visible on the next tick; actual transmit still checks + * live carrier. Without the time service, use the original live query. */ static int ready(void *context) { struct e1k_device *d=context; - return d->active && (e1k_read(d,E1K_STATUS)&E1K_STATUS_LINK); + if (!d->active) return 0; + if (!d->api->ticks) return (e1k_read(d,E1K_STATUS)&E1K_STATUS_LINK)!=0; + uint64_t flags; + kernel_spin_lock_irqsave(&d->carrier_lock,&flags); + uint64_t now=d->api->ticks(); + if (!d->carrier_valid || d->carrier_tick!=now) { + d->carrier_up=(e1k_read(d,E1K_STATUS)&E1K_STATUS_LINK)!=0; + d->carrier_tick=now; + d->carrier_valid=true; + } + bool up=d->carrier_up; + kernel_spin_unlock_irqrestore(&d->carrier_lock,flags); + return up; } /** @brief Borrow the selected controller's address while pinned. * @param context Pinned controller. @return Six immutable device bytes. diff --git a/fs/ext_common/alloc.c b/fs/ext_common/alloc.c index 25ecb465..ae63c8a3 100644 --- a/fs/ext_common/alloc.c +++ b/fs/ext_common/alloc.c @@ -721,10 +721,33 @@ static uint32_t ext4_bitmap_next(const uint8_t *bitmap, uint32_t lo, return hi; } +/** + * @brief Treat blocks freed by the current operation as still allocated. + * @param v Borrowed volume under storage execution ownership. + * @param first First filesystem block represented by the mask. + * @param width Number of represented bits (1 through 64). + * @return Mask of physical blocks that cannot yet be recycled. + */ +static uint64_t ext4_freed_mask(const struct storage_volume *v,uint64_t first,uint32_t width) +{ + uint64_t mask=0; + for (uint32_t i=0;iext4.journal_free_count;i++) { + const struct storage_ext4_free_range *range=&v->ext4.journal_frees[i]; + if (range->end<=first) continue; + uint64_t lo=range->first>first ? range->first-first : 0; + uint64_t hi=range->end-first; + if (lo>=width) continue; + if (hi>width) hi=width; + mask|=(hi==64 ? UINT64_MAX : (UINT64_C(1)<ext4.journal_free_count && ext4_freed_mask(volume,block,1))) return 0; if (!window_owner && block >= volume->ext4.next_goal_block && block < volume->ext4.reserved_window_end) @@ -783,6 +806,7 @@ static void ext4_scan_bits(const struct storage_volume *volume, occupied |= end_mask & (UINT64_MAX << start); } } + if (volume->ext4.journal_free_count) occupied|=ext4_freed_mask(volume,first,width); occupied &= mask; if (!occupied) { if (!run_len) run_start = bit; @@ -1215,6 +1239,32 @@ static int ext4_alloc_blocks_impl(struct storage_volume *volume, uint64_t goal, return 0; } +/** + * @brief Quarantine a validated free until its outer journal operation stops. + * @param v Live volume under storage execution ownership. + * @param first First freed physical block. @param end Exclusive end. + * @return Zero, or ENOSPC if the bounded edit cannot track another range. + * A successful outer stop forces the group durable before the next edit. + * Abort discards the quarantine together with the bitmap edits. + */ +static int ext4_hold_freed(struct storage_volume *v,uint64_t first,uint64_t end) +{ + if (!v->ext4.journal) return 0; + uint32_t n=v->ext4.journal_free_count; + if (n) { + struct storage_ext4_free_range *last=&v->ext4.journal_frees[n-1]; + if (first<=last->end && end>=last->first) { + if (firstfirst) last->first=first; + if (end>last->end) last->end=end; + return 0; + } + } + if (n==EXT4_JOURNAL_FREE_RANGES) return -RELIEFOS_ENOSPC; + v->ext4.journal_frees[n]=(struct storage_ext4_free_range){first,end}; + ++v->ext4.journal_free_count; + return 0; +} + static int ext4_free_blocks_impl(struct storage_volume *volume, uint64_t first, uint32_t count) { @@ -1280,7 +1330,8 @@ static int ext4_free_blocks_impl(struct storage_volume *volume, uint64_t first, /* Commit (rollback on failure: the inverse operation restores the * already-cleared chunks). */ { - int ret = ext4_commit_run(volume, first, count, false); + int ret = ext4_hold_freed(volume,first,end); + if (!ret) ret = ext4_commit_run(volume, first, count, false); if (ret < 0) return ret; } @@ -1506,7 +1557,9 @@ static int ext4_free_inode_impl(struct storage_volume *volume, uint64_t ino, ret = storage_ext4_cache_mark_dirty(volume, view.inode_bitmap); if (ret < 0) return ret; - return ext4_super_counts_update(volume, 0, 1); + ret=ext4_super_counts_update(volume,0,1); + if (!ret && volume->ext4.journal) volume->ext4.order_on_stop=true; + return ret; } /* Nested allocator calls join an outer inode/directory transaction. Standalone diff --git a/fs/ext_common/cache.c b/fs/ext_common/cache.c index d4b92a09..b89368a9 100644 --- a/fs/ext_common/cache.c +++ b/fs/ext_common/cache.c @@ -206,7 +206,8 @@ static struct storage_ext4_cache_entry *ext4_cache_fill(struct ext4_cache_table return NULL; } } - ret = storage_read_device(volume, lba, sectors, victim->data); + ret = storage_ext4_journal_read(volume,block,victim->data) ? 0 : + storage_read_device(volume, lba, sectors, victim->data); if (ret < 0) { victim->valid = 0; victim->dirty = 0; @@ -242,6 +243,7 @@ int storage_ext4_cache_read(struct storage_volume *volume, uint64_t block, void if (err < 0) { return err; } + if (storage_ext4_journal_read(volume,block,out)) return 0; err = storage_read_device(volume, lba, sectors, ext4_read_dma); if (!err) storage_memcpy(out, ext4_read_dma, volume->ext4.block_size); return err; @@ -275,9 +277,14 @@ static int ext4_cache_read_blocks(struct storage_volume *v, uint64_t first, entry->age = ++table->age_clock; ++v->ext4.read_cache_hits; ++done; continue; } + if (storage_ext4_journal_read(v,first+done,(uint8_t *)out+(size_t)done*bs)) { + ++v->ext4.read_cache_hits; ++done; + continue; + } uint32_t run = 1; while (run < count - done && run < EXT4_READAHEAD_BLOCKS && - !ext4_cache_lookup(table, v, first + done + run)) ++run; + !ext4_cache_lookup(table, v, first + done + run) && + !storage_ext4_journal_owns(v,first+done+run)) ++run; ret = ext4_cache_block_range(v, first + done, &lba, §ors); if (ret < 0) return ret; ret = storage_read_device(v, lba, run * sectors, ext4_read_dma); @@ -337,6 +344,10 @@ int storage_ext4_cache_read_blocks(struct storage_volume *v, uint64_t first, e->volume_generation == v->mount_generation && e->block >= first && e->block - first < count) ++hits; } + if (hitsext4.journal) for (uint32_t i=0;i #define EJ_MAGIC 0xc03b3998u #define EJ_CSUM2 8u #define EJ_CSUM3 16u #define EJ_REVOKES 512u #define EJ_BATCH_BLOCKS 8u +#define EJ_GROUP_IMAGES 128u +#define EJ_COMMIT_AGE (5u * RELIEFNT_TICK_HZ) /* CPU-only staging; the storage execution lock serializes all journal I/O. */ static uint8_t ej_payload[EJ_BATCH_BLOCKS * EXT4_MAX_BLOCK_SIZE]; @@ -17,20 +20,26 @@ static uint8_t ej_payload[EJ_BATCH_BLOCKS * EXT4_MAX_BLOCK_SIZE]; struct ext4_journal_image { uint64_t block; bool dirty; - uint8_t before[EXT4_MAX_BLOCK_SIZE], after[EXT4_MAX_BLOCK_SIZE]; + uint8_t after[EXT4_MAX_BLOCK_SIZE]; +}; +struct ext4_journal_edit { + uint32_t slot; + uint8_t before[EXT4_MAX_BLOCK_SIZE]; }; struct ext4_journal_revoke { uint64_t block; uint32_t sequence; bool valid; }; struct ext4_journal_scan { uint8_t descriptor[EXT4_MAX_BLOCK_SIZE], data[EXT4_MAX_BLOCK_SIZE]; }; struct storage_ext4_journal { struct ext4_inode_view inode; uint32_t first, maxlen, sequence, start, head, compat, incompat, seed; - uint32_t count, credits, active; + uint32_t count, base, edits, capacity, credits, active; + uint64_t started; int error; - bool committed, revoke_overflow; + bool committed, ordered, revoke_overflow; uint8_t uuid[16]; struct storage_ext4_super_view before_super; uint64_t before_goal, before_window; - struct ext4_journal_image images[EXT4_JOURNAL_CREDITS]; + struct ext4_journal_image images[EJ_GROUP_IMAGES]; + struct ext4_journal_edit undo[EXT4_JOURNAL_CREDITS]; struct ext4_journal_revoke revokes[EJ_REVOKES]; struct ext4_journal_scan scan, fallback; }; @@ -233,6 +242,12 @@ int storage_ext4_journal_open(struct storage_volume *v) if (type==4 && !ej_equal(j->uuid,v->ext4.super_view.uuid,16)) { ret=-RELIEFOS_EOPNOTSUPP; goto fail; } + uint32_t room=j->maxlen-j->first; + uint32_t tags=(v->ext4.block_size-12-16-(ej_csum(j)?4:0))/ej_tag_size(j); + /* One descriptor plus its payload and commit, with a ring slot unused. */ + j->capacity=room>3 ? room-3 : 0; + if (j->capacity>tags) j->capacity=tags; + if (j->capacity>EJ_GROUP_IMAGES) j->capacity=EJ_GROUP_IMAGES; j->seed=storage_ext4_crc32c(~0u,j->uuid,16); if (j->headfirst || j->head>=j->maxlen) j->head=j->first; return 0; @@ -246,38 +261,74 @@ void storage_ext4_journal_close(struct storage_volume *v) storage_ext4_cache_invalidate(v); kernel_free(v->ext4.journal); v->ext4.journal=NULL; } +/** + * @brief Find a block image in the running or committed group. + * @param j Borrowed journal under execution ownership. + * @param block Filesystem block number. + * @return Image index, or the current count if absent. + */ +static uint32_t ej_image_slot(const struct storage_ext4_journal *j,uint64_t block) +{ + for (uint32_t i=0;icount;i++) + if (j->images[i].block==block) return i; + return j->count; +} + +/** @copydoc storage_ext4_journal_owns */ bool storage_ext4_journal_owns(const struct storage_volume *v,uint64_t block) { - if (!v || !v->ext4.journal) return false; - for (uint32_t i=0;iext4.journal->count;i++) - if (v->ext4.journal->images[i].block==block) return true; - return false; + const struct storage_ext4_journal *j=v ? v->ext4.journal : NULL; + return j && ej_image_slot(j,block)count; } + +/** @copydoc storage_ext4_journal_read */ +bool storage_ext4_journal_read(const struct storage_volume *v,uint64_t block,void *out) +{ + const struct storage_ext4_journal *j=v->ext4.journal; + if (!j) return false; + uint32_t slot=ej_image_slot(j,block); + if (slot==j->count) return false; + storage_memcpy(out,j->images[slot].after,v->ext4.block_size); + return true; +} + +/** @copydoc storage_ext4_journal_capture */ int storage_ext4_journal_capture(struct storage_volume *v,uint64_t block,const uint8_t *data) { - /* New mutations are gated by journal_start. An operation already in - * flight may still need non-journaled compensation after latching fs_error. */ if (v->read_only_reason) return -RELIEFOS_EROFS; struct storage_ext4_journal *j=v->ext4.journal; if (!j) return (v->ext4.super_view.feature_compat&EXT4_FEATURE_COMPAT_HAS_JOURNAL) ? -RELIEFOS_EROFS : 0; if (!j->active || j->committed || j->error) return -RELIEFOS_EROFS; - if (storage_ext4_journal_owns(v,block)) return 0; - if (j->count>=j->credits || j->count>=EXT4_JOURNAL_CREDITS) + uint32_t slot=ej_image_slot(j,block); + for (uint32_t i=0;iedits;i++) + if (j->undo[i].slot==slot && slotcount) return 0; + if (j->edits>=j->credits || (slot==j->count && slot>=j->capacity)) return j->error=-RELIEFOS_ENOSPC; - if (!ej_target_ok(v,block)) return j->error=-RELIEFOS_EIO; - struct ext4_journal_image *image=&j->images[j->count++]; - image->block=block; image->dirty=false; - storage_memcpy(image->before,data,v->ext4.block_size); - storage_memcpy(image->after,data,v->ext4.block_size); + struct ext4_journal_image *image=&j->images[slot]; + if (slot==j->count) { + if (!ej_target_ok(v,block)) return j->error=-RELIEFOS_EIO; + ++j->count; image->block=block; image->dirty=false; + storage_memcpy(image->after,data,v->ext4.block_size); + } + struct ext4_journal_edit *edit=&j->undo[j->edits++]; + edit->slot=slot; + if (slotbase) storage_memcpy(edit->before,image->after,v->ext4.block_size); return 0; } + +/** @copydoc storage_ext4_journal_publish */ int storage_ext4_journal_publish(struct storage_volume *v,uint64_t block,const uint8_t *data) { struct storage_ext4_journal *j=v->ext4.journal; if (!j) return 0; - for (uint32_t i=0;icount;i++) if (j->images[i].block==block) { - storage_memcpy(j->images[i].after,data,v->ext4.block_size); j->images[i].dirty=true; return 0; - } + if (!j->active || j->error) return j->error ? j->error : -RELIEFOS_EROFS; + uint32_t slot=ej_image_slot(j,block); + for (uint32_t i=0;iedits;i++) + if (j->undo[i].slot==slot && slotcount) { + struct ext4_journal_image *image=&j->images[slot]; + storage_memcpy(image->after,data,v->ext4.block_size); image->dirty=true; + return 0; + } return j->error=-RELIEFOS_EIO; } @@ -285,17 +336,26 @@ int storage_ext4_journal_publish(struct storage_volume *v,uint64_t block,const u static int ej_checkpoint(struct storage_volume *v); /** - * @brief Admit a non-replayable metadata transaction and finish prior journal work. - * @param v Borrowed live ext-family instance under storage execution ownership. - * @param credits Positive maximum block-image count, bounded by journal capacity. - * @param h Required caller-owned handle, empty on validation/admission failure. - * @return Zero with an active handle requiring stop, or negative validation, - * readonly, recovery, commit/checkpoint or I/O error. No module/graph lock may - * span this call. Admission latches storage mutation before any old-journal - * read or write: a resumable read must not be mistaken for journal corruption. - * The latch stays set on failure; native metadata is not replayed after yield. - * Checkpoint the prior transaction without clearing the live recovery flag. + * @brief Commit and checkpoint a bounded group without clearing RECOVER. + * @param v Ext volume under synchronous storage execution ownership. + * @return Zero or journal/transport errno. */ +static int ej_finish_group(struct storage_volume *v) +{ + int ret=storage_ext4_journal_commit(v,true); + return ret<0 ? ret : ej_checkpoint(v); +} + +/** @copydoc storage_ext4_journal_writeback */ +int storage_ext4_journal_writeback(struct storage_volume *v,uint64_t now) +{ + struct storage_ext4_journal *j=v->ext4.journal; + if (!j || !j->count || j->active || j->error || v->ext4.fs_error || v->read_only_reason || + now-j->startedEXT4_JOURNAL_CREDITS) return -RELIEFOS_EINVAL; @@ -307,10 +367,16 @@ int storage_ext4_journal_start(struct storage_volume *v,uint32_t credits,struct storage_begin_mutation(); if (j) { if (!j->active) { - int ret=storage_ext4_journal_commit(v,true); if (ret<0) return ret; - ret=ej_checkpoint(v); if (ret<0) return ret; + /* A nested helper may raise the outer credit limit; reserve for + * it now so we never run out of group space halfway through an op. */ + if (j->count && (j->ordered || j->committed || + j->capacity-j->countstarted>=EJ_COMMIT_AGE)) { + int ret=ej_finish_group(v); if (ret<0) return ret; + } j->before_super=v->ext4.super_view; j->before_goal=v->ext4.next_goal_block; j->before_window=v->ext4.reserved_window_end; j->credits=credits; j->error=0; + j->base=j->count; j->edits=0; } else if (credits>j->credits) { j->credits=credits; } @@ -328,6 +394,7 @@ int storage_ext4_journal_dirty(struct storage_ext4_handle *h,uint64_t block) } void storage_ext4_journal_abort(struct storage_ext4_handle *h,int error) { if (h && h->active && h->volume->ext4.journal) h->volume->ext4.journal->error=error<0 ? error : -RELIEFOS_EIO; } +/** @copydoc storage_ext4_journal_stop */ int storage_ext4_journal_stop(struct storage_ext4_handle *h) { if (!h || !h->active) return -RELIEFOS_EINVAL; @@ -335,13 +402,43 @@ int storage_ext4_journal_stop(struct storage_ext4_handle *h) struct storage_volume *v=h->volume; struct storage_ext4_journal *j=v->ext4.journal; if (!j) return 0; --j->active; int ret=j->error; - if (!j->active && ret) { - for (uint32_t i=0;icount;i++) storage_ext4_cache_finish(v,j->images[i].block,j->images[i].before); + if (j->active) return ret; + if (ret) { + /* The group's previous after-images remain authoritative even if + * the failing operation touched a previously published block. */ + for (uint32_t i=0;iedits;i++) { + const struct ext4_journal_edit *edit=&j->undo[i]; + if (edit->slotbase) + storage_memcpy(j->images[edit->slot].after,edit->before,v->ext4.block_size); + } + j->count=j->base; j->error=0; v->ext4.super_view=j->before_super; v->ext4.next_goal_block=j->before_goal; v->ext4.reserved_window_end=j->before_window; storage_ext4_invalidate_groups(v); storage_ext4_cache_invalidate(v); - j->count=0; j->error=0; + } else { + /* The group, not the shared cache, owns completed dirty images. + * Unpin every edit so unrelated reads and mounts can evict it. */ + for (uint32_t i=0;iedits;i++) { + const struct ext4_journal_image *image=&j->images[j->undo[i].slot]; + storage_ext4_cache_finish(v,image->block,image->after); + } + uint32_t next=j->base; + for (uint32_t i=j->base;icount;i++) { + const struct ext4_journal_image *image=&j->images[i]; + if (!image->dirty) continue; + if (next!=i) { + j->images[next].block=image->block; + j->images[next].dirty=true; + storage_memcpy(j->images[next].after,image->after,v->ext4.block_size); + } + ++next; + } + if (!j->base && next) j->started=time_ticks(); + j->count=next; + j->ordered|=v->ext4.order_on_stop || v->ext4.journal_free_count!=0; } + v->ext4.order_on_stop=false; v->ext4.journal_free_count=0; + if (!ret && (v->mount_flags&(MS_SYNCHRONOUS|MS_DIRSYNC))) ret=ej_finish_group(v); return ret; } @@ -363,16 +460,12 @@ int storage_ext4_journal_commit(struct storage_volume *v,bool wait) (void)wait; /* This backend has synchronous sector completion. */ if (!v) return -RELIEFOS_EINVAL; struct storage_ext4_journal *j=v->ext4.journal; - if (!j || !j->count || j->committed) return 0; + if (!j) return 0; if (j->active) return -RELIEFOS_EBUSY; + if (!j->count || j->committed) return 0; if (j->error || v->ext4.fs_error || v->read_only_reason) return -RELIEFOS_EROFS; - uint32_t bs=v->ext4.block_size, tags=0; - for (uint32_t i=0;icount;i++) if (j->images[i].dirty) ++tags; - if (!tags) { - for (uint32_t i=0;icount;i++) storage_ext4_cache_finish(v,j->images[i].block,j->images[i].before); - j->count=0; return 0; - } - if (tags+2>=j->maxlen-j->first) return -RELIEFOS_ENOSPC; + uint32_t bs=v->ext4.block_size, tags=j->count; + if (tags>j->capacity) return -RELIEFOS_ENOSPC; /* Keep RECOVER set between transactions. A clean journal with RECOVER * still set is recoverable; a live journal without it must not be exposed. */ int ret; @@ -444,15 +537,31 @@ static int ej_checkpoint(struct storage_volume *v) struct storage_ext4_journal *j=v->ext4.journal; if (!j || !j->committed) return 0; if (j->active || j->error) return -RELIEFOS_EBUSY; - for (uint32_t i=0;icount;i++) if (j->images[i].dirty) { - int ret=ej_io(v,j->images[i].block,1,j->images[i].after,true); + uint32_t bs=v->ext4.block_size; + for (uint32_t i=0;icount;) { + struct ext4_journal_image *image=&j->images[i++]; + if (!image->dirty) continue; + uint32_t count=1; + while (icount && countimages[i]; + if (!next->dirty || next->block<=image->block || + next->block-image->block!=count) break; + storage_memcpy(ej_payload+(size_t)count*bs,next->after,bs); + ++count; ++i; + } + uint8_t *data=image->after; + if (count>1) { + storage_memcpy(ej_payload,data,bs); + data=ej_payload; + } + int ret=ej_io(v,image->block,count,data,true); if (ret<0) return ej_fail(v,ret); } int ret=storage_ext4_device_flush(v); if (ret<0) return ej_fail(v,ret); ret=ej_super_write(v,0,j->sequence+1,j->head); if (ret<0) return ej_fail(v,ret); ret=storage_ext4_device_flush(v); if (ret<0) return ej_fail(v,ret); for (uint32_t i=0;icount;i++) storage_ext4_cache_finish(v,j->images[i].block,j->images[i].after); - ++j->sequence; j->start=0; j->count=0; j->committed=false; return 0; + ++j->sequence; j->start=0; j->count=0; j->committed=false; j->ordered=false; return 0; } /** @copydoc storage_ext4_journal_checkpoint */ diff --git a/fs/ext_common/native.c b/fs/ext_common/native.c index 8a55aaac..7e75547b 100644 --- a/fs/ext_common/native.c +++ b/fs/ext_common/native.c @@ -511,6 +511,7 @@ const struct storage_filesystem_ops storage_ext_ops={ #endif .fallocate=ext_native_fallocate, .sync=storage_ext4_sync, + .writeback=storage_ext4_journal_writeback, .invalidate_write=ext_native_invalidate_write, .create=ext_native_create, .create_device=ext_native_create_device, diff --git a/fs/ext_common/ops.c b/fs/ext_common/ops.c index 72704d04..f19b44e2 100644 --- a/fs/ext_common/ops.c +++ b/fs/ext_common/ops.c @@ -355,6 +355,7 @@ static int ext4_ops_truncate(struct storage_volume *v,uint64_t ino,uint64_t size if (!no_data && size%bs) ret=ext4_ops_zero_edge(v,ino,size,(size/bs+1)*bs); if (no_data && !size) storage_memzero(in.i_block_raw,60); if (!ret) { in.size=size; ext4_ops_touch(&in); ret=storage_ext4_orphan_add(v,ino,&in); } + if (!ret && v->ext4.journal) v->ext4.order_on_stop=true; ret=ext4_ops_stop(&h,ret); if (ret<0) return ret; uint64_t end=EXT4_MAX_LOGICAL_BLOCK+1ULL; if (!(in.flags&EXT4_EXTENTS_FL)) { diff --git a/fs/ext_common/storage_ext4_types.h b/fs/ext_common/storage_ext4_types.h index 1fa0c472..5159ca1b 100644 --- a/fs/ext_common/storage_ext4_types.h +++ b/fs/ext_common/storage_ext4_types.h @@ -218,6 +218,15 @@ struct storage_ext4_handle { bool active; }; #define EXT4_JOURNAL_CREDITS 32u + +/* A bounded truncate slice removes at most 32 data blocks plus tree nodes. + * Within one edit, physical frees stay unavailable for reallocation until + * the edit and its group are durable. */ +#define EXT4_JOURNAL_FREE_RANGES (2u * EXT4_JOURNAL_CREDITS) +struct storage_ext4_free_range { + uint64_t first; + uint64_t end; +}; #define EXT4_INDEX_FL 0x1000u int storage_ext4_dir_hash(struct storage_volume *,const char *,unsigned,uint32_t *); struct storage_ext4_dirent { uint64_t ino; uint8_t type, name_len; char name[256]; }; @@ -261,6 +270,9 @@ struct storage_ext4_state { uint32_t backup_bgs[2]; uint8_t flex_log_groups; uint8_t fs_error; + bool order_on_stop; + uint32_t journal_free_count; + struct storage_ext4_free_range journal_frees[EXT4_JOURNAL_FREE_RANGES]; uint64_t next_goal_block; uint64_t reserved_window_end; uint64_t read_bytes, read_commands, read_blocks, read_cache_hits; diff --git a/fs/operations.h b/fs/operations.h index c3ecb754..eb243291 100644 --- a/fs/operations.h +++ b/fs/operations.h @@ -75,6 +75,9 @@ struct storage_filesystem_ops { const struct storage_node *parent,const char *name); int (*fallocate)(struct storage_volume *volume,struct storage_node *node,uint32_t mode,uint64_t offset,uint64_t length); int (*sync)(struct storage_volume *volume); + /* Optional deadline-driven writeback; native execution and exact volume + * ownership are held, with no pending resumable transport request. */ + int (*writeback)(struct storage_volume *volume,uint64_t now); #ifdef CONFIG_SWAP /* Exact provider mappings, borrowed only under the inode claim. */ int (*swap_extent)(struct storage_volume *volume,const struct storage_node *node, diff --git a/include/reliefnt/storage.h b/include/reliefnt/storage.h index 5f83a12b..ec164e6c 100644 --- a/include/reliefnt/storage.h +++ b/include/reliefnt/storage.h @@ -242,6 +242,12 @@ int storage_sync_volume(uint32_t volume_id); * Runtime tmpfs has no persistent writeback; namespace sync uses actual mounts. */ int storage_sync_all(void); +/** @brief Service due native writeback without taking over another task's I/O. + * @param now Current monotonic boot tick. + * Called from the permanent worker under execution ownership, without graph, + * module or transport locks. Active mounted volumes pin their providers. + */ +void storage_writeback_expired(uint64_t now); int storage_sync_disk(uint32_t disk_id); int storage_write_held_node(struct storage_node *node, uint64_t offset, const void *buffer, uint32_t length, uint32_t *written); diff --git a/kernel/workqueue/services.c b/kernel/workqueue/services.c index 1b31382f..3ae0e229 100644 --- a/kernel/workqueue/services.c +++ b/kernel/workqueue/services.c @@ -14,6 +14,8 @@ #include #include #include +#include +#include /** @brief Poll protocol timers/NIC work once per tick using existing budgets. * @param work Permanent protocol work. @param context Unused NULL. @@ -61,6 +63,15 @@ static void audio_work(struct kernel_work *work,void *context) */ static void network_rx_work(struct kernel_work *work,void *context) { (void)work;(void)context;net_poll_rx_budget(32); } +/** @brief Service aged metadata groups even when there are no later writers. + * @param work Permanent storage work. @param context Unused NULL. + */ +static void storage_work(struct kernel_work *work,void *context) +{ + (void)context;storage_writeback_expired(time_ticks()); + (void)kernel_queue_delayed_work(work,RELIEFNT_TICK_HZ); +} +static struct kernel_work storage=KERNEL_WORK_INIT(storage_work,NULL); static struct kernel_work network=KERNEL_WORK_INIT(network_work,NULL); static struct kernel_work services[]={ KERNEL_WORK_INIT(usb_work,NULL),KERNEL_WORK_INIT(vfs_work,NULL), @@ -71,12 +82,13 @@ static struct kernel_work services[]={ */ void kernel_deferred_request(enum kernel_deferred_service service) { if((unsigned)servicepoll(network_context, output,sizeof(output),&length)==-74 && !length); i=(i+1)%rx_count; rx[i].length=64; rx[i].status=3; rx[i].byte13=1; assert(network->poll(network_context, output,sizeof(output),&length)==-74 && !length); - REG(0x8)=0; assert(!network->is_ready(network_context)); + /* Readiness shares one hardware sample per tick, but TX still tests live carrier. */ + REG(0x8)=0; assert(network->is_ready(network_context)); assert(network->send(network_context, bytes,64)==-100); + ++tick; assert(!network->is_ready(network_context)); + REG(0x8)=2; assert(!network->is_ready(network_context)); + ++tick; assert(network->is_ready(network_context)); reset_stuck=1; e1000e_driver_module.fini(); assert(stop_error==-110 && live && maps==unmaps+1 && !(command&4)); @@ -289,6 +296,8 @@ int main(void) networks[0]->get_info(contexts[0],&first_info); networks[1]->get_info(contexts[1],&second_info); assert(first_info.slot==3 && second_info.slot==4 && memcmp(first_info.mac,second_info.mac,6)); + registers[1][0x8/4]=0; ++tick; + assert(!networks[1]->is_ready(contexts[1]) && networks[0]->is_ready(contexts[0])); active_registers=0; struct descriptor *first_rx=ring(0x2800); active_registers=1; struct descriptor *second_rx=ring(0x2800); assert(first_rx!=second_rx); diff --git a/tools/tests/ext4_dma_read_test.c b/tools/tests/ext4_dma_read_test.c index 267afecf..171af4bd 100644 --- a/tools/tests/ext4_dma_read_test.c +++ b/tools/tests/ext4_dma_read_test.c @@ -65,6 +65,8 @@ int storage_ext4_journal_capture(struct storage_volume *v, uint64_t block, const { (void)v; (void)block; (void)data; return 0; } int storage_ext4_journal_publish(struct storage_volume *v, uint64_t block, const uint8_t *data) { (void)v; (void)block; (void)data; return 0; } +bool storage_ext4_journal_read(const struct storage_volume *v,uint64_t block,void *out) +{ (void)v; (void)block; (void)out; return false; } bool storage_ext4_journal_owns(const struct storage_volume *v, uint64_t block) { (void)v; (void)block; return false; } diff --git a/tools/tests/ext4_journal_test.c b/tools/tests/ext4_journal_test.c index e48698c9..c2228819 100644 --- a/tools/tests/ext4_journal_test.c +++ b/tools/tests/ext4_journal_test.c @@ -11,6 +11,8 @@ static int fail_write_at = -1, device_failed; static int fail_flush_at = -1; static uint64_t flushes, last_flushed_writes; static uint32_t descriptor_sectors; +static uint64_t checkpoint_lba=UINT64_MAX; +static uint32_t checkpoint_sectors; static uint8_t *durable; int storage_write_device(const struct storage_volume *v, uint64_t lba, uint32_t n, const void *in) @@ -24,6 +26,7 @@ int storage_write_device(const struct storage_volume *v, uint64_t lba, if (raw[7]==1) descriptor_sectors=n; if (raw[7]==2) assert(last_flushed_writes == writes); /* Before commit. */ } + if (lba==checkpoint_lba) checkpoint_sectors=n; return ext4_fixture_write_device(v, lba, n, in); } int storage_ext4_device_flush(const struct storage_volume *v) @@ -207,27 +210,65 @@ int main(int argc,char **argv) } storage_ext4_journal_close(&volume); invalidate(); } - /* Model consecutive small-file metadata changes. A new operation still - * checkpoints the previous one, but does not mark a live volume clean. */ + /* Ordinary operations share a durable group, while a failed + * operation can only undo its own changes to that group. */ memcpy(disk,initial,disk_len); load_geometry(); memcpy(durable,initial,disk_len); writes=flushes=last_flushed_writes=0; assert(storage_ext4_journal_open(&volume)==0); - assert(storage_ext4_journal_start(&volume,2,&handle)==0); for (unsigned i=0;i<2;i++) { + assert(storage_ext4_journal_start(&volume,2,&handle)==0); + assert(flushes==0); assert(storage_ext4_cache_get(&volume,target,&cache,true)==0); cache[0]=(uint8_t)(0x40+i); assert(storage_ext4_cache_mark_dirty(&volume,target)==0); assert(storage_ext4_journal_stop(&handle)==0); - assert(storage_ext4_journal_start(&volume,2,&handle)==0); - assert(flushes==5+4*i); - assert(durable[target*bs]==0x40+i && !be32(durable+jb*bs+28)); - assert(ext4_get_le32(durable+1024+96)&EXT4_FEATURE_INCOMPAT_RECOVER); } - assert(storage_ext4_journal_stop(&handle)==0); + assert(storage_ext4_journal_start(&volume,2,&handle)==0); + assert(storage_ext4_cache_get(&volume,target,&cache,true)==0); + cache[0]=0x42; + assert(storage_ext4_cache_mark_dirty(&volume,target)==0); + assert(storage_ext4_cache_get(&volume,target+1,&cache,true)==0); + cache[0]^=0xff; + assert(storage_ext4_cache_mark_dirty(&volume,target+1)==0); + storage_ext4_journal_abort(&handle,-RELIEFOS_EIO); + assert(storage_ext4_journal_stop(&handle)==-RELIEFOS_EIO); + assert(durable[target*bs]==initial[target*bs] && !memcmp(disk,initial,disk_len)); + uint8_t *pair=malloc(2*bs); assert(pair); + assert(storage_ext4_cache_read_blocks(&volume,target,2,pair)==0); + assert(pair[0]==0x41 && !memcmp(pair+bs,initial+(target+1)*bs,bs)); + free(pair); + assert(storage_ext4_journal_commit(&volume,true)==0); assert(storage_ext4_journal_checkpoint(&volume)==0); - assert(flushes==10 && !be32(durable+jb*bs+28)); + assert(flushes==6 && durable[target*bs]==0x41 && !be32(durable+jb*bs+28)); assert(!(ext4_get_le32(durable+1024+96)&EXT4_FEATURE_INCOMPAT_RECOVER)); storage_ext4_journal_close(&volume); invalidate(); + /* A quiet filesystem still checkpoints an aged group. Prove that the + * old after-image remains authoritative after the shared cache is evicted. */ + memcpy(disk,initial,disk_len); load_geometry(); + memcpy(durable,initial,disk_len); writes=flushes=last_flushed_writes=0; + assert(storage_ext4_journal_open(&volume)==0); + codec_ticks=100; + assert(storage_ext4_journal_start(&volume,2,&handle)==0); + assert(storage_ext4_cache_get(&volume,target,&cache,true)==0); + cache[0]=0x43; + assert(storage_ext4_cache_mark_dirty(&volume,target)==0); + assert(storage_ext4_journal_stop(&handle)==0); + assert(storage_ext4_journal_start(&volume,2,&handle)==0); + assert(storage_ext4_cache_get(&volume,target+1,&cache,true)==0); + assert(storage_ext4_cache_mark_dirty(&volume,target+1)==0); + assert(storage_ext4_journal_stop(&handle)==0); + invalidate(); + assert(storage_ext4_cache_read(&volume,target,next)==0 && next[0]==0x43); + assert(storage_ext4_journal_writeback(&volume,codec_ticks+5*RELIEFNT_TICK_HZ-1)==0); + assert(!writes && !flushes && durable[target*bs]==old[0]); + checkpoint_lba=target*(bs/512); + assert(storage_ext4_journal_writeback(&volume,codec_ticks+5*RELIEFNT_TICK_HZ)==0); + assert(checkpoint_sectors==2*(bs/512)); + checkpoint_lba=UINT64_MAX; + assert(flushes==5 && durable[target*bs]==0x43 && !be32(durable+jb*bs+28)); + assert(ext4_get_le32(durable+1024+96)&EXT4_FEATURE_INCOMPAT_RECOVER); + codec_ticks=0; + storage_ext4_journal_close(&volume); invalidate(); memcpy(disk,initial,disk_len); load_geometry(); assert(storage_ext4_journal_open(&volume)==0); assert(storage_ext4_journal_start(&volume,1,&handle)==0); @@ -249,7 +290,18 @@ int main(int argc,char **argv) assert(storage_ext4_journal_stop(&handle)==-RELIEFOS_EIO); assert(volume.ext4.super_view.free_blocks_count==free_before && !memcmp(disk,initial,disk_len)); assert(storage_ext4_alloc_blocks(&volume,target+16,3,&allocated_first,&allocated_count)==0); + assert(storage_ext4_journal_start(&volume,EXT4_JOURNAL_CREDITS,&handle)==0); assert(storage_ext4_free_blocks(&volume,allocated_first,allocated_count)==0); + uint64_t second; + uint32_t second_count; + assert(storage_ext4_alloc_blocks(&volume,allocated_first,3,&second,&second_count)==0); + assert(second_count==3 && (second>=allocated_first+3 || second+3<=allocated_first)); + assert(storage_ext4_free_blocks(&volume,second,second_count)==0); + assert(storage_ext4_journal_stop(&handle)==0); + uint64_t before_reuse=flushes; + assert(storage_ext4_journal_start(&volume,EXT4_JOURNAL_CREDITS,&handle)==0); + assert(flushes>before_reuse); + assert(storage_ext4_journal_stop(&handle)==0); assert(storage_ext4_journal_commit(&volume,true)==0); /* The data block is not part of the allocation transaction. Checkpoint * must preserve its cache hit but not the superblock's stale RECOVER bit. */ diff --git a/tools/tests/ext4_read_batch_resume_test.c b/tools/tests/ext4_read_batch_resume_test.c index cb9b2507..69d40ccb 100644 --- a/tools/tests/ext4_read_batch_resume_test.c +++ b/tools/tests/ext4_read_batch_resume_test.c @@ -52,6 +52,8 @@ int storage_ext4_journal_capture(struct storage_volume *v, uint64_t block, const { (void)v; (void)block; (void)data; return 0; } int storage_ext4_journal_publish(struct storage_volume *v, uint64_t block, const uint8_t *data) { (void)v; (void)block; (void)data; return 0; } +bool storage_ext4_journal_read(const struct storage_volume *v,uint64_t block,void *out) +{ (void)v; (void)block; (void)out; return false; } bool storage_ext4_journal_owns(const struct storage_volume *v, uint64_t block) { (void)v; (void)block; return false; } diff --git a/tools/tests/ext4_write_batch_transport_test.c b/tools/tests/ext4_write_batch_transport_test.c index 35299781..944e3e22 100644 --- a/tools/tests/ext4_write_batch_transport_test.c +++ b/tools/tests/ext4_write_batch_transport_test.c @@ -48,6 +48,8 @@ int storage_ext4_journal_capture(struct storage_volume *v, uint64_t block, const { (void)v; (void)block; (void)data; return 0; } int storage_ext4_journal_publish(struct storage_volume *v, uint64_t block, const uint8_t *data) { (void)v; (void)block; (void)data; return 0; } +bool storage_ext4_journal_read(const struct storage_volume *v,uint64_t block,void *out) +{ (void)v; (void)block; (void)out; return false; } bool storage_ext4_journal_owns(const struct storage_volume *v, uint64_t block) { (void)v; (void)block; return false; } diff --git a/tools/tests/storage_codec_context_fixture.h b/tools/tests/storage_codec_context_fixture.h index 002c3ec4..2fa46d22 100644 --- a/tools/tests/storage_codec_context_fixture.h +++ b/tools/tests/storage_codec_context_fixture.h @@ -4,6 +4,9 @@ #ifndef RELIEFNT_STORAGE_CODEC_CONTEXT_FIXTURE_H #define RELIEFNT_STORAGE_CODEC_CONTEXT_FIXTURE_H #include +#include +static uint64_t codec_ticks; +uint64_t time_ticks(void) { return codec_ticks; } static struct storage_io_context codec_io_context; void storage_kernel_context_enter(struct storage_io_context *saved) { diff --git a/tools/tests/storage_mkdir_mount_test.c b/tools/tests/storage_mkdir_mount_test.c index 47a417de..5a844b31 100644 --- a/tools/tests/storage_mkdir_mount_test.c +++ b/tools/tests/storage_mkdir_mount_test.c @@ -212,7 +212,12 @@ void x86_64_outb(uint8_t value, uint16_t port) { (void)value; (void)port; abort( void x86_64_outw(uint16_t value, uint16_t port) { (void)value; (void)port; abort(); } void x86_64_insw(uint16_t port, void *buffer, size_t count) { (void)port; (void)buffer; (void)count; abort(); } void x86_64_outsw(uint16_t port, const void *buffer, size_t count) { (void)port; (void)buffer; (void)count; abort(); } -uint64_t time_ticks(void) { abort(); } +static uint64_t test_ticks; +uint64_t time_ticks(void) { return test_ticks; } +/** @brief Reject controller IRQ waits; this fixture only uses memory disks. + * @param deadline Controller timeout tick. + */ +void storage_wait_hint(uint64_t deadline) { (void)deadline; abort(); } static uint64_t test_wall_seconds=1800000000; int time_wall_clock(struct reliefos_time_info *info) { *info = (struct reliefos_time_info){.unix_seconds = test_wall_seconds}; return 0; } From f03a0a7a62ef3d210db5fdbd009771c8d4d27e54 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Tue, 1 Dec 2026 19:03:36 +0800 Subject: [PATCH 87/97] perf(kernel): cut console and storage overhead during boot --- Documentation/admin-guide/boot.rst | 7 ++ Documentation/core-api/network-devices.rst | 4 +- drivers/console/core.c | 1 + drivers/console/internal.h | 18 ++- drivers/console/panic.c | 1 + drivers/console/render.c | 109 ++++++++++++++---- drivers/console/vt.c | 74 ++++-------- drivers/net/e1000/e1000_main.c | 30 ++++- drivers/storage/ahci/storage_ahci.c | 35 +++--- fs/ext_common/cache.c | 124 ++++++++++++--------- fs/vfs/mount.c | 12 ++ fs/vfs/storage_initial.c | 6 +- include/reliefnt/storage.h | 11 +- kernel/init/kernel.c | 14 ++- tools/tests/console_replay_test.c | 7 +- tools/tests/e1000_init_test.c | 18 ++- tools/tests/ext4_mount_test.c | 23 ++-- tools/tests/ext4_read_batch_resume_test.c | 11 +- tools/tests/mount_backend_test.c | 12 +- 19 files changed, 325 insertions(+), 192 deletions(-) diff --git a/Documentation/admin-guide/boot.rst b/Documentation/admin-guide/boot.rst index 3050f308..9d816d49 100644 --- a/Documentation/admin-guide/boot.rst +++ b/Documentation/admin-guide/boot.rst @@ -35,3 +35,10 @@ COM1 使用 115200 波特、8N1。早期启动和 panic 使用有界轮询。进 ``/dev/ttyS0`` 时,阻塞写等待可用空间,非阻塞写在无法接收任何字节时返回 ``EAGAIN``。关闭或重启系统前会尝试发送队列中的数据。 文字控制台使用现有 framebuffer 字形、pitch 和原生 RGB 转换,可处理带行间填充的帧缓冲。 +可见文本在普通内存中绘制、滚动并更新光标,随后只向显存写入变动区域。 +分配失败时使用直接绘制。panic 使用直接绘制以避免进入常规显示锁。 + +当 ``reliefos.direct_root=1`` 与明确的 ``root=PARTUUID=...`` 同时存在时, +内核优先尝试用内置驱动挂载 ext4 根。成功后直接执行真实根的 init, +把 ESP 和 ``/boot`` 的挂载交给用户态。无法挂载指定 ext4 根时加载预置 +initramfs。未设置该选项时采用常规启动顺序。 diff --git a/Documentation/core-api/network-devices.rst b/Documentation/core-api/network-devices.rst index 6f364aac..23529d53 100644 --- a/Documentation/core-api/network-devices.rst +++ b/Documentation/core-api/network-devices.rst @@ -19,8 +19,8 @@ Device identity 驱动关闭回调接入、排空引用并停止自身全部设备后,管理器移除对应接口。 停止失败的设备保留 DMA 和模块代码,后续卸载可以重试。 -e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO -寄存器。实际发送仍检查当前链路,驱动没有关闭收包轮询或协议定时器。 +e1000 和 e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO +寄存器。e1000e 发送前另行检查当前链路。收包轮询和协议定时器照常运行。 旧 ``e1000_*`` 服务入口和 ReliefOS 旧网络管理请求查询首个存活接口。 旧驱动 API 表和公开用户结构继续使用原布局。新设备接口属于 ReliefNT 私有 diff --git a/drivers/console/core.c b/drivers/console/core.c index d3eee376..6dc3ce2e 100644 --- a/drivers/console/core.c +++ b/drivers/console/core.c @@ -163,6 +163,7 @@ void console_enable_framebuffer(void) return; } fb_console_enabled = true; + fb_console_buffer_visible(); fb_console_initialize_fullscreen(); fb_console_clear_log(); for (size_t i = console_log_replay_start(); i < log_len; ++i) { diff --git a/drivers/console/internal.h b/drivers/console/internal.h index c24761fe..31571f6c 100644 --- a/drivers/console/internal.h +++ b/drivers/console/internal.h @@ -252,10 +252,26 @@ extern bool fb_ansi_private; /** * @brief Return the framebuffer currently used by the text renderer. - * @return The temporary replay surface, or the active framebuffer. + * @return The temporary replay surface, visible text buffer, or framebuffer. */ const struct framebuffer *fb_console_framebuffer(void); +/** @brief Allocate a RAM surface matching a validated display layout. + * @param frame Receives the owned surface on success. @param display Layout to copy. + * @return True on allocation success. Caller initializes the visible pixels. + */ +bool fb_console_allocate_surface(struct framebuffer *frame, const struct framebuffer *display); + +/** @brief Prepare RAM for a full repaint of the visible text console. + * Serialized by the console owner. Allocation failure keeps direct rendering. + */ +void fb_console_buffer_visible(void); + +/** @brief Flush pending text pixels and return to direct panic rendering. + * No allocation, free, or framebuffer damage locks. + */ +void fb_console_panic_direct(void); + uint32_t console_panel(void); uint32_t console_fg(void); diff --git a/drivers/console/panic.c b/drivers/console/panic.c index 990374e9..801a0448 100644 --- a/drivers/console/panic.c +++ b/drivers/console/panic.c @@ -74,6 +74,7 @@ struct console_panic_context console_panic_begin(void) state->charset[0] = state->charset[1] = state->charset_bank = 0; } if (usable && !context.graphical) fb_console_hide_tty_cursor(); + fb_console_panic_direct(); console_boot_logo_active = false; console_vt_graphical = false; fb_console_tty_cursor_active = fb_console_tty_cursor_visible = false; diff --git a/drivers/console/render.c b/drivers/console/render.c index 0b2bcfee..6f36c3c9 100644 --- a/drivers/console/render.c +++ b/drivers/console/render.c @@ -37,6 +37,77 @@ static uint32_t fb_console_tty_cursor_pitch; static uint8_t fb_console_tty_cursor_bpp; static uint8_t fb_console_tty_cursor_saved[FB_CONSOLE_CURSOR_BYTES]; static struct framebuffer_damage fb_console_damage; +static struct framebuffer visible_text; +static const uint32_t *visible_output; + +/** @brief Check whether the buffered text is still bound to this display mode. + * @param display Live framebuffer descriptor. @return True for a usable buffer. + */ +static bool fb_console_buffer_matches(const struct framebuffer *display) +{ + return visible_text.pixels && visible_output && display->available && + visible_output == display->pixels && visible_text.width == display->width && + visible_text.height == display->height && visible_text.pitch == display->pitch && + visible_text.bpp == display->bpp && visible_text.bytes_per_pixel == display->bytes_per_pixel && + visible_text.red_field_position == display->red_field_position && + visible_text.red_mask_size == display->red_mask_size && + visible_text.green_field_position == display->green_field_position && + visible_text.green_mask_size == display->green_mask_size && + visible_text.blue_field_position == display->blue_field_position && + visible_text.blue_mask_size == display->blue_mask_size; +} + +void fb_console_buffer_visible(void) +{ + const struct framebuffer *display = framebuffer_get(); + if (fb_console_buffer_matches(display)) return; + if (visible_text.pixels) kernel_free(visible_text.pixels); + visible_text = (struct framebuffer){0}; + visible_output = NULL; + fb_console_damage = (struct framebuffer_damage){0}; + if (fb_console_allocate_surface(&visible_text, display)) + visible_output = display->pixels; +} + +/** @brief Copy an exact nonoverlapping pixel span in word-sized writes. + * @param destination Writable RAM or framebuffer bytes. @param source Readable bytes. + * @param bytes Exact span including a possible unaligned tail. No SIMD state is used. + */ +static void fb_console_copy_pixels(uint8_t *destination, const uint8_t *source, size_t bytes) +{ + size_t words = bytes / sizeof(uint64_t); + size_t tail = bytes % sizeof(uint64_t); + __asm__ volatile("cld; rep movsq" + : "+D"(destination), "+S"(source), "+c"(words) : : "memory", "cc"); + __asm__ volatile("rep movsb" + : "+D"(destination), "+S"(source), "+c"(tail) : : "memory", "cc"); +} + +/** @brief Write changed RAM pixels to the display, without reading from VRAM. + * @param display Live output descriptor. @param damage Clipped drawing rectangle. + */ +static void fb_console_blit(const struct framebuffer *display, struct framebuffer_damage damage) +{ + if (!fb_console_buffer_matches(display) || damage.x1 >= damage.x2 || + damage.y1 >= damage.y2 || damage.x2 > display->width || + damage.y2 > display->height) + return; + size_t offset = (size_t)damage.x1 * display->bytes_per_pixel; + size_t bytes = (size_t)(damage.x2 - damage.x1) * display->bytes_per_pixel; + for (uint32_t row = damage.y1; row < damage.y2; ++row) { + uint8_t *destination = (uint8_t *)display->pixels + (size_t)row * display->pitch; + const uint8_t *source = (const uint8_t *)visible_text.pixels + (size_t)row * visible_text.pitch; + fb_console_copy_pixels(destination + offset, source + offset, bytes); + } +} + +void fb_console_panic_direct(void) +{ + if (!console_vt_graphical) + fb_console_blit(framebuffer_get(), fb_console_damage); + visible_output = NULL; + fb_console_damage = (struct framebuffer_damage){0}; +} /** @brief Merge visible text damage; replay and fatal rendering publish separately. */ void fb_console_mark_damage(uint32_t x, uint32_t y, uint32_t w, uint32_t h) @@ -56,16 +127,19 @@ void fb_console_publish_damage(void) if (!fb_console_damage.x2 || fb_console_render_target) return; struct framebuffer_damage damage = fb_console_damage; fb_console_damage = (struct framebuffer_damage){0}; + fb_console_blit(framebuffer_get(), damage); framebuffer_present_region(damage.x1, damage.y1, damage.x2 - damage.x1, damage.y2 - damage.y1); } /** * @brief Return the framebuffer currently used by the text renderer. - * @return The temporary replay surface, or the active framebuffer. + * @return The staging surface, matching RAM buffer, or live framebuffer. */ const struct framebuffer *fb_console_framebuffer(void) { - return fb_console_render_target ? fb_console_render_target : framebuffer_get(); + if (fb_console_render_target) return fb_console_render_target; + const struct framebuffer *display = framebuffer_get(); + return !console_vt_graphical && fb_console_buffer_matches(display) ? &visible_text : display; } /** @@ -79,12 +153,8 @@ const struct framebuffer *fb_console_framebuffer(void) static void fb_console_rect(uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint32_t color) { - if (fb_console_render_target) { - framebuffer_rect_to(fb_console_render_target, x, y, width, height, color); - } else { - framebuffer_rect(x, y, width, height, color); - fb_console_mark_damage(x, y, width, height); - } + framebuffer_rect_to(fb_console_framebuffer(), x, y, width, height, color); + fb_console_mark_damage(x, y, width, height); } /** @@ -98,13 +168,9 @@ static void fb_console_rect(uint32_t x, uint32_t y, uint32_t width, static void fb_console_codepoint(uint32_t x, uint32_t y, uint32_t cp, uint32_t fg, uint32_t bg) { - if (fb_console_bold) { - framebuffer_codepoint_bold_to(fb_console_framebuffer(), x, y, cp, fg, bg); - } else if (fb_console_render_target) { - framebuffer_codepoint_to(fb_console_render_target, x, y, cp, fg, bg); - } else { - framebuffer_codepoint(x, y, cp, fg, bg); - } + const struct framebuffer *target = fb_console_framebuffer(); + if (fb_console_bold) framebuffer_codepoint_bold_to(target, x, y, cp, fg, bg); + else framebuffer_codepoint_to(target, x, y, cp, fg, bg); } uint32_t console_panel(void) @@ -226,13 +292,14 @@ void fb_console_show_tty_cursor(void) /** * @brief Scroll an entire ANSI request with one copy of the retained rows. - * @param lines Number of text rows to move up. + * @param top First text row. @param bottom Inclusive last text row. + * @param lines Number of text rows to move. @param reverse True to scroll down. * @par Context * Caller serializes console state and retains the current rendering surface. * Rows move upward, preserving padding and pixels outside the clipped region. * Uses exact forward scalar word copies with a byte tail; no allocation, - * SIMD state or cache-attribute change. Full VRAM words avoid a separately - * emulated uncached read/write for each byte on hardware-assisted VMs. + * SIMD state or cache-attribute change. Active text normally scrolls in RAM; + * full words also limit uncached access on the direct-rendering fallback. * Forward reads precede their matching stores; upward row order preserves overlap. */ void fb_console_scroll_region(uint32_t top, uint32_t bottom, uint32_t lines, bool reverse) @@ -267,13 +334,9 @@ void fb_console_scroll_region(uint32_t top, uint32_t bottom, uint32_t lines, boo const uint8_t *src = (const uint8_t *)fb->pixels + (uint64_t)(src_y + y) * fb->pitch + (uint64_t)fb_x * fb->bytes_per_pixel; - size_t words = bytes / sizeof(uint64_t), tail = bytes % sizeof(uint64_t); /* x86 permits unaligned scalar words; neither operation crosses the * exact clipped extent, including 24-bit/padded framebuffer layouts. */ - __asm__ volatile("cld; rep movsq" - : "+D"(dst), "+S"(src), "+c"(words) : : "memory", "cc"); - __asm__ volatile("rep movsb" - : "+D"(dst), "+S"(src), "+c"(tail) : : "memory", "cc"); + fb_console_copy_pixels(dst, src, bytes); } uint32_t first_y = fb_y + top * RELIEFOS_FONT_H; diff --git a/drivers/console/vt.c b/drivers/console/vt.c index 0f602027..ee04e258 100644 --- a/drivers/console/vt.c +++ b/drivers/console/vt.c @@ -1,14 +1,5 @@ #include "internal.h" -/** - * @brief Allocate a same-layout RAM surface for one fullscreen text replay. - * @param target Receives a copy of the active framebuffer descriptor. - * @param pixels Receives the allocated backing storage on success. - * @return True when a valid surface was allocated. - */ -static bool fb_console_allocate_replay_target(struct framebuffer *target, - uint8_t **pixels); - /** * @brief Save the graphical framebuffer before a text VT paints over it. */ @@ -57,8 +48,7 @@ static struct console_vt_surface *fb_console_vt_surface(uint32_t number) return surface; if (surface->frame.pixels) kernel_free(surface->frame.pixels); *surface = (struct console_vt_surface){0}; - uint8_t *pixels; - if (!fb_console_allocate_replay_target(&surface->frame, &pixels)) return NULL; + if (!fb_console_allocate_surface(&surface->frame, active)) return NULL; return surface; } @@ -132,9 +122,7 @@ static void fb_console_save_active_text(void) if (!console_active_vt || console_vt_graphical || !fb_console_enabled) return; struct console_vt_surface *surface = fb_console_vt_surface(console_active_vt); if (!surface) return; - const struct framebuffer *active = framebuffer_get(); - __builtin_memcpy(surface->frame.pixels, active->pixels, - (size_t)active->pitch * active->height); + fb_console_copy_surface(&surface->frame, fb_console_framebuffer()); fb_console_state_save(&surface->state); surface->initialized = true; } @@ -196,43 +184,27 @@ static void fb_console_write_background(uint32_t number, const char *bytes, size } /** - * @brief Allocate a same-layout RAM surface for one fullscreen text replay. - * @param target Receives a copy of the active framebuffer descriptor. - * @param pixels Receives the allocated backing storage on success. - * @return True when a valid surface was allocated. + * @brief Allocate visible or staged text pixels in ordinary RAM. + * @param frame Receives the layout and allocation. + * @param display Live framebuffer layout without ownership transfer. + * @return True when allocation succeeds and the caller can paint the surface. */ -static bool fb_console_allocate_replay_target(struct framebuffer *target, - uint8_t **pixels) +bool fb_console_allocate_surface(struct framebuffer *frame, const struct framebuffer *display) { - const struct framebuffer *active = framebuffer_get(); uint64_t visible_row_bytes; uint64_t allocation_bytes; - uint8_t *storage; - if (!target || !pixels) { - return false; - } - *pixels = NULL; - if (!active->available || !active->pixels || - !active->width || !active->height || - (active->bytes_per_pixel != 3u && active->bytes_per_pixel != 4u)) { + if (!display->available || !display->pixels || !display->width || + !display->height || (display->bytes_per_pixel != 3u && display->bytes_per_pixel != 4u)) return false; - } - visible_row_bytes = (uint64_t)active->width * active->bytes_per_pixel; - if (active->pitch < visible_row_bytes) { + visible_row_bytes = (uint64_t)display->width * display->bytes_per_pixel; + allocation_bytes = (uint64_t)display->pitch * display->height; + if (display->pitch < visible_row_bytes || allocation_bytes > SIZE_MAX) return false; - } - allocation_bytes = (uint64_t)active->pitch * active->height; - if (!allocation_bytes || allocation_bytes > (uint64_t)(size_t)-1) { - return false; - } - storage = kernel_malloc((size_t)allocation_bytes); - if (!storage) { - return false; - } - *target = *active; - target->pixels = (uint32_t *)(void *)storage; - *pixels = storage; + uint32_t *pixels = kernel_malloc((size_t)allocation_bytes); + if (!pixels) return false; + *frame = *display; + frame->pixels = pixels; return true; } @@ -360,25 +332,17 @@ void console_vt_activate(uint32_t number, bool graphical) console_present(); return; } + fb_console_buffer_visible(); struct console_vt_surface *surface = fb_console_vt_surface(number); if (surface) fb_console_render_target = &surface->frame; if (surface && surface->initialized) fb_console_state_restore(&surface->state); else fb_console_replay_terminal(number); surface = fb_console_vt_surface(number); + fb_console_render_target = NULL; if (surface) { fb_console_state_save(&surface->state); surface->initialized = true; - const struct framebuffer *active = framebuffer_get(); - size_t visible_row_bytes = - (size_t)active->width * active->bytes_per_pixel; - for (uint32_t row = 0; row < active->height; ++row) { - uint8_t *destination = (uint8_t *)active->pixels + - (uint64_t)row * active->pitch; - const uint8_t *source = (const uint8_t *)surface->frame.pixels + - (uint64_t)row * surface->frame.pitch; - __builtin_memcpy(destination, source, visible_row_bytes); - } - fb_console_render_target = NULL; + fb_console_copy_surface(fb_console_framebuffer(), &surface->frame); } const struct framebuffer *active = framebuffer_get(); fb_console_mark_damage(0, 0, active->width, active->height); diff --git a/drivers/net/e1000/e1000_main.c b/drivers/net/e1000/e1000_main.c index 2bc12f53..c89f46c9 100644 --- a/drivers/net/e1000/e1000_main.c +++ b/drivers/net/e1000/e1000_main.c @@ -2,6 +2,7 @@ #include #include +#include #include static const struct reliefos_driver_kernel_api *kernel_api; @@ -55,6 +56,7 @@ static void e1000_log(enum console_log_level level, const char *message) #define E1000_REGISTER_BYTES (E1000_REG_RAH + sizeof(uint32_t)) #define E1000_CTRL_SLU (1u << 6) #define E1000_CTRL_RST (1u << 26) +#define E1000_STATUS_LINK (1u << 1) #define E1000_RCTL_EN (1u << 1) #define E1000_RCTL_UPE (1u << 3) @@ -133,6 +135,10 @@ struct e1000_state { uint8_t *tx_buf[E1000_TX_COUNT]; uint32_t rx_index; uint32_t tx_tail; + struct kernel_spinlock carrier_lock; + uint64_t carrier_tick; + bool carrier_valid; + bool carrier_up; uint8_t mac[6]; }; @@ -391,10 +397,30 @@ static void e1000_hardware_init(struct e1000_state *d) e1000_log(CONSOLE_LOG_INFO, "descriptor rings initialized; hardware MAC loaded"); } +/** + * @brief Report link readiness using at most one STATUS read per tick. + * @param context Pinned controller whose callbacks are still admitted. + * @return Nonzero for carrier up. A caller without a tick service reads the + * register directly; polling and descriptor handling otherwise remain independent. + */ static int e1000_device_is_ready(void *context) { - struct e1000_state *d=context; - return d->active && (e1000_reg_read(d, E1000_REG_STATUS) & (1u << 1)); + struct e1000_state *d = context; + if (!d->active) return 0; + if (!kernel_api->ticks) + return (e1000_reg_read(d, E1000_REG_STATUS) & E1000_STATUS_LINK) != 0; + + uint64_t flags; + kernel_spin_lock_irqsave(&d->carrier_lock, &flags); + uint64_t now = kernel_api->ticks(); + if (!d->carrier_valid || d->carrier_tick != now) { + d->carrier_up = (e1000_reg_read(d, E1000_REG_STATUS) & E1000_STATUS_LINK) != 0; + d->carrier_tick = now; + d->carrier_valid = true; + } + bool up = d->carrier_up; + kernel_spin_unlock_irqrestore(&d->carrier_lock, flags); + return up; } static const uint8_t *e1000_device_mac(void *context) diff --git a/drivers/storage/ahci/storage_ahci.c b/drivers/storage/ahci/storage_ahci.c index 3b945f31..8b43cce7 100644 --- a/drivers/storage/ahci/storage_ahci.c +++ b/drivers/storage/ahci/storage_ahci.c @@ -42,18 +42,21 @@ static int ahci_async_fast_poll_idle(struct ahci_hba_port *port) return -RELIEFOS_EAGAIN; } -/** @brief Briefly wait for slot-zero hardware completion, without consuming data. +/** @brief Wait for slot zero with bounded, less frequent error-register polling. * @param port Stable mapped port under transport exclusion. + * @param limit Maximum polls for the caller's synchronous or async budget. * @return Zero for completion, -EIO for TFES, or -EAGAIN while hardware owns CI. + * The caller always checks final interrupt status before accepting data. */ -static int ahci_async_fast_poll_command(struct ahci_hba_port *port) +static int ahci_poll_command(struct ahci_hba_port *port, uint32_t limit) { - for (uint32_t i = 0; i < AHCI_ASYNC_FAST_POLL_SPINS; ++i) { - if (ahci_interrupt_status(port) & AHCI_PORT_ERROR_MASK) return -5; + for (uint32_t i = 0; i < limit; ++i) { if (!(port->ci & 1u)) return 0; + if ((i & 7u) == 0 && (ahci_interrupt_status(port) & AHCI_PORT_ERROR_MASK)) + return -5; ahci_cpu_relax(); } - return -RELIEFOS_EAGAIN; + return (ahci_interrupt_status(port) & AHCI_PORT_ERROR_MASK) ? -5 : -RELIEFOS_EAGAIN; } /** @brief Wait for the taskfile before preparing a command, preserving async retry. @@ -124,30 +127,22 @@ static int ahci_pending_poll(void *destination) struct ahci_hba_port *port = ahci_pending_command.port; struct ahci_port_dma *dma = ahci_pending_command.dma; if (!ahci_pending_command.active || !port) return -22; - if (ahci_interrupt_status(port) & AHCI_PORT_ERROR_MASK) goto failed; if (port->ci & 1u) { - if (!ahci_pending_command.write && storage_async_can_yield()) { - int result = ahci_async_fast_poll_command(port); - if (result != -RELIEFOS_EAGAIN) goto complete; - if (time_ticks() - ahci_pending_command.start_tick < AHCI_ASYNC_TIMEOUT_TICKS) { + bool asynchronous = !ahci_pending_command.write && storage_async_can_yield(); + int result = ahci_poll_command(port, asynchronous ? AHCI_ASYNC_FAST_POLL_SPINS : AHCI_WAIT_SPINS); + if (result == -5) goto failed; + if (result == -RELIEFOS_EAGAIN) { + if (asynchronous && + time_ticks() - ahci_pending_command.start_tick < AHCI_ASYNC_TIMEOUT_TICKS) { if(dma && dma->irq_enabled) storage_wait_hint(ahci_pending_command.start_tick+AHCI_ASYNC_TIMEOUT_TICKS); return -RELIEFOS_EAGAIN; } - ahci_log_pending_failure("timeout", port); + ahci_log_pending_failure(asynchronous ? "timeout" : "wait timeout", port); ahci_pending_clear(); return -5; } - for (uint32_t i = 0; i < AHCI_WAIT_SPINS; ++i) { - if (ahci_interrupt_status(port) & AHCI_PORT_ERROR_MASK) goto failed; - if (!(port->ci & 1u)) goto complete; - ahci_cpu_relax(); - } - ahci_log_pending_failure("wait timeout", port); - ahci_pending_clear(); - return -5; } -complete: if (ahci_interrupt_status(port) & AHCI_PORT_ERROR_MASK) goto failed; ahci_memory_barrier(); if (dma && dma->data.busy) { diff --git a/fs/ext_common/cache.c b/fs/ext_common/cache.c index b89368a9..d5d8d386 100644 --- a/fs/ext_common/cache.c +++ b/fs/ext_common/cache.c @@ -10,8 +10,9 @@ * macros with -D to exercise eviction at small scale. */ #ifndef EXT4_BLOCK_CACHE_ENTRIES -#define EXT4_BLOCK_CACHE_ENTRIES 64u +#define EXT4_BLOCK_CACHE_ENTRIES 512u #endif +#define EXT4_CACHE_SET_WAYS 64u #ifndef EXT4_INODE_CACHE_ENTRIES #define EXT4_INODE_CACHE_ENTRIES 64u #endif @@ -31,22 +32,26 @@ struct storage_ext4_cache_entry { uint8_t dirty; uint8_t pinned; uint8_t checksum_ok; - uint8_t data[EXT4_MAX_BLOCK_SIZE]; + uint8_t *data; }; struct ext4_cache_table { struct storage_ext4_cache_entry *entries; uint64_t age_clock; - uint32_t capacity; + uint32_t limit, capacity; uint64_t physical; uint32_t pages; }; +struct ext4_cache_set_range { + uint32_t first, end; +}; + static struct ext4_cache_table ext4_cache_tables[] = { - {.capacity = EXT4_BLOCK_CACHE_ENTRIES}, - {.capacity = EXT4_INODE_CACHE_ENTRIES}, - {.capacity = EXT4_DIR_CACHE_ENTRIES}, - {.capacity = EXT4_JOURNAL_CACHE_ENTRIES}, + {.limit = EXT4_BLOCK_CACHE_ENTRIES}, + {.limit = EXT4_INODE_CACHE_ENTRIES}, + {.limit = EXT4_DIR_CACHE_ENTRIES}, + {.limit = EXT4_JOURNAL_CACHE_ENTRIES}, }; #define EXT4_CACHE_TABLE_BLOCK 0 #define EXT4_CACHE_TABLE_COUNT \ @@ -87,6 +92,20 @@ int ext4_cache_block_range(const struct storage_volume *volume, uint64_t block, return 0; } +/** @brief Select one eviction set for an exact volume/block key. + * @param table Allocated cache domain. @param volume Borrowed instance. + * @param block Filesystem block. @return Half-open range of entry indices. + */ +static struct ext4_cache_set_range ext4_cache_set(const struct ext4_cache_table *table, + const struct storage_volume *volume, uint64_t block) +{ + uint32_t sets = (table->capacity + EXT4_CACHE_SET_WAYS - 1u) / EXT4_CACHE_SET_WAYS; + uint64_t key = block ^ (block >> 7) ^ ((uintptr_t)volume >> 6); + uint32_t first = (uint32_t)(key % sets) * EXT4_CACHE_SET_WAYS; + uint32_t end = first + EXT4_CACHE_SET_WAYS; + return (struct ext4_cache_set_range){first, end < table->capacity ? end : table->capacity}; +} + static struct storage_ext4_cache_entry *ext4_cache_lookup(struct ext4_cache_table *table, const struct storage_volume *volume, uint64_t block) @@ -94,7 +113,8 @@ static struct storage_ext4_cache_entry *ext4_cache_lookup(struct ext4_cache_tabl if (!table->entries) { return NULL; } - for (uint32_t i = 0; i < table->capacity; ++i) { + struct ext4_cache_set_range set = ext4_cache_set(table, volume, block); + for (uint32_t i = set.first; i < set.end; ++i) { struct storage_ext4_cache_entry *entry = &table->entries[i]; if (entry->valid && entry->volume == volume && entry->block == block && entry->volume_generation == volume->mount_generation) { @@ -111,29 +131,33 @@ static struct storage_ext4_cache_entry *ext4_cache_lookup(struct ext4_cache_tabl */ static bool ext4_cache_ensure(struct ext4_cache_table *table) { - size_t bytes; - uint64_t phys; - if (table->entries) { return true; } - bytes = sizeof(*table->entries) * (size_t)table->capacity; - /* Keep the bounded cache outside the fixed kernel image load region, as - * ext2_cache does; an allocation failure only disables caching. */ - phys = mm_alloc_pages((uint32_t)((bytes + 4095u) / 4096u)); - if (!phys) { - - return false; - } - table->entries = (struct storage_ext4_cache_entry *)mm_phys_to_virt(phys); - if (!table->entries) { - mm_free_pages(phys, (uint32_t)((bytes + 4095u) / 4096u)); - return false; + /* Keep lookup/alias scans on compact headers and off the payload pages. + * When contiguous storage is tight, retry with one original-size set. */ + uint32_t count = table->limit; + for (;;) { + size_t headers = sizeof(*table->entries) * count; + size_t bytes = headers + (size_t)count * EXT4_MAX_BLOCK_SIZE; + uint32_t pages = (uint32_t)((bytes + 4095u) / 4096u); + uint64_t phys = mm_alloc_pages(pages); + struct storage_ext4_cache_entry *entries = phys ? mm_phys_to_virt(phys) : NULL; + if (entries) { + storage_memzero(entries, headers); + uint8_t *data = (uint8_t *)entries + headers; + for (uint32_t i = 0; i < count; ++i) + entries[i].data = data + (size_t)i * EXT4_MAX_BLOCK_SIZE; + table->entries = entries; + table->capacity = count; + table->physical = phys; + table->pages = pages; + return true; + } + if (phys) mm_free_pages(phys, pages); + if (count <= EXT4_CACHE_SET_WAYS) return false; + count = EXT4_CACHE_SET_WAYS; } - storage_memzero(table->entries, bytes); - table->physical = phys; - table->pages = (uint32_t)((bytes + 4095u) / 4096u); - return true; } static int ext4_cache_write_back(const struct storage_volume *volume, @@ -175,22 +199,15 @@ static struct storage_ext4_cache_entry *ext4_cache_fill(struct ext4_cache_table return entry; } } - for (uint32_t i = 0; i < table->capacity; ++i) { - if (!table->entries[i].valid) { - victim = &table->entries[i]; + struct ext4_cache_set_range set = ext4_cache_set(table, volume, block); + for (uint32_t i = set.first; i < set.end; ++i) { + struct storage_ext4_cache_entry *entry = &table->entries[i]; + if (!entry->valid) { + victim = entry; break; } - } - if (!victim) { - for (uint32_t i = 0; i < table->capacity; ++i) { - struct storage_ext4_cache_entry *entry = &table->entries[i]; - if (entry->pinned) { - continue; - } - if (!victim || entry->age < victim->age) { - victim = entry; - } - } + if (!entry->pinned && (!victim || entry->age < victim->age)) + victim = entry; } if (!victim) { /* Capacity is full and every entry is pinned. */ @@ -293,7 +310,8 @@ static int ext4_cache_read_blocks(struct storage_volume *v, uint64_t first, ++v->ext4.read_commands; v->ext4.read_blocks += run; for (uint32_t j = 0; caching && j < run; ++j) { struct storage_ext4_cache_entry *victim = NULL; - for (uint32_t i = 0; i < table->capacity; ++i) { + struct ext4_cache_set_range set = ext4_cache_set(table, v, first + done + j); + for (uint32_t i = set.first; i < set.end; ++i) { struct storage_ext4_cache_entry *candidate = &table->entries[i]; if (!candidate->valid) { victim = candidate; break; } if (!candidate->pinned && !candidate->dirty && @@ -337,17 +355,6 @@ int storage_ext4_cache_read_blocks(struct storage_volume *v, uint64_t first, !info.max_blocks) return -RELIEFOS_EOPNOTSUPP; struct ext4_cache_table *table = &ext4_cache_tables[EXT4_CACHE_TABLE_BLOCK]; bool caching = ext4_cache_ensure(table); - uint32_t hits = 0; - for (uint32_t i = 0; caching && i < table->capacity; ++i) { - const struct storage_ext4_cache_entry *e = &table->entries[i]; - if (e->valid && e->volume == v && - e->volume_generation == v->mount_generation && - e->block >= first && e->block - first < count) ++hits; - } - if (hitsext4.journal) for (uint32_t i=0;i info.max_blocks || - count > EXT4_READAHEAD_BLOCKS || (hits && hits < count); + count > EXT4_READAHEAD_BLOCKS; + if (!synchronous && count > 1) { + bool first_cached = ext4_cache_lookup(table, v, first) || storage_ext4_journal_owns(v, first); + for (uint32_t i = 1; !synchronous && i < count; ++i) { + bool cached = ext4_cache_lookup(table, v, first + i) || storage_ext4_journal_owns(v, first + i); + synchronous = cached != first_cached; + } + } struct storage_io_context saved; if (synchronous) storage_kernel_context_enter(&saved); ret = ext4_cache_read_blocks(v, first, count, out, caching); @@ -543,7 +557,7 @@ int storage_ext4_cache_release(void) uint64_t physical = table->physical; uint32_t pages = table->pages; table->entries = NULL; - table->physical = table->pages = table->age_clock = 0; + table->physical = table->pages = table->age_clock = table->capacity = 0; if (physical) mm_free_pages(physical, pages); } return 0; diff --git a/fs/vfs/mount.c b/fs/vfs/mount.c index cd077a52..c5a5781b 100644 --- a/fs/vfs/mount.c +++ b/fs/vfs/mount.c @@ -347,6 +347,18 @@ void storage_init(void) if(!root_ready)console_error("[reliefnt] no registered GPT root filesystem found\n"); } +bool storage_try_direct_root(const struct boot_info *boot) +{ + storage_boot_root_configure(boot ? boot->cmdline : NULL); + if (!storage_boot_root_requested()) return false; + storage_init(); + if (g_volumes[STORAGE_VOLUME_ROOT].ready && + g_volumes[STORAGE_VOLUME_ROOT].filesystem == STORAGE_FILESYSTEM_EXT4) + return true; + storage_boot_reset(); + return false; +} + /** * @brief Look up a named Multiboot module and return its byte range. * @param boot Parsed boot information; may be NULL. diff --git a/fs/vfs/storage_initial.c b/fs/vfs/storage_initial.c index 219d1f10..d9597484 100644 --- a/fs/vfs/storage_initial.c +++ b/fs/vfs/storage_initial.c @@ -67,6 +67,8 @@ static int storage_initial_shm(void *context,struct vfs_mount **out) } /** @brief Assemble the one initial shared namespace before kernel path users. + * @param mount_boot_esp Attach the legacy ESP at /boot. The direct systemd + * root must be free to attach its own ESP and any per-instance bind mount. * @return Zero after root/providers/boot attachments and explicit fresh shm * are all published, or negative errno after complete assembly rollback. A * failed constructor/attachment never publishes a partial system namespace. @@ -78,7 +80,7 @@ static int storage_initial_shm(void *context,struct vfs_mount **out) * discovered instance remains available for an explicit mount. No stored * mount-path label participates in selection or routing. */ -int storage_namespace_bootstrap(void) +int storage_namespace_bootstrap(bool mount_boot_esp) { if(vfs_system_namespace())return -EBUSY; if(!g_volumes[0].ready)return -ENODEV; @@ -89,7 +91,7 @@ int storage_namespace_bootstrap(void) }; size_t count=3;uint32_t optical_count=0; char optical_targets[STORAGE_MAX_VOLUMES][32]; - if(g_volumes[STORAGE_VOLUME_BOOT].ready) + if(mount_boot_esp && g_volumes[STORAGE_VOLUME_BOOT].ready) mounts[count++]=(struct vfs_boot_mount){.target="/boot",.create=storage_initial_volume, .context=&g_volumes[STORAGE_VOLUME_BOOT]}; for(uint32_t i=STORAGE_VOLUME_DYNAMIC_FIRST;istate); lock->state = 1; *flags = 0; } +void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) +{ assert(lock->state == 1 && !flags); lock->state = 0; } static uint64_t allocate(uint32_t count) { if (allocations == allocation_limit) return 0; @@ -254,9 +260,19 @@ int main(void) *(uint32_t *)(registers_second+E1000_REG_RAL)=0x12345602; *(uint32_t *)(registers_second+E1000_REG_RAH)=E1000_RAH_AV|0x9876; command_bits_second=7; multi_mode=1; - assert(!e1000_driver_init(&api) && network_count==2 && contexts[0]!=contexts[1]); + struct reliefos_driver_kernel_api sampled_api = api; + sampled_api.ticks = ticks; + assert(!e1000_driver_init(&sampled_api) && network_count==2 && contexts[0]!=contexts[1]); struct e1000_state *first=contexts[0], *second=contexts[1]; assert(first->pci.slot==0 && second->pci.slot==1 && first->rx_phys!=second->rx_phys); + *(uint32_t *)(registers_second + E1000_REG_STATUS) = 0; + assert(networks[1]->is_ready(second)); + ++fixture_tick; + assert(!networks[1]->is_ready(second) && networks[0]->is_ready(first)); + *(uint32_t *)(registers_second + E1000_REG_STATUS) = E1000_STATUS_LINK; + assert(!networks[1]->is_ready(second)); + ++fixture_tick; + assert(networks[1]->is_ready(second)); first->rx_buf[0][0]=0xa1; first->rx[0].length=1; first->rx[0].status=3; second->rx_buf[0][0]=0xb2; second->rx[0].length=1; second->rx[0].status=3; assert(networks[1]->poll(contexts[1],frame,sizeof(frame),&length)==1 && frame[0]==0xb2); diff --git a/tools/tests/ext4_mount_test.c b/tools/tests/ext4_mount_test.c index 68d40639..7ffce4fc 100644 --- a/tools/tests/ext4_mount_test.c +++ b/tools/tests/ext4_mount_test.c @@ -497,18 +497,23 @@ static void test_cache_semantics(const char *image) /* Pinned entries are never evicted; exhaustion returns -ENOMEM. */ storage_ext4_cache_invalidate(volume); { - uint8_t *pinned[EXT4_BLOCK_CACHE_ENTRIES]; - for (uint32_t i = 0; i < EXT4_BLOCK_CACHE_ENTRIES; ++i) - assert(storage_ext4_cache_get(volume, 200 + i, &pinned[i], true) == 0); - assert(storage_ext4_cache_get(volume, 200 + EXT4_BLOCK_CACHE_ENTRIES, &data, true) == - -RELIEFOS_ENOMEM); - assert(storage_ext4_cache_read(volume, 200 + EXT4_BLOCK_CACHE_ENTRIES, buf) == - -RELIEFOS_ENOMEM); + struct ext4_cache_table *table = &ext4_cache_tables[EXT4_CACHE_TABLE_BLOCK]; + struct ext4_cache_set_range set = ext4_cache_set(table, volume, 200); + uint8_t *first_pinned = NULL; + uint64_t block = 200; + for (uint32_t i = set.first; i < set.end; ++i) { + while (ext4_cache_set(table, volume, block).first != set.first) ++block; + assert(storage_ext4_cache_get(volume, block++, &data, true) == 0); + if (i == set.first) first_pinned = data; + } + while (ext4_cache_set(table, volume, block).first != set.first) ++block; + assert(storage_ext4_cache_get(volume, block, &data, true) == -RELIEFOS_ENOMEM); + assert(storage_ext4_cache_read(volume, block, buf) == -RELIEFOS_ENOMEM); /* mark_dirty releases the pin and marks the entry dirty: the next * insert evicts it and writes the modification back first. */ - memset(pinned[0], 'A', 16); + memset(first_pinned, 'A', 16); assert(storage_ext4_cache_mark_dirty(volume, 200) == 0); - assert(storage_ext4_cache_get(volume, 300, &data, true) == 0); + assert(storage_ext4_cache_get(volume, block, &data, true) == 0); assert(disk_bytes[200 * (uint64_t)bs] == 'A'); } /* flush() also releases outstanding pins (transaction end). */ diff --git a/tools/tests/ext4_read_batch_resume_test.c b/tools/tests/ext4_read_batch_resume_test.c index 69d40ccb..3957c5ac 100644 --- a/tools/tests/ext4_read_batch_resume_test.c +++ b/tools/tests/ext4_read_batch_resume_test.c @@ -5,6 +5,7 @@ #include #include #include +#define EXT4_BLOCK_CACHE_ENTRIES 64u #include "../../block/core/storage_internal.h" /* Storage completion wakeups are outside this host fixture. */ void storage_completion_notify(void) {} @@ -105,7 +106,7 @@ int main(int argc, char **argv) struct storage_ext4_cache_entry *e = &ext4_cache_tables[0].entries[i]; *e = (struct storage_ext4_cache_entry){.valid = 1, .dirty = 1, .pinned = 1, .volume = &g_storage, .volume_generation = 1, - .block = 64 + i}; + .block = 64 + i, .data = e->data}; } } if (pressure >= 3) { @@ -114,7 +115,7 @@ int main(int argc, char **argv) struct storage_ext4_cache_entry *e = &ext4_cache_tables[0].entries[0]; *e = (struct storage_ext4_cache_entry){.valid = 1, .volume = &g_storage, .volume_generation = 1, .block = block, - .dirty = pressure == 4, .pinned = pressure == 4}; + .dirty = pressure == 4, .pinned = pressure == 4, .data = e->data}; memcpy(e->data, media + block * 4096, 4096); if (pressure == 4) memset(e->data, 0x7e, 4096); } @@ -156,7 +157,7 @@ int main(int argc, char **argv) allocation_fail = 0; assert(ext4_cache_ensure(&ext4_cache_tables[0])); struct storage_ext4_cache_entry *e = &ext4_cache_tables[0].entries[0]; *e = (struct storage_ext4_cache_entry){.valid = 1, .dirty = 1, .pinned = 1, - .volume = &g_storage, .volume_generation = 1, .block = 10}; + .volume = &g_storage, .volume_generation = 1, .block = 10, .data = e->data}; memcpy(e->data, media + 10 * 4096, 4096); calls = completed = discarded = synchronous_calls = asynchronous_calls = 0; memset(&pending, 0, sizeof(pending)); @@ -168,7 +169,7 @@ int main(int argc, char **argv) /* Already synchronous committed context remains exactly so. */ storage_ext4_cache_invalidate(&g_storage); *e = (struct storage_ext4_cache_entry){.valid = 1, .dirty = 1, .pinned = 1, - .volume = &g_storage, .volume_generation = 1, .block = 10}; + .volume = &g_storage, .volume_generation = 1, .block = 10, .data = e->data}; memcpy(e->data, media + 10 * 4096, 4096); storage_io_async_context = false; storage_io_write_started = true; calls = synchronous_calls = 0; @@ -182,7 +183,7 @@ int main(int argc, char **argv) for (unsigned i = 0; i < 32; ++i) { struct storage_ext4_cache_entry *e = &ext4_cache_tables[0].entries[i]; *e = (struct storage_ext4_cache_entry){.valid = 1, .volume = &g_storage, - .volume_generation = 1, .block = 3 + i}; + .volume_generation = 1, .block = 3 + i, .data = e->data}; memcpy(e->data, media + (3 + i) * 4096, 4096); } calls = 0; fail_at = 0; memset(&pending, 0, sizeof(pending)); diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 343a2e7f..12a57dcb 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -495,7 +495,7 @@ static void initial_optical_namespace(void) struct tmpfs_super *fs=g_volumes[0].tmpfs; for(size_t i=0;i Date: Tue, 1 Dec 2026 19:08:37 +0800 Subject: [PATCH 88/97] fix(tmpfs): support Linux-length directory names --- Documentation/userspace-api/abi.rst | 4 + fs/tmpfs/core.c | 167 +++++++++++++++++++--------- fs/tmpfs/native.c | 11 ++ include/reliefnt/tmpfs.h | 10 +- tools/tests/tmpfs_test.c | 42 +++++++ 5 files changed, 180 insertions(+), 54 deletions(-) diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 1a961906..976a7818 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -251,6 +251,10 @@ RECONFIGURE 使用这些值;参数写入只要求有效上下文描述符, mountinfo 报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 inode 引用释放且相关缓存回收后,设备号才能重用。 +tmpfs 支持最长 255 字节的路径分量。 ``statfs`` 报告该上限, +``getdents`` 和 ``getdents64`` 返回完整名称。旧 ReliefOS 目录接口只枚举固定字段 +可以容纳的名称。 + ``fsopen("proc", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 ``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 ``FSCONFIG_SET_STRING`` 接受支持的 ``hidepid`` 和 ``gid`` 参数,挂载属性由 diff --git a/fs/tmpfs/core.c b/fs/tmpfs/core.c index b0dca798..735b68d5 100644 --- a/fs/tmpfs/core.c +++ b/fs/tmpfs/core.c @@ -19,7 +19,7 @@ struct tmpfs_entry { struct tmpfs_entry *next; struct tmpfs_inode *inode; uint64_t cookie; - char name[RELIEFOS_FS_NAME_LEN]; + char name[]; }; struct tmpfs_inode { struct tmpfs_super *owner; @@ -377,6 +377,26 @@ static struct tmpfs_entry **tmpfs_find(struct tmpfs_inode *dir, const char *name e = &(*e)->next; return e; } +/** @brief Validate a literal tmpfs entry name. + * @param name NUL-terminated name. @return Zero or EINVAL/ENAMETOOLONG. + */ +static int tmpfs_validate_name(const char *name) +{ + if (!name || !name[0] || !__builtin_strcmp(name, ".") || !__builtin_strcmp(name, "..")) + return -22; + for (size_t i = 0; name[i]; ++i) { + if (name[i] == '/') return -22; + if (i == LINUX_NAME_MAX) return -36; + } + return 0; +} +/** @brief Walk a native tmpfs path, optionally ending at its parent. + * @param fs Borrowed filesystem. @param path Absolute path. + * @param parent Whether to stop before the last component. + * @param out Receives the located inode. @param last Parent mode name buffer, + * with capacity for LINUX_NAME_MAX plus its terminator. + * @return Zero or a negative path error. + */ static int tmpfs_walk(struct tmpfs_super *fs, const char *path, bool parent, struct tmpfs_inode **out, char *last) { @@ -391,7 +411,7 @@ static int tmpfs_walk(struct tmpfs_super *fs, const char *path, bool parent, str break; if (!tmpfs_dir(n)) return -20; - char name[RELIEFOS_FS_NAME_LEN]; + char name[LINUX_NAME_MAX + 1]; unsigned length = 0; while (*p && *p != '/') { if (length + 1 == sizeof(name)) @@ -436,12 +456,13 @@ int tmpfs_lookup(struct tmpfs_super *fs, const char *path, struct storage_node * tmpfs_node(fs, n, out); return ret; } +/** @copydoc tmpfs_lookup_child */ int tmpfs_lookup_child(struct tmpfs_super *fs,uint32_t parent_ino,const char *name, struct storage_node *out) { - if (!fs || !name || !name[0] || !out) return -22; - for (const char *p=name;*p;++p) if (*p=='/') return -22; - if (!__builtin_strcmp(name,".") || !__builtin_strcmp(name,"..")) return -22; + if (!fs || !out) return -22; + int rc = tmpfs_validate_name(name); + if (rc) return rc; struct tmpfs_inode *parent=tmpfs_inode(fs,parent_ino); if (!parent) return -2; if (!tmpfs_dir(parent)) return -20; @@ -450,16 +471,21 @@ int tmpfs_lookup_child(struct tmpfs_super *fs,uint32_t parent_ino,const char *na tmpfs_node(fs,entry->inode,out);return 0; } +/** @brief Allocate a new directory member with inline variable-length storage. + * @param parent Destination directory. @param name Validated entry name. + * @param n Referenced inode. @return A fresh unlinked member or NULL. + */ static struct tmpfs_entry *tmpfs_entry_new(struct tmpfs_inode *parent, const char *name, struct tmpfs_inode *n) { if (parent->next_cookie == UINT64_MAX) return NULL; - struct tmpfs_entry *e = kernel_malloc(sizeof(*e)); + size_t bytes = __builtin_strlen(name) + 1; + struct tmpfs_entry *e = kernel_malloc(sizeof(*e) + bytes); if (!e) return NULL; *e = (struct tmpfs_entry){.inode = n, .cookie = parent->next_cookie++}; - __builtin_memcpy(e->name, name, __builtin_strlen(name) + 1); + __builtin_memcpy(e->name, name, bytes); return e; } static void tmpfs_attach(struct tmpfs_inode *parent, struct tmpfs_entry *e) @@ -492,12 +518,9 @@ int tmpfs_create_child(struct tmpfs_super *fs,uint32_t parent_ino,const char *na uint32_t mode,const char *target,const struct reliefos_permissions *value, struct storage_node *out) { - if(!fs || !name || !name[0] || !__builtin_strcmp(name,".") || !__builtin_strcmp(name,".."))return -22; - size_t length=0; - for(;name[length];++length) { - if(name[length]=='/')return -22; - if(length>=RELIEFOS_FS_NAME_LEN-1)return -36; - } + if (!fs) return -22; + int ret = tmpfs_validate_name(name); + if (ret) return ret; if(fs->flags&MS_RDONLY)return -30; struct tmpfs_inode *parent=tmpfs_inode(fs,parent_ino),*n; if(!parent)return -2; @@ -513,7 +536,7 @@ int tmpfs_create_child(struct tmpfs_super *fs,uint32_t parent_ino,const char *na if(target && type!=LINUX_S_IFLNK)return -22; if (type == LINUX_S_IFLNK && (!target || !*target)) return -2; - int ret = tmpfs_alloc_inode(fs, mode, &n); + ret = tmpfs_alloc_inode(fs, mode, &n); if (ret) return ret; n->parent = parent; @@ -584,7 +607,7 @@ int tmpfs_create(struct tmpfs_super *fs,const char *path,uint32_t mode,const cha { if(!fs || !path)return -22; if(fs->flags&MS_RDONLY)return -30; - struct tmpfs_inode *parent;char name[RELIEFOS_FS_NAME_LEN]; + struct tmpfs_inode *parent;char name[LINUX_NAME_MAX + 1]; int ret=tmpfs_walk(fs,path,true,&parent,name);if(ret)return ret; return tmpfs_create_child(fs,(uint32_t)parent->stat.st_ino,name,mode,target,NULL,out); } @@ -907,11 +930,9 @@ static void tmpfs_remove(struct tmpfs_super *fs, struct tmpfs_inode *parent, str */ static int tmpfs_mutation_parent(struct tmpfs_super *fs,uint32_t ino,const char *name,struct tmpfs_inode **out) { - if(!fs || !name || !name[0] || !__builtin_strcmp(name,".") || !__builtin_strcmp(name,".."))return -22; - for(size_t i=0;name[i];++i) { - if(name[i]=='/')return -22; - if(i>=RELIEFOS_FS_NAME_LEN-1)return -36; - } + if (!fs) return -22; + int rc = tmpfs_validate_name(name); + if (rc) return rc; struct tmpfs_inode *parent=tmpfs_inode(fs,ino); if(!parent || !parent->stat.st_nlink)return -2; if(!tmpfs_dir(parent))return -20; @@ -941,7 +962,7 @@ int tmpfs_unlink(struct tmpfs_super *fs,const char *path,bool directory) { if(!fs)return -22; if(fs->flags&MS_RDONLY)return -30; - char name[RELIEFOS_FS_NAME_LEN];struct tmpfs_inode *parent; + char name[LINUX_NAME_MAX + 1];struct tmpfs_inode *parent; int ret=tmpfs_walk(fs,path,true,&parent,name); return ret ? ret : tmpfs_unlink_child(fs,(uint32_t)parent->stat.st_ino,name,directory); } @@ -978,7 +999,7 @@ int tmpfs_link(struct tmpfs_super *fs,const char *old_path,const char *new_path) { if(!fs)return -22; if(fs->flags&MS_RDONLY)return -30; - char name[RELIEFOS_FS_NAME_LEN];struct tmpfs_inode *node,*parent; + char name[LINUX_NAME_MAX + 1];struct tmpfs_inode *node,*parent; int ret=tmpfs_walk(fs,old_path,false,&node,NULL); if(!ret && tmpfs_dir(node))ret=-1; if(!ret)ret=tmpfs_walk(fs,new_path,true,&parent,name); @@ -1039,22 +1060,44 @@ int tmpfs_rename(struct tmpfs_super *fs,const char *old_path,const char *new_pat { if(!fs)return -22; if(fs->flags&MS_RDONLY)return -30; - char old_name[RELIEFOS_FS_NAME_LEN],new_name[RELIEFOS_FS_NAME_LEN]; + char old_name[LINUX_NAME_MAX + 1], new_name[LINUX_NAME_MAX + 1]; struct tmpfs_inode *old_parent,*new_parent; int ret=tmpfs_walk(fs,old_path,true,&old_parent,old_name); if(!ret)ret=tmpfs_walk(fs,new_path,true,&new_parent,new_name); return ret ? ret : tmpfs_rename_child(fs,(uint32_t)old_parent->stat.st_ino,old_name, (uint32_t)new_parent->stat.st_ino,new_name); } -/** @brief Return one real directory entry with the selected attachment's policy. - * @param fs Borrowed live filesystem under execution ownership. - * @param ino Linked directory inode. @param offset Required opaque cursor. - * @param out Required entry destination. @param mount_flags Effective access flags. - * @return One entry, zero EOF or negative inode/type errno. Successful entries - * mark atime unless readonly/noatime/nodiratime; no allocation/I/O or flag mutation. +/** @brief Select a directory entry and advance a local cursor. + * @param dir Live directory. @param cursor Entry cookie, updated on selection. + * @param item Receives the referenced inode. @return Borrowed name or NULL at EOF. */ -int tmpfs_readdir_with_flags(struct tmpfs_super *fs, uint32_t ino, uint64_t *offset, struct reliefos_dir_entry *out, - uint64_t mount_flags) +static const char *tmpfs_next_dirent(struct tmpfs_inode *dir, uint64_t *cursor, + struct tmpfs_inode **item) +{ + if (*cursor < 2) { + bool parent = (*cursor)++; + *item = parent ? dir->parent : dir; + return parent ? ".." : "."; + } + struct tmpfs_entry *entry = dir->entries; + while (entry && entry->cookie < *cursor) + entry = entry->next; + if (!entry) + return NULL; + *item = entry->inode; + *cursor = entry->cookie + 1; + return entry->name; +} + +/** @brief Read a Linux name or a legacy name and type from a tmpfs directory. + * @param fs Borrowed filesystem. @param ino Directory inode. + * @param offset Caller cursor, committed on success. @param name Output buffer. + * @param capacity Name buffer size. @param legacy_type Optional legacy result, + * which selects entries representable by the fixed-width ABI. + * @param mount_flags Effective flags for atime. @return One entry, EOF, or errno. + */ +static int tmpfs_read_dirent(struct tmpfs_super *fs, uint32_t ino, uint64_t *offset, + char *name, size_t capacity, uint32_t *legacy_type, uint64_t mount_flags) { struct tmpfs_inode *n = tmpfs_inode(fs, ino); if (!n) @@ -1063,29 +1106,44 @@ int tmpfs_readdir_with_flags(struct tmpfs_super *fs, uint32_t ino, uint64_t *off return -20; if (!n->stat.st_nlink) return -2; - struct tmpfs_inode *item; - const char *name; - if (*offset < 2) { - name = *offset ? ".." : "."; - item = *offset ? n->parent : n; - ++*offset; - } else { - struct tmpfs_entry *e = n->entries; - while (e && e->cookie < *offset) - e = e->next; - if (!e) + uint64_t next = *offset; + for (;;) { + struct tmpfs_inode *item; + const char *entry_name = tmpfs_next_dirent(n, &next, &item); + if (!entry_name) return 0; - item = e->inode; - name = e->name; - *offset = e->cookie + 1; + size_t bytes = __builtin_strlen(entry_name) + 1; + if (bytes > capacity) { + if (legacy_type) continue; + return -36; + } + __builtin_memcpy(name, entry_name, bytes); + if (legacy_type) { + struct storage_node node; + tmpfs_node(fs, item, &node); + *legacy_type = node.type; + } + *offset = next; + tmpfs_mark_access(n, mount_flags); + return 1; } - struct storage_node node; - tmpfs_node(fs, item, &node); - __builtin_memset(out, 0, sizeof(*out)); - out->type = node.type; - __builtin_memcpy(out->name, name, __builtin_strlen(name) + 1); - tmpfs_mark_access(n,mount_flags); - return 1; +} + +/** @copydoc tmpfs_readdir_name */ +int tmpfs_readdir_name(struct tmpfs_super *fs, uint32_t ino, uint64_t *offset, + char *name, size_t capacity, uint64_t mount_flags) +{ + return tmpfs_read_dirent(fs, ino, offset, name, capacity, NULL, mount_flags); +} + +/** @copydoc tmpfs_readdir_with_flags */ +int tmpfs_readdir_with_flags(struct tmpfs_super *fs, uint32_t ino, uint64_t *offset, + struct reliefos_dir_entry *out, uint64_t mount_flags) +{ + struct reliefos_dir_entry entry = {0}; + int rc = tmpfs_read_dirent(fs, ino, offset, entry.name, sizeof(entry.name), &entry.type, mount_flags); + if (rc > 0) *out = entry; + return rc; } /** @brief Enumerate a raw directory using its filesystem's default policy. * @param fs Borrowed live filesystem under execution ownership. @@ -1153,6 +1211,9 @@ int tmpfs_utimens(struct tmpfs_super *fs, uint32_t ino, int64_t atime, int64_t m tmpfs_changed(n, false); return 0; } +/** @brief Report tmpfs geometry, quotas and the Linux component limit. + * @param fs Borrowed live filesystem. @param out Required statfs destination. + */ void tmpfs_statfs(struct tmpfs_super *fs, struct linux_statfs_abi *out) { *out = (struct linux_statfs_abi){ @@ -1164,7 +1225,7 @@ void tmpfs_statfs(struct tmpfs_super *fs, struct linux_statfs_abi *out) .f_bavail = fs->max_pages ? fs->max_pages - fs->used_pages : 0, .f_files = fs->max_inodes, .f_ffree = fs->max_inodes ? fs->max_inodes - fs->used_inodes : 0, - .f_namelen = RELIEFOS_FS_NAME_LEN - 1, + .f_namelen = LINUX_NAME_MAX, .f_flags = LINUX_ST_VALID | (fs->flags & (MS_RDONLY | MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_NODIRATIME)) | ((fs->flags & MS_RELATIME) ? LINUX_ST_RELATIME : 0)}; diff --git a/fs/tmpfs/native.c b/fs/tmpfs/native.c index 101a1fbb..bc5a6dc7 100644 --- a/fs/tmpfs/native.c +++ b/fs/tmpfs/native.c @@ -58,6 +58,16 @@ static int tmpfs_native_readdir(struct storage_volume *volume,const struct stora { return tmpfs_readdir_with_flags(volume->tmpfs,node->first_cluster,cursor,entry,mount_flags); } +/** @brief Read a full Linux component from a retained tmpfs directory. + * @param volume Borrowed instance. @param node Directory. @param cursor Entry cookie. + * @param name Output buffer. @param capacity Name buffer size. @param mount_flags Access flags. + * @return One entry, zero EOF, or negative errno. Execution ownership required. + */ +static int tmpfs_native_readdir_name(struct storage_volume *volume, const struct storage_node *node, + uint64_t *cursor, char *name, size_t capacity, uint64_t mount_flags) +{ + return tmpfs_readdir_name(volume->tmpfs, node->first_cluster, cursor, name, capacity, mount_flags); +} /** @brief Query/store authorized builtin memory inode ownership and mode. * @param volume Borrowed pinned instance. @param node Actual retained inode. * @param value Required result or authorized metadata. @param write Store if true. @@ -218,6 +228,7 @@ const struct storage_filesystem_ops storage_tmpfs_ops={ .utimens=tmpfs_native_utimens, .read=tmpfs_native_read, .readdir=tmpfs_native_readdir, + .readdir_name=tmpfs_native_readdir_name, .root=tmpfs_native_root, .lookup=tmpfs_native_lookup, .readlink=tmpfs_native_readlink diff --git a/include/reliefnt/tmpfs.h b/include/reliefnt/tmpfs.h index e0645032..a6009d54 100644 --- a/include/reliefnt/tmpfs.h +++ b/include/reliefnt/tmpfs.h @@ -131,7 +131,7 @@ int tmpfs_get_page(struct tmpfs_super *fs, uint32_t ino, uint64_t offset, uint64 */ bool tmpfs_page_resident(struct tmpfs_super *fs, uint32_t ino, uint64_t offset); int tmpfs_readdir(struct tmpfs_super *fs, uint32_t ino, uint64_t *offset, struct reliefos_dir_entry *out); -/** @brief Enumerate one actual directory using this attachment's atime policy. +/** @brief Enumerate legacy-representable names with this attachment's atime policy. * @param fs Borrowed live filesystem under execution ownership. * @param ino Retained linked directory inode. * @param offset Required opaque cursor, advanced only for a returned entry. @@ -142,6 +142,14 @@ int tmpfs_readdir(struct tmpfs_super *fs, uint32_t ino, uint64_t *offset, struct */ int tmpfs_readdir_with_flags(struct tmpfs_super *fs,uint32_t ino,uint64_t *offset, struct reliefos_dir_entry *out,uint64_t mount_flags); +/** @brief Enumerate a full Linux tmpfs component for getdents/getdents64. + * @param fs Borrowed filesystem under execution ownership. @param ino Directory. + * @param offset Cursor, advanced only on success. @param name Output buffer. + * @param capacity Available space including NUL. @param mount_flags Access flags. + * @return One entry, zero EOF, or a negative errno. No allocation or I/O. + */ +int tmpfs_readdir_name(struct tmpfs_super *fs, uint32_t ino, uint64_t *offset, + char *name, size_t capacity, uint64_t mount_flags); int tmpfs_unlink(struct tmpfs_super *fs, const char *path, bool directory); int tmpfs_link(struct tmpfs_super *fs, const char *old_path, const char *new_path); int tmpfs_rename(struct tmpfs_super *fs, const char *old_path, const char *new_path); diff --git a/tools/tests/tmpfs_test.c b/tools/tests/tmpfs_test.c index 4d8586eb..052966f3 100644 --- a/tools/tests/tmpfs_test.c +++ b/tools/tests/tmpfs_test.c @@ -167,9 +167,51 @@ static void long_link_payload(void) tmpfs_destroy(fs); puts("PASS tmpfs Linux PATH_MAX symlink payload, exact readlink and failure quota rollback"); } +/** @brief Exercise Linux NAME_MAX, including package download suffixes. */ +static void long_component(void) +{ + struct tmpfs_super *fs; + struct storage_node root, file, found; + struct linux_statfs_abi space; + char path[LINUX_NAME_MAX + 3]; + path[0] = '/'; + memset(path + 1, 'a', LINUX_NAME_MAX); + path[LINUX_NAME_MAX + 1] = '\0'; + assert(!tmpfs_new(9, 0, "", 0, 0, &fs)); + assert(!tmpfs_lookup(fs, "/", &root)); + assert(!tmpfs_create(fs, path, LINUX_S_IFREG | 0600, NULL, &file)); + assert(!tmpfs_lookup_child(fs, root.first_cluster, path + 1, &found)); + assert(found.first_cluster == file.first_cluster); + char name[LINUX_NAME_MAX + 1]; + uint64_t cursor = 2; + assert(tmpfs_readdir_name(fs, root.first_cluster, &cursor, name, LINUX_NAME_MAX, 0) == -36); + assert(cursor == 2); + assert(tmpfs_readdir_name(fs, root.first_cluster, &cursor, name, sizeof(name), 0) == 1); + assert(!strcmp(name, path + 1)); + assert(!tmpfs_readdir_name(fs, root.first_cluster, &cursor, name, sizeof(name), 0)); + tmpfs_statfs(fs, &space); + assert(space.f_namelen == LINUX_NAME_MAX); + path[LINUX_NAME_MAX + 1] = 'b'; + path[LINUX_NAME_MAX + 2] = '\0'; + assert(tmpfs_create(fs, path, LINUX_S_IFREG | 0600, NULL, NULL) == -36); + assert(tmpfs_rename_child(fs, root.first_cluster, path + 1, root.first_cluster, "short") == -36); + path[LINUX_NAME_MAX + 1] = '\0'; + assert(!tmpfs_rename(fs, path, "/short")); + assert(!tmpfs_link(fs, "/short", path)); + struct reliefos_dir_entry legacy; + cursor = 2; + assert(tmpfs_readdir(fs, root.first_cluster, &cursor, &legacy) == 1); + assert(!strcmp(legacy.name, "short")); + assert(!tmpfs_readdir(fs, root.first_cluster, &cursor, &legacy)); + assert(!tmpfs_unlink(fs, path, false)); + assert(!tmpfs_unlink(fs, "/short", false)); + tmpfs_destroy(fs); + puts("PASS tmpfs Linux NAME_MAX component and exact mutation boundary"); +} int main(void) { long_link_payload(); + long_component(); real_preallocation(); retained_directory_mutations(); struct tmpfs_super *fs = NULL; From 88b932b1ede358f11764963c38f787c2349d313b Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Wed, 2 Dec 2026 07:43:38 +0800 Subject: [PATCH 89/97] refactor: retire legacy boot and private userspace interfaces --- AGENT.md | 2 +- Documentation/core-api/realtek.rst | 2 +- Documentation/core-api/resource-limits.rst | 2 +- Documentation/core-api/virtio-gpu.rst | 2 +- Documentation/kbuild/modules.rst | 2 +- .../locale/en/LC_MESSAGES/admin-guide/boot.po | 108 +- .../LC_MESSAGES/core-api/network-devices.po | 356 +++-- .../locale/en/LC_MESSAGES/core-api/realtek.po | 187 +-- .../LC_MESSAGES/core-api/resource-limits.po | 530 +++---- .../en/LC_MESSAGES/core-api/virtio-gpu.po | 33 +- .../locale/en/LC_MESSAGES/kbuild/modules.po | 322 ++-- .../en/LC_MESSAGES/process/e1000e-plan.po | 95 +- .../locale/en/LC_MESSAGES/process/testing.po | 354 +++-- .../en/LC_MESSAGES/userspace-api/abi.po | 1313 +++++++++++------ .../en/LC_MESSAGES/userspace-api/inotify.po | 199 +-- .../en/LC_MESSAGES/userspace-api/ipv6.po | 876 ++++++++--- .../locale/ja/LC_MESSAGES/admin-guide/boot.po | 85 +- .../LC_MESSAGES/core-api/network-devices.po | 273 ++-- .../locale/ja/LC_MESSAGES/core-api/realtek.po | 89 +- .../LC_MESSAGES/core-api/resource-limits.po | 218 +-- .../ja/LC_MESSAGES/core-api/virtio-gpu.po | 28 +- .../locale/ja/LC_MESSAGES/kbuild/modules.po | 208 +-- .../ja/LC_MESSAGES/process/e1000e-plan.po | 48 +- .../locale/ja/LC_MESSAGES/process/testing.po | 264 ++-- .../ja/LC_MESSAGES/userspace-api/abi.po | 1039 ++++++++----- .../ja/LC_MESSAGES/userspace-api/inotify.po | 135 +- .../ja/LC_MESSAGES/userspace-api/ipv6.po | 718 +++++++-- Documentation/process/e1000e-plan.rst | 2 +- Documentation/process/testing.rst | 2 +- Documentation/userspace-api/inotify.rst | 2 +- Documentation/userspace-api/ipv6.rst | 2 +- block/Kbuild | 2 +- block/core/storage_block.c | 5 +- block/core/storage_state_data.c | 1 - block/core/storage_types.h | 1 - block/partition/disk_io.c | 2 +- block/partition/partition_gpt.c | 2 +- block/ramdisk/Kbuild | 3 - block/ramdisk/boot.c | 186 --- configs/toolchains/llvm-x86_64.mk | 4 +- drivers/video/framebuffer/fbdev.c | 2 +- fs/proc/procfs.c | 10 +- fs/sysfs/sysfs.c | 4 +- fs/vfs/internal.h | 6 - fs/vfs/mount.c | 181 +-- fs/vfs/storage_status.c | 10 - include/reliefnt/boot_block.h | 27 - include/reliefnt/elf.h | 9 +- include/reliefnt/storage.h | 40 +- include/reliefnt/task/types.h | 2 +- include/reliefos/elf_abi.h | 39 - include/reliefos/layout.h | 112 +- include/uapi/README.rst | 8 +- include/uapi/reliefos/rootfs.h | 106 +- kernel/exec/elf.c | 85 +- kernel/exec/userland.c | 24 +- kernel/init/kernel.c | 25 +- kernel/module/lifecycle.c | 2 +- kernel/sched/signal.c | 3 +- kernel/signal/signal.c | 16 +- kernel/signal/signal_queue.c | 1 + kernel/syscall/device/input_ioctl.c | 2 +- net/core.c | 3 +- net/interface/config.c | 179 --- net/internal.h | 8 - tools/host/manifest/reliefos-deps.c | 4 +- tools/test_boot_block.py | 15 - tools/test_boot_policy.py | 8 +- tools/test_installer_ramdisk.py | 27 - tools/test_linux_audio.py | 27 +- ...openrc_network.py => test_network_time.py} | 6 +- tools/test_squashfs.py | 4 +- tools/test_squashfs_boot.py | 19 - tools/tests/Makefile | 4 +- tools/tests/boot_block_test.c | 83 -- tools/tests/boot_lookup_contention_probe.c | 2 +- tools/tests/brand-allowlist.tsv | 18 - tools/tests/execution_lock_runtime_probe.c | 2 +- tools/tests/host-suites.list | 5 +- tools/tests/initramfs_runtime_probe.c | 69 +- tools/tests/installer_ramdisk_test.c | 401 ----- tools/tests/linux_inventory_test.c | 22 +- tools/tests/module_drm_probe.c | 2 +- tools/tests/module_hda_probe.c | 4 +- tools/tests/module_lifecycle_test.c | 2 +- tools/tests/network_guest_test.c | 4 +- tools/tests/signal_wake_test.c | 37 + tools/tests/squashfs_boot_modules_test.c | 95 -- tools/tests/syscall_io_test.c | 1 - tools/tests/user_mmap_arena_test.c | 2 +- tools/tests/vdso_auxv_test.c | 9 +- tools/tests/vt_console_test.c | 24 +- 92 files changed, 5117 insertions(+), 4385 deletions(-) delete mode 100644 block/ramdisk/Kbuild delete mode 100644 block/ramdisk/boot.c delete mode 100644 include/reliefnt/boot_block.h delete mode 100644 include/reliefos/elf_abi.h delete mode 100644 tools/test_boot_block.py delete mode 100644 tools/test_installer_ramdisk.py rename tools/{test_openrc_network.py => test_network_time.py} (78%) delete mode 100644 tools/test_squashfs_boot.py delete mode 100644 tools/tests/boot_block_test.c delete mode 100644 tools/tests/installer_ramdisk_test.c delete mode 100644 tools/tests/squashfs_boot_modules_test.c diff --git a/AGENT.md b/AGENT.md index 598fb397..b330ec97 100644 --- a/AGENT.md +++ b/AGENT.md @@ -6,7 +6,7 @@ ## 构建与验证 - 根 Makefile 是生产入口;产物为 `kernel.sys` 和 `kernel.debug`。 - 本仓不包含 ReliefOS 用户态、系统镜像或 APK 打包。 + ReliefOS 用户态、系统镜像和发行版打包由父仓维护。 - C/汇编、宿主工具、依赖追踪和配置由 `scripts/kbuild-source.json` 中校验过的 Linux 6.12 Kbuild/Kconfig 文件提供;适配只放在 `Kbuild`、`scripts/Makefile.reliefnt` 和 `scripts/Makefile.port`。不得改写导入的 `scripts/Makefile.*`、`basic/`、 diff --git a/Documentation/core-api/realtek.rst b/Documentation/core-api/realtek.rst index 56130c7e..b612cbef 100644 --- a/Documentation/core-api/realtek.rst +++ b/Documentation/core-api/realtek.rst @@ -107,7 +107,7 @@ RTL8168 家族路径。真实 PHY 协商、DMA 时序和实体网线收发仍需 本次 QEMU 回归覆盖默认内置启动,以及无匹配 Realtek 硬件时三次 ``r8169.ko`` 加载与卸载。既有 e1000 的 IPv4、IPv6 ping 均通过。 -测试使用当前新编译内核和私有 initramfs,BusyBox 来自已有 ReliefOS 构建。 +测试在匹配当前内核的 ReliefOS 构建镜像上运行,使用私有测试磁盘。 本地 QEMU 只提供 RTL8139 Realtek 模型,真实 RTL8111/8168、RTL8125 需要实体网卡或正确的 PCI 直通验证。实体网卡验证未完成。VMware 验证未完成。 diff --git a/Documentation/core-api/resource-limits.rst b/Documentation/core-api/resource-limits.rst index e07e2c45..3f60cd28 100644 --- a/Documentation/core-api/resource-limits.rst +++ b/Documentation/core-api/resource-limits.rst @@ -207,7 +207,7 @@ fbdev 的 ``smem_start`` 与用户设备映射的 PFN 保持物理地址语义 ``tools/tests/resource_capacity_runtime_probe.c`` 是原生 Linux ABI 容量探针, ``tools/tests/tcp_runtime_probe.c`` 连接测试编排提供的本地 TCP 对端。 -二者可用 musl 静态构建。完整镜像、私有磁盘和 QEMU 编排归 ReliefOS 持有, +二者可用 glibc 静态构建。完整镜像、私有磁盘和 QEMU 编排归 ReliefOS 持有, 宿主 Linux 上通过只证明参考行为,不能代替 ReliefOS 来宾验证。 ``tools/tests/kmodules/memory_layout_probe`` 是独立 Apache-2.0 外部模块, diff --git a/Documentation/core-api/virtio-gpu.rst b/Documentation/core-api/virtio-gpu.rst index 16c08aa8..bf1bf0e9 100644 --- a/Documentation/core-api/virtio-gpu.rst +++ b/Documentation/core-api/virtio-gpu.rst @@ -65,7 +65,7 @@ fatal owner 使用,不获取普通 GPU 锁或执行分配。GUI panic 只上 ``tools/test_virtio.py`` 在 ASan/UBSan 下运行生产 ring 实现,覆盖乱序、 131080 次环回绕、背压、非法 used entry 及 fatal 预留链。原生用户态探针 -``tools/tests/virtgpu_guest.c`` 可用 musl 编译,执行实际 DRM、PRIME、 +``tools/tests/virtgpu_guest.c`` 可用 glibc 编译,执行实际 DRM、PRIME、 sync_file、sysfs、翻页和光标操作;用 ``--no-pause`` 跳过截图握手。 ``tools/test_drm.py`` 覆盖局部文本上传的偏移、失败重试、VT 整屏恢复, 以及 2D DIRTYFB 的区域拆分、合并和校验。 diff --git a/Documentation/kbuild/modules.rst b/Documentation/kbuild/modules.rst index 3c73ebe8..ad52c749 100644 --- a/Documentation/kbuild/modules.rst +++ b/Documentation/kbuild/modules.rst @@ -97,7 +97,7 @@ OBJCOPY。改变内核架构、PROFILE、编译策略或头文件应从完整源 加载器校验完整 vermagic、类型 CRC、依赖和参数,并实现 Linux 编号的 init_module、finit_module、delete_module;调用者需要 CAP_SYS_MODULE。 finit_module 不支持的装载标志明确返回错误。delete_module 与 Linux 6.12 -禁用强制卸载的配置一致,接受 BusyBox 使用的 O_EXCL,并忽略额外位; +禁用强制卸载的配置一致,接受用户态模块工具传入的 O_EXCL,并忽略额外位; O_TRUNC 也不会绕过引用、exit 或硬件停止检查。finit_module 使用独立文件快照,不移动共享 文件偏移;已有可写文件描述会阻止快照,快照期间也不能新增可写打开。 diff --git a/Documentation/locale/en/LC_MESSAGES/admin-guide/boot.po b/Documentation/locale/en/LC_MESSAGES/admin-guide/boot.po index 80bed251..c672a94f 100644 --- a/Documentation/locale/en/LC_MESSAGES/admin-guide/boot.po +++ b/Documentation/locale/en/LC_MESSAGES/admin-guide/boot.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "启动契约" msgstr "Boot Contract" @@ -20,40 +23,93 @@ msgid "固件与交接" msgstr "Firmware and Handoff" msgid "" -"同一 kernel.sys 包含 Multiboot2 BIOS 32 位入口与 EFI64 入口。 BIOS 入口检查 CPU 能力、建立页表与栈后进入共享 64 位内核。 " -"解析交接数据时检查边界、对齐、长度和溢出;EFI 信息指针保留完整宽度。 固件、GRUB 与模块载荷需满足该协议,本仓不生成 ISO 或安装引导器。" +"同一 kernel.sys 包含 Multiboot2 BIOS 32 位入口与 EFI64 入口。 BIOS 入口检查 CPU " +"能力、建立页表与栈后进入共享 64 位内核。 解析交接数据时检查边界、对齐、长度和溢出;EFI 信息指针保留完整宽度。 固件、GRUB " +"与模块载荷需满足该协议,本仓不生成 ISO 或安装引导器。" msgstr "" -"The same kernel.sys contains both a Multiboot2 BIOS 32-bit entry and an EFI64 entry. The BIOS " -"entry checks CPU capabilities and sets up page tables and a stack before entering the shared " -"64-bit kernel. Handoff data parsing checks bounds, alignment, lengths, and overflow; EFI " -"information pointers retain their full width. Firmware, GRUB, and module payloads must satisfy " -"this protocol. This repository does not generate an ISO or install a bootloader." +"The same kernel.sys contains both a Multiboot2 BIOS 32-bit entry and an " +"EFI64 entry. The BIOS entry checks CPU capabilities and sets up page " +"tables and a stack before entering the shared 64-bit kernel. Handoff data" +" parsing checks bounds, alignment, lengths, and overflow; EFI information" +" pointers retain their full width. Firmware, GRUB, and module payloads " +"must satisfy this protocol. This repository does not generate an ISO or " +"install a bootloader." msgid "根分区" msgstr "Root Partition" msgid "" -"设备发现后解析显式 ``root=PARTUUID=...``,匹配唯一 GPT 分区身份。 畸形、缺失或重复请求拒绝自动回退;连接顺序不能替代指定身份。 " -"旧自动发现行为与显式选择是不同路线。内核映像和引导模块的内存范围 在物理内存管理初始化前保留,不能当作可重用空闲页。" +"设备发现后解析显式 ``root=PARTUUID=...``,匹配唯一 GPT 分区身份。 " +"畸形、缺失或重复请求拒绝自动回退;连接顺序不能替代指定身份。 旧自动发现行为与显式选择是不同路线。内核映像和引导模块的内存范围 " +"在物理内存管理初始化前保留,不能当作可重用空闲页。" msgstr "" -"After device discovery, an explicit ``root=PARTUUID=...`` is parsed to match a unique GPT " -"partition identity. Malformed, missing, or duplicate requests reject automatic fallback; " -"connection order cannot replace the specified identity. Legacy automatic discovery and explicit " -"selection are separate paths. Memory ranges occupied by the kernel image and boot modules are " -"reserved before physical memory management is initialized and must not be treated as reusable free" -" pages." +"After device discovery, an explicit ``root=PARTUUID=...`` is parsed to " +"match a unique GPT partition identity. Malformed, missing, or duplicate " +"requests reject automatic fallback; connection order cannot replace the " +"specified identity. Legacy automatic discovery and explicit selection are" +" separate paths. Memory ranges occupied by the kernel image and boot " +"modules are reserved before physical memory management is initialized and" +" must not be treated as reusable free pages." msgid "日志" msgstr "Logging" -msgid "内核日志使用 ``[启动后秒数] [等级] [组件] 消息`` 格式。默认保留 INFO、WARN、ERROR 和 FATAL。常见的进程启动、退出、回收及硬件缺席记录仅在 DEBUG 下输出。``debug`` 或 ``loglevel=8`` 开启 DEBUG,``quiet`` 等效于 ``loglevel=4``。``loglevel=N`` 接受 0–8,输出优先级数值小于 N 的记录。FATAL 和 panic 始终保留紧急输出。" -msgstr "Kernel records use ``[seconds since boot] [level] [component] message``. INFO, WARN, ERROR, and FATAL are enabled by default. Routine process launches, exits, reaping, and absent hardware are visible at DEBUG. Use ``debug`` or ``loglevel=8`` to enable DEBUG. ``quiet`` is equivalent to ``loglevel=4``. ``loglevel=N`` accepts 0–8 and emits priorities numerically below N. Emergency FATAL and panic output remains enabled." +msgid "" +"内核日志使用 ``[启动后秒数] [等级] [组件] 消息`` 格式。默认保留 INFO、WARN、ERROR 和 " +"FATAL。常见的进程启动、退出、回收及硬件缺席记录仅在 DEBUG 下输出。``debug`` 或 ``loglevel=8`` 开启 " +"DEBUG,``quiet`` 等效于 ``loglevel=4``。``loglevel=N`` 接受 0–8,输出优先级数值小于 N " +"的记录。FATAL 和 panic 始终保留紧急输出。" +msgstr "" +"Kernel records use ``[seconds since boot] [level] [component] message``. " +"INFO, WARN, ERROR, and FATAL are enabled by default. Routine process " +"launches, exits, reaping, and absent hardware are visible at DEBUG. Use " +"``debug`` or ``loglevel=8`` to enable DEBUG. ``quiet`` is equivalent to " +"``loglevel=4``. ``loglevel=N`` accepts 0–8 and emits priorities " +"numerically below N. Emergency FATAL and panic output remains enabled." -msgid "``log=screen,serial`` 是默认值。可用 ``log=screen`` 或 ``log=serial`` 只选一个日志目标,也可用 ``log=none`` 关闭常规内核日志。``logcolor=0`` 关闭普通日志颜色。``bootlog-pause=1`` 在启动检查点等待输入。``syscall-trace=/path/prefix`` 为匹配的程序启用系统调用诊断。" -msgstr "``log=screen,serial`` is the default. Use ``log=screen`` or ``log=serial`` for a single log sink, or ``log=none`` to disable regular kernel records. ``logcolor=0`` disables regular log colors. ``bootlog-pause=1`` waits for input at a boot checkpoint. ``syscall-trace=/path/prefix`` enables syscall diagnostics for matching programs." +msgid "" +"``log=screen,serial`` 是默认值。可用 ``log=screen`` 或 ``log=serial`` " +"只选一个日志目标,也可用 ``log=none`` 关闭常规内核日志。``logcolor=0`` 关闭普通日志颜色。``bootlog-" +"pause=1`` 在启动检查点等待输入。``syscall-trace=/path/prefix`` 为匹配的程序启用系统调用诊断。" +msgstr "" +"``log=screen,serial`` is the default. Use ``log=screen`` or " +"``log=serial`` for a single log sink, or ``log=none`` to disable regular " +"kernel records. ``logcolor=0`` disables regular log colors. ``bootlog-" +"pause=1`` waits for input at a boot checkpoint. ``syscall-" +"trace=/path/prefix`` enables syscall diagnostics for matching programs." -msgid "COM1 使用 115200 波特、8N1。早期启动和 panic 使用有界轮询。进入用户态后,内核日志和控制台镜像进入 32 KiB 发送队列,由 IRQ4 批量填充 UART FIFO,定时器负责兜底。队列为 WARN 和 ERROR 预留空间。积压清空后,串口报告丢弃的日志和控制台镜像数量。直接写入 ``/dev/ttyS0`` 时,阻塞写等待可用空间,非阻塞写在无法接收任何字节时返回 ``EAGAIN``。关闭或重启系统前会尝试发送队列中的数据。" -msgstr "COM1 uses 115200 baud, 8N1. Early boot and panic use bounded polling. After entering userspace, kernel logs and console mirroring use a 32 KiB transmit queue. IRQ4 fills the UART FIFO in batches, and the timer provides a fallback. The queue reserves space for WARN and ERROR. After the backlog drains, serial output reports the number of dropped records and console chunks. Blocking writes to ``/dev/ttyS0`` wait for space. Nonblocking writes return ``EAGAIN`` when no input bytes fit. Shutdown and reboot attempt to flush the queue." +msgid "" +"COM1 使用 115200 波特、8N1。早期启动和 panic 使用有界轮询。进入用户态后,内核日志和控制台镜像进入 32 KiB " +"发送队列,由 IRQ4 批量填充 UART FIFO,定时器负责兜底。队列为 WARN 和 ERROR " +"预留空间。积压清空后,串口报告丢弃的日志和控制台镜像数量。直接写入 ``/dev/ttyS0`` " +"时,阻塞写等待可用空间,非阻塞写在无法接收任何字节时返回 ``EAGAIN``。关闭或重启系统前会尝试发送队列中的数据。" +msgstr "" +"COM1 uses 115200 baud, 8N1. Early boot and panic use bounded polling. " +"After entering userspace, kernel logs and console mirroring use a 32 KiB " +"transmit queue. IRQ4 fills the UART FIFO in batches, and the timer " +"provides a fallback. The queue reserves space for WARN and ERROR. After " +"the backlog drains, serial output reports the number of dropped records " +"and console chunks. Blocking writes to ``/dev/ttyS0`` wait for space. " +"Nonblocking writes return ``EAGAIN`` when no input bytes fit. Shutdown " +"and reboot attempt to flush the queue." -msgid "文字控制台使用现有 framebuffer 字形、pitch 和原生 RGB 转换,可处理带行间填充的帧缓冲。" -msgstr "The text console uses the existing framebuffer glyphs, pitch, and native RGB conversion and supports framebuffers with row padding." +msgid "" +"文字控制台使用现有 framebuffer 字形、pitch 和原生 RGB 转换,可处理带行间填充的帧缓冲。 " +"可见文本在普通内存中绘制、滚动并更新光标,随后只向显存写入变动区域。 分配失败时使用直接绘制。panic 使用直接绘制以避免进入常规显示锁。" +msgstr "" +"The text console uses the existing framebuffer glyphs, pitch and native " +"RGB conversion, including padded scanlines. It draws visible text, " +"scrolls and updates the cursor in ordinary memory, then copies changed " +"areas to video memory. It draws directly on allocation failure. Panic " +"output also draws directly to avoid normal display locks." + +msgid "" +"当 ``reliefos.direct_root=1`` 与明确的 ``root=PARTUUID=...`` 同时存在时, " +"内核优先尝试用内置驱动挂载 ext4 根。成功后直接执行真实根的 init, 把 ESP 和 ``/boot`` 的挂载交给用户态。无法挂载指定 " +"ext4 根时加载预置 initramfs。未设置该选项时采用常规启动顺序。" +msgstr "" +"With ``reliefos.direct_root=1`` and an explicit ``root=PARTUUID=...``, " +"the kernel first tries to mount the ext4 root with built-in drivers. " +"After success, it runs init in the real root, leaving ESP and ``/boot`` " +"mounts to userspace. A failed direct mount falls back to the prepared " +"initramfs. Without the option, the normal boot sequence applies." diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po index 216cea5d..a0e6b4bb 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/network-devices.po @@ -4,25 +4,29 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0800\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "Multiple network devices" msgstr "Multiple network devices" msgid "" -"ReliefNT 为每个受支持的 Ethernet PCI 功能分配独立网络接口。e1000、e1000e、 i225、r8169、rtl8139 和 vmxnet3 " -"可以同时注册,多张相同型号网卡也分别拥有设备状态和 DMA 环。" +"ReliefNT 为每个受支持的 Ethernet PCI 功能分配独立网络接口。e1000、e1000e、 i225、r8169、rtl8139" +" 和 vmxnet3 可以同时注册,多张相同型号网卡也分别拥有设备状态和 DMA 环。" msgstr "" -"ReliefNT allocates an independent network interface to each supported Ethernet PCI function. " -"e1000, e1000e, i225, r8169, rtl8139 and vmxnet3 can register simultaneously, with separate device " -"state and DMA rings even for multiple cards of the same model." +"ReliefNT allocates an independent network interface to each supported " +"Ethernet PCI function. e1000, e1000e, i225, r8169, rtl8139 and vmxnet3 " +"can register simultaneously, with separate device state and DMA rings " +"even for multiple cards of the same model." msgid "Device identity" msgstr "Device identity" @@ -33,116 +37,286 @@ msgid "" "eth2 继续使用原来的编号。 重新加载驱动时,新设备获得新的索引和名称。" msgstr "" "``lo`` has ifindex 1. Hardware interfaces receive increasing indexes " -"starting at ifindex 2 and are named ``eth``. Interfaces retain " -"their names and indexes during a boot, leaving index gaps after removal. For" -" example, after unloading the driver that owns eth0 and eth1, the surviving " -"eth2 keeps its original number. When the driver is reloaded, new devices " -"receive new indexes and names." +"starting at ifindex 2 and are named ``eth``. Interfaces retain" +" their names and indexes during a boot, leaving index gaps after removal." +" For example, after unloading the driver that owns eth0 and eth1, the " +"surviving eth2 keeps its original number. When the driver is reloaded, " +"new devices receive new indexes and names." msgid "" "私有 ``include/reliefnt/net_device.h`` 的 ``driver_register_netdev`` 接收 " "版本化回调表、每设备上下文和索引输出。管理器复制回调表,将其与原驱动 owner 绑定,回调前固定 " -"owner,释放服务锁后执行回调。初始化成功后发布接口。 驱动关闭回调接入、排空引用并停止自身全部设备后,管理器移除对应接口。 停止失败的设备保留 " -"DMA 和模块代码,后续卸载可以重试。" +"owner,释放服务锁后执行回调。初始化成功后发布接口。 驱动关闭回调接入、排空引用并停止自身全部设备后,管理器移除对应接口。 停止失败的设备保留" +" DMA 和模块代码,后续卸载可以重试。" msgstr "" -"``driver_register_netdev`` in the private ``include/reliefnt/net_device.h`` " -"accepts a versioned callback table, per-device context, and an index output." -" The manager copies the callback table and binds it to the original driver " -"owner, pins the owner before callbacks, and executes callbacks after " -"releasing the service lock. Interfaces are published after successful " -"initialization. Once a driver closes callback admission, drains references, " -"and stops all its devices, the manager removes the corresponding interfaces." -" Devices that fail to stop retain DMA and module code, allowing a later " -"unload to retry." +"``driver_register_netdev`` in the private " +"``include/reliefnt/net_device.h`` accepts a versioned callback table, " +"per-device context, and an index output. The manager copies the callback " +"table and binds it to the original driver owner, pins the owner before " +"callbacks, and executes callbacks after releasing the service lock. " +"Interfaces are published after successful initialization. Once a driver " +"closes callback admission, drains references, and stops all its devices, " +"the manager removes the corresponding interfaces. Devices that fail to " +"stop retain DMA and module code, allowing a later unload to retry." + +msgid "" +"e1000 和 e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO " +"寄存器。e1000e 发送前另行检查当前链路。收包轮询和协议定时器照常运行。" +msgstr "" +"e1000 and e1000e cache link-state samples per device and clock tick to " +"avoid repeated reads of the same MMIO register. e1000e also checks the " +"current link before sending. Receive polling and protocol timers continue" +" normally." msgid "" "旧 ``e1000_*`` 服务入口和 ReliefOS 旧网络管理请求查询首个存活接口。 旧驱动 API " "表和公开用户结构继续使用原布局。新设备接口属于 ReliefNT 私有 内核接口,原生模块通过精确构建 ABI 关联。" msgstr "" "Legacy ``e1000_*`` service entry points and legacy ReliefOS network-" -"management requests query the first surviving interface. The old driver API " -"table and public user structures retain their original layouts. The new " -"device interface is a ReliefNT private kernel interface, with native modules" -" associated through the exact build ABI." +"management requests query the first surviving interface. The old driver " +"API table and public user structures retain their original layouts. The " +"new device interface is a ReliefNT private kernel interface, with native " +"modules associated through the exact build ABI." msgid "Configuration and routing" msgstr "Configuration and routing" msgid "" "每张网卡拥有独立的行政状态、IPv4 地址、掩码、广播地址和默认网关。 IPv4 路由优先使用最长前缀,再比较 metric " -"和接口索引。绑定本机源地址和 ``SO_BINDTODEVICE`` 的 socket 按其约束选路。ARP 缓存按接口和下一跳地址 区分。TCP " -"路由变化时重新检查下一跳 MAC,向本机 NIC 地址发送的 TCP、UDP 保留目标接口身份。" +"和接口索引。绑定本机源地址和 ``SO_BINDTODEVICE`` 的 socket 按其约束选路。ARP 缓存按接口和下一跳地址 区分。TCP" +" 路由变化时重新检查下一跳 MAC,向本机 NIC 地址发送的 TCP、UDP 保留目标接口身份。" msgstr "" -"Each adapter has independent administrative state, IPv4 address, netmask, " -"broadcast address, and default gateway. IPv4 routing prefers the longest " -"prefix, then compares metric and interface index. Sockets bound to a local " -"source address or using ``SO_BINDTODEVICE`` select routes according to their" -" constraints. ARP caches are distinguished by interface and next-hop " -"address. TCP rechecks the next-hop MAC when routes change; TCP and UDP sent " -"to local NIC addresses retain the destination interface identity." +"Each adapter has independent administrative state, IPv4 address, netmask," +" broadcast address, and default gateway. IPv4 routing prefers the longest" +" prefix, then compares metric and interface index. Sockets bound to a " +"local source address or using ``SO_BINDTODEVICE`` select routes according" +" to their constraints. ARP caches are distinguished by interface and " +"next-hop address. TCP rechecks the next-hop MAC when routes change; TCP " +"and UDP sent to local NIC addresses retain the destination interface " +"identity." msgid "" -"IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 按网络空间隔离,并携带该空间的 ifindex。逐链路状态通过动态分配管理,RA、RS、DAD、MLD " -"和发现定时分别推进。不同链路可以使用相同 link-local 地址,socket 的作用域与设备绑定须一致。IPv6 表和队列的容量按网络空间分别计量,耗尽时返回错误。" +"IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 按网络空间隔离,并携带该空间的 " +"ifindex。逐链路状态通过动态分配管理,RA、RS、DAD、MLD 和发现定时分别推进。不同链路可以使用相同 link-local " +"地址,socket 的作用域与设备绑定须一致。IPv6 表和队列的容量按网络空间分别计量,耗尽时返回错误。" msgstr "" -"IPv6 addresses, routes, neighbors, multicast memberships, pending packets, reassembly and " -"PMTU are isolated by network namespace and carry that network's ifindex. Per-link state is " -"dynamically allocated, with independent RA, RS, DAD, MLD and discovery timing. Different " -"links may use the same link-local address, and socket scope must agree with device binding. " -"IPv6 tables and queues account capacity independently per network and return errors on " -"exhaustion." +"IPv6 addresses, routes, neighbors, multicast memberships, pending " +"packets, reassembly and PMTU are isolated by network namespace and carry " +"that network's ifindex. Per-link state is dynamically allocated, with " +"independent RA, RS, DAD, MLD and discovery timing. Different links may " +"use the same link-local address, and socket scope must agree with device " +"binding. IPv6 tables and queues account capacity independently per " +"network and return errors on exhaustion." -msgid "Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及行政状态开关。查询使用 socket 创建时保留的网络,接口配置修改需要该网络 user owner 的 ``CAP_NET_ADMIN``。首次设置 ``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要该 owner 的 ``CAP_NET_RAW``。AF_PACKET 和 raw socket 的创建同样要求该 owner 的 ``CAP_NET_RAW``。" -msgstr "Linux network management supports name and index queries, IPv4/IPv6 address and route operations, and administrative state changes. Queries use the socket's retained creating network. Interface changes require ``CAP_NET_ADMIN`` in that network's user owner. Initial ``SO_BINDTODEVICE`` is allowed for ordinary processes. Changing an existing device binding requires ``CAP_NET_RAW`` in that owner. AF_PACKET and raw socket creation also requires ``CAP_NET_RAW`` in that owner." +msgid "" +"Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及行政状态开关。查询使用 socket " +"创建时保留的网络,接口配置修改需要该网络 user owner 的 ``CAP_NET_ADMIN``。首次设置 " +"``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要该 owner 的 ``CAP_NET_RAW``。AF_PACKET " +"和 raw socket 的创建同样要求该 owner 的 ``CAP_NET_RAW``。" +msgstr "" +"Linux network management supports name and index queries, IPv4/IPv6 " +"address and route operations, and administrative state changes. Queries " +"use the socket's retained creating network. Interface changes require " +"``CAP_NET_ADMIN`` in that network's user owner. Initial " +"``SO_BINDTODEVICE`` is allowed for ordinary processes. Changing an " +"existing device binding requires ``CAP_NET_RAW`` in that owner. AF_PACKET" +" and raw socket creation also requires ``CAP_NET_RAW`` in that owner." msgid "" -"设备直接接收软件提交的帧,发送队列交由各设备的有界 DMA 环管理。 ``SIOCGIFTXQLEN`` 报告的软件队列长度为 0。硬件 MTU 为 " -"1500。" +"设备直接接收软件提交的帧,发送队列交由各设备的有界 DMA 环管理。 ``SIOCGIFTXQLEN`` 报告的软件队列长度为 0。硬件 MTU " +"为 1500。" msgstr "" "Devices directly receive frames submitted by software, and each device's " "bounded DMA rings manage its transmit queue. ``SIOCGIFTXQLEN`` reports a " "software queue length of 0. Hardware MTU is 1500." msgid "" -"``/proc/net/dev`` 列举所有已登记接口,包括未分配 IPv4 地址或行政关闭的设备。 ``SIOCGIFCONF`` 按 Linux 的" -" IPv4 地址列表语义输出 loopback 和有地址的接口。 枚举硬件接口可使用 rtnetlink 或 " +"``/proc/net/dev`` 列举所有已登记接口,包括未分配 IPv4 地址或行政关闭的设备。 ``SIOCGIFCONF`` 按 " +"Linux 的 IPv4 地址列表语义输出 loopback 和有地址的接口。 枚举硬件接口可使用 rtnetlink 或 " "``/proc/net/dev``,并按名称查询 ifindex。" msgstr "" -"``/proc/net/dev`` lists all registered interfaces, including devices without" -" an IPv4 address or administratively down. ``SIOCGIFCONF`` follows Linux " -"IPv4 address-list semantics and outputs loopback and interfaces with " -"addresses. Hardware interfaces can be enumerated with rtnetlink or " +"``/proc/net/dev`` lists all registered interfaces, including devices " +"without an IPv4 address or administratively down. ``SIOCGIFCONF`` follows" +" Linux IPv4 address-list semantics and outputs loopback and interfaces " +"with addresses. Hardware interfaces can be enumerated with rtnetlink or " "``/proc/net/dev``, with ifindex queried by name." +msgid "IPv6 host controls" +msgstr "IPv6 host controls" + +msgid "" +"``/proc/sys/net/ipv6/conf//`` 提供 " +"``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode`` 和 " +"``use_tempaddr``。配置和协议状态由网络空间持有。打开的文件保留目标网络和稳定 " +"ifindex,接口改名或调用者切换网络后继续操作原目标,接口移除后返回 ``ENODEV``。" +msgstr "" +"``/proc/sys/net/ipv6/conf//`` provides " +"``disable_ipv6``, ``accept_ra``, ``hop_limit``, ``addr_gen_mode`` and " +"``use_tempaddr``. The network namespace owns configuration and protocol " +"state. An open file retains its target network and stable ifindex across " +"interface renames and caller network changes. Interface removal returns " +"``ENODEV``." + +msgid "" +"控制文件为 0644,读取公开,写入按当前凭据检查全局 root 身份或目标网络 user owner 的 " +"``CAP_NET_ADMIN``,只读挂载仍拒绝写入。整数输入接受符号、十六进制、八进制及首尾 ASCII 空白,溢出和非法输入返回 " +"``EINVAL``。非零偏移写入消耗输入而不改变配置。" +msgstr "" +"Control files have mode 0644 and are publicly readable. Writes check " +"current credentials for global root identity or ``CAP_NET_ADMIN`` in the " +"target network's user owner. Read-only mounts reject writes. Integer " +"input accepts signs, hexadecimal, octal and surrounding ASCII whitespace." +" Overflow and malformed input return ``EINVAL``. Writes at nonzero " +"offsets consume input without changing configuration." + +msgid "" +"默认值为启用 IPv6、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0`` 和 " +"``use_tempaddr=0``。修改 ``default`` 影响随后创建的接口,已有接口包括行政关闭的接口保留原值。写入 " +"``all/disable_ipv6`` 或 ``all/addr_gen_mode`` 同时更新默认值和现存接口,其他 ``all`` " +"控制保留独立值。" +msgstr "" +"Defaults enable IPv6 with ``accept_ra=1``, ``hop_limit=64``, " +"``addr_gen_mode=0`` and ``use_tempaddr=0``. Changing ``default`` affects " +"interfaces created afterwards. Existing interfaces, including " +"administratively down interfaces, retain their values. Writes to " +"``all/disable_ipv6`` or ``all/addr_gen_mode`` update defaults and " +"existing interfaces together. Other ``all`` controls retain independent " +"values." + +msgid "" +"``disable_ipv6`` 接受 0 和 1,禁用时清理链路 IPv6 " +"状态并停止收发。重新启用时按链路配置恢复自动地址。``accept_ra`` 接受 0、1 和 2,0 停止内核 RA 处理和 RS,1 与 2 " +"启用当前主机模式的 RA 处理。官方 networkd 将该值设为 0 后,通过自己的发现协议处理 RA。``hop_limit`` 接受 1 至" +" 255,供未指定跳数的实际发包使用,内核接收的有效 RA 可以更新该值。" +msgstr "" +"``disable_ipv6`` accepts 0 and 1. Disabling clears link IPv6 state and " +"stops transmission and reception. Re-enabling restores automatic " +"addresses according to link policy. ``accept_ra`` accepts 0, 1 and 2. " +"Zero stops kernel RA processing and RS. Values 1 and 2 enable RA " +"processing in the current host mode. Official networkd sets this value to" +" zero and processes RA with its own discovery protocol. ``hop_limit`` " +"accepts 1 through 255 and supplies the actual packet hop limit when none " +"is specified. Valid RA received by the kernel can update it." + +msgid "" +"``addr_gen_mode`` 支持 EUI64 模式 0 和关闭自动链路本地地址的模式 1,切换为 1 保留已有地址。模式 2、3 和正数 " +"``use_tempaddr`` 返回 ``EOPNOTSUPP``,稳定隐私地址和临时地址生成仍待实现。``RTM_SETLINK`` 和 " +"``RTM_NEWLINK`` 接受 ``IFLA_AF_SPEC`` 下的 " +"``AF_INET6/IFLA_INET6_ADDR_GEN_MODE``,查询和链路通知回报实际模式,嵌套属性允许 " +"``NLA_F_NESTED`` 标记。" +msgstr "" +"``addr_gen_mode`` supports EUI64 mode 0 and mode 1, which disables " +"automatic link-local addresses. Switching to mode 1 retains existing " +"addresses. Modes 2 and 3 and positive ``use_tempaddr`` values return " +"``EOPNOTSUPP``. Stable-privacy and temporary address generation remain " +"pending. ``RTM_SETLINK`` and ``RTM_NEWLINK`` accept " +"``AF_INET6/IFLA_INET6_ADDR_GEN_MODE`` under ``IFLA_AF_SPEC``. Queries and" +" link notifications report the actual mode. Nested attributes accept " +"``NLA_F_NESTED`` markers." + +msgid "" +"启用控制先检查地址、路由和多播容量,再更新配置及协议表。分配或容量失败保留可见配置和协议状态,可在资源释放后重试。普通 Ethernet " +"链路在自动地址表耗尽时仍可用于手动地址配置。IPv4 次地址提升控制 ``promote_secondaries`` 仍待接入。" +msgstr "" +"Enable controls check address, route and multicast capacity before " +"updating configuration and protocol tables. Allocation or capacity " +"failure preserves visible controls and protocol state, allowing a retry " +"after resources are released. Ordinary Ethernet links remain available " +"for manual addresses when automatic-address tables are exhausted. IPv4 " +"secondary-address promotion through ``promote_secondaries`` remains " +"pending." + +msgid "IPv6 raw and ping errors" +msgstr "IPv6 raw and ping errors" + +msgid "" +"IPv6 raw socket 和 ICMPv6 ping socket 支持 ``IPV6_RECVERR``,每个 socket 独立保存最多" +" 32 条扩展错误。错误记录持有被引用报文的上层载荷、原目标地址、``sock_extended_err`` " +"和产生错误的节点地址,按创建网络、接口、作用域、本地地址及连接目标匹配。ping socket 还校验 Echo Request 类型、code " +"和 identifier。" +msgstr "" +"IPv6 raw and ICMPv6 ping sockets support ``IPV6_RECVERR``, retaining up " +"to 32 extended errors per socket. Each record owns the quoted upper-layer" +" payload, original destination, ``sock_extended_err`` and offender " +"address. Matching uses the creating network, interface, scope, local " +"address and connected destination. Ping sockets also validate the Echo " +"Request type, code and identifier." + +msgid "" +"``recvmsg(MSG_ERRQUEUE)`` 返回扩展错误控制消息,``recvfrom(MSG_ERRQUEUE)`` " +"返回载荷和原目标地址。外部 ``MSG_PEEK`` 仍消费一条错误,空错误队列返回 " +"``EAGAIN``。内部换页探测保留记录,输出内存准备成功后才消费。普通收包队列独立保留。``SO_ERROR`` 清除待报告 errno " +"后,未读扩展错误仍产生 ``POLLERR``。" +msgstr "" +"``recvmsg(MSG_ERRQUEUE)`` returns extended-error control messages, while " +"``recvfrom(MSG_ERRQUEUE)`` returns the payload and original destination. " +"External ``MSG_PEEK`` still consumes one error. An empty error queue " +"returns ``EAGAIN``. Internal swap probes retain the record until output " +"memory is prepared successfully. The ordinary receive queue remains " +"independent. Unread extended errors continue to report ``POLLERR`` after " +"``SO_ERROR`` clears the pending errno." + +msgid "" +"关闭 ``IPV6_RECVERR`` 清理扩展错误队列并保留待报告 errno。队列满或分配失败保留已有记录及待报告错误,最后关闭 socket" +" 时释放全部队列和网络引用。" +msgstr "" +"Disabling ``IPV6_RECVERR`` clears the extended-error queue and preserves " +"the pending errno. A full queue or allocation failure preserves existing " +"records and the pending error. Final socket close releases all queues and" +" network references." + msgid "Validation" msgstr "Validation" msgid "" "``tools/test_net_device.py`` 验证多个 owner、独立回调、计数和索引生命周期。 " "``tools/test_net_multi_interface.py`` 验证 ioctl、rtnetlink 和逐接口选路。 " -"``tools/test_net_multinic_data.py`` 验证 ARP、UDP 输出和 AF_PACKET 隔离。 既有 TCP、UDP " -"和 IPv6 定向套件覆盖对应传输的设备绑定、作用域与资源清理。" +"``tools/test_net_multinic_data.py`` 验证 ARP、UDP 输出和 AF_PACKET 隔离。 既有 " +"TCP、UDP 和 IPv6 定向套件覆盖对应传输的设备绑定、作用域与资源清理。" msgstr "" "``tools/test_net_device.py`` validates multiple owners, independent " "callbacks, counters, and index lifecycles. " -"``tools/test_net_multi_interface.py`` validates ioctl, rtnetlink, and per-" -"interface routing. ``tools/test_net_multinic_data.py`` validates ARP, UDP " -"output, and AF_PACKET isolation. Existing targeted TCP, UDP, and IPv6 suites" -" cover device binding, scope, and resource cleanup for their respective " -"transports." +"``tools/test_net_multi_interface.py`` validates ioctl, rtnetlink, and " +"per-interface routing. ``tools/test_net_multinic_data.py`` validates ARP," +" UDP output, and AF_PACKET isolation. Existing targeted TCP, UDP, and " +"IPv6 suites cover device binding, scope, and resource cleanup for their " +"respective transports." + +msgid "" +"``tools/test_ipv6_protocol.py`` " +"覆盖控制值、协议副作用、默认继承、网络隔离和容量失败重试。``tools/test_ipv6_control.py`` 覆盖 networkd " +"嵌套地址生成属性、查询及权限。``tools/test_procfs.py`` 覆盖控制文件的 VFS " +"生命周期、当前凭据、解析、只读挂载、改名、移除和内存失败。" +msgstr "" +"``tools/test_ipv6_protocol.py`` covers control values, protocol effects, " +"default inheritance, network isolation and capacity-failure retry. " +"``tools/test_ipv6_control.py`` covers networkd nested address-generation " +"attributes, queries and authority. ``tools/test_procfs.py`` covers " +"control-file VFS lifetime, current credentials, parsing, read-only " +"mounts, rename, removal and allocation failure." + +msgid "" +"``tools/test_ipv6_transport.py`` 使用实际 raw/ping 实现验证扩展错误、identifier " +"和网络隔离、队列容量、分配失败与关闭清理,并通过实际 ``recvmsg`` 入口验证辅助数据和换页重试期间的安全消费。" +msgstr "" +"``tools/test_ipv6_transport.py`` exercises the real raw/ping " +"implementation for extended errors, identifier and network isolation, " +"queue bounds, allocation failures and close cleanup. The real ``recvmsg``" +" entry validates ancillary data and safe consumption across swap retries." msgid "" "``tools/tests/multinic_guest.c`` 是标准 socket 用户程序探针,由 ReliefOS 的 " "``tools/test_multi_nic_qemu.py`` 放入私有来宾执行。来宾使用两张 e1000 和 一张 e1000e,验证独立 " -"DHCP、IPv4/IPv6、并发 TCP/UDP,以及模块卸载期间 另一 owner 的活动 TCP 连接。完整桌面镜像与实体硬件的运行验证分别记录。" -" VMware 验证未完成。" +"DHCP、IPv4/IPv6、并发 TCP/UDP,以及模块卸载期间 另一 owner 的活动 TCP " +"连接。完整桌面镜像与实体硬件的运行验证分别记录。 VMware 验证未完成。" msgstr "" -"``tools/tests/multinic_guest.c`` is a standard socket userspace probe placed" -" in a private guest by ReliefOS's ``tools/test_multi_nic_qemu.py``. The " -"guest uses two e1000 adapters and one e1000e to validate independent DHCP, " -"IPv4/IPv6, concurrent TCP/UDP, and an active TCP connection on another owner" -" during module unloading. Runtime validation of the full desktop image and " -"physical hardware is recorded separately. VMware validation is incomplete." +"``tools/tests/multinic_guest.c`` is a standard socket userspace probe " +"placed in a private guest by ReliefOS's ``tools/test_multi_nic_qemu.py``." +" The guest uses two e1000 adapters and one e1000e to validate independent" +" DHCP, IPv4/IPv6, concurrent TCP/UDP, and an active TCP connection on " +"another owner during module unloading. Runtime validation of the full " +"desktop image and physical hardware is recorded separately. VMware " +"validation is incomplete." msgid "References" msgstr "References" @@ -167,45 +341,3 @@ msgid "" msgstr "" "`IPv6 scoped address architecture, RFC 4007 `_" - -msgid "IPv6 host controls" -msgstr "IPv6 host controls" - -msgid "``/proc/sys/net/ipv6/conf//`` 提供 ``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode`` 和 ``use_tempaddr``。配置和协议状态由网络空间持有。打开的文件保留目标网络和稳定 ifindex,接口改名或调用者切换网络后继续操作原目标,接口移除后返回 ``ENODEV``。" -msgstr "``/proc/sys/net/ipv6/conf//`` provides ``disable_ipv6``, ``accept_ra``, ``hop_limit``, ``addr_gen_mode`` and ``use_tempaddr``. The network namespace owns configuration and protocol state. An open file retains its target network and stable ifindex across interface renames and caller network changes. Interface removal returns ``ENODEV``." - -msgid "控制文件为 0644,读取公开,写入按当前凭据检查全局 root 身份或目标网络 user owner 的 ``CAP_NET_ADMIN``,只读挂载仍拒绝写入。整数输入接受符号、十六进制、八进制及首尾 ASCII 空白,溢出和非法输入返回 ``EINVAL``。非零偏移写入消耗输入而不改变配置。" -msgstr "Control files have mode 0644 and are publicly readable. Writes check current credentials for global root identity or ``CAP_NET_ADMIN`` in the target network's user owner. Read-only mounts reject writes. Integer input accepts signs, hexadecimal, octal and surrounding ASCII whitespace. Overflow and malformed input return ``EINVAL``. Writes at nonzero offsets consume input without changing configuration." - -msgid "默认值为启用 IPv6、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0`` 和 ``use_tempaddr=0``。修改 ``default`` 影响随后创建的接口,已有接口包括行政关闭的接口保留原值。写入 ``all/disable_ipv6`` 或 ``all/addr_gen_mode`` 同时更新默认值和现存接口,其他 ``all`` 控制保留独立值。" -msgstr "Defaults enable IPv6 with ``accept_ra=1``, ``hop_limit=64``, ``addr_gen_mode=0`` and ``use_tempaddr=0``. Changing ``default`` affects interfaces created afterwards. Existing interfaces, including administratively down interfaces, retain their values. Writes to ``all/disable_ipv6`` or ``all/addr_gen_mode`` update defaults and existing interfaces together. Other ``all`` controls retain independent values." - -msgid "``disable_ipv6`` 接受 0 和 1,禁用时清理链路 IPv6 状态并停止收发。重新启用时按链路配置恢复自动地址。``accept_ra`` 接受 0、1 和 2,0 停止内核 RA 处理和 RS,1 与 2 启用当前主机模式的 RA 处理。官方 networkd 将该值设为 0 后,通过自己的发现协议处理 RA。``hop_limit`` 接受 1 至 255,供未指定跳数的实际发包使用,内核接收的有效 RA 可以更新该值。" -msgstr "``disable_ipv6`` accepts 0 and 1. Disabling clears link IPv6 state and stops transmission and reception. Re-enabling restores automatic addresses according to link policy. ``accept_ra`` accepts 0, 1 and 2. Zero stops kernel RA processing and RS. Values 1 and 2 enable RA processing in the current host mode. Official networkd sets this value to zero and processes RA with its own discovery protocol. ``hop_limit`` accepts 1 through 255 and supplies the actual packet hop limit when none is specified. Valid RA received by the kernel can update it." - -msgid "``addr_gen_mode`` 支持 EUI64 模式 0 和关闭自动链路本地地址的模式 1,切换为 1 保留已有地址。模式 2、3 和正数 ``use_tempaddr`` 返回 ``EOPNOTSUPP``,稳定隐私地址和临时地址生成仍待实现。``RTM_SETLINK`` 和 ``RTM_NEWLINK`` 接受 ``IFLA_AF_SPEC`` 下的 ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE``,查询和链路通知回报实际模式,嵌套属性允许 ``NLA_F_NESTED`` 标记。" -msgstr "``addr_gen_mode`` supports EUI64 mode 0 and mode 1, which disables automatic link-local addresses. Switching to mode 1 retains existing addresses. Modes 2 and 3 and positive ``use_tempaddr`` values return ``EOPNOTSUPP``. Stable-privacy and temporary address generation remain pending. ``RTM_SETLINK`` and ``RTM_NEWLINK`` accept ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE`` under ``IFLA_AF_SPEC``. Queries and link notifications report the actual mode. Nested attributes accept ``NLA_F_NESTED`` markers." - -msgid "启用控制先检查地址、路由和多播容量,再更新配置及协议表。分配或容量失败保留可见配置和协议状态,可在资源释放后重试。普通 Ethernet 链路在自动地址表耗尽时仍可用于手动地址配置。IPv4 次地址提升控制 ``promote_secondaries`` 仍待接入。" -msgstr "Enable controls check address, route and multicast capacity before updating configuration and protocol tables. Allocation or capacity failure preserves visible controls and protocol state, allowing a retry after resources are released. Ordinary Ethernet links remain available for manual addresses when automatic-address tables are exhausted. IPv4 secondary-address promotion through ``promote_secondaries`` remains pending." - -msgid "``tools/test_ipv6_protocol.py`` 覆盖控制值、协议副作用、默认继承、网络隔离和容量失败重试。``tools/test_ipv6_control.py`` 覆盖 networkd 嵌套地址生成属性、查询及权限。``tools/test_procfs.py`` 覆盖控制文件的 VFS 生命周期、当前凭据、解析、只读挂载、改名、移除和内存失败。" -msgstr "``tools/test_ipv6_protocol.py`` covers control values, protocol effects, default inheritance, network isolation and capacity-failure retry. ``tools/test_ipv6_control.py`` covers networkd nested address-generation attributes, queries and authority. ``tools/test_procfs.py`` covers control-file VFS lifetime, current credentials, parsing, read-only mounts, rename, removal and allocation failure." - -msgid "IPv6 raw and ping errors" -msgstr "IPv6 raw and ping errors" - -msgid "IPv6 raw socket 和 ICMPv6 ping socket 支持 ``IPV6_RECVERR``,每个 socket 独立保存最多 32 条扩展错误。错误记录持有被引用报文的上层载荷、原目标地址、``sock_extended_err`` 和产生错误的节点地址,按创建网络、接口、作用域、本地地址及连接目标匹配。ping socket 还校验 Echo Request 类型、code 和 identifier。" -msgstr "IPv6 raw and ICMPv6 ping sockets support ``IPV6_RECVERR``, retaining up to 32 extended errors per socket. Each record owns the quoted upper-layer payload, original destination, ``sock_extended_err`` and offender address. Matching uses the creating network, interface, scope, local address and connected destination. Ping sockets also validate the Echo Request type, code and identifier." - -msgid "``recvmsg(MSG_ERRQUEUE)`` 返回扩展错误控制消息,``recvfrom(MSG_ERRQUEUE)`` 返回载荷和原目标地址。外部 ``MSG_PEEK`` 仍消费一条错误,空错误队列返回 ``EAGAIN``。内部换页探测保留记录,输出内存准备成功后才消费。普通收包队列独立保留。``SO_ERROR`` 清除待报告 errno 后,未读扩展错误仍产生 ``POLLERR``。" -msgstr "``recvmsg(MSG_ERRQUEUE)`` returns extended-error control messages, while ``recvfrom(MSG_ERRQUEUE)`` returns the payload and original destination. External ``MSG_PEEK`` still consumes one error. An empty error queue returns ``EAGAIN``. Internal swap probes retain the record until output memory is prepared successfully. The ordinary receive queue remains independent. Unread extended errors continue to report ``POLLERR`` after ``SO_ERROR`` clears the pending errno." - -msgid "关闭 ``IPV6_RECVERR`` 清理扩展错误队列并保留待报告 errno。队列满或分配失败保留已有记录及待报告错误,最后关闭 socket 时释放全部队列和网络引用。" -msgstr "Disabling ``IPV6_RECVERR`` clears the extended-error queue and preserves the pending errno. A full queue or allocation failure preserves existing records and the pending error. Final socket close releases all queues and network references." - -msgid "``tools/test_ipv6_transport.py`` 使用实际 raw/ping 实现验证扩展错误、identifier 和网络隔离、队列容量、分配失败与关闭清理,并通过实际 ``recvmsg`` 入口验证辅助数据和换页重试期间的安全消费。" -msgstr "``tools/test_ipv6_transport.py`` exercises the real raw/ping implementation for extended errors, identifier and network isolation, queue bounds, allocation failures and close cleanup. The real ``recvmsg`` entry validates ancillary data and safe consumption across swap retries." - -msgid "e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO 寄存器。实际发送仍检查当前链路,驱动没有关闭收包轮询或协议定时器。" -msgstr "e1000e carrier queries reuse one hardware sample per device per tick instead of repeatedly reading the same MMIO register. Transmit still checks the live link; receive polling and protocol timers remain enabled." diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/realtek.po b/Documentation/locale/en/LC_MESSAGES/core-api/realtek.po index 78d6e748..0910dd48 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/realtek.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/realtek.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0800\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "Realtek PCIe 以太网驱动" msgstr "Realtek PCIe Ethernet driver" @@ -20,21 +23,21 @@ msgid "设备与配置" msgstr "Devices and configuration" msgid "" -"``drivers/net/r8169/`` 提供 ReliefNT 原生网卡驱动。``CONFIG_R8169`` 为 tristate,``make" -" defconfig`` 默认选择 ``y``。选择 ``m`` 生成 ``drivers/net/r8169/r8169.ko``,由普通 " -"``modprobe`` 根据 PCI 别名加载。" +"``drivers/net/r8169/`` 提供 ReliefNT 原生网卡驱动。``CONFIG_R8169`` 为 " +"tristate,``make defconfig`` 默认选择 ``y``。选择 ``m`` 生成 " +"``drivers/net/r8169/r8169.ko``,由普通 ``modprobe`` 根据 PCI 别名加载。" msgstr "" "``drivers/net/r8169/`` provides a native ReliefNT network driver. " "``CONFIG_R8169`` is tristate, and ``make defconfig`` selects ``y`` by " -"default. Selecting ``m`` generates ``drivers/net/r8169/r8169.ko``, loaded by" -" ordinary ``modprobe`` using PCI aliases." +"default. Selecting ``m`` generates ``drivers/net/r8169/r8169.ko``, loaded" +" by ordinary ``modprobe`` using PCI aliases." msgid "" "设备表包含 ``10ec:8168`` 和 ``10ec:8125``。驱动进一步读取 TxConfig 中的硬件版本,分别选择初始化、PHY " "和固件流程。" msgstr "" -"The device table includes ``10ec:8168`` and ``10ec:8125``. The driver also " -"reads the hardware revision in TxConfig to select the respective " +"The device table includes ``10ec:8168`` and ``10ec:8125``. The driver " +"also reads the hardware revision in TxConfig to select the respective " "initialization, PHY, and firmware procedures." msgid "已实现的芯片版本路径" @@ -50,8 +53,8 @@ msgid "``10ec:8168``" msgstr "``10ec:8168``" msgid "" -"RTL8111/8168 B、C、CP、D、DP、E、E-VL、F、G、GU、H、EP、FP。 按 OpenBSD 的版本掩码区分家族与 B/C 的 " -"spin。" +"RTL8111/8168 B、C、CP、D、DP、E、E-VL、F、G、GU、H、EP、FP。 按 OpenBSD 的版本掩码区分家族与 B/C " +"的 spin。" msgstr "" "RTL8111/8168 B, C, CP, D, DP, E, E-VL, F, G, GU, H, EP, and FP. OpenBSD " "revision masks distinguish families and B/C spins." @@ -71,76 +74,77 @@ msgid "" "``driver_register_netdev`` 注册 ``eth0``、``eth1`` 等接口。网络用户程序使用 Linux " "socket、ioctl、netlink 和 proc 接口。接口生命周期和多网卡选路见 :doc:`network-devices`。" msgstr "" -"Unknown MAC families return ``-ENODEV``. The driver enumerates all matching " -"PCI functions, allocates independent DMA rings and contexts for each " -"adapter, and registers interfaces such as ``eth0`` and ``eth1`` through the " -"private ``driver_register_netdev``. Network user programs use Linux socket, " -"ioctl, netlink, and proc interfaces. See :doc:`network-devices` for " -"interface lifecycles and routing across multiple adapters." +"Unknown MAC families return ``-ENODEV``. The driver enumerates all " +"matching PCI functions, allocates independent DMA rings and contexts for " +"each adapter, and registers interfaces such as ``eth0`` and ``eth1`` " +"through the private ``driver_register_netdev``. Network user programs use" +" Linux socket, ioctl, netlink, and proc interfaces. See :doc:`network-" +"devices` for interface lifecycles and routing across multiple adapters." msgid "" -"无网线时接口仍可查询和配置,载波状态来自硬件。PHY 自动协商覆盖 10/100/1000 Mb/s,RTL8125 另行通告 2500BASE-T " -"全双工。协商异步完成。 PHY、EPHY、CSI、固件握手和复位均有界等待,失败返回具体 errno。" +"无网线时接口仍可查询和配置,载波状态来自硬件。PHY 自动协商覆盖 10/100/1000 Mb/s,RTL8125 另行通告 " +"2500BASE-T 全双工。协商异步完成。 PHY、EPHY、CSI、固件握手和复位均有界等待,失败返回具体 errno。" msgstr "" -"Interfaces remain queryable and configurable without a cable, and carrier " -"state comes from hardware. PHY autonegotiation covers 10/100/1000 Mb/s, with" -" RTL8125 additionally advertising 2500BASE-T full duplex. Negotiation " -"completes asynchronously. PHY, EPHY, CSI, firmware handshakes, and reset all" -" use bounded waits and return specific errno values on failure." +"Interfaces remain queryable and configurable without a cable, and carrier" +" state comes from hardware. PHY autonegotiation covers 10/100/1000 Mb/s, " +"with RTL8125 additionally advertising 2500BASE-T full duplex. Negotiation" +" completes asynchronously. PHY, EPHY, CSI, firmware handshakes, and reset" +" all use bounded waits and return specific errno values on failure." msgid "" "硬件初始化中的微秒级稳定等待使用启动时间采样;短于 1 ms 的等待最多 轮询 4096 次,且采样期间关闭本地中断以避免 CPU " "迁移。时钟停滞、回退或 达到轮询上限时改用 tick 等待;较长等待也使用 tick 等待,并额外加入一整个 tick,以覆盖请求恰好接近下一个 " "tick 的情况。等待返回后恢复原中断状态, 调用方不得持有自旋锁。短等待依赖内核启动时钟的精度;该时钟突然向前跳变 可能缩短等待。" msgstr "" -"Microsecond stabilization waits during hardware initialization use boot-time" -" clock samples. Waits shorter than 1 ms poll at most 4096 times, with local " -"interrupts disabled during sampling to avoid CPU migration. If the clock " -"stalls, moves backward, or the poll limit is reached, waiting switches to " -"ticks. Longer waits also use ticks and add one full tick to cover requests " -"made just before the next tick. The original interrupt state is restored on " -"return; callers must not hold spinlocks. Short waits depend on the accuracy " -"of the kernel boot clock; a sudden forward jump can shorten a wait." +"Microsecond stabilization waits during hardware initialization use boot-" +"time clock samples. Waits shorter than 1 ms poll at most 4096 times, with" +" local interrupts disabled during sampling to avoid CPU migration. If the" +" clock stalls, moves backward, or the poll limit is reached, waiting " +"switches to ticks. Longer waits also use ticks and add one full tick to " +"cover requests made just before the next tick. The original interrupt " +"state is restored on return; callers must not hold spinlocks. Short waits" +" depend on the accuracy of the kernel boot clock; a sudden forward jump " +"can shorten a wait." msgid "收发和生命周期" msgstr "Transmit/receive and lifecycle" msgid "" -"驱动优先映射 PCI BAR2,再尝试其他有效内存 BAR,支持 64 位地址。 PCI 电源管理使用常规 capability 链请求 D0。原始 " -"MAC 在复位前读取并保留, 无效地址导致初始化失败。 早期 RTL8168 的控制 BAR 可能只有 256 字节,此时可通过该设备的 I/O BAR" -" 访问同一寄存器组。PCI 内存映射仍要求完整页面位于有效 BAR 内。" +"驱动优先映射 PCI BAR2,再尝试其他有效内存 BAR,支持 64 位地址。 PCI 电源管理使用常规 capability 链请求 " +"D0。原始 MAC 在复位前读取并保留, 无效地址导致初始化失败。 早期 RTL8168 的控制 BAR 可能只有 256 " +"字节,此时可通过该设备的 I/O BAR 访问同一寄存器组。PCI 内存映射仍要求完整页面位于有效 BAR 内。" msgstr "" "The driver first tries to map PCI BAR2, then other valid memory BARs, " -"supporting 64-bit addresses. PCI power management requests D0 through the " -"standard capability chain. The original MAC is read and retained before " -"reset; an invalid address fails initialization. Early RTL8168 control BARs " -"may be only 256 bytes, in which case the device's I/O BAR can access the " -"same register set. PCI memory mappings still require a complete page within " -"a valid BAR." +"supporting 64-bit addresses. PCI power management requests D0 through the" +" standard capability chain. The original MAC is read and retained before " +"reset; an invalid address fails initialization. Early RTL8168 control " +"BARs may be only 256 bytes, in which case the device's I/O BAR can access" +" the same register set. PCI memory mappings still require a complete page" +" within a valid BAR." msgid "" -"RX/TX 各使用 256 个 16 字节经典描述符和 2048 字节缓冲区。RTL8125 显式选择经典布局。描述符保留物理 DMA 地址,CPU " -"通过独立映射访问数据。 所有权交接使用 acquire/release 屏障,发送与接收有独立的短临界区。 当前使用单队列轮询,MTU 为 " -"1500,IP/传输层校验和由现有网络栈计算。" +"RX/TX 各使用 256 个 16 字节经典描述符和 2048 字节缓冲区。RTL8125 显式选择经典布局。描述符保留物理 DMA " +"地址,CPU 通过独立映射访问数据。 所有权交接使用 acquire/release 屏障,发送与接收有独立的短临界区。 " +"当前使用单队列轮询,MTU 为 1500,IP/传输层校验和由现有网络栈计算。" msgstr "" -"RX and TX each use 256 classic 16-byte descriptors and 2048-byte buffers. " -"RTL8125 explicitly selects the classic layout. Descriptors retain physical " -"DMA addresses, while the CPU accesses data through separate mappings. " -"Ownership handoff uses acquire/release barriers, with separate short " -"critical sections for transmit and receive. The current implementation uses " -"single-queue polling with an MTU of 1500, and the existing network stack " -"computes IP/transport checksums." +"RX and TX each use 256 classic 16-byte descriptors and 2048-byte buffers." +" RTL8125 explicitly selects the classic layout. Descriptors retain " +"physical DMA addresses, while the CPU accesses data through separate " +"mappings. Ownership handoff uses acquire/release barriers, with separate " +"short critical sections for transmit and receive. The current " +"implementation uses single-queue polling with an MTU of 1500, and the " +"existing network stack computes IP/transport checksums." msgid "" "发送帧补零到最小 Ethernet 长度,再由硬件附加 FCS。队列满返回 ``-EAGAIN``。接收检查错误、缓冲区与调用者容量,移除一个 " "FCS,并完整 丢弃跨描述符的异常分片链。接收过滤器接受本站单播、广播和多播,供 IPv4 ARP、DHCP 与 IPv6 邻居发现使用。" msgstr "" "Transmit frames are zero-padded to the minimum Ethernet length before " -"hardware appends the FCS. A full queue returns ``-EAGAIN``. Receive checks " -"errors, buffer capacity, and caller capacity, removes one FCS, and drops " -"abnormal fragment chains spanning descriptors in full. Receive filters " -"accept local unicast, broadcast, and multicast for IPv4 ARP, DHCP, and IPv6 " -"neighbor discovery." +"hardware appends the FCS. A full queue returns ``-EAGAIN``. Receive " +"checks errors, buffer capacity, and caller capacity, removes one FCS, and" +" drops abnormal fragment chains spanning descriptors in full. Receive " +"filters accept local unicast, broadcast, and multicast for IPv4 ARP, " +"DHCP, and IPv6 neighbor discovery." msgid "" "初始化先禁用 PCI bus master 并确认控制器复位,再分配和发布 DMA 队列。 卸载由模块 owner " @@ -148,10 +152,11 @@ msgid "" "保持关闭。" msgstr "" "Initialization first disables PCI bus mastering and confirms controller " -"reset, then allocates and publishes DMA queues. During unloading, the module" -" owner closes callback admission and drains in-flight calls before stopping " -"transmit/receive and resetting. A stop failure retains DMA, MMIO, and module" -" code for retry. PCI bus mastering remains disabled after memory is freed." +"reset, then allocates and publishes DMA queues. During unloading, the " +"module owner closes callback admission and drains in-flight calls before " +"stopping transmit/receive and resetting. A stop failure retains DMA, " +"MMIO, and module code for retry. PCI bus mastering remains disabled after" +" memory is freed." msgid "固件和许可" msgstr "Firmware and licensing" @@ -160,28 +165,28 @@ msgid "" "RTL8125 的 MAC/PHY 固件以未经修改的常量寄存器对嵌入内核或模块,启动时 按芯片版本选择。构建消费仓库内数据。运行时无需网络下载。 " "固件在完成写入与握手后才更新版本标记,并回读确认。" msgstr "" -"RTL8125 MAC/PHY firmware is embedded in the kernel or module as unmodified " -"constant register pairs and selected by chip revision at startup. The build " -"consumes data in the repository; no network download is required at runtime." -" Firmware version markers are updated only after writing and handshaking " -"complete, then read back for confirmation." +"RTL8125 MAC/PHY firmware is embedded in the kernel or module as " +"unmodified constant register pairs and selected by chip revision at " +"startup. The build consumes data in the repository; no network download " +"is required at runtime. Firmware version markers are updated only after " +"writing and handshaking complete, then read back for confirmation." msgid "" "硬件初始化改编自 OpenBSD src 提交 ``7779d12194498048b288afda664dd6271a2ec016``。 " "RTL8111/8168 派生代码保留 BSD-4-Clause,RTL8125 派生代码保留 ISC, 固件保留 Realtek " "的再分发许可。项目新增的 PCI/DMA/模块连接代码使用 Apache-2.0。完整声明见 ``NOTICE`` 和 " -"``LICENSES/realtek/``。 ``modules_install`` 将声明放入版本化模块目录的 ``LICENSES/``,连同 " -"模块加入安装所有权和校验清单,并随 ReliefOS 的内核载荷分发。" +"``LICENSES/realtek/``。 ``modules_install`` 将声明放入版本化模块目录的 ``LICENSES/``,连同" +" 模块加入安装所有权和校验清单,并随 ReliefOS 的内核载荷分发。" msgstr "" "Hardware initialization is adapted from OpenBSD src commit " "``7779d12194498048b288afda664dd6271a2ec016``. RTL8111/8168-derived code " -"retains BSD-4-Clause, RTL8125-derived code retains ISC, and firmware retains" -" Realtek's redistribution license. New project PCI/DMA/module integration " -"code uses Apache-2.0. Full notices are in ``NOTICE`` and " +"retains BSD-4-Clause, RTL8125-derived code retains ISC, and firmware " +"retains Realtek's redistribution license. New project PCI/DMA/module " +"integration code uses Apache-2.0. Full notices are in ``NOTICE`` and " "``LICENSES/realtek/``. ``modules_install`` places the notices in " -"``LICENSES/`` in the versioned module directory, includes them with modules " -"in installation ownership and checksum manifests, and distributes them with " -"the ReliefOS kernel payload." +"``LICENSES/`` in the versioned module directory, includes them with " +"modules in installation ownership and checksum manifests, and distributes" +" them with the ReliefOS kernel payload." msgid "This product includes software developed by Bill Paul." msgstr "This product includes software developed by Bill Paul." @@ -219,34 +224,34 @@ msgstr "Validation coverage" msgid "" "``tools/test_r8169.py`` 编译真实驱动对象并模拟 PCI/MMIO/DMA 边界,另行编译 " -"真实寄存器与等待实现,检查时钟边界、中断状态和不同寄存器访问方式。 它覆盖 4 GiB 以上地址、收发回绕、长度与错误检查、补零、无载波、资源分配 " -"失败、owner 冲突、停止失败保留与重试。芯片模型覆盖四个 RTL8125 版本和 RTL8168 家族路径。真实 PHY 协商、DMA " +"真实寄存器与等待实现,检查时钟边界、中断状态和不同寄存器访问方式。 它覆盖 4 GiB 以上地址、收发回绕、长度与错误检查、补零、无载波、资源分配" +" 失败、owner 冲突、停止失败保留与重试。芯片模型覆盖四个 RTL8125 版本和 RTL8168 家族路径。真实 PHY 协商、DMA " "时序和实体网线收发仍需对应硬件验证。" msgstr "" "``tools/test_r8169.py`` compiles actual driver objects and models the " "PCI/MMIO/DMA boundary. It separately compiles the real register and wait " -"implementations to check clock boundaries, interrupt state, and different " -"register access methods. Coverage includes addresses above 4 GiB, " +"implementations to check clock boundaries, interrupt state, and different" +" register access methods. Coverage includes addresses above 4 GiB, " "transmit/receive wraparound, length and error checks, zero padding, no " -"carrier, resource-allocation failures, owner conflicts, and retention and " -"retry after stop failure. Chip models cover four RTL8125 revisions and " -"RTL8168 family paths. Actual PHY negotiation, DMA timing, and physical cable" -" traffic still require validation on the corresponding hardware." +"carrier, resource-allocation failures, owner conflicts, and retention and" +" retry after stop failure. Chip models cover four RTL8125 revisions and " +"RTL8168 family paths. Actual PHY negotiation, DMA timing, and physical " +"cable traffic still require validation on the corresponding hardware." msgid "" "本次 QEMU 回归覆盖默认内置启动,以及无匹配 Realtek 硬件时三次 ``r8169.ko`` 加载与卸载。既有 e1000 的 " -"IPv4、IPv6 ping 均通过。 测试使用当前新编译内核和私有 initramfs,BusyBox 来自已有 ReliefOS 构建。" +"IPv4、IPv6 ping 均通过。 测试在匹配当前内核的 ReliefOS 构建镜像上运行,使用私有测试磁盘。" msgstr "" -"This QEMU regression covers default built-in boot and three load/unload " -"cycles of ``r8169.ko`` without matching Realtek hardware. Existing e1000 " -"IPv4 and IPv6 ping tests both pass. Tests use the newly compiled current " -"kernel and a private initramfs, with BusyBox from an existing ReliefOS " -"build." +"The QEMU regression covered built-in boot and three load/unload cycles of" +" ``r8169.ko`` without matching Realtek hardware. The existing e1000 " +"passed IPv4 and IPv6 ping. The checks use a private disk with the " +"corresponding ReliefOS build image." msgid "" "本地 QEMU 只提供 RTL8139 Realtek 模型,真实 RTL8111/8168、RTL8125 需要实体网卡或正确的 PCI " "直通验证。实体网卡验证未完成。VMware 验证未完成。" msgstr "" -"Local QEMU provides only the RTL8139 Realtek model; actual RTL8111/8168 and " -"RTL8125 require physical adapters or correct PCI passthrough validation. " -"Physical-adapter validation is incomplete. VMware validation is incomplete." +"Local QEMU provides only the RTL8139 Realtek model; actual RTL8111/8168 " +"and RTL8125 require physical adapters or correct PCI passthrough " +"validation. Physical-adapter validation is incomplete. VMware validation " +"is incomplete." diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/resource-limits.po b/Documentation/locale/en/LC_MESSAGES/core-api/resource-limits.po index 7b0f9d68..a773979e 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/resource-limits.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/resource-limits.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0800\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "资源容量与 Linux ABI" msgstr "Resource capacity and the Linux ABI" @@ -26,18 +29,19 @@ msgstr "" "ranges still limit resource counts." msgid "" -"``/proc/PID/oom_score`` 使用独立的 Linux 6.12 风格 0..2000 展示值, 不改变内部 OOM 选择策略。RSS " -"只计入有实际 RAM 后备的用户页面,另计 swap 槽引用,不把设备 PFN 当作 RAM。``oom_score_adj`` 的读取和写入先 " -"经过普通 proc DAC 与 PID 身份检查;降低到继承的下限以下需要 ``CAP_SYS_RESOURCE``。进程退出后保留的 proc " -"身份不会指向重用的 PID。" +"``/proc/PID/oom_score`` 使用独立的 Linux 6.12 风格 0..2000 展示值, 不改变内部 OOM " +"选择策略。RSS 只计入有实际 RAM 后备的用户页面,另计 swap 槽引用,不把设备 PFN 当作 RAM。``oom_score_adj``" +" 的读取和写入先 经过普通 proc DAC 与 PID 身份检查;降低到继承的下限以下需要 " +"``CAP_SYS_RESOURCE``。进程退出后保留的 proc 身份不会指向重用的 PID。" msgstr "" -"``/proc/PID/oom_score`` uses a separate Linux 6.12-style display value of " -"0..2000 without changing the internal OOM selection policy. RSS counts only " -"user pages with actual RAM backing, with swap-slot references counted " -"separately; device PFNs are not treated as RAM. Reads and writes of " -"``oom_score_adj`` first pass ordinary proc DAC and PID identity checks; " -"lowering it below the inherited floor requires ``CAP_SYS_RESOURCE``. A proc " -"identity retained after process exit does not point to a reused PID." +"``/proc/PID/oom_score`` uses a separate Linux 6.12-style display value of" +" 0..2000 without changing the internal OOM selection policy. RSS counts " +"only user pages with actual RAM backing, with swap-slot references " +"counted separately; device PFNs are not treated as RAM. Reads and writes " +"of ``oom_score_adj`` first pass ordinary proc DAC and PID identity " +"checks; lowering it below the inherited floor requires " +"``CAP_SYS_RESOURCE``. A proc identity retained after process exit does " +"not point to a reused PID." msgid "容量与生命周期" msgstr "Capacity and lifecycles" @@ -51,67 +55,67 @@ msgid "" "控制文件不套用普通文件大小配额。OpenSSH 的预认证沙箱可以将此限制降为 零,不会因此获得不受限制的文件写入能力。" msgstr "" "``getrlimit``, ``setrlimit``, and ``prlimit64`` support process-shared " -"``RLIMIT_FSIZE``. New processes default to unlimited soft and hard limits, " -"inherited through fork/exec. Regular-file writes return valid short writes " -"at the boundary; further writes at or beyond it return ``EFBIG`` and send " -"``SIGXFSZ``. Truncation and preallocation that grows a file check the new " -"size before writing; ``FALLOC_FL_KEEP_SIZE`` does not change logical size " -"when the preallocated range exceeds the limit. File copying and memfd/shmem " -"writes are also subject to this limit; devices, pipes, and generated " -"proc/sysfs control files do not use regular-file size quotas. OpenSSH's pre-" -"authentication sandbox can lower this limit to zero without thereby " -"acquiring unrestricted file-writing ability." +"``RLIMIT_FSIZE``. New processes default to unlimited soft and hard " +"limits, inherited through fork/exec. Regular-file writes return valid " +"short writes at the boundary; further writes at or beyond it return " +"``EFBIG`` and send ``SIGXFSZ``. Truncation and preallocation that grows a" +" file check the new size before writing; ``FALLOC_FL_KEEP_SIZE`` does not" +" change logical size when the preallocated range exceeds the limit. File " +"copying and memfd/shmem writes are also subject to this limit; devices, " +"pipes, and generated proc/sysfs control files do not use regular-file " +"size quotas. OpenSSH's pre-authentication sandbox can lower this limit to" +" zero without thereby acquiring unrestricted file-writing ability." msgid "" "任务枚举直接遍历调度器的任务表。``/proc`` 的进程列表、线程统计以及 memfd 的可写共享映射检查不截断为前 64 " "个任务。描述符目录使用实际文件表 和 PTY 别名,不截断为前 1024 个描述符。" msgstr "" -"Task enumeration walks the scheduler's task table directly. Process lists " -"and thread statistics in ``/proc``, and memfd writable-shared-mapping " -"checks, are not truncated to the first 64 tasks. Descriptor directories use " -"the actual file table and PTY aliases, without truncation to the first 1024 " -"descriptors." +"Task enumeration walks the scheduler's task table directly. Process lists" +" and thread statistics in ``/proc``, and memfd writable-shared-mapping " +"checks, are not truncated to the first 64 tasks. Descriptor directories " +"use the actual file table and PTY aliases, without truncation to the " +"first 1024 descriptors." msgid "" -"内部对象注册表按需扩容,扩容不移动对象,分配在自旋锁外完成。句柄保留 16 位槽号和 16 位代际编码,最多表示 65535 个同时存在的槽;此编码上限" -" 仍然存在。查找句柄只返回借用引用,调用方必须按所属子系统的锁和引用规则 保证对象存活。" +"内部对象注册表按需扩容,扩容不移动对象,分配在自旋锁外完成。句柄保留 16 位槽号和 16 位代际编码,最多表示 65535 " +"个同时存在的槽;此编码上限 仍然存在。查找句柄只返回借用引用,调用方必须按所属子系统的锁和引用规则 保证对象存活。" msgstr "" "Internal object registries grow on demand without moving objects, and " -"allocation happens outside spinlocks. Handles retain a 16-bit slot number " -"and 16-bit generation encoding, representing at most 65535 simultaneous " -"slots; this encoding limit remains. Handle lookup returns only a borrowed " -"reference, and callers must preserve object lifetime under the owning " +"allocation happens outside spinlocks. Handles retain a 16-bit slot number" +" and 16-bit generation encoding, representing at most 65535 simultaneous " +"slots; this encoding limit remains. Handle lookup returns only a borrowed" +" reference, and callers must preserve object lifetime under the owning " "subsystem's locking and reference rules." msgid "等待队列使用任务内嵌链表节点。IRQ 唤醒不分配内存;任务退出和取消等待 必须先脱链。队列本身的存储必须活到所有等待者脱离后才能释放。" msgstr "" "Wait queues use list nodes embedded in tasks. IRQ wakeup allocates no " -"memory; task exit and wait cancellation must first unlink the node. Queue " -"storage itself must remain alive until all waiters have detached." +"memory; task exit and wait cancellation must first unlink the node. Queue" +" storage itself must remain alive until all waiters have detached." msgid "" "epoll 监听表按需扩容;注册键由描述符编号和打开文件描述共同确定。 关闭一个编号后,``dup``、``fork``、排队中的 " "``SCM_RIGHTS`` 或在途 I/O 引用仍可维持原对象的监听;重新使用该编号不会把旧监听转向新对象。 " -"监听项只借用稳定的对象身份,最终引用释放时反向清除监听,不延长对象生命周期。 当前不支持嵌套 epoll,向 epoll 实例注册另一个 epoll " -"实例时返回 ``EPERM``; 直接 ``poll`` epoll 描述符只查看已就绪的监听项,不消费 ET/ONESHOT 状态。 原始 " -"``select``/``pselect6`` 系统调用按 ``nfds`` 复制位图,并检查 " +"监听项只借用稳定的对象身份,最终引用释放时反向清除监听,不延长对象生命周期。 当前不支持嵌套 epoll,向 epoll 实例注册另一个 " +"epoll 实例时返回 ``EPERM``; 直接 ``poll`` epoll 描述符只查看已就绪的监听项,不消费 ET/ONESHOT 状态。" +" 原始 ``select``/``pselect6`` 系统调用按 ``nfds`` 复制位图,并检查 " "``RLIMIT_NOFILE``、溢出、无效描述符和用户指针。libc 的 ``fd_set`` 大小 由 libc 决定,不能用 " "``FD_SET`` 操作其表示范围以外的描述符。" msgstr "" -"epoll watch tables grow on demand; registration keys combine the descriptor " -"number and open file description. After a number is closed, ``dup``, " -"``fork``, queued ``SCM_RIGHTS``, or in-flight I/O references can keep the " -"original object's watch alive; reusing the number does not redirect the old " -"watch to a new object. Watch entries only borrow a stable object identity " -"and are removed through reverse cleanup when the final reference is " -"released, without extending object lifetime. Nested epoll is currently " -"unsupported; registering another epoll instance with an epoll instance " -"returns ``EPERM``. Directly using ``poll`` on an epoll descriptor only " -"inspects ready watches without consuming ET/ONESHOT state. Raw " -"``select``/``pselect6`` syscalls copy bitmaps according to ``nfds`` and " -"check ``RLIMIT_NOFILE``, overflow, invalid descriptors, and user pointers. " -"libc determines its ``fd_set`` size; ``FD_SET`` must not be used on " -"descriptors beyond its representable range." +"epoll watch tables grow on demand; registration keys combine the " +"descriptor number and open file description. After a number is closed, " +"``dup``, ``fork``, queued ``SCM_RIGHTS``, or in-flight I/O references can" +" keep the original object's watch alive; reusing the number does not " +"redirect the old watch to a new object. Watch entries only borrow a " +"stable object identity and are removed through reverse cleanup when the " +"final reference is released, without extending object lifetime. Nested " +"epoll is currently unsupported; registering another epoll instance with " +"an epoll instance returns ``EPERM``. Directly using ``poll`` on an epoll " +"descriptor only inspects ready watches without consuming ET/ONESHOT " +"state. Raw ``select``/``pselect6`` syscalls copy bitmaps according to " +"``nfds`` and check ``RLIMIT_NOFILE``, overflow, invalid descriptors, and " +"user pointers. libc determines its ``fd_set`` size; ``FD_SET`` must not " +"be used on descriptors beyond its representable range." msgid "管道" msgstr "Pipes" @@ -120,89 +124,90 @@ msgid "" "管道对象与环形缓冲区分别分配,不再使用固定 256 项全局池。 ``PIPE_BUF`` 保持 4096 字节;不超过此值的非阻塞写入具有全写或 " "``EAGAIN`` 的原子语义,较大写入允许短写。" msgstr "" -"Pipe objects and ring buffers are allocated separately, replacing the fixed " -"global pool of 256 entries. ``PIPE_BUF`` remains 4096 bytes; nonblocking " -"writes no larger than this have all-or-``EAGAIN`` atomic semantics, while " -"larger writes may be short." +"Pipe objects and ring buffers are allocated separately, replacing the " +"fixed global pool of 256 entries. ``PIPE_BUF`` remains 4096 bytes; " +"nonblocking writes no larger than this have all-or-``EAGAIN`` atomic " +"semantics, while larger writes may be short." msgid "" -"命名管道按解析后的 inode 类型进入管道实现,不从权限位推断文件类型。 没有对端时,阻塞打开等待另一端;非阻塞写端打开返回 ``ENXIO``。 " -"``O_PATH`` 只保留路径,不参与对端会合。原生探针 ``tools/tests/fifo_abi_test.c`` " +"命名管道按解析后的 inode 类型进入管道实现,不从权限位推断文件类型。 没有对端时,阻塞打开等待另一端;非阻塞写端打开返回 " +"``ENXIO``。 ``O_PATH`` 只保留路径,不参与对端会合。原生探针 ``tools/tests/fifo_abi_test.c`` " "检查磁盘和内存文件系统上的数据、断开通知、 信号中断及打开等待;可通过命令行指定测试目录。" msgstr "" -"Named pipes enter the pipe implementation according to the resolved inode " -"type, without inferring file type from permission bits. With no peer, a " -"blocking open waits for the other end; a nonblocking write-end open returns " -"``ENXIO``. ``O_PATH`` retains only the path and does not participate in " -"endpoint rendezvous. The native probe ``tools/tests/fifo_abi_test.c`` checks" -" data, disconnect notifications, signal interruption, and open waits on disk" -" and memory filesystems; the test directory can be specified on the command " -"line." +"Named pipes enter the pipe implementation according to the resolved inode" +" type, without inferring file type from permission bits. With no peer, a " +"blocking open waits for the other end; a nonblocking write-end open " +"returns ``ENXIO``. ``O_PATH`` retains only the path and does not " +"participate in endpoint rendezvous. The native probe " +"``tools/tests/fifo_abi_test.c`` checks data, disconnect notifications, " +"signal interruption, and open waits on disk and memory filesystems; the " +"test directory can be specified on the command line." msgid "" -"``F_GETPIPE_SZ`` 查询可用容量;``F_SETPIPE_SZ`` 向上取整到至少一页的 二次幂容量。缩小到不足以容纳现有数据时返回 " -"``EBUSY``,失败不改变数据 顺序或容量。" +"``F_GETPIPE_SZ`` 查询可用容量;``F_SETPIPE_SZ`` 向上取整到至少一页的 二次幂容量。缩小到不足以容纳现有数据时返回" +" ``EBUSY``,失败不改变数据 顺序或容量。" msgstr "" -"``F_GETPIPE_SZ`` queries usable capacity; ``F_SETPIPE_SZ`` rounds up to a " -"power-of-two capacity of at least one page. Shrinking below the size needed " -"for existing data returns ``EBUSY``; failure leaves data order and capacity " -"unchanged." +"``F_GETPIPE_SZ`` queries usable capacity; ``F_SETPIPE_SZ`` rounds up to a" +" power-of-two capacity of at least one page. Shrinking below the size " +"needed for existing data returns ``EBUSY``; failure leaves data order and" +" capacity unchanged." msgid "" -"默认容量为 16 页。当前每个 UID 的软预算为 16384 页;达到预算后,新建 管道使用两页。无资源管理能力的调用者不能把单管道扩大到 1 MiB" -" 以上, 也不能通过扩容超出软预算。``CAP_SYS_RESOURCE`` 或 ``CAP_SYS_ADMIN`` " +"默认容量为 16 页。当前每个 UID 的软预算为 16384 页;达到预算后,新建 管道使用两页。无资源管理能力的调用者不能把单管道扩大到 1 " +"MiB 以上, 也不能通过扩容超出软预算。``CAP_SYS_RESOURCE`` 或 ``CAP_SYS_ADMIN`` " "可绕过这项资源策略;分配失败仍会返回错误。这些是内核策略常量,当前未 通过 sysctl 暴露,不能将其误称为已支持 Linux 的全部管道 " "sysctl。" msgstr "" "Default capacity is 16 pages. The current per-UID soft budget is 16384 " "pages; once reached, new pipes use two pages. Callers without resource-" -"management capabilities cannot grow a single pipe beyond 1 MiB or exceed the" -" soft budget by growing pipes. ``CAP_SYS_RESOURCE`` or ``CAP_SYS_ADMIN`` can" -" bypass this resource policy; allocation failures still return errors. These" -" are kernel policy constants and are not currently exposed through sysctl; " -"they must not be described as support for all Linux pipe sysctls." +"management capabilities cannot grow a single pipe beyond 1 MiB or exceed " +"the soft budget by growing pipes. ``CAP_SYS_RESOURCE`` or " +"``CAP_SYS_ADMIN`` can bypass this resource policy; allocation failures " +"still return errors. These are kernel policy constants and are not " +"currently exposed through sysctl; they must not be described as support " +"for all Linux pipe sysctls." msgid "" "参考:`pipe(7) `_ 和 " "`F_GETPIPE_SZ(2const) `_。" msgstr "" -"References: `pipe(7) `_ " -"and `F_GETPIPE_SZ(2const) `_." +"References: `pipe(7) `_ and `F_GETPIPE_SZ(2const) " +"`_." msgid "匿名共享文件" msgstr "Anonymous shared files" msgid "" -"memfd 使用不挂载的内部 tmpfs 实例。它不占用用户挂载卷槽,也不需要一个 与文件逻辑大小相同的连续物理内存块。逻辑扩展是稀疏的,实际页面按访问" -" 分配,空洞读为零;不再使用 32 项专用池或桌面分辨率作为文件大小上限。" +"memfd 使用不挂载的内部 tmpfs 实例。它不占用用户挂载卷槽,也不需要一个 " +"与文件逻辑大小相同的连续物理内存块。逻辑扩展是稀疏的,实际页面按访问 分配,空洞读为零;不再使用 32 项专用池或桌面分辨率作为文件大小上限。" msgstr "" -"memfd uses an unmounted internal tmpfs instance. It consumes no user mount-" -"volume slot and does not require a contiguous physical-memory block as large" -" as the logical file size. Logical expansion is sparse, actual pages are " -"allocated on access, and holes read as zero; the old dedicated pool of 32 " -"entries and desktop resolution no longer limit file size." +"memfd uses an unmounted internal tmpfs instance. It consumes no user " +"mount-volume slot and does not require a contiguous physical-memory block" +" as large as the logical file size. Logical expansion is sparse, actual " +"pages are allocated on access, and holes read as zero; the old dedicated " +"pool of 32 entries and desktop resolution no longer limit file size." msgid "" "打开文件描述与 VMA 各自持有 inode 引用,关闭最后一个描述符不会提前释放 仍被映射的页面。``MAP_SHARED`` " "保持别名一致性,``MAP_PRIVATE`` 使用 COW。 缩小文件先撤销受影响映射,再释放页面,重新扩展不能暴露旧数据。" msgstr "" -"Open file descriptions and VMAs each hold inode references, so closing the " -"last descriptor does not prematurely release pages that remain mapped. " -"``MAP_SHARED`` preserves alias consistency, while ``MAP_PRIVATE`` uses COW. " -"Shrinking first revokes affected mappings before freeing pages, so " -"subsequent expansion cannot expose old data." +"Open file descriptions and VMAs each hold inode references, so closing " +"the last descriptor does not prematurely release pages that remain " +"mapped. ``MAP_SHARED`` preserves alias consistency, while ``MAP_PRIVATE``" +" uses COW. Shrinking first revokes affected mappings before freeing " +"pages, so subsequent expansion cannot expose old data." msgid "" "seal 状态随共享文件描述持有。增加 ``F_SEAL_WRITE`` 时检查所有任务中可能 写入的共享 VMA,存在这类映射时返回 " "``EBUSY``;私有 COW 映射不阻止封印。 封印后的新共享映射不能借助后续 ``mprotect`` 绕过写保护。" msgstr "" -"Seal state is held with the shared file description. Adding ``F_SEAL_WRITE``" -" checks potentially writable shared VMAs across all tasks and returns " -"``EBUSY`` if any exist; private COW mappings do not prevent sealing. New " -"shared mappings after sealing cannot bypass write protection through later " -"``mprotect`` calls." +"Seal state is held with the shared file description. Adding " +"``F_SEAL_WRITE`` checks potentially writable shared VMAs across all tasks" +" and returns ``EBUSY`` if any exist; private COW mappings do not prevent " +"sealing. New shared mappings after sealing cannot bypass write protection" +" through later ``mprotect`` calls." msgid "" "参考:`memfd_create(2) `_、 `RFC " -"9293 `_ 和 `RFC 6298 " +"参考:`epoll(7) `_、 `RFC" +" 9293 `_ 和 `RFC 6298 " "`_。" msgstr "" "References: `epoll(7) `_。 " "``tools/tests/jit_memory_runtime_probe.c`` 可在 Linux 和 ReliefOS 中运行, 检查 " "W→WX、RWX 映射、撤销执行权限的 NX 效果及 fork COW 隔离。" msgstr "" -"This follows Linux's default behavior for permission combinations and does " -"not imply implementation of Linux MDWE/LSM policy interfaces; restrictions " -"of separate interfaces such as SysV SHM are also unchanged. See `Linux 6.12 " -"permission and MDWE rules " +"This follows Linux's default behavior for permission combinations and " +"does not imply implementation of Linux MDWE/LSM policy interfaces; " +"restrictions of separate interfaces such as SysV SHM are also unchanged. " +"See `Linux 6.12 permission and MDWE rules " "`_. " "``tools/tests/jit_memory_runtime_probe.c`` runs on Linux and ReliefOS to " -"check W→WX, RWX mappings, NX after revoking execute permission, and fork COW" -" isolation." +"check W→WX, RWX mappings, NX after revoking execute permission, and fork " +"COW isolation." msgid "" -"跨核屏障和用户 TLB 刷新在内部串行发布请求,使请求代际与操作类型在 所有 CPU 确认前保持稳定。等待锁或确认的 CPU 即使关闭本地中断,也会 " -"处理其他 CPU 已发布的请求;返回时恢复调用前的中断状态。并行缺页中的 刷新也使用同一发布与确认路径。" +"跨核屏障和用户 TLB 刷新在内部串行发布请求,使请求代际与操作类型在 所有 CPU 确认前保持稳定。等待锁或确认的 CPU " +"即使关闭本地中断,也会 处理其他 CPU 已发布的请求;返回时恢复调用前的中断状态。并行缺页中的 刷新也使用同一发布与确认路径。" msgstr "" "Cross-core barriers and user TLB flushes publish requests serially " -"internally, keeping the request generation and operation type stable until " -"all CPUs acknowledge. CPUs waiting for a lock or acknowledgment process " -"requests published by other CPUs even with local interrupts disabled, " -"restoring the pre-call interrupt state on return. Flushes during parallel " -"page faults use the same publication and acknowledgment path." +"internally, keeping the request generation and operation type stable " +"until all CPUs acknowledge. CPUs waiting for a lock or acknowledgment " +"process requests published by other CPUs even with local interrupts " +"disabled, restoring the pre-call interrupt state on return. Flushes " +"during parallel page faults use the same publication and acknowledgment " +"path." msgid "" "懒加载 ELF 段只登记 VMA,较大的 BSS 不会提前分配覆盖全段的空页表。 实际访问时才建立页表和数据页。``fork`` " @@ -356,58 +369,59 @@ msgid "" "计数达到最终表示上限时页面保持固定,避免未计入引用导致提前回收。" msgstr "" "Lazy-loaded ELF segments register only VMAs; large BSS regions do not " -"preallocate empty page tables for the entire segment. Page tables and data " -"pages are created only on actual access. ``fork`` protects private writable " -"pages in both parent and child, with separate COW on writes; physical-page " -"reference counts retain full ownership beyond 65535. Once the final " -"representational limit is reached, pages remain pinned to prevent uncounted " -"references from causing premature reclamation." +"preallocate empty page tables for the entire segment. Page tables and " +"data pages are created only on actual access. ``fork`` protects private " +"writable pages in both parent and child, with separate COW on writes; " +"physical-page reference counts retain full ownership beyond 65535. Once " +"the final representational limit is reached, pages remain pinned to " +"prevent uncounted references from causing premature reclamation." msgid "" -"内核访问物理页面使用 supervisor 直映射。当前 x86 PCI 后端采用直接 DMA, 设备描述符提交可寻址的物理地址,CPU 访问使用 " -"``mm_phys_to_virt`` 或驱动 API 回调;不能将两者混用。当前没有 IOMMU 或总线地址重映射实现,不能把 " -"总线地址与物理地址相同的假设推广到其他平台。 x86-64 内核直映射从 ``0xffff800000000000`` 开始,虚拟窗口为 64 TiB;" -" 可用物理地址还受 CPU 物理地址位数、可信固件拓扑、实际页表和可用元数据 约束。直映射稀疏建立,RAM 空洞不会因为落在窗口内而变成有效指针。 " -"物理类型、CPU 可表示性和页表实际覆盖是三个不同条件;分配器只接纳实际 映射的可信可用 RAM。引导期间页表仍需要在临时低地址映射内取得页面, " -"资源不足会使引导停止。64 TiB 是虚拟设计容量,不是已验证硬件 RAM 容量。" +"内核访问物理页面使用 supervisor 直映射。当前 x86 PCI 后端采用直接 DMA, 设备描述符提交可寻址的物理地址,CPU 访问使用" +" ``mm_phys_to_virt`` 或驱动 API 回调;不能将两者混用。当前没有 IOMMU 或总线地址重映射实现,不能把 " +"总线地址与物理地址相同的假设推广到其他平台。 x86-64 内核直映射从 ``0xffff800000000000`` 开始,虚拟窗口为 64 " +"TiB; 可用物理地址还受 CPU 物理地址位数、可信固件拓扑、实际页表和可用元数据 约束。直映射稀疏建立,RAM " +"空洞不会因为落在窗口内而变成有效指针。 物理类型、CPU 可表示性和页表实际覆盖是三个不同条件;分配器只接纳实际 映射的可信可用 " +"RAM。引导期间页表仍需要在临时低地址映射内取得页面, 资源不足会使引导停止。64 TiB 是虚拟设计容量,不是已验证硬件 RAM 容量。" msgstr "" "The kernel accesses physical pages through a supervisor direct map. The " "current x86 PCI backend uses direct DMA: device descriptors receive " -"addressable physical addresses, while CPU access uses ``mm_phys_to_virt`` or" -" driver API callbacks; the two must not be confused. There is currently no " -"IOMMU or bus-address remapping implementation, and equality of bus and " -"physical addresses must not be assumed on other platforms. The x86-64 kernel" -" direct map starts at ``0xffff800000000000`` with a 64 TiB virtual window; " -"usable physical addresses are further constrained by CPU physical-address " -"width, trusted firmware topology, actual page tables, and available " -"metadata. The direct map is built sparsely; RAM holes do not become valid " -"pointers merely because they fall within the window. Physical type, CPU " -"representability, and actual page-table coverage are three separate " -"conditions; the allocator accepts only actually mapped trusted usable RAM. " -"During boot, page tables still require pages obtained within temporary low-" -"address mappings; insufficient resources stop boot. 64 TiB is a virtual " -"design capacity, not a validated hardware RAM capacity." - -msgid "" -"PCI BAR 可在 RAM 空洞内通过独立设备窗口映射;内核拒绝与 RAM 或已有 直映射别名冲突的缓存属性。DMA 使用设备实际地址掩码分配:例如 " -"DMA32 分配的最后一个字节也必须不超过 ``0xffffffff``。目前没有 IOMMU。 UEFI " +"addressable physical addresses, while CPU access uses ``mm_phys_to_virt``" +" or driver API callbacks; the two must not be confused. There is " +"currently no IOMMU or bus-address remapping implementation, and equality " +"of bus and physical addresses must not be assumed on other platforms. The" +" x86-64 kernel direct map starts at ``0xffff800000000000`` with a 64 TiB " +"virtual window; usable physical addresses are further constrained by CPU " +"physical-address width, trusted firmware topology, actual page tables, " +"and available metadata. The direct map is built sparsely; RAM holes do " +"not become valid pointers merely because they fall within the window. " +"Physical type, CPU representability, and actual page-table coverage are " +"three separate conditions; the allocator accepts only actually mapped " +"trusted usable RAM. During boot, page tables still require pages obtained" +" within temporary low-address mappings; insufficient resources stop boot." +" 64 TiB is a virtual design capacity, not a validated hardware RAM " +"capacity." + +msgid "" +"PCI BAR 可在 RAM 空洞内通过独立设备窗口映射;内核拒绝与 RAM 或已有 直映射别名冲突的缓存属性。DMA " +"使用设备实际地址掩码分配:例如 DMA32 分配的最后一个字节也必须不超过 ``0xffffffff``。目前没有 IOMMU。 UEFI " "若交接时启动服务仍活动,内核必须使用映像句柄和最新内存映射键 成功退出启动服务后才接管常规 RAM;无法证明所有权时停止引导。 " -"固件表发现还需证明当时的地址映射:活动 EFI amd64 入口的身份映射证明 可跨内核自己的退出启动服务调用保留;i386 入口只证明前 4 GiB。" -" 仅有已结束的 EFI 内存描述符不能证明高地址表当前可访问。" -msgstr "" -"PCI BARs in RAM holes can be mapped through a separate device window; the " -"kernel rejects cache attributes conflicting with RAM or existing direct-map " -"aliases. DMA allocation uses the device's actual address mask: for example, " -"even the final byte of a DMA32 allocation must not exceed ``0xffffffff``. " -"There is currently no IOMMU. If UEFI boot services are still active at " -"handoff, the kernel must successfully exit boot services using the image " -"handle and latest memory-map key before taking over ordinary RAM; boot stops" -" if ownership cannot be proven. Firmware-table discovery must also prove " -"address mappings at that time: identity-mapping evidence from an active EFI " -"amd64 entry can be retained across the kernel's own exit-boot-services call," -" whereas an i386 entry proves only the first 4 GiB. EFI memory descriptors " -"from already-ended services alone do not prove that high-address tables are " -"currently accessible." +"固件表发现还需证明当时的地址映射:活动 EFI amd64 入口的身份映射证明 可跨内核自己的退出启动服务调用保留;i386 入口只证明前 4 " +"GiB。 仅有已结束的 EFI 内存描述符不能证明高地址表当前可访问。" +msgstr "" +"PCI BARs in RAM holes can be mapped through a separate device window; the" +" kernel rejects cache attributes conflicting with RAM or existing direct-" +"map aliases. DMA allocation uses the device's actual address mask: for " +"example, even the final byte of a DMA32 allocation must not exceed " +"``0xffffffff``. There is currently no IOMMU. If UEFI boot services are " +"still active at handoff, the kernel must successfully exit boot services " +"using the image handle and latest memory-map key before taking over " +"ordinary RAM; boot stops if ownership cannot be proven. Firmware-table " +"discovery must also prove address mappings at that time: identity-mapping" +" evidence from an active EFI amd64 entry can be retained across the " +"kernel's own exit-boot-services call, whereas an i386 entry proves only " +"the first 4 GiB. EFI memory descriptors from already-ended services alone" +" do not prove that high-address tables are currently accessible." msgid "" "内部驱动 API 版本为 2,末尾增加 ``phys_to_virt`` 回调。驱动必须检查 版本、``struct_size`` " @@ -417,27 +431,29 @@ msgstr "" "The internal driver API is version 2, with a ``phys_to_virt`` callback " "appended. Drivers must check the version, ``struct_size``, and callback " "presence before use. Version 1 drivers need rebuilding, and the kernel " -"rejects mismatched modules before initialization; the Linux syscall ABI is " -"unchanged. Current built-in drivers are built together with the kernel." +"rejects mismatched modules before initialization; the Linux syscall ABI " +"is unchanged. Current built-in drivers are built together with the " +"kernel." msgid "" "fbdev 的 ``smem_start`` 与用户设备映射的 PFN 保持物理地址语义,不能包含 内核直映射指针。显存与 FIFO " "的物理保留范围也不能直接与 CPU 指针比较。 安装器根镜像的入口接收 Multiboot 模块物理地址,只在挂载实现内部转换。" msgstr "" "fbdev's ``smem_start`` and PFNs in user device mappings retain physical-" -"address semantics and must not contain kernel direct-map pointers. Physical " -"reservations for video memory and FIFO also must not be compared directly " -"with CPU pointers. The installer root-image entry receives physical " -"Multiboot module addresses and converts them only inside the mount " -"implementation." +"address semantics and must not contain kernel direct-map pointers. " +"Physical reservations for video memory and FIFO also must not be compared" +" directly with CPU pointers. The installer root-image entry receives " +"physical Multiboot module addresses and converts them only inside the " +"mount implementation." msgid "" -"参考:`Linux DMA 地址说明 `_ 和 `Linux 6.12 fbdev UAPI " +"参考:`Linux DMA 地址说明 `_ 和 `Linux 6.12 fbdev UAPI " "`_。" msgstr "" "References: `Linux DMA address explanation `_ and `Linux 6.12 fbdev UAPI " +"api/dma-api-howto.html#cpu-and-dma-addresses>`_ and `Linux 6.12 fbdev " +"UAPI " "`_." msgid "验证入口" @@ -450,35 +466,35 @@ msgstr "" msgid "" "``tools/tests/resource_capacity_runtime_probe.c`` 是原生 Linux ABI 容量探针, " -"``tools/tests/tcp_runtime_probe.c`` 连接测试编排提供的本地 TCP 对端。 二者可用 musl " +"``tools/tests/tcp_runtime_probe.c`` 连接测试编排提供的本地 TCP 对端。 二者可用 glibc " "静态构建。完整镜像、私有磁盘和 QEMU 编排归 ReliefOS 持有, 宿主 Linux 上通过只证明参考行为,不能代替 ReliefOS " "来宾验证。" msgstr "" -"``tools/tests/resource_capacity_runtime_probe.c`` is a native Linux ABI " -"capacity probe, and ``tools/tests/tcp_runtime_probe.c`` connects to a local " -"TCP peer provided by test orchestration. Both can be statically built with " -"musl. Full images, private disks, and QEMU orchestration belong to ReliefOS;" -" passing on host Linux establishes only reference behavior and cannot " -"replace ReliefOS guest validation." +"``tools/tests/resource_capacity_runtime_probe.c`` checks native Linux ABI" +" resource capacity. ``tools/tests/tcp_runtime_probe.c`` connects to the " +"fixture's local TCP peer. Both can be statically linked with glibc. " +"ReliefOS owns the complete image and QEMU orchestration. Host Linux " +"results cover the reference behavior." msgid "" "``tools/tests/kmodules/memory_layout_probe`` 是独立 Apache-2.0 外部模块, 不要求启用 " -"``MODULE_TESTS``。在使用匹配内核配置及 ABI 的构建环境中, 将其中的 ``Kbuild`` 和 C 文件复制到自有输出目录,再用正式" -" ``make O= M= modules`` 入口构建;``M`` 目录 " -"会产生构建文件,不能指向源码目录。在来宾使用 ``insmod`` 和 ``rmmod`` 加载、卸载后检查 ``[memory-probe]`` " -"日志:模块只触碰自身取得的 513 页 高于 16 GiB 的连续内存和两页 DMA32 内存,验证零填充及逐页写读, " -"并在所有失败路径释放已取得页面。低内存环境或连续高端内存不足时探针 会报告失败;不能用该失败推断内核其余 RAM 不可用。" -msgstr "" -"``tools/tests/kmodules/memory_layout_probe`` is an independent Apache-2.0 " -"external module that does not require ``MODULE_TESTS``. In a build " -"environment with matching kernel configuration and ABI, copy its ``Kbuild`` " -"and C files into your own output directory, then build through the official " -"``make O= M= modules`` entry point; the ``M`` " -"directory receives build files and must not point to the source directory. " -"In the guest, load and unload with ``insmod`` and ``rmmod``, then inspect " -"``[memory-probe]`` logs: the module touches only its own 513 contiguous " -"pages above 16 GiB and two DMA32 pages, validates zero filling and per-page " -"writes/reads, and frees acquired pages on every failure path. In low-memory " -"environments or with insufficient contiguous high memory, the probe reports " -"failure; that failure does not imply that the kernel's other RAM is " -"unusable." +"``MODULE_TESTS``。在使用匹配内核配置及 ABI 的构建环境中, 将其中的 ``Kbuild`` 和 C " +"文件复制到自有输出目录,再用正式 ``make O= M= modules`` " +"入口构建;``M`` 目录 会产生构建文件,不能指向源码目录。在来宾使用 ``insmod`` 和 ``rmmod`` 加载、卸载后检查 " +"``[memory-probe]`` 日志:模块只触碰自身取得的 513 页 高于 16 GiB 的连续内存和两页 DMA32 " +"内存,验证零填充及逐页写读, 并在所有失败路径释放已取得页面。低内存环境或连续高端内存不足时探针 会报告失败;不能用该失败推断内核其余 RAM " +"不可用。" +msgstr "" +"``tools/tests/kmodules/memory_layout_probe`` is an independent Apache-2.0" +" external module that does not require ``MODULE_TESTS``. In a build " +"environment with matching kernel configuration and ABI, copy its " +"``Kbuild`` and C files into your own output directory, then build through" +" the official ``make O= M= modules`` entry " +"point; the ``M`` directory receives build files and must not point to the" +" source directory. In the guest, load and unload with ``insmod`` and " +"``rmmod``, then inspect ``[memory-probe]`` logs: the module touches only " +"its own 513 contiguous pages above 16 GiB and two DMA32 pages, validates " +"zero filling and per-page writes/reads, and frees acquired pages on every" +" failure path. In low-memory environments or with insufficient contiguous" +" high memory, the probe reports failure; that failure does not imply that" +" the kernel's other RAM is unusable." diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/virtio-gpu.po b/Documentation/locale/en/LC_MESSAGES/core-api/virtio-gpu.po index abcb3622..14b67071 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/virtio-gpu.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/virtio-gpu.po @@ -5,7 +5,7 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.3\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2026-11-19 18:40+0800\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: ReliefOS contributors\n" "Language: en\n" @@ -154,34 +154,23 @@ msgstr "" msgid "验证与上游来源" msgstr "Validation and upstream sources" -# | msgid "" "``tools/test_virtio.py`` 在 ASan/UBSan 下运行生产 ring 实现,覆盖乱序、 131080 -# " -# | "次环回绕、背压、非法 used entry 及 fatal 预留链。原生用户态探针 -# ``tools/tests/virtgpu_guest.c``" -# | " 可用 musl 编译,执行实际 DRM、PRIME、 sync_file、sysfs、翻页和光标操作;用 ``--no-pause`` " -# | "跳过截图握手。 完整系统、Mesa/EGL、Xorg、BIOS/UEFI 及模块重载的 QEMU 编排由 ReliefOS 持有。 离屏 -# draw" -# | " 速率不能替代桌面帧率或实体显卡性能。VMware 验证未完成。" msgid "" "``tools/test_virtio.py`` 在 ASan/UBSan 下运行生产 ring 实现,覆盖乱序、 131080 " "次环回绕、背压、非法 used entry 及 fatal 预留链。原生用户态探针 ``tools/tests/virtgpu_guest.c``" -" 可用 musl 编译,执行实际 DRM、PRIME、 sync_file、sysfs、翻页和光标操作;用 ``--no-pause`` " +" 可用 glibc 编译,执行实际 DRM、PRIME、 sync_file、sysfs、翻页和光标操作;用 ``--no-pause`` " "跳过截图握手。 ``tools/test_drm.py`` 覆盖局部文本上传的偏移、失败重试、VT 整屏恢复, 以及 2D DIRTYFB " "的区域拆分、合并和校验。 完整系统、Mesa/EGL、Xorg、BIOS/UEFI 及模块重载的 QEMU 编排由 ReliefOS 持有。 离屏" " draw 速率不能替代桌面帧率或实体显卡性能。VMware 验证未完成。" msgstr "" -"``tools/test_virtio.py`` runs the production ring implementation under " -"ASan/UBSan, covering out-of-order completion, 131080 ring-wrap " -"operations, backpressure, malformed used entries, and the reserved fatal " -"chain. The native userspace probe ``tools/tests/virtgpu_guest.c`` can be " -"compiled with musl to exercise actual DRM, PRIME, sync_file, sysfs, page-" -"flip, and cursor operations; ``--no-pause`` skips the screenshot " -"handshake. ``tools/test_drm.py`` covers partial text-upload offsets, " -"failed-refresh retry, full VT restoration, and 2D DIRTYFB region " -"splitting, merging, and validation. ReliefOS owns QEMU orchestration for " -"the full system, Mesa/EGL, Xorg, BIOS/UEFI, and module reloads. Offscreen" -" draw rates cannot replace desktop frame rates or physical GPU " -"performance measurements. VMware validation is incomplete." +"``tools/test_virtio.py`` runs the production rings under ASan/UBSan. It " +"covers out-of-order completion, 131,080 wraps, backpressure, invalid used" +" entries and fatal reserved chains. Build ``tools/tests/virtgpu_guest.c``" +" with glibc to exercise DRM, PRIME, sync_file, sysfs, page flip and " +"cursor in the guest. ``--no-pause`` skips the screenshot handshake. " +"``tools/test_drm.py`` covers partial text uploads, retries, full VT " +"restore and 2D DIRTYFB region handling. ReliefOS owns full-system " +"Mesa/EGL, Xorg, BIOS/UEFI and module reload checks. Offscreen draw rates " +"describe that workload. VMware verification remains incomplete." msgid "" "协议参考 OASIS VirtIO 1.3 第 4.1、2.7 和 5.7 节。VirtGPU、VirtIO-GPU 与 sync_file " diff --git a/Documentation/locale/en/LC_MESSAGES/kbuild/modules.po b/Documentation/locale/en/LC_MESSAGES/kbuild/modules.po index d854335b..9bc49935 100644 --- a/Documentation/locale/en/LC_MESSAGES/kbuild/modules.po +++ b/Documentation/locale/en/LC_MESSAGES/kbuild/modules.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "原生内核模块与 SDK" msgstr "Native Kernel Modules and SDK" @@ -20,22 +23,26 @@ msgid "兼容边界" msgstr "Compatibility Boundaries" msgid "" -"ReliefNT 使用 Linux 风格的 ELF64 .ko、Kbuild、模块元数据和符号版本机制。 模块必须针对匹配的 ReliefNT 内核重新编译;Linux 的内部内核 API 和原版" -" Linux 二进制 .ko 不属于兼容目标。POSIX 不定义内核模块格式或模块加载接口。" +"ReliefNT 使用 Linux 风格的 ELF64 .ko、Kbuild、模块元数据和符号版本机制。 模块必须针对匹配的 ReliefNT " +"内核重新编译;Linux 的内部内核 API 和原版 Linux 二进制 .ko 不属于兼容目标。POSIX 不定义内核模块格式或模块加载接口。" msgstr "" -"ReliefNT uses Linux-style ELF64 .ko files, Kbuild, module metadata, and symbol versioning. Modules" -" must be rebuilt for a matching ReliefNT kernel; internal Linux kernel APIs and upstream Linux " -"binary .ko files are not compatibility targets. POSIX defines neither a kernel module format nor a" -" module loading interface." +"ReliefNT uses Linux-style ELF64 .ko files, Kbuild, module metadata, and " +"symbol versioning. Modules must be rebuilt for a matching ReliefNT " +"kernel; internal Linux kernel APIs and upstream Linux binary .ko files " +"are not compatibility targets. POSIX defines neither a kernel module " +"format nor a module loading interface." msgid "" -"默认 defconfig 的生产驱动为 y;已开放的 tristate 可以在 menuconfig 中 选择 m。关闭 MODULES 时不能选择 m,内建配置仍可构建。测试模块由 " -"MODULE_TESTS 显式开启,不进入默认产品。 完整生产部件及依赖矩阵见 :doc:`../core-api/drivers`。" +"默认 defconfig 的生产驱动为 y;已开放的 tristate 可以在 menuconfig 中 选择 m。关闭 MODULES " +"时不能选择 m,内建配置仍可构建。测试模块由 MODULE_TESTS 显式开启,不进入默认产品。 完整生产部件及依赖矩阵见 :doc" +":`../core-api/drivers`。" msgstr "" -"Production drivers in the default defconfig are y; exposed tristates can be set to m in " -"menuconfig. With MODULES disabled, m cannot be selected, but built-in configurations can still be " -"built. Test modules require explicit MODULE_TESTS enablement and are not part of the default " -"product. See :doc:`../core-api/drivers` for the full production component and dependency matrix." +"Production drivers in the default defconfig are y; exposed tristates can " +"be set to m in menuconfig. With MODULES disabled, m cannot be selected, " +"but built-in configurations can still be built. Test modules require " +"explicit MODULE_TESTS enablement and are not part of the default product." +" See :doc:`../core-api/drivers` for the full production component and " +"dependency matrix." msgid "构建与安装" msgstr "Building and Installing" @@ -45,66 +52,77 @@ msgstr "Run from the ReliefNT source root::" msgid "" "modules 使用固定的 Linux 6.12 编译、modpost 和最终链接规则,生成 " -"Module.symvers、modules.order、modules.builtin、modules.builtin.modinfo 与选中的 .ko。modules_prepare " -"准备宿主工具和生成头文件;它不替代生成 完整符号版本清单所需的内核构建。" +"Module.symvers、modules.order、modules.builtin、modules.builtin.modinfo 与选中的" +" .ko。modules_prepare 准备宿主工具和生成头文件;它不替代生成 完整符号版本清单所需的内核构建。" msgstr "" -"modules uses pinned Linux 6.12 compilation, modpost, and final linking rules to generate " -"Module.symvers, modules.order, modules.builtin, modules.builtin.modinfo, and the selected .ko " -"files. modules_prepare prepares host tools and generated headers; it does not replace the kernel " -"build needed to generate a complete symbol version manifest." +"modules uses pinned Linux 6.12 compilation, modpost, and final linking " +"rules to generate Module.symvers, modules.order, modules.builtin, " +"modules.builtin.modinfo, and the selected .ko files. modules_prepare " +"prepares host tools and generated headers; it does not replace the kernel" +" build needed to generate a complete symbol version manifest." msgid "" -"完整原生 release 保存在 O/include/config/kernel.release,ABI 摘要在 O/include/config/module.abi。安装目录为 " -"/lib/modules//kernel/, 树外模块使用 updates/。只清理由相应安装清单管理的旧产物,保留其他 release " -"和用户模块。覆盖已修改的受管文件会导致明确错误;不再生成的旧文件若被 用户修改则予以保留,不将它作为陈旧产物删除。" +"完整原生 release 保存在 O/include/config/kernel.release,ABI 摘要在 " +"O/include/config/module.abi。安装目录为 /lib/modules//kernel/, 树外模块使用 " +"updates/。只清理由相应安装清单管理的旧产物,保留其他 release 和用户模块。覆盖已修改的受管文件会导致明确错误;不再生成的旧文件若被" +" 用户修改则予以保留,不将它作为陈旧产物删除。" msgstr "" -"The full native release is stored in O/include/config/kernel.release, and the ABI digest in " -"O/include/config/module.abi. Installation uses /lib/modules//kernel/, with updates/ for " -"out-of-tree modules. Only old artifacts managed by the corresponding installation manifest are " -"cleaned up; other releases and user modules are retained. Overwriting a modified managed file " -"produces an explicit error. A formerly generated file modified by the user is preserved rather " -"than removed as stale." +"The full native release is stored in O/include/config/kernel.release, and" +" the ABI digest in O/include/config/module.abi. Installation uses " +"/lib/modules//kernel/, with updates/ for out-of-tree modules. " +"Only old artifacts managed by the corresponding installation manifest are" +" cleaned up; other releases and user modules are retained. Overwriting a " +"modified managed file produces an explicit error. A formerly generated " +"file modified by the user is preserved rather than removed as stale." msgid "" -"内核构建标识及 SOURCE_DATE_EPOCH 纳入 ABI 摘要,构建信息变化会产生新的 release。要从不包含 Git 元数据的源码归档重现原有 release,需要向 make " -"提供相同的 RELIEFNT_SOURCE_ID 和 SOURCE_DATE_EPOCH。" +"内核构建标识及 SOURCE_DATE_EPOCH 纳入 ABI 摘要,构建信息变化会产生新的 release。要从不包含 Git " +"元数据的源码归档重现原有 release,需要向 make 提供相同的 RELIEFNT_SOURCE_ID 和 " +"SOURCE_DATE_EPOCH。" msgstr "" -"The kernel build identifier and SOURCE_DATE_EPOCH are included in the ABI digest, so changes to " -"build information produce a new release. To reproduce an existing release from a source archive " -"without Git metadata, provide the same RELIEFNT_SOURCE_ID and SOURCE_DATE_EPOCH to make." +"The kernel build identifier and SOURCE_DATE_EPOCH are included in the ABI" +" digest, so changes to build information produce a new release. To " +"reproduce an existing release from a source archive without Git metadata," +" provide the same RELIEFNT_SOURCE_ID and SOURCE_DATE_EPOCH to make." msgid "模块元数据" msgstr "Module Metadata" msgid "" -"默认构建的最终 ``.ko`` 导出表保留 Linux 风格的 ``__ksymtab_<符号名>``、 ``__kstrtab_<符号名>`` 与 ``__kstrtabns_<符号名>`` " -"标签,供模块工具建立 符号索引。普通和 GPL 导出、函数和数据导出都使用这些标签;原生表项仍为 地址、名称和命名空间三个指针。``Module.symvers`` 记录类型 CRC,不能用 " -"普通全局符号表代替实际导出清单。" +"默认构建的最终 ``.ko`` 导出表保留 Linux 风格的 ``__ksymtab_<符号名>``、 ``__kstrtab_<符号名>`` " +"与 ``__kstrtabns_<符号名>`` 标签,供模块工具建立 符号索引。普通和 GPL 导出、函数和数据导出都使用这些标签;原生表项仍为 " +"地址、名称和命名空间三个指针。``Module.symvers`` 记录类型 CRC,不能用 普通全局符号表代替实际导出清单。" msgstr "" -"The final ``.ko`` export table in a default build retains Linux-style ``__ksymtab_<符号名>``, " -"``__kstrtab_<符号名>``, and ``__kstrtabns_<符号名>`` labels so module tools can build symbol indexes. " -"Normal and GPL exports, and function and data exports, all use these labels; native entries still " -"contain three pointers: address, name, and namespace. ``Module.symvers`` records type CRCs; an " -"ordinary global symbol table cannot replace the actual export manifest." +"The final ``.ko`` export table in a default build retains Linux-style " +"``__ksymtab_<符号名>``, ``__kstrtab_<符号名>``, and ``__kstrtabns_<符号名>`` " +"labels so module tools can build symbol indexes. Normal and GPL exports, " +"and function and data exports, all use these labels; native entries still" +" contain three pointers: address, name, and namespace. ``Module.symvers``" +" records type CRCs; an ordinary global symbol table cannot replace the " +"actual export manifest." msgid "" -"依赖这些标签的模块工具需要保留本地符号。安装时 ``INSTALL_MOD_STRIP=1`` 仅剥除调试信息,保留这些标签;自定义 ``--strip-unneeded`` 或 " -"``--strip-all`` 会移除标签,不适用于依赖标签扫描的 ``depmod``。" +"依赖这些标签的模块工具需要保留本地符号。安装时 ``INSTALL_MOD_STRIP=1`` 仅剥除调试信息,保留这些标签;自定义 " +"``--strip-unneeded`` 或 ``--strip-all`` 会移除标签,不适用于依赖标签扫描的 ``depmod``。" msgstr "" -"Module tools that depend on these labels need local symbols preserved. At installation, " -"``INSTALL_MOD_STRIP=1`` strips only debug information and retains the labels. Custom ``--strip-" -"unneeded`` or ``--strip-all`` removes them and is unsuitable for ``depmod`` that scans labels." +"Module tools that depend on these labels need local symbols preserved. At" +" installation, ``INSTALL_MOD_STRIP=1`` strips only debug information and " +"retains the labels. Custom ``--strip-unneeded`` or ``--strip-all`` " +"removes them and is unsuitable for ``depmod`` that scans labels." msgid "" -"``modules.builtin`` 列出内置模块路径;``modules.builtin.modinfo`` 保存 以模块名加点号为前缀、以 NUL 分隔的元数据。模块工具需要读取这些文件 " -"才能查询内置模块及其别名。内置模块不写入动态 ``/proc/modules`` 列表, 也不生成用于冒充可加载模块的 ``.ko`` 文件。文件约定见 `Linux Kbuild 输出文件 " +"``modules.builtin`` 列出内置模块路径;``modules.builtin.modinfo`` 保存 以模块名加点号为前缀、以 " +"NUL 分隔的元数据。模块工具需要读取这些文件 才能查询内置模块及其别名。内置模块不写入动态 ``/proc/modules`` 列表, " +"也不生成用于冒充可加载模块的 ``.ko`` 文件。文件约定见 `Linux Kbuild 输出文件 " "`_。" msgstr "" -"``modules.builtin`` lists built-in module paths; ``modules.builtin.modinfo`` holds NUL-separated " -"metadata prefixed with the module name and a dot. Module tools must read these files to query " -"built-in modules and their aliases. Built-in modules are not added to the dynamic " -"``/proc/modules`` list, and no ``.ko`` files are generated to impersonate loadable modules. See " -"`Linux Kbuild output files `_ for file " +"``modules.builtin`` lists built-in module paths; " +"``modules.builtin.modinfo`` holds NUL-separated metadata prefixed with " +"the module name and a dot. Module tools must read these files to query " +"built-in modules and their aliases. Built-in modules are not added to the" +" dynamic ``/proc/modules`` list, and no ``.ko`` files are generated to " +"impersonate loadable modules. See `Linux Kbuild output files " +"`_ for file " "conventions." msgid "树外模块" @@ -114,12 +132,13 @@ msgid "模块目录中的 Kbuild::" msgstr "Kbuild in the module directory::" msgid "" -"hello.c 使用 reliefnt/module.h 的 module_init、module_exit 和 MODULE_LICENSE 等接口。导出符号须使用 " -"reliefnt/export.h;外置模块采用 原生模块的地址模型,不能沿用内建内核的直接地址或静态 DMA 假设。" +"hello.c 使用 reliefnt/module.h 的 module_init、module_exit 和 MODULE_LICENSE " +"等接口。导出符号须使用 reliefnt/export.h;外置模块采用 原生模块的地址模型,不能沿用内建内核的直接地址或静态 DMA 假设。" msgstr "" -"hello.c uses interfaces such as module_init, module_exit, and MODULE_LICENSE from " -"reliefnt/module.h. Exported symbols must use reliefnt/export.h. External modules use the native " -"module address model and must not retain the direct-address or static-DMA assumptions of the " +"hello.c uses interfaces such as module_init, module_exit, and " +"MODULE_LICENSE from reliefnt/module.h. Exported symbols must use " +"reliefnt/export.h. External modules use the native module address model " +"and must not retain the direct-address or static-DMA assumptions of the " "built-in kernel." msgid "使用完整源码与已有输出时::" @@ -129,94 +148,119 @@ msgid "也可以导出独立 prepared SDK::" msgstr "A standalone prepared SDK can also be exported::" msgid "" -"prepared SDK 带匹配头文件、生成配置、ABI、Module.symvers,以及原版 fixdep、genksyms、modpost 和 Kbuild " -"输入。它不带内核实现源码,也不通过 重新编译整个内核来构建树外模块。源码/输出树仍可用时直接调用 M=;部署后的 /lib/modules//build 指向同一前缀内的 " -"prepared SDK。" +"prepared SDK 带匹配头文件、生成配置、ABI、Module.symvers,以及原版 fixdep、genksyms、modpost " +"和 Kbuild 输入。它不带内核实现源码,也不通过 重新编译整个内核来构建树外模块。源码/输出树仍可用时直接调用 M=;部署后的 " +"/lib/modules//build 指向同一前缀内的 prepared SDK。" msgstr "" -"The prepared SDK includes matching headers, generated configuration, ABI, Module.symvers, and " -"upstream fixdep, genksyms, modpost, and Kbuild inputs. It contains no kernel implementation source" -" and builds out-of-tree modules without recompiling the entire kernel. Call M= directly while the " -"source/output trees remain available; deployed /lib/modules//build points to the prepared" -" SDK under the same prefix." +"The prepared SDK includes matching headers, generated configuration, ABI," +" Module.symvers, and upstream fixdep, genksyms, modpost, and Kbuild " +"inputs. It contains no kernel implementation source and builds out-of-" +"tree modules without recompiling the entire kernel. Call M= directly " +"while the source/output trees remain available; deployed " +"/lib/modules//build points to the prepared SDK under the same " +"prefix." msgid "" -"该 SDK 支持与生成它的 Linux x86_64 宿主工具环境相匹配的构建。目标工具 必须具有匹配身份;允许同一工具搬到其他目录,并可显式传入 CC、AR、LD、 " -"OBJCOPY。改变内核架构、PROFILE、编译策略或头文件应从完整源码重新构建并 导出新的 SDK,不能继续沿用旧 ABI 标记。SDK 本身可只读,构建产物与临时 文件写入 M= " -"目录;模块安装仍需指定可写的 INSTALL_MOD_PATH。 沿用 Linux Kbuild 的路径要求,SDK 和构建目录不能包含空白字符。" +"该 SDK 支持与生成它的 Linux x86_64 宿主工具环境相匹配的构建。目标工具 必须具有匹配身份;允许同一工具搬到其他目录,并可显式传入" +" CC、AR、LD、 OBJCOPY。改变内核架构、PROFILE、编译策略或头文件应从完整源码重新构建并 导出新的 SDK,不能继续沿用旧 " +"ABI 标记。SDK 本身可只读,构建产物与临时 文件写入 M= 目录;模块安装仍需指定可写的 INSTALL_MOD_PATH。 沿用 " +"Linux Kbuild 的路径要求,SDK 和构建目录不能包含空白字符。" msgstr "" -"The SDK supports builds matching the Linux x86_64 host tool environment that generated it. Target " -"tools must have matching identities; the same tools may move to other directories, and CC, AR, LD," -" and OBJCOPY can be passed explicitly. Changes to the kernel architecture, PROFILE, compilation " -"policy, or headers require rebuilding from full source and exporting a new SDK rather than reusing" -" old ABI markers. The SDK itself may be read-only; artifacts and temporary files go into the M= " -"directory. Module installation still requires a writable INSTALL_MOD_PATH. Linux Kbuild path " -"requirements apply: SDK and build directories must not contain whitespace." +"The SDK supports builds matching the Linux x86_64 host tool environment " +"that generated it. Target tools must have matching identities; the same " +"tools may move to other directories, and CC, AR, LD, and OBJCOPY can be " +"passed explicitly. Changes to the kernel architecture, PROFILE, " +"compilation policy, or headers require rebuilding from full source and " +"exporting a new SDK rather than reusing old ABI markers. The SDK itself " +"may be read-only; artifacts and temporary files go into the M= directory." +" Module installation still requires a writable INSTALL_MOD_PATH. Linux " +"Kbuild path requirements apply: SDK and build directories must not " +"contain whitespace." msgid "加载诊断" msgstr "Loading Diagnostics" msgid "" -"加载器校验完整 vermagic、类型 CRC、依赖和参数,并实现 Linux 编号的 init_module、finit_module、delete_module;调用者需要 " -"CAP_SYS_MODULE。 finit_module 不支持的装载标志明确返回错误。delete_module 与 Linux 6.12 禁用强制卸载的配置一致,接受 BusyBox 使用的 " +"加载器校验完整 vermagic、类型 CRC、依赖和参数,并实现 Linux 编号的 " +"init_module、finit_module、delete_module;调用者需要 CAP_SYS_MODULE。 finit_module" +" 不支持的装载标志明确返回错误。delete_module 与 Linux 6.12 禁用强制卸载的配置一致,接受用户态模块工具传入的 " "O_EXCL,并忽略额外位; O_TRUNC 也不会绕过引用、exit 或硬件停止检查。finit_module 使用独立文件快照,不移动共享 " "文件偏移;已有可写文件描述会阻止快照,快照期间也不能新增可写打开。" msgstr "" -"The loader checks the full vermagic, type CRCs, dependencies, and parameters, and implements " -"Linux-numbered init_module, finit_module, and delete_module; callers require CAP_SYS_MODULE. " -"Unsupported finit_module loading flags return explicit errors. Like Linux 6.12 with forced " -"unloading disabled, delete_module accepts the O_EXCL used by BusyBox and ignores extra bits; even " -"O_TRUNC cannot bypass reference, exit, or hardware-stop checks. finit_module uses an independent " -"file snapshot without moving the shared file offset. Existing writable file descriptions block the" -" snapshot, and new writable opens are prohibited during it." - -msgid "" -"模块状态为 COMING、LIVE、GOING。LIVE 表示代码加载成功,是否发现并激活 硬件应检查驱动状态,不能把没有相应硬件的成功注册当作硬件验证。 " -"打开设备、挂载、映射、依赖和执行中的回调会约束卸载;设备停止失败时保留 代码与 DMA 所有权以便诊断和重试。/proc/modules 与 /sys/module 提供状态视图。" -msgstr "" -"Module states are COMING, LIVE, and GOING. LIVE means code loaded successfully; check driver state" -" to determine whether hardware was discovered and activated. Successful registration without the " -"corresponding hardware is not hardware validation. Open devices, mounts, mappings, dependencies, " -"and executing callbacks constrain unloading. If device shutdown fails, code and DMA ownership are " -"retained for diagnosis and retry. /proc/modules and /sys/module expose state views." - -msgid "" -"模块参数遵循 Linux 风格的 ``module_param`` 类型、命令行解析和 sysfs 权限。 例如 DRM 的只读布尔参数 ``faildiag`` 可在内核命令行中写为 " -"``drm.faildiag=1``,或在装载时使用 ``modprobe drm faildiag=1``。 内置驱动由内核参数框架处理,外置驱动由 modprobe 传入同一参数描述表; " -"诊断在初始化时设置。使用 ``0`` 或 ``N`` 可禁用,非法布尔值会拒绝装载。 只读或权限为零的参数不能从 sysfs 任意修改;卸载后的旧参数句柄不能指向 " -"重新加载模块的存储。模块版本与导出符号类型 CRC 不匹配必须重新构建, 不提供忽略 vermagic 或 CRC 的强制装载选项。模块内存采用独立的代码、只读 " -"和可写区域,页权限与直映射别名同时约束,所有 CPU 保持 WP/NXE。" -msgstr "" -"Module parameters follow Linux-style ``module_param`` types, command-line parsing, and sysfs " -"permissions. For example, DRM's read-only Boolean ``faildiag`` can be set with ``drm.faildiag=1`` " -"on the kernel command line or ``modprobe drm faildiag=1`` at loading. Built-in drivers are handled" -" by the kernel parameter framework; modprobe passes parameters to external drivers using the same " -"parameter descriptor table. Diagnostics are set at initialization. Use ``0`` or ``N`` to disable; " -"invalid Boolean values reject loading. Read-only or zero-permission parameters cannot be changed " -"arbitrarily through sysfs; stale parameter handles after unloading must not point into a reloaded " -"module's storage. Module version or exported-symbol type CRC mismatches require rebuilding; no " -"forced-load option ignores vermagic or CRCs. Module memory uses separate code, read-only, and " -"writable regions, with both page permissions and direct-map aliases constrained, and WP/NXE " -"retained on every CPU." - -msgid "" -"未定义弱符号只有在确实没有对应导出时才解析为零。若同名导出存在,但类型 CRC、许可证或 namespace 不匹配,加载仍须失败;弱绑定不能绕过这些检查。 x86_64 加载器支持 " -"NONE、64、32、32S、PC32、PLT32 与 PC64 重定位; 未知类型或不可表示的结果会被拒绝。32S 按符号扩展检查,合法负值不会仅因 其为负而被拒绝;越界时不写入目标位置。" -msgstr "" -"Undefined weak symbols resolve to zero only when no corresponding export exists. If an export with" -" the same name exists but its type CRC, license, or namespace does not match, loading must still " -"fail; weak binding cannot bypass these checks. The x86_64 loader supports NONE, 64, 32, 32S, PC32," -" PLT32, and PC64 relocations. Unknown types or unrepresentable results are rejected. 32S is " -"checked using sign extension, so valid negative values are not rejected merely for being negative;" -" out-of-range results do not write the target location." - -msgid "初始化代码随模块保留到卸载,首版不提供 Linux 内部 ``__init`` API 或 初始化段提前回收。模块初始化结束并不能证明注册的回调已不再引用这些段。" -msgstr "" -"Initialization code remains with the module until unloading. The first version provides neither " -"the Linux internal ``__init`` API nor early reclamation of initialization sections. Completion of " -"module initialization does not prove registered callbacks no longer reference those sections." - -msgid "根文件系统模块的启动加载、模块管理命令与镜像更新集成由 ReliefOS 构建链 负责;应分别验证编译、打包、BIOS/UEFI 启动和实际设备操作。" -msgstr "" -"The ReliefOS build chain handles boot-time loading of root-filesystem modules, module management " -"commands, and image-update integration. Compilation, packaging, BIOS/UEFI boot, and actual device " -"operations should be validated separately." +"The loader validates vermagic, type CRCs, dependencies and parameters. It" +" implements the Linux init_module, finit_module and delete_module numbers" +" and requires CAP_SYS_MODULE. finit_module rejects unsupported load " +"flags. As in Linux 6.12 without forced unloading, delete_module accepts " +"O_EXCL and ignores extra bits. O_TRUNC still requires reference, exit and" +" hardware stop checks. finit_module snapshots the file without moving the" +" shared offset. Existing or new writable opens are excluded during the " +"snapshot." + +msgid "" +"模块状态为 COMING、LIVE、GOING。LIVE 表示代码加载成功,是否发现并激活 " +"硬件应检查驱动状态,不能把没有相应硬件的成功注册当作硬件验证。 打开设备、挂载、映射、依赖和执行中的回调会约束卸载;设备停止失败时保留 代码与 " +"DMA 所有权以便诊断和重试。/proc/modules 与 /sys/module 提供状态视图。" +msgstr "" +"Module states are COMING, LIVE, and GOING. LIVE means code loaded " +"successfully; check driver state to determine whether hardware was " +"discovered and activated. Successful registration without the " +"corresponding hardware is not hardware validation. Open devices, mounts, " +"mappings, dependencies, and executing callbacks constrain unloading. If " +"device shutdown fails, code and DMA ownership are retained for diagnosis " +"and retry. /proc/modules and /sys/module expose state views." + +msgid "" +"模块参数遵循 Linux 风格的 ``module_param`` 类型、命令行解析和 sysfs 权限。 例如 DRM 的只读布尔参数 " +"``faildiag`` 可在内核命令行中写为 ``drm.faildiag=1``,或在装载时使用 ``modprobe drm " +"faildiag=1``。 内置驱动由内核参数框架处理,外置驱动由 modprobe 传入同一参数描述表; 诊断在初始化时设置。使用 ``0`` " +"或 ``N`` 可禁用,非法布尔值会拒绝装载。 只读或权限为零的参数不能从 sysfs 任意修改;卸载后的旧参数句柄不能指向 " +"重新加载模块的存储。模块版本与导出符号类型 CRC 不匹配必须重新构建, 不提供忽略 vermagic 或 CRC " +"的强制装载选项。模块内存采用独立的代码、只读 和可写区域,页权限与直映射别名同时约束,所有 CPU 保持 WP/NXE。" +msgstr "" +"Module parameters follow Linux-style ``module_param`` types, command-line" +" parsing, and sysfs permissions. For example, DRM's read-only Boolean " +"``faildiag`` can be set with ``drm.faildiag=1`` on the kernel command " +"line or ``modprobe drm faildiag=1`` at loading. Built-in drivers are " +"handled by the kernel parameter framework; modprobe passes parameters to " +"external drivers using the same parameter descriptor table. Diagnostics " +"are set at initialization. Use ``0`` or ``N`` to disable; invalid Boolean" +" values reject loading. Read-only or zero-permission parameters cannot be" +" changed arbitrarily through sysfs; stale parameter handles after " +"unloading must not point into a reloaded module's storage. Module version" +" or exported-symbol type CRC mismatches require rebuilding; no forced-" +"load option ignores vermagic or CRCs. Module memory uses separate code, " +"read-only, and writable regions, with both page permissions and direct-" +"map aliases constrained, and WP/NXE retained on every CPU." + +msgid "" +"未定义弱符号只有在确实没有对应导出时才解析为零。若同名导出存在,但类型 CRC、许可证或 namespace " +"不匹配,加载仍须失败;弱绑定不能绕过这些检查。 x86_64 加载器支持 NONE、64、32、32S、PC32、PLT32 与 PC64 " +"重定位; 未知类型或不可表示的结果会被拒绝。32S 按符号扩展检查,合法负值不会仅因 其为负而被拒绝;越界时不写入目标位置。" +msgstr "" +"Undefined weak symbols resolve to zero only when no corresponding export " +"exists. If an export with the same name exists but its type CRC, license," +" or namespace does not match, loading must still fail; weak binding " +"cannot bypass these checks. The x86_64 loader supports NONE, 64, 32, 32S," +" PC32, PLT32, and PC64 relocations. Unknown types or unrepresentable " +"results are rejected. 32S is checked using sign extension, so valid " +"negative values are not rejected merely for being negative; out-of-range " +"results do not write the target location." + +msgid "" +"初始化代码随模块保留到卸载,首版不提供 Linux 内部 ``__init`` API 或 " +"初始化段提前回收。模块初始化结束并不能证明注册的回调已不再引用这些段。" +msgstr "" +"Initialization code remains with the module until unloading. The first " +"version provides neither the Linux internal ``__init`` API nor early " +"reclamation of initialization sections. Completion of module " +"initialization does not prove registered callbacks no longer reference " +"those sections." + +msgid "" +"根文件系统模块的启动加载、模块管理命令与镜像更新集成由 ReliefOS 构建链 负责;应分别验证编译、打包、BIOS/UEFI " +"启动和实际设备操作。" +msgstr "" +"The ReliefOS build chain handles boot-time loading of root-filesystem " +"modules, module management commands, and image-update integration. " +"Compilation, packaging, BIOS/UEFI boot, and actual device operations " +"should be validated separately." diff --git a/Documentation/locale/en/LC_MESSAGES/process/e1000e-plan.po b/Documentation/locale/en/LC_MESSAGES/process/e1000e-plan.po index ab4150c6..6f492005 100644 --- a/Documentation/locale/en/LC_MESSAGES/process/e1000e-plan.po +++ b/Documentation/locale/en/LC_MESSAGES/process/e1000e-plan.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "e1000e 实现与验证计划" msgstr "e1000e Implementation and Validation Plan" @@ -20,82 +23,96 @@ msgid "目标与边界" msgstr "Goals and Boundaries" msgid "" -"为 Intel 82574L/82574IT(8086:10d3)和 82583V(8086:150c)提供独立的 原生 PCIe 以太网驱动。沿用现有单 eth0 网络服务、Linux " -"socket/ioctl ABI 及原生模块 owner 管理,不修改 BusyBox 或公开 ABI。其他 e1000e 家族设备 不在本次设备表中。默认内置,允许配置为 e1000e.ko。" +"为 Intel 82574L/82574IT(8086:10d3)和 82583V(8086:150c)提供独立的 原生 PCIe " +"以太网驱动。沿用现有单 eth0 网络服务、Linux socket/ioctl ABI 及原生模块 owner 管理,沿用公开 Linux 网络" +" ABI。其他 e1000e 家族设备 不在本次设备表中。默认内置,允许配置为 e1000e.ko。" msgstr "" -"Provide a standalone native PCIe Ethernet driver for Intel 82574L/82574IT (8086:10d3) and 82583V " -"(8086:150c). Retain the existing single-eth0 network service, Linux socket/ioctl ABI, and native " -"module owner management, without changing BusyBox or public ABI. Other e1000e-family devices are " -"outside this device table. Built in by default, with e1000e.ko configurable." +"Provide a native PCIe Ethernet driver for Intel 82574L/82574IT " +"(8086:10d3) and 82583V (8086:150c). It uses the existing eth0 network " +"service, Linux socket/ioctl ABI and native module ownership. The device " +"table covers these variants. The driver is built in by default and can be" +" configured as e1000e.ko." msgid "" -"实现采用本项目 Apache-2.0 源码,依据 Intel 寄存器手册;不复制 Linux GPL 驱动。保留现有 E1000。芯片识别、复位与链路管理、DMA 收发环和模块注册分别 归属 " -"drivers/net/e1000e/ 中的文件,并由该目录 Kbuild 列出。" +"实现采用本项目 Apache-2.0 源码,依据 Intel 寄存器手册;不复制 Linux GPL 驱动。保留现有 " +"E1000。芯片识别、复位与链路管理、DMA 收发环和模块注册分别 归属 drivers/net/e1000e/ 中的文件,并由该目录 " +"Kbuild 列出。" msgstr "" -"Use this project's Apache-2.0 source, based on Intel register manuals; do not copy Linux GPL " -"drivers. Retain the existing E1000. Chip identification, reset/link management, DMA " -"transmit/receive rings, and module registration belong in separate files under " -"drivers/net/e1000e/, listed by that directory's Kbuild." +"Use this project's Apache-2.0 source, based on Intel register manuals; do" +" not copy Linux GPL drivers. Retain the existing E1000. Chip " +"identification, reset/link management, DMA transmit/receive rings, and " +"module registration belong in separate files under drivers/net/e1000e/, " +"listed by that directory's Kbuild." msgid "执行清单" msgstr "Execution Checklist" msgid "[x] 核对实际工作树、旧 E1000、PCI MMIO/DMA 和网络 owner 生命周期。" -msgstr "[x] Check the actual worktree, legacy E1000, PCI MMIO/DMA, and network owner lifecycle." +msgstr "" +"[x] Check the actual worktree, legacy E1000, PCI MMIO/DMA, and network " +"owner lifecycle." msgid "[x] 先建立驱动行为测试,确认驱动缺失时失败。" -msgstr "[x] Establish driver behavior tests first and confirm failure when the driver is absent." +msgstr "" +"[x] Establish driver behavior tests first and confirm failure when the " +"driver is absent." msgid "[x] 实现精确 PCI 设备表、64 位 BAR、复位、MAC/NVM 和 PHY 自动协商。" msgstr "" -"[x] Implement an exact PCI device table, 64-bit BARs, reset, MAC/NVM, and PHY autonegotiation." +"[x] Implement an exact PCI device table, 64-bit BARs, reset, MAC/NVM, and" +" PHY autonegotiation." msgid "[x] 实现有界异步 TX、完整 RX 校验、并发环访问和安全停止/回滚。" msgstr "" -"[x] Implement bounded asynchronous TX, full RX validation, concurrent ring access, and safe " -"shutdown/rollback." +"[x] Implement bounded asynchronous TX, full RX validation, concurrent " +"ring access, and safe shutdown/rollback." msgid "[x] 接入 E1000E tristate、模块别名、默认内置和独立模块构建。" msgstr "" -"[x] Integrate the E1000E tristate, module aliases, default built-in configuration, and separate " -"module build." +"[x] Integrate the E1000E tristate, module aliases, default built-in " +"configuration, and separate module build." msgid "[x] 防止第二个网络提供者覆盖已有 eth0,验证原提供者仍然可用。" msgstr "" -"[x] Prevent a second network provider from overwriting existing eth0 and verify the original " -"provider remains usable." +"[x] Prevent a second network provider from overwriting existing eth0 and " +"verify the original provider remains usable." msgid "[x] 运行定向宿主测试、内置和模块构建、相关 Kconfig/归属检查。" msgstr "" -"[x] Run targeted host tests, built-in and module builds, and related Kconfig/ownership checks." +"[x] Run targeted host tests, built-in and module builds, and related " +"Kconfig/ownership checks." msgid "[x] 在私有 QEMU 镜像验证 DHCP、IPv4/IPv6、TCP 数据校验和模块重载。" msgstr "" -"[x] Validate DHCP, IPv4/IPv6, TCP data integrity, and module reloading with a private QEMU image." +"[x] Validate DHCP, IPv4/IPv6, TCP data integrity, and module reloading " +"with a private QEMU image." msgid "[x] 更新驱动文档,分别记录 QEMU、VMware、实体硬件的验证边界。" msgstr "" -"[x] Update driver documentation, recording QEMU, VMware, and physical hardware validation " -"boundaries separately." +"[x] Update driver documentation, recording QEMU, VMware, and physical " +"hardware validation boundaries separately." msgid "验证约束" msgstr "Validation Constraints" msgid "" -"测试驱动初始化、DMA 地址而非 CPU 地址、描述符回收与环回绕、错误 RX、 无网线启动、分配/映射失败、复位超时和卸载后的资源回收。宿主硬件模型只替代 PCI/MMIO/DMA " +"测试驱动初始化、DMA 地址而非 CPU 地址、描述符回收与环回绕、错误 RX、 " +"无网线启动、分配/映射失败、复位超时和卸载后的资源回收。宿主硬件模型只替代 PCI/MMIO/DMA " "外部设备,执行真实驱动入口与回调;不为生产驱动增加测试接口。" msgstr "" -"Test driver initialization, DMA rather than CPU addresses, descriptor reclamation and ring " -"wraparound, erroneous RX, boot without a cable, allocation/mapping failures, reset timeout, and " -"resource reclamation after unloading. The host hardware model substitutes only external " -"PCI/MMIO/DMA devices and executes real driver entries and callbacks; add no test interfaces to " -"production drivers." +"Test driver initialization, DMA rather than CPU addresses, descriptor " +"reclamation and ring wraparound, erroneous RX, boot without a cable, " +"allocation/mapping failures, reset timeout, and resource reclamation " +"after unloading. The host hardware model substitutes only external " +"PCI/MMIO/DMA devices and executes real driver entries and callbacks; add " +"no test interfaces to production drivers." msgid "" -"内核行为探针和宿主测试放在 ReliefNT;完整镜像与 QEMU 编排放在 ReliefOS。 仅修改新建的 out/e1000e/ 留证与镜像副本,保留原镜像。TMPDIR 使用父仓 " -"out/tmp。实体硬件与 VMware 未运行时必须明确标记未验证。" +"内核行为探针和宿主测试放在 ReliefNT;完整镜像与 QEMU 编排放在 ReliefOS。 仅修改新建的 out/e1000e/ " +"留证与镜像副本,保留原镜像。TMPDIR 使用父仓 out/tmp。实体硬件与 VMware 未运行时必须明确标记未验证。" msgstr "" -"Kernel behavior probes and host tests belong in ReliefNT; full images and QEMU orchestration " -"belong in ReliefOS. Modify only newly created evidence and image copies under out/e1000e/, " -"retaining original images. Use the parent repository's out/tmp for TMPDIR. Physical hardware and " +"Kernel behavior probes and host tests belong in ReliefNT; full images and" +" QEMU orchestration belong in ReliefOS. Modify only newly created " +"evidence and image copies under out/e1000e/, retaining original images. " +"Use the parent repository's out/tmp for TMPDIR. Physical hardware and " "VMware must be explicitly marked unvalidated if not run." diff --git a/Documentation/locale/en/LC_MESSAGES/process/testing.po b/Documentation/locale/en/LC_MESSAGES/process/testing.po index 94646383..daccd615 100644 --- a/Documentation/locale/en/LC_MESSAGES/process/testing.po +++ b/Documentation/locale/en/LC_MESSAGES/process/testing.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "内核验证" msgstr "Kernel Validation" @@ -21,17 +24,19 @@ msgstr "Targeted Checks" msgid "从本仓运行受影响目标;作为父仓子模块时 TMPDIR 使用父仓 out/tmp::" msgstr "" -"Run affected targets from this repository; when used as a parent repository's submodule, set " -"TMPDIR to the parent's out/tmp::" +"Run affected targets from this repository; when used as a parent " +"repository's submodule, set TMPDIR to the parent's out/tmp::" msgid "" -"module-layout 检查本地 Kbuild、重复/遗漏对象、生产实现包含和上游引擎摘要。 宿主工具/ASan/UBSan、头导出、自包含 C/C++、ELF 和真实运行是不同层次。 ABI" -" 变化必须明确审查,不通过重生成历史 golden 消除差异。" +"module-layout 检查本地 Kbuild、重复/遗漏对象、生产实现包含和上游引擎摘要。 宿主工具/ASan/UBSan、头导出、自包含 " +"C/C++、ELF 和真实运行是不同层次。 ABI 变化必须明确审查,不通过重生成历史 golden 消除差异。" msgstr "" -"module-layout checks local Kbuild files, duplicate/missing objects, inclusion of production " -"implementations, and upstream engine digests. Host tools/ASan/UBSan, header exports, self-" -"contained C/C++, ELF, and actual execution are distinct layers. ABI changes require explicit " -"review, not regeneration of historical golden data to eliminate differences." +"module-layout checks local Kbuild files, duplicate/missing objects, " +"inclusion of production implementations, and upstream engine digests. " +"Host tools/ASan/UBSan, header exports, self-contained C/C++, ELF, and " +"actual execution are distinct layers. ABI changes require explicit " +"review, not regeneration of historical golden data to eliminate " +"differences." msgid "" "``tools/tests/pidfd_probe.c`` 是原生 Linux ABI 对照探针。可用宿主 C 编译器 以 " @@ -49,162 +54,214 @@ msgid "测试归属" msgstr "Test Ownership" msgid "" -"``tools/test_*.py``、``tools/tests/`` 与 ``tests/host/`` 保存内核实现、 驱动、文件系统、调度、内存管理和 Linux UAPI " -"的宿主测试、原生系统调用探针、 夹具及参考头。它们使用本仓源码与头文件,不依赖 ReliefOS 父仓的用户态或 构建目录。固定 syscall 表及其维护生成器也由本仓持有。" +"``tools/test_*.py``、``tools/tests/`` 与 ``tests/host/`` 保存内核实现、 " +"驱动、文件系统、调度、内存管理和 Linux UAPI 的宿主测试、原生系统调用探针、 夹具及参考头。它们使用本仓源码与头文件,不依赖 " +"ReliefOS 父仓的用户态或 构建目录。固定 syscall 表及其维护生成器也由本仓持有。" msgstr "" -"``tools/test_*.py``, ``tools/tests/``, and ``tests/host/`` hold host tests, native syscall probes," -" fixtures, and reference headers for kernel implementations, drivers, filesystems, scheduling, " -"memory management, and Linux UAPI. They use this repository's source and headers without depending" -" on ReliefOS userspace or build directories. This repository also owns the fixed syscall table and" -" its maintenance generator." +"``tools/test_*.py``, ``tools/tests/``, and ``tests/host/`` hold host " +"tests, native syscall probes, fixtures, and reference headers for kernel " +"implementations, drivers, filesystems, scheduling, memory management, and" +" Linux UAPI. They use this repository's source and headers without " +"depending on ReliefOS userspace or build directories. This repository " +"also owns the fixed syscall table and its maintenance generator." msgid "独立 checkout 或源码归档中可运行::" msgstr "In a standalone checkout or source archive, run::" msgid "" "``tools/tests/host-suites.list`` 显式登记宿主套件和必要参数;runner 保留各套件 日志及 " -"``results.json``,任何失败均返回非零,后续套件仍会执行以形成完整报告。 ``test-host-smoke`` 是 CI 中的定向门禁;完整 ``test`` 还包括所有宿主套件、" -" ABI golden、导出头、启动、vDSO、徽标、panic、Kconfig 和模块布局检查。 仅有 Linux 参考探针通过,不表示相同接口已在 ReliefNT 来宾运行通过。" +"``results.json``,任何失败均返回非零,后续套件仍会执行以形成完整报告。 ``test-host-smoke`` 是 CI " +"中的定向门禁;完整 ``test`` 还包括所有宿主套件、 ABI golden、导出头、启动、vDSO、徽标、panic、Kconfig " +"和模块布局检查。 仅有 Linux 参考探针通过,不表示相同接口已在 ReliefNT 来宾运行通过。" msgstr "" -"``tools/tests/host-suites.list`` explicitly registers host suites and required arguments. The " -"runner retains suite logs and ``results.json``, returns nonzero for any failure, and continues " -"later suites for a complete report. ``test-host-smoke`` is a targeted CI gate; full ``test`` also " -"includes all host suites, ABI golden, exported headers, boot, vDSO, logo, panic, Kconfig, and " -"module layout checks. A passing Linux reference probe does not mean the same interface passed in a" -" ReliefNT guest." +"``tools/tests/host-suites.list`` explicitly registers host suites and " +"required arguments. The runner retains suite logs and ``results.json``, " +"returns nonzero for any failure, and continues later suites for a " +"complete report. ``test-host-smoke`` is a targeted CI gate; full ``test``" +" also includes all host suites, ABI golden, exported headers, boot, vDSO," +" logo, panic, Kconfig, and module layout checks. A passing Linux " +"reference probe does not mean the same interface passed in a ReliefNT " +"guest." msgid "" -"``procfs`` 套件执行真实 proc/VFS/fdinfo 的 ASan/UBSan 夹具,并在宿主 Linux 编译运行 ``tools/tests/procfs_probe.c`` " -"作为 ABI 参考。探针检查系统/进程节点、 seek、maps、二进制 auxv、描述符和多线程 thread-self;来宾验证应由操作系统 使用其 SDK " -"编译该探针后实际运行,并与宿主结果分别记录。" +"``procfs`` 套件执行真实 proc/VFS/fdinfo 的 ASan/UBSan 夹具,并在宿主 Linux 编译运行 " +"``tools/tests/procfs_probe.c`` 作为 ABI 参考。探针检查系统/进程节点、 seek、maps、二进制 " +"auxv、描述符和多线程 thread-self;来宾验证应由操作系统 使用其 SDK 编译该探针后实际运行,并与宿主结果分别记录。" msgstr "" -"The ``procfs`` suite runs ASan/UBSan fixtures for actual proc/VFS/fdinfo and compiles/runs " -"``tools/tests/procfs_probe.c`` on host Linux as an ABI reference. The probe checks system/process " -"nodes, seek, maps, binary auxv, descriptors, and multithreaded thread-self. For guest validation, " -"the OS should compile it with its SDK and actually execute it, recording guest and host results " -"separately." +"The ``procfs`` suite runs ASan/UBSan fixtures for actual proc/VFS/fdinfo " +"and compiles/runs ``tools/tests/procfs_probe.c`` on host Linux as an ABI " +"reference. The probe checks system/process nodes, seek, maps, binary " +"auxv, descriptors, and multithreaded thread-self. For guest validation, " +"the OS should compile it with its SDK and actually execute it, recording " +"guest and host results separately." msgid "" -"同套件还运行无需 libc 的 ``tools/tests/procfs_raw_probe.c``。该探针可编译为 initramfs 的 ``/init``,通过 " -"``rdinit=/init`` 在真实挂载的 procfs 上验收; PID 1 将结果写入串口并等待。编译示例::" +"同套件还运行无需 libc 的 ``tools/tests/procfs_raw_probe.c``。该探针可编译为 initramfs 的 " +"``/init``,通过 ``rdinit=/init`` 在真实挂载的 procfs 上验收; PID 1 将结果写入串口并等待。编译示例::" msgstr "" -"The same suite also runs libc-free ``tools/tests/procfs_raw_probe.c``. It can be built as an " -"initramfs ``/init`` and booted with ``rdinit=/init`` to validate actually mounted procfs; PID 1 " -"writes results to serial and waits. Build example::" +"The same suite also runs libc-free ``tools/tests/procfs_raw_probe.c``. It" +" can be built as an initramfs ``/init`` and booted with ``rdinit=/init`` " +"to validate actually mounted procfs; PID 1 writes results to serial and " +"waits. Build example::" -msgid "来宾验收分别记录单核和多核启动的完整串口日志、内核与探针摘要; 出现 PASS 后仍需检查没有 FAIL 或 panic,不能只以启动完成代替 syscall 验证。" +msgid "" +"来宾验收分别记录单核和多核启动的完整串口日志、内核与探针摘要; 出现 PASS 后仍需检查没有 FAIL 或 panic,不能只以启动完成代替 " +"syscall 验证。" msgstr "" -"Guest acceptance records full serial logs and kernel/probe digests separately for single-core and " -"multicore boots. Even after PASS, check for any FAIL or panic; boot completion alone does not " -"validate syscalls." +"Guest acceptance records full serial logs and kernel/probe digests " +"separately for single-core and multicore boots. Even after PASS, check " +"for any FAIL or panic; boot completion alone does not validate syscalls." -msgid "``service_roles`` 套件检查旧内核桌面实现未恢复、旧窗口服务权限标志未恢复, 以及 exec 只保留允许的任务标志;这些内核源码检查由本仓持有,父仓不再重复。" +msgid "" +"``seccomp_bpf`` 套件以 ASan/UBSan 直接运行生产用经典 BPF 验证器和解释器。 " +"``tools/tests/seccomp_probe.c`` 可用静态 x86-64 glibc 工具链编译,在测试系统 " +"中以普通进程运行(不可直接作为 PID 1),退出成功时打印 ``SECCOMP_ABI_PASS``。 在 Linux 上不带参数运行,在 " +"ReliefNT 上添加 ``--reliefnt`` 测试原生旧入口和 未支持扩展。来宾串口证据应包含实际在线 CPU 数、探针结果及 " +"guest 退出状态。" +msgstr "" +"The ``seccomp_bpf`` suite runs the production classic BPF validator and " +"interpreter under ASan/UBSan. Build ``tools/tests/seccomp_probe.c`` with " +"a static x86-64 glibc toolchain and run it as an ordinary process. It " +"prints ``SECCOMP_ABI_PASS`` on success. Use no arguments on Linux, and " +"``--reliefnt`` for the native interface and unsupported extensions on " +"ReliefNT. Record online CPU count, probe output and guest exit status." + +msgid "" +"``service_roles`` 套件检查旧内核桌面实现未恢复、旧窗口服务权限标志未恢复, 以及 exec " +"只保留允许的任务标志;这些内核源码检查由本仓持有,父仓不再重复。" msgstr "" -"The ``service_roles`` suite checks that legacy in-kernel desktop implementations and old window-" -"service permission flags have not returned, and that exec preserves only permitted task flags. " -"This repository owns these kernel source checks; the parent no longer duplicates them." +"The ``service_roles`` suite checks that legacy in-kernel desktop " +"implementations and old window-service permission flags have not " +"returned, and that exec preserves only permitted task flags. This " +"repository owns these kernel source checks; the parent no longer " +"duplicates them." msgid "" -"``syscall_io`` 套件覆盖真实设备节点标志组合下的 ``/dev/null`` 写入、访问模式、 ``O_PATH`` 和 Linux ``MAX_RW_COUNT`` " -"上限,避免通用设备分片截短空设备写入。 其原生探针 ``tools/tests/syscall_io_runtime_probe.c`` 编译后可用 ``--null`` 单独检查大块写入、原始 " -"write syscall、dup 和 writev;默认模式继续运行综合 POSIX I/O 检查。宿主 Linux 参考运行与 ReliefNT 来宾执行分别记录。" +"``syscall_io`` 套件覆盖真实设备节点标志组合下的 ``/dev/null`` 写入、访问模式、 ``O_PATH`` 和 Linux" +" ``MAX_RW_COUNT`` 上限,避免通用设备分片截短空设备写入。 其原生探针 " +"``tools/tests/syscall_io_runtime_probe.c`` 编译后可用 ``--null`` 单独检查大块写入、原始 " +"write syscall、dup 和 writev;默认模式继续运行综合 POSIX I/O 检查。宿主 Linux 参考运行与 " +"ReliefNT 来宾执行分别记录。" msgstr "" -"The ``syscall_io`` suite covers ``/dev/null`` writes under actual device-node flag combinations, " -"access modes, ``O_PATH``, and Linux's ``MAX_RW_COUNT`` limit, preventing generic device chunking " -"from truncating null-device writes. Its native ``tools/tests/syscall_io_runtime_probe.c`` can be " -"compiled and run with ``--null`` to check large writes, raw write syscalls, dup, and writev alone;" -" default mode retains comprehensive POSIX I/O checks. Record host Linux reference and ReliefNT " -"guest runs separately." +"The ``syscall_io`` suite covers ``/dev/null`` writes under actual device-" +"node flag combinations, access modes, ``O_PATH``, and Linux's " +"``MAX_RW_COUNT`` limit, preventing generic device chunking from " +"truncating null-device writes. Its native " +"``tools/tests/syscall_io_runtime_probe.c`` can be compiled and run with " +"``--null`` to check large writes, raw write syscalls, dup, and writev " +"alone; default mode retains comprehensive POSIX I/O checks. Record host " +"Linux reference and ReliefNT guest runs separately." msgid "" -"``test-smp-time``、``test-page-cache-growth``、``test-user-return``、 ``test-syscall-io" -"``、``test-vdso-host`` 和 ``test-version`` 提供定向入口。 ``make test-ext4-reference " -"LINUX_REFERENCE=<目录>`` 检查 ext4 schema, 需要已有 Linux 参考树; 它不会下载参考源码。互操作检查需要宿主 ``e2fsprogs``。 " -"``squashfs`` 宿主套件需要 ``squashfs-tools``,用 ``mksquashfs`` 生成真实镜像, 并用 ``unsquashfs`` " -"交叉检查文件内容;``squashfs_boot`` 检查 Multiboot2 载荷 对应的只读 RAM 设备。两项均不替代来宾挂载与安装测试。 音频探针 ``--build-" -"guest`` 需要显式传入由操作系统提供的 ``--sdk``。" +"``test-smp-time``、``test-page-cache-growth``、``test-user-return``、 " +"``test-syscall-io``、``test-vdso-host`` 和 ``test-version`` 提供定向入口。 ``make " +"test-ext4-reference LINUX_REFERENCE=<目录>`` 检查 ext4 schema, 需要已有 Linux " +"参考树; 它不会下载参考源码。互操作检查需要宿主 ``e2fsprogs``。 ``squashfs`` 宿主套件需要 ``squashfs-" +"tools``,用 ``mksquashfs`` 生成真实镜像, 并用 ``unsquashfs`` " +"交叉检查文件内容;``squashfs_boot`` 检查 Multiboot2 载荷 对应的只读 RAM 设备。两项均不替代来宾挂载与安装测试。" +" 音频探针 ``--build-guest`` 需要显式传入由操作系统提供的 ``--sdk``。" msgstr "" -"``test-smp-time``, ``test-page-cache-growth``, ``test-user-return``, ``test-syscall-io``, " -"``test-vdso-host``, and ``test-version`` provide targeted entry points. ``make test-" -"ext4-reference LINUX_REFERENCE=<目录>`` checks ext4 schemas and requires an existing Linux " -"reference tree; it does not download reference source. Interoperability checks require host " -"``e2fsprogs``. The ``squashfs`` host suite requires ``squashfs-tools``. It generates real " -"images with ``mksquashfs`` and cross-checks file contents with ``unsquashfs``. " -"``squashfs_boot`` checks the read-only RAM device for the Multiboot2 payload. Guest mount and" -" installation tests are still required. Audio probe ``--build-guest`` requires explicitly " +"``test-smp-time``, ``test-page-cache-growth``, ``test-user-return``, " +"``test-syscall-io``, ``test-vdso-host``, and ``test-version`` provide " +"targeted entry points. ``make test-ext4-reference LINUX_REFERENCE=<目录>`` " +"checks ext4 schemas and requires an existing Linux reference tree; it " +"does not download reference source. Interoperability checks require host " +"``e2fsprogs``. The ``squashfs`` host suite requires ``squashfs-tools``. " +"It generates real images with ``mksquashfs`` and cross-checks file " +"contents with ``unsquashfs``. ``squashfs_boot`` checks the read-only RAM " +"device for the Multiboot2 payload. Guest mount and installation tests are" +" still required. Audio probe ``--build-guest`` requires explicitly " "passing the OS-provided ``--sdk``." msgid "兼容性基线" msgstr "Compatibility Baseline" msgid "" -"``tools/tests/abi_layout_golden.json`` 保留原始布局基线; ``tools/tests/fixtures/legacy-abi-layout.json`` " -"保存旧导出面的原始布局记录, 迁移时逐字保留,两份均不能通过重生成来掩盖布局变化。 驱动服务表版本 2 的 17 个追加字段在 ``tools/tests/fixtures/driver-" -"api-v2.json`` 单独冻结:168 字节旧前缀的类型与 偏移仍与原始基线比较,当前服务表总长为 304 字节、对齐为 8。 ``make test-abi`` " -"同时检查旧前缀与追加字段,版本、大小、偏移和类型变化 均需显式审查。``abi_layout_checks`` 套件包含对应的失败反例;驱动管理器的 ``driver_modules`` " -"套件验证旧版本、未知版本和错误描述符大小在 init 前被拒绝。 这不表示版本 1 驱动二进制能在版本 2 内核运行。" -msgstr "" -"``tools/tests/abi_layout_golden.json`` retains the original layout baseline; " -"``tools/tests/fixtures/legacy-abi-layout.json`` records the original legacy export layout. " -"Preserve both verbatim during migration; neither may be regenerated to conceal layout changes. The" -" driver service table version 2's 17 appended fields are frozen separately in " -"``tools/tests/fixtures/driver-api-v2.json``. Types and offsets in the 168-byte legacy prefix are " -"still compared to the original baseline; the current table is 304 bytes with alignment 8. ``make " -"test-abi`` checks both the prefix and appended fields; version, size, offset, and type changes " -"require explicit review. ``abi_layout_checks`` includes corresponding negative cases; the driver " -"manager's ``driver_modules`` suite verifies rejection of old/unknown versions and incorrect " -"descriptor sizes before init. This does not mean version 1 driver binaries run on version 2 " -"kernels." - -msgid "" -"音频 ioctl 支持清单为 ``configs/audio-abi-support.json``。 宿主门禁检查标志类型、构建前提、证据路径和验证范围;来宾、上游 ALSA 与 " -"硬件声明必须有对应说明,缺少证据声明的反例应失败。清单保留已有的验证标志 和未解决项;这些静态检查不重新执行历史来宾测试,不构成新的运行验收。 ``linux_audio`` 的 " -"ASan/UBSan 探针遇到未定义行为立即失败,不将带有 sanitizer 错误的零退出状态计为通过;PCM 回归覆盖尚无 DMA 缓冲区时的 DROP。" -msgstr "" -"The audio ioctl support manifest is ``configs/audio-abi-support.json``. Host gates check flag " -"types, build prerequisites, evidence paths, and validation scope. Guest, upstream ALSA, and " -"hardware claims require corresponding descriptions; negative cases lacking evidence declarations " -"must fail. The manifest retains existing validation flags and unresolved items. These static " -"checks do not rerun historical guest tests or constitute new runtime acceptance. The " -"``linux_audio`` ASan/UBSan probe fails immediately on undefined behavior and does not count a zero" -" exit status with sanitizer errors as a pass; PCM regressions cover DROP before a DMA buffer " -"exists." - -msgid "" -"``sched_wakeup`` 套件覆盖生产调度唤醒与 SMP IPI 的逻辑 CPU/APIC 映射、启动 交接、合并通知、本地 IRQ 状态、离线/单核及停止/vfork 任务边界。输入 " -"IRQ 夹具另检查重新调度向量不会被当成 timer 或 PIC 中断。I/O 预算测试在旧 uptime 停止增长时检查续传、偏移与完整结果;vDSO/timekeeper 测试区分内部 CPU" -" 本地工作计数与用户可见时钟。framebuffer 的 guard-page 夹具检查精确 像素范围、未对齐来源和行尾边界,既有 FIFO 满时的损伤重试仍须通过。" -msgstr "" -"The ``sched_wakeup`` suite covers logical CPU/APIC mappings for production scheduler wakeups and " -"SMP IPIs, boot handoff, notification coalescing, local IRQ state, offline/single-core cases, and " -"stopped/vfork task boundaries. Input IRQ fixtures also check that reschedule vectors are not " -"treated as timer or PIC interrupts. I/O budget tests check resumption, offsets, and complete " -"results when legacy uptime stops advancing; vDSO/timekeeper tests distinguish internal CPU-local " -"work counters from user-visible clocks. Framebuffer guard-page fixtures check exact pixel ranges, " -"unaligned sources, and line-end boundaries; existing damage retries when the FIFO is full must " -"still pass." +"``tools/tests/abi_layout_golden.json`` 保留原始布局基线; ``tools/tests/fixtures" +"/legacy-abi-layout.json`` 保存旧导出面的原始布局记录, 迁移时逐字保留,两份均不能通过重生成来掩盖布局变化。 " +"驱动服务表版本 2 的 17 个追加字段在 ``tools/tests/fixtures/driver-api-v2.json`` " +"单独冻结:168 字节旧前缀的类型与 偏移仍与原始基线比较,当前服务表总长为 304 字节、对齐为 8。 ``make test-abi`` " +"同时检查旧前缀与追加字段,版本、大小、偏移和类型变化 均需显式审查。``abi_layout_checks`` " +"套件包含对应的失败反例;驱动管理器的 ``driver_modules`` 套件验证旧版本、未知版本和错误描述符大小在 init 前被拒绝。 " +"这不表示版本 1 驱动二进制能在版本 2 内核运行。" +msgstr "" +"``tools/tests/abi_layout_golden.json`` retains the original layout " +"baseline; ``tools/tests/fixtures/legacy-abi-layout.json`` records the " +"original legacy export layout. Preserve both verbatim during migration; " +"neither may be regenerated to conceal layout changes. The driver service " +"table version 2's 17 appended fields are frozen separately in " +"``tools/tests/fixtures/driver-api-v2.json``. Types and offsets in the " +"168-byte legacy prefix are still compared to the original baseline; the " +"current table is 304 bytes with alignment 8. ``make test-abi`` checks " +"both the prefix and appended fields; version, size, offset, and type " +"changes require explicit review. ``abi_layout_checks`` includes " +"corresponding negative cases; the driver manager's ``driver_modules`` " +"suite verifies rejection of old/unknown versions and incorrect descriptor" +" sizes before init. This does not mean version 1 driver binaries run on " +"version 2 kernels." + +msgid "" +"音频 ioctl 支持清单为 ``configs/audio-abi-support.json``。 " +"宿主门禁检查标志类型、构建前提、证据路径和验证范围;来宾、上游 ALSA 与 " +"硬件声明必须有对应说明,缺少证据声明的反例应失败。清单保留已有的验证标志 和未解决项;这些静态检查不重新执行历史来宾测试,不构成新的运行验收。 " +"``linux_audio`` 的 ASan/UBSan 探针遇到未定义行为立即失败,不将带有 sanitizer " +"错误的零退出状态计为通过;PCM 回归覆盖尚无 DMA 缓冲区时的 DROP。" +msgstr "" +"The audio ioctl support manifest is ``configs/audio-abi-support.json``. " +"Host gates check flag types, build prerequisites, evidence paths, and " +"validation scope. Guest, upstream ALSA, and hardware claims require " +"corresponding descriptions; negative cases lacking evidence declarations " +"must fail. The manifest retains existing validation flags and unresolved " +"items. These static checks do not rerun historical guest tests or " +"constitute new runtime acceptance. The ``linux_audio`` ASan/UBSan probe " +"fails immediately on undefined behavior and does not count a zero exit " +"status with sanitizer errors as a pass; PCM regressions cover DROP before" +" a DMA buffer exists." + +msgid "" +"``sched_wakeup`` 套件覆盖生产调度唤醒与 SMP IPI 的逻辑 CPU/APIC 映射、启动 交接、合并通知、本地 IRQ " +"状态、离线/单核及停止/vfork 任务边界。输入 IRQ 夹具另检查重新调度向量不会被当成 timer 或 PIC 中断。I/O 预算测试在旧 " +"uptime 停止增长时检查续传、偏移与完整结果;vDSO/timekeeper 测试区分内部 CPU " +"本地工作计数与用户可见时钟。framebuffer 的 guard-page 夹具检查精确 像素范围、未对齐来源和行尾边界,既有 FIFO " +"满时的损伤重试仍须通过。" +msgstr "" +"The ``sched_wakeup`` suite covers logical CPU/APIC mappings for " +"production scheduler wakeups and SMP IPIs, boot handoff, notification " +"coalescing, local IRQ state, offline/single-core cases, and stopped/vfork" +" task boundaries. Input IRQ fixtures also check that reschedule vectors " +"are not treated as timer or PIC interrupts. I/O budget tests check " +"resumption, offsets, and complete results when legacy uptime stops " +"advancing; vDSO/timekeeper tests distinguish internal CPU-local work " +"counters from user-visible clocks. Framebuffer guard-page fixtures check " +"exact pixel ranges, unaligned sources, and line-end boundaries; existing " +"damage retries when the FIFO is full must still pass." msgid "" "同一调度套件检查 IRQ 延迟时的公平时间计费、ACPI PM 回绕及源切换;APIC 夹具检查 100/250/1000 Hz " -"的计数与失败回退。``private_fault_transactions`` 使用真实缺页分发、页表和返回谓词,检查无抢占请求时的私有页直接恢复, " -"以及远端通知、信号、停止、亲和性和失效帧仍进入调度路径。" +"的计数与失败回退。``private_fault_transactions`` " +"使用真实缺页分发、页表和返回谓词,检查无抢占请求时的私有页直接恢复, 以及远端通知、信号、停止、亲和性和失效帧仍进入调度路径。" msgstr "" -"The same scheduler suite checks fair time charging during IRQ delays, ACPI PM wraparound, and " -"source switching; APIC fixtures check counts and failure fallback at 100/250/1000 Hz. " -"``private_fault_transactions`` uses actual fault dispatch, page tables, and return predicates to " -"check direct private-page restoration without preemption requests, while remote notifications, " -"signals, stops, affinity, and invalid frames still take the scheduling path." +"The same scheduler suite checks fair time charging during IRQ delays, " +"ACPI PM wraparound, and source switching; APIC fixtures check counts and " +"failure fallback at 100/250/1000 Hz. ``private_fault_transactions`` uses " +"actual fault dispatch, page tables, and return predicates to check direct" +" private-page restoration without preemption requests, while remote " +"notifications, signals, stops, affinity, and invalid frames still take " +"the scheduling path." msgid "" "``process_priority`` 使用真实 syscall 分发验证 PRIO_PROCESS 的同属主父进程 " -"降优先级、跨属主拒绝、CAP_SYS_NICE、升优先级拒绝、数值钳制、ESRCH 和 Linux 返回值编码;不修改宿主进程的调度状态。整机还需验证 XDM/IceWM " -"与用户终端分别继承预期优先级,不能以临时 root 提权实验代替启动链检查。" +"降优先级、跨属主拒绝、CAP_SYS_NICE、升优先级拒绝、数值钳制、ESRCH 和 Linux " +"返回值编码;不修改宿主进程的调度状态。整机还需验证 XDM/IceWM 与用户终端分别继承预期优先级,不能以临时 root " +"提权实验代替启动链检查。" msgstr "" -"``process_priority`` uses actual syscall dispatch to validate PRIO_PROCESS priority lowering by a " -"same-owner parent, cross-owner denial, CAP_SYS_NICE, priority-raising denial, value clamping, " -"ESRCH, and Linux return encoding, without changing host process scheduling. Full-system validation" -" must also check expected inherited priorities for XDM/IceWM and user terminals separately; " -"temporary root escalation experiments cannot replace boot-chain checks." +"``process_priority`` uses actual syscall dispatch to validate " +"PRIO_PROCESS priority lowering by a same-owner parent, cross-owner " +"denial, CAP_SYS_NICE, priority-raising denial, value clamping, ESRCH, and" +" Linux return encoding, without changing host process scheduling. Full-" +"system validation must also check expected inherited priorities for " +"XDM/IceWM and user terminals separately; temporary root escalation " +"experiments cannot replace boot-chain checks." msgid "" "``pat`` 套件覆盖生产 PAT 引导/AP 策略及真实页表的 UC 到 WC 转换: " @@ -221,26 +278,27 @@ msgid "目标运行" msgstr "Target Execution" msgid "" -"启动检查固件与内核完成、PID 1;系统调用探针必须实际进入来宾。 panic 验证还需真实异常与画面,徽标需检查数量、留距和移除。 主仓提供集成 QEMU " -"工具,但它们不是本仓新增产品;每次记录源码与二进制 摘要,保留源镜像。VMware 与物理硬件未验证不能记作通过。" +"``tools/tests/uname_runtime_probe.c`` 使用 libc 与原始 uname 系统调用,检查 原生/Linux " +"系统名、其他字段不变、prctl 参数拒绝、fork/线程/exec/vfork 继承及相互隔离。编译时使用导出的 " +"```` 和 pthread; 来宾原生运行不带参数,Linux 模式运行时传入 " +"``Linux``,可分别编译静态和 动态程序。仅在 ReliefNT 来宾执行,其扩展不要求宿主 Linux 实现。" msgstr "" -"Boot checks cover firmware and kernel completion and PID 1; syscall probes must actually enter the" -" guest. Panic validation also requires real exceptions and screen output; logos require count, " -"spacing, and removal checks. The main repository provides integrated QEMU tools, but they are not " -"new products of this repository. Record source and binary digests each time and retain source " -"images. Unvalidated VMware and physical hardware must not be marked passed." - -msgid "``tools/tests/uname_runtime_probe.c`` 使用 libc 与原始 uname 系统调用,检查 原生/Linux 系统名、其他字段不变、prctl 参数拒绝、fork/线程/exec/vfork 继承及相互隔离。编译时使用导出的 ```` 和 pthread; 来宾原生运行不带参数,Linux 模式运行时传入 ``Linux``,可分别编译静态和 动态程序。仅在 ReliefNT 来宾执行,其扩展不要求宿主 Linux 实现。" -msgstr "``tools/tests/uname_runtime_probe.c`` uses libc and raw uname syscalls to check native/Linux system names, unchanged remaining fields, rejected prctl arguments, inheritance through fork/threads/exec/vfork, and isolation. Compile with the exported ```` and pthread. Run without arguments for the guest's native mode, or pass ``Linux`` for Linux mode. Build static and dynamic versions separately. Run only in a ReliefNT guest; host Linux is not required to implement these extensions." +"``tools/tests/uname_runtime_probe.c`` uses libc and raw uname syscalls to" +" check native/Linux system names, unchanged remaining fields, rejected " +"prctl arguments, inheritance through fork/threads/exec/vfork, and " +"isolation. Compile with the exported ```` and pthread. " +"Run without arguments for the guest's native mode, or pass ``Linux`` for " +"Linux mode. Build static and dynamic versions separately. Run only in a " +"ReliefNT guest; host Linux is not required to implement these extensions." msgid "" -"``seccomp_bpf`` 套件以 ASan/UBSan 直接运行生产用经典 BPF 验证器和解释器。 ``tools/tests/seccomp_probe.c`` 可用静态 " -"x86-64 musl 工具链编译,在测试系统 中以普通进程运行(不可直接作为 PID 1),退出成功时打印 ``SECCOMP_ABI_PASS``。 在 Linux " -"上不带参数运行,在 ReliefNT 上添加 ``--reliefnt`` 测试原生旧入口和 未支持扩展。来宾串口证据应包含实际在线 CPU 数、探针结果及 guest 退出状态。" +"启动检查固件与内核完成、PID 1;系统调用探针必须实际进入来宾。 panic 验证还需真实异常与画面,徽标需检查数量、留距和移除。 主仓提供集成" +" QEMU 工具,但它们不是本仓新增产品;每次记录源码与二进制 摘要,保留源镜像。VMware 与物理硬件未验证不能记作通过。" msgstr "" -"The ``seccomp_bpf`` suite runs the production classic BPF verifier and interpreter directly " -"under ASan/UBSan. Build ``tools/tests/seccomp_probe.c`` with a static x86-64 musl toolchain " -"and run it as a normal process in the test system (never directly as PID 1). Successful " -"execution prints ``SECCOMP_ABI_PASS``. Run without arguments on Linux; add ``--reliefnt`` on " -"ReliefNT to test the native legacy entry and unsupported extensions. Guest serial evidence " -"should include the actual online CPU count, probe results, and guest exit status." +"Boot checks cover firmware and kernel completion and PID 1; syscall " +"probes must actually enter the guest. Panic validation also requires real" +" exceptions and screen output; logos require count, spacing, and removal " +"checks. The main repository provides integrated QEMU tools, but they are " +"not new products of this repository. Record source and binary digests " +"each time and retain source images. Unvalidated VMware and physical " +"hardware must not be marked passed." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 10ba2333..335ec0c6 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "系统调用与 UAPI" msgstr "System Calls and UAPI" @@ -20,42 +23,125 @@ msgid "约定" msgstr "Conventions" msgid "" -"x86_64 使用 Linux syscall 编号与寄存器约定,未知接口返回 ENOSYS。 公开线协议位于 include/uapi,headers_install 由 " -"configs/header-export.list 控制;私有 task、页表和驱动状态不导出为用户 ABI。固定宽度、长度、版本、 边界和负 errno 都是接口契约的一部分。" +"x86_64 使用 Linux syscall 编号与寄存器约定,未知接口返回 ENOSYS。 公开线协议位于 " +"include/uapi,headers_install 由 configs/header-export.list 控制;私有 " +"task、页表和驱动状态不导出为用户 ABI。固定宽度、长度、版本、 边界和负 errno 都是接口契约的一部分。" msgstr "" -"x86_64 uses Linux syscall numbers and register conventions; unknown interfaces return ENOSYS. " -"Public wire formats reside in include/uapi, and configs/header-export.list controls " -"headers_install. Private task, page-table, and driver state is not exported as a user ABI. Fixed " -"widths, lengths, versions, bounds, and negative errno values are all part of the interface " -"contract." +"x86_64 uses Linux syscall numbers and register conventions; unknown " +"interfaces return ENOSYS. Public wire formats reside in include/uapi, and" +" configs/header-export.list controls headers_install. Private task, page-" +"table, and driver state is not exported as a user ABI. Fixed widths, " +"lengths, versions, bounds, and negative errno values are all part of the " +"interface contract." msgid "vDSO 的 ELF 符号版本、辅助向量、vvar 邻接映射及时间读取均有专用测试。 不支持的时钟或条件继续走真实 syscall,不返回猜测值。" msgstr "" -"Dedicated tests cover vDSO ELF symbol versions, auxiliary vectors, adjacent vvar mappings, and " -"time reads. Unsupported clocks or conditions fall back to real syscalls rather than returning " -"guessed values." +"Dedicated tests cover vDSO ELF symbol versions, auxiliary vectors, " +"adjacent vvar mappings, and time reads. Unsupported clocks or conditions " +"fall back to real syscalls rather than returning guessed values." msgid "兼容" msgstr "Compatibility" msgid "" -"公开头保留实际支持的兼容名称,旧用户库不能伪装成新 SONAME。 只实现的接口才可视为可用;头文件存在不能代替完整运行认证。 接口修改同步内核、导出头、用户态包装、消费者和必要验证,不以更新 " -"golden 替代布局或语义审查。" +"公开头保留实际支持的兼容名称,旧用户库不能伪装成新 SONAME。 只实现的接口才可视为可用;头文件存在不能代替完整运行认证。 " +"接口修改同步内核、导出头、用户态包装、消费者和必要验证,不以更新 golden 替代布局或语义审查。" +msgstr "" +"Public headers retain compatibility names that are actually supported; " +"old user libraries must not masquerade as a new SONAME. Only implemented " +"interfaces can be considered available; the presence of a header does not" +" establish full runtime certification. Interface changes must be " +"synchronized across the kernel, exported headers, userspace wrappers, " +"consumers, and necessary validation. Updating golden data does not " +"replace layout or semantic review." + +msgid "timerfd 时钟" +msgstr "timerfd clocks" + +msgid "" +"``timerfd_create()`` 支持 ``CLOCK_REALTIME``、``CLOCK_MONOTONIC`` 和 " +"``CLOCK_BOOTTIME``,接受 ``TFD_CLOEXEC`` 与 ``TFD_NONBLOCK``。绝对截止时间 " +"按创建时选定的时钟解释,周期到期累计可读次数。``timerfd_settime()`` 的 ``it_value`` 为零时解除定时器,包括 " +"``TFD_TIMER_ABSTIME`` 模式。" +msgstr "" +"``timerfd_create()`` supports ``CLOCK_REALTIME``, ``CLOCK_MONOTONIC`` and" +" ``CLOCK_BOOTTIME`` with ``TFD_CLOEXEC`` and ``TFD_NONBLOCK``. Absolute " +"deadlines use the clock selected at creation, and periodic expirations " +"accumulate the readable count. A zero ``it_value`` in " +"``timerfd_settime()`` disarms the timer, including in " +"``TFD_TIMER_ABSTIME`` mode." + +msgid "" +"``CLOCK_BOOTTIME`` 使用现有启动时间时钟,当前与单调时钟共用计时来源。 官方 systemd 的 DHCP " +"重传定时器通过该接口运行。" +msgstr "" +"``CLOCK_BOOTTIME`` uses the existing boot-time clock, which currently " +"shares its time source with the monotonic clock. Official systemd DHCP " +"retransmission timers use this interface." + +msgid "按任务选择 uname 系统名" +msgstr "Selecting the uname system name per task" + +msgid "```` 提供以下不需要特权的 ``prctl`` 扩展:" +msgstr "" +"```` provides the following unprivileged ``prctl`` " +"extensions:" + +msgid "" +"``RELIEFOS_PR_SET_UNAME_LINUX``(``0x52550001``):arg2 为 0 或 1, 关闭或开启当前任务的 " +"Linux 系统名;arg3、arg4、arg5 必须为零。" msgstr "" -"Public headers retain compatibility names that are actually supported; old user libraries must not" -" masquerade as a new SONAME. Only implemented interfaces can be considered available; the presence" -" of a header does not establish full runtime certification. Interface changes must be synchronized" -" across the kernel, exported headers, userspace wrappers, consumers, and necessary validation. " -"Updating golden data does not replace layout or semantic review." +"``RELIEFOS_PR_SET_UNAME_LINUX`` (``0x52550001``): arg2 is 0 or 1 to " +"disable or enable the calling task's Linux system name; arg3, arg4, and " +"arg5 must be zero." + +msgid "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):所有参数为零, 返回当前选择 0 或 1。" +msgstr "" +"``RELIEFOS_PR_GET_UNAME_LINUX`` (``0x52550002``): all arguments must be " +"zero; returns the current selection, 0 or 1." + +msgid "" +"非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone " +"复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 " +"``sysname`` 改为 Linux,其余字段、UTS 命名空间状态及 procfs 均不改变。 使用标准 libc prctl " +"包装或原始系统调用均可;不改变 personality 数值语义。" +msgstr "" +"Invalid values and nonzero reserved arguments return EINVAL without " +"changing state. New tasks use ReliefNT by default. fork, vfork, and clone" +" copy the calling task's selection, and exec preserves it. Other existing" +" tasks are unaffected; threads may also set their selection " +"independently. The switch changes only the ``sysname`` returned by " +"``uname(2)`` to Linux; other fields, UTS namespace state, and procfs are " +"unchanged. Both the standard libc prctl wrapper and raw syscalls are " +"supported. Linux personality values retain their existing meaning." msgid "孤儿进程接管" msgstr "Orphan Process Adoption" -msgid "``PR_SET_CHILD_SUBREAPER`` 的第二个参数为非零时启用,为零时清除。 ``PR_GET_CHILD_SUBREAPER`` 将当前状态(0 或 1)写入第二个参数指向的用户态 ``int``。不需要特权。同一进程内的线程共享该状态;fork 和创建新进程的 clone 不继承该状态,exec 保留。" -msgstr "``PR_SET_CHILD_SUBREAPER`` enables the setting with a nonzero second argument and clears it with zero. ``PR_GET_CHILD_SUBREAPER`` writes the current state (0 or 1) to the user-space ``int`` pointed to by its second argument. No privilege is required. Threads in the process share this state; fork and clone that creates a new process do not inherit it, and exec preserves it." +msgid "" +"``PR_SET_CHILD_SUBREAPER`` 的第二个参数为非零时启用,为零时清除。 ``PR_GET_CHILD_SUBREAPER``" +" 将当前状态(0 或 1)写入第二个参数指向的用户态 ``int``。不需要特权。同一进程内的线程共享该状态;fork 和创建新进程的 clone" +" 不继承该状态,exec 保留。" +msgstr "" +"``PR_SET_CHILD_SUBREAPER`` enables the setting with a nonzero second " +"argument and clears it with zero. ``PR_GET_CHILD_SUBREAPER`` writes the " +"current state (0 or 1) to the user-space ``int`` pointed to by its second" +" argument. No privilege is required. Threads in the process share this " +"state; fork and clone that creates a new process do not inherit it, and " +"exec preserves it." -msgid "创建子进程的线程退出时,若其进程仍有活动线程,则不改变子进程的可见父进程。 最后一个活动线程退出后,最近的仍存活且已启用接管的祖先进程成为新父进程; 没有这种祖先则回退到 PID 1。新父进程可等待被接管的子进程,并按 SIGCHLD 规则 接收退出通知。当前不提供独立的 PID 命名空间。" -msgstr "When the thread that created a child exits, the child's visible parent process is unchanged if that process has other living threads. Once the last living thread exits, the nearest living ancestor with subreaping enabled becomes the new parent, falling back to PID 1 if none exists. The new parent can wait for adopted children and receives exit notifications according to the SIGCHLD rules. Separate PID namespaces are not implemented." +msgid "" +"创建子进程的线程退出时,若其进程仍有活动线程,则不改变子进程的可见父进程。 " +"最后一个活动线程退出后,最近的仍存活且已启用接管的祖先进程成为新父进程; 没有这种祖先则回退到 PID 1。新父进程可等待被接管的子进程,并按 " +"SIGCHLD 规则 接收退出通知。当前不提供独立的 PID 命名空间。" +msgstr "" +"When the thread that created a child exits, the child's visible parent " +"process is unchanged if that process has other living threads. Once the " +"last living thread exits, the nearest living ancestor with subreaping " +"enabled becomes the new parent, falling back to PID 1 if none exists. The" +" new parent can wait for adopted children and receives exit notifications" +" according to the SIGCHLD rules. Separate PID namespaces are not " +"implemented." msgid "创建挂载命名空间" msgstr "Creating a mount namespace" @@ -73,290 +159,434 @@ msgstr "" "without applying any part of the request." msgid "" -"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` 同用,否则返回 " -"``EINVAL``。单独创建挂载命名空间要求当前 用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` " +"同用,否则返回 ``EINVAL``。单独创建挂载命名空间要求当前 用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 " +"``EPERM``。" msgstr "" -"``CLONE_NEWNS`` in ``clone()`` and ``clone3()`` copies the mount tree only for the child. " -"Combining it with ``CLONE_FS`` returns ``EINVAL``. Creating only a mount namespace requires " -"effective ``CAP_SYS_ADMIN`` in the current user namespace and returns ``EPERM`` without that " -"capability." +"``CLONE_NEWNS`` in ``clone()`` and ``clone3()`` copies the mount tree " +"only for the child. Combining it with ``CLONE_FS`` returns ``EINVAL``. " +"Creating only a mount namespace requires effective ``CAP_SYS_ADMIN`` in " +"the current user namespace and returns ``EPERM`` without that capability." msgid "" -"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。新图由创建者的当前用户空间拥有。相同 owner 的快照保留共享传播; 跨 owner 时 " -"shared 转为 slave,只接收原上游事件,并锁定继承的覆盖关系和 只读、nosuid、nodev、noexec、atime 限制。可用 ``MS_REC | " -"MS_PRIVATE`` 使子树停止传播。" +"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。新图由创建者的当前用户空间拥有。相同 owner " +"的快照保留共享传播; 跨 owner 时 shared 转为 slave,只接收原上游事件,并锁定继承的覆盖关系和 " +"只读、nosuid、nodev、noexec、atime 限制。可用 ``MS_REC | MS_PRIVATE`` 使子树停止传播。" msgstr "" -"The original and new mount trees share file contents. Root and cwd retain their original " -"directory identities, and existing open files keep their bindings. The creator's current user" -" namespace owns the new graph. Same-owner snapshots preserve shared propagation. Across " -"owners, shared mounts become slaves that receive events only from the original upstream, and " -"inherited coverage plus readonly, nosuid, nodev, noexec and atime restrictions are locked. " -"``MS_REC | MS_PRIVATE`` stops propagation in the subtree." - -msgid "bind mount" -msgstr "Bind Mounts" - -msgid "``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录与文件绑定。 源和目标必须同为目录或同为非目录,不匹配时返回 ``ENOTDIR``。普通文件、 设备和 FIFO 等非目录对象可以相互作为源或目标。新挂载保留源的实际 inode、 父链和文件系统生命周期,继承源挂载的只读、nosuid、nodev 等策略。 ``/proc/self/mountinfo`` 的 root 字段报告源 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" -msgstr "``mount(source, target, NULL, MS_BIND, NULL)`` supports nonrecursive directory and file binds. The source and destination must both be directories or both be nondirectories, otherwise the call returns ``ENOTDIR``. Nondirectories such as regular files, devices, and FIFOs may be bound to one another. The new mount retains the source inode, parent chain, and filesystem lifetime, and inherits source policies such as read-only, nosuid, and nodev. The root field of ``/proc/self/mountinfo`` reports the source path within its filesystem. Namespace paths, ``..``, and chroot boundaries are computed relative to the new mount. The source filesystem cannot be normally unmounted while the bind remains, and unbinding does not destroy it." - -msgid "``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑,对非目录源则只绑定该对象。 子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" -msgstr "``MS_BIND | MS_REC`` also copies the mount topology beneath a source directory. A nondirectory source binds only that object. The copied mounts have independent mount IDs and policies, but share their source inodes and filesystems. Mounts outside the source directory and unbindable subtrees are skipped. Preparation failure leaves the destination tree and existing mounts unchanged." - -msgid "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" -msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` only changes the policy at the target mountpoint. It does not read the source, type, or filesystem options. The source mount, submounts, and shared filesystem are unchanged. Omitted atime options preserve the existing policy. If the shared filesystem is read-only, clearing the mountpoint's read-only flag does not make it writable." - -msgid "只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。" -msgstr "A readonly transition returns EBUSY without changing policy while any regular file is open for writing on the target mount. References to the same open file description from dup, fork, and file mappings extend that restriction. Writers on other mounts and O_PATH-only handles do not block the transition." - -msgid "文件挂载的目标本身是挂载根,也可独立重新挂载、移动和卸载。移动时源挂载根 与目标必须同为目录或同为非目录,不匹配返回 ``EINVAL``。卸载后目标重新显示 被覆盖的原对象;原 inode、挂载 ID 和访问策略在移动期间保持不变。" -msgstr "The target of a file mount is itself a mount root and can be remounted, moved, or unmounted independently. For a move, the source mount root and target must both be directories or both be nondirectories, otherwise the call returns ``EINVAL``. Unmounting reveals the covered object. The original inode, mount ID, and access policy are preserved across the move." - -msgid "按任务选择 uname 系统名" -msgstr "Selecting the uname system name per task" - -msgid "```` 提供以下不需要特权的 ``prctl`` 扩展:" -msgstr "```` provides the following unprivileged ``prctl`` extensions:" +"The original and new mount trees share file contents. Root and cwd retain" +" their original directory identities, and existing open files keep their " +"bindings. The creator's current user namespace owns the new graph. Same-" +"owner snapshots preserve shared propagation. Across owners, shared mounts" +" become slaves that receive events only from the original upstream, and " +"inherited coverage plus readonly, nosuid, nodev, noexec and atime " +"restrictions are locked. ``MS_REC | MS_PRIVATE`` stops propagation in the" +" subtree." -msgid "``RELIEFOS_PR_SET_UNAME_LINUX``(``0x52550001``):arg2 为 0 或 1, 关闭或开启当前任务的 Linux 系统名;arg3、arg4、arg5 必须为零。" -msgstr "``RELIEFOS_PR_SET_UNAME_LINUX`` (``0x52550001``): arg2 is 0 or 1 to disable or enable the calling task's Linux system name; arg3, arg4, and arg5 must be zero." +msgid "创建用户命名空间" +msgstr "Creating user namespaces" -msgid "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):所有参数为零, 返回当前选择 0 或 1。" -msgstr "``RELIEFOS_PR_GET_UNAME_LINUX`` (``0x52550002``): all arguments must be zero; returns the current selection, 0 or 1." +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUSER`` 为子任务建立独立用户空间, 不能与 " +"``CLONE_FS`` 或 ``CLONE_THREAD`` 组合。``unshare(CLONE_NEWUSER)`` " +"在当前任务建立用户空间并隐含取消文件系统状态共享;允许同时指定 ``CLONE_FS`` 或 ``CLONE_THREAD``,活动多线程组返回 " +"``EINVAL``。" +msgstr "" +"``CLONE_NEWUSER`` in ``clone()`` and ``clone3()`` creates a separate user" +" namespace for the child. Combining it with ``CLONE_FS`` or " +"``CLONE_THREAD`` returns ``EINVAL``. ``unshare(CLONE_NEWUSER)`` creates a" +" user namespace for the caller and implicitly separates filesystem state." +" Explicit ``CLONE_FS`` or ``CLONE_THREAD`` is accepted. A live " +"multithreaded group returns ``EINVAL``." -msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、UTS 命名空间状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" -msgstr "Invalid values and nonzero reserved arguments return EINVAL without changing state. New tasks use ReliefNT by default. fork, vfork, and clone copy the calling task's selection, and exec preserves it. Other existing tasks are unaffected; threads may also set their selection independently. The switch changes only the ``sysname`` returned by ``uname(2)`` to Linux; other fields, UTS namespace state, and procfs are unchanged. Both the standard libc prctl wrapper and raw syscalls are supported. Linux personality values retain their existing meaning." +msgid "" +"创建者的有效 UID 和 GID 必须在其当前用户空间有映射,真实 root 必须等于当前 挂载树的根,否则返回 ``EPERM``。最多嵌套 " +"32 层,超过时返回 ``ENOSPC``。 新空间初始 UID/GID 映射为空,通过 :doc:`procfs` 的映射文件建立映射。" +msgstr "" +"The creator effective UID and GID must be mapped in its current user " +"namespace, and its actual root must equal the mount tree root. Otherwise " +"creation returns ``EPERM``. Nesting is limited to 32 levels, with " +"``ENOSPC`` beyond that limit. New UID/GID maps are empty and can be " +"populated through the mapping files described in :doc:`procfs`." -msgid "挂载传播" -msgstr "Mount propagation" +msgid "" +"内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding " +"能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 " +"能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability " +"与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 组合 ``CLONE_NEWUSER | CLONE_NEWNS`` " +"以新用户空间作为新挂载图 owner, 使用新空间的能力完成挂载图创建;候选空间或快照准备失败均整体回滚。" +msgstr "" +"Internal UID/GID, supplementary groups and no_new_privs are preserved. " +"The new namespace's permitted, effective and bounding capability sets " +"contain all supported capabilities, while inheritable, ambient and " +"securebits are cleared. Capabilities are checked by namespace scope and " +"apply to the namespace and its descendants. Unshare preserves dumpability" +" and the parent-death signal. Preparation failures preserve original " +"credentials, filesystem sharing state and process publication state. " +"Combined ``CLONE_NEWUSER | CLONE_NEWNS`` makes the new user namespace the" +" new mount graph owner and uses its capabilities to create the graph. " +"Failure to prepare either the candidate namespace or the snapshot rolls " +"back the entire operation." -msgid "``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 ``MS_SLAVE`` 使共享挂载离开对等组,并从剩余组成员接收传播;没有剩余成员时 继承原上游组,若无上游则变成 private。对非共享挂载执行 ``MS_SLAVE`` 不改变 其类型。slave 可再设为 shared,保留其上游关系。bind 副本继承源的传播关系。" -msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` creates a peer group for a nonshared target. ``MS_SLAVE`` takes a shared mount out of its peer group so it receives events from the remaining peers. If none remain, it inherits the previous master group or becomes private if it has no master. ``MS_SLAVE`` leaves a nonshared mount's type unchanged. A slave can become shared without losing its master. Bind copies inherit the source's propagation relationships." +msgid "UTS 命名空间与主机名" +msgstr "UTS namespaces and hostnames" -msgid "``MS_PRIVATE`` 清除目标的对等组和上游关系;``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员时,其下游改接到该组 原来的上游组,若无上游则不再接收传播。" -msgstr "``MS_PRIVATE`` removes the target from its peer and master groups. ``MS_UNBINDABLE`` also rejects the target as a bind source and prunes the subtree during recursive bind. When an upstream group loses its last member, its receivers follow that group's previous master or stop receiving events if there is none." +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUTS`` 为子任务复制调用者当前的 hostname 和 NIS" +" domainname,``unshare(CLONE_NEWUTS)`` 为调用任务创建同样的 副本。新空间由调用者当前用户空间拥有,同时指定 " +"``CLONE_NEWUSER`` 时由新建 用户空间拥有。单独创建 UTS 空间要求当前用户空间的 ``CAP_SYS_ADMIN``,缺少 " +"时返回 ``EPERM``。普通 fork 和未指定 ``CLONE_NEWUTS`` 的 clone 共享原 UTS 空间。UTS 创建可与 " +"``CLONE_FS`` 共享并用,单独 unshare UTS 保留文件系统共享。" +msgstr "" +"``CLONE_NEWUTS`` in ``clone()`` and ``clone3()`` copies the caller's " +"current hostname and NIS domainname for the child. " +"``unshare(CLONE_NEWUTS)`` creates the same copy for the caller. The " +"caller's current user namespace owns the new namespace. When combined " +"with ``CLONE_NEWUSER``, the newly created user namespace owns it. " +"Creating only a UTS namespace requires ``CAP_SYS_ADMIN`` in the current " +"user namespace. Missing capability returns ``EPERM``. Ordinary fork and " +"clone without ``CLONE_NEWUTS`` share the original UTS namespace. UTS " +"creation supports sharing with ``CLONE_FS``, and unsharing only UTS " +"preserves filesystem sharing." msgid "" -"``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 " -"``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。对等组号在 VFS 中全局分配。挂载信息报告 " -"``shared:``、``master:`` 或 ``unbindable``。对 slave,``master:`` " -"始终指向即时上游组;如果查看根下可见的最近上游组与该组不同,另报告 ``propagate_from:``。如果没有可见上游组,则不报告 " -"``propagate_from``。" +"``uname()`` 的 ``nodename`` 和 ``domainname`` 来自调用任务的 UTS 空间。 " +"``sethostname()`` 和 ``setdomainname()`` 要求该 UTS 空间 owner 用户空间的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。长度为 0 至 64 字节,超出返回 " +"``EINVAL``。名称按长度复制,保留换行及内嵌 NUL,尾部补零。" msgstr "" -"``MS_REC`` applies the requested type to the target and its existing " -"submounts. It neither merges different submounts into one group nor " -"changes an existing shared group ID. Changing the type requires " -"``CAP_SYS_ADMIN`` and a mount root; it does not alter mount access policy" -" or filesystem state. The VFS assigns peer group IDs globally. Mount info" -" reports ``shared:``, ``master:``, or ``unbindable``. For a " -"slave, ``master:`` always names the immediate upstream group. If the " -"nearest upstream group visible below the viewing root differs from it, " -"``propagate_from:`` names that group. With no visible upstream group," -" ``propagate_from`` is omitted." +"The ``nodename`` and ``domainname`` fields of ``uname()`` come from the " +"calling task's UTS namespace. ``sethostname()`` and ``setdomainname()`` " +"require ``CAP_SYS_ADMIN`` in the user namespace that owns this UTS " +"namespace. Missing capability returns ``EPERM``. Lengths range from 0 to " +"64 bytes. Out-of-range lengths return ``EINVAL``. Names are copied by " +"length, preserving newlines and embedded NUL bytes, with zero padding at " +"the end." msgid "" -"在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 " -"bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 " -"上游副本组。接收方可以位于其他活动挂载命名空间。非共享父挂载下创建的新文件 系统挂载默认是 " -"private。所有副本一起发布;分配失败不留下部分挂载。接收位置 已有挂载时,副本插入已有挂载下方,原可见内容保持不变。" +"``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 的权限为 " +"``0644``,归全局 UID/GID 0 所有。写打开及每次写入要求调用者的全局有效 UID 为 0,缺少时返回 " +"``EACCES``,该判断独立于 fsuid 和 DAC capabilities,执行权限 检查返回 ``EACCES``。写入按当时调用者的" +" UTS 空间立即生效,已经打开 或经 dup、fork 继承的 FD 也使用实际写入者的当前空间。只读 proc 挂载或只读 bind " +"挂载上的写入返回 ``EROFS``。" msgstr "" -"When a mount or bind (including recursive bind) is created under a shared" -" parent, peers and downstream slaves receive copies at the same directory" -" object. Events do not propagate upstream. A receiver whose bind root " -"excludes the directory is skipped, without blocking downstream receivers " -"that contain it. Copies in a receiving peer group share an ID and follow " -"the nearest upstream copy group. Receivers may be in other active mount " -"namespaces. A new filesystem mount under a nonshared parent is private by" -" default. All copies publish together; an allocation failure leaves no " -"partial mounts. A copy received at an already mounted location goes below" -" the existing mount, leaving the visible content unchanged." +"``/proc/sys/kernel/hostname`` and ``/proc/sys/kernel/domainname`` have " +"mode ``0644`` and global UID/GID 0 ownership. Opening for writing and " +"every write require the caller global effective UID to be zero, returning" +" ``EACCES`` otherwise. This check is independent of fsuid and DAC " +"capabilities. Execute access returns ``EACCES``. Writes immediately " +"affect the current writer UTS namespace, including through already-open " +"FDs or descriptors inherited by dup or fork. Writes through a read-only " +"proc or bind mount return ``EROFS``." -msgid "``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, 为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable 挂载的子树移入共享父挂载, 返回 EINVAL。" -msgstr "``MS_MOVE`` into a shared parent preserves the original tree’s mount IDs, existing peer groups, upstream relationships, and held paths. It assigns a separate peer group to each original that is not already shared and copies the entire tree to receivers. Allocation failure leaves locations, groups, and receiver covers unchanged. Moving out of a shared parent, or moving a subtree containing an unbindable mount into one, returns EINVAL." +msgid "" +"这两个 sysctl 读取名称至首个 NUL,并追加换行。写入最多保留 64 字节的名称, 在首个换行或 NUL " +"处停止并补零,成功时报告接受的输入字节数。零长度写入保留 名称。它们与 ``uname()`` 及主机名系统调用访问同一份 UTS 名称。" +msgstr "" +"Reads from these two sysctls return the name up to the first NUL and " +"append a newline. Writes retain at most 64 bytes of the name, stop at the" +" first newline or NUL, and zero-pad the end. Successful writes report the" +" accepted input byte count. A zero-length write preserves the name. These" +" files access the same UTS names as ``uname()`` and the hostname " +"syscalls." msgid "" -"卸载从目标挂载的父挂载传播到对应位置;普通卸载在任一选中的挂载仍有忙引用, " -"或最终后端拒绝卸载时失败,且不移除任何挂载。与事件无关的子挂载通常使该接收 " -"分支保留;但覆盖副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标 " -"子树中的每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方 保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" +"当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 文件 I/O 规则推进。此处尚未实现 Linux strict " +"sysctl 对忽略写入保留偏移的行为。" msgstr "" -"Unmount propagates from the target mount's parent to the corresponding " -"locations. Ordinary unmount fails without detaching anything if any " -"selected mount has a busy reference or a final backend rejects the " -"unmount. Unrelated child mounts normally keep a receiving branch " -"attached, but an overmount at a copy's root stays visible without " -"blocking that copy's removal. Lazy unmount propagates an event for every " -"mount in the target subtree, does not wait for open paths, and also " -"preserves unrelated mounts on receivers. Preserved mounts continue to use" -" the backend even after the initiating mount is detached." +"When the current position is beyond the name end, a write preserves the " +"name and reports the accepted input byte count. The file position still " +"advances under ordinary file I/O rules. Preserving the offset for ignored" +" writes as Linux strict sysctl does remains pending." -msgid "延迟卸载" -msgstr "Lazy Unmount" +msgid "创建网络命名空间" +msgstr "Creating network namespaces" -msgid "``umount2(target, MNT_DETACH)`` 立即移除目标挂载及其子挂载的命名空间连接, 不等待持有者或同步刷盘。新的路径查找会看到原挂载点下的内容,挂载表不再列出 已摘除的挂载。永久的命名空间基准根不可摘除。" -msgstr "``umount2(target, MNT_DETACH)`` immediately disconnects the target and its submounts from the namespace without waiting for references or synchronously flushing data. Fresh lookups see the original contents beneath the mountpoint, and the mount table no longer lists the detached mounts. The permanent namespace anchor cannot be detached." +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNET`` 为子任务建立独立网络空间, " +"``unshare(CLONE_NEWNET)`` 为调用任务建立独立网络空间。单独创建要求当前用户 空间的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。同时指定 ``CLONE_NEWUSER`` " +"时,新网络由候选用户空间拥有。普通 fork 及未指定该标志的 clone 共享原网络。" +msgstr "" +"``CLONE_NEWNET`` in ``clone()`` and ``clone3()`` creates an independent " +"network for the child. ``unshare(CLONE_NEWNET)`` creates one for the " +"caller. Creation on its own requires ``CAP_SYS_ADMIN`` in the current " +"user namespace and returns ``EPERM`` when it is absent. When combined " +"with ``CLONE_NEWUSER``, the candidate user namespace owns the new " +"network. Ordinary fork and clone without this flag share the original " +"network." -msgid "已打开的文件及持有的目录仍可使用,子挂载的独立引用亦有效。从保留的目录开始 查找时不再跨越被摘除的挂载边,``..`` 不越过已摘除的挂载根。当工作目录不再 连接到任务根时,原始 ``getcwd`` 返回以 ``(unreachable)`` 开头的路径。 最后的引用释放后由 VFS 工作队列完成文件系统清理。" -msgstr "Open files and retained directories remain usable, including independent references to submounts. Lookups starting from a retained directory no longer cross the detached mount edges, and ``..`` stops at the detached mount root. If the working directory is no longer connected to the task root, raw ``getcwd`` returns a path prefixed with ``(unreachable)``. The VFS work queue completes filesystem cleanup after the last reference is released." +msgid "" +"新网络仅包含默认 down 的 ``lo``,置为 up 时配置回环地址。接口、路由、IPv6 " +"协议状态和套接字匹配按网络隔离。已有套接字保留创建时的网络,任务切换后也 " +"继续使用该网络。单独创建或切换网络保留文件系统共享状态。组合创建先准备全部 " +"候选状态,准备失败保留原空间、凭据、路径和进程发布状态。内部生命周期和已 实现网络范围见 :doc:`../core-api/mount-" +"namespaces`。" +msgstr "" +"A new network contains only ``lo``, initially down. Bringing it up " +"configures loopback addresses. Interfaces, routes, IPv6 protocol state " +"and socket matching are network-scoped. Existing sockets retain their " +"creating network after task movement. Creating or joining only a network " +"preserves filesystem sharing. Combined creation prepares all candidates " +"first. Preparation failure preserves the original namespaces, " +"credentials, paths and process publication state. See :doc:`../core-api" +"/mount-namespaces` for lifetimes and implemented networking scope." -msgid "glibc 线程与 CPU 状态兼容" -msgstr "glibc thread and CPU-state compatibility" +msgid "加入命名空间" +msgstr "Joining namespaces" msgid "" -"以下行为按 x86_64 Linux ABI 实现。``rseq``、futex PI 操作和扩展信号帧使用 Linux 的接口及布局。POSIX 线程、互斥锁和 CPU " -"时间接口由用户态 libc 提供。" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 " +"``/proc//ns/mnt`` 句柄。调用者需要当前用户空间中有效的 ``CAP_SYS_ADMIN`` 和 " +"``CAP_SYS_CHROOT``,以及目标挂载图 owner 的 ``CAP_SYS_ADMIN``,否则 返回 " +"``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" msgstr "" -"The following behavior implements the x86_64 Linux ABI. ``rseq``, futex PI operations, and " -"extended signal frames use Linux interfaces and layouts. Userspace libc provides the POSIX " -"thread, mutex, and CPU-time interfaces." +"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNS)`` accept a " +"``/proc//ns/mnt`` handle opened for ordinary read access. The caller" +" needs effective ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` in the current " +"user namespace, plus ``CAP_SYS_ADMIN`` in the target mount graph owner, " +"or receives ``EPERM``. Sharing ``CLONE_FS`` state with another task " +"returns ``EINVAL``." -msgid "rseq" -msgstr "rseq" +msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" +msgstr "" +"After switching, root and cwd both point to the visible root of the " +"target mount graph. Existing FDs and umask are preserved. Handles remain " +"usable after the original process exits or changes namespaces." msgid "" -"注册后向用户区域发布实际运行 CPU,线程迁移后在返回用户态前更新 ``cpu_id_start``、``cpu_id``、``node_id`` 和 ``mm_cid``。当前 " -"NUMA 节点为 0, ``mm_cid`` 使用执行 CPU 的逻辑索引。抢占或信号中断活动临界区时,内核验证 描述符、地址范围及 abort 签名,清除 " -"``rseq_cs``,并跳转至 abort 地址。 无效描述符或不可访问的注册区域触发同步 SIGSEGV。" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 " +"``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 " +"``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 " +"``EPERM``。所属空间的祖先无法通过这项权限检查。" msgstr "" -"Registration publishes the actual execution CPU to the userspace area. After thread " -"migration, ``cpu_id_start``, ``cpu_id``, ``node_id``, and ``mm_cid`` are updated before " -"returning to userspace. The current NUMA node is 0, and ``mm_cid`` uses the logical index of " -"the execution CPU. When preemption or a signal interrupts an active critical section, the " -"kernel validates the descriptor, address ranges, and abort signature, clears ``rseq_cs``, and" -" jumps to the abort address. An invalid descriptor or inaccessible registered area triggers a" -" synchronous SIGSEGV." +"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUSER)`` accept an ordinary " +"read-only ``/proc//ns/user`` handle. Joining the current user " +"namespace, having another live thread in the group, or sharing filesystem" +" state with another task returns ``EINVAL``. The caller needs " +"``CAP_SYS_ADMIN`` in the target user namespace or receives ``EPERM``. " +"Ancestors of the current namespace fail this authority check." msgid "" -"``fork`` 复制注册信息,共享地址空间的新线程独立注册,``exec`` 清除注册。 注册保留用户提供的临界区指针及 flags。glibc 可直接读取其 TLS rseq 区域以" -" 实现 ``sched_getcpu``,并可按其自身配置关闭 rseq 使用。" +"成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask " +"保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 " +"securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" msgstr "" -"``fork`` copies the registration. New threads sharing the address space register " -"independently, and ``exec`` clears the registration. Registration preserves the critical-" -"section pointer and flags supplied by userspace. glibc can read its TLS rseq area directly to" -" implement ``sched_getcpu``, and can disable rseq use through its own configuration." +"A successful user namespace join preserves global UID/GID, supplementary " +"groups, no_new_privs, root, cwd and umask. The permitted, effective and " +"bounding sets contain all supported capabilities. Inheritable, ambient " +"and securebits are cleared. An increase in scoped authority clears the " +"parent-death signal and restricts dumpability. Rejection preserves the " +"original credentials and filesystem state." -msgid "PI futex" -msgstr "PI futex" +msgid "" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUTS)`` 接受普通只读的 " +"``/proc//ns/uts`` 句柄。调用者需要当前用户空间和目标 UTS owner 用户 空间两侧的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。切换允许共享 ``CLONE_FS`` 状态,root、cwd 和 umask" +" 保留。句柄持有目标 UTS 空间的引用, 目标进程退出或切换空间后仍可使用。" +msgstr "" +"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUTS)`` accept an ordinary read-" +"only ``/proc//ns/uts`` handle. The caller needs ``CAP_SYS_ADMIN`` in" +" both the current user namespace and the user namespace that owns the " +"target UTS namespace. Missing capability returns ``EPERM``. Switching " +"permits shared ``CLONE_FS`` state and preserves root, cwd and umask. The " +"handle retains the target UTS namespace and remains usable after the " +"target process exits or switches namespaces." msgid "" -"实现 ``FUTEX_LOCK_PI``、``FUTEX_TRYLOCK_PI``、``FUTEX_UNLOCK_PI`` 和 ``FUTEX_LOCK_PI2``,支持私有及共享 " -"futex、竞争交接、死锁检查、超时和 robust owner death。共享等待队列保留物理页,退出时释放等待关系。 普通 futex 与 PI 等待队列混用返回 EINVAL。" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNET)`` 接受普通只读的 " +"``/proc//ns/net`` 句柄。调用者需要当前用户空间和目标网络 owner 用户 空间两侧的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。成功后替换任务网络 引用,root、cwd、umask " +"和已有套接字的创建网络保留。允许共享 ``CLONE_FS``, 句柄继续保留目标网络,权限或类型检查失败时保留调用者原网络。" msgstr "" -"``FUTEX_LOCK_PI``, ``FUTEX_TRYLOCK_PI``, ``FUTEX_UNLOCK_PI``, and ``FUTEX_LOCK_PI2`` are " -"implemented with support for private and shared futexes, contended handoff, deadlock checks, " -"timeouts, and robust owner death. Shared wait queues retain physical pages, and exit releases" -" wait relationships. Mixing ordinary futex and PI wait queues returns EINVAL." +"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNET)`` accept an ordinary " +"readonly ``/proc//ns/net`` handle. The caller needs " +"``CAP_SYS_ADMIN`` in both its current user namespace and the target " +"network owner’s user namespace. Missing authority returns ``EPERM``. " +"Success replaces the task’s network reference while retaining root, cwd, " +"umask and the creating networks of existing sockets. Shared ``CLONE_FS`` " +"is allowed. The handle retains the target network. Failed permission or " +"type checks preserve the caller’s original network." msgid "" -"``LOCK_PI`` 使用绝对 CLOCK_REALTIME 超时。``LOCK_PI2`` 默认使用绝对 CLOCK_MONOTONIC,可通过 " -"``FUTEX_CLOCK_REALTIME`` 选择实时钟。 PI 等待被信号打断后按 Linux 规则重启,包括未设置 ``SA_RESTART`` 的处理器。 " -"已完成的锁所有权交接先结束该次等待,再交付待处理信号。" +"无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 " +"``EINVAL``。当前支持 mount、user、UTS 与 network 句柄,pidfd 和 nsfs 句柄的 bind mount " +"仍未接通。参见 :doc:`../core-api/mount-namespaces`。" msgstr "" -"``LOCK_PI`` uses an absolute CLOCK_REALTIME timeout. ``LOCK_PI2`` defaults to absolute " -"CLOCK_MONOTONIC time and can select the realtime clock with ``FUTEX_CLOCK_REALTIME``. Signal-" -"interrupted PI waits restart according to Linux rules, including handlers without " -"``SA_RESTART``. A completed lock-ownership handoff finishes the wait before delivering " -"pending signals." +"Invalid FDs and ``O_PATH`` FDs return ``EBADF``. Non-nsfs FDs, mismatched" +" types and unsupported types return ``EINVAL``. Mount, user, UTS and " +"network handles are supported. Pidfds and bind mounting nsfs handles " +"remain unimplemented. See :doc:`../core-api/mount-namespaces`." msgid "" -"当前调度器仅接纳 SCHED_OTHER,PI 队列按相同有效优先级的 FIFO 顺序交接。 SCHED_FIFO、SCHED_RR 的实时调度与优先级提升仍需对应调度策略支持。 " -"``FUTEX_WAIT_REQUEUE_PI`` 和 ``FUTEX_CMP_REQUEUE_PI`` 尚未实现,返回 ENOSYS。" +"nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` " +"忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 " +"``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 " +"``CLONE_NEWNS``、``CLONE_NEWUSER``、 ``CLONE_NEWUTS`` 或 ``CLONE_NEWNET``。 " +"``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD " +"可用于元数据查询,但不能 读写、定位或执行 ioctl。" msgstr "" -"The current scheduler accepts only SCHED_OTHER. PI queues hand off ownership in FIFO order " -"among tasks with equal effective priority. Realtime scheduling and priority boosting for " -"SCHED_FIFO and SCHED_RR still require support for those scheduling policies. " -"``FUTEX_WAIT_REQUEUE_PI`` and ``FUTEX_CMP_REQUEUE_PI`` are not yet implemented and return " -"ENOSYS." +"Nsfs handles provide metadata and ioctls. Opening for writing or with " +"``O_TRUNC`` returns ``EPERM``. ``O_PATH`` ignores those flags. Scalar, " +"positioned and vector reads on ordinary FDs return ``EINVAL``, writes " +"return ``EBADF``, and ``lseek()`` with a valid ``whence`` returns " +"``ESPIPE``. ``NS_GET_NSTYPE`` returns ``CLONE_NEWNS``, ``CLONE_NEWUSER``," +" ``CLONE_NEWUTS`` or ``CLONE_NEWNET`` according to the handle. " +"``FIONREAD`` stores zero. Unsupported namespace ioctls return ``ENOTTY``." +" ``O_PATH`` FDs support metadata queries, while read, write, seek and " +"ioctl operations are rejected." -msgid "CPU 时间时钟" -msgstr "CPU-time clocks" +msgid "bind mount" +msgstr "Bind Mounts" msgid "" -"除当前进程和线程的固定 clock ID 外,支持 Linux 编码的进程及线程 CPU 时钟, 供 ``clock_getcpuclockid`` 和 " -"``pthread_getcpuclockid`` 使用。PROF 和 SCHED 报告用户态与内核态累计时间,VIRT 报告用户态时间。进程时钟汇总线程组。 线程目标遵守 Linux " -"的线程组限制。``clock_gettime`` 和 ``clock_getres`` 按各自的目标验证规则处理编码 ID,非法 ID 返回 EINVAL。 当前时间统计及报告分辨率为 " -"10 ms。" +"``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录与文件绑定。 " +"源和目标必须同为目录或同为非目录,不匹配时返回 ``ENOTDIR``。普通文件、 设备和 FIFO " +"等非目录对象可以相互作为源或目标。新挂载保留源的实际 inode、 父链和文件系统生命周期,继承源挂载的只读、nosuid、nodev 等策略。 " +"``/proc/self/mountinfo`` 的 root 字段报告源 在文件系统内的路径;命名空间路径、``..`` 和 chroot " +"边界按新挂载计算。 源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" msgstr "" -"In addition to the fixed clock IDs for the current process and thread, Linux-encoded process " -"and thread CPU clocks are supported for ``clock_getcpuclockid`` and " -"``pthread_getcpuclockid``. PROF and SCHED report accumulated userspace and kernel time, while" -" VIRT reports userspace time. Process clocks aggregate the thread group. Thread targets obey " -"Linux thread-group restrictions. ``clock_gettime`` and ``clock_getres`` handle encoded IDs " -"according to their respective target-validation rules, returning EINVAL for invalid IDs. The " -"current accounting and reported resolution is 10 ms." +"``mount(source, target, NULL, MS_BIND, NULL)`` supports nonrecursive " +"directory and file binds. The source and destination must both be " +"directories or both be nondirectories, otherwise the call returns " +"``ENOTDIR``. Nondirectories such as regular files, devices, and FIFOs may" +" be bound to one another. The new mount retains the source inode, parent " +"chain, and filesystem lifetime, and inherits source policies such as " +"read-only, nosuid, and nodev. The root field of ``/proc/self/mountinfo`` " +"reports the source path within its filesystem. Namespace paths, ``..``, " +"and chroot boundaries are computed relative to the new mount. The source " +"filesystem cannot be normally unmounted while the bind remains, and " +"unbinding does not destroy it." -msgid "XSAVE 与信号帧" -msgstr "XSAVE and signal frames" +msgid "" +"``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑,对非目录源则只绑定该对象。 子挂载在目的树中拥有新的 挂载 ID " +"和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" +msgstr "" +"``MS_BIND | MS_REC`` also copies the mount topology beneath a source " +"directory. A nondirectory source binds only that object. The copied " +"mounts have independent mount IDs and policies, but share their source " +"inodes and filesystems. Mounts outside the source directory and " +"unbindable subtrees are skipped. Preparation failure leaves the " +"destination tree and existing mounts unchanged." msgid "" -"支持 AVX 的 CPU 启用统一的 x87、SSE、AVX XSAVE 状态,任务保存区保持 64 字节对齐,调度切换保留全部启用状态。缺少所需 CPU 能力时使用 512 字节 " -"FXSAVE 状态。当前 XSAVE mask 为 0x7,保存区为 832 字节。" +"bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 " +"owner 的覆盖挂载不能单独移动或卸载,普通与 lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 " +"``EINVAL``, 递归 bind 剪除锁定的 unbindable 子树返回 ``EPERM``。新 bind 根与跨 owner " +"传播的新根允许整树摘除,后代的覆盖锁继续有效。" msgstr "" -"CPUs supporting AVX enable a unified x87, SSE, and AVX XSAVE state. Task save areas remain " -"64-byte aligned, and scheduling switches preserve all enabled state. CPUs lacking the " -"required capabilities use a 512-byte FXSAVE state. The current XSAVE mask is 0x7, with an " -"832-byte save area." +"Bind, bind-remount, move, propagation changes and unmount require " +"``CAP_SYS_ADMIN`` in the mount graph owner. Covering mounts inherited " +"from another owner cannot be moved or unmounted individually. Both " +"ordinary and lazy unmount return ``EINVAL``. A nonrecursive bind that " +"omits locked child mounts returns ``EINVAL``, and a recursive bind that " +"prunes a locked unbindable subtree returns ``EPERM``. New bind roots and " +"newly propagated roots across owners can be detached as a whole tree, " +"with descendant coverage locks preserved." msgid "" -"信号帧包含 Linux 的 ``_fpx_sw_bytes``、XSAVE bitmap 和末尾 magic。 ``rt_sigreturn`` 验证对齐、长度、feature " -"位、保留字段和 MXCSR,并恢复 x87、SSE、YMM 状态。传统 fpstate 及空 fpstate 按其 Linux 语义处理。" +"``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` " +"只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime " +"选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" msgstr "" -"Signal frames contain Linux ``_fpx_sw_bytes``, an XSAVE bitmap, and a trailing magic value. " -"``rt_sigreturn`` validates alignment, lengths, feature bits, reserved fields, and MXCSR, then" -" restores x87, SSE, and YMM state. Legacy fpstate and null fpstate follow their Linux " -"semantics." +"``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` " +"only changes the policy at the target mountpoint. It does not read the " +"source, type, or filesystem options. The source mount, submounts, and " +"shared filesystem are unchanged. Omitted atime options preserve the " +"existing policy. If the shared filesystem is read-only, clearing the " +"mountpoint's read-only flag does not make it writable." -msgid "定向验证" -msgstr "Targeted validation" +msgid "" +"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略。新建 " +"tmpfs/devpts 使用调用者用户空间的文件系统 owner,其他后端使用初始用户空间 owner。共享后端 remount 要求文件系统 " +"owner 的 ``CAP_SYS_ADMIN``,bind 别名保留同一 owner。" +msgstr "" +"Clearing inherited readonly, nosuid, nodev or noexec restrictions, or " +"changing the locked atime selection, returns ``EPERM`` and preserves the " +"attachment policy. New tmpfs/devpts filesystems use the caller’s user " +"namespace as filesystem owner. Other backends use the initial user " +"namespace. Shared-backend remount requires ``CAP_SYS_ADMIN`` in the " +"filesystem owner, which bind aliases also retain." msgid "" -"``tools/test_linux_threads.py`` 覆盖 rseq 生命周期、PI 等待队列与信号恢复。 CPU accounting 和用户态返回路径另有宿主回归测试。 " -"``tools/tests/glibc_runtime_probe.c`` 可由原版 glibc 工具链编译,覆盖 编码 CPU 时钟、rseq 迁移与临界区中断、PI mutex " -"竞争、信号、双时钟超时、 robust 恢复、AVX 调度切换和扩展信号帧。" +"只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork " +"和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。" msgstr "" -"``tools/test_linux_threads.py`` covers the rseq lifecycle, PI wait queues, and signal " -"restoration. CPU accounting and userspace return paths have additional host regression tests." -" ``tools/tests/glibc_runtime_probe.c`` can be compiled with an unmodified glibc toolchain and" -" covers encoded CPU clocks, rseq migration and critical-section interruption, PI mutex " -"contention, signals, timeouts with both clocks, robust recovery, AVX scheduling switches, and" -" extended signal frames." +"A readonly transition returns EBUSY without changing policy while any " +"regular file is open for writing on the target mount. References to the " +"same open file description from dup, fork, and file mappings extend that " +"restriction. Writers on other mounts and O_PATH-only handles do not block" +" the transition." msgid "" -"此次使用未修改的 Debian glibc 2.41,在双核 QEMU/KVM 中分别验证启用 AVX/XSAVE 和关闭 AVX/XSAVE 的 CPU 配置。动态 " -"ELF、pthread/TLS、 ``posix_spawn``、``dlopen/dlsym``、localhost NSS 和普通 robust mutex 也已运行。关闭 AVX " -"时跳过 AVX 专项。该覆盖范围以外的应用及 glibc 版本 仍需各自验证。VMware 验证未完成,实体硬件未验证。" +"文件挂载的目标本身是挂载根,也可独立重新挂载、移动和卸载。移动时源挂载根 与目标必须同为目录或同为非目录,不匹配返回 " +"``EINVAL``。卸载后目标重新显示 被覆盖的原对象;原 inode、挂载 ID 和访问策略在移动期间保持不变。" msgstr "" -"This validation used unmodified Debian glibc 2.41 on dual-core QEMU/KVM with CPU " -"configurations enabling and disabling AVX/XSAVE. Dynamic ELF, pthread/TLS, ``posix_spawn``, " -"``dlopen/dlsym``, localhost NSS, and ordinary robust mutexes were also exercised. AVX-" -"specific checks are skipped when AVX is disabled. Applications and glibc versions outside " -"this coverage still require individual validation. VMware validation is incomplete, and " -"physical hardware has not been validated." +"The target of a file mount is itself a mount root and can be remounted, " +"moved, or unmounted independently. For a move, the source mount root and " +"target must both be directories or both be nondirectories, otherwise the " +"call returns ``EINVAL``. Unmounting reveals the covered object. The " +"original inode, mount ID, and access policy are preserved across the " +"move." msgid "文件系统上下文和游离挂载" msgstr "Filesystem Contexts and Detached Mounts" -msgid "由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 ``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 mountinfo 报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 inode 引用释放且相关缓存回收后,设备号才能重用。" -msgstr "Tmpfs instances created by ``mount(2)`` or a filesystem context, and the initial ``/dev/shm``, do not occupy disk volume slots. Each instance has a distinct anonymous device number; ``stat`` and mountinfo report the same device number, and bind mounts share the original instance's number. The number may be reused only after the last mount and inode references are released and their caches are retired." - msgid "" "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文,捕获打开者的用户 空间作为文件系统 " "owner。``fsopen``、``fsmount`` 和 ``move_mount`` 要求 挂载图 owner 的 " -"``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 " -"``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 " -"``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` " -"要求上下文 owner 的 ``CAP_SYS_ADMIN``,使用已设置 选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 " -"fork 后共享,最后一个引用释放时清理。" +"``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括" +" ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 " +"``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE``" +" 要求上下文 owner 的 ``CAP_SYS_ADMIN``,使用已设置 选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup" +" 或 fork 后共享,最后一个引用释放时清理。" msgstr "" "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` creates a filesystem context and " "captures the opener’s user namespace as filesystem owner. ``fsopen``, " -"``fsmount`` and ``move_mount`` require ``CAP_SYS_ADMIN`` in the mount graph" -" owner. ``FSCONFIG_SET_STRING`` through ``fsconfig`` accepts the existing " -"tmpfs options, including ``size``, ``nr_blocks``, ``nr_inodes``, ``mode``, " -"``uid`` and ``gid``. ``FSCONFIG_SET_FLAG`` accepts ``ro`` and ``rw``. " -"``FSCONFIG_CMD_CREATE`` requires ``CAP_SYS_ADMIN`` in the context owner and" -" creates a filesystem from the configured options. Failed creation can be " -"retried. The open file description owns the context, which is shared by dup" -" or fork and cleaned up when its last reference is released." +"``fsmount`` and ``move_mount`` require ``CAP_SYS_ADMIN`` in the mount " +"graph owner. ``FSCONFIG_SET_STRING`` through ``fsconfig`` accepts the " +"existing tmpfs options, including ``size``, ``nr_blocks``, ``nr_inodes``," +" ``mode``, ``uid`` and ``gid``. ``FSCONFIG_SET_FLAG`` accepts ``ro`` and " +"``rw``. ``FSCONFIG_CMD_CREATE`` requires ``CAP_SYS_ADMIN`` in the context" +" owner and creates a filesystem from the configured options. Failed " +"creation can be retried. The open file description owns the context, " +"which is shared by dup or fork and cleaned up when its last reference is " +"released." + +msgid "" +"tmpfs、devtmpfs、devpts 的 ``uid/gid`` 和 proc 的 ``gid`` 在 mount、remount 或 " +"``FSCONFIG_SET_STRING`` 时按实际写入者的用户空间转换为全局 ID。tmpfs 和 devtmpfs 还要求该 ID " +"能在文件系统 owner 空间表示。十进制输入支持前导零, 未映射、溢出或无效 ID 返回 " +"``EINVAL``。上下文保存转换后的值,CREATE 和 RECONFIGURE 使用这些值;参数写入只要求有效上下文描述符,失败保留原配置。" +msgstr "" +"The ``uid/gid`` options of tmpfs, devtmpfs and devpts, and proc’s ``gid``" +" option, are translated from the actual writer’s user namespace to global" +" IDs during mount, remount or ``FSCONFIG_SET_STRING``. tmpfs and devtmpfs" +" also require the ID to be representable in the filesystem owner’s " +"namespace. Decimal input accepts leading zeros. Unmapped, overflowing or " +"invalid IDs return ``EINVAL``. Contexts retain the translated values for " +"CREATE and RECONFIGURE. Writing parameters requires a valid context " +"descriptor, and failure preserves the previous configuration." + +msgid "" +"由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 " +"``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 mountinfo " +"报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 inode 引用释放且相关缓存回收后,设备号才能重用。" +msgstr "" +"Tmpfs instances created by ``mount(2)`` or a filesystem context, and the " +"initial ``/dev/shm``, do not occupy disk volume slots. Each instance has " +"a distinct anonymous device number; ``stat`` and mountinfo report the " +"same device number, and bind mounts share the original instance's number." +" The number may be reused only after the last mount and inode references " +"are released and their caches are retired." + +msgid "" +"tmpfs 支持最长 255 字节的路径分量。 ``statfs`` 报告该上限, ``getdents`` 和 ``getdents64`` " +"返回完整名称。旧 ReliefOS 目录接口只枚举固定字段 可以容纳的名称。" +msgstr "" +"tmpfs supports pathname components up to 255 bytes. ``statfs`` reports " +"that limit, and ``getdents`` and ``getdents64`` return the full names. " +"The older ReliefOS directory API enumerates names that fit its fixed " +"fields." msgid "" "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 " @@ -367,269 +597,482 @@ msgid "" msgstr "" "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` also creates an independent proc " "context. ``FSCONFIG_CMD_CREATE``, ``fsmount`` and ``move_mount`` then " -"create and attach the mount. ``FSCONFIG_SET_STRING`` accepts the supported " -"``hidepid`` and ``gid`` parameters, and ``fsmount`` supplies mount " -"attributes. Proc’s global PID view retains the initial user namespace as " -"owner. CREATE requires ``CAP_SYS_ADMIN`` in that owner. See :doc:`procfs` " -"for policy and reconfiguration semantics." +"create and attach the mount. ``FSCONFIG_SET_STRING`` accepts the " +"supported ``hidepid`` and ``gid`` parameters, and ``fsmount`` supplies " +"mount attributes. Proc’s global PID view retains the initial user " +"namespace as owner. CREATE requires ``CAP_SYS_ADMIN`` in that owner. See " +":doc:`procfs` for policy and reconfiguration semantics." -msgid "``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 同时保留当前网络空间及其 user owner,并要求该 owner 的 ``CAP_SYS_ADMIN``。CREATE 再次检查捕获的 owner,并使用捕获的网络创建 sysfs 视图。上下文传递或调用者随后切换网络时,这两项捕获继续生效。传统 sysfs mount 同样使用挂载时的网络及其 owner。sysfs 上下文接受通用 ``source``、``ro`` 和 ``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" -msgstr "``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` retains both the current network namespace and its user owner and requires ``CAP_SYS_ADMIN`` in that owner. CREATE checks the captured owner again and creates the sysfs view in the captured network. Passing the context or subsequently switching the caller's network preserves both captures. A legacy sysfs mount likewise uses the network and its owner at mount time. A sysfs context accepts the generic ``source``, ``ro`` and ``rw`` parameters. Unknown private options return ``EINVAL``. CREATE stores readonly policy in the shared backend, RECONFIGURE can update it, and independent readonly attributes from ``fsmount`` continue to restrict their respective mounts. Allocation, descriptor installation and creation failures release candidate references and allow retries." +msgid "" +"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 同时保留当前网络空间及其 user owner,并要求该 owner " +"的 ``CAP_SYS_ADMIN``。CREATE 再次检查捕获的 owner,并使用捕获的网络创建 sysfs " +"视图。上下文传递或调用者随后切换网络时,这两项捕获继续生效。传统 sysfs mount 同样使用挂载时的网络及其 owner。sysfs " +"上下文接受通用 ``source``、``ro`` 和 ``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE " +"的只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` " +"的独立只读属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" +msgstr "" +"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` retains both the current network " +"namespace and its user owner and requires ``CAP_SYS_ADMIN`` in that " +"owner. CREATE checks the captured owner again and creates the sysfs view " +"in the captured network. Passing the context or subsequently switching " +"the caller's network preserves both captures. A legacy sysfs mount " +"likewise uses the network and its owner at mount time. A sysfs context " +"accepts the generic ``source``, ``ro`` and ``rw`` parameters. Unknown " +"private options return ``EINVAL``. CREATE stores readonly policy in the " +"shared backend, RECONFIGURE can update it, and independent readonly " +"attributes from ``fsmount`` continue to restrict their respective mounts." +" Allocation, descriptor installation and creation failures release " +"candidate references and allow retries." + +msgid "" +"sysfs 已公开的 block、PCI 和 DRM 设备 ``uevent`` 控制由 kernel UID 0 所有,模式为 " +"0644,权限检查沿用现有 DAC 与 kernel UID 语义。支持 ``O_TRUNC`` " +"的零长度截断,截断本身不发布事件。写入直接提交事件,action 与可选 UUID 的格式同网络 ``uevent``,见 " +":doc:`ipv6`。非法输入、只读挂载或权限检查失败均不发布事件。" +msgstr "" +"Sysfs exposes writable ``uevent`` controls for its published block, PCI " +"and DRM devices, owned by kernel UID 0 with mode 0644. Permission checks " +"follow existing DAC and kernel UID semantics. Zero-length truncation for " +"``O_TRUNC`` is supported and emits no event. Writes commit events " +"immediately. The action and optional UUID use the same format as network " +"``uevent`` controls, described in :doc:`ipv6`. Invalid input, a readonly " +"mount or a failed permission check emits no event." msgid "" -"tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 " -"字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 " -"``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo " -"中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" +"已注册的块文件系统也支持 ``fsopen``、``fsconfig``、``fsmount`` 和 ``move_mount``。 " +"上下文持有文件系统提供者引用,CREATE 要求初始用户空间的 ``CAP_SYS_ADMIN``。 ``source`` 必须为非空设备路径,在" +" CREATE 时按调用者的实际 root、cwd 和目录搜索权限 解析并跟随符号链接;非块设备返回 ``ENOTBLK``。支持 " +"``ro``、``rw``,vfat/exfat 接受既有 ``uid``、``gid``、``umask``、``fmask`` 和 " +"``dmask`` 参数,ext3 接受 ``data=ordered``。只读设备拒绝可写创建,调用者可在同一上下文设置 ``ro`` 后重试。" +" 创建或描述符安装失败保留配置,释放所有候选挂载;``fsmount`` 的独立挂载属性继续 " +"受共享后端只读状态约束。最后一个上下文引用关闭时释放提供者引用。" +msgstr "" +"Registered block filesystems also support ``fsopen``, ``fsconfig``, " +"``fsmount`` and ``move_mount``. The context retains its filesystem " +"provider, and CREATE requires ``CAP_SYS_ADMIN`` in the initial user " +"namespace. ``source`` must be a nonempty device path resolved at CREATE " +"using the caller's actual root, cwd and directory-search permissions, " +"following symbolic links. A non-block device returns ``ENOTBLK``. ``ro`` " +"and ``rw`` are supported. vfat/exfat accept the existing ``uid``, " +"``gid``, ``umask``, ``fmask`` and ``dmask`` parameters, and ext3 accepts " +"``data=ordered``. A read-only device rejects writable creation. The " +"caller can set ``ro`` on the same context and retry. Creation or " +"descriptor-installation failure preserves the configuration and releases " +"every candidate mount. Independent ``fsmount`` attributes remain subject " +"to the shared backend's read-only state. Closing the final context " +"reference releases the provider reference." + +msgid "" +"tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 " +"255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 " +"``fsmount`` 成功前,设置参数返回 ``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 " +"``source``;重配置不会改变已有挂载在 mountinfo 中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" msgstr "" "The tmpfs, proc and sysfs contexts accept the ``source`` parameter with " -"``FSCONFIG_SET_STRING``. Its value may be empty or contain commas and is limited to 255 " -"bytes. If unset, the source is displayed as ``none``. Setting it twice in the same " -"configuration phase returns ``EINVAL``. Setting parameters after successful creation and " -"before successful ``fsmount`` returns ``EBUSY``. After a successful ``fsmount`` and each " -"successful reconfiguration, a new ``source`` may be set for the next configuration phase. " -"Reconfiguration preserves the existing mount's source in mountinfo. If creation or " -"reconfiguration fails, the pending source remains available for retry." +"``FSCONFIG_SET_STRING``. Its value may be empty or contain commas and is " +"limited to 255 bytes. If unset, the source is displayed as ``none``. " +"Setting it twice in the same configuration phase returns ``EINVAL``. " +"Setting parameters after successful creation and before successful " +"``fsmount`` returns ``EBUSY``. After a successful ``fsmount`` and each " +"successful reconfiguration, a new ``source`` may be set for the next " +"configuration phase. Reconfiguration preserves the existing mount's " +"source in mountinfo. If creation or reconfiguration fails, the pending " +"source remains available for retry." msgid "" "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` " -"以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` " -"重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` " +"以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd``" +" 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` " "更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。RECONFIGURE 要求 实际文件系统 owner 的 " "``CAP_SYS_ADMIN``,上下文传递后也执行此权限检查。" msgstr "" -"``fsmount`` returns an ``O_PATH`` descriptor for the detached mount root. " -"It supports ``FSMOUNT_CLOEXEC`` and readonly, nosuid, nodev, noexec and " -"atime attributes. Files can be accessed relative to the descriptor, and the" -" directory can be reopened through ``/proc/self/fd``. After success, the " -"context accepts new options through ``fsconfig`` and updates the shared " -"filesystem with ``FSCONFIG_CMD_RECONFIGURE``. Failed configuration retains " -"pending options, allowing retry after closing write descriptors that " -"prevent a readonly transition. RECONFIGURE requires ``CAP_SYS_ADMIN`` in " -"the actual filesystem owner, including after the context is transferred." - -msgid "``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 ``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" -msgstr "``move_mount`` attaches the held mount root at a destination and supports the empty-path and symbolic-link flags for both source and destination. Attachment follows the existing propagation rules when the destination mount is shared. ``MOUNT_ATTR_NOSYMFOLLOW`` and ``MOVE_MOUNT_BENEATH`` return ``EINVAL``, allowing callers to use their corresponding compatibility fallbacks." - -msgid "字节范围文件锁" -msgstr "Byte-range File Locks" - -msgid "``fcntl`` 支持 ``F_GETLK``、``F_SETLK``、``F_SETLKW`` 及 ``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW``。POSIX 锁归描述符表 所有,关闭该表中指向同一 inode 的任意描述符会释放其 POSIX 锁。OFD 锁归打开 文件描述所有,dup 和 fork 共享锁,最后一个引用释放时清锁并唤醒等待者。 在途系统调用和传递中的描述符引用也会延长 OFD 锁的生命周期。" -msgstr "``fcntl`` supports ``F_GETLK``, ``F_SETLK``, ``F_SETLKW``, ``F_OFD_GETLK``, ``F_OFD_SETLK`` and ``F_OFD_SETLKW``. POSIX locks belong to the descriptor table. Closing any descriptor for the same inode in that table releases its POSIX locks. OFD locks belong to the open-file description, are shared through dup and fork, and are released with the final reference, waking waiters. In-flight syscalls and descriptors in transit also extend the OFD lock lifetime." - -msgid "两类锁使用同一 inode 和范围冲突规则,包括同一进程持有的不同类型锁。相同 OFD 上的锁可转换、拆分和合并。OFD 请求的 ``l_pid`` 必须为零,否则返回 ``EINVAL``。查询到 OFD 冲突时 ``l_pid`` 为 -1,查询到 POSIX 冲突时为持锁 进程的 PID。``F_OFD_SETLK`` 遇到冲突返回 ``EAGAIN``。" -msgstr "Both lock classes use the same inode and range conflict rules, including different lock classes held by one process. Locks on the same OFD can be converted, split and merged. OFD requests require ``l_pid`` to be zero, otherwise they return ``EINVAL``. A query reports ``l_pid`` as -1 for an OFD conflict and as the owning process PID for a POSIX conflict. ``F_OFD_SETLK`` returns ``EAGAIN`` on conflict." +"``fsmount`` returns an ``O_PATH`` descriptor for the detached mount root." +" It supports ``FSMOUNT_CLOEXEC`` and readonly, nosuid, nodev, noexec and " +"atime attributes. Files can be accessed relative to the descriptor, and " +"the directory can be reopened through ``/proc/self/fd``. After success, " +"the context accepts new options through ``fsconfig`` and updates the " +"shared filesystem with ``FSCONFIG_CMD_RECONFIGURE``. Failed configuration" +" retains pending options, allowing retry after closing write descriptors " +"that prevent a readonly transition. RECONFIGURE requires " +"``CAP_SYS_ADMIN`` in the actual filesystem owner, including after the " +"context is transferred." -msgid "``F_OFD_SETLKW`` 等待锁释放,信号处理沿用现有系统调用中断和重启规则。 OFD 等待不参与 POSIX 锁的死锁检测。六种锁命令均保留实际 OFD,阻塞期间其他 线程关闭并复用数字 FD 后,重试仍使用原打开文件描述。任务退出或调用取消会 移除待处理的锁请求,最终 OFD 引用释放后才能回收其锁。" -msgstr "``F_OFD_SETLKW`` waits for lock release and follows the existing syscall signal interruption and restart rules. OFD waits are excluded from POSIX lock deadlock detection. All six lock commands retain the actual OFD. If another thread closes and reuses the numeric FD while the operation blocks, retries continue using the original open-file description. Task exit or syscall cancellation removes the pending lock request. Held OFD locks survive until the final reference is released." - -msgid "``tools/test_record_locks.py`` 和 ``tools/test_linux_descriptors.py`` 覆盖范围 变更、冲突查询、内存不足回滚、dup/fork、最终引用释放及阻塞期间的 FD 复用。 ``tools/tests/record_locks_runtime_probe.c`` 提供原生用户态运行探针。" -msgstr "``tools/test_record_locks.py`` and ``tools/test_linux_descriptors.py`` cover range changes, conflict queries, allocation-failure rollback, dup/fork, final reference release and FD reuse during blocking. ``tools/tests/record_locks_runtime_probe.c`` provides a native userspace runtime probe." +msgid "" +"``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 " +"目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 " +"``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" +msgstr "" +"``move_mount`` attaches the held mount root at a destination and supports" +" the empty-path and symbolic-link flags for both source and destination. " +"Attachment follows the existing propagation rules when the destination " +"mount is shared. ``MOUNT_ATTR_NOSYMFOLLOW`` and ``MOVE_MOUNT_BENEATH`` " +"return ``EINVAL``, allowing callers to use their corresponding " +"compatibility fallbacks." msgid "statx 挂载标识和根属性" msgstr "statx mount ID and root attribute" -msgid "``statx()`` 成功时在 ``stx_attributes_mask`` 中报告支持 ``STATX_ATTR_MOUNT_ROOT``。只有实际查询到的路径是其所在挂载的根时,才在 ``stx_attributes`` 中设置该位。因此,目录绑定的目标是挂载根,同一 inode 经原挂载查询时不一定是。``AT_EMPTY_PATH`` 使用描述符持有的路径,不重新查找 可见名称;没有路径的匿名描述符不设置该属性。" -msgstr "On success, ``statx()`` reports support for ``STATX_ATTR_MOUNT_ROOT`` in ``stx_attributes_mask``. The bit is set in ``stx_attributes`` only when the actual path being queried is the root of its mount. The target of a directory bind is therefore a mount root, while querying the same inode through the original mount need not report it as one. ``AT_EMPTY_PATH`` uses the path retained by the descriptor rather than looking up a visible name again. Anonymous descriptors without a path do not have this attribute set." - -msgid "实际路径有挂载 ID 时,``statx()`` 在 ``stx_mask`` 中设置 ``STATX_MNT_ID``, 并在 ``stx_mnt_id`` 中返回与 ``/proc/self/mountinfo`` 一致的 ID,即使请求掩码 未指定该位。同一 inode 经不同挂载访问时可得到不同 ID。只有合成元数据、没有 实际挂载路径的对象不报告 ID。不支持 ``STATX_MNT_ID_UNIQUE``,不会将旧式 ID 标记为唯一 ID。输出页争用后重试时沿用同一份已完成的 inode 元数据、ID 和属性。" -msgstr "If the actual path has a mount ID, ``statx()`` sets ``STATX_MNT_ID`` in ``stx_mask`` and returns the ID matching ``/proc/self/mountinfo`` in ``stx_mnt_id``, even if the request mask omits the bit. The same inode can have different IDs when accessed through different mounts. Objects with only synthetic metadata and no actual mount path do not report an ID. ``STATX_MNT_ID_UNIQUE`` is unsupported; legacy IDs are not marked as unique. A retry after output-page contention uses the same completed inode metadata, ID and attributes." +msgid "" +"``statx()`` 成功时在 ``stx_attributes_mask`` 中报告支持 " +"``STATX_ATTR_MOUNT_ROOT``。只有实际查询到的路径是其所在挂载的根时,才在 ``stx_attributes`` " +"中设置该位。因此,目录绑定的目标是挂载根,同一 inode 经原挂载查询时不一定是。``AT_EMPTY_PATH`` " +"使用描述符持有的路径,不重新查找 可见名称;没有路径的匿名描述符不设置该属性。" +msgstr "" +"On success, ``statx()`` reports support for ``STATX_ATTR_MOUNT_ROOT`` in " +"``stx_attributes_mask``. The bit is set in ``stx_attributes`` only when " +"the actual path being queried is the root of its mount. The target of a " +"directory bind is therefore a mount root, while querying the same inode " +"through the original mount need not report it as one. ``AT_EMPTY_PATH`` " +"uses the path retained by the descriptor rather than looking up a visible" +" name again. Anonymous descriptors without a path do not have this " +"attribute set." -msgid "创建用户命名空间" -msgstr "Creating user namespaces" +msgid "" +"实际路径有挂载 ID 时,``statx()`` 在 ``stx_mask`` 中设置 ``STATX_MNT_ID``, 并在 " +"``stx_mnt_id`` 中返回与 ``/proc/self/mountinfo`` 一致的 ID,即使请求掩码 未指定该位。同一 inode" +" 经不同挂载访问时可得到不同 ID。只有合成元数据、没有 实际挂载路径的对象不报告 ID。不支持 " +"``STATX_MNT_ID_UNIQUE``,不会将旧式 ID 标记为唯一 ID。输出页争用后重试时沿用同一份已完成的 inode 元数据、ID" +" 和属性。" +msgstr "" +"If the actual path has a mount ID, ``statx()`` sets ``STATX_MNT_ID`` in " +"``stx_mask`` and returns the ID matching ``/proc/self/mountinfo`` in " +"``stx_mnt_id``, even if the request mask omits the bit. The same inode " +"can have different IDs when accessed through different mounts. Objects " +"with only synthetic metadata and no actual mount path do not report an " +"ID. ``STATX_MNT_ID_UNIQUE`` is unsupported; legacy IDs are not marked as " +"unique. A retry after output-page contention uses the same completed " +"inode metadata, ID and attributes." -msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUSER`` 为子任务建立独立用户空间, 不能与 ``CLONE_FS`` 或 ``CLONE_THREAD`` 组合。``unshare(CLONE_NEWUSER)`` 在当前任务建立用户空间并隐含取消文件系统状态共享;允许同时指定 ``CLONE_FS`` 或 ``CLONE_THREAD``,活动多线程组返回 ``EINVAL``。" -msgstr "``CLONE_NEWUSER`` in ``clone()`` and ``clone3()`` creates a separate user namespace for the child. Combining it with ``CLONE_FS`` or ``CLONE_THREAD`` returns ``EINVAL``. ``unshare(CLONE_NEWUSER)`` creates a user namespace for the caller and implicitly separates filesystem state. Explicit ``CLONE_FS`` or ``CLONE_THREAD`` is accepted. A live multithreaded group returns ``EINVAL``." +msgid "挂载传播" +msgstr "Mount propagation" -msgid "创建者的有效 UID 和 GID 必须在其当前用户空间有映射,真实 root 必须等于当前 挂载树的根,否则返回 ``EPERM``。最多嵌套 32 层,超过时返回 ``ENOSPC``。 新空间初始 UID/GID 映射为空,通过 :doc:`procfs` 的映射文件建立映射。" -msgstr "The creator effective UID and GID must be mapped in its current user namespace, and its actual root must equal the mount tree root. Otherwise creation returns ``EPERM``. Nesting is limited to 32 levels, with ``ENOSPC`` beyond that limit. New UID/GID maps are empty and can be populated through the mapping files described in :doc:`procfs`." +msgid "" +"``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 " +"``MS_SLAVE`` 使共享挂载离开对等组,并从剩余组成员接收传播;没有剩余成员时 继承原上游组,若无上游则变成 " +"private。对非共享挂载执行 ``MS_SLAVE`` 不改变 其类型。slave 可再设为 shared,保留其上游关系。bind " +"副本继承源的传播关系。" +msgstr "" +"``mount(NULL, target, NULL, MS_SHARED, NULL)`` creates a peer group for a" +" nonshared target. ``MS_SLAVE`` takes a shared mount out of its peer " +"group so it receives events from the remaining peers. If none remain, it " +"inherits the previous master group or becomes private if it has no " +"master. ``MS_SLAVE`` leaves a nonshared mount's type unchanged. A slave " +"can become shared without losing its master. Bind copies inherit the " +"source's propagation relationships." msgid "" -"内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding " -"能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 " -"dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 组合 ``CLONE_NEWUSER | CLONE_NEWNS`` 以新用户空间作为新挂载图" -" owner, 使用新空间的能力完成挂载图创建;候选空间或快照准备失败均整体回滚。" +"``MS_PRIVATE`` 清除目标的对等组和上游关系;``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind " +"跳过该子树。上游组失去最后一个成员时,其下游改接到该组 原来的上游组,若无上游则不再接收传播。" msgstr "" -"Internal UID/GID, supplementary groups and no_new_privs are preserved. The new namespace's " -"permitted, effective and bounding capability sets contain all supported capabilities, while " -"inheritable, ambient and securebits are cleared. Capabilities are checked by namespace scope " -"and apply to the namespace and its descendants. Unshare preserves dumpability and the parent-" -"death signal. Preparation failures preserve original credentials, filesystem sharing state " -"and process publication state. Combined ``CLONE_NEWUSER | CLONE_NEWNS`` makes the new user " -"namespace the new mount graph owner and uses its capabilities to create the graph. Failure to" -" prepare either the candidate namespace or the snapshot rolls back the entire operation." +"``MS_PRIVATE`` removes the target from its peer and master groups. " +"``MS_UNBINDABLE`` also rejects the target as a bind source and prunes the" +" subtree during recursive bind. When an upstream group loses its last " +"member, its receivers follow that group's previous master or stop " +"receiving events if there is none." msgid "" -"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` " -"句柄。调用者需要当前用户空间中有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,以及目标挂载图 owner 的 " -"``CAP_SYS_ADMIN``,否则 返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" +"``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 " +"``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。对等组号在 VFS 中全局分配。挂载信息报告 " +"``shared:``、``master:`` 或 ``unbindable``。对 slave,``master:`` " +"始终指向即时上游组;如果查看根下可见的最近上游组与该组不同,另报告 ``propagate_from:``。如果没有可见上游组,则不报告 " +"``propagate_from``。" msgstr "" -"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNS)`` accept a ``/proc//ns/mnt`` handle opened" -" for ordinary read access. The caller needs effective ``CAP_SYS_ADMIN`` and " -"``CAP_SYS_CHROOT`` in the current user namespace, plus ``CAP_SYS_ADMIN`` in the target mount " -"graph owner, or receives ``EPERM``. Sharing ``CLONE_FS`` state with another task returns " -"``EINVAL``." +"``MS_REC`` applies the requested type to the target and its existing " +"submounts. It neither merges different submounts into one group nor " +"changes an existing shared group ID. Changing the type requires " +"``CAP_SYS_ADMIN`` and a mount root; it does not alter mount access policy" +" or filesystem state. The VFS assigns peer group IDs globally. Mount info" +" reports ``shared:``, ``master:``, or ``unbindable``. For a " +"slave, ``master:`` always names the immediate upstream group. If the " +"nearest upstream group visible below the viewing root differs from it, " +"``propagate_from:`` names that group. With no visible upstream group," +" ``propagate_from`` is omitted." -msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" -msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUSER)`` accept an ordinary read-only ``/proc//ns/user`` handle. Joining the current user namespace, having another live thread in the group, or sharing filesystem state with another task returns ``EINVAL``. The caller needs ``CAP_SYS_ADMIN`` in the target user namespace or receives ``EPERM``. Ancestors of the current namespace fail this authority check." +msgid "" +"在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 " +"bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 " +"上游副本组。接收方可以位于其他活动挂载命名空间。非共享父挂载下创建的新文件 系统挂载默认是 " +"private。所有副本一起发布;分配失败不留下部分挂载。接收位置 已有挂载时,副本插入已有挂载下方,原可见内容保持不变。" +msgstr "" +"When a mount or bind (including recursive bind) is created under a shared" +" parent, peers and downstream slaves receive copies at the same directory" +" object. Events do not propagate upstream. A receiver whose bind root " +"excludes the directory is skipped, without blocking downstream receivers " +"that contain it. Copies in a receiving peer group share an ID and follow " +"the nearest upstream copy group. Receivers may be in other active mount " +"namespaces. A new filesystem mount under a nonshared parent is private by" +" default. All copies publish together; an allocation failure leaves no " +"partial mounts. A copy received at an already mounted location goes below" +" the existing mount, leaving the visible content unchanged." -msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" -msgstr "After switching, root and cwd both point to the visible root of the target mount graph. Existing FDs and umask are preserved. Handles remain usable after the original process exits or changes namespaces." +msgid "" +"``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, " +"为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable" +" 挂载的子树移入共享父挂载, 返回 EINVAL。" +msgstr "" +"``MS_MOVE`` into a shared parent preserves the original tree’s mount IDs," +" existing peer groups, upstream relationships, and held paths. It assigns" +" a separate peer group to each original that is not already shared and " +"copies the entire tree to receivers. Allocation failure leaves locations," +" groups, and receiver covers unchanged. Moving out of a shared parent, or" +" moving a subtree containing an unbindable mount into one, returns " +"EINVAL." -msgid "加入命名空间" -msgstr "Joining namespaces" +msgid "" +"卸载从目标挂载的父挂载传播到对应位置;普通卸载在任一选中的挂载仍有忙引用, " +"或最终后端拒绝卸载时失败,且不移除任何挂载。与事件无关的子挂载通常使该接收 " +"分支保留;但覆盖副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标 " +"子树中的每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方 保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" +msgstr "" +"Unmount propagates from the target mount's parent to the corresponding " +"locations. Ordinary unmount fails without detaching anything if any " +"selected mount has a busy reference or a final backend rejects the " +"unmount. Unrelated child mounts normally keep a receiving branch " +"attached, but an overmount at a copy's root stays visible without " +"blocking that copy's removal. Lazy unmount propagates an event for every " +"mount in the target subtree, does not wait for open paths, and also " +"preserves unrelated mounts on receivers. Preserved mounts continue to use" +" the backend even after the initiating mount is detached." -msgid "成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask 保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" -msgstr "A successful user namespace join preserves global UID/GID, supplementary groups, no_new_privs, root, cwd and umask. The permitted, effective and bounding sets contain all supported capabilities. Inheritable, ambient and securebits are cleared. An increase in scoped authority clears the parent-death signal and restricts dumpability. Rejection preserves the original credentials and filesystem state." +msgid "延迟卸载" +msgstr "Lazy Unmount" msgid "" -"bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 owner " -"的覆盖挂载不能单独移动或卸载,普通与 lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 ``EINVAL``, 递归 bind 剪除锁定的 " -"unbindable 子树返回 ``EPERM``。新 bind 根与跨 owner 传播的新根允许整树摘除,后代的覆盖锁继续有效。" +"``umount2(target, MNT_DETACH)`` 立即移除目标挂载及其子挂载的命名空间连接, " +"不等待持有者或同步刷盘。新的路径查找会看到原挂载点下的内容,挂载表不再列出 已摘除的挂载。永久的命名空间基准根不可摘除。" msgstr "" -"Bind, bind-remount, move, propagation changes and unmount require ``CAP_SYS_ADMIN`` in the " -"mount graph owner. Covering mounts inherited from another owner cannot be moved or unmounted " -"individually. Both ordinary and lazy unmount return ``EINVAL``. A nonrecursive bind that " -"omits locked child mounts returns ``EINVAL``, and a recursive bind that prunes a locked " -"unbindable subtree returns ``EPERM``. New bind roots and newly propagated roots across owners" -" can be detached as a whole tree, with descendant coverage locks preserved." +"``umount2(target, MNT_DETACH)`` immediately disconnects the target and " +"its submounts from the namespace without waiting for references or " +"synchronously flushing data. Fresh lookups see the original contents " +"beneath the mountpoint, and the mount table no longer lists the detached " +"mounts. The permanent namespace anchor cannot be detached." msgid "" -"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略。新建 " -"tmpfs/devpts 使用调用者用户空间的文件系统 owner,其他后端使用初始用户空间 owner。共享后端 remount 要求文件系统 " -"owner 的 ``CAP_SYS_ADMIN``,bind 别名保留同一 owner。" +"已打开的文件及持有的目录仍可使用,子挂载的独立引用亦有效。从保留的目录开始 查找时不再跨越被摘除的挂载边,``..`` " +"不越过已摘除的挂载根。当工作目录不再 连接到任务根时,原始 ``getcwd`` 返回以 ``(unreachable)`` 开头的路径。 " +"最后的引用释放后由 VFS 工作队列完成文件系统清理。" msgstr "" -"Clearing inherited readonly, nosuid, nodev or noexec restrictions, or " -"changing the locked atime selection, returns ``EPERM`` and preserves the " -"attachment policy. New tmpfs/devpts filesystems use the caller’s user " -"namespace as filesystem owner. Other backends use the initial user " -"namespace. Shared-backend remount requires ``CAP_SYS_ADMIN`` in the " -"filesystem owner, which bind aliases also retain." +"Open files and retained directories remain usable, including independent " +"references to submounts. Lookups starting from a retained directory no " +"longer cross the detached mount edges, and ``..`` stops at the detached " +"mount root. If the working directory is no longer connected to the task " +"root, raw ``getcwd`` returns a path prefixed with ``(unreachable)``. The " +"VFS work queue completes filesystem cleanup after the last reference is " +"released." + +msgid "字节范围文件锁" +msgstr "Byte-range File Locks" msgid "" -"tmpfs、devtmpfs、devpts 的 ``uid/gid`` 和 proc 的 ``gid`` 在 mount、remount 或 " -"``FSCONFIG_SET_STRING`` 时按实际写入者的用户空间转换为全局 ID。tmpfs 和 devtmpfs 还要求该 ID " -"能在文件系统 owner 空间表示。十进制输入支持前导零, 未映射、溢出或无效 ID 返回 ``EINVAL``。上下文保存转换后的值,CREATE " -"和 RECONFIGURE 使用这些值;参数写入只要求有效上下文描述符,失败保留原配置。" +"``fcntl`` 支持 ``F_GETLK``、``F_SETLK``、``F_SETLKW`` 及 " +"``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW``。POSIX 锁归描述符表 " +"所有,关闭该表中指向同一 inode 的任意描述符会释放其 POSIX 锁。OFD 锁归打开 文件描述所有,dup 和 fork " +"共享锁,最后一个引用释放时清锁并唤醒等待者。 在途系统调用和传递中的描述符引用也会延长 OFD 锁的生命周期。" msgstr "" -"The ``uid/gid`` options of tmpfs, devtmpfs and devpts, and proc’s ``gid`` " -"option, are translated from the actual writer’s user namespace to global " -"IDs during mount, remount or ``FSCONFIG_SET_STRING``. tmpfs and devtmpfs " -"also require the ID to be representable in the filesystem owner’s " -"namespace. Decimal input accepts leading zeros. Unmapped, overflowing or " -"invalid IDs return ``EINVAL``. Contexts retain the translated values for " -"CREATE and RECONFIGURE. Writing parameters requires a valid context " -"descriptor, and failure preserves the previous configuration." +"``fcntl`` supports ``F_GETLK``, ``F_SETLK``, ``F_SETLKW``, " +"``F_OFD_GETLK``, ``F_OFD_SETLK`` and ``F_OFD_SETLKW``. POSIX locks belong" +" to the descriptor table. Closing any descriptor for the same inode in " +"that table releases its POSIX locks. OFD locks belong to the open-file " +"description, are shared through dup and fork, and are released with the " +"final reference, waking waiters. In-flight syscalls and descriptors in " +"transit also extend the OFD lock lifetime." -msgid "UTS 命名空间与主机名" -msgstr "UTS namespaces and hostnames" +msgid "" +"普通文件和 socket 均可使用这些锁命令。socket 按完整的匿名 inode 编号识别, " +"同一端点的别名共享冲突范围,不同端点的锁独立。socket 的 ``SEEK_END`` 基准 为零,``O_PATH`` 描述符返回 " +"``EBADF``。关闭 socket 的 POSIX 锁释放规则与 普通文件相同,OFD 锁持续到最后一个引用释放。" +msgstr "" +"Regular files and sockets support these lock commands. Socket identity " +"uses the complete anonymous inode number. Aliases of one endpoint share " +"conflict ranges, while separate endpoints have independent locks. A " +"socket uses zero as the ``SEEK_END`` base, and an ``O_PATH`` descriptor " +"returns ``EBADF``. Closing a socket follows the regular-file POSIX lock " +"release rules. OFD locks remain until the final reference is released." -msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUTS`` 为子任务复制调用者当前的 hostname 和 NIS domainname,``unshare(CLONE_NEWUTS)`` 为调用任务创建同样的 副本。新空间由调用者当前用户空间拥有,同时指定 ``CLONE_NEWUSER`` 时由新建 用户空间拥有。单独创建 UTS 空间要求当前用户空间的 ``CAP_SYS_ADMIN``,缺少 时返回 ``EPERM``。普通 fork 和未指定 ``CLONE_NEWUTS`` 的 clone 共享原 UTS 空间。UTS 创建可与 ``CLONE_FS`` 共享并用,单独 unshare UTS 保留文件系统共享。" -msgstr "``CLONE_NEWUTS`` in ``clone()`` and ``clone3()`` copies the caller's current hostname and NIS domainname for the child. ``unshare(CLONE_NEWUTS)`` creates the same copy for the caller. The caller's current user namespace owns the new namespace. When combined with ``CLONE_NEWUSER``, the newly created user namespace owns it. Creating only a UTS namespace requires ``CAP_SYS_ADMIN`` in the current user namespace. Missing capability returns ``EPERM``. Ordinary fork and clone without ``CLONE_NEWUTS`` share the original UTS namespace. UTS creation supports sharing with ``CLONE_FS``, and unsharing only UTS preserves filesystem sharing." +msgid "" +"两类锁使用同一 inode 和范围冲突规则,包括同一进程持有的不同类型锁。相同 OFD 上的锁可转换、拆分和合并。OFD 请求的 " +"``l_pid`` 必须为零,否则返回 ``EINVAL``。查询到 OFD 冲突时 ``l_pid`` 为 -1,查询到 POSIX " +"冲突时为持锁 进程的 PID。``F_OFD_SETLK`` 遇到冲突返回 ``EAGAIN``。" +msgstr "" +"Both lock classes use the same inode and range conflict rules, including " +"different lock classes held by one process. Locks on the same OFD can be " +"converted, split and merged. OFD requests require ``l_pid`` to be zero, " +"otherwise they return ``EINVAL``. A query reports ``l_pid`` as -1 for an " +"OFD conflict and as the owning process PID for a POSIX conflict. " +"``F_OFD_SETLK`` returns ``EAGAIN`` on conflict." -msgid "``uname()`` 的 ``nodename`` 和 ``domainname`` 来自调用任务的 UTS 空间。 ``sethostname()`` 和 ``setdomainname()`` 要求该 UTS 空间 owner 用户空间的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。长度为 0 至 64 字节,超出返回 ``EINVAL``。名称按长度复制,保留换行及内嵌 NUL,尾部补零。" -msgstr "The ``nodename`` and ``domainname`` fields of ``uname()`` come from the calling task's UTS namespace. ``sethostname()`` and ``setdomainname()`` require ``CAP_SYS_ADMIN`` in the user namespace that owns this UTS namespace. Missing capability returns ``EPERM``. Lengths range from 0 to 64 bytes. Out-of-range lengths return ``EINVAL``. Names are copied by length, preserving newlines and embedded NUL bytes, with zero padding at the end." +msgid "" +"``F_OFD_SETLKW`` 等待锁释放,信号处理沿用现有系统调用中断和重启规则。 OFD 等待不参与 POSIX " +"锁的死锁检测。六种锁命令均保留实际 OFD,阻塞期间其他 线程关闭并复用数字 FD 后,重试仍使用原打开文件描述。任务退出或调用取消会 " +"移除待处理的锁请求,最终 OFD 引用释放后才能回收其锁。" +msgstr "" +"``F_OFD_SETLKW`` waits for lock release and follows the existing syscall " +"signal interruption and restart rules. OFD waits are excluded from POSIX " +"lock deadlock detection. All six lock commands retain the actual OFD. If " +"another thread closes and reuses the numeric FD while the operation " +"blocks, retries continue using the original open-file description. Task " +"exit or syscall cancellation removes the pending lock request. Held OFD " +"locks survive until the final reference is released." -msgid "``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 的权限为 ``0644``,归全局 UID/GID 0 所有。写打开及每次写入要求调用者的全局有效 UID 为 0,缺少时返回 ``EACCES``,该判断独立于 fsuid 和 DAC capabilities,执行权限 检查返回 ``EACCES``。写入按当时调用者的 UTS 空间立即生效,已经打开 或经 dup、fork 继承的 FD 也使用实际写入者的当前空间。只读 proc 挂载或只读 bind 挂载上的写入返回 ``EROFS``。" -msgstr "``/proc/sys/kernel/hostname`` and ``/proc/sys/kernel/domainname`` have mode ``0644`` and global UID/GID 0 ownership. Opening for writing and every write require the caller global effective UID to be zero, returning ``EACCES`` otherwise. This check is independent of fsuid and DAC capabilities. Execute access returns ``EACCES``. Writes immediately affect the current writer UTS namespace, including through already-open FDs or descriptors inherited by dup or fork. Writes through a read-only proc or bind mount return ``EROFS``." +msgid "" +"``tools/test_record_locks.py`` 和 ``tools/test_linux_descriptors.py`` 覆盖范围" +" 变更、冲突查询、内存不足回滚、dup/fork、最终引用释放及阻塞期间的 FD 复用。 " +"``tools/tests/record_locks_runtime_probe.c`` 提供原生用户态运行探针。" +msgstr "" +"``tools/test_record_locks.py`` and ``tools/test_linux_descriptors.py`` " +"cover range changes, conflict queries, allocation-failure rollback, " +"dup/fork, final reference release and FD reuse during blocking. " +"``tools/tests/record_locks_runtime_probe.c`` provides a native userspace " +"runtime probe." -msgid "这两个 sysctl 读取名称至首个 NUL,并追加换行。写入最多保留 64 字节的名称, 在首个换行或 NUL 处停止并补零,成功时报告接受的输入字节数。零长度写入保留 名称。它们与 ``uname()`` 及主机名系统调用访问同一份 UTS 名称。" -msgstr "Reads from these two sysctls return the name up to the first NUL and append a newline. Writes retain at most 64 bytes of the name, stop at the first newline or NUL, and zero-pad the end. Successful writes report the accepted input byte count. A zero-length write preserves the name. These files access the same UTS names as ``uname()`` and the hostname syscalls." +msgid "glibc 线程与 CPU 状态兼容" +msgstr "glibc thread and CPU-state compatibility" -msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUTS)`` 接受普通只读的 ``/proc//ns/uts`` 句柄。调用者需要当前用户空间和目标 UTS owner 用户 空间两侧的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。切换允许共享 ``CLONE_FS`` 状态,root、cwd 和 umask 保留。句柄持有目标 UTS 空间的引用, 目标进程退出或切换空间后仍可使用。" -msgstr "``setns(fd, 0)`` and ``setns(fd, CLONE_NEWUTS)`` accept an ordinary read-only ``/proc//ns/uts`` handle. The caller needs ``CAP_SYS_ADMIN`` in both the current user namespace and the user namespace that owns the target UTS namespace. Missing capability returns ``EPERM``. Switching permits shared ``CLONE_FS`` state and preserves root, cwd and umask. The handle retains the target UTS namespace and remains usable after the target process exits or switches namespaces." +msgid "" +"以下行为按 x86_64 Linux ABI 实现。``rseq``、futex PI 操作和扩展信号帧使用 Linux 的接口及布局。POSIX" +" 线程、互斥锁和 CPU 时间接口由用户态 libc 提供。" +msgstr "" +"The following behavior implements the x86_64 Linux ABI. ``rseq``, futex " +"PI operations, and extended signal frames use Linux interfaces and " +"layouts. Userspace libc provides the POSIX thread, mutex, and CPU-time " +"interfaces." -msgid "当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 文件 I/O 规则推进。此处尚未实现 Linux strict sysctl 对忽略写入保留偏移的行为。" -msgstr "When the current position is beyond the name end, a write preserves the name and reports the accepted input byte count. The file position still advances under ordinary file I/O rules. Preserving the offset for ignored writes as Linux strict sysctl does remains pending." +msgid "rseq" +msgstr "rseq" -msgid "创建网络命名空间" -msgstr "Creating network namespaces" +msgid "" +"注册后向用户区域发布实际运行 CPU,线程迁移后在返回用户态前更新 ``cpu_id_start``、``cpu_id``、``node_id``" +" 和 ``mm_cid``。当前 NUMA 节点为 0, ``mm_cid`` 使用执行 CPU 的逻辑索引。抢占或信号中断活动临界区时,内核验证" +" 描述符、地址范围及 abort 签名,清除 ``rseq_cs``,并跳转至 abort 地址。 无效描述符或不可访问的注册区域触发同步 " +"SIGSEGV。" +msgstr "" +"Registration publishes the actual execution CPU to the userspace area. " +"After thread migration, ``cpu_id_start``, ``cpu_id``, ``node_id``, and " +"``mm_cid`` are updated before returning to userspace. The current NUMA " +"node is 0, and ``mm_cid`` uses the logical index of the execution CPU. " +"When preemption or a signal interrupts an active critical section, the " +"kernel validates the descriptor, address ranges, and abort signature, " +"clears ``rseq_cs``, and jumps to the abort address. An invalid descriptor" +" or inaccessible registered area triggers a synchronous SIGSEGV." msgid "" -"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNET`` 为子任务建立独立网络空间, " -"``unshare(CLONE_NEWNET)`` 为调用任务建立独立网络空间。单独创建要求当前用户 空间的 " -"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。同时指定 ``CLONE_NEWUSER`` 时,新网络由候选用户空间拥有。普通 " -"fork 及未指定该标志的 clone 共享原网络。" +"``fork`` 复制注册信息,共享地址空间的新线程独立注册,``exec`` 清除注册。 注册保留用户提供的临界区指针及 flags。glibc" +" 可直接读取其 TLS rseq 区域以 实现 ``sched_getcpu``,并可按其自身配置关闭 rseq 使用。" msgstr "" -"``CLONE_NEWNET`` in ``clone()`` and ``clone3()`` creates an independent " -"network for the child. ``unshare(CLONE_NEWNET)`` creates one for the " -"caller. Creation on its own requires ``CAP_SYS_ADMIN`` in the current user " -"namespace and returns ``EPERM`` when it is absent. When combined with " -"``CLONE_NEWUSER``, the candidate user namespace owns the new network. " -"Ordinary fork and clone without this flag share the original network." +"``fork`` copies the registration. New threads sharing the address space " +"register independently, and ``exec`` clears the registration. " +"Registration preserves the critical-section pointer and flags supplied by" +" userspace. glibc can read its TLS rseq area directly to implement " +"``sched_getcpu``, and can disable rseq use through its own configuration." + +msgid "PI futex" +msgstr "PI futex" msgid "" -"新网络仅包含默认 down 的 ``lo``,置为 up 时配置回环地址。接口、路由、IPv6 " -"协议状态和套接字匹配按网络隔离。已有套接字保留创建时的网络,任务切换后也 继续使用该网络。单独创建或切换网络保留文件系统共享状态。组合创建先准备全部 " -"候选状态,准备失败保留原空间、凭据、路径和进程发布状态。内部生命周期和已 实现网络范围见 " -":doc:`../core-api/mount-namespaces`。" +"实现 ``FUTEX_LOCK_PI``、``FUTEX_TRYLOCK_PI``、``FUTEX_UNLOCK_PI`` 和 " +"``FUTEX_LOCK_PI2``,支持私有及共享 futex、竞争交接、死锁检查、超时和 robust owner " +"death。共享等待队列保留物理页,退出时释放等待关系。 普通 futex 与 PI 等待队列混用返回 EINVAL。" msgstr "" -"A new network contains only ``lo``, initially down. Bringing it up " -"configures loopback addresses. Interfaces, routes, IPv6 protocol state and " -"socket matching are network-scoped. Existing sockets retain their creating " -"network after task movement. Creating or joining only a network preserves " -"filesystem sharing. Combined creation prepares all candidates first. " -"Preparation failure preserves the original namespaces, credentials, paths " -"and process publication state. See :doc:`../core-api/mount-namespaces` for " -"lifetimes and implemented networking scope." +"``FUTEX_LOCK_PI``, ``FUTEX_TRYLOCK_PI``, ``FUTEX_UNLOCK_PI``, and " +"``FUTEX_LOCK_PI2`` are implemented with support for private and shared " +"futexes, contended handoff, deadlock checks, timeouts, and robust owner " +"death. Shared wait queues retain physical pages, and exit releases wait " +"relationships. Mixing ordinary futex and PI wait queues returns EINVAL." msgid "" -"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNET)`` 接受普通只读的 " -"``/proc//ns/net`` 句柄。调用者需要当前用户空间和目标网络 owner 用户 空间两侧的 " -"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。成功后替换任务网络 引用,root、cwd、umask " -"和已有套接字的创建网络保留。允许共享 ``CLONE_FS``, 句柄继续保留目标网络,权限或类型检查失败时保留调用者原网络。" +"``LOCK_PI`` 使用绝对 CLOCK_REALTIME 超时。``LOCK_PI2`` 默认使用绝对 " +"CLOCK_MONOTONIC,可通过 ``FUTEX_CLOCK_REALTIME`` 选择实时钟。 PI 等待被信号打断后按 Linux " +"规则重启,包括未设置 ``SA_RESTART`` 的处理器。 已完成的锁所有权交接先结束该次等待,再交付待处理信号。" msgstr "" -"``setns(fd, 0)`` and ``setns(fd, CLONE_NEWNET)`` accept an ordinary " -"readonly ``/proc//ns/net`` handle. The caller needs ``CAP_SYS_ADMIN`` " -"in both its current user namespace and the target network owner’s user " -"namespace. Missing authority returns ``EPERM``. Success replaces the task’s" -" network reference while retaining root, cwd, umask and the creating " -"networks of existing sockets. Shared ``CLONE_FS`` is allowed. The handle " -"retains the target network. Failed permission or type checks preserve the " -"caller’s original network." +"``LOCK_PI`` uses an absolute CLOCK_REALTIME timeout. ``LOCK_PI2`` " +"defaults to absolute CLOCK_MONOTONIC time and can select the realtime " +"clock with ``FUTEX_CLOCK_REALTIME``. Signal-interrupted PI waits restart " +"according to Linux rules, including handlers without ``SA_RESTART``. A " +"completed lock-ownership handoff finishes the wait before delivering " +"pending signals." msgid "" -"无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 " -"``EINVAL``。当前支持 mount、user、UTS 与 network 句柄,pidfd 和 nsfs 句柄的 bind mount " -"仍未接通。参见 :doc:`../core-api/mount-namespaces`。" +"当前调度器仅接纳 SCHED_OTHER,PI 队列按相同有效优先级的 FIFO 顺序交接。 SCHED_FIFO、SCHED_RR " +"的实时调度与优先级提升仍需对应调度策略支持。 ``FUTEX_WAIT_REQUEUE_PI`` 和 " +"``FUTEX_CMP_REQUEUE_PI`` 尚未实现,返回 ENOSYS。" msgstr "" -"Invalid FDs and ``O_PATH`` FDs return ``EBADF``. Non-nsfs FDs, mismatched " -"types and unsupported types return ``EINVAL``. Mount, user, UTS and network" -" handles are supported. Pidfds and bind mounting nsfs handles remain " -"unimplemented. See :doc:`../core-api/mount-namespaces`." +"The current scheduler accepts only SCHED_OTHER. PI queues hand off " +"ownership in FIFO order among tasks with equal effective priority. " +"Realtime scheduling and priority boosting for SCHED_FIFO and SCHED_RR " +"still require support for those scheduling policies. " +"``FUTEX_WAIT_REQUEUE_PI`` and ``FUTEX_CMP_REQUEUE_PI`` are not yet " +"implemented and return ENOSYS." + +msgid "CPU 时间时钟" +msgstr "CPU-time clocks" msgid "" -"nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` " -"忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 " -"``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 " -"``CLONE_NEWNS``、``CLONE_NEWUSER``、 ``CLONE_NEWUTS`` 或 ``CLONE_NEWNET``。 " -"``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD " -"可用于元数据查询,但不能 读写、定位或执行 ioctl。" +"除当前进程和线程的固定 clock ID 外,支持 Linux 编码的进程及线程 CPU 时钟, 供 " +"``clock_getcpuclockid`` 和 ``pthread_getcpuclockid`` 使用。PROF 和 SCHED " +"报告用户态与内核态累计时间,VIRT 报告用户态时间。进程时钟汇总线程组。 线程目标遵守 Linux " +"的线程组限制。``clock_gettime`` 和 ``clock_getres`` 按各自的目标验证规则处理编码 ID,非法 ID 返回 " +"EINVAL。 当前时间统计及报告分辨率为 10 ms。" msgstr "" -"Nsfs handles provide metadata and ioctls. Opening for writing or with " -"``O_TRUNC`` returns ``EPERM``. ``O_PATH`` ignores those flags. Scalar, " -"positioned and vector reads on ordinary FDs return ``EINVAL``, writes " -"return ``EBADF``, and ``lseek()`` with a valid ``whence`` returns " -"``ESPIPE``. ``NS_GET_NSTYPE`` returns ``CLONE_NEWNS``, ``CLONE_NEWUSER``, " -"``CLONE_NEWUTS`` or ``CLONE_NEWNET`` according to the handle. ``FIONREAD`` " -"stores zero. Unsupported namespace ioctls return ``ENOTTY``. ``O_PATH`` FDs" -" support metadata queries, while read, write, seek and ioctl operations are" -" rejected." +"In addition to the fixed clock IDs for the current process and thread, " +"Linux-encoded process and thread CPU clocks are supported for " +"``clock_getcpuclockid`` and ``pthread_getcpuclockid``. PROF and SCHED " +"report accumulated userspace and kernel time, while VIRT reports " +"userspace time. Process clocks aggregate the thread group. Thread targets" +" obey Linux thread-group restrictions. ``clock_gettime`` and " +"``clock_getres`` handle encoded IDs according to their respective target-" +"validation rules, returning EINVAL for invalid IDs. The current " +"accounting and reported resolution is 10 ms." -msgid "普通文件和 socket 均可使用这些锁命令。socket 按完整的匿名 inode 编号识别, 同一端点的别名共享冲突范围,不同端点的锁独立。socket 的 ``SEEK_END`` 基准 为零,``O_PATH`` 描述符返回 ``EBADF``。关闭 socket 的 POSIX 锁释放规则与 普通文件相同,OFD 锁持续到最后一个引用释放。" -msgstr "Regular files and sockets support these lock commands. Socket identity uses the complete anonymous inode number. Aliases of one endpoint share conflict ranges, while separate endpoints have independent locks. A socket uses zero as the ``SEEK_END`` base, and an ``O_PATH`` descriptor returns ``EBADF``. Closing a socket follows the regular-file POSIX lock release rules. OFD locks remain until the final reference is released." +msgid "XSAVE 与信号帧" +msgstr "XSAVE and signal frames" -msgid "sysfs 已公开的 block、PCI 和 DRM 设备 ``uevent`` 控制由 kernel UID 0 所有,模式为 0644,权限检查沿用现有 DAC 与 kernel UID 语义。支持 ``O_TRUNC`` 的零长度截断,截断本身不发布事件。写入直接提交事件,action 与可选 UUID 的格式同网络 ``uevent``,见 :doc:`ipv6`。非法输入、只读挂载或权限检查失败均不发布事件。" -msgstr "Sysfs exposes writable ``uevent`` controls for its published block, PCI and DRM devices, owned by kernel UID 0 with mode 0644. Permission checks follow existing DAC and kernel UID semantics. Zero-length truncation for ``O_TRUNC`` is supported and emits no event. Writes commit events immediately. The action and optional UUID use the same format as network ``uevent`` controls, described in :doc:`ipv6`. Invalid input, a readonly mount or a failed permission check emits no event." +msgid "" +"支持 AVX 的 CPU 启用统一的 x87、SSE、AVX XSAVE 状态,任务保存区保持 64 字节对齐,调度切换保留全部启用状态。缺少所需" +" CPU 能力时使用 512 字节 FXSAVE 状态。当前 XSAVE mask 为 0x7,保存区为 832 字节。" +msgstr "" +"CPUs supporting AVX enable a unified x87, SSE, and AVX XSAVE state. Task " +"save areas remain 64-byte aligned, and scheduling switches preserve all " +"enabled state. CPUs lacking the required capabilities use a 512-byte " +"FXSAVE state. The current XSAVE mask is 0x7, with an 832-byte save area." -msgid "timerfd 时钟" -msgstr "timerfd clocks" +msgid "" +"信号帧包含 Linux 的 ``_fpx_sw_bytes``、XSAVE bitmap 和末尾 magic。 ``rt_sigreturn`` " +"验证对齐、长度、feature 位、保留字段和 MXCSR,并恢复 x87、SSE、YMM 状态。传统 fpstate 及空 fpstate 按其" +" Linux 语义处理。" +msgstr "" +"Signal frames contain Linux ``_fpx_sw_bytes``, an XSAVE bitmap, and a " +"trailing magic value. ``rt_sigreturn`` validates alignment, lengths, " +"feature bits, reserved fields, and MXCSR, then restores x87, SSE, and YMM" +" state. Legacy fpstate and null fpstate follow their Linux semantics." -msgid "``timerfd_create()`` 支持 ``CLOCK_REALTIME``、``CLOCK_MONOTONIC`` 和 ``CLOCK_BOOTTIME``,接受 ``TFD_CLOEXEC`` 与 ``TFD_NONBLOCK``。绝对截止时间 按创建时选定的时钟解释,周期到期累计可读次数。``timerfd_settime()`` 的 ``it_value`` 为零时解除定时器,包括 ``TFD_TIMER_ABSTIME`` 模式。" -msgstr "``timerfd_create()`` supports ``CLOCK_REALTIME``, ``CLOCK_MONOTONIC`` and ``CLOCK_BOOTTIME`` with ``TFD_CLOEXEC`` and ``TFD_NONBLOCK``. Absolute deadlines use the clock selected at creation, and periodic expirations accumulate the readable count. A zero ``it_value`` in ``timerfd_settime()`` disarms the timer, including in ``TFD_TIMER_ABSTIME`` mode." +msgid "定向验证" +msgstr "Targeted validation" -msgid "``CLOCK_BOOTTIME`` 使用现有启动时间时钟,当前与单调时钟共用计时来源。 官方 systemd 的 DHCP 重传定时器通过该接口运行。" -msgstr "``CLOCK_BOOTTIME`` uses the existing boot-time clock, which currently shares its time source with the monotonic clock. Official systemd DHCP retransmission timers use this interface." +msgid "" +"``tools/test_linux_threads.py`` 覆盖 rseq 生命周期、PI 等待队列与信号恢复。 CPU accounting" +" 和用户态返回路径另有宿主回归测试。 ``tools/tests/glibc_runtime_probe.c`` 可由原版 glibc " +"工具链编译,覆盖 编码 CPU 时钟、rseq 迁移与临界区中断、PI mutex 竞争、信号、双时钟超时、 robust 恢复、AVX " +"调度切换和扩展信号帧。" +msgstr "" +"``tools/test_linux_threads.py`` covers the rseq lifecycle, PI wait " +"queues, and signal restoration. CPU accounting and userspace return paths" +" have additional host regression tests. " +"``tools/tests/glibc_runtime_probe.c`` can be compiled with an unmodified " +"glibc toolchain and covers encoded CPU clocks, rseq migration and " +"critical-section interruption, PI mutex contention, signals, timeouts " +"with both clocks, robust recovery, AVX scheduling switches, and extended " +"signal frames." -msgid "已注册的块文件系统也支持 ``fsopen``、``fsconfig``、``fsmount`` 和 ``move_mount``。 上下文持有文件系统提供者引用,CREATE 要求初始用户空间的 ``CAP_SYS_ADMIN``。 ``source`` 必须为非空设备路径,在 CREATE 时按调用者的实际 root、cwd 和目录搜索权限 解析并跟随符号链接;非块设备返回 ``ENOTBLK``。支持 ``ro``、``rw``,vfat/exfat 接受既有 ``uid``、``gid``、``umask``、``fmask`` 和 ``dmask`` 参数,ext3 接受 ``data=ordered``。只读设备拒绝可写创建,调用者可在同一上下文设置 ``ro`` 后重试。 创建或描述符安装失败保留配置,释放所有候选挂载;``fsmount`` 的独立挂载属性继续 受共享后端只读状态约束。最后一个上下文引用关闭时释放提供者引用。" -msgstr "Registered block filesystems also support ``fsopen``, ``fsconfig``, ``fsmount`` and ``move_mount``. The context retains its filesystem provider, and CREATE requires ``CAP_SYS_ADMIN`` in the initial user namespace. ``source`` must be a nonempty device path resolved at CREATE using the caller's actual root, cwd and directory-search permissions, following symbolic links. A non-block device returns ``ENOTBLK``. ``ro`` and ``rw`` are supported. vfat/exfat accept the existing ``uid``, ``gid``, ``umask``, ``fmask`` and ``dmask`` parameters, and ext3 accepts ``data=ordered``. A read-only device rejects writable creation. The caller can set ``ro`` on the same context and retry. Creation or descriptor-installation failure preserves the configuration and releases every candidate mount. Independent ``fsmount`` attributes remain subject to the shared backend's read-only state. Closing the final context reference releases the provider reference." +msgid "" +"此次使用未修改的 Debian glibc 2.41,在双核 QEMU/KVM 中分别验证启用 AVX/XSAVE 和关闭 AVX/XSAVE 的" +" CPU 配置。动态 ELF、pthread/TLS、 ``posix_spawn``、``dlopen/dlsym``、localhost " +"NSS 和普通 robust mutex 也已运行。关闭 AVX 时跳过 AVX 专项。该覆盖范围以外的应用及 glibc 版本 " +"仍需各自验证。VMware 验证未完成,实体硬件未验证。" +msgstr "" +"This validation used unmodified Debian glibc 2.41 on dual-core QEMU/KVM " +"with CPU configurations enabling and disabling AVX/XSAVE. Dynamic ELF, " +"pthread/TLS, ``posix_spawn``, ``dlopen/dlsym``, localhost NSS, and " +"ordinary robust mutexes were also exercised. AVX-specific checks are " +"skipped when AVX is disabled. Applications and glibc versions outside " +"this coverage still require individual validation. VMware validation is " +"incomplete, and physical hardware has not been validated." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/inotify.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/inotify.po index d6f0d1f5..24c953b8 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/inotify.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/inotify.po @@ -4,95 +4,109 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "文件事件通知" msgstr "File Event Notification" msgid "" -"inotify 是 Linux 文件事件接口,不属于 POSIX。应用通过 libc 的 ```` 调用;内核的 ```` 由 " -"``headers_install`` 导出,不需要修改 BusyBox 或 musl。" +"inotify 是 Linux 文件事件接口,不属于 POSIX。应用通过 libc 的 ```` 调用;内核的 " +"```` 由 ``headers_install`` 提供给标准 Linux 用户态。" msgstr "" -"inotify is a Linux file event interface, not part of POSIX. Applications call it through libc's " -"````; the kernel's ```` is exported by ``headers_install``, " -"without requiring BusyBox or musl changes." +"inotify is the Linux file-event interface. Applications use libc's " +"````. ``headers_install`` publishes the kernel's " +"```` for standard Linux userspace." msgid "接口与使用" msgstr "Interface and Usage" msgid "" -"x86-64 syscall 编号与 Linux 一致:``inotify_init`` 为 253, ``inotify_add_watch`` 为 " -"254,``inotify_rm_watch`` 为 255, ``inotify_init1`` 为 294。常见事件循环先以 ``IN_NONBLOCK | IN_CLOEXEC`` " -"创建实例,为目录安装监听,再读取初始列表, 通过 ``poll`` 或 ``epoll`` 等待并读取通知。监听前发生的变化没有历史重放。" +"x86-64 syscall 编号与 Linux 一致:``inotify_init`` 为 253, ``inotify_add_watch``" +" 为 254,``inotify_rm_watch`` 为 255, ``inotify_init1`` 为 294。常见事件循环先以 " +"``IN_NONBLOCK | IN_CLOEXEC`` 创建实例,为目录安装监听,再读取初始列表, 通过 ``poll`` 或 " +"``epoll`` 等待并读取通知。监听前发生的变化没有历史重放。" msgstr "" -"x86-64 syscall numbers match Linux: 253 for ``inotify_init``, 254 for ``inotify_add_watch``, 255 " -"for ``inotify_rm_watch``, and 294 for ``inotify_init1``. A typical event loop creates an instance " -"with ``IN_NONBLOCK | IN_CLOEXEC``, installs directory watches, reads the initial listing, then " -"waits with ``poll`` or ``epoll`` and reads notifications. Changes before watch installation are " -"not replayed." +"x86-64 syscall numbers match Linux: 253 for ``inotify_init``, 254 for " +"``inotify_add_watch``, 255 for ``inotify_rm_watch``, and 294 for " +"``inotify_init1``. A typical event loop creates an instance with " +"``IN_NONBLOCK | IN_CLOEXEC``, installs directory watches, reads the " +"initial listing, then waits with ``poll`` or ``epoll`` and reads " +"notifications. Changes before watch installation are not replayed." msgid "" -"``read`` 返回完整的 ``struct inotify_event`` 记录;固定头为 16 字节, 可选名称包含 NUL 和对齐填充。容量小于下一条记录时返回 ``EINVAL``, " -"不拆分记录;非阻塞空队列返回 ``EAGAIN``。阻塞等待可被信号中断。 ``readv`` 同样以每个 iovec 的容量容纳完整记录,不把一条记录拆到两个 " -"iovec;``FIONREAD`` 返回队列内包含填充的总字节数。" +"``read`` 返回完整的 ``struct inotify_event`` 记录;固定头为 16 字节, 可选名称包含 NUL " +"和对齐填充。容量小于下一条记录时返回 ``EINVAL``, 不拆分记录;非阻塞空队列返回 ``EAGAIN``。阻塞等待可被信号中断。 " +"``readv`` 同样以每个 iovec 的容量容纳完整记录,不把一条记录拆到两个 iovec;``FIONREAD`` " +"返回队列内包含填充的总字节数。" msgstr "" -"``read`` returns complete ``struct inotify_event`` records. The fixed header is 16 bytes; an " -"optional name includes NUL and alignment padding. A buffer smaller than the next record returns " -"``EINVAL`` without splitting the record; an empty nonblocking queue returns ``EAGAIN``. Signals " -"can interrupt blocking waits. ``readv`` likewise fits complete records within each iovec, never " -"splitting a record across two iovecs. ``FIONREAD`` returns total queued bytes including padding." +"``read`` returns complete ``struct inotify_event`` records. The fixed " +"header is 16 bytes; an optional name includes NUL and alignment padding. " +"A buffer smaller than the next record returns ``EINVAL`` without " +"splitting the record; an empty nonblocking queue returns ``EAGAIN``. " +"Signals can interrupt blocking waits. ``readv`` likewise fits complete " +"records within each iovec, never splitting a record across two iovecs. " +"``FIONREAD`` returns total queued bytes including padding." msgid "" "``IN_CREATE``、``IN_DELETE``、``IN_MODIFY``、``IN_ATTRIB``、 " "``IN_OPEN``、``IN_CLOSE_WRITE``、``IN_CLOSE_NOWRITE``、 " -"``IN_ACCESS``、``IN_MOVE_SELF``、``IN_DELETE_SELF`` 及移动父目录事件 来自实际 VFS 或 syscall 完成路径。重命名的 " -"``IN_MOVED_FROM`` 和 ``IN_MOVED_TO`` 共用非零 cookie。目录事件按 Linux 语义附带 ``IN_ISDIR``。 内部页缓存读取和 ``mmap`` " -"缺页不产生用户读取事件。" +"``IN_ACCESS``、``IN_MOVE_SELF``、``IN_DELETE_SELF`` 及移动父目录事件 来自实际 VFS 或 " +"syscall 完成路径。重命名的 ``IN_MOVED_FROM`` 和 ``IN_MOVED_TO`` 共用非零 cookie。目录事件按 " +"Linux 语义附带 ``IN_ISDIR``。 内部页缓存读取和 ``mmap`` 缺页不产生用户读取事件。" msgstr "" -"``IN_CREATE``, ``IN_DELETE``, ``IN_MODIFY``, ``IN_ATTRIB``, ``IN_OPEN``, ``IN_CLOSE_WRITE``, " -"``IN_CLOSE_NOWRITE``, ``IN_ACCESS``, ``IN_MOVE_SELF``, ``IN_DELETE_SELF``, and parent-directory " -"move events originate from actual VFS or syscall completion paths. A rename's ``IN_MOVED_FROM`` " -"and ``IN_MOVED_TO`` share a nonzero cookie. Directory events carry ``IN_ISDIR`` according to Linux" -" semantics. Internal page-cache reads and ``mmap`` faults do not generate user read events." +"``IN_CREATE``, ``IN_DELETE``, ``IN_MODIFY``, ``IN_ATTRIB``, ``IN_OPEN``, " +"``IN_CLOSE_WRITE``, ``IN_CLOSE_NOWRITE``, ``IN_ACCESS``, " +"``IN_MOVE_SELF``, ``IN_DELETE_SELF``, and parent-directory move events " +"originate from actual VFS or syscall completion paths. A rename's " +"``IN_MOVED_FROM`` and ``IN_MOVED_TO`` share a nonzero cookie. Directory " +"events carry ``IN_ISDIR`` according to Linux semantics. Internal page-" +"cache reads and ``mmap`` faults do not generate user read events." msgid "" -"监听以 inode 身份关联:重命名不把监听转移给同名新文件,硬链接指向同一个 监听对象。``IN_MASK_ADD`` 合并掩码,``IN_MASK_CREATE`` 拒绝覆盖已有监听, " -"``IN_ONLYDIR``、``IN_DONT_FOLLOW``、``IN_EXCL_UNLINK`` 和 ``IN_ONESHOT`` 按各自语义处理。删除、显式移除和文件系统终止会生成 " -"``IN_IGNORED``;卸载还生成 ``IN_UNMOUNT``。监听本身不保留路径引用, 不会仅因存在监听而阻止卸载。" +"监听以 inode 身份关联:重命名不把监听转移给同名新文件,硬链接指向同一个 监听对象。``IN_MASK_ADD`` " +"合并掩码,``IN_MASK_CREATE`` 拒绝覆盖已有监听, " +"``IN_ONLYDIR``、``IN_DONT_FOLLOW``、``IN_EXCL_UNLINK`` 和 ``IN_ONESHOT`` " +"按各自语义处理。删除、显式移除和文件系统终止会生成 ``IN_IGNORED``;卸载还生成 " +"``IN_UNMOUNT``。监听本身不保留路径引用, 不会仅因存在监听而阻止卸载。" msgstr "" -"Watches attach to inode identity: renaming does not transfer a watch to a new file with the same " -"name, and hard links refer to the same watched object. ``IN_MASK_ADD`` merges masks, " -"``IN_MASK_CREATE`` refuses to overwrite an existing watch, and ``IN_ONLYDIR``, ``IN_DONT_FOLLOW``," -" ``IN_EXCL_UNLINK``, and ``IN_ONESHOT`` follow their respective semantics. Deletion, explicit " -"removal, and filesystem termination generate ``IN_IGNORED``; unmounting also generates " -"``IN_UNMOUNT``. Watches retain no path references and do not prevent unmounting merely by " -"existing." +"Watches attach to inode identity: renaming does not transfer a watch to a" +" new file with the same name, and hard links refer to the same watched " +"object. ``IN_MASK_ADD`` merges masks, ``IN_MASK_CREATE`` refuses to " +"overwrite an existing watch, and ``IN_ONLYDIR``, ``IN_DONT_FOLLOW``, " +"``IN_EXCL_UNLINK``, and ``IN_ONESHOT`` follow their respective semantics." +" Deletion, explicit removal, and filesystem termination generate " +"``IN_IGNORED``; unmounting also generates ``IN_UNMOUNT``. Watches retain " +"no path references and do not prevent unmounting merely by existing." msgid "" -"``dup``、``fork`` 和传递的描述符共享同一个打开文件描述及队列;最后一个 引用释放时撤销全部监听。``CLOEXEC`` 属于描述符,``O_NONBLOCK`` 属于 " -"共享打开文件描述。对该 fd 写入返回 ``EBADF``,定位读取返回 ``ESPIPE``。 ``lseek`` 遵守 Linux 匿名 inode 的空操作行为,对支持的 whence " -"返回零。" +"``dup``、``fork`` 和传递的描述符共享同一个打开文件描述及队列;最后一个 引用释放时撤销全部监听。``CLOEXEC`` " +"属于描述符,``O_NONBLOCK`` 属于 共享打开文件描述。对该 fd 写入返回 ``EBADF``,定位读取返回 ``ESPIPE``。 " +"``lseek`` 遵守 Linux 匿名 inode 的空操作行为,对支持的 whence 返回零。" msgstr "" -"``dup``, ``fork``, and passed descriptors share one open file description and queue; releasing the" -" last reference removes all watches. ``CLOEXEC`` belongs to the descriptor, while ``O_NONBLOCK`` " -"belongs to the shared open file description. Writing to the fd returns ``EBADF`` and positioned " -"reads return ``ESPIPE``. ``lseek`` follows Linux anonymous-inode no-op behavior and returns zero " -"for supported whence values." +"``dup``, ``fork``, and passed descriptors share one open file description" +" and queue; releasing the last reference removes all watches. ``CLOEXEC``" +" belongs to the descriptor, while ``O_NONBLOCK`` belongs to the shared " +"open file description. Writing to the fd returns ``EBADF`` and positioned" +" reads return ``ESPIPE``. ``lseek`` follows Linux anonymous-inode no-op " +"behavior and returns zero for supported whence values." msgid "容量与恢复" msgstr "Capacity and Recovery" msgid "root 可以通过下列 ``0644`` 控制文件读取或修改非负整数策略,普通用户只读:" msgstr "" -"root can read or change nonnegative integer policies through these ``0644`` control files; other " -"users have read-only access:" +"root can read or change nonnegative integer policies through these " +"``0644`` control files; other users have read-only access:" msgid "``/proc/sys/fs/inotify/`` 下的节点" msgstr "Nodes under ``/proc/sys/fs/inotify/``" @@ -117,56 +131,69 @@ msgstr "``max_queued_events``" msgid "16384;新实例的事件队列容量,已有实例保留创建时的容量。" msgstr "" -"16384; event queue capacity for new instances. Existing instances retain their creation-time " -"capacity." +"16384; event queue capacity for new instances. Existing instances retain " +"their creation-time capacity." msgid "" -"零值可阻止后续资源创建;降低策略不会撤销已有实例或监听。实际内存分配仍可能 失败。通知分配失败或队列已满时,原文件操作保持其结果,队列提供 ``wd == -1`` 的 " -"``IN_Q_OVERFLOW``。应用收到溢出后必须重新扫描,不能继续 把旧缓存当作完整状态。相邻相同的未读事件可合并,通知数量不是操作计数器。" +"零值可阻止后续资源创建;降低策略不会撤销已有实例或监听。实际内存分配仍可能 失败。通知分配失败或队列已满时,原文件操作保持其结果,队列提供 " +"``wd == -1`` 的 ``IN_Q_OVERFLOW``。应用收到溢出后必须重新扫描,不能继续 " +"把旧缓存当作完整状态。相邻相同的未读事件可合并,通知数量不是操作计数器。" msgstr "" -"Zero can prevent subsequent resource creation; lowering policies does not revoke existing " -"instances or watches. Actual memory allocation can still fail. If notification allocation fails or" -" the queue is full, the original file operation retains its result and the queue provides " -"``IN_Q_OVERFLOW`` with ``wd == -1``. Applications must rescan after overflow rather than treating " -"old caches as complete state. Adjacent identical unread events may coalesce; notification counts " -"are not operation counters." +"Zero can prevent subsequent resource creation; lowering policies does not" +" revoke existing instances or watches. Actual memory allocation can still" +" fail. If notification allocation fails or the queue is full, the " +"original file operation retains its result and the queue provides " +"``IN_Q_OVERFLOW`` with ``wd == -1``. Applications must rescan after " +"overflow rather than treating old caches as complete state. Adjacent " +"identical unread events may coalesce; notification counts are not " +"operation counters." msgid "使用边界" msgstr "Usage Boundaries" msgid "" -"目录监听只覆盖直接子项;递归监听需要应用逐目录安装监听并处理竞态。 通知不能作为审计日志或保证每次写入单独报告,也不能保证读取通知时旧文件名 仍指向同一对象。读事件到无效用户地址时按 Linux " -"语义返回 ``EFAULT``, 该次已出队的记录不会恢复;应用应使用有效、足够大的用户缓冲区。" +"目录监听只覆盖直接子项;递归监听需要应用逐目录安装监听并处理竞态。 通知不能作为审计日志或保证每次写入单独报告,也不能保证读取通知时旧文件名 " +"仍指向同一对象。读事件到无效用户地址时按 Linux 语义返回 ``EFAULT``, " +"该次已出队的记录不会恢复;应用应使用有效、足够大的用户缓冲区。" msgstr "" -"Directory watches cover only direct children; recursive monitoring requires applications to " -"install per-directory watches and handle races. Notifications are not audit logs, do not guarantee" -" a separate report for each write, and do not guarantee that an old filename still refers to the " -"same object when read. Reading events to an invalid user address returns ``EFAULT`` with Linux " -"semantics; records already dequeued by that call are not restored. Applications should use valid, " -"sufficiently large user buffers." - -msgid "当前不提供 fanotify、网络文件系统远端事件或可选调试 ioctl ``INOTIFY_IOC_SETNEXTWD`` 的实现;不支持的 ioctl 返回错误,不伪造成功。" +"Directory watches cover only direct children; recursive monitoring " +"requires applications to install per-directory watches and handle races. " +"Notifications are not audit logs, do not guarantee a separate report for " +"each write, and do not guarantee that an old filename still refers to the" +" same object when read. Reading events to an invalid user address returns" +" ``EFAULT`` with Linux semantics; records already dequeued by that call " +"are not restored. Applications should use valid, sufficiently large user " +"buffers." + +msgid "" +"当前不提供 fanotify、网络文件系统远端事件或可选调试 ioctl ``INOTIFY_IOC_SETNEXTWD`` 的实现;不支持的 " +"ioctl 返回错误,不伪造成功。" msgstr "" -"fanotify, remote events on network filesystems, and the optional debug ioctl " -"``INOTIFY_IOC_SETNEXTWD`` are not currently implemented. Unsupported ioctls return errors rather " -"than fabricated success." +"fanotify, remote events on network filesystems, and the optional debug " +"ioctl ``INOTIFY_IOC_SETNEXTWD`` are not currently implemented. " +"Unsupported ioctls return errors rather than fabricated success." msgid "验证入口" msgstr "Validation Entry Points" msgid "" -"``tools/test_inotify_core.py``、``tools/test_inotify_vfs.py``、 ``tools/test_inotify_adapter.py`` 和 " -"``tools/test_inotify_proc.py`` 分别检查 实际队列/监听、VFS 生命周期、用户复制/等待及 sysctl 配额。 " -"``tools/test_inotify_abi.py`` 在 Linux 上运行同一份 ABI 对照探针; ``tools/tests/inotify_runtime_probe.c`` " +"``tools/test_inotify_core.py``、``tools/test_inotify_vfs.py``、 " +"``tools/test_inotify_adapter.py`` 和 ``tools/test_inotify_proc.py`` 分别检查 " +"实际队列/监听、VFS 生命周期、用户复制/等待及 sysctl 配额。 ``tools/test_inotify_abi.py`` 在 " +"Linux 上运行同一份 ABI 对照探针; ``tools/tests/inotify_runtime_probe.c`` " "也可静态编译后在来宾执行。 系统镜像及 Fileman 验证脚本由 ReliefOS 仓库持有。" msgstr "" -"``tools/test_inotify_core.py``, ``tools/test_inotify_vfs.py``, ``tools/test_inotify_adapter.py``, " -"and ``tools/test_inotify_proc.py`` check actual queues/watches, VFS lifecycles, user " -"copying/waiting, and sysctl quotas respectively. ``tools/test_inotify_abi.py`` runs the same ABI " -"comparison probe on Linux; ``tools/tests/inotify_runtime_probe.c`` can also be statically compiled" -" and run in a guest. The ReliefOS repository owns system image and Fileman validation scripts." +"``tools/test_inotify_core.py``, ``tools/test_inotify_vfs.py``, " +"``tools/test_inotify_adapter.py``, and ``tools/test_inotify_proc.py`` " +"check actual queues/watches, VFS lifecycles, user copying/waiting, and " +"sysctl quotas respectively. ``tools/test_inotify_abi.py`` runs the same " +"ABI comparison probe on Linux; ``tools/tests/inotify_runtime_probe.c`` " +"can also be statically compiled and run in a guest. The ReliefOS " +"repository owns system image and Fileman validation scripts." -msgid "接口依据见 `Linux inotify 手册 `_。" +msgid "" +"接口依据见 `Linux inotify 手册 `_。" msgstr "" -"The interface is based on the `Linux inotify manual `_." +"The interface is based on the `Linux inotify manual " +"`_." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po index 24476fc0..9388364c 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: English\n" "Language: en\n" +"Language-Team: English\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Generated-By: Babel 2.18.0\n" msgid "IPv6 双栈" msgstr "IPv6 Dual Stack" @@ -20,242 +23,769 @@ msgid "接口与报文" msgstr "Interfaces and Packets" msgid "" -"IPv6 与 IPv4 共用描述符、等待队列、权限和网络执行上下文。应用使用 Linux x86-64 socket ABI 和 POSIX socket 调用,不需要 ReliefNT 私有 " -"IPv6 调用。 ``AF_INET6`` 为 10,``sockaddr_in6`` 大小为 28 字节;地址和端口为网络字节序, ``sin6_scope_id`` 是接口索引。默认 " -"``lo`` 为 1,首个物理接口 ``eth0`` 为 2。 链路本地地址需要正确的区域标识。" +"IPv6 与 IPv4 共用描述符、等待队列、权限和网络执行上下文。应用使用 Linux x86-64 socket ABI 和 POSIX " +"socket 调用,不需要 ReliefNT 私有 IPv6 调用。 ``AF_INET6`` 为 10,``sockaddr_in6`` 大小为" +" 28 字节;地址和端口为网络字节序, ``sin6_scope_id`` 是接口索引。默认 ``lo`` 为 1,首个物理接口 ``eth0``" +" 为 2。 链路本地地址需要正确的区域标识。" msgstr "" -"IPv6 shares descriptors, wait queues, permissions, and the network execution context with IPv4. " -"Applications use the Linux x86-64 socket ABI and POSIX socket calls, without private ReliefNT IPv6" -" calls. ``AF_INET6`` is 10 and ``sockaddr_in6`` is 28 bytes; addresses and ports use network byte " -"order, and ``sin6_scope_id`` is the interface index. By default ``lo`` is 1 and the first physical interface ``eth0`` is 2. " -"Link-local addresses require the correct scope identifier." +"IPv6 shares descriptors, wait queues, permissions, and the network " +"execution context with IPv4. Applications use the Linux x86-64 socket ABI" +" and POSIX socket calls, without private ReliefNT IPv6 calls. " +"``AF_INET6`` is 10 and ``sockaddr_in6`` is 28 bytes; addresses and ports " +"use network byte order, and ``sin6_scope_id`` is the interface index. By " +"default ``lo`` is 1 and the first physical interface ``eth0`` is 2. Link-" +"local addresses require the correct scope identifier." msgid "" -"实现包含 UDP、TCP、ICMPv6 raw socket、回环、以太网 IPv6、邻居发现、重复地址 检测、路由器发现和 SLAAC。地址与默认路由按通告有效期维护;SLAAC 地址遵守 " -"RFC 4862 的两小时有效期保护。处理 IPv6 校验和、扩展首部、源端分片、乱序重组、 重叠分片拒绝及 Packet Too Big。IPv6 路由器不应在转发路径代替发送端分片。 " +"TCP、UDP 和 raw socket 的 ``bind`` 与 Linux 一样,只对需要区域标识的地址 使用 " +"``sin6_scope_id``。绑定 ``::``、``::1``、IPv4 映射地址或其他无此需求的 地址时忽略该字段,避免将旧版 " +"Netty 留下的未初始化值误判为不存在的网卡。 链路本地地址及接口/链路本地多播地址仍校验接口;``SO_BINDTODEVICE`` " +"指定的设备绑定继续生效。" +msgstr "" +"As on Linux, bind on TCP, UDP, and raw sockets uses sin6_scope_id only " +"for addresses that require a scope identifier. For ::, ::1, IPv4-mapped " +"addresses, and other addresses without that requirement, the field is " +"ignored so that an uninitialized value left by older Netty versions is " +"not mistaken for a nonexistent interface. Link-local addresses and " +"interface-local or link-local multicast addresses still require a valid " +"interface. Device binding selected with SO_BINDTODEVICE remains " +"effective." + +msgid "" +"实现包含 UDP、TCP、ICMPv6 raw socket、回环、以太网 IPv6、邻居发现、重复地址 检测、路由器发现和 " +"SLAAC。地址与默认路由按通告有效期维护;SLAAC 地址遵守 RFC 4862 的两小时有效期保护。处理 IPv6 " +"校验和、扩展首部、源端分片、乱序重组、 重叠分片拒绝及 Packet Too Big。IPv6 路由器不应在转发路径代替发送端分片。 " "协议维护在可调度的任务上下文执行,不在原始中断中进行阻塞内存回收。" msgstr "" -"The implementation includes UDP, TCP, ICMPv6 raw sockets, loopback, Ethernet IPv6, neighbor " -"discovery, duplicate address detection, router discovery, and SLAAC. Addresses and default routes " -"follow advertised lifetimes; SLAAC addresses observe RFC 4862's two-hour valid-lifetime " -"protection. IPv6 checksums, extension headers, source fragmentation, out-of-order reassembly, " -"overlapping-fragment rejection, and Packet Too Big are handled. IPv6 routers must not fragment on " -"the forwarding path on behalf of the sender. Protocol maintenance runs in schedulable task " +"The implementation includes UDP, TCP, ICMPv6 raw sockets, loopback, " +"Ethernet IPv6, neighbor discovery, duplicate address detection, router " +"discovery, and SLAAC. Addresses and default routes follow advertised " +"lifetimes; SLAAC addresses observe RFC 4862's two-hour valid-lifetime " +"protection. IPv6 checksums, extension headers, source fragmentation, out-" +"of-order reassembly, overlapping-fragment rejection, and Packet Too Big " +"are handled. IPv6 routers must not fragment on the forwarding path on " +"behalf of the sender. Protocol maintenance runs in schedulable task " "context, without blocking memory reclaim in raw interrupt context." msgid "" -"IPv6 socket 默认允许 IPv4 映射地址;应用可在绑定前使用 ``IPV6_V6ONLY`` 限制为 IPv6。``IPV6_RECVPKTINFO`` 和 " -"``IPV6_RECVHOPLIMIT`` 提供接收接口、 目标地址和 hop limit,便于实现标准协议客户端。保留 BusyBox 使用的旧版 hop-limit 辅助数据及 raw " -"ICMPv6 checksum/filter 选项。未知选项返回错误, 不能将未实现功能报告为设置成功。" +"IPv6 socket 默认允许 IPv4 映射地址;应用可在绑定前使用 ``IPV6_V6ONLY`` 限制为 " +"IPv6。``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` 提供接收接口、 目标地址和 hop " +"limit,便于实现标准协议客户端。保留 Linux 客户端使用的兼容 hop-limit 辅助数据及 raw ICMPv6 " +"checksum/filter 选项。未知选项返回错误, 不能将未实现功能报告为设置成功。" msgstr "" -"IPv6 sockets allow IPv4-mapped addresses by default; applications can restrict them to IPv6 using " -"``IPV6_V6ONLY`` before binding. ``IPV6_RECVPKTINFO`` and ``IPV6_RECVHOPLIMIT`` provide the " -"receiving interface, destination address, and hop limit for standard protocol clients. Legacy hop-" -"limit ancillary data and raw ICMPv6 checksum/filter options used by BusyBox are retained. Unknown " -"options return errors; unimplemented features must not report successful configuration." +"IPv6 sockets allow IPv4-mapped addresses by default. Applications can set" +" ``IPV6_V6ONLY`` before binding. ``IPV6_RECVPKTINFO`` and " +"``IPV6_RECVHOPLIMIT`` expose the receive interface, destination address " +"and hop limit for protocol clients. Compatible hop-limit ancillary data " +"and raw ICMPv6 checksum and filter options are available. Unknown options" +" return an error." -msgid "配置与观测" -msgstr "Configuration and Observation" +msgid "" +"``SOL_SOCKET`` 的 ``SO_BINDTODEVICE`` 在 socket " +"创建网络中按名称查找设备,空名称解除绑定。``SO_BINDTOIFINDEX`` 的编号为 62,按 ``int`` " +"接口索引设置或查询同一绑定。正索引允许对应尚不存在或已删除的设备,负值返回 ``EINVAL``,0 解除绑定。两者的绑定均属于 socket " +"创建网络,任务切换网络或传递 FD 后继续使用该网络。当前已有非零绑定时,修改绑定或解绑需要创建网络 user owner 的 " +"``CAP_NET_RAW``。" +msgstr "" +"At ``SOL_SOCKET``, ``SO_BINDTODEVICE`` looks up a device by name in the " +"socket's creating network. An empty name clears the binding. " +"``SO_BINDTOIFINDEX``, numbered 62, sets or queries the same binding with " +"an ``int`` interface index. Positive indices may refer to devices that do" +" not yet exist or have been removed. Negative values return ``EINVAL``, " +"and 0 clears the binding. Both bindings belong to the socket's creating " +"network, which remains in use across task network changes and FD passing." +" Changing or clearing a currently nonzero binding requires " +"``CAP_NET_RAW`` in the creating network's user owner." -msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。" -msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 addresses and routes in the network scope retained when the socket was created, including after FD transfer. Changes require ``CAP_NET_ADMIN`` in the network owner's user namespace. ``getifaddrs()`` obtains that scope's IPv6 addresses through standard queries. IPv6 address and route ioctls use the selected network's state and owner authority, with layouts selected by socket family. Interface ioctls on UDP, TCP, raw and AF_PACKET sockets, and address and route ioctls on IPv6 sockets, all use the creating network." +msgid "IPv4 选项与 UDP 消息" +msgstr "IPv4 Options and UDP Messages" -msgid "路由多播发布链路、IPv4/IPv6 地址和路由的新增、变更与删除。IPv4 路由包含直连、默认及显式路由,metric 替换发布旧路由删除和新路由添加。接口删除时,地址通知保留原接口名称与地址。每个网络空间独立维护订阅快照,全部捕获成功后替换,最后一个订阅关闭或退订时释放。快照捕获失败保留旧基线并报告 overrun,后续变更重新捕获。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" -msgstr "Route multicast publishes link, IPv4/IPv6 address and route additions, changes and deletions. IPv4 routes include connected, default and explicit routes. Replacing a metric publishes deletion of the old route and addition of the new one. Address notifications retain the original interface name and address after interface deletion. Each network namespace maintains its own subscription snapshots, replaced after all captures succeed and released when its final subscriber closes or unsubscribes. Capture failure preserves the old baseline and reports an overrun, with capture retried on a subsequent change. Change notifications and overruns follow the network scope. Receive queue overflow reports ``ENOBUFS``, and callers should query again." +msgid "" +"UDP 和 packet socket 的 ``SO_PRIORITY`` 保存有符号整数优先级,默认 0。0 至 6 可直接设置,其他值需要 " +"socket 创建网络 user owner 的 ``CAP_NET_RAW`` 或 " +"``CAP_NET_ADMIN``。用户内存或权限检查失败保留原值。" +msgstr "" +"``SO_PRIORITY`` on UDP and packet sockets stores a signed integer " +"priority, initially 0. Values from 0 through 6 can be set directly. Other" +" values require ``CAP_NET_RAW`` or ``CAP_NET_ADMIN`` in the user owner of" +" the socket creation network. Failed user-memory or permission checks " +"preserve the previous value." -msgid "路由 socket 接受 Linux 6.12 的标准组编号 1 至 36,支持 networkd 和 resolved 的订阅组合。实际事件由对应子系统提供,具体请求仍按其实现能力校验。``sockaddr_nl.nl_groups`` 表示低 32 位,``NETLINK_ADD_MEMBERSHIP`` 和 ``NETLINK_DROP_MEMBERSHIP`` 按组编号操作。初始化后的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 8 字节位图,短缓冲区复制可容纳的完整 32 位字并报告完整所需长度;uevent 位图长度为 4 字节。" -msgstr "Route sockets accept standard Linux 6.12 group numbers 1 through 36, supporting the subscription combinations used by networkd and resolved. The corresponding subsystems supply events, and individual requests are validated against their implemented capabilities. ``sockaddr_nl.nl_groups`` represents the low 32 bits. ``NETLINK_ADD_MEMBERSHIP`` and ``NETLINK_DROP_MEMBERSHIP`` operate on group numbers. After initialization, ``NETLINK_LIST_MEMBERSHIPS`` returns an 8-byte bitmap. Short buffers receive the complete 32-bit words that fit and report the full required length. The uevent bitmap is 4 bytes long." +msgid "" +"UDP 的 ``IP_TOS`` 默认 0,保存输入低八位并写入实际 IPv4 首部,包含 DSCP 和 ECN 位。TOS 变化同时按 " +"Linux 的 TOS 映射更新 socket 优先级。``IP_FREEBIND`` 默认关闭,开启后允许绑定尚未配置的 IPv4 地址及 " +"IPv4 映射地址。端口冲突、设备绑定、特权端口授权和创建网络范围仍按原规则检查,发送继续要求有效路由。" +msgstr "" +"UDP ``IP_TOS`` defaults to 0 and stores the low eight input bits in the " +"actual IPv4 header, including DSCP and ECN. A TOS change also updates " +"socket priority using the Linux TOS mapping. ``IP_FREEBIND`` defaults to " +"disabled and permits binding unconfigured IPv4 and IPv4-mapped addresses " +"when enabled. Port conflicts, device bindings, privileged-port " +"authorization and the creating-network scope retain their checks. Sending" +" still requires a valid route." msgid "" -"多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 " -"每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。" +"UDP 的 ``IP_UNICAST_IF`` 和 ``IPV6_UNICAST_IF`` 分别保存 IPv4 和 IPv6 " +"的默认单播出口。设置与查询均使用网络字节序的 32 位接口索引,设置长度必须恰好为 4 字节。0 清除配置,非零索引必须存在于 socket " +"创建网络中,否则返回 ``EADDRNOTAVAIL``。已有设备绑定时设置非零索引返回 " +"``EINVAL``。普通用户可设置这些选项,接收筛选继续使用原有设备绑定。消息级接口、显式 scope 和设备绑定优先于默认单播出口;IPv4 " +"映射发送使用 IPv4 配置。" msgstr "" -"Multipart query data and the terminating ``NLMSG_DONE`` marker are sent as separate datagrams; the" -" marker retains the request sequence number and receiving port ID. A marker is sent even for an " -"empty query result. Receivers must still iterate all messages in each datagram until the matching " -"``NLMSG_DONE`` or an error arrives." +"UDP ``IP_UNICAST_IF`` and ``IPV6_UNICAST_IF`` retain separate default " +"IPv4 and IPv6 unicast output interfaces. Setters and getters use a " +"network-byte-order 32-bit interface index, and setters require exactly " +"four bytes. Zero clears the setting. A nonzero index must exist in the " +"socket's creating network, otherwise the setter returns " +"``EADDRNOTAVAIL``. Setting a nonzero index on a device-bound socket " +"returns ``EINVAL``. Ordinary users can set these options. Receive " +"filtering continues to use the existing device binding. Per-message " +"interfaces, explicit scope and device binding take precedence over the " +"default unicast interface. IPv4-mapped output uses the IPv4 setting." -msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP、TCP 和 raw 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。" -msgstr "``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` use Linux text layouts. Address scope encoding differs from rtnetlink scope values. Address, route, UDP, TCP and raw tables follow the caller's current network scope. Snapshots copy internal state and retain only copies across waits." +msgid "" +"UDP 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 返回 realtime 微秒时间戳,支持原生 " +"IPv4、IPv6 和 IPv4 映射报文。启用时在入队采样,接收前才启用则在首次接收时采样。``MSG_PEEK`` " +"和切换时间戳格式保留已有样本,关闭选项后停止交付时间戳。时间戳通过 ``SOL_SOCKET`` 辅助消息返回,可与 IP packet info" +" 和 TTL 同时使用。输出内存准备失败保留队列,控制区不足设置 ``MSG_CTRUNC``。" +msgstr "" +"UDP ``SO_TIMESTAMP_OLD`` and ``SO_TIMESTAMP_NEW`` return realtime " +"microsecond timestamps for native IPv4, IPv6 and IPv4-mapped datagrams. " +"Enabled sockets sample at enqueue. Enabling after arrival samples at the " +"first receive. ``MSG_PEEK`` and timestamp-format changes retain the " +"sample. Disabling stops timestamp delivery. ``SOL_SOCKET`` ancillary " +"messages carry timestamps alongside IP packet information and TTL. " +"Output-memory preparation failure preserves the queue, and insufficient " +"control space sets ``MSG_CTRUNC``." -msgid "范围与标准" -msgstr "Scope and Standards" +msgid "" +"UDP 和 TCP 的 IPv4 及 IPv4 映射通信支持 ``SOL_IP`` 的 " +"``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL`` 和 ``IP_MTU_DISCOVER``。TTL 默认 " +"64,接受 1 至 255,设置 -1 恢复默认值。接收辅助信息选项默认关闭。MTU discovery 默认 " +"``IP_PMTUDISC_WANT``,接受从 ``IP_PMTUDISC_DONT`` 到 ``IP_PMTUDISC_OMIT`` 的 0 " +"至 5。当前 IPv4 输出仅在 ``DO`` 或 ``PROBE`` 时设置 DF,其余模式清除 " +"DF。这些模式的设置与查询支持有上述报文效果,完整 IPv4 PMTU 探测与分片仍有实现边界。" +msgstr "" +"IPv4 and IPv4-mapped communication on UDP and TCP supports the ``SOL_IP``" +" options ``IP_TTL``, ``IP_PKTINFO``, ``IP_RECVTTL`` and " +"``IP_MTU_DISCOVER``. TTL defaults to 64, accepts 1 through 255, and " +"resets to the default with -1. Receive ancillary information options " +"default to disabled. MTU discovery defaults to ``IP_PMTUDISC_WANT`` and " +"accepts values 0 through 5, from ``IP_PMTUDISC_DONT`` to " +"``IP_PMTUDISC_OMIT``. Current IPv4 output sets DF only for ``DO`` or " +"``PROBE`` and clears it for the other modes. Setting and querying these " +"modes has the packet effects described here. Full IPv4 PMTU discovery and" +" fragmentation remain subject to implementation limits." msgid "" -"这是 IPv6 主机实现,不提供 IPv6 路由转发、IPsec、MLDv2 源特定组播过滤或 Redirect 路由更新。DNS 策略、RDNSS 和 DHCPv6 客户端属于用户态。接收和发送" -" 缓存有资源上限,资源不足返回错误;并不宣称覆盖 Linux 的全部网络功能或全部 IPv6 扩展。" +"TCP 被动建立的子连接继承上述四项 IPv4 选项,IPv6 hop limit 与 PMTU 配置独立保存。TCP 上的 " +"``IP_PKTINFO`` 和 ``IP_RECVTTL`` 保存配置并由子连接继承,接收辅助数据由 UDP 路径提供。" msgstr "" -"This is an IPv6 host implementation. It does not provide IPv6 routing/forwarding, IPsec, MLDv2 " -"source-specific multicast filtering, or Redirect route updates. DNS policy, RDNSS, and DHCPv6 " -"clients belong in userspace. Receive and send buffers have resource limits, and resource " -"exhaustion returns errors. No claim is made to cover all Linux networking features or all IPv6 " -"extensions." +"Passively established TCP child connections inherit all four IPv4 " +"options. IPv6 hop limit and PMTU configuration are stored independently. " +"On TCP, ``IP_PKTINFO`` and ``IP_RECVTTL`` retain configuration that child" +" connections inherit. Receive ancillary data is provided by the UDP path." msgid "" -"依据 RFC 8200、4291、4443、4861、4862、8201、3493、3542 以及 Linux ``ipv6(7)``、``rtnetlink(7)``。POSIX " -"规定应用接口,线上 IPv6 协议细节由 相应 IETF 标准规定。宿主定向测试与完整系统 VM 测试是不同证据;VMware 和 真实硬件结果不能由 QEMU 结果替代。" +"TCP IPv6 socket 支持 ``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` " +"的独立状态,默认关闭,任意非零设置值查询为 1,零查询为 0。原生 IPv6 和 IPv4 映射的被动子连接继承这两项,建立后各自保存状态。TCP" +" 保存这些接收配置,当前 ``recvmsg()`` 仅交付流数据,UDP 提供上述接收辅助数据。" msgstr "" -"Based on RFC 8200, 4291, 4443, 4861, 4862, 8201, 3493, and 3542, and Linux ``ipv6(7)`` and " -"``rtnetlink(7)``. POSIX specifies application interfaces; the corresponding IETF standards specify" -" IPv6 wire protocol details. Targeted host tests and full-system VM tests provide different " -"evidence; QEMU results cannot replace VMware or physical hardware results." +"TCP IPv6 sockets support independent ``IPV6_RECVPKTINFO`` and " +"``IPV6_RECVHOPLIMIT`` state, disabled by default. Any nonzero setting " +"reads back as 1, and zero reads back as 0. Native IPv6 and IPv4-mapped " +"passive child connections inherit both options and retain independent " +"state after creation. TCP stores these receive settings, and its current " +"``recvmsg()`` delivers stream data only. UDP provides the receive " +"ancillary data described above." -msgid "TCP、UDP 和 raw socket 的 ``bind`` 与 Linux 一样,只对需要区域标识的地址 使用 ``sin6_scope_id``。绑定 ``::``、``::1``、IPv4 映射地址或其他无此需求的 地址时忽略该字段,避免将旧版 Netty 留下的未初始化值误判为不存在的网卡。 链路本地地址及接口/链路本地多播地址仍校验接口;``SO_BINDTODEVICE`` 指定的设备绑定继续生效。" -msgstr "As on Linux, bind on TCP, UDP, and raw sockets uses sin6_scope_id only for addresses that require a scope identifier. For ::, ::1, IPv4-mapped addresses, and other addresses without that requirement, the field is ignored so that an uninitialized value left by older Netty versions is not mistaken for a nonexistent interface. Link-local addresses and interface-local or link-local multicast addresses still require a valid interface. Device binding selected with SO_BINDTODEVICE remains effective." +msgid "" +"TCP 开放文件描述的最后一个引用关闭时,未连接的绑定端点及 listener " +"立即释放端口、缓冲区和创建网络引用,服务可立即重新绑定监听地址。已有关联对端的端点继续按协议状态回收,排队数据、FIN 和 TIME_WAIT " +"保留各自的生命周期。" +msgstr "" +"When a TCP open file description is finally closed, an unconnected bound " +"endpoint or listener immediately releases its port, buffers and creating-" +"network reference, allowing services to rebind their listening address " +"immediately. Endpoints with an associated peer continue to be collected " +"according to protocol state. Queued data, FIN and TIME_WAIT retain their " +"respective lifetimes." -msgid "raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 ``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD 后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。" -msgstr "Raw IPv6 sockets independently retain their creating network. Creation requires ``CAP_NET_RAW`` in that network's user owner. Address binding, routing, delivery, multicast memberships, ICMPv6 errors, ping ID conflicts and device options are isolated by creating network, including after FD transfer. Final close leaves multicast in the original network and releases references. Physical device removal reports errors only to affected sockets in the initial network." +msgid "" +"UDP IPv4 多播提供 " +"``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL``" +" 及 ``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP``。接口选择支持 " +"``in_addr``、``ip_mreq`` 和 ``ip_mreqn``,成员操作支持后两种布局。多播 TTL 默认 1,-1 恢复默认值,0" +" 仅本地投递。loop 和 all 默认开启。接收按创建网络、组地址、入站接口、端口和已连接对端筛选,并向所有匹配的 socket " +"投递。``IP_MULTICAST_ALL=1`` 可使用同网络其他 socket 的组成员资格,设置 0 后仅使用本 socket 成员资格。" +msgstr "" +"UDP IPv4 multicast provides ``IP_MULTICAST_IF``, ``IP_MULTICAST_TTL``, " +"``IP_MULTICAST_LOOP``, ``IP_MULTICAST_ALL`` and ``IP_ADD_MEMBERSHIP`` / " +"``IP_DROP_MEMBERSHIP``. Interface selection accepts ``in_addr``, " +"``ip_mreq`` and ``ip_mreqn``, and membership operations accept the latter" +" two layouts. Multicast TTL defaults to 1, resets with -1, and limits " +"delivery to the local host with 0. Loop and all default to enabled. " +"Reception filters by creating network, group address, ingress interface, " +"port and connected peer, delivering to all matching sockets. " +"``IP_MULTICAST_ALL=1`` can use group memberships of other sockets in the " +"same network. With 0, only the receiving socket's memberships apply." msgid "" -"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP " -"错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host " -"route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态通过 " -"``clone()``、``clone3()`` 或 ``unshare()`` 的 ``CLONE_NEWNET`` 创建网络,通过 " -"``/proc//ns/net`` 句柄和 ``setns()`` 切换网络。授权与失败语义见 :doc:`abi`,内部生命周期与 " -"proc 范围见 :doc:`../core-api/mount-namespaces`。" +"多播发送在创建网络中选择路由和源地址,以太网目的地址使用 ``01:00:5e`` 加组地址低 23 位的映射。TTL 为 0 或选择 " +"loopback 时仅按 loop 设置进行本地投递。非初始网络的发送受其可见接口限制。当前成员资格用于本地接收筛选,尚未实现 IGMP " +"报告与查询,启用 IGMP snooping 的网络可能需要额外配置才能转发流量。" msgstr "" -"Each network namespace owns its interfaces, loopback, IPv4 routes, IPv6 " -"addresses and routes, neighbors, multicast state, pending packets, fragment" -" reassembly, PMTU, fragment IDs and ICMP error rate limits. A new namespace" -" starts with ``lo`` down and no IPv6 address. Its first transition up " -"configures ``::1/128`` and a host route. Tables and queues account for " -"capacity independently, and namespace destruction releases protocol " -"resources. Physical NIC registration and ingress remain in the initial " -"namespace. Userspace creates networks with ``CLONE_NEWNET`` in ``clone()``," -" ``clone3()`` or ``unshare()`` and switches through ``/proc//ns/net`` " -"handles and ``setns()``. See :doc:`abi` for authorization and failure " -"semantics and :doc:`../core-api/mount-namespaces` for lifetimes and proc " -"scope." - -msgid "netlink socket 的 ``SO_SNDBUF`` 和 ``SO_RCVBUF`` 默认有效大小均为 65536 字节。 设置值按无符号整数裁剪到 65536 后乘二,发送和接收的最小有效值分别为 4608 和 2304 字节,查询返回有效大小。发送数据报同时受 8192 字节硬上限及有效发送 缓冲区减 32 字节的限制,超过时返回 ``EMSGSIZE``。短设置值、错误用户指针和 负长度返回错误并保留原设置。" -msgstr "A netlink socket defaults to effective ``SO_SNDBUF`` and ``SO_RCVBUF`` sizes of 65536 bytes each. Setters clamp the unsigned request to 65536 before doubling it, with effective send and receive minima of 4608 and 2304 bytes. Getters return the effective size. A sent datagram must fit both the 8192-byte hard limit and the effective send buffer minus 32 bytes, otherwise it returns ``EMSGSIZE``. Short setter values, invalid user pointers, and negative lengths return errors while preserving the previous setting." - -msgid "接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 位置。预留失败时返回 ``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 属于实际 socket,传递 FD 或切换网络后继续保留。" -msgstr "The receive queue conservatively charges 8192 bytes per datagram. Multipart queries reserve two slots for data and the terminator. Failed reservation returns ``ENOBUFS`` before the request changes network state. Shrinking the receive buffer preserves queued messages and new messages wait for available capacity. Reading releases capacity, and growing the buffer updates writability. Buffer settings belong to the actual socket and survive FD transfer or a network switch." - -msgid "" -"路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含 " -"被忽略的尾部;全部消息无效时不生成回复。预扫描和实际处理使用同一前缀边界。" -msgstr "" -"Route requests process the valid message prefix of a datagram in order, ignoring the first " -"malformed or incomplete message and all subsequent bytes. The last complete message may omit " -"alignment padding. A successful send returns the entire datagram length, including the " -"ignored tail. A datagram with no valid messages generates no replies. Prescanning and " -"processing use the same prefix boundary." +"Multicast transmission selects routes and source addresses in the " +"creating network. Ethernet destination addresses use ``01:00:5e`` " +"followed by the low 23 bits of the group address. A TTL of 0 or selection" +" of loopback limits delivery to the local host according to the loop " +"setting. Transmission from noninitial networks is limited to their " +"visible interfaces. Memberships currently provide local receive " +"filtering. IGMP reports and queries remain unimplemented, and networks " +"with IGMP snooping may require additional configuration to forward " +"traffic." -msgid "IPv4 选项与 UDP 消息" -msgstr "IPv4 Options and UDP Messages" +msgid "" +"UDP ``recvmsg()`` 在启用 IPv4 选项后通过 ``SOL_IP/IP_PKTINFO`` 和 " +"``SOL_IP/IP_TTL`` 返回实际入站接口、目的地址和 TTL,IPv4 " +"映射报文也使用该布局。``in_pktinfo.ipi_addr`` 为报文目的地址,``ipi_spec_dst`` 为接收接口的本地 IPv4" +" 地址,``ipi_ifindex`` 为入站接口索引。原生 IPv6 使用 ``IPV6_PKTINFO`` 和 hop-limit " +"辅助数据。控制缓冲区不足设置 ``MSG_CTRUNC``,载荷截断设置 ``MSG_TRUNC``,支持 ``MSG_PEEK``。向量 I/O" +" 保持单个 UDP 数据报的边界。" +msgstr "" +"With IPv4 options enabled, UDP ``recvmsg()`` returns the actual ingress " +"interface, destination address and TTL through ``SOL_IP/IP_PKTINFO`` and " +"``SOL_IP/IP_TTL``. IPv4-mapped packets use the same layout. " +"``in_pktinfo.ipi_addr`` is the packet destination, ``ipi_spec_dst`` is " +"the receiving interface's local IPv4 address, and ``ipi_ifindex`` is the " +"ingress interface index. Native IPv6 uses ``IPV6_PKTINFO`` and hop-limit " +"ancillary data. Insufficient control space sets ``MSG_CTRUNC`` and " +"payload truncation sets ``MSG_TRUNC``. ``MSG_PEEK`` is supported. Vector " +"I/O preserves a single UDP datagram boundary." -msgid "UDP 和 TCP 的 IPv4 及 IPv4 映射通信支持 ``SOL_IP`` 的 ``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL`` 和 ``IP_MTU_DISCOVER``。TTL 默认 64,接受 1 至 255,设置 -1 恢复默认值。接收辅助信息选项默认关闭。MTU discovery 默认 ``IP_PMTUDISC_WANT``,接受从 ``IP_PMTUDISC_DONT`` 到 ``IP_PMTUDISC_OMIT`` 的 0 至 5。当前 IPv4 输出仅在 ``DO`` 或 ``PROBE`` 时设置 DF,其余模式清除 DF。这些模式的设置与查询支持有上述报文效果,完整 IPv4 PMTU 探测与分片仍有实现边界。" -msgstr "IPv4 and IPv4-mapped communication on UDP and TCP supports the ``SOL_IP`` options ``IP_TTL``, ``IP_PKTINFO``, ``IP_RECVTTL`` and ``IP_MTU_DISCOVER``. TTL defaults to 64, accepts 1 through 255, and resets to the default with -1. Receive ancillary information options default to disabled. MTU discovery defaults to ``IP_PMTUDISC_WANT`` and accepts values 0 through 5, from ``IP_PMTUDISC_DONT`` to ``IP_PMTUDISC_OMIT``. Current IPv4 output sets DF only for ``DO`` or ``PROBE`` and clears it for the other modes. Setting and querying these modes has the packet effects described here. Full IPv4 PMTU discovery and fragmentation remain subject to implementation limits." +msgid "" +"UDP ``sendmsg()`` 可用 ``SOL_IP/IP_PKTINFO`` 的 ``ipi_ifindex`` 与 " +"``ipi_spec_dst`` 为单条消息选择接口和源地址,用 ``SOL_IP/IP_TTL`` 设置 1 至 255 的 TTL。IPv6 " +"socket 还支持 ``IPV6_PKTINFO`` 与 hop-limit " +"辅助数据。发送前导入并校验控制信息,消息覆盖值不改变持久选项,接口和源地址仍受创建网络及 ``SO_BINDTODEVICE`` 约束。" +msgstr "" +"UDP ``sendmsg()`` can select an interface and source address for one " +"message using ``ipi_ifindex`` and ``ipi_spec_dst`` in " +"``SOL_IP/IP_PKTINFO``, and a TTL from 1 through 255 using " +"``SOL_IP/IP_TTL``. IPv6 sockets also support ``IPV6_PKTINFO`` and hop-" +"limit ancillary data. Control information is imported and validated " +"before transmission. Per-message overrides preserve persistent options, " +"and interface and source selection remain constrained by the creating " +"network and ``SO_BINDTODEVICE``." + +msgid "UDP 扩展错误队列" +msgstr "UDP Extended Error Queue" -msgid "TCP 被动建立的子连接继承上述四项 IPv4 选项,IPv6 hop limit 与 PMTU 配置独立保存。TCP 上的 ``IP_PKTINFO`` 和 ``IP_RECVTTL`` 保存配置并由子连接继承,接收辅助数据由 UDP 路径提供。" -msgstr "Passively established TCP child connections inherit all four IPv4 options. IPv6 hop limit and PMTU configuration are stored independently. On TCP, ``IP_PKTINFO`` and ``IP_RECVTTL`` retain configuration that child connections inherit. Receive ancillary data is provided by the UDP path." +msgid "" +"``IP_RECVERR`` 和 ``IPV6_RECVERR`` 默认关闭。启用后,经过校验的 IPv4 ICMP 或 ICMPv6 错误按 " +"socket 创建网络、接口及原始 UDP 地址和端口关联到独立错误队列。记录保存 ``sock_extended_err`` 的 " +"errno、origin、type、code 和 MTU,以及错误发送者、原始目的地址和被引用的 UDP 载荷。IPv4 映射 socket " +"返回原生 IPv6 地址布局。" +msgstr "" +"``IP_RECVERR`` and ``IPV6_RECVERR`` default to disabled. When enabled, " +"validated IPv4 ICMP and ICMPv6 errors are matched to an independent error" +" queue using the socket's creating network, interface, and original UDP " +"addresses and ports. Records retain the errno, origin, type, code and MTU" +" in ``sock_extended_err``, the offender, original destination and quoted " +"UDP payload. IPv4-mapped sockets return native IPv6 address layouts." -msgid "UDP IPv4 多播提供 ``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL`` 及 ``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP``。接口选择支持 ``in_addr``、``ip_mreq`` 和 ``ip_mreqn``,成员操作支持后两种布局。多播 TTL 默认 1,-1 恢复默认值,0 仅本地投递。loop 和 all 默认开启。接收按创建网络、组地址、入站接口、端口和已连接对端筛选,并向所有匹配的 socket 投递。``IP_MULTICAST_ALL=1`` 可使用同网络其他 socket 的组成员资格,设置 0 后仅使用本 socket 成员资格。" -msgstr "UDP IPv4 multicast provides ``IP_MULTICAST_IF``, ``IP_MULTICAST_TTL``, ``IP_MULTICAST_LOOP``, ``IP_MULTICAST_ALL`` and ``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP``. Interface selection accepts ``in_addr``, ``ip_mreq`` and ``ip_mreqn``, and membership operations accept the latter two layouts. Multicast TTL defaults to 1, resets with -1, and limits delivery to the local host with 0. Loop and all default to enabled. Reception filters by creating network, group address, ingress interface, port and connected peer, delivering to all matching sockets. ``IP_MULTICAST_ALL=1`` can use group memberships of other sockets in the same network. With 0, only the receiving socket's memberships apply." +msgid "" +"``recvmsg(MSG_ERRQUEUE)`` 通过 ``msg_name`` 返回原始目的地址,通过 " +"``SOL_IP/IP_RECVERR`` 或 ``SOL_IPV6/IPV6_RECVERR`` 辅助消息返回扩展错误及其发送者,并设置输出 " +"``MSG_ERRQUEUE``。队列为空时立即返回 ``EAGAIN``,设置 ``MSG_PEEK`` " +"仍消费该条错误。载荷和控制区不足分别报告 ``MSG_TRUNC`` 和 " +"``MSG_CTRUNC``。用户输出内存准备失败保留记录,成功读取后按下一条错误更新待处理 errno。" +msgstr "" +"``recvmsg(MSG_ERRQUEUE)`` returns the original destination in " +"``msg_name`` and the extended error and offender in a " +"``SOL_IP/IP_RECVERR`` or ``SOL_IPV6/IPV6_RECVERR`` control message, " +"setting output ``MSG_ERRQUEUE``. An empty queue immediately returns " +"``EAGAIN``. ``MSG_PEEK`` still consumes the error record. Insufficient " +"payload and control capacity report ``MSG_TRUNC`` and ``MSG_CTRUNC`` " +"respectively. Failed user-output preparation preserves the record. " +"Successful reads update the pending errno from the next error." -msgid "多播发送在创建网络中选择路由和源地址,以太网目的地址使用 ``01:00:5e`` 加组地址低 23 位的映射。TTL 为 0 或选择 loopback 时仅按 loop 设置进行本地投递。非初始网络的发送受其可见接口限制。当前成员资格用于本地接收筛选,尚未实现 IGMP 报告与查询,启用 IGMP snooping 的网络可能需要额外配置才能转发流量。" -msgstr "Multicast transmission selects routes and source addresses in the creating network. Ethernet destination addresses use ``01:00:5e`` followed by the low 23 bits of the group address. A TTL of 0 or selection of loopback limits delivery to the local host according to the loop setting. Transmission from noninitial networks is limited to their visible interfaces. Memberships currently provide local receive filtering. IGMP reports and queries remain unimplemented, and networks with IGMP snooping may require additional configuration to forward traffic." +msgid "" +"错误记录与普通数据报分别持有存储,待处理 errno 或错误队列可触发 ``POLLERR``。查询 ``SO_ERROR`` 清除待处理 " +"errno,已排队记录继续可读。关闭相应 RECVERR 选项会清空错误队列,保留普通数据和待处理 " +"errno。分配失败或队列达到上限时保留已有记录并继续报告 socket 错误。最后关闭释放全部记录及创建网络引用。" +msgstr "" +"Error records and ordinary datagrams own separate storage. A pending " +"errno or queued error can trigger ``POLLERR``. Reading ``SO_ERROR`` " +"clears the pending errno while queued records remain readable. Disabling " +"the corresponding RECVERR option clears the error queue while retaining " +"ordinary data and the pending errno. Allocation failure or a full queue " +"preserves existing records and continues to report the socket error. " +"Final close releases all records and the creating-network reference." -msgid "UDP ``recvmsg()`` 在启用 IPv4 选项后通过 ``SOL_IP/IP_PKTINFO`` 和 ``SOL_IP/IP_TTL`` 返回实际入站接口、目的地址和 TTL,IPv4 映射报文也使用该布局。``in_pktinfo.ipi_addr`` 为报文目的地址,``ipi_spec_dst`` 为接收接口的本地 IPv4 地址,``ipi_ifindex`` 为入站接口索引。原生 IPv6 使用 ``IPV6_PKTINFO`` 和 hop-limit 辅助数据。控制缓冲区不足设置 ``MSG_CTRUNC``,载荷截断设置 ``MSG_TRUNC``,支持 ``MSG_PEEK``。向量 I/O 保持单个 UDP 数据报的边界。" -msgstr "With IPv4 options enabled, UDP ``recvmsg()`` returns the actual ingress interface, destination address and TTL through ``SOL_IP/IP_PKTINFO`` and ``SOL_IP/IP_TTL``. IPv4-mapped packets use the same layout. ``in_pktinfo.ipi_addr`` is the packet destination, ``ipi_spec_dst`` is the receiving interface's local IPv4 address, and ``ipi_ifindex`` is the ingress interface index. Native IPv6 uses ``IPV6_PKTINFO`` and hop-limit ancillary data. Insufficient control space sets ``MSG_CTRUNC`` and payload truncation sets ``MSG_TRUNC``. ``MSG_PEEK`` is supported. Vector I/O preserves a single UDP datagram boundary." +msgid "packet socket 与链路接收" +msgstr "Packet sockets and link reception" -msgid "UDP ``sendmsg()`` 可用 ``SOL_IP/IP_PKTINFO`` 的 ``ipi_ifindex`` 与 ``ipi_spec_dst`` 为单条消息选择接口和源地址,用 ``SOL_IP/IP_TTL`` 设置 1 至 255 的 TTL。IPv6 socket 还支持 ``IPV6_PKTINFO`` 与 hop-limit 辅助数据。发送前导入并校验控制信息,消息覆盖值不改变持久选项,接口和源地址仍受创建网络及 ``SO_BINDTODEVICE`` 约束。" -msgstr "UDP ``sendmsg()`` can select an interface and source address for one message using ``ipi_ifindex`` and ``ipi_spec_dst`` in ``SOL_IP/IP_PKTINFO``, and a TTL from 1 through 255 using ``SOL_IP/IP_TTL``. IPv6 sockets also support ``IPV6_PKTINFO`` and hop-limit ancillary data. Control information is imported and validated before transmission. Per-message overrides preserve persistent options, and interface and source selection remain constrained by the creating network and ``SO_BINDTODEVICE``." +msgid "" +"``AF_PACKET`` 的 ``SO_ATTACH_FILTER`` 与 ``SO_DETACH_FILTER`` 复用 classic " +"BPF 校验和执行器。过滤结果为 0 时丢弃报文,正值限制保留长度。替换失败保留旧过滤器。``bind()`` 的零 " +"``sll_protocol`` 保留创建时选择的协议。" +msgstr "" +"``SO_ATTACH_FILTER`` and ``SO_DETACH_FILTER`` on ``AF_PACKET`` use the " +"classic BPF validator and interpreter. A zero result drops the frame, and" +" a positive result limits its retained length. Failed replacement " +"preserves the previous filter. A zero ``sll_protocol`` in ``bind()`` " +"retains the protocol selected at creation." -msgid "``NETLINK_GENERIC`` 提供标准控制族 ``nlctrl``,family ID 为 16,版本为 2。``CTRL_CMD_GETFAMILY`` 支持按 ``CTRL_ATTR_FAMILY_NAME`` 或 ``CTRL_ATTR_FAMILY_ID`` 查询,同时提供时优先名称。dump 返回已注册族及独立的 ``NLMSG_DONE``,回复公布查询操作和 ``notify`` 组 16。未知族通过 ``NLMSG_ERROR`` 返回 ``ENOENT``,未实现的控制命令返回 ``EOPNOTSUPP``。当前注册族仅有 ``nlctrl``,无线 ``nl80211`` 族尚未提供。socket 保留创建网络并复用端口、队列、ACK 和错误处理语义。" -msgstr "``NETLINK_GENERIC`` provides the standard ``nlctrl`` controller family with family ID 16 and version 2. ``CTRL_CMD_GETFAMILY`` looks up ``CTRL_ATTR_FAMILY_NAME`` or ``CTRL_ATTR_FAMILY_ID``, preferring the name when both are supplied. Dumps return registered families and a separate ``NLMSG_DONE``. Replies advertise the query operation and ``notify`` group 16. Unknown families return ``ENOENT`` through ``NLMSG_ERROR``, and unimplemented controller commands return ``EOPNOTSUPP``. The currently registered family is ``nlctrl`` alone. The wireless ``nl80211`` family remains unavailable. Sockets retain their creating network and reuse port, queue, ACK and error-handling semantics." +msgid "" +"``SOL_PACKET`` 的 ``PACKET_ADD_MEMBERSHIP`` 与 ``PACKET_DROP_MEMBERSHIP`` " +"支持按创建网络、接口及六字节地址管理 " +"``PACKET_MR_MULTICAST``,重复加入按引用计数回收。最后关闭或设备移除释放订阅。额外链路组播按同网络、同接口的订阅执行软件接收筛选。当前其他成员类型返回" +" ``EINVAL``。" +msgstr "" +"At ``SOL_PACKET``, ``PACKET_ADD_MEMBERSHIP`` and " +"``PACKET_DROP_MEMBERSHIP`` manage ``PACKET_MR_MULTICAST`` by creating " +"network, interface and six-byte address. Duplicate joins are reference " +"counted. Final close and device removal release subscriptions. Additional" +" link multicast is admitted in software using subscriptions in the same " +"network and interface. Other membership types currently return " +"``EINVAL``." -msgid "IPv4 地址的 ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知投递到 ``RTNLGRP_IPV4_IFADDR``,IPv4 路由的 ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` 通知投递到 ``RTNLGRP_IPV4_ROUTE``。订阅与通知均沿用 socket 创建网络。" -msgstr "IPv4 address ``RTM_NEWADDR`` / ``RTM_DELADDR`` notifications go to ``RTNLGRP_IPV4_IFADDR``, and IPv4 route ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` notifications go to ``RTNLGRP_IPV4_ROUTE``. Subscriptions and notifications both follow the socket's creating network." +msgid "" +"``PACKET_AUXDATA`` 在 ``recvmsg()`` 返回 " +"``tpacket_auxdata``,包括过滤前长度、保留长度及链路偏移。RAW 报文的网络偏移为 14,DGRAM 为 " +"0。``SO_TIMESTAMP_OLD`` 与 ``SO_TIMESTAMP_NEW`` 提供 realtime " +"微秒时间戳,排队时采样,接收前才启用时延迟采样,重复 ``MSG_PEEK`` 保留同一样本。输出内存准备失败保留队列,控制缓冲区不足设置 " +"``MSG_CTRUNC``。" +msgstr "" +"``PACKET_AUXDATA`` returns ``tpacket_auxdata`` through ``recvmsg()``, " +"including the pre-filter length, retained length and link offsets. The " +"network offset is 14 for RAW frames and 0 for DGRAM frames. " +"``SO_TIMESTAMP_OLD`` and ``SO_TIMESTAMP_NEW`` provide realtime " +"microsecond timestamps sampled at enqueue, or lazily when enabled after " +"arrival. Repeated ``MSG_PEEK`` retains the same sample. Output-memory " +"preparation failure preserves the queue, and insufficient control space " +"sets ``MSG_CTRUNC``." -msgid "``NETLINK_GENERIC`` 的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 4 字节位图,控制族 ``notify`` 使用组 16。" -msgstr "``NETLINK_LIST_MEMBERSHIPS`` on ``NETLINK_GENERIC`` returns a 4-byte bitmap. The controller's ``notify`` group uses group 16." +msgid "配置与观测" +msgstr "Configuration and Observation" -msgid "TCP IPv6 socket 支持 ``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` 的独立状态,默认关闭,任意非零设置值查询为 1,零查询为 0。原生 IPv6 和 IPv4 映射的被动子连接继承这两项,建立后各自保存状态。TCP 保存这些接收配置,当前 ``recvmsg()`` 仅交付流数据,UDP 提供上述接收辅助数据。" -msgstr "TCP IPv6 sockets support independent ``IPV6_RECVPKTINFO`` and ``IPV6_RECVHOPLIMIT`` state, disabled by default. Any nonzero setting reads back as 1, and zero reads back as 0. Native IPv6 and IPv4-mapped passive child connections inherit both options and retain independent state after creation. TCP stores these receive settings, and its current ``recvmsg()`` delivers stream data only. UDP provides the receive ancillary data described above." +msgid "" +"``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 " +"地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 " +"``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl " +"使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET " +"socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。" +msgstr "" +"``AF_NETLINK`` / ``NETLINK_ROUTE`` queries and changes links, IPv4/IPv6 " +"addresses and routes in the network scope retained when the socket was " +"created, including after FD transfer. Changes require ``CAP_NET_ADMIN`` " +"in the network owner's user namespace. ``getifaddrs()`` obtains that " +"scope's IPv6 addresses through standard queries. IPv6 address and route " +"ioctls use the selected network's state and owner authority, with layouts" +" selected by socket family. Interface ioctls on UDP, TCP, raw and " +"AF_PACKET sockets, and address and route ioctls on IPv6 sockets, all use " +"the creating network." -msgid "``RTM_GETNEIGH`` dump 从 socket 创建网络的 ARP 和 NDP 快照输出邻居,支持 ``AF_UNSPEC``、``AF_INET``、``AF_INET6`` 及接口索引筛选。IPv4 的 ``NDA_DST`` 转为网络字节序,缓存地址映射以 ``NUD_STALE`` 表示,IPv6 保留现有 NUD 状态。回复包含接口、目的地址及可用的链路层地址。``AF_BRIDGE`` 和 ``NTF_PROXY`` 查询返回空表及 ``NLMSG_DONE``,邻居新增、修改和删除请求返回 ``EOPNOTSUPP``。" -msgstr "``RTM_GETNEIGH`` dumps render neighbors from ARP and NDP snapshots in the socket's creating network, supporting ``AF_UNSPEC``, ``AF_INET``, ``AF_INET6`` and interface-index filtering. IPv4 ``NDA_DST`` is converted to network byte order. Cached address mappings use ``NUD_STALE``, and IPv6 retains the existing NUD state. Replies include the interface, destination address and available link-layer address. ``AF_BRIDGE`` and ``NTF_PROXY`` queries return an empty table and ``NLMSG_DONE``. Requests to add, modify or delete neighbors return ``EOPNOTSUPP``." +msgid "" +"``RTM_GETNEIGH`` dump 从 socket 创建网络的 ARP 和 NDP 快照输出邻居,支持 " +"``AF_UNSPEC``、``AF_INET``、``AF_INET6`` 及接口索引筛选。IPv4 的 ``NDA_DST`` " +"转为网络字节序,缓存地址映射以 ``NUD_STALE`` 表示,IPv6 保留现有 NUD " +"状态。回复包含接口、目的地址及可用的链路层地址。``AF_BRIDGE`` 和 ``NTF_PROXY`` 查询返回空表及 " +"``NLMSG_DONE``,邻居新增、修改和删除请求返回 ``EOPNOTSUPP``。" +msgstr "" +"``RTM_GETNEIGH`` dumps render neighbors from ARP and NDP snapshots in the" +" socket's creating network, supporting ``AF_UNSPEC``, ``AF_INET``, " +"``AF_INET6`` and interface-index filtering. IPv4 ``NDA_DST`` is converted" +" to network byte order. Cached address mappings use ``NUD_STALE``, and " +"IPv6 retains the existing NUD state. Replies include the interface, " +"destination address and available link-layer address. ``AF_BRIDGE`` and " +"``NTF_PROXY`` queries return an empty table and ``NLMSG_DONE``. Requests " +"to add, modify or delete neighbors return ``EOPNOTSUPP``." msgid "``AF_BRIDGE`` 的 ``RTM_GETLINK`` dump 返回空表及 ``NLMSG_DONE``。" -msgstr "``RTM_GETLINK`` dumps for ``AF_BRIDGE`` return an empty table and ``NLMSG_DONE``." +msgstr "" +"``RTM_GETLINK`` dumps for ``AF_BRIDGE`` return an empty table and " +"``NLMSG_DONE``." -msgid "独立单路径 nexthop 按 socket 创建网络保存。``RTM_NEWNEXTHOP`` 和 ``RTM_DELNEXTHOP`` 按非零 ``NHA_ID`` 创建、替换或删除 IPv4/IPv6 对象,支持 ``NHA_OIF``、``NHA_GATEWAY`` 和 ``RTNH_F_ONLINK``。``RTM_GETNEXTHOP`` 支持按 ID 查询,以及按地址族、ID 和接口筛选的 dump,dump 以 ``NLMSG_DONE`` 结束。路由通过 ``RTA_NH_ID`` 引用同网络、同地址族的对象。替换对象同步更新依赖路由,删除对象或接口同时删除依赖路由,网络销毁释放全部对象。分配失败保留对象和路由状态。nexthop group、blackhole 和封装请求返回 ``EOPNOTSUPP``。" -msgstr "Standalone single-path nexthops belong to the socket's creating network. ``RTM_NEWNEXTHOP`` and ``RTM_DELNEXTHOP`` create, replace or delete IPv4/IPv6 objects by nonzero ``NHA_ID``, supporting ``NHA_OIF``, ``NHA_GATEWAY`` and ``RTNH_F_ONLINK``. ``RTM_GETNEXTHOP`` supports lookup by ID and dumps filtered by address family, ID and interface, ending each dump with ``NLMSG_DONE``. Routes use ``RTA_NH_ID`` to reference objects in the same network and address family. Replacement updates dependent routes, deleting an object or interface also deletes dependent routes, and network destruction releases all objects. Allocation failure preserves object and route state. Nexthop group, blackhole and encapsulation requests return ``EOPNOTSUPP``." +msgid "" +"独立单路径 nexthop 按 socket 创建网络保存。``RTM_NEWNEXTHOP`` 和 ``RTM_DELNEXTHOP`` 按非零" +" ``NHA_ID`` 创建、替换或删除 IPv4/IPv6 对象,支持 ``NHA_OIF``、``NHA_GATEWAY`` 和 " +"``RTNH_F_ONLINK``。``RTM_GETNEXTHOP`` 支持按 ID 查询,以及按地址族、ID 和接口筛选的 dump,dump" +" 以 ``NLMSG_DONE`` 结束。路由通过 ``RTA_NH_ID`` " +"引用同网络、同地址族的对象。替换对象同步更新依赖路由,删除对象或接口同时删除依赖路由,网络销毁释放全部对象。分配失败保留对象和路由状态。nexthop" +" group、blackhole 和封装请求返回 ``EOPNOTSUPP``。" +msgstr "" +"Standalone single-path nexthops belong to the socket's creating network. " +"``RTM_NEWNEXTHOP`` and ``RTM_DELNEXTHOP`` create, replace or delete " +"IPv4/IPv6 objects by nonzero ``NHA_ID``, supporting ``NHA_OIF``, " +"``NHA_GATEWAY`` and ``RTNH_F_ONLINK``. ``RTM_GETNEXTHOP`` supports lookup" +" by ID and dumps filtered by address family, ID and interface, ending " +"each dump with ``NLMSG_DONE``. Routes use ``RTA_NH_ID`` to reference " +"objects in the same network and address family. Replacement updates " +"dependent routes, deleting an object or interface also deletes dependent " +"routes, and network destruction releases all objects. Allocation failure " +"preserves object and route state. Nexthop group, blackhole and " +"encapsulation requests return ``EOPNOTSUPP``." -msgid "TCP 开放文件描述的最后一个引用关闭时,未连接的绑定端点及 listener 立即释放端口、缓冲区和创建网络引用,服务可立即重新绑定监听地址。已有关联对端的端点继续按协议状态回收,排队数据、FIN 和 TIME_WAIT 保留各自的生命周期。" -msgstr "When a TCP open file description is finally closed, an unconnected bound endpoint or listener immediately releases its port, buffers and creating-network reference, allowing services to rebind their listening address immediately. Endpoints with an associated peer continue to be collected according to protocol state. Queued data, FIN and TIME_WAIT retain their respective lifetimes." +msgid "" +"``NETLINK_GENERIC`` 提供标准控制族 ``nlctrl``,family ID 为 16,版本为 " +"2。``CTRL_CMD_GETFAMILY`` 支持按 ``CTRL_ATTR_FAMILY_NAME`` 或 " +"``CTRL_ATTR_FAMILY_ID`` 查询,同时提供时优先名称。dump 返回已注册族及独立的 " +"``NLMSG_DONE``,回复公布查询操作和 ``notify`` 组 16。未知族通过 ``NLMSG_ERROR`` 返回 " +"``ENOENT``,未实现的控制命令返回 ``EOPNOTSUPP``。当前注册族仅有 ``nlctrl``,无线 ``nl80211`` " +"族尚未提供。socket 保留创建网络并复用端口、队列、ACK 和错误处理语义。" +msgstr "" +"``NETLINK_GENERIC`` provides the standard ``nlctrl`` controller family " +"with family ID 16 and version 2. ``CTRL_CMD_GETFAMILY`` looks up " +"``CTRL_ATTR_FAMILY_NAME`` or ``CTRL_ATTR_FAMILY_ID``, preferring the name" +" when both are supplied. Dumps return registered families and a separate " +"``NLMSG_DONE``. Replies advertise the query operation and ``notify`` " +"group 16. Unknown families return ``ENOENT`` through ``NLMSG_ERROR``, and" +" unimplemented controller commands return ``EOPNOTSUPP``. The currently " +"registered family is ``nlctrl`` alone. The wireless ``nl80211`` family " +"remains unavailable. Sockets retain their creating network and reuse " +"port, queue, ACK and error-handling semantics." -msgid "``SOL_SOCKET`` 的 ``SO_BINDTODEVICE`` 在 socket 创建网络中按名称查找设备,空名称解除绑定。``SO_BINDTOIFINDEX`` 的编号为 62,按 ``int`` 接口索引设置或查询同一绑定。正索引允许对应尚不存在或已删除的设备,负值返回 ``EINVAL``,0 解除绑定。两者的绑定均属于 socket 创建网络,任务切换网络或传递 FD 后继续使用该网络。当前已有非零绑定时,修改绑定或解绑需要创建网络 user owner 的 ``CAP_NET_RAW``。" -msgstr "At ``SOL_SOCKET``, ``SO_BINDTODEVICE`` looks up a device by name in the socket's creating network. An empty name clears the binding. ``SO_BINDTOIFINDEX``, numbered 62, sets or queries the same binding with an ``int`` interface index. Positive indices may refer to devices that do not yet exist or have been removed. Negative values return ``EINVAL``, and 0 clears the binding. Both bindings belong to the socket's creating network, which remains in use across task network changes and FD passing. Changing or clearing a currently nonzero binding requires ``CAP_NET_RAW`` in the creating network's user owner." +msgid "" +"IPv4 地址查询和新增、删除通知携带 ``ifaddrmsg.ifa_flags``、32 位 " +"``IFA_FLAGS``、scope、``IFA_CACHEINFO`` 及可选的 ``IFA_RT_PRIORITY``。每个接口保存一个主 " +"IPv4 地址,支持 ``IFA_F_PERMANENT``、``IFA_F_DEPRECATED`` 和 " +"``IFA_F_NOPREFIXROUTE``。有限有效期清除 PERMANENT,首选期到期设置 " +"DEPRECATED,有效期到期删除地址。NOPREFIXROUTE 抑制自动前缀路由,IFA_RT_PRIORITY 设置其 " +"metric。省略有效期时地址永久有效。" +msgstr "" +"IPv4 address queries and addition and deletion notifications carry " +"``ifaddrmsg.ifa_flags``, 32-bit ``IFA_FLAGS``, scope, ``IFA_CACHEINFO`` " +"and optional ``IFA_RT_PRIORITY``. Each interface retains one primary IPv4" +" address, supporting ``IFA_F_PERMANENT``, ``IFA_F_DEPRECATED`` and " +"``IFA_F_NOPREFIXROUTE``. A finite valid lifetime clears PERMANENT, " +"preferred-lifetime expiry sets DEPRECATED, and valid-lifetime expiry " +"deletes the address. NOPREFIXROUTE suppresses the automatic prefix route," +" and IFA_RT_PRIORITY sets its metric. Omitting lifetimes makes the " +"address permanent." -msgid "IPv4 地址查询和新增、删除通知携带 ``ifaddrmsg.ifa_flags``、32 位 ``IFA_FLAGS``、scope、``IFA_CACHEINFO`` 及可选的 ``IFA_RT_PRIORITY``。每个接口保存一个主 IPv4 地址,支持 ``IFA_F_PERMANENT``、``IFA_F_DEPRECATED`` 和 ``IFA_F_NOPREFIXROUTE``。有限有效期清除 PERMANENT,首选期到期设置 DEPRECATED,有效期到期删除地址。NOPREFIXROUTE 抑制自动前缀路由,IFA_RT_PRIORITY 设置其 metric。省略有效期时地址永久有效。" -msgstr "IPv4 address queries and addition and deletion notifications carry ``ifaddrmsg.ifa_flags``, 32-bit ``IFA_FLAGS``, scope, ``IFA_CACHEINFO`` and optional ``IFA_RT_PRIORITY``. Each interface retains one primary IPv4 address, supporting ``IFA_F_PERMANENT``, ``IFA_F_DEPRECATED`` and ``IFA_F_NOPREFIXROUTE``. A finite valid lifetime clears PERMANENT, preferred-lifetime expiry sets DEPRECATED, and valid-lifetime expiry deletes the address. NOPREFIXROUTE suppresses the automatic prefix route, and IFA_RT_PRIORITY sets its metric. Omitting lifetimes makes the address permanent." +msgid "" +"IPv6 地址使用相同的租期和前缀 metric 属性,支持 NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE 和" +" MANAGETEMPADDR。MANAGETEMPADDR 要求 /64 " +"前缀并保存配置标志,临时隐私地址的自动生成仍待实现。自动前缀路由随地址、metric、标志和有效期维护,同时保留同前缀的其他有效地址及 RA " +"路由贡献。" +msgstr "" +"IPv6 addresses use the same lifetime and prefix-metric attributes and " +"support NODAD, PERMANENT, DEPRECATED, NOPREFIXROUTE and MANAGETEMPADDR. " +"MANAGETEMPADDR requires a /64 prefix and retains the configuration flag. " +"Automatic generation of temporary privacy addresses remains pending. " +"Automatic prefix routes track addresses, metrics, flags and lifetimes " +"while preserving contributions from other valid addresses with the same " +"prefix and from RA routes." -msgid "IPv6 地址使用相同的租期和前缀 metric 属性,支持 NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE 和 MANAGETEMPADDR。MANAGETEMPADDR 要求 /64 前缀并保存配置标志,临时隐私地址的自动生成仍待实现。自动前缀路由随地址、metric、标志和有效期维护,同时保留同前缀的其他有效地址及 RA 路由贡献。" -msgstr "IPv6 addresses use the same lifetime and prefix-metric attributes and support NODAD, PERMANENT, DEPRECATED, NOPREFIXROUTE and MANAGETEMPADDR. MANAGETEMPADDR requires a /64 prefix and retains the configuration flag. Automatic generation of temporary privacy addresses remains pending. Automatic prefix routes track addresses, metrics, flags and lifetimes while preserving contributions from other valid addresses with the same prefix and from RA routes." +msgid "" +"IPv4/IPv6 的 ``RTM_NEWADDR`` 允许仅携带 ``NLM_F_REPLACE`` 创建地址。已有地址遇 " +"``NLM_F_EXCL`` 或缺少 REPLACE 时返回 ``EEXIST``,校验失败保留原配置。``RTM_NEWROUTE`` 接受 " +"``NLM_F_APPEND``,新增路由保留同优先级存活路由的插入顺序。修改请求的 ``NLM_F_ECHO`` 和其他修改消息上的 " +"APPEND 返回 ``EOPNOTSUPP``。" +msgstr "" +"IPv4/IPv6 ``RTM_NEWADDR`` permits address creation with ``NLM_F_REPLACE``" +" alone. An existing address returns ``EEXIST`` with ``NLM_F_EXCL`` or " +"without REPLACE. Validation failure preserves the configuration. " +"``RTM_NEWROUTE`` accepts ``NLM_F_APPEND``, and new routes preserve " +"insertion order among surviving routes with equal priority. " +"``NLM_F_ECHO`` on mutation requests and APPEND on other mutation messages" +" return ``EOPNOTSUPP``." -msgid "IPv4/IPv6 的 ``RTM_NEWADDR`` 允许仅携带 ``NLM_F_REPLACE`` 创建地址。已有地址遇 ``NLM_F_EXCL`` 或缺少 REPLACE 时返回 ``EEXIST``,校验失败保留原配置。``RTM_NEWROUTE`` 接受 ``NLM_F_APPEND``,新增路由保留同优先级存活路由的插入顺序。修改请求的 ``NLM_F_ECHO`` 和其他修改消息上的 APPEND 返回 ``EOPNOTSUPP``。" -msgstr "IPv4/IPv6 ``RTM_NEWADDR`` permits address creation with ``NLM_F_REPLACE`` alone. An existing address returns ``EEXIST`` with ``NLM_F_EXCL`` or without REPLACE. Validation failure preserves the configuration. ``RTM_NEWROUTE`` accepts ``NLM_F_APPEND``, and new routes preserve insertion order among surviving routes with equal priority. ``NLM_F_ECHO`` on mutation requests and APPEND on other mutation messages return ``EOPNOTSUPP``." +msgid "" +"IPv4/IPv6 路由支持 ``RTA_PREFSRC`` 及 ``RTNH_F_ONLINK``,首选源地址须已配置在同网络。IPv6 还支持" +" ``RTA_PREF`` 的低、中、高优先级与 ``RTA_EXPIRES`` 秒级有效期,到期发布删除通知。IPv6 " +"路由身份包含目的前缀、接口、网关、nexthop ID 和 metric,同路径不同 metric 可共存。选路依次比较最长前缀、较低 " +"metric 和较高 preference,完全相同时保留先插入路由。REPLACE 更新匹配条目,目标缺失且未携带 CREATE 时返回 " +"``ESRCH``。" +msgstr "" +"IPv4/IPv6 routes support ``RTA_PREFSRC`` and ``RTNH_F_ONLINK``. Preferred" +" source addresses must be configured in the same network. IPv6 also " +"supports low, medium and high ``RTA_PREF`` preference and ``RTA_EXPIRES``" +" lifetimes in seconds, publishing deletion notifications on expiry. IPv6 " +"route identity includes the destination prefix, interface, gateway, " +"nexthop ID and metric, allowing different metrics on the same path. " +"Selection compares longest prefix, lower metric and higher preference in " +"that order, retaining the earlier route on a complete tie. REPLACE " +"updates a matching entry and returns ``ESRCH`` when the target is absent " +"and CREATE is omitted." -msgid "IPv4/IPv6 路由支持 ``RTA_PREFSRC`` 及 ``RTNH_F_ONLINK``,首选源地址须已配置在同网络。IPv6 还支持 ``RTA_PREF`` 的低、中、高优先级与 ``RTA_EXPIRES`` 秒级有效期,到期发布删除通知。IPv6 路由身份包含目的前缀、接口、网关、nexthop ID 和 metric,同路径不同 metric 可共存。选路依次比较最长前缀、较低 metric 和较高 preference,完全相同时保留先插入路由。REPLACE 更新匹配条目,目标缺失且未携带 CREATE 时返回 ``ESRCH``。" -msgstr "IPv4/IPv6 routes support ``RTA_PREFSRC`` and ``RTNH_F_ONLINK``. Preferred source addresses must be configured in the same network. IPv6 also supports low, medium and high ``RTA_PREF`` preference and ``RTA_EXPIRES`` lifetimes in seconds, publishing deletion notifications on expiry. IPv6 route identity includes the destination prefix, interface, gateway, nexthop ID and metric, allowing different metrics on the same path. Selection compares longest prefix, lower metric and higher preference in that order, retaining the earlier route on a complete tie. REPLACE updates a matching entry and returns ``ESRCH`` when the target is absent and CREATE is omitted." +msgid "" +"IPv4 地址的 ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知投递到 " +"``RTNLGRP_IPV4_IFADDR``,IPv4 路由的 ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` " +"通知投递到 ``RTNLGRP_IPV4_ROUTE``。订阅与通知均沿用 socket 创建网络。" +msgstr "" +"IPv4 address ``RTM_NEWADDR`` / ``RTM_DELADDR`` notifications go to " +"``RTNLGRP_IPV4_IFADDR``, and IPv4 route ``RTM_NEWROUTE`` / " +"``RTM_DELROUTE`` notifications go to ``RTNLGRP_IPV4_ROUTE``. " +"Subscriptions and notifications both follow the socket's creating " +"network." -msgid "网络 sysfs 与设备事件" -msgstr "Network sysfs and Device Events" +msgid "" +"路由多播发布链路、IPv4/IPv6 地址和路由的新增、变更与删除。IPv4 路由包含直连、默认及显式路由,metric " +"替换发布旧路由删除和新路由添加。接口删除时,地址通知保留原接口名称与地址。每个网络空间独立维护订阅快照,全部捕获成功后替换,最后一个订阅关闭或退订时释放。快照捕获失败保留旧基线并报告" +" overrun,后续变更重新捕获。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 " +"``ENOBUFS``,调用者应重新查询。" +msgstr "" +"Route multicast publishes link, IPv4/IPv6 address and route additions, " +"changes and deletions. IPv4 routes include connected, default and " +"explicit routes. Replacing a metric publishes deletion of the old route " +"and addition of the new one. Address notifications retain the original " +"interface name and address after interface deletion. Each network " +"namespace maintains its own subscription snapshots, replaced after all " +"captures succeed and released when its final subscriber closes or " +"unsubscribes. Capture failure preserves the old baseline and reports an " +"overrun, with capture retried on a subsequent change. Change " +"notifications and overruns follow the network scope. Receive queue " +"overflow reports ``ENOBUFS``, and callers should query again." -msgid "sysfs 挂载保留创建时捕获的网络空间,后续 lookup、readdir、read 和 write 均使用该视图。任务执行 ``setns()``、``unshare()`` 或传递挂载句柄后,已有挂载继续观察原网络。``fsopen(\"sysfs\")`` 的网络与 owner 捕获及 CREATE 授权见 :doc:`abi`。" -msgstr "A sysfs mount retains the network namespace captured at creation. Subsequent lookup, readdir, read and write operations use that view. Existing mounts continue to observe the original network after a task calls ``setns()`` or ``unshare()`` or passes a mount handle. See :doc:`abi` for network and owner capture by ``fsopen(\"sysfs\")`` and CREATE authorization." +msgid "" +"路由 socket 接受 Linux 6.12 的标准组编号 1 至 36,支持 networkd 和 resolved " +"的订阅组合。实际事件由对应子系统提供,具体请求仍按其实现能力校验。``sockaddr_nl.nl_groups`` 表示低 32 " +"位,``NETLINK_ADD_MEMBERSHIP`` 和 ``NETLINK_DROP_MEMBERSHIP`` 按组编号操作。初始化后的 " +"``NETLINK_LIST_MEMBERSHIPS`` 返回 8 字节位图,短缓冲区复制可容纳的完整 32 位字并报告完整所需长度;uevent" +" 位图长度为 4 字节。" +msgstr "" +"Route sockets accept standard Linux 6.12 group numbers 1 through 36, " +"supporting the subscription combinations used by networkd and resolved. " +"The corresponding subsystems supply events, and individual requests are " +"validated against their implemented capabilities. " +"``sockaddr_nl.nl_groups`` represents the low 32 bits. " +"``NETLINK_ADD_MEMBERSHIP`` and ``NETLINK_DROP_MEMBERSHIP`` operate on " +"group numbers. After initialization, ``NETLINK_LIST_MEMBERSHIPS`` returns" +" an 8-byte bitmap. Short buffers receive the complete 32-bit words that " +"fit and report the full required length. The uevent bitmap is 4 bytes " +"long." -msgid "``/sys/class/net/`` 是指向 canonical 设备节点的符号链接。loopback 位于 ``/sys/devices/virtual/net/lo``,物理接口位于对应 PCI function 下的 ``net/``,``device`` 链接指向 PCI 父节点,``subsystem`` 链接指向 ``/sys/class/net``。属性包含 ``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier`` 和 ``uevent``。物理接口仅在初始网络中可见。接口移除后,持有的旧 inode 在重新打开、读取或写入时返回 ``ENOENT``。" -msgstr "``/sys/class/net/`` is a symbolic link to the canonical device node. Loopback resides at ``/sys/devices/virtual/net/lo``. A physical interface resides at ``net/`` below its PCI function, with ``device`` linking to the PCI parent and ``subsystem`` linking to ``/sys/class/net``. Attributes include ``ifindex``, ``iflink``, ``address``, ``broadcast``, ``type``, ``mtu``, ``flags``, ``operstate``, ``carrier`` and ``uevent``. Physical interfaces are visible only in the initial network. After interface removal, reopening, reading or writing a retained old inode returns ``ENOENT``." +msgid "" +"``NETLINK_GENERIC`` 的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 4 字节位图,控制族 " +"``notify`` 使用组 16。" +msgstr "" +"``NETLINK_LIST_MEMBERSHIPS`` on ``NETLINK_GENERIC`` returns a 4-byte " +"bitmap. The controller's ``notify`` group uses group 16." -msgid "网络 ``uevent`` 文件由 root 所有,模式为 0644,写入遵循常规 DAC 与挂载只读策略。只读挂载也阻止 root 写入。读取提供 ``INTERFACE`` 和 ``IFINDEX``。写入接受 ``add``、``remove``、``change``、``move``、``online``、``offline``、``bind`` 或 ``unbind``,可在一个空格后附加 36 字符的十六进制 UUID,连字符位于标准位置,末尾可带一个换行。无 UUID 时事件使用 ``SYNTH_UUID=0``,提供 UUID 时按输入传递。无效 action、UUID 或 embedded NUL 返回 ``EINVAL``,并保持事件队列不变。" -msgstr "Network ``uevent`` files are root-owned with mode 0644. Writes follow normal DAC and mount readonly policy. Readonly mounts also prevent root writes. Reads provide ``INTERFACE`` and ``IFINDEX``. Writes accept ``add``, ``remove``, ``change``, ``move``, ``online``, ``offline``, ``bind`` or ``unbind``, optionally followed by one space and a 36-character hexadecimal UUID with hyphens in the standard positions. One trailing newline is allowed. Events without a UUID use ``SYNTH_UUID=0``. A supplied UUID is passed through as entered. An invalid action, UUID or embedded NUL returns ``EINVAL`` and preserves the event queue." +msgid "" +"netlink socket 的 ``SO_SNDBUF`` 和 ``SO_RCVBUF`` 默认有效大小均为 65536 字节。 " +"设置值按无符号整数裁剪到 65536 后乘二,发送和接收的最小有效值分别为 4608 和 2304 字节,查询返回有效大小。发送数据报同时受 " +"8192 字节硬上限及有效发送 缓冲区减 32 字节的限制,超过时返回 ``EMSGSIZE``。短设置值、错误用户指针和 " +"负长度返回错误并保留原设置。" +msgstr "" +"A netlink socket defaults to effective ``SO_SNDBUF`` and ``SO_RCVBUF`` " +"sizes of 65536 bytes each. Setters clamp the unsigned request to 65536 " +"before doubling it, with effective send and receive minima of 4608 and " +"2304 bytes. Getters return the effective size. A sent datagram must fit " +"both the 8192-byte hard limit and the effective send buffer minus 32 " +"bytes, otherwise it returns ``EMSGSIZE``. Short setter values, invalid " +"user pointers, and negative lengths return errors while preserving the " +"previous setting." -msgid "``NETLINK_KOBJECT_UEVENT`` 的网络设备事件按订阅 socket 的创建网络筛选。物理接口注册和移除分别发布 ``add`` 和 ``remove``,移除事件保留注册时的设备身份。sysfs 合成事件使用挂载捕获的网络,事件携带 action、设备路径、``SUBSYSTEM=net``、``INTERFACE`` 和 ``IFINDEX``,合成事件还携带 ``SYNTH_UUID``。其他网络的订阅者不会收到该网络事件,任务随后切换网络也保留已有 socket 的订阅范围。" -msgstr "Network device events on ``NETLINK_KOBJECT_UEVENT`` are filtered by each subscribing socket's creating network. Physical interface registration and removal publish ``add`` and ``remove`` respectively. Removal events preserve the device identity captured at registration. Synthetic sysfs events use the network captured by the mount. Events carry the action, device path, ``SUBSYSTEM=net``, ``INTERFACE`` and ``IFINDEX``, with synthetic events also carrying ``SYNTH_UUID``. Subscribers in other networks receive no such network event. Subsequent task network changes preserve the subscription scope of existing sockets." +msgid "" +"接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 位置。预留失败时返回 " +"``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 " +"属于实际 socket,传递 FD 或切换网络后继续保留。" +msgstr "" +"The receive queue conservatively charges 8192 bytes per datagram. " +"Multipart queries reserve two slots for data and the terminator. Failed " +"reservation returns ``ENOBUFS`` before the request changes network state." +" Shrinking the receive buffer preserves queued messages and new messages " +"wait for available capacity. Reading releases capacity, and growing the " +"buffer updates writability. Buffer settings belong to the actual socket " +"and survive FD transfer or a network switch." -msgid "block、PCI 和 DRM 已公开的设备 ``uevent`` 控制同样接受上述 action 与可选 UUID,权限和即时写入语义见 :doc:`abi`。事件属性取自同一设备的当前真实 inventory,``SUBSYSTEM`` 取自该设备的 ``subsystem`` 链接,并附带 ``SYNTH_UUID``。这些 global 设备事件仅投递给初始 user namespace 所拥有的网络空间中的订阅者,包含永久初始网络。网络设备事件继续严格按 socket 创建网络与挂载捕获网络隔离。" -msgstr "The published ``uevent`` controls for block, PCI and DRM devices accept the same actions and optional UUID. See :doc:`abi` for permissions and immediate-write semantics. Event properties come from the current real inventory of the same device. ``SUBSYSTEM`` comes from that device's ``subsystem`` link, and ``SYNTH_UUID`` is appended. These global device events reach subscribers only in network namespaces owned by the initial user namespace, including the permanent initial network. Network device events retain strict isolation by the socket's creating network and the mount's captured network." +msgid "" +"路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含" +" 被忽略的尾部;全部消息无效时不生成回复。预扫描和实际处理使用同一前缀边界。" +msgstr "" +"Route requests process the valid message prefix of a datagram in order, " +"ignoring the first malformed or incomplete message and all subsequent " +"bytes. The last complete message may omit alignment padding. A successful" +" send returns the entire datagram length, including the ignored tail. A " +"datagram with no valid messages generates no replies. Prescanning and " +"processing use the same prefix boundary." -msgid "``RTM_SETLINK`` 与 ``RTM_NEWLINK`` 在提供正接口索引和 ``IFLA_IFNAME`` 时执行重命名,索引为 0 时按名称选择已有接口。``SIOCSIFNAME`` 使用相同的创建网络与 ``CAP_NET_ADMIN`` 授权。重命名保留接口索引和 UP 状态,更新 ioctl、socket 设备绑定查询及 sysfs 名称,并发布同网络的 ``RTM_NEWLINK`` 与携带 ``DEVPATH_OLD`` 的 ``move`` 事件。名称最长 15 字节,空白、斜线、冒号、``.`` 和 ``..`` 返回 ``EINVAL``,同网络名称冲突返回 ``EEXIST``。单个 ``%d`` 模板选择 0 至 32767 内首个空闲编号,同名请求不发布事件。``name_assign_type`` 对枚举物理名称报告 1,重命名后报告 4。" -msgstr "``RTM_SETLINK`` and ``RTM_NEWLINK`` rename an interface when given a positive interface index and ``IFLA_IFNAME``. An index of 0 selects an existing interface by name. ``SIOCSIFNAME`` uses the same creating-network scope and ``CAP_NET_ADMIN`` authorization. Renaming preserves the interface index and UP state, updates ioctl, socket device-binding queries and sysfs names, and publishes a same-network ``RTM_NEWLINK`` and a ``move`` event carrying ``DEVPATH_OLD``. Names contain at most 15 bytes. Whitespace, slash, colon, ``.`` and ``..`` return ``EINVAL``, and a name collision in the same network returns ``EEXIST``. A single ``%d`` template selects the first free unit from 0 through 32767. A same-name request publishes no event. ``name_assign_type`` reports 1 for enumerated physical names and 4 after a rename." +msgid "" +"多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 " +"ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。" +msgstr "" +"Multipart query data and the terminating ``NLMSG_DONE`` marker are sent " +"as separate datagrams; the marker retains the request sequence number and" +" receiving port ID. A marker is sent even for an empty query result. " +"Receivers must still iterate all messages in each datagram until the " +"matching ``NLMSG_DONE`` or an error arrives." -msgid "packet socket 与链路接收" -msgstr "Packet sockets and link reception" +msgid "" +"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux" +" 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP、TCP 和 raw 表按调用者当前网络" +" scope 输出。快照复制出内部状态,跨等待仅保留副本。" +msgstr "" +"``/proc/net/if_inet6``, ``ipv6_route``, ``tcp6``, ``udp6`` and ``raw6`` " +"use Linux text layouts. Address scope encoding differs from rtnetlink " +"scope values. Address, route, UDP, TCP and raw tables follow the caller's" +" current network scope. Snapshots copy internal state and retain only " +"copies across waits." -msgid "``AF_PACKET`` 的 ``SO_ATTACH_FILTER`` 与 ``SO_DETACH_FILTER`` 复用 classic BPF 校验和执行器。过滤结果为 0 时丢弃报文,正值限制保留长度。替换失败保留旧过滤器。``bind()`` 的零 ``sll_protocol`` 保留创建时选择的协议。" -msgstr "``SO_ATTACH_FILTER`` and ``SO_DETACH_FILTER`` on ``AF_PACKET`` use the classic BPF validator and interpreter. A zero result drops the frame, and a positive result limits its retained length. Failed replacement preserves the previous filter. A zero ``sll_protocol`` in ``bind()`` retains the protocol selected at creation." +msgid "" +"raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 " +"``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD " +"后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。" +msgstr "" +"Raw IPv6 sockets independently retain their creating network. Creation " +"requires ``CAP_NET_RAW`` in that network's user owner. Address binding, " +"routing, delivery, multicast memberships, ICMPv6 errors, ping ID " +"conflicts and device options are isolated by creating network, including " +"after FD transfer. Final close leaves multicast in the original network " +"and releases references. Physical device removal reports errors only to " +"affected sockets in the initial network." -msgid "``SOL_PACKET`` 的 ``PACKET_ADD_MEMBERSHIP`` 与 ``PACKET_DROP_MEMBERSHIP`` 支持按创建网络、接口及六字节地址管理 ``PACKET_MR_MULTICAST``,重复加入按引用计数回收。最后关闭或设备移除释放订阅。额外链路组播按同网络、同接口的订阅执行软件接收筛选。当前其他成员类型返回 ``EINVAL``。" -msgstr "At ``SOL_PACKET``, ``PACKET_ADD_MEMBERSHIP`` and ``PACKET_DROP_MEMBERSHIP`` manage ``PACKET_MR_MULTICAST`` by creating network, interface and six-byte address. Duplicate joins are reference counted. Final close and device removal release subscriptions. Additional link multicast is admitted in software using subscriptions in the same network and interface. Other membership types currently return ``EINVAL``." +msgid "" +"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 " +"ICMP 错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host " +"route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态通过 " +"``clone()``、``clone3()`` 或 ``unshare()`` 的 ``CLONE_NEWNET`` 创建网络,通过 " +"``/proc//ns/net`` 句柄和 ``setns()`` 切换网络。授权与失败语义见 :doc:`abi`,内部生命周期与 " +"proc 范围见 :doc:`../core-api/mount-namespaces`。" +msgstr "" +"Each network namespace owns its interfaces, loopback, IPv4 routes, IPv6 " +"addresses and routes, neighbors, multicast state, pending packets, " +"fragment reassembly, PMTU, fragment IDs and ICMP error rate limits. A new" +" namespace starts with ``lo`` down and no IPv6 address. Its first " +"transition up configures ``::1/128`` and a host route. Tables and queues " +"account for capacity independently, and namespace destruction releases " +"protocol resources. Physical NIC registration and ingress remain in the " +"initial namespace. Userspace creates networks with ``CLONE_NEWNET`` in " +"``clone()``, ``clone3()`` or ``unshare()`` and switches through " +"``/proc//ns/net`` handles and ``setns()``. See :doc:`abi` for " +"authorization and failure semantics and :doc:`../core-api/mount-" +"namespaces` for lifetimes and proc scope." -msgid "``PACKET_AUXDATA`` 在 ``recvmsg()`` 返回 ``tpacket_auxdata``,包括过滤前长度、保留长度及链路偏移。RAW 报文的网络偏移为 14,DGRAM 为 0。``SO_TIMESTAMP_OLD`` 与 ``SO_TIMESTAMP_NEW`` 提供 realtime 微秒时间戳,排队时采样,接收前才启用时延迟采样,重复 ``MSG_PEEK`` 保留同一样本。输出内存准备失败保留队列,控制缓冲区不足设置 ``MSG_CTRUNC``。" -msgstr "``PACKET_AUXDATA`` returns ``tpacket_auxdata`` through ``recvmsg()``, including the pre-filter length, retained length and link offsets. The network offset is 14 for RAW frames and 0 for DGRAM frames. ``SO_TIMESTAMP_OLD`` and ``SO_TIMESTAMP_NEW`` provide realtime microsecond timestamps sampled at enqueue, or lazily when enabled after arrival. Repeated ``MSG_PEEK`` retains the same sample. Output-memory preparation failure preserves the queue, and insufficient control space sets ``MSG_CTRUNC``." +msgid "网络 sysfs 与设备事件" +msgstr "Network sysfs and Device Events" -msgid "UDP 和 packet socket 的 ``SO_PRIORITY`` 保存有符号整数优先级,默认 0。0 至 6 可直接设置,其他值需要 socket 创建网络 user owner 的 ``CAP_NET_RAW`` 或 ``CAP_NET_ADMIN``。用户内存或权限检查失败保留原值。" -msgstr "``SO_PRIORITY`` on UDP and packet sockets stores a signed integer priority, initially 0. Values from 0 through 6 can be set directly. Other values require ``CAP_NET_RAW`` or ``CAP_NET_ADMIN`` in the user owner of the socket creation network. Failed user-memory or permission checks preserve the previous value." +msgid "" +"sysfs 挂载保留创建时捕获的网络空间,后续 lookup、readdir、read 和 write 均使用该视图。任务执行 " +"``setns()``、``unshare()`` 或传递挂载句柄后,已有挂载继续观察原网络。``fsopen(\"sysfs\")`` 的网络与" +" owner 捕获及 CREATE 授权见 :doc:`abi`。" +msgstr "" +"A sysfs mount retains the network namespace captured at creation. " +"Subsequent lookup, readdir, read and write operations use that view. " +"Existing mounts continue to observe the original network after a task " +"calls ``setns()`` or ``unshare()`` or passes a mount handle. See " +":doc:`abi` for network and owner capture by ``fsopen(\"sysfs\")`` and " +"CREATE authorization." -msgid "UDP 的 ``IP_TOS`` 默认 0,保存输入低八位并写入实际 IPv4 首部,包含 DSCP 和 ECN 位。TOS 变化同时按 Linux 的 TOS 映射更新 socket 优先级。``IP_FREEBIND`` 默认关闭,开启后允许绑定尚未配置的 IPv4 地址及 IPv4 映射地址。端口冲突、设备绑定、特权端口授权和创建网络范围仍按原规则检查,发送继续要求有效路由。" -msgstr "UDP ``IP_TOS`` defaults to 0 and stores the low eight input bits in the actual IPv4 header, including DSCP and ECN. A TOS change also updates socket priority using the Linux TOS mapping. ``IP_FREEBIND`` defaults to disabled and permits binding unconfigured IPv4 and IPv4-mapped addresses when enabled. Port conflicts, device bindings, privileged-port authorization and the creating-network scope retain their checks. Sending still requires a valid route." +msgid "" +"``/sys/class/net/`` 是指向 canonical 设备节点的符号链接。loopback 位于 " +"``/sys/devices/virtual/net/lo``,物理接口位于对应 PCI function 下的 " +"``net/``,``device`` 链接指向 PCI 父节点,``subsystem`` 链接指向 " +"``/sys/class/net``。属性包含 " +"``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier``" +" 和 ``uevent``。物理接口仅在初始网络中可见。接口移除后,持有的旧 inode 在重新打开、读取或写入时返回 ``ENOENT``。" +msgstr "" +"``/sys/class/net/`` is a symbolic link to the canonical device " +"node. Loopback resides at ``/sys/devices/virtual/net/lo``. A physical " +"interface resides at ``net/`` below its PCI function, with " +"``device`` linking to the PCI parent and ``subsystem`` linking to " +"``/sys/class/net``. Attributes include ``ifindex``, ``iflink``, " +"``address``, ``broadcast``, ``type``, ``mtu``, ``flags``, ``operstate``, " +"``carrier`` and ``uevent``. Physical interfaces are visible only in the " +"initial network. After interface removal, reopening, reading or writing a" +" retained old inode returns ``ENOENT``." + +#, python-format +msgid "" +"``RTM_SETLINK`` 与 ``RTM_NEWLINK`` 在提供正接口索引和 ``IFLA_IFNAME`` 时执行重命名,索引为 0 " +"时按名称选择已有接口。``SIOCSIFNAME`` 使用相同的创建网络与 ``CAP_NET_ADMIN`` 授权。重命名保留接口索引和 UP " +"状态,更新 ioctl、socket 设备绑定查询及 sysfs 名称,并发布同网络的 ``RTM_NEWLINK`` 与携带 " +"``DEVPATH_OLD`` 的 ``move`` 事件。名称最长 15 字节,空白、斜线、冒号、``.`` 和 ``..`` 返回 " +"``EINVAL``,同网络名称冲突返回 ``EEXIST``。单个 ``%d`` 模板选择 0 至 32767 " +"内首个空闲编号,同名请求不发布事件。``name_assign_type`` 对枚举物理名称报告 1,重命名后报告 4。" +msgstr "" +"``RTM_SETLINK`` and ``RTM_NEWLINK`` rename an interface when given a " +"positive interface index and ``IFLA_IFNAME``. An index of 0 selects an " +"existing interface by name. ``SIOCSIFNAME`` uses the same creating-" +"network scope and ``CAP_NET_ADMIN`` authorization. Renaming preserves the" +" interface index and UP state, updates ioctl, socket device-binding " +"queries and sysfs names, and publishes a same-network ``RTM_NEWLINK`` and" +" a ``move`` event carrying ``DEVPATH_OLD``. Names contain at most 15 " +"bytes. Whitespace, slash, colon, ``.`` and ``..`` return ``EINVAL``, and " +"a name collision in the same network returns ``EEXIST``. A single ``%d`` " +"template selects the first free unit from 0 through 32767. A same-name " +"request publishes no event. ``name_assign_type`` reports 1 for enumerated" +" physical names and 4 after a rename." -msgid "UDP 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 返回 realtime 微秒时间戳,支持原生 IPv4、IPv6 和 IPv4 映射报文。启用时在入队采样,接收前才启用则在首次接收时采样。``MSG_PEEK`` 和切换时间戳格式保留已有样本,关闭选项后停止交付时间戳。时间戳通过 ``SOL_SOCKET`` 辅助消息返回,可与 IP packet info 和 TTL 同时使用。输出内存准备失败保留队列,控制区不足设置 ``MSG_CTRUNC``。" -msgstr "UDP ``SO_TIMESTAMP_OLD`` and ``SO_TIMESTAMP_NEW`` return realtime microsecond timestamps for native IPv4, IPv6 and IPv4-mapped datagrams. Enabled sockets sample at enqueue. Enabling after arrival samples at the first receive. ``MSG_PEEK`` and timestamp-format changes retain the sample. Disabling stops timestamp delivery. ``SOL_SOCKET`` ancillary messages carry timestamps alongside IP packet information and TTL. Output-memory preparation failure preserves the queue, and insufficient control space sets ``MSG_CTRUNC``." +msgid "" +"网络 ``uevent`` 文件由 root 所有,模式为 0644,写入遵循常规 DAC 与挂载只读策略。只读挂载也阻止 root " +"写入。读取提供 ``INTERFACE`` 和 ``IFINDEX``。写入接受 " +"``add``、``remove``、``change``、``move``、``online``、``offline``、``bind`` 或 " +"``unbind``,可在一个空格后附加 36 字符的十六进制 UUID,连字符位于标准位置,末尾可带一个换行。无 UUID 时事件使用 " +"``SYNTH_UUID=0``,提供 UUID 时按输入传递。无效 action、UUID 或 embedded NUL 返回 " +"``EINVAL``,并保持事件队列不变。" +msgstr "" +"Network ``uevent`` files are root-owned with mode 0644. Writes follow " +"normal DAC and mount readonly policy. Readonly mounts also prevent root " +"writes. Reads provide ``INTERFACE`` and ``IFINDEX``. Writes accept " +"``add``, ``remove``, ``change``, ``move``, ``online``, ``offline``, " +"``bind`` or ``unbind``, optionally followed by one space and a " +"36-character hexadecimal UUID with hyphens in the standard positions. One" +" trailing newline is allowed. Events without a UUID use ``SYNTH_UUID=0``." +" A supplied UUID is passed through as entered. An invalid action, UUID or" +" embedded NUL returns ``EINVAL`` and preserves the event queue." -msgid "UDP 的 ``IP_UNICAST_IF`` 和 ``IPV6_UNICAST_IF`` 分别保存 IPv4 和 IPv6 的默认单播出口。设置与查询均使用网络字节序的 32 位接口索引,设置长度必须恰好为 4 字节。0 清除配置,非零索引必须存在于 socket 创建网络中,否则返回 ``EADDRNOTAVAIL``。已有设备绑定时设置非零索引返回 ``EINVAL``。普通用户可设置这些选项,接收筛选继续使用原有设备绑定。消息级接口、显式 scope 和设备绑定优先于默认单播出口;IPv4 映射发送使用 IPv4 配置。" -msgstr "UDP ``IP_UNICAST_IF`` and ``IPV6_UNICAST_IF`` retain separate default IPv4 and IPv6 unicast output interfaces. Setters and getters use a network-byte-order 32-bit interface index, and setters require exactly four bytes. Zero clears the setting. A nonzero index must exist in the socket's creating network, otherwise the setter returns ``EADDRNOTAVAIL``. Setting a nonzero index on a device-bound socket returns ``EINVAL``. Ordinary users can set these options. Receive filtering continues to use the existing device binding. Per-message interfaces, explicit scope and device binding take precedence over the default unicast interface. IPv4-mapped output uses the IPv4 setting." +msgid "" +"``NETLINK_KOBJECT_UEVENT`` 的网络设备事件按订阅 socket 的创建网络筛选。物理接口注册和移除分别发布 " +"``add`` 和 ``remove``,移除事件保留注册时的设备身份。sysfs 合成事件使用挂载捕获的网络,事件携带 " +"action、设备路径、``SUBSYSTEM=net``、``INTERFACE`` 和 ``IFINDEX``,合成事件还携带 " +"``SYNTH_UUID``。其他网络的订阅者不会收到该网络事件,任务随后切换网络也保留已有 socket 的订阅范围。" +msgstr "" +"Network device events on ``NETLINK_KOBJECT_UEVENT`` are filtered by each " +"subscribing socket's creating network. Physical interface registration " +"and removal publish ``add`` and ``remove`` respectively. Removal events " +"preserve the device identity captured at registration. Synthetic sysfs " +"events use the network captured by the mount. Events carry the action, " +"device path, ``SUBSYSTEM=net``, ``INTERFACE`` and ``IFINDEX``, with " +"synthetic events also carrying ``SYNTH_UUID``. Subscribers in other " +"networks receive no such network event. Subsequent task network changes " +"preserve the subscription scope of existing sockets." -msgid "UDP 扩展错误队列" -msgstr "UDP Extended Error Queue" +msgid "" +"block、PCI 和 DRM 已公开的设备 ``uevent`` 控制同样接受上述 action 与可选 UUID,权限和即时写入语义见 " +":doc:`abi`。事件属性取自同一设备的当前真实 inventory,``SUBSYSTEM`` 取自该设备的 ``subsystem`` " +"链接,并附带 ``SYNTH_UUID``。这些 global 设备事件仅投递给初始 user namespace " +"所拥有的网络空间中的订阅者,包含永久初始网络。网络设备事件继续严格按 socket 创建网络与挂载捕获网络隔离。" +msgstr "" +"The published ``uevent`` controls for block, PCI and DRM devices accept " +"the same actions and optional UUID. See :doc:`abi` for permissions and " +"immediate-write semantics. Event properties come from the current real " +"inventory of the same device. ``SUBSYSTEM`` comes from that device's " +"``subsystem`` link, and ``SYNTH_UUID`` is appended. These global device " +"events reach subscribers only in network namespaces owned by the initial " +"user namespace, including the permanent initial network. Network device " +"events retain strict isolation by the socket's creating network and the " +"mount's captured network." -msgid "``IP_RECVERR`` 和 ``IPV6_RECVERR`` 默认关闭。启用后,经过校验的 IPv4 ICMP 或 ICMPv6 错误按 socket 创建网络、接口及原始 UDP 地址和端口关联到独立错误队列。记录保存 ``sock_extended_err`` 的 errno、origin、type、code 和 MTU,以及错误发送者、原始目的地址和被引用的 UDP 载荷。IPv4 映射 socket 返回原生 IPv6 地址布局。" -msgstr "``IP_RECVERR`` and ``IPV6_RECVERR`` default to disabled. When enabled, validated IPv4 ICMP and ICMPv6 errors are matched to an independent error queue using the socket's creating network, interface, and original UDP addresses and ports. Records retain the errno, origin, type, code and MTU in ``sock_extended_err``, the offender, original destination and quoted UDP payload. IPv4-mapped sockets return native IPv6 address layouts." +msgid "范围与标准" +msgstr "Scope and Standards" -msgid "``recvmsg(MSG_ERRQUEUE)`` 通过 ``msg_name`` 返回原始目的地址,通过 ``SOL_IP/IP_RECVERR`` 或 ``SOL_IPV6/IPV6_RECVERR`` 辅助消息返回扩展错误及其发送者,并设置输出 ``MSG_ERRQUEUE``。队列为空时立即返回 ``EAGAIN``,设置 ``MSG_PEEK`` 仍消费该条错误。载荷和控制区不足分别报告 ``MSG_TRUNC`` 和 ``MSG_CTRUNC``。用户输出内存准备失败保留记录,成功读取后按下一条错误更新待处理 errno。" -msgstr "``recvmsg(MSG_ERRQUEUE)`` returns the original destination in ``msg_name`` and the extended error and offender in a ``SOL_IP/IP_RECVERR`` or ``SOL_IPV6/IPV6_RECVERR`` control message, setting output ``MSG_ERRQUEUE``. An empty queue immediately returns ``EAGAIN``. ``MSG_PEEK`` still consumes the error record. Insufficient payload and control capacity report ``MSG_TRUNC`` and ``MSG_CTRUNC`` respectively. Failed user-output preparation preserves the record. Successful reads update the pending errno from the next error." +msgid "" +"这是 IPv6 主机实现,不提供 IPv6 路由转发、IPsec、MLDv2 源特定组播过滤或 Redirect 路由更新。DNS " +"策略、RDNSS 和 DHCPv6 客户端属于用户态。接收和发送 缓存有资源上限,资源不足返回错误;并不宣称覆盖 Linux 的全部网络功能或全部" +" IPv6 扩展。" +msgstr "" +"This is an IPv6 host implementation. It does not provide IPv6 " +"routing/forwarding, IPsec, MLDv2 source-specific multicast filtering, or " +"Redirect route updates. DNS policy, RDNSS, and DHCPv6 clients belong in " +"userspace. Receive and send buffers have resource limits, and resource " +"exhaustion returns errors. No claim is made to cover all Linux networking" +" features or all IPv6 extensions." -msgid "错误记录与普通数据报分别持有存储,待处理 errno 或错误队列可触发 ``POLLERR``。查询 ``SO_ERROR`` 清除待处理 errno,已排队记录继续可读。关闭相应 RECVERR 选项会清空错误队列,保留普通数据和待处理 errno。分配失败或队列达到上限时保留已有记录并继续报告 socket 错误。最后关闭释放全部记录及创建网络引用。" -msgstr "Error records and ordinary datagrams own separate storage. A pending errno or queued error can trigger ``POLLERR``. Reading ``SO_ERROR`` clears the pending errno while queued records remain readable. Disabling the corresponding RECVERR option clears the error queue while retaining ordinary data and the pending errno. Allocation failure or a full queue preserves existing records and continues to report the socket error. Final close releases all records and the creating-network reference." +msgid "" +"依据 RFC 8200、4291、4443、4861、4862、8201、3493、3542 以及 Linux " +"``ipv6(7)``、``rtnetlink(7)``。POSIX 规定应用接口,线上 IPv6 协议细节由 相应 IETF " +"标准规定。宿主定向测试与完整系统 VM 测试是不同证据;VMware 和 真实硬件结果不能由 QEMU 结果替代。" +msgstr "" +"Based on RFC 8200, 4291, 4443, 4861, 4862, 8201, 3493, and 3542, and " +"Linux ``ipv6(7)`` and ``rtnetlink(7)``. POSIX specifies application " +"interfaces; the corresponding IETF standards specify IPv6 wire protocol " +"details. Targeted host tests and full-system VM tests provide different " +"evidence; QEMU results cannot replace VMware or physical hardware " +"results." diff --git a/Documentation/locale/ja/LC_MESSAGES/admin-guide/boot.po b/Documentation/locale/ja/LC_MESSAGES/admin-guide/boot.po index f1e5af1d..73979ba6 100644 --- a/Documentation/locale/ja/LC_MESSAGES/admin-guide/boot.po +++ b/Documentation/locale/ja/LC_MESSAGES/admin-guide/boot.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "启动契约" msgstr "起動契約" @@ -20,20 +23,23 @@ msgid "固件与交接" msgstr "ファームウェアと引き渡し" msgid "" -"同一 kernel.sys 包含 Multiboot2 BIOS 32 位入口与 EFI64 入口。 BIOS 入口检查 CPU 能力、建立页表与栈后进入共享 64 位内核。 " -"解析交接数据时检查边界、对齐、长度和溢出;EFI 信息指针保留完整宽度。 固件、GRUB 与模块载荷需满足该协议,本仓不生成 ISO 或安装引导器。" +"同一 kernel.sys 包含 Multiboot2 BIOS 32 位入口与 EFI64 入口。 BIOS 入口检查 CPU " +"能力、建立页表与栈后进入共享 64 位内核。 解析交接数据时检查边界、对齐、长度和溢出;EFI 信息指针保留完整宽度。 固件、GRUB " +"与模块载荷需满足该协议,本仓不生成 ISO 或安装引导器。" msgstr "" -"同じ kernel.sys に Multiboot2 BIOS の 32 ビットエントリーと EFI64 エントリーを含みます。BIOS エントリーは CPU " -"機能を確認し、ページテーブルとスタックを構築してから共通の 64 ビットカーネルに入ります。引き渡しデータの解析では境界、アラインメント、長さ、オーバーフローを検査し、EFI " -"情報のポインターは全ビット幅を保持します。ファームウェア、GRUB、モジュールのペイロードはこのプロトコルを満たす必要があります。このリポジトリーでは ISO " -"の生成やブートローダーのインストールは行いません。" +"同じ kernel.sys に Multiboot2 BIOS の 32 ビットエントリーと EFI64 エントリーを含みます。BIOS " +"エントリーは CPU 機能を確認し、ページテーブルとスタックを構築してから共通の 64 " +"ビットカーネルに入ります。引き渡しデータの解析では境界、アラインメント、長さ、オーバーフローを検査し、EFI " +"情報のポインターは全ビット幅を保持します。ファームウェア、GRUB、モジュールのペイロードはこのプロトコルを満たす必要があります。このリポジトリーでは" +" ISO の生成やブートローダーのインストールは行いません。" msgid "根分区" msgstr "ルートパーティション" msgid "" -"设备发现后解析显式 ``root=PARTUUID=...``,匹配唯一 GPT 分区身份。 畸形、缺失或重复请求拒绝自动回退;连接顺序不能替代指定身份。 " -"旧自动发现行为与显式选择是不同路线。内核映像和引导模块的内存范围 在物理内存管理初始化前保留,不能当作可重用空闲页。" +"设备发现后解析显式 ``root=PARTUUID=...``,匹配唯一 GPT 分区身份。 " +"畸形、缺失或重复请求拒绝自动回退;连接顺序不能替代指定身份。 旧自动发现行为与显式选择是不同路线。内核映像和引导模块的内存范围 " +"在物理内存管理初始化前保留,不能当作可重用空闲页。" msgstr "" "デバイス検出後、明示された ``root=PARTUUID=...`` を解析し、一意の GPT " "パーティション識別情報と照合します。不正、欠落、重複した要求では自動フォールバックを拒否し、接続順序で指定された識別情報を代用することはできません。従来の自動検出と明示的な選択は別の経路です。カーネルイメージと起動モジュールが占めるメモリー範囲は、物理メモリー管理の初期化前に予約し、再利用可能な空きページとして扱ってはなりません。" @@ -41,14 +47,55 @@ msgstr "" msgid "日志" msgstr "ログ" -msgid "内核日志使用 ``[启动后秒数] [等级] [组件] 消息`` 格式。默认保留 INFO、WARN、ERROR 和 FATAL。常见的进程启动、退出、回收及硬件缺席记录仅在 DEBUG 下输出。``debug`` 或 ``loglevel=8`` 开启 DEBUG,``quiet`` 等效于 ``loglevel=4``。``loglevel=N`` 接受 0–8,输出优先级数值小于 N 的记录。FATAL 和 panic 始终保留紧急输出。" -msgstr "カーネルログは ``[起動後の秒数] [レベル] [コンポーネント] メッセージ`` の形式を使用します。既定では INFO、WARN、ERROR、FATAL が有効です。通常のプロセス起動、終了、回収、およびハードウェア未検出の記録は DEBUG で確認できます。``debug`` または ``loglevel=8`` で DEBUG を有効にできます。``quiet`` は ``loglevel=4`` と同等です。``loglevel=N`` は 0–8 を受け付け、数値が N 未満の優先度を出力します。FATAL と panic の緊急出力は常に有効です。" +msgid "" +"内核日志使用 ``[启动后秒数] [等级] [组件] 消息`` 格式。默认保留 INFO、WARN、ERROR 和 " +"FATAL。常见的进程启动、退出、回收及硬件缺席记录仅在 DEBUG 下输出。``debug`` 或 ``loglevel=8`` 开启 " +"DEBUG,``quiet`` 等效于 ``loglevel=4``。``loglevel=N`` 接受 0–8,输出优先级数值小于 N " +"的记录。FATAL 和 panic 始终保留紧急输出。" +msgstr "" +"カーネルログは ``[起動後の秒数] [レベル] [コンポーネント] メッセージ`` の形式を使用します。既定では " +"INFO、WARN、ERROR、FATAL が有効です。通常のプロセス起動、終了、回収、およびハードウェア未検出の記録は DEBUG " +"で確認できます。``debug`` または ``loglevel=8`` で DEBUG を有効にできます。``quiet`` は " +"``loglevel=4`` と同等です。``loglevel=N`` は 0–8 を受け付け、数値が N 未満の優先度を出力します。FATAL " +"と panic の緊急出力は常に有効です。" -msgid "``log=screen,serial`` 是默认值。可用 ``log=screen`` 或 ``log=serial`` 只选一个日志目标,也可用 ``log=none`` 关闭常规内核日志。``logcolor=0`` 关闭普通日志颜色。``bootlog-pause=1`` 在启动检查点等待输入。``syscall-trace=/path/prefix`` 为匹配的程序启用系统调用诊断。" -msgstr "既定は ``log=screen,serial`` です。``log=screen`` または ``log=serial`` で出力先を一つに絞り、``log=none`` で通常のカーネルログを無効にできます。``logcolor=0`` で通常のログの色を無効にします。``bootlog-pause=1`` は起動中のチェックポイントで入力を待ちます。``syscall-trace=/path/prefix`` は該当するプログラムのシステムコール診断を有効にします。" +msgid "" +"``log=screen,serial`` 是默认值。可用 ``log=screen`` 或 ``log=serial`` " +"只选一个日志目标,也可用 ``log=none`` 关闭常规内核日志。``logcolor=0`` 关闭普通日志颜色。``bootlog-" +"pause=1`` 在启动检查点等待输入。``syscall-trace=/path/prefix`` 为匹配的程序启用系统调用诊断。" +msgstr "" +"既定は ``log=screen,serial`` です。``log=screen`` または ``log=serial`` " +"で出力先を一つに絞り、``log=none`` で通常のカーネルログを無効にできます。``logcolor=0`` で通常のログの色を無効にします" +"。``bootlog-pause=1`` は起動中のチェックポイントで入力を待ちます。``syscall-trace=/path/prefix``" +" は該当するプログラムのシステムコール診断を有効にします。" -msgid "COM1 使用 115200 波特、8N1。早期启动和 panic 使用有界轮询。进入用户态后,内核日志和控制台镜像进入 32 KiB 发送队列,由 IRQ4 批量填充 UART FIFO,定时器负责兜底。队列为 WARN 和 ERROR 预留空间。积压清空后,串口报告丢弃的日志和控制台镜像数量。直接写入 ``/dev/ttyS0`` 时,阻塞写等待可用空间,非阻塞写在无法接收任何字节时返回 ``EAGAIN``。关闭或重启系统前会尝试发送队列中的数据。" -msgstr "COM1 は 115200 ボー、8N1 を使用します。起動初期と panic では上限付きのポーリングを使います。ユーザー空間に移行すると、カーネルログとコンソールの複製は 32 KiB の送信キューに入ります。IRQ4 が UART FIFO にまとめて書き込み、タイマーはその補助を行います。キューには WARN と ERROR 用の領域を確保します。滞留データの送信後、破棄したログとコンソール出力の件数をシリアルに出力します。``/dev/ttyS0`` のブロッキング書き込みは空き領域を待ちます。ノンブロッキング書き込みで入力を 1 バイトも受け付けられない場合は ``EAGAIN`` を返します。シャットダウンと再起動の前に送信キューの排出を試みます。" +msgid "" +"COM1 使用 115200 波特、8N1。早期启动和 panic 使用有界轮询。进入用户态后,内核日志和控制台镜像进入 32 KiB " +"发送队列,由 IRQ4 批量填充 UART FIFO,定时器负责兜底。队列为 WARN 和 ERROR " +"预留空间。积压清空后,串口报告丢弃的日志和控制台镜像数量。直接写入 ``/dev/ttyS0`` " +"时,阻塞写等待可用空间,非阻塞写在无法接收任何字节时返回 ``EAGAIN``。关闭或重启系统前会尝试发送队列中的数据。" +msgstr "" +"COM1 は 115200 ボー、8N1 を使用します。起動初期と panic " +"では上限付きのポーリングを使います。ユーザー空間に移行すると、カーネルログとコンソールの複製は 32 KiB の送信キューに入ります。IRQ4 が" +" UART FIFO にまとめて書き込み、タイマーはその補助を行います。キューには WARN と ERROR " +"用の領域を確保します。滞留データの送信後、破棄したログとコンソール出力の件数をシリアルに出力します。``/dev/ttyS0`` " +"のブロッキング書き込みは空き領域を待ちます。ノンブロッキング書き込みで入力を 1 バイトも受け付けられない場合は ``EAGAIN`` " +"を返します。シャットダウンと再起動の前に送信キューの排出を試みます。" -msgid "文字控制台使用现有 framebuffer 字形、pitch 和原生 RGB 转换,可处理带行间填充的帧缓冲。" -msgstr "テキストコンソールは既存のフレームバッファーのグリフ、ピッチ、およびネイティブ RGB 変換を使用し、行パディングのあるフレームバッファーに対応します。" +msgid "" +"文字控制台使用现有 framebuffer 字形、pitch 和原生 RGB 转换,可处理带行间填充的帧缓冲。 " +"可见文本在普通内存中绘制、滚动并更新光标,随后只向显存写入变动区域。 分配失败时使用直接绘制。panic 使用直接绘制以避免进入常规显示锁。" +msgstr "" +"テキストコンソールは既存のフレームバッファの字形、ピッチ、ネイティブ RGB " +"変換を使用し、各走査線のパディングにも対応します。通常メモリで文字描画、スクロール、カーソル更新を行い、変更箇所だけをビデオメモリへ転送します。メモリ確保に失敗した場合や、panic" +" 時に通常の表示ロックを避ける場合は直接描画します。" + +msgid "" +"当 ``reliefos.direct_root=1`` 与明确的 ``root=PARTUUID=...`` 同时存在时, " +"内核优先尝试用内置驱动挂载 ext4 根。成功后直接执行真实根的 init, 把 ESP 和 ``/boot`` 的挂载交给用户态。无法挂载指定 " +"ext4 根时加载预置 initramfs。未设置该选项时采用常规启动顺序。" +msgstr "" +"``reliefos.direct_root=1`` と明示的な ``root=PARTUUID=...`` " +"がある場合、カーネルはまず組み込みドライバーで ext4 ルートのマウントを試みます。成功後は実ルートの init を直接実行し、ESP と " +"``/boot`` のマウントをユーザー空間に任せます。直接マウントに失敗した場合は準備済み initramfs " +"を使用します。指定がなければ通常の起動順序で動作します。" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po index 99520bed..7379c50c 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/network-devices.po @@ -4,24 +4,28 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0800\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "Multiple network devices" msgstr "複数のネットワークデバイス" msgid "" -"ReliefNT 为每个受支持的 Ethernet PCI 功能分配独立网络接口。e1000、e1000e、 i225、r8169、rtl8139 和 vmxnet3 " -"可以同时注册,多张相同型号网卡也分别拥有设备状态和 DMA 环。" +"ReliefNT 为每个受支持的 Ethernet PCI 功能分配独立网络接口。e1000、e1000e、 i225、r8169、rtl8139" +" 和 vmxnet3 可以同时注册,多张相同型号网卡也分别拥有设备状态和 DMA 环。" msgstr "" -"ReliefNT は対応する Ethernet PCI 機能ごとに独立したネットワークインターフェースを割り当てます。e1000、e1000e、i225、r8169、rtl8139、vmxnet3" -" を同時に登録でき、同型カードが複数あってもデバイス状態と DMA リングは個別に管理されます。" +"ReliefNT は対応する Ethernet PCI " +"機能ごとに独立したネットワークインターフェースを割り当てます。e1000、e1000e、i225、r8169、rtl8139、vmxnet3 " +"を同時に登録でき、同型カードが複数あってもデバイス状態と DMA リングは個別に管理されます。" msgid "Device identity" msgstr "デバイスの識別" @@ -32,15 +36,16 @@ msgid "" "eth2 继续使用原来的编号。 重新加载驱动时,新设备获得新的索引和名称。" msgstr "" "``lo`` の ifindex は 1 です。ハードウェアインターフェースは ifindex 2 から順に増加し、名前は " -"``eth`` です。インターフェースは 1 回の起動中に名前とインデックスを維持し、削除後はインデックスの欠番を残します。例えば" -" eth0、eth1 を所有するドライバーをアンロードしても、残る eth2 " +"``eth`` です。インターフェースは 1 " +"回の起動中に名前とインデックスを維持し、削除後はインデックスの欠番を残します。例えば eth0、eth1 " +"を所有するドライバーをアンロードしても、残る eth2 " "は元の番号を使い続けます。ドライバーを再ロードすると、新しいデバイスには新しいインデックスと名前を割り当てます。" msgid "" "私有 ``include/reliefnt/net_device.h`` 的 ``driver_register_netdev`` 接收 " "版本化回调表、每设备上下文和索引输出。管理器复制回调表,将其与原驱动 owner 绑定,回调前固定 " -"owner,释放服务锁后执行回调。初始化成功后发布接口。 驱动关闭回调接入、排空引用并停止自身全部设备后,管理器移除对应接口。 停止失败的设备保留 " -"DMA 和模块代码,后续卸载可以重试。" +"owner,释放服务锁后执行回调。初始化成功后发布接口。 驱动关闭回调接入、排空引用并停止自身全部设备后,管理器移除对应接口。 停止失败的设备保留" +" DMA 和模块代码,后续卸载可以重试。" msgstr "" "非公開の ``include/reliefnt/net_device.h`` の ``driver_register_netdev`` " "は、バージョン付きコールバックテーブル、デバイスごとのコンテキスト、インデックス出力を受け取ります。manager " @@ -48,12 +53,20 @@ msgstr "" "を保持し、サービスロック解放後にコールバックを実行します。初期化成功後にインターフェースを公開します。ドライバーがコールバックの受け入れを閉じ、参照の解消を待ち、自身の全デバイスを停止すると、manager" " が対応するインターフェースを削除します。停止に失敗したデバイスは DMA とモジュールコードを保持し、後のアンロードで再試行できます。" +msgid "" +"e1000 和 e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO " +"寄存器。e1000e 发送前另行检查当前链路。收包轮询和协议定时器照常运行。" +msgstr "" +"e1000 と e1000e はデバイスおよびクロック tick ごとにリンク状態の測定結果を再利用し、同じ MMIO " +"レジスターの連続読み取りを避けます。e1000e は送信前にも現在のリンクを確認します。受信ポーリングとプロトコルタイマーは通常どおり動作します。" + msgid "" "旧 ``e1000_*`` 服务入口和 ReliefOS 旧网络管理请求查询首个存活接口。 旧驱动 API " "表和公开用户结构继续使用原布局。新设备接口属于 ReliefNT 私有 内核接口,原生模块通过精确构建 ABI 关联。" msgstr "" -"従来の ``e1000_*`` サービスエントリーと ReliefOS の旧ネットワーク管理要求は、最初の存続インターフェースを照会します。旧ドライバー" -" API テーブルと公開ユーザー構造体は元のレイアウトを維持します。新しいデバイスインターフェースは ReliefNT " +"従来の ``e1000_*`` サービスエントリーと ReliefOS " +"の旧ネットワーク管理要求は、最初の存続インターフェースを照会します。旧ドライバー API " +"テーブルと公開ユーザー構造体は元のレイアウトを維持します。新しいデバイスインターフェースは ReliefNT " "非公開のカーネルインターフェースで、ネイティブモジュールは厳密に一致するビルド ABI で関連付けられます。" msgid "Configuration and routing" @@ -61,42 +74,156 @@ msgstr "構成と経路選択" msgid "" "每张网卡拥有独立的行政状态、IPv4 地址、掩码、广播地址和默认网关。 IPv4 路由优先使用最长前缀,再比较 metric " -"和接口索引。绑定本机源地址和 ``SO_BINDTODEVICE`` 的 socket 按其约束选路。ARP 缓存按接口和下一跳地址 区分。TCP " -"路由变化时重新检查下一跳 MAC,向本机 NIC 地址发送的 TCP、UDP 保留目标接口身份。" +"和接口索引。绑定本机源地址和 ``SO_BINDTODEVICE`` 的 socket 按其约束选路。ARP 缓存按接口和下一跳地址 区分。TCP" +" 路由变化时重新检查下一跳 MAC,向本机 NIC 地址发送的 TCP、UDP 保留目标接口身份。" msgstr "" "各アダプターは独立した管理状態、IPv4 アドレス、ネットマスク、ブロードキャストアドレス、デフォルトゲートウェイを持ちます。IPv4 " "経路は最長プレフィックスを優先し、次に metric とインターフェースインデックスを比較します。ローカル送信元アドレスや " "``SO_BINDTODEVICE`` にバインドした socket は、その制約に従って経路を選びます。ARP " -"キャッシュはインターフェースと次ホップアドレスで区別します。TCP は経路変更時に次ホップの MAC を再確認し、ローカル NIC アドレス宛ての " -"TCP、UDP は宛先インターフェースの識別情報を保持します。" +"キャッシュはインターフェースと次ホップアドレスで区別します。TCP は経路変更時に次ホップの MAC を再確認し、ローカル NIC アドレス宛ての" +" TCP、UDP は宛先インターフェースの識別情報を保持します。" msgid "" -"IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 按网络空间隔离,并携带该空间的 ifindex。逐链路状态通过动态分配管理,RA、RS、DAD、MLD " -"和发现定时分别推进。不同链路可以使用相同 link-local 地址,socket 的作用域与设备绑定须一致。IPv6 表和队列的容量按网络空间分别计量,耗尽时返回错误。" +"IPv6 地址、路由、邻居、多播成员、待发包、重组和 PMTU 按网络空间隔离,并携带该空间的 " +"ifindex。逐链路状态通过动态分配管理,RA、RS、DAD、MLD 和发现定时分别推进。不同链路可以使用相同 link-local " +"地址,socket 的作用域与设备绑定须一致。IPv6 表和队列的容量按网络空间分别计量,耗尽时返回错误。" msgstr "" "IPv6 アドレス、経路、近隣、多播メンバー、送信待ちパケット、再構成、PMTU はネットワーク名前空間ごとに分離し、その空間の ifindex " -"を保持します。リンクごとの状態は動的に確保し、RA、RS、DAD、MLD、探索の時刻を個別に進めます。異なるリンクは同じ link-local アドレスを使用でき、socket の " -"scope とデバイス束縛は一致する必要があります。IPv6 テーブルとキューの容量はネットワークごとに計量し、枯渇時にはエラーを返します。" +"を保持します。リンクごとの状態は動的に確保し、RA、RS、DAD、MLD、探索の時刻を個別に進めます。異なるリンクは同じ link-local " +"アドレスを使用でき、socket の scope とデバイス束縛は一致する必要があります。IPv6 " +"テーブルとキューの容量はネットワークごとに計量し、枯渇時にはエラーを返します。" -msgid "Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及行政状态开关。查询使用 socket 创建时保留的网络,接口配置修改需要该网络 user owner 的 ``CAP_NET_ADMIN``。首次设置 ``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要该 owner 的 ``CAP_NET_RAW``。AF_PACKET 和 raw socket 的创建同样要求该 owner 的 ``CAP_NET_RAW``。" -msgstr "Linux のネットワーク管理は名前・索引の照会、IPv4/IPv6 アドレスと経路の操作、管理状態の変更を提供します。照会はソケットが保持する作成元ネットワークを使用し、インターフェースの変更にはその user owner における ``CAP_NET_ADMIN`` が必要です。最初の ``SO_BINDTODEVICE`` は通常のプロセスにも許可され、既存のデバイス bind の変更には同じ owner における ``CAP_NET_RAW`` が必要です。AF_PACKET と raw socket の作成にも同じ owner における ``CAP_NET_RAW`` が必要です。" +msgid "" +"Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路由操作,以及行政状态开关。查询使用 socket " +"创建时保留的网络,接口配置修改需要该网络 user owner 的 ``CAP_NET_ADMIN``。首次设置 " +"``SO_BINDTODEVICE`` 允许普通进程,更改已有设备绑定需要该 owner 的 ``CAP_NET_RAW``。AF_PACKET " +"和 raw socket 的创建同样要求该 owner 的 ``CAP_NET_RAW``。" +msgstr "" +"Linux のネットワーク管理は名前・索引の照会、IPv4/IPv6 " +"アドレスと経路の操作、管理状態の変更を提供します。照会はソケットが保持する作成元ネットワークを使用し、インターフェースの変更にはその user " +"owner における ``CAP_NET_ADMIN`` が必要です。最初の ``SO_BINDTODEVICE`` " +"は通常のプロセスにも許可され、既存のデバイス bind の変更には同じ owner における ``CAP_NET_RAW`` " +"が必要です。AF_PACKET と raw socket の作成にも同じ owner における ``CAP_NET_RAW`` が必要です。" msgid "" -"设备直接接收软件提交的帧,发送队列交由各设备的有界 DMA 环管理。 ``SIOCGIFTXQLEN`` 报告的软件队列长度为 0。硬件 MTU 为 " -"1500。" +"设备直接接收软件提交的帧,发送队列交由各设备的有界 DMA 环管理。 ``SIOCGIFTXQLEN`` 报告的软件队列长度为 0。硬件 MTU " +"为 1500。" msgstr "" -"デバイスはソフトウェアが投入したフレームを直接受け取り、送信キューは各デバイスの上限付き DMA リングが管理します。``SIOCGIFTXQLEN``" -" が報告するソフトウェアキュー長は 0 です。ハードウェア MTU は 1500 です。" +"デバイスはソフトウェアが投入したフレームを直接受け取り、送信キューは各デバイスの上限付き DMA " +"リングが管理します。``SIOCGIFTXQLEN`` が報告するソフトウェアキュー長は 0 です。ハードウェア MTU は 1500 です。" msgid "" -"``/proc/net/dev`` 列举所有已登记接口,包括未分配 IPv4 地址或行政关闭的设备。 ``SIOCGIFCONF`` 按 Linux 的" -" IPv4 地址列表语义输出 loopback 和有地址的接口。 枚举硬件接口可使用 rtnetlink 或 " +"``/proc/net/dev`` 列举所有已登记接口,包括未分配 IPv4 地址或行政关闭的设备。 ``SIOCGIFCONF`` 按 " +"Linux 的 IPv4 地址列表语义输出 loopback 和有地址的接口。 枚举硬件接口可使用 rtnetlink 或 " "``/proc/net/dev``,并按名称查询 ifindex。" msgstr "" "``/proc/net/dev`` は登録済みの全インターフェースを列挙し、IPv4 " "アドレス未割り当てや管理上無効なデバイスも含みます。``SIOCGIFCONF`` は Linux の IPv4 " -"アドレス一覧の意味に従い、loopback とアドレス付きインターフェースを出力します。ハードウェアインターフェースの列挙には rtnetlink " -"または ``/proc/net/dev`` を使い、名前から ifindex を照会できます。" +"アドレス一覧の意味に従い、loopback とアドレス付きインターフェースを出力します。ハードウェアインターフェースの列挙には rtnetlink" +" または ``/proc/net/dev`` を使い、名前から ifindex を照会できます。" + +msgid "IPv6 host controls" +msgstr "IPv6 ホスト制御" + +msgid "" +"``/proc/sys/net/ipv6/conf//`` 提供 " +"``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode`` 和 " +"``use_tempaddr``。配置和协议状态由网络空间持有。打开的文件保留目标网络和稳定 " +"ifindex,接口改名或调用者切换网络后继续操作原目标,接口移除后返回 ``ENODEV``。" +msgstr "" +"``/proc/sys/net/ipv6/conf//`` は " +"``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode``、``use_tempaddr``" +" を提供します。設定とプロトコル状態はネットワーク名前空間が所有します。開いたファイルは対象ネットワークと固定 ifindex " +"を保持し、インターフェース名や呼び出し元ネットワークが変わっても元の対象を操作します。インターフェース削除後は ``ENODEV`` を返します。" + +msgid "" +"控制文件为 0644,读取公开,写入按当前凭据检查全局 root 身份或目标网络 user owner 的 " +"``CAP_NET_ADMIN``,只读挂载仍拒绝写入。整数输入接受符号、十六进制、八进制及首尾 ASCII 空白,溢出和非法输入返回 " +"``EINVAL``。非零偏移写入消耗输入而不改变配置。" +msgstr "" +"制御ファイルのモードは 0644 で、読み取りは公開されています。書き込み時は現在の資格情報でグローバル root、または対象ネットワークの " +"user owner における ``CAP_NET_ADMIN`` を確認します。読み取り専用マウントは書き込みを拒否します。整数入力は符号、16" +" 進数、8 進数、前後の ASCII 空白を受け付け、オーバーフローや不正入力は ``EINVAL`` " +"を返します。ゼロ以外のオフセットへの書き込みは入力を消費し、設定を維持します。" + +msgid "" +"默认值为启用 IPv6、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0`` 和 " +"``use_tempaddr=0``。修改 ``default`` 影响随后创建的接口,已有接口包括行政关闭的接口保留原值。写入 " +"``all/disable_ipv6`` 或 ``all/addr_gen_mode`` 同时更新默认值和现存接口,其他 ``all`` " +"控制保留独立值。" +msgstr "" +"既定では IPv6 " +"が有効で、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0``、``use_tempaddr=0``" +" です。``default`` " +"の変更は以後作成するインターフェースに適用します。管理上停止したものを含む既存インターフェースは元の値を保持します。``all/disable_ipv6``" +" または ``all/addr_gen_mode`` への書き込みは既定値と既存インターフェースを同時に更新します。他の ``all`` " +"制御は独立した値を保持します。" + +msgid "" +"``disable_ipv6`` 接受 0 和 1,禁用时清理链路 IPv6 " +"状态并停止收发。重新启用时按链路配置恢复自动地址。``accept_ra`` 接受 0、1 和 2,0 停止内核 RA 处理和 RS,1 与 2 " +"启用当前主机模式的 RA 处理。官方 networkd 将该值设为 0 后,通过自己的发现协议处理 RA。``hop_limit`` 接受 1 至" +" 255,供未指定跳数的实际发包使用,内核接收的有效 RA 可以更新该值。" +msgstr "" +"``disable_ipv6`` は 0 と 1 を受け付け、無効化時はリンクの IPv6 " +"状態を消去して送受信を停止します。再有効化時はリンク設定に従って自動アドレスを復元します。``accept_ra`` は 0、1、2 " +"を受け付け、0 はカーネルの RA 処理と RS を停止し、1 と 2 は現在のホストモードの RA 処理を有効にします。公式 networkd " +"はこの値を 0 に設定し、独自の探索プロトコルで RA を処理します。``hop_limit`` は 1 から 255 " +"を受け付け、指定のない実際の送信パケットに使います。カーネルが受信した有効な RA はこの値を更新できます。" + +msgid "" +"``addr_gen_mode`` 支持 EUI64 模式 0 和关闭自动链路本地地址的模式 1,切换为 1 保留已有地址。模式 2、3 和正数 " +"``use_tempaddr`` 返回 ``EOPNOTSUPP``,稳定隐私地址和临时地址生成仍待实现。``RTM_SETLINK`` 和 " +"``RTM_NEWLINK`` 接受 ``IFLA_AF_SPEC`` 下的 " +"``AF_INET6/IFLA_INET6_ADDR_GEN_MODE``,查询和链路通知回报实际模式,嵌套属性允许 " +"``NLA_F_NESTED`` 标记。" +msgstr "" +"``addr_gen_mode`` は EUI64 モード 0 と、自動リンクローカルアドレスを無効にするモード 1 に対応します。1 " +"への変更時も既存アドレスを保持します。モード 2、3 と正の ``use_tempaddr`` は ``EOPNOTSUPP`` " +"を返します。安定プライバシーアドレスと一時アドレスの生成は実装予定です。``RTM_SETLINK`` と ``RTM_NEWLINK`` は " +"``IFLA_AF_SPEC`` 内の ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE`` " +"を受け付けます。照会とリンク通知は実際のモードを返し、ネスト属性は ``NLA_F_NESTED`` を受け付けます。" + +msgid "" +"启用控制先检查地址、路由和多播容量,再更新配置及协议表。分配或容量失败保留可见配置和协议状态,可在资源释放后重试。普通 Ethernet " +"链路在自动地址表耗尽时仍可用于手动地址配置。IPv4 次地址提升控制 ``promote_secondaries`` 仍待接入。" +msgstr "" +"有効化制御は設定とプロトコルテーブルを更新する前にアドレス、経路、マルチキャストの容量を確認します。割り当てや容量の失敗時は可視設定とプロトコル状態を保持し、資源解放後に再試行できます。通常の" +" Ethernet リンクは自動アドレステーブルが満杯でも手動アドレスに利用できます。IPv4 の ``promote_secondaries``" +" による副アドレス昇格は実装予定です。" + +msgid "IPv6 raw and ping errors" +msgstr "IPv6 raw と ping のエラー" + +msgid "" +"IPv6 raw socket 和 ICMPv6 ping socket 支持 ``IPV6_RECVERR``,每个 socket 独立保存最多" +" 32 条扩展错误。错误记录持有被引用报文的上层载荷、原目标地址、``sock_extended_err`` " +"和产生错误的节点地址,按创建网络、接口、作用域、本地地址及连接目标匹配。ping socket 还校验 Echo Request 类型、code " +"和 identifier。" +msgstr "" +"IPv6 raw socket と ICMPv6 ping socket は ``IPV6_RECVERR`` に対応し、socket ごとに最大" +" 32 件の拡張エラーを保持します。各レコードは引用パケットの上位層ペイロード、元の宛先、``sock_extended_err`` " +"とエラー発生元アドレスを所有します。作成元ネットワーク、インターフェース、スコープ、ローカルアドレスと接続先で照合し、ping socket は " +"Echo Request の型、code と identifier も検証します。" + +msgid "" +"``recvmsg(MSG_ERRQUEUE)`` 返回扩展错误控制消息,``recvfrom(MSG_ERRQUEUE)`` " +"返回载荷和原目标地址。外部 ``MSG_PEEK`` 仍消费一条错误,空错误队列返回 " +"``EAGAIN``。内部换页探测保留记录,输出内存准备成功后才消费。普通收包队列独立保留。``SO_ERROR`` 清除待报告 errno " +"后,未读扩展错误仍产生 ``POLLERR``。" +msgstr "" +"``recvmsg(MSG_ERRQUEUE)`` は拡張エラー制御メッセージを返し、``recvfrom(MSG_ERRQUEUE)`` " +"はペイロードと元の宛先を返します。外部の ``MSG_PEEK`` でもエラーを 1 件消費し、空のエラーキューは ``EAGAIN`` " +"を返します。内部のスワップ用プローブは出力メモリの準備が成功するまでレコードを保持します。通常の受信キューは独立して保持されます。``SO_ERROR``" +" が保留中の errno を消去しても、未読の拡張エラーは ``POLLERR`` を通知します。" + +msgid "" +"关闭 ``IPV6_RECVERR`` 清理扩展错误队列并保留待报告 errno。队列满或分配失败保留已有记录及待报告错误,最后关闭 socket" +" 时释放全部队列和网络引用。" +msgstr "" +"``IPV6_RECVERR`` を無効にすると拡張エラーキューを解放し、保留中の errno " +"を保持します。キューの満杯や割り当て失敗時も既存レコードと保留中のエラーを保持し、socket " +"の最終クローズで全キューとネットワーク参照を解放します。" msgid "Validation" msgstr "検証" @@ -104,25 +231,45 @@ msgstr "検証" msgid "" "``tools/test_net_device.py`` 验证多个 owner、独立回调、计数和索引生命周期。 " "``tools/test_net_multi_interface.py`` 验证 ioctl、rtnetlink 和逐接口选路。 " -"``tools/test_net_multinic_data.py`` 验证 ARP、UDP 输出和 AF_PACKET 隔离。 既有 TCP、UDP " -"和 IPv6 定向套件覆盖对应传输的设备绑定、作用域与资源清理。" +"``tools/test_net_multinic_data.py`` 验证 ARP、UDP 输出和 AF_PACKET 隔离。 既有 " +"TCP、UDP 和 IPv6 定向套件覆盖对应传输的设备绑定、作用域与资源清理。" msgstr "" "``tools/test_net_device.py`` は複数 " "owner、独立コールバック、カウンター、インデックスのライフサイクルを検証します。``tools/test_net_multi_interface.py``" -" は ioctl、rtnetlink、インターフェースごとの経路選択を検証します。``tools/test_net_multinic_data.py``" +" は " +"ioctl、rtnetlink、インターフェースごとの経路選択を検証します。``tools/test_net_multinic_data.py``" " は ARP、UDP 出力、AF_PACKET の分離を検証します。既存の TCP、UDP、IPv6 " "の専用スイートは、各転送のデバイスバインド、スコープ、リソース解放を検証します。" +msgid "" +"``tools/test_ipv6_protocol.py`` " +"覆盖控制值、协议副作用、默认继承、网络隔离和容量失败重试。``tools/test_ipv6_control.py`` 覆盖 networkd " +"嵌套地址生成属性、查询及权限。``tools/test_procfs.py`` 覆盖控制文件的 VFS " +"生命周期、当前凭据、解析、只读挂载、改名、移除和内存失败。" +msgstr "" +"``tools/test_ipv6_protocol.py`` " +"は制御値、プロトコルへの効果、既定値の継承、ネットワーク分離、容量不足後の再試行を検証します。``tools/test_ipv6_control.py``" +" は networkd のネストしたアドレス生成属性、照会、権限を検証します。``tools/test_procfs.py`` は制御ファイルの " +"VFS ライフサイクル、現在の資格情報、解析、読み取り専用マウント、改名、削除、メモリー割り当て失敗を検証します。" + +msgid "" +"``tools/test_ipv6_transport.py`` 使用实际 raw/ping 实现验证扩展错误、identifier " +"和网络隔离、队列容量、分配失败与关闭清理,并通过实际 ``recvmsg`` 入口验证辅助数据和换页重试期间的安全消费。" +msgstr "" +"``tools/test_ipv6_transport.py`` は実際の raw/ping 実装で拡張エラー、identifier " +"とネットワークの分離、キュー上限、割り当て失敗とクローズ時の解放を検証します。実際の ``recvmsg`` " +"入口で補助データとスワップ再試行時の安全な消費を確認します。" + msgid "" "``tools/tests/multinic_guest.c`` 是标准 socket 用户程序探针,由 ReliefOS 的 " "``tools/test_multi_nic_qemu.py`` 放入私有来宾执行。来宾使用两张 e1000 和 一张 e1000e,验证独立 " -"DHCP、IPv4/IPv6、并发 TCP/UDP,以及模块卸载期间 另一 owner 的活动 TCP 连接。完整桌面镜像与实体硬件的运行验证分别记录。" -" VMware 验证未完成。" +"DHCP、IPv4/IPv6、并发 TCP/UDP,以及模块卸载期间 另一 owner 的活动 TCP " +"连接。完整桌面镜像与实体硬件的运行验证分别记录。 VMware 验证未完成。" msgstr "" "``tools/tests/multinic_guest.c`` は標準 socket のユーザープログラムプローブで、ReliefOS の " -"``tools/test_multi_nic_qemu.py`` が専用ゲストに配置して実行します。ゲストは e1000 を 2 枚、e1000e を " -"1 枚使用し、独立した DHCP、IPv4/IPv6、並行 TCP/UDP、およびモジュールのアンロード中に別 owner 上で稼働する TCP " -"接続を検証します。完全なデスクトップイメージと実機の実行検証は別々に記録します。VMware の検証は未完了です。" +"``tools/test_multi_nic_qemu.py`` が専用ゲストに配置して実行します。ゲストは e1000 を 2 枚、e1000e" +" を 1 枚使用し、独立した DHCP、IPv4/IPv6、並行 TCP/UDP、およびモジュールのアンロード中に別 owner 上で稼働する " +"TCP 接続を検証します。完全なデスクトップイメージと実機の実行検証は別々に記録します。VMware の検証は未完了です。" msgid "References" msgstr "参考資料" @@ -137,53 +284,11 @@ msgstr "" msgid "" "`Linux packet sockets `_" -msgstr "" -"`Linux パケット socket `_" +msgstr "`Linux パケット socket `_" msgid "" "`IPv6 scoped address architecture, RFC 4007 `_" msgstr "" -"`IPv6 スコープ付きアドレスアーキテクチャ、RFC 4007 `_" - -msgid "IPv6 host controls" -msgstr "IPv6 ホスト制御" - -msgid "``/proc/sys/net/ipv6/conf//`` 提供 ``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode`` 和 ``use_tempaddr``。配置和协议状态由网络空间持有。打开的文件保留目标网络和稳定 ifindex,接口改名或调用者切换网络后继续操作原目标,接口移除后返回 ``ENODEV``。" -msgstr "``/proc/sys/net/ipv6/conf//`` は ``disable_ipv6``、``accept_ra``、``hop_limit``、``addr_gen_mode``、``use_tempaddr`` を提供します。設定とプロトコル状態はネットワーク名前空間が所有します。開いたファイルは対象ネットワークと固定 ifindex を保持し、インターフェース名や呼び出し元ネットワークが変わっても元の対象を操作します。インターフェース削除後は ``ENODEV`` を返します。" - -msgid "控制文件为 0644,读取公开,写入按当前凭据检查全局 root 身份或目标网络 user owner 的 ``CAP_NET_ADMIN``,只读挂载仍拒绝写入。整数输入接受符号、十六进制、八进制及首尾 ASCII 空白,溢出和非法输入返回 ``EINVAL``。非零偏移写入消耗输入而不改变配置。" -msgstr "制御ファイルのモードは 0644 で、読み取りは公開されています。書き込み時は現在の資格情報でグローバル root、または対象ネットワークの user owner における ``CAP_NET_ADMIN`` を確認します。読み取り専用マウントは書き込みを拒否します。整数入力は符号、16 進数、8 進数、前後の ASCII 空白を受け付け、オーバーフローや不正入力は ``EINVAL`` を返します。ゼロ以外のオフセットへの書き込みは入力を消費し、設定を維持します。" - -msgid "默认值为启用 IPv6、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0`` 和 ``use_tempaddr=0``。修改 ``default`` 影响随后创建的接口,已有接口包括行政关闭的接口保留原值。写入 ``all/disable_ipv6`` 或 ``all/addr_gen_mode`` 同时更新默认值和现存接口,其他 ``all`` 控制保留独立值。" -msgstr "既定では IPv6 が有効で、``accept_ra=1``、``hop_limit=64``、``addr_gen_mode=0``、``use_tempaddr=0`` です。``default`` の変更は以後作成するインターフェースに適用します。管理上停止したものを含む既存インターフェースは元の値を保持します。``all/disable_ipv6`` または ``all/addr_gen_mode`` への書き込みは既定値と既存インターフェースを同時に更新します。他の ``all`` 制御は独立した値を保持します。" - -msgid "``disable_ipv6`` 接受 0 和 1,禁用时清理链路 IPv6 状态并停止收发。重新启用时按链路配置恢复自动地址。``accept_ra`` 接受 0、1 和 2,0 停止内核 RA 处理和 RS,1 与 2 启用当前主机模式的 RA 处理。官方 networkd 将该值设为 0 后,通过自己的发现协议处理 RA。``hop_limit`` 接受 1 至 255,供未指定跳数的实际发包使用,内核接收的有效 RA 可以更新该值。" -msgstr "``disable_ipv6`` は 0 と 1 を受け付け、無効化時はリンクの IPv6 状態を消去して送受信を停止します。再有効化時はリンク設定に従って自動アドレスを復元します。``accept_ra`` は 0、1、2 を受け付け、0 はカーネルの RA 処理と RS を停止し、1 と 2 は現在のホストモードの RA 処理を有効にします。公式 networkd はこの値を 0 に設定し、独自の探索プロトコルで RA を処理します。``hop_limit`` は 1 から 255 を受け付け、指定のない実際の送信パケットに使います。カーネルが受信した有効な RA はこの値を更新できます。" - -msgid "``addr_gen_mode`` 支持 EUI64 模式 0 和关闭自动链路本地地址的模式 1,切换为 1 保留已有地址。模式 2、3 和正数 ``use_tempaddr`` 返回 ``EOPNOTSUPP``,稳定隐私地址和临时地址生成仍待实现。``RTM_SETLINK`` 和 ``RTM_NEWLINK`` 接受 ``IFLA_AF_SPEC`` 下的 ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE``,查询和链路通知回报实际模式,嵌套属性允许 ``NLA_F_NESTED`` 标记。" -msgstr "``addr_gen_mode`` は EUI64 モード 0 と、自動リンクローカルアドレスを無効にするモード 1 に対応します。1 への変更時も既存アドレスを保持します。モード 2、3 と正の ``use_tempaddr`` は ``EOPNOTSUPP`` を返します。安定プライバシーアドレスと一時アドレスの生成は実装予定です。``RTM_SETLINK`` と ``RTM_NEWLINK`` は ``IFLA_AF_SPEC`` 内の ``AF_INET6/IFLA_INET6_ADDR_GEN_MODE`` を受け付けます。照会とリンク通知は実際のモードを返し、ネスト属性は ``NLA_F_NESTED`` を受け付けます。" - -msgid "启用控制先检查地址、路由和多播容量,再更新配置及协议表。分配或容量失败保留可见配置和协议状态,可在资源释放后重试。普通 Ethernet 链路在自动地址表耗尽时仍可用于手动地址配置。IPv4 次地址提升控制 ``promote_secondaries`` 仍待接入。" -msgstr "有効化制御は設定とプロトコルテーブルを更新する前にアドレス、経路、マルチキャストの容量を確認します。割り当てや容量の失敗時は可視設定とプロトコル状態を保持し、資源解放後に再試行できます。通常の Ethernet リンクは自動アドレステーブルが満杯でも手動アドレスに利用できます。IPv4 の ``promote_secondaries`` による副アドレス昇格は実装予定です。" - -msgid "``tools/test_ipv6_protocol.py`` 覆盖控制值、协议副作用、默认继承、网络隔离和容量失败重试。``tools/test_ipv6_control.py`` 覆盖 networkd 嵌套地址生成属性、查询及权限。``tools/test_procfs.py`` 覆盖控制文件的 VFS 生命周期、当前凭据、解析、只读挂载、改名、移除和内存失败。" -msgstr "``tools/test_ipv6_protocol.py`` は制御値、プロトコルへの効果、既定値の継承、ネットワーク分離、容量不足後の再試行を検証します。``tools/test_ipv6_control.py`` は networkd のネストしたアドレス生成属性、照会、権限を検証します。``tools/test_procfs.py`` は制御ファイルの VFS ライフサイクル、現在の資格情報、解析、読み取り専用マウント、改名、削除、メモリー割り当て失敗を検証します。" - -msgid "IPv6 raw and ping errors" -msgstr "IPv6 raw と ping のエラー" - -msgid "IPv6 raw socket 和 ICMPv6 ping socket 支持 ``IPV6_RECVERR``,每个 socket 独立保存最多 32 条扩展错误。错误记录持有被引用报文的上层载荷、原目标地址、``sock_extended_err`` 和产生错误的节点地址,按创建网络、接口、作用域、本地地址及连接目标匹配。ping socket 还校验 Echo Request 类型、code 和 identifier。" -msgstr "IPv6 raw socket と ICMPv6 ping socket は ``IPV6_RECVERR`` に対応し、socket ごとに最大 32 件の拡張エラーを保持します。各レコードは引用パケットの上位層ペイロード、元の宛先、``sock_extended_err`` とエラー発生元アドレスを所有します。作成元ネットワーク、インターフェース、スコープ、ローカルアドレスと接続先で照合し、ping socket は Echo Request の型、code と identifier も検証します。" - -msgid "``recvmsg(MSG_ERRQUEUE)`` 返回扩展错误控制消息,``recvfrom(MSG_ERRQUEUE)`` 返回载荷和原目标地址。外部 ``MSG_PEEK`` 仍消费一条错误,空错误队列返回 ``EAGAIN``。内部换页探测保留记录,输出内存准备成功后才消费。普通收包队列独立保留。``SO_ERROR`` 清除待报告 errno 后,未读扩展错误仍产生 ``POLLERR``。" -msgstr "``recvmsg(MSG_ERRQUEUE)`` は拡張エラー制御メッセージを返し、``recvfrom(MSG_ERRQUEUE)`` はペイロードと元の宛先を返します。外部の ``MSG_PEEK`` でもエラーを 1 件消費し、空のエラーキューは ``EAGAIN`` を返します。内部のスワップ用プローブは出力メモリの準備が成功するまでレコードを保持します。通常の受信キューは独立して保持されます。``SO_ERROR`` が保留中の errno を消去しても、未読の拡張エラーは ``POLLERR`` を通知します。" - -msgid "关闭 ``IPV6_RECVERR`` 清理扩展错误队列并保留待报告 errno。队列满或分配失败保留已有记录及待报告错误,最后关闭 socket 时释放全部队列和网络引用。" -msgstr "``IPV6_RECVERR`` を無効にすると拡張エラーキューを解放し、保留中の errno を保持します。キューの満杯や割り当て失敗時も既存レコードと保留中のエラーを保持し、socket の最終クローズで全キューとネットワーク参照を解放します。" - -msgid "``tools/test_ipv6_transport.py`` 使用实际 raw/ping 实现验证扩展错误、identifier 和网络隔离、队列容量、分配失败与关闭清理,并通过实际 ``recvmsg`` 入口验证辅助数据和换页重试期间的安全消费。" -msgstr "``tools/test_ipv6_transport.py`` は実際の raw/ping 実装で拡張エラー、identifier とネットワークの分離、キュー上限、割り当て失敗とクローズ時の解放を検証します。実際の ``recvmsg`` 入口で補助データとスワップ再試行時の安全な消費を確認します。" - -msgid "e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO 寄存器。实际发送仍检查当前链路,驱动没有关闭收包轮询或协议定时器。" -msgstr "e1000e のリンク状態の問い合わせでは、同じ MMIO レジスタを繰り返し読まず、デバイスごとに同一 tick 内のハードウェア測定値を再利用します。実際の送信では現在のリンクを確認し、受信ポーリングとプロトコルタイマーも有効なままです。" +"`IPv6 スコープ付きアドレスアーキテクチャ、RFC 4007 `_" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/realtek.po b/Documentation/locale/ja/LC_MESSAGES/core-api/realtek.po index 5a50972e..403eec6a 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/realtek.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/realtek.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0800\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "Realtek PCIe 以太网驱动" msgstr "Realtek PCIe イーサネットドライバー" @@ -20,13 +23,14 @@ msgid "设备与配置" msgstr "デバイスと構成" msgid "" -"``drivers/net/r8169/`` 提供 ReliefNT 原生网卡驱动。``CONFIG_R8169`` 为 tristate,``make" -" defconfig`` 默认选择 ``y``。选择 ``m`` 生成 ``drivers/net/r8169/r8169.ko``,由普通 " -"``modprobe`` 根据 PCI 别名加载。" +"``drivers/net/r8169/`` 提供 ReliefNT 原生网卡驱动。``CONFIG_R8169`` 为 " +"tristate,``make defconfig`` 默认选择 ``y``。选择 ``m`` 生成 " +"``drivers/net/r8169/r8169.ko``,由普通 ``modprobe`` 根据 PCI 别名加载。" msgstr "" -"``drivers/net/r8169/`` は ReliefNT ネイティブのネットワークドライバーを提供します。``CONFIG_R8169`` は" -" tristate で、``make defconfig`` は既定で ``y`` を選択します。``m`` を選ぶと " -"``drivers/net/r8169/r8169.ko`` を生成し、通常の ``modprobe`` が PCI エイリアスに基づいてロードします。" +"``drivers/net/r8169/`` は ReliefNT " +"ネイティブのネットワークドライバーを提供します。``CONFIG_R8169`` は tristate で、``make defconfig`` " +"は既定で ``y`` を選択します。``m`` を選ぶと ``drivers/net/r8169/r8169.ko`` を生成し、通常の " +"``modprobe`` が PCI エイリアスに基づいてロードします。" msgid "" "设备表包含 ``10ec:8168`` 和 ``10ec:8125``。驱动进一步读取 TxConfig 中的硬件版本,分别选择初始化、PHY " @@ -48,11 +52,11 @@ msgid "``10ec:8168``" msgstr "``10ec:8168``" msgid "" -"RTL8111/8168 B、C、CP、D、DP、E、E-VL、F、G、GU、H、EP、FP。 按 OpenBSD 的版本掩码区分家族与 B/C 的 " -"spin。" +"RTL8111/8168 B、C、CP、D、DP、E、E-VL、F、G、GU、H、EP、FP。 按 OpenBSD 的版本掩码区分家族与 B/C " +"的 spin。" msgstr "" -"RTL8111/8168 B、C、CP、D、DP、E、E-VL、F、G、GU、H、EP、FP。OpenBSD のリビジョンマスクで系列と B/C の " -"spin を区別します。" +"RTL8111/8168 B、C、CP、D、DP、E、E-VL、F、G、GU、H、EP、FP。OpenBSD のリビジョンマスクで系列と B/C " +"の spin を区別します。" msgid "``10ec:8125``" msgstr "``10ec:8125``" @@ -76,11 +80,11 @@ msgstr "" "を参照してください。" msgid "" -"无网线时接口仍可查询和配置,载波状态来自硬件。PHY 自动协商覆盖 10/100/1000 Mb/s,RTL8125 另行通告 2500BASE-T " -"全双工。协商异步完成。 PHY、EPHY、CSI、固件握手和复位均有界等待,失败返回具体 errno。" +"无网线时接口仍可查询和配置,载波状态来自硬件。PHY 自动协商覆盖 10/100/1000 Mb/s,RTL8125 另行通告 " +"2500BASE-T 全双工。协商异步完成。 PHY、EPHY、CSI、固件握手和复位均有界等待,失败返回具体 errno。" msgstr "" -"ケーブルがなくてもインターフェースは照会・設定でき、キャリア状態はハードウェアから取得します。PHY の自動ネゴシエーションは 10/100/1000 " -"Mb/s に対応し、RTL8125 は追加で 2500BASE-T " +"ケーブルがなくてもインターフェースは照会・設定でき、キャリア状態はハードウェアから取得します。PHY の自動ネゴシエーションは " +"10/100/1000 Mb/s に対応し、RTL8125 は追加で 2500BASE-T " "全二重を通知します。ネゴシエーションは非同期に完了します。PHY、EPHY、CSI、ファームウェアのハンドシェイク、リセットはいずれも上限付きで待機し、失敗時は具体的な" " errno を返します。" @@ -89,18 +93,18 @@ msgid "" "迁移。时钟停滞、回退或 达到轮询上限时改用 tick 等待;较长等待也使用 tick 等待,并额外加入一整个 tick,以覆盖请求恰好接近下一个 " "tick 的情况。等待返回后恢复原中断状态, 调用方不得持有自旋锁。短等待依赖内核启动时钟的精度;该时钟突然向前跳变 可能缩短等待。" msgstr "" -"ハードウェア初期化中のマイクロ秒単位の安定待ちは、起動時間のサンプルを使用します。1 ms 未満の待機は最大 4096 回ポーリングし、サンプリング中は" -" CPU 移行を避けるためローカル割り込みを無効化します。クロックの停止、逆行、ポーリング上限到達時には tick 待機へ切り替えます。長い待機も " -"tick を使用し、要求が次の tick 直前に発生する場合をカバーするため、さらに丸 1 tick " +"ハードウェア初期化中のマイクロ秒単位の安定待ちは、起動時間のサンプルを使用します。1 ms 未満の待機は最大 4096 " +"回ポーリングし、サンプリング中は CPU 移行を避けるためローカル割り込みを無効化します。クロックの停止、逆行、ポーリング上限到達時には tick" +" 待機へ切り替えます。長い待機も tick を使用し、要求が次の tick 直前に発生する場合をカバーするため、さらに丸 1 tick " "を加えます。待機から戻ると元の割り込み状態を復元します。呼び出し元はスピンロックを保持してはいけません。短い待機はカーネル起動クロックの精度に依存し、このクロックが突然進むと待機が短くなる場合があります。" msgid "收发和生命周期" msgstr "送受信とライフサイクル" msgid "" -"驱动优先映射 PCI BAR2,再尝试其他有效内存 BAR,支持 64 位地址。 PCI 电源管理使用常规 capability 链请求 D0。原始 " -"MAC 在复位前读取并保留, 无效地址导致初始化失败。 早期 RTL8168 的控制 BAR 可能只有 256 字节,此时可通过该设备的 I/O BAR" -" 访问同一寄存器组。PCI 内存映射仍要求完整页面位于有效 BAR 内。" +"驱动优先映射 PCI BAR2,再尝试其他有效内存 BAR,支持 64 位地址。 PCI 电源管理使用常规 capability 链请求 " +"D0。原始 MAC 在复位前读取并保留, 无效地址导致初始化失败。 早期 RTL8168 的控制 BAR 可能只有 256 " +"字节,此时可通过该设备的 I/O BAR 访问同一寄存器组。PCI 内存映射仍要求完整页面位于有效 BAR 内。" msgstr "" "ドライバーは PCI BAR2 のマッピングを優先し、その後に他の有効なメモリ BAR を試します。64 ビットアドレスに対応します。PCI " "電源管理は通常の capability チェーンで D0 を要求します。元の MAC " @@ -109,9 +113,9 @@ msgstr "" "メモリマッピングには、引き続きページ全体が有効な BAR 内にあることが必要です。" msgid "" -"RX/TX 各使用 256 个 16 字节经典描述符和 2048 字节缓冲区。RTL8125 显式选择经典布局。描述符保留物理 DMA 地址,CPU " -"通过独立映射访问数据。 所有权交接使用 acquire/release 屏障,发送与接收有独立的短临界区。 当前使用单队列轮询,MTU 为 " -"1500,IP/传输层校验和由现有网络栈计算。" +"RX/TX 各使用 256 个 16 字节经典描述符和 2048 字节缓冲区。RTL8125 显式选择经典布局。描述符保留物理 DMA " +"地址,CPU 通过独立映射访问数据。 所有权交接使用 acquire/release 屏障,发送与接收有独立的短临界区。 " +"当前使用单队列轮询,MTU 为 1500,IP/传输层校验和由现有网络栈计算。" msgstr "" "RX/TX はそれぞれ、16 バイトの従来型記述子 256 個と 2048 バイトのバッファーを使用します。RTL8125 " "は従来型レイアウトを明示的に選択します。記述子は物理 DMA アドレスを保持し、CPU " @@ -152,14 +156,14 @@ msgid "" "硬件初始化改编自 OpenBSD src 提交 ``7779d12194498048b288afda664dd6271a2ec016``。 " "RTL8111/8168 派生代码保留 BSD-4-Clause,RTL8125 派生代码保留 ISC, 固件保留 Realtek " "的再分发许可。项目新增的 PCI/DMA/模块连接代码使用 Apache-2.0。完整声明见 ``NOTICE`` 和 " -"``LICENSES/realtek/``。 ``modules_install`` 将声明放入版本化模块目录的 ``LICENSES/``,连同 " -"模块加入安装所有权和校验清单,并随 ReliefOS 的内核载荷分发。" +"``LICENSES/realtek/``。 ``modules_install`` 将声明放入版本化模块目录的 ``LICENSES/``,连同" +" 模块加入安装所有权和校验清单,并随 ReliefOS 的内核载荷分发。" msgstr "" -"ハードウェア初期化は OpenBSD src のコミット ``7779d12194498048b288afda664dd6271a2ec016`` " -"を基にしています。RTL8111/8168 派生コードは BSD-4-Clause、RTL8125 派生コードは ISC、ファームウェアは " +"ハードウェア初期化は OpenBSD src のコミット ``7779d12194498048b288afda664dd6271a2ec016``" +" を基にしています。RTL8111/8168 派生コードは BSD-4-Clause、RTL8125 派生コードは ISC、ファームウェアは " "Realtek の再配布ライセンスを維持します。本プロジェクトが追加した PCI/DMA/モジュール接続コードは Apache-2.0 " -"です。完全な表記は ``NOTICE`` と ``LICENSES/realtek/`` を参照してください。``modules_install`` " -"は表記をバージョン付きモジュールディレクトリの ``LICENSES/`` " +"です。完全な表記は ``NOTICE`` と ``LICENSES/realtek/`` " +"を参照してください。``modules_install`` は表記をバージョン付きモジュールディレクトリの ``LICENSES/`` " "に配置し、モジュールとともにインストール所有権とチェックサムの一覧へ登録して、ReliefOS のカーネルペイロードに含めて配布します。" msgid "This product includes software developed by Bill Paul." @@ -198,24 +202,23 @@ msgstr "検証範囲" msgid "" "``tools/test_r8169.py`` 编译真实驱动对象并模拟 PCI/MMIO/DMA 边界,另行编译 " -"真实寄存器与等待实现,检查时钟边界、中断状态和不同寄存器访问方式。 它覆盖 4 GiB 以上地址、收发回绕、长度与错误检查、补零、无载波、资源分配 " -"失败、owner 冲突、停止失败保留与重试。芯片模型覆盖四个 RTL8125 版本和 RTL8168 家族路径。真实 PHY 协商、DMA " +"真实寄存器与等待实现,检查时钟边界、中断状态和不同寄存器访问方式。 它覆盖 4 GiB 以上地址、收发回绕、长度与错误检查、补零、无载波、资源分配" +" 失败、owner 冲突、停止失败保留与重试。芯片模型覆盖四个 RTL8125 版本和 RTL8168 家族路径。真实 PHY 协商、DMA " "时序和实体网线收发仍需对应硬件验证。" msgstr "" "``tools/test_r8169.py`` は実際のドライバーオブジェクトをコンパイルして PCI/MMIO/DMA " -"境界をモデル化し、さらに実際のレジスター実装と待機実装を個別にコンパイルして、クロック境界、割り込み状態、異なるレジスターアクセス方式を確認します。4 " -"GiB より上のアドレス、送受信の折り返し、長さとエラーの検査、ゼロ埋め、キャリアなし、リソース割り当て失敗、owner " -"競合、停止失敗時の保持と再試行を検証します。チップモデルは RTL8125 の 4 リビジョンと RTL8168 系列の経路をカバーします。実際の " -"PHY ネゴシエーション、DMA タイミング、物理ケーブルでの送受信は、対応するハードウェアで引き続き検証が必要です。" +"境界をモデル化し、さらに実際のレジスター実装と待機実装を個別にコンパイルして、クロック境界、割り込み状態、異なるレジスターアクセス方式を確認します。4" +" GiB より上のアドレス、送受信の折り返し、長さとエラーの検査、ゼロ埋め、キャリアなし、リソース割り当て失敗、owner " +"競合、停止失敗時の保持と再試行を検証します。チップモデルは RTL8125 の 4 リビジョンと RTL8168 系列の経路をカバーします。実際の" +" PHY ネゴシエーション、DMA タイミング、物理ケーブルでの送受信は、対応するハードウェアで引き続き検証が必要です。" msgid "" "本次 QEMU 回归覆盖默认内置启动,以及无匹配 Realtek 硬件时三次 ``r8169.ko`` 加载与卸载。既有 e1000 的 " -"IPv4、IPv6 ping 均通过。 测试使用当前新编译内核和私有 initramfs,BusyBox 来自已有 ReliefOS 构建。" +"IPv4、IPv6 ping 均通过。 测试在匹配当前内核的 ReliefOS 构建镜像上运行,使用私有测试磁盘。" msgstr "" -"今回の QEMU 回帰テストは、既定の組み込み起動と、一致する Realtek ハードウェアがない場合の ``r8169.ko`` の 3 " -"回のロード・アンロードをカバーします。既存の e1000 の IPv4、IPv6 ping " -"はどちらも成功しています。テストは現在新しくコンパイルしたカーネルと専用 initramfs を使用し、BusyBox は既存の ReliefOS " -"ビルドから取得します。" +"QEMU 回帰テストでは、組み込み構成での起動と、対応 Realtek デバイスがない状態での ``r8169.ko`` の読み込みと取り外しを " +"3 回確認しました。既存 e1000 の IPv4 と IPv6 の ping も通りました。対応する ReliefOS " +"ビルドイメージを専用ディスクで実行します。" msgid "" "本地 QEMU 只提供 RTL8139 Realtek 模型,真实 RTL8111/8168、RTL8125 需要实体网卡或正确的 PCI " diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/resource-limits.po b/Documentation/locale/ja/LC_MESSAGES/core-api/resource-limits.po index 28759d0b..6c6243cb 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/resource-limits.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/resource-limits.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0800\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "资源容量与 Linux ABI" msgstr "リソース容量と Linux ABI" @@ -24,14 +27,14 @@ msgstr "" "を完全実装したことを示しません。メモリ不足、リソース枠、ハードウェアアドレス範囲は引き続きリソース数を制限します。" msgid "" -"``/proc/PID/oom_score`` 使用独立的 Linux 6.12 风格 0..2000 展示值, 不改变内部 OOM 选择策略。RSS " -"只计入有实际 RAM 后备的用户页面,另计 swap 槽引用,不把设备 PFN 当作 RAM。``oom_score_adj`` 的读取和写入先 " -"经过普通 proc DAC 与 PID 身份检查;降低到继承的下限以下需要 ``CAP_SYS_RESOURCE``。进程退出后保留的 proc " -"身份不会指向重用的 PID。" +"``/proc/PID/oom_score`` 使用独立的 Linux 6.12 风格 0..2000 展示值, 不改变内部 OOM " +"选择策略。RSS 只计入有实际 RAM 后备的用户页面,另计 swap 槽引用,不把设备 PFN 当作 RAM。``oom_score_adj``" +" 的读取和写入先 经过普通 proc DAC 与 PID 身份检查;降低到继承的下限以下需要 " +"``CAP_SYS_RESOURCE``。进程退出后保留的 proc 身份不会指向重用的 PID。" msgstr "" "``/proc/PID/oom_score`` は Linux 6.12 形式の独立した 0..2000 の表示値を使用し、内部の OOM " -"選択方針は変えません。RSS は実際の RAM backing を持つユーザーページだけを数え、swap スロット参照は別に計上し、デバイス PFN を" -" RAM と扱いません。``oom_score_adj`` の読み書きはまず通常の proc DAC と PID " +"選択方針は変えません。RSS は実際の RAM backing を持つユーザーページだけを数え、swap スロット参照は別に計上し、デバイス " +"PFN を RAM と扱いません。``oom_score_adj`` の読み書きはまず通常の proc DAC と PID " "識別検査を通り、継承した下限より低くするには ``CAP_SYS_RESOURCE`` が必要です。プロセス終了後に保持された proc " "の識別情報が、再利用された PID を指すことはありません。" @@ -48,23 +51,25 @@ msgid "" msgstr "" "``getrlimit``、``setrlimit``、``prlimit64`` はプロセスで共有する ``RLIMIT_FSIZE`` " "に対応します。新しいプロセスはソフト・ハード両制限とも既定で unlimited となり、fork/exec " -"で継承します。通常ファイルへの書き込みは境界で正当な短い書き込みを返し、境界以降からさらに書くと ``EFBIG`` を返して ``SIGXFSZ`` " +"で継承します。通常ファイルへの書き込みは境界で正当な短い書き込みを返し、境界以降からさらに書くと ``EFBIG`` を返して " +"``SIGXFSZ`` " "を送ります。切り詰めとファイルを拡張する事前割り当ては、書き込み前に新しいサイズを確認します。``FALLOC_FL_KEEP_SIZE`` " "は事前割り当て範囲が制限を超えても論理サイズを変更しません。ファイルコピーと memfd/shmem " -"書き込みもこの制限を受けますが、デバイス、パイプ、生成された proc/sysfs 制御ファイルには通常ファイルのサイズ枠を適用しません。OpenSSH" -" の認証前サンドボックスはこの制限をゼロに下げることができ、それによって無制限のファイル書き込み能力を得ることはありません。" +"書き込みもこの制限を受けますが、デバイス、パイプ、生成された proc/sysfs " +"制御ファイルには通常ファイルのサイズ枠を適用しません。OpenSSH " +"の認証前サンドボックスはこの制限をゼロに下げることができ、それによって無制限のファイル書き込み能力を得ることはありません。" msgid "" "任务枚举直接遍历调度器的任务表。``/proc`` 的进程列表、线程统计以及 memfd 的可写共享映射检查不截断为前 64 " "个任务。描述符目录使用实际文件表 和 PTY 别名,不截断为前 1024 个描述符。" msgstr "" "タスク列挙はスケジューラーのタスクテーブルを直接走査します。``/proc`` のプロセス一覧、スレッド統計、memfd " -"の書き込み可能な共有マッピングの確認は、先頭 64 タスクで打ち切りません。記述子ディレクトリは実際のファイルテーブルと PTY エイリアスを使い、先頭" -" 1024 記述子で打ち切りません。" +"の書き込み可能な共有マッピングの確認は、先頭 64 タスクで打ち切りません。記述子ディレクトリは実際のファイルテーブルと PTY " +"エイリアスを使い、先頭 1024 記述子で打ち切りません。" msgid "" -"内部对象注册表按需扩容,扩容不移动对象,分配在自旋锁外完成。句柄保留 16 位槽号和 16 位代际编码,最多表示 65535 个同时存在的槽;此编码上限" -" 仍然存在。查找句柄只返回借用引用,调用方必须按所属子系统的锁和引用规则 保证对象存活。" +"内部对象注册表按需扩容,扩容不移动对象,分配在自旋锁外完成。句柄保留 16 位槽号和 16 位代际编码,最多表示 65535 " +"个同时存在的槽;此编码上限 仍然存在。查找句柄只返回借用引用,调用方必须按所属子系统的锁和引用规则 保证对象存活。" msgstr "" "内部オブジェクトレジストリーは必要に応じて拡張し、拡張してもオブジェクトは移動せず、割り当てはスピンロック外で行います。ハンドルは 16 " "ビットのスロット番号と 16 ビットの世代エンコードを維持し、同時に存在するスロットを最大 65535 " @@ -78,9 +83,9 @@ msgstr "" msgid "" "epoll 监听表按需扩容;注册键由描述符编号和打开文件描述共同确定。 关闭一个编号后,``dup``、``fork``、排队中的 " "``SCM_RIGHTS`` 或在途 I/O 引用仍可维持原对象的监听;重新使用该编号不会把旧监听转向新对象。 " -"监听项只借用稳定的对象身份,最终引用释放时反向清除监听,不延长对象生命周期。 当前不支持嵌套 epoll,向 epoll 实例注册另一个 epoll " -"实例时返回 ``EPERM``; 直接 ``poll`` epoll 描述符只查看已就绪的监听项,不消费 ET/ONESHOT 状态。 原始 " -"``select``/``pselect6`` 系统调用按 ``nfds`` 复制位图,并检查 " +"监听项只借用稳定的对象身份,最终引用释放时反向清除监听,不延长对象生命周期。 当前不支持嵌套 epoll,向 epoll 实例注册另一个 " +"epoll 实例时返回 ``EPERM``; 直接 ``poll`` epoll 描述符只查看已就绪的监听项,不消费 ET/ONESHOT 状态。" +" 原始 ``select``/``pselect6`` 系统调用按 ``nfds`` 复制位图,并检查 " "``RLIMIT_NOFILE``、溢出、无效描述符和用户指针。libc 的 ``fd_set`` 大小 由 libc 决定,不能用 " "``FD_SET`` 操作其表示范围以外的描述符。" msgstr "" @@ -88,8 +93,8 @@ msgstr "" "の監視テーブルは必要に応じて拡張し、登録キーは記述子番号とオープンファイル記述の組み合わせです。番号をクローズした後も、``dup``、``fork``、待機中の" " ``SCM_RIGHTS``、処理中の I/O " "参照が元のオブジェクトの監視を維持できます。番号の再利用で古い監視が新しいオブジェクトへ向くことはありません。監視項目は安定したオブジェクト識別情報を借用するだけで、最終参照の解放時に逆方向から監視を消去し、オブジェクトの寿命を延ばしません。現在は" -" epoll の入れ子に対応せず、epoll インスタンスに別の epoll インスタンスを登録すると ``EPERM`` を返します。epoll " -"記述子への直接の ``poll`` は準備済み監視だけを確認し、ET/ONESHOT 状態を消費しません。生の " +" epoll の入れ子に対応せず、epoll インスタンスに別の epoll インスタンスを登録すると ``EPERM`` を返します。epoll" +" 記述子への直接の ``poll`` は準備済み監視だけを確認し、ET/ONESHOT 状態を消費しません。生の " "``select``/``pselect6`` システムコールは ``nfds`` " "に従ってビットマップをコピーし、``RLIMIT_NOFILE``、オーバーフロー、無効な記述子、ユーザーポインターを確認します。libc の " "``fd_set`` サイズは libc が決めるため、その表現範囲外の記述子に ``FD_SET`` を使用してはいけません。" @@ -106,31 +111,31 @@ msgstr "" "の原子的な意味を持ち、大きな書き込みは短くなることがあります。" msgid "" -"命名管道按解析后的 inode 类型进入管道实现,不从权限位推断文件类型。 没有对端时,阻塞打开等待另一端;非阻塞写端打开返回 ``ENXIO``。 " -"``O_PATH`` 只保留路径,不参与对端会合。原生探针 ``tools/tests/fifo_abi_test.c`` " +"命名管道按解析后的 inode 类型进入管道实现,不从权限位推断文件类型。 没有对端时,阻塞打开等待另一端;非阻塞写端打开返回 " +"``ENXIO``。 ``O_PATH`` 只保留路径,不参与对端会合。原生探针 ``tools/tests/fifo_abi_test.c`` " "检查磁盘和内存文件系统上的数据、断开通知、 信号中断及打开等待;可通过命令行指定测试目录。" msgstr "" "名前付きパイプは解決後の inode " -"型でパイプ実装に入り、権限ビットからファイル型を推測しません。相手側がない場合、ブロッキングオープンは他端を待ち、非ブロッキングの書き込み端オープンは " -"``ENXIO`` を返します。``O_PATH`` はパスだけを保持し、相手側との合流には参加しません。ネイティブプローブ " +"型でパイプ実装に入り、権限ビットからファイル型を推測しません。相手側がない場合、ブロッキングオープンは他端を待ち、非ブロッキングの書き込み端オープンは" +" ``ENXIO`` を返します。``O_PATH`` はパスだけを保持し、相手側との合流には参加しません。ネイティブプローブ " "``tools/tests/fifo_abi_test.c`` " "はディスクおよびメモリファイルシステムのデータ、切断通知、シグナル割り込み、オープン待機を確認し、テストディレクトリはコマンドラインで指定できます。" msgid "" -"``F_GETPIPE_SZ`` 查询可用容量;``F_SETPIPE_SZ`` 向上取整到至少一页的 二次幂容量。缩小到不足以容纳现有数据时返回 " -"``EBUSY``,失败不改变数据 顺序或容量。" +"``F_GETPIPE_SZ`` 查询可用容量;``F_SETPIPE_SZ`` 向上取整到至少一页的 二次幂容量。缩小到不足以容纳现有数据时返回" +" ``EBUSY``,失败不改变数据 顺序或容量。" msgstr "" "``F_GETPIPE_SZ`` は利用可能容量を照会し、``F_SETPIPE_SZ`` は少なくとも 1 ページ以上の 2 " "のべき乗の容量へ切り上げます。既存データを収容できないサイズへの縮小は ``EBUSY`` を返し、失敗ではデータ順序も容量も変わりません。" msgid "" -"默认容量为 16 页。当前每个 UID 的软预算为 16384 页;达到预算后,新建 管道使用两页。无资源管理能力的调用者不能把单管道扩大到 1 MiB" -" 以上, 也不能通过扩容超出软预算。``CAP_SYS_RESOURCE`` 或 ``CAP_SYS_ADMIN`` " +"默认容量为 16 页。当前每个 UID 的软预算为 16384 页;达到预算后,新建 管道使用两页。无资源管理能力的调用者不能把单管道扩大到 1 " +"MiB 以上, 也不能通过扩容超出软预算。``CAP_SYS_RESOURCE`` 或 ``CAP_SYS_ADMIN`` " "可绕过这项资源策略;分配失败仍会返回错误。这些是内核策略常量,当前未 通过 sysctl 暴露,不能将其误称为已支持 Linux 的全部管道 " "sysctl。" msgstr "" -"既定容量は 16 ページです。現在の UID ごとのソフト予算は 16384 ページで、到達後の新規パイプは 2 ページを使用します。リソース管理 " -"capability のない呼び出し元は、単一パイプを 1 MiB " +"既定容量は 16 ページです。現在の UID ごとのソフト予算は 16384 ページで、到達後の新規パイプは 2 ページを使用します。リソース管理" +" capability のない呼び出し元は、単一パイプを 1 MiB " "より大きくしたり、拡張でソフト予算を超えたりできません。``CAP_SYS_RESOURCE`` または ``CAP_SYS_ADMIN`` " "はこのリソース方針を回避できますが、割り当て失敗は引き続きエラーを返します。これらはカーネルの方針定数で、現在 sysctl " "では公開していません。Linux の全パイプ sysctl に対応済みと表現してはいけません。" @@ -141,15 +146,15 @@ msgid "" "pages/man2/F_GETPIPE_SZ.2const.html>`_。" msgstr "" "参考:`pipe(7) `_、`F_GETPIPE_SZ(2const) `_。" +"pages/man7/pipe.7.html>`_、`F_GETPIPE_SZ(2const) `_。" msgid "匿名共享文件" msgstr "匿名共有ファイル" msgid "" -"memfd 使用不挂载的内部 tmpfs 实例。它不占用用户挂载卷槽,也不需要一个 与文件逻辑大小相同的连续物理内存块。逻辑扩展是稀疏的,实际页面按访问" -" 分配,空洞读为零;不再使用 32 项专用池或桌面分辨率作为文件大小上限。" +"memfd 使用不挂载的内部 tmpfs 实例。它不占用用户挂载卷槽,也不需要一个 " +"与文件逻辑大小相同的连续物理内存块。逻辑扩展是稀疏的,实际页面按访问 分配,空洞读为零;不再使用 32 项专用池或桌面分辨率作为文件大小上限。" msgstr "" "memfd はマウントしない内部 tmpfs " "インスタンスを使用します。ユーザーのマウントボリュームスロットを消費せず、ファイルの論理サイズと同じ大きさの連続物理メモリも必要としません。論理拡張は疎で、実ページはアクセス時に割り当て、穴はゼロとして読み取ります。32" @@ -169,8 +174,8 @@ msgid "" "``EBUSY``;私有 COW 映射不阻止封印。 封印后的新共享映射不能借助后续 ``mprotect`` 绕过写保护。" msgstr "" "seal 状態は共有ファイル記述に付随して保持します。``F_SEAL_WRITE`` の追加時は全タスクの書き込み可能性がある共有 VMA " -"を確認し、存在すれば ``EBUSY`` を返します。非公開 COW マッピングは seal を妨げません。seal 後の新規共有マッピングは、後の " -"``mprotect`` で書き込み保護を回避できません。" +"を確認し、存在すれば ``EBUSY`` を返します。非公開 COW マッピングは seal を妨げません。seal " +"後の新規共有マッピングは、後の ``mprotect`` で書き込み保護を回避できません。" msgid "" "参考:`memfd_create(2) `_、 `RFC " -"9293 `_ 和 `RFC 6298 " +"参考:`epoll(7) `_、 `RFC" +" 9293 `_ 和 `RFC 6298 " "`_。" msgstr "" "参考:`epoll(7) `_、`RFC " @@ -247,48 +256,50 @@ msgid "地址空间与驱动" msgstr "アドレス空間とドライバー" msgid "" -"用户页表按四级层次稀疏分配,支持低 canonical 半区,独占上界为 ``0x0000800000000000``。当前内核仍在低地址运行,保留 " -"``[0x08000000, 0x0c000000)`` 的 supervisor 区间;用户最小地址、堆区和 " -"栈增长窗口也仍有实现边界。这不是无条件可用的完整 128 TiB 连续区间。 ``RLIMIT_AS`` 和页权限检查继续有效。" +"用户页表按四级层次稀疏分配,支持低 canonical 半区,独占上界为 " +"``0x0000800000000000``。当前内核仍在低地址运行,保留 ``[0x08000000, 0x0c000000)`` 的 " +"supervisor 区间;用户最小地址、堆区和 栈增长窗口也仍有实现边界。这不是无条件可用的完整 128 TiB 连续区间。 " +"``RLIMIT_AS`` 和页权限检查继续有效。" msgstr "" -"ユーザーページテーブルは 4 階層で疎に割り当て、低位 canonical 半空間に対応し、含まない上限は ``0x0000800000000000``" -" です。現在のカーネルはまだ低位アドレスで動作し、``[0x08000000, 0x0c000000)`` の supervisor " +"ユーザーページテーブルは 4 階層で疎に割り当て、低位 canonical 半空間に対応し、含まない上限は " +"``0x0000800000000000`` です。現在のカーネルはまだ低位アドレスで動作し、``[0x08000000, " +"0x0c000000)`` の supervisor " "区間を予約します。ユーザー最小アドレス、ヒープ領域、スタック成長ウィンドウにも実装上の境界が残ります。無条件に利用可能な連続 128 TiB " "全域ではありません。``RLIMIT_AS`` とページ権限検査は引き続き有効です。" msgid "" "普通匿名及文件 ``mmap``/``mprotect`` 按请求分别设置读、写和执行权限, 允许显式 ``PROT_WRITE | " -"PROT_EXEC``,以兼容 HotSpot 等 JIT 运行时。 没有请求执行权限的数据页保持 NX;再次移除 ``PROT_EXEC`` 会恢复 " -"NX。 懒分配、驻留匿名页及私有 COW 保持同一权限语义。文件访问模式、只读挂载、 ``noexec``、设备映射限制及 VMA 的 " +"PROT_EXEC``,以兼容 HotSpot 等 JIT 运行时。 没有请求执行权限的数据页保持 NX;再次移除 ``PROT_EXEC`` " +"会恢复 NX。 懒分配、驻留匿名页及私有 COW 保持同一权限语义。文件访问模式、只读挂载、 ``noexec``、设备映射限制及 VMA 的 " "``max_prot`` 上限继续生效,不能通过 后续 ``mprotect`` 增加被禁止的权限。" msgstr "" -"通常の匿名およびファイルの ``mmap``/``mprotect`` は、要求に応じて読み取り、書き込み、実行権限を個別に設定し、HotSpot " -"などの JIT ランタイムとの互換性のため、明示的な ``PROT_WRITE | PROT_EXEC`` " +"通常の匿名およびファイルの ``mmap``/``mprotect`` は、要求に応じて読み取り、書き込み、実行権限を個別に設定し、HotSpot" +" などの JIT ランタイムとの互換性のため、明示的な ``PROT_WRITE | PROT_EXEC`` " "を許可します。実行権限を要求していないデータページは NX を維持し、``PROT_EXEC`` を再び外すと NX " "に戻ります。遅延割り当て、常駐匿名ページ、非公開 COW " "は同じ権限の意味を維持します。ファイルアクセスモード、読み取り専用マウント、``noexec``、デバイスマッピング制限、VMA の " "``max_prot`` 上限は引き続き有効で、後の ``mprotect`` で禁止された権限を追加できません。" msgid "" -"这对应 Linux 默认权限组合行为,不表示已实现 Linux 的 MDWE/LSM 策略接口; SysV SHM 等独立接口的限制也不因此改变。参考 " -"`Linux 6.12 权限及 MDWE 规则 " +"这对应 Linux 默认权限组合行为,不表示已实现 Linux 的 MDWE/LSM 策略接口; SysV SHM " +"等独立接口的限制也不因此改变。参考 `Linux 6.12 权限及 MDWE 规则 " "`_。 " "``tools/tests/jit_memory_runtime_probe.c`` 可在 Linux 和 ReliefOS 中运行, 检查 " "W→WX、RWX 映射、撤销执行权限的 NX 效果及 fork COW 隔离。" msgstr "" "これは Linux の既定の権限組み合わせ動作に対応し、Linux の MDWE/LSM " -"ポリシーインターフェースを実装済みという意味ではありません。SysV SHM など独立したインターフェースの制約も変わりません。`Linux 6.12 " -"の権限および MDWE 規則 " +"ポリシーインターフェースを実装済みという意味ではありません。SysV SHM など独立したインターフェースの制約も変わりません。`Linux " +"6.12 の権限および MDWE 規則 " "`_ " "を参照してください。``tools/tests/jit_memory_runtime_probe.c`` は Linux と ReliefOS " "で実行でき、W→WX、RWX マッピング、実行権限取り消しによる NX の効果、fork COW の分離を確認します。" msgid "" -"跨核屏障和用户 TLB 刷新在内部串行发布请求,使请求代际与操作类型在 所有 CPU 确认前保持稳定。等待锁或确认的 CPU 即使关闭本地中断,也会 " -"处理其他 CPU 已发布的请求;返回时恢复调用前的中断状态。并行缺页中的 刷新也使用同一发布与确认路径。" +"跨核屏障和用户 TLB 刷新在内部串行发布请求,使请求代际与操作类型在 所有 CPU 确认前保持稳定。等待锁或确认的 CPU " +"即使关闭本地中断,也会 处理其他 CPU 已发布的请求;返回时恢复调用前的中断状态。并行缺页中的 刷新也使用同一发布与确认路径。" msgstr "" -"コア間バリアとユーザー TLB フラッシュは、内部で要求を直列に公開し、全 CPU が確認するまで要求世代と操作種別を安定させます。ロックや確認を待つ " -"CPU は、ローカル割り込みを無効化していても他の CPU " +"コア間バリアとユーザー TLB フラッシュは、内部で要求を直列に公開し、全 CPU " +"が確認するまで要求世代と操作種別を安定させます。ロックや確認を待つ CPU は、ローカル割り込みを無効化していても他の CPU " "が公開した要求を処理し、復帰時に呼び出し前の割り込み状態へ戻します。並行ページフォルト中のフラッシュも同じ公開・確認経路を使います。" msgid "" @@ -302,12 +313,12 @@ msgstr "" "を超えても完全な所有権を保ちます。最終的な表現上限に達するとページを固定し、未計上参照による早期回収を防ぎます。" msgid "" -"内核访问物理页面使用 supervisor 直映射。当前 x86 PCI 后端采用直接 DMA, 设备描述符提交可寻址的物理地址,CPU 访问使用 " -"``mm_phys_to_virt`` 或驱动 API 回调;不能将两者混用。当前没有 IOMMU 或总线地址重映射实现,不能把 " -"总线地址与物理地址相同的假设推广到其他平台。 x86-64 内核直映射从 ``0xffff800000000000`` 开始,虚拟窗口为 64 TiB;" -" 可用物理地址还受 CPU 物理地址位数、可信固件拓扑、实际页表和可用元数据 约束。直映射稀疏建立,RAM 空洞不会因为落在窗口内而变成有效指针。 " -"物理类型、CPU 可表示性和页表实际覆盖是三个不同条件;分配器只接纳实际 映射的可信可用 RAM。引导期间页表仍需要在临时低地址映射内取得页面, " -"资源不足会使引导停止。64 TiB 是虚拟设计容量,不是已验证硬件 RAM 容量。" +"内核访问物理页面使用 supervisor 直映射。当前 x86 PCI 后端采用直接 DMA, 设备描述符提交可寻址的物理地址,CPU 访问使用" +" ``mm_phys_to_virt`` 或驱动 API 回调;不能将两者混用。当前没有 IOMMU 或总线地址重映射实现,不能把 " +"总线地址与物理地址相同的假设推广到其他平台。 x86-64 内核直映射从 ``0xffff800000000000`` 开始,虚拟窗口为 64 " +"TiB; 可用物理地址还受 CPU 物理地址位数、可信固件拓扑、实际页表和可用元数据 约束。直映射稀疏建立,RAM " +"空洞不会因为落在窗口内而变成有效指针。 物理类型、CPU 可表示性和页表实际覆盖是三个不同条件;分配器只接纳实际 映射的可信可用 " +"RAM。引导期间页表仍需要在临时低地址映射内取得页面, 资源不足会使引导停止。64 TiB 是虚拟设计容量,不是已验证硬件 RAM 容量。" msgstr "" "カーネルは supervisor の直線マッピングで物理ページにアクセスします。現在の x86 PCI バックエンドは直接 DMA " "を使用し、デバイス記述子には到達可能な物理アドレスを渡し、CPU アクセスには ``mm_phys_to_virt`` またはドライバー API " @@ -322,11 +333,11 @@ msgstr "" " TiB は仮想設計容量であり、検証済みのハードウェア RAM 容量ではありません。" msgid "" -"PCI BAR 可在 RAM 空洞内通过独立设备窗口映射;内核拒绝与 RAM 或已有 直映射别名冲突的缓存属性。DMA 使用设备实际地址掩码分配:例如 " -"DMA32 分配的最后一个字节也必须不超过 ``0xffffffff``。目前没有 IOMMU。 UEFI " +"PCI BAR 可在 RAM 空洞内通过独立设备窗口映射;内核拒绝与 RAM 或已有 直映射别名冲突的缓存属性。DMA " +"使用设备实际地址掩码分配:例如 DMA32 分配的最后一个字节也必须不超过 ``0xffffffff``。目前没有 IOMMU。 UEFI " "若交接时启动服务仍活动,内核必须使用映像句柄和最新内存映射键 成功退出启动服务后才接管常规 RAM;无法证明所有权时停止引导。 " -"固件表发现还需证明当时的地址映射:活动 EFI amd64 入口的身份映射证明 可跨内核自己的退出启动服务调用保留;i386 入口只证明前 4 GiB。" -" 仅有已结束的 EFI 内存描述符不能证明高地址表当前可访问。" +"固件表发现还需证明当时的地址映射:活动 EFI amd64 入口的身份映射证明 可跨内核自己的退出启动服务调用保留;i386 入口只证明前 4 " +"GiB。 仅有已结束的 EFI 内存描述符不能证明高地址表当前可访问。" msgstr "" "PCI BAR は RAM の穴でも独立したデバイスウィンドウでマッピングできます。カーネルは RAM " "や既存の直線マッピングエイリアスと競合するキャッシュ属性を拒否します。DMA はデバイスの実際のアドレスマスクで割り当て、例えば DMA32 " @@ -334,8 +345,8 @@ msgstr "" "の引き渡し時にブートサービスがまだ動作中なら、カーネルはイメージハンドルと最新のメモリマップキーでブートサービスを正常終了してから通常 RAM " "を引き継ぐ必要があります。所有権を証明できなければ起動を停止します。ファームウェアテーブルの探索には、その時点のアドレスマッピングの証明も必要です。動作中" " EFI amd64 エントリーの identity mapping " -"の証明は、カーネル自身によるブートサービス終了呼び出しをまたいで維持できますが、i386 エントリーが証明するのは先頭 4 GiB だけです。終了済み " -"EFI のメモリ記述子だけでは、高位アドレスのテーブルに現在アクセスできることを証明できません。" +"の証明は、カーネル自身によるブートサービス終了呼び出しをまたいで維持できますが、i386 エントリーが証明するのは先頭 4 GiB " +"だけです。終了済み EFI のメモリ記述子だけでは、高位アドレスのテーブルに現在アクセスできることを証明できません。" msgid "" "内部驱动 API 版本为 2,末尾增加 ``phys_to_virt`` 回调。驱动必须检查 版本、``struct_size`` " @@ -343,8 +354,8 @@ msgid "" "当前内置驱动随内核一起构建。" msgstr "" "内部ドライバー API はバージョン 2 で、末尾に ``phys_to_virt`` " -"コールバックを追加しています。ドライバーは使用前にバージョン、``struct_size``、コールバックの存在を確認する必要があります。バージョン 1" -" のドライバーは再ビルドが必要で、カーネルは初期化前に不一致モジュールを拒否します。Linux システムコール ABI " +"コールバックを追加しています。ドライバーは使用前にバージョン、``struct_size``、コールバックの存在を確認する必要があります。バージョン" +" 1 のドライバーは再ビルドが必要で、カーネルは初期化前に不一致モジュールを拒否します。Linux システムコール ABI " "は変わりません。現在の組み込みドライバーはカーネルと一緒にビルドします。" msgid "" @@ -357,8 +368,8 @@ msgstr "" "モジュールの物理アドレスを受け取り、マウント実装内部でのみ変換します。" msgid "" -"参考:`Linux DMA 地址说明 `_ 和 `Linux 6.12 fbdev UAPI " +"参考:`Linux DMA 地址说明 `_ 和 `Linux 6.12 fbdev UAPI " "`_。" msgstr "" "参考:`Linux の DMA アドレス説明 M= modules`` 入口构建;``M`` 目录 " -"会产生构建文件,不能指向源码目录。在来宾使用 ``insmod`` 和 ``rmmod`` 加载、卸载后检查 ``[memory-probe]`` " -"日志:模块只触碰自身取得的 513 页 高于 16 GiB 的连续内存和两页 DMA32 内存,验证零填充及逐页写读, " -"并在所有失败路径释放已取得页面。低内存环境或连续高端内存不足时探针 会报告失败;不能用该失败推断内核其余 RAM 不可用。" +"``MODULE_TESTS``。在使用匹配内核配置及 ABI 的构建环境中, 将其中的 ``Kbuild`` 和 C " +"文件复制到自有输出目录,再用正式 ``make O= M= modules`` " +"入口构建;``M`` 目录 会产生构建文件,不能指向源码目录。在来宾使用 ``insmod`` 和 ``rmmod`` 加载、卸载后检查 " +"``[memory-probe]`` 日志:模块只触碰自身取得的 513 页 高于 16 GiB 的连续内存和两页 DMA32 " +"内存,验证零填充及逐页写读, 并在所有失败路径释放已取得页面。低内存环境或连续高端内存不足时探针 会报告失败;不能用该失败推断内核其余 RAM " +"不可用。" msgstr "" "``tools/tests/kmodules/memory_layout_probe`` は独立した Apache-2.0 " -"の外部モジュールで、``MODULE_TESTS`` の有効化は不要です。対応するカーネル構成と ABI を持つビルド環境で、その ``Kbuild``" -" と C ファイルを自身の出力ディレクトリへコピーし、正式な ``make O= M= " -"modules`` エントリーでビルドします。``M`` " +"の外部モジュールで、``MODULE_TESTS`` の有効化は不要です。対応するカーネル構成と ABI を持つビルド環境で、その " +"``Kbuild`` と C ファイルを自身の出力ディレクトリへコピーし、正式な ``make O= M" +"= modules`` エントリーでビルドします。``M`` " "ディレクトリにはビルドファイルを生成するため、ソースディレクトリを指定してはいけません。ゲストで ``insmod`` と ``rmmod`` " -"によるロード・アンロード後、``[memory-probe]`` ログを確認します。モジュールは自身が取得した 16 GiB より上の連続 513 " -"ページと DMA32 の 2 " +"によるロード・アンロード後、``[memory-probe]`` ログを確認します。モジュールは自身が取得した 16 GiB より上の連続 513" +" ページと DMA32 の 2 " "ページだけにアクセスし、ゼロ埋めとページごとの書き読みを検証し、すべての失敗経路で取得済みページを解放します。メモリが少ない環境や連続した高位メモリが不足する場合、プローブは失敗を報告します。その失敗からカーネルの残りの" " RAM が利用不能と判断してはいけません。" diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/virtio-gpu.po b/Documentation/locale/ja/LC_MESSAGES/core-api/virtio-gpu.po index ccd9a3de..aff68442 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/virtio-gpu.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/virtio-gpu.po @@ -5,7 +5,7 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.3\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2026-11-19 18:40+0800\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: ReliefOS contributors\n" "Language: ja\n" @@ -140,31 +140,21 @@ msgstr "" msgid "验证与上游来源" msgstr "検証と上流の出典" -# | msgid "" "``tools/test_virtio.py`` 在 ASan/UBSan 下运行生产 ring 实现,覆盖乱序、 131080 -# " -# | "次环回绕、背压、非法 used entry 及 fatal 预留链。原生用户态探针 -# ``tools/tests/virtgpu_guest.c``" -# | " 可用 musl 编译,执行实际 DRM、PRIME、 sync_file、sysfs、翻页和光标操作;用 ``--no-pause`` " -# | "跳过截图握手。 完整系统、Mesa/EGL、Xorg、BIOS/UEFI 及模块重载的 QEMU 编排由 ReliefOS 持有。 离屏 -# draw" -# | " 速率不能替代桌面帧率或实体显卡性能。VMware 验证未完成。" msgid "" "``tools/test_virtio.py`` 在 ASan/UBSan 下运行生产 ring 实现,覆盖乱序、 131080 " "次环回绕、背压、非法 used entry 及 fatal 预留链。原生用户态探针 ``tools/tests/virtgpu_guest.c``" -" 可用 musl 编译,执行实际 DRM、PRIME、 sync_file、sysfs、翻页和光标操作;用 ``--no-pause`` " +" 可用 glibc 编译,执行实际 DRM、PRIME、 sync_file、sysfs、翻页和光标操作;用 ``--no-pause`` " "跳过截图握手。 ``tools/test_drm.py`` 覆盖局部文本上传的偏移、失败重试、VT 整屏恢复, 以及 2D DIRTYFB " "的区域拆分、合并和校验。 完整系统、Mesa/EGL、Xorg、BIOS/UEFI 及模块重载的 QEMU 编排由 ReliefOS 持有。 离屏" " draw 速率不能替代桌面帧率或实体显卡性能。VMware 验证未完成。" msgstr "" -"``tools/test_virtio.py`` は ASan/UBSan 下で本番 ring 実装を実行し、順不同の完了、131080 " -"回のリング折り返し、背圧、不正な used entry、fatal 予約チェーンを検証します。ネイティブユーザー空間プローブ " -"``tools/tests/virtgpu_guest.c`` は musl でコンパイルでき、実際の " -"DRM、PRIME、sync_file、sysfs、page flip、カーソル操作を実行します。``--no-pause`` " -"でスクリーンショットのハンドシェイクを省略できます。``tools/test_drm.py`` " -"は部分テキスト転送のオフセット、更新失敗時の再試行、VT 全体の復元、2D DIRTYFB " -"領域の分割・統合・検証を確認します。システム全体、Mesa/EGL、Xorg、BIOS/UEFI、モジュール再読み込みの QEMU 編成は " -"ReliefOS が担当します。オフスクリーン描画速度はデスクトップのフレームレートや実機 GPU " -"性能の測定に代わるものではありません。VMware の検証は未完了です。" +"``tools/test_virtio.py`` は本番のリング実装を ASan/UBSan で実行し、順序が異なる完了、131080 " +"回の折り返し、バックプレッシャー、無効 used " +"エントリー、致命的な予約チェーンを検査します。``tools/tests/virtgpu_guest.c`` は glibc でビルドし、ゲストで" +" DRM、PRIME、sync_file、sysfs、ページフリップ、カーソルを実行します。``--no-pause`` " +"は画面取得の待ち合わせを省略します。``tools/test_drm.py`` は部分転送、再試行、VT の全画面復元、2D DIRTYFB " +"の領域処理を検査します。Mesa/EGL、Xorg、BIOS/UEFI、モジュール再読み込みの統合検査は ReliefOS " +"が担当します。オフスクリーン描画速度は対象の負荷についての値です。VMware の検証は未完了です。" msgid "" "协议参考 OASIS VirtIO 1.3 第 4.1、2.7 和 5.7 节。VirtGPU、VirtIO-GPU 与 sync_file " diff --git a/Documentation/locale/ja/LC_MESSAGES/kbuild/modules.po b/Documentation/locale/ja/LC_MESSAGES/kbuild/modules.po index 60a6da36..83d20cfe 100644 --- a/Documentation/locale/ja/LC_MESSAGES/kbuild/modules.po +++ b/Documentation/locale/ja/LC_MESSAGES/kbuild/modules.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "原生内核模块与 SDK" msgstr "ネイティブカーネルモジュールと SDK" @@ -20,20 +23,23 @@ msgid "兼容边界" msgstr "互換性の範囲" msgid "" -"ReliefNT 使用 Linux 风格的 ELF64 .ko、Kbuild、模块元数据和符号版本机制。 模块必须针对匹配的 ReliefNT 内核重新编译;Linux 的内部内核 API 和原版" -" Linux 二进制 .ko 不属于兼容目标。POSIX 不定义内核模块格式或模块加载接口。" +"ReliefNT 使用 Linux 风格的 ELF64 .ko、Kbuild、模块元数据和符号版本机制。 模块必须针对匹配的 ReliefNT " +"内核重新编译;Linux 的内部内核 API 和原版 Linux 二进制 .ko 不属于兼容目标。POSIX 不定义内核模块格式或模块加载接口。" msgstr "" -"ReliefNT は Linux 形式の ELF64 .ko、Kbuild、モジュールメタデータ、シンボルバージョン管理を使います。モジュールは対応する ReliefNT " -"カーネル向けに再コンパイルする必要があります。Linux 内部カーネル API や元の Linux バイナリー .ko は互換性の対象ではありません。POSIX " -"はカーネルモジュール形式やモジュール読み込みインターフェースを定義していません。" +"ReliefNT は Linux 形式の ELF64 " +".ko、Kbuild、モジュールメタデータ、シンボルバージョン管理を使います。モジュールは対応する ReliefNT " +"カーネル向けに再コンパイルする必要があります。Linux 内部カーネル API や元の Linux バイナリー .ko " +"は互換性の対象ではありません。POSIX はカーネルモジュール形式やモジュール読み込みインターフェースを定義していません。" msgid "" -"默认 defconfig 的生产驱动为 y;已开放的 tristate 可以在 menuconfig 中 选择 m。关闭 MODULES 时不能选择 m,内建配置仍可构建。测试模块由 " -"MODULE_TESTS 显式开启,不进入默认产品。 完整生产部件及依赖矩阵见 :doc:`../core-api/drivers`。" +"默认 defconfig 的生产驱动为 y;已开放的 tristate 可以在 menuconfig 中 选择 m。关闭 MODULES " +"时不能选择 m,内建配置仍可构建。测试模块由 MODULE_TESTS 显式开启,不进入默认产品。 完整生产部件及依赖矩阵见 :doc" +":`../core-api/drivers`。" msgstr "" -"デフォルト defconfig の製品用ドライバーは y で、有効になっている tristate は menuconfig で m を選択できます。MODULES を無効にすると m " -"は選べませんが、組み込み設定は引き続きビルドできます。テストモジュールは MODULE_TESTS で明示的に有効化し、デフォルト製品には含めません。製品用構成要素と依存関係の完全な表は " -":doc:`../core-api/drivers` を参照してください。" +"デフォルト defconfig の製品用ドライバーは y で、有効になっている tristate は menuconfig で m " +"を選択できます。MODULES を無効にすると m は選べませんが、組み込み設定は引き続きビルドできます。テストモジュールは " +"MODULE_TESTS で明示的に有効化し、デフォルト製品には含めません。製品用構成要素と依存関係の完全な表は :doc:`../core-" +"api/drivers` を参照してください。" msgid "构建与安装" msgstr "ビルドとインストール" @@ -43,60 +49,70 @@ msgstr "ReliefNT ソースのルートで実行します::" msgid "" "modules 使用固定的 Linux 6.12 编译、modpost 和最终链接规则,生成 " -"Module.symvers、modules.order、modules.builtin、modules.builtin.modinfo 与选中的 .ko。modules_prepare " -"准备宿主工具和生成头文件;它不替代生成 完整符号版本清单所需的内核构建。" +"Module.symvers、modules.order、modules.builtin、modules.builtin.modinfo 与选中的" +" .ko。modules_prepare 准备宿主工具和生成头文件;它不替代生成 完整符号版本清单所需的内核构建。" msgstr "" "modules は固定された Linux 6.12 " "のコンパイル、modpost、最終リンク規則を使い、Module.symvers、modules.order、modules.builtin、modules.builtin.modinfo、選択した" -" .ko を生成します。modules_prepare はホストツールと生成ヘッダーを準備しますが、完全なシンボルバージョン一覧の生成に必要なカーネルビルドを代替するものではありません。" +" .ko を生成します。modules_prepare " +"はホストツールと生成ヘッダーを準備しますが、完全なシンボルバージョン一覧の生成に必要なカーネルビルドを代替するものではありません。" msgid "" -"完整原生 release 保存在 O/include/config/kernel.release,ABI 摘要在 O/include/config/module.abi。安装目录为 " -"/lib/modules//kernel/, 树外模块使用 updates/。只清理由相应安装清单管理的旧产物,保留其他 release " -"和用户模块。覆盖已修改的受管文件会导致明确错误;不再生成的旧文件若被 用户修改则予以保留,不将它作为陈旧产物删除。" +"完整原生 release 保存在 O/include/config/kernel.release,ABI 摘要在 " +"O/include/config/module.abi。安装目录为 /lib/modules//kernel/, 树外模块使用 " +"updates/。只清理由相应安装清单管理的旧产物,保留其他 release 和用户模块。覆盖已修改的受管文件会导致明确错误;不再生成的旧文件若被" +" 用户修改则予以保留,不将它作为陈旧产物删除。" msgstr "" -"完全なネイティブ release は O/include/config/kernel.release、ABI ダイジェストは O/include/config/module.abi " -"に保存します。インストール先は /lib/modules//kernel/ で、ツリー外モジュールは updates/ " +"完全なネイティブ release は O/include/config/kernel.release、ABI ダイジェストは " +"O/include/config/module.abi に保存します。インストール先は " +"/lib/modules//kernel/ で、ツリー外モジュールは updates/ " "を使います。対応するインストールマニフェストが管理する古い成果物だけを削除し、他の release " "やユーザーモジュールは保持します。変更済みの管理ファイルを上書きすると明示的なエラーになります。生成されなくなった古いファイルもユーザーが変更していれば保持し、不要な成果物として削除しません。" msgid "" -"内核构建标识及 SOURCE_DATE_EPOCH 纳入 ABI 摘要,构建信息变化会产生新的 release。要从不包含 Git 元数据的源码归档重现原有 release,需要向 make " -"提供相同的 RELIEFNT_SOURCE_ID 和 SOURCE_DATE_EPOCH。" +"内核构建标识及 SOURCE_DATE_EPOCH 纳入 ABI 摘要,构建信息变化会产生新的 release。要从不包含 Git " +"元数据的源码归档重现原有 release,需要向 make 提供相同的 RELIEFNT_SOURCE_ID 和 " +"SOURCE_DATE_EPOCH。" msgstr "" -"カーネルのビルド識別子と SOURCE_DATE_EPOCH は ABI ダイジェストに含まれるため、ビルド情報が変わると新しい release が生成されます。Git " -"メタデータを含まないソースアーカイブから既存の release を再現するには、同じ RELIEFNT_SOURCE_ID と SOURCE_DATE_EPOCH を make に指定します。" +"カーネルのビルド識別子と SOURCE_DATE_EPOCH は ABI ダイジェストに含まれるため、ビルド情報が変わると新しい release " +"が生成されます。Git メタデータを含まないソースアーカイブから既存の release を再現するには、同じ RELIEFNT_SOURCE_ID" +" と SOURCE_DATE_EPOCH を make に指定します。" msgid "模块元数据" msgstr "モジュールメタデータ" msgid "" -"默认构建的最终 ``.ko`` 导出表保留 Linux 风格的 ``__ksymtab_<符号名>``、 ``__kstrtab_<符号名>`` 与 ``__kstrtabns_<符号名>`` " -"标签,供模块工具建立 符号索引。普通和 GPL 导出、函数和数据导出都使用这些标签;原生表项仍为 地址、名称和命名空间三个指针。``Module.symvers`` 记录类型 CRC,不能用 " -"普通全局符号表代替实际导出清单。" +"默认构建的最终 ``.ko`` 导出表保留 Linux 风格的 ``__ksymtab_<符号名>``、 ``__kstrtab_<符号名>`` " +"与 ``__kstrtabns_<符号名>`` 标签,供模块工具建立 符号索引。普通和 GPL 导出、函数和数据导出都使用这些标签;原生表项仍为 " +"地址、名称和命名空间三个指针。``Module.symvers`` 记录类型 CRC,不能用 普通全局符号表代替实际导出清单。" msgstr "" "デフォルトビルドの最終 ``.ko`` エクスポート表は、モジュールツールがシンボル索引を作れるよう、Linux 形式の " -"``__ksymtab_<符号名>``、``__kstrtab_<符号名>``、``__kstrtabns_<符号名>`` ラベルを保持します。通常/GPL " -"エクスポート、関数/データエクスポートのいずれもこれらのラベルを使い、ネイティブ項目は引き続きアドレス、名前、名前空間の 3 ポインターです。``Module.symvers`` は型 CRC " +"``__ksymtab_<符号名>``、``__kstrtab_<符号名>``、``__kstrtabns_<符号名>`` " +"ラベルを保持します。通常/GPL " +"エクスポート、関数/データエクスポートのいずれもこれらのラベルを使い、ネイティブ項目は引き続きアドレス、名前、名前空間の 3 " +"ポインターです。``Module.symvers`` は型 CRC " "を記録し、通常のグローバルシンボル表で実際のエクスポート一覧を代用することはできません。" msgid "" -"依赖这些标签的模块工具需要保留本地符号。安装时 ``INSTALL_MOD_STRIP=1`` 仅剥除调试信息,保留这些标签;自定义 ``--strip-unneeded`` 或 " -"``--strip-all`` 会移除标签,不适用于依赖标签扫描的 ``depmod``。" +"依赖这些标签的模块工具需要保留本地符号。安装时 ``INSTALL_MOD_STRIP=1`` 仅剥除调试信息,保留这些标签;自定义 " +"``--strip-unneeded`` 或 ``--strip-all`` 会移除标签,不适用于依赖标签扫描的 ``depmod``。" msgstr "" "これらのラベルに依存するモジュールツールには、ローカルシンボルの保持が必要です。インストール時の ``INSTALL_MOD_STRIP=1`` " -"はデバッグ情報だけを除去し、ラベルを保持します。独自の ``--strip-unneeded`` や ``--strip-all`` はラベルを除去するため、ラベル走査に依存する " -"``depmod`` には適しません。" +"はデバッグ情報だけを除去し、ラベルを保持します。独自の ``--strip-unneeded`` や ``--strip-all`` " +"はラベルを除去するため、ラベル走査に依存する ``depmod`` には適しません。" msgid "" -"``modules.builtin`` 列出内置模块路径;``modules.builtin.modinfo`` 保存 以模块名加点号为前缀、以 NUL 分隔的元数据。模块工具需要读取这些文件 " -"才能查询内置模块及其别名。内置模块不写入动态 ``/proc/modules`` 列表, 也不生成用于冒充可加载模块的 ``.ko`` 文件。文件约定见 `Linux Kbuild 输出文件 " +"``modules.builtin`` 列出内置模块路径;``modules.builtin.modinfo`` 保存 以模块名加点号为前缀、以 " +"NUL 分隔的元数据。模块工具需要读取这些文件 才能查询内置模块及其别名。内置模块不写入动态 ``/proc/modules`` 列表, " +"也不生成用于冒充可加载模块的 ``.ko`` 文件。文件约定见 `Linux Kbuild 输出文件 " "`_。" msgstr "" -"``modules.builtin`` は組み込みモジュールのパスを列挙し、``modules.builtin.modinfo`` はモジュール名とドットを接頭辞に持つ NUL " -"区切りのメタデータを保存します。組み込みモジュールとその別名を問い合わせるには、モジュールツールがこれらのファイルを読む必要があります。組み込みモジュールは動的な " -"``/proc/modules`` 一覧に記載せず、読み込み可能なモジュールに見せかける ``.ko`` ファイルも生成しません。ファイル規約は `Linux Kbuild の出力ファイル " -"`_ を参照してください。" +"``modules.builtin`` は組み込みモジュールのパスを列挙し、``modules.builtin.modinfo`` " +"はモジュール名とドットを接頭辞に持つ NUL " +"区切りのメタデータを保存します。組み込みモジュールとその別名を問い合わせるには、モジュールツールがこれらのファイルを読む必要があります。組み込みモジュールは動的な" +" ``/proc/modules`` 一覧に記載せず、読み込み可能なモジュールに見せかける ``.ko`` ファイルも生成しません。ファイル規約は" +" `Linux Kbuild の出力ファイル `_ を参照してください。" msgid "树外模块" msgstr "ツリー外モジュール" @@ -105,12 +121,13 @@ msgid "模块目录中的 Kbuild::" msgstr "モジュールディレクトリー内の Kbuild::" msgid "" -"hello.c 使用 reliefnt/module.h 的 module_init、module_exit 和 MODULE_LICENSE 等接口。导出符号须使用 " -"reliefnt/export.h;外置模块采用 原生模块的地址模型,不能沿用内建内核的直接地址或静态 DMA 假设。" +"hello.c 使用 reliefnt/module.h 的 module_init、module_exit 和 MODULE_LICENSE " +"等接口。导出符号须使用 reliefnt/export.h;外置模块采用 原生模块的地址模型,不能沿用内建内核的直接地址或静态 DMA 假设。" msgstr "" "hello.c は reliefnt/module.h の module_init、module_exit、MODULE_LICENSE " "などのインターフェースを使います。シンボルのエクスポートには reliefnt/export.h " -"を使う必要があります。外部モジュールはネイティブモジュールのアドレスモデルを採用し、組み込みカーネルの直接アドレスや静的 DMA の前提を流用してはなりません。" +"を使う必要があります。外部モジュールはネイティブモジュールのアドレスモデルを採用し、組み込みカーネルの直接アドレスや静的 DMA " +"の前提を流用してはなりません。" msgid "使用完整源码与已有输出时::" msgstr "完全なソースと既存の出力を使う場合::" @@ -119,78 +136,95 @@ msgid "也可以导出独立 prepared SDK::" msgstr "独立した prepared SDK もエクスポートできます::" msgid "" -"prepared SDK 带匹配头文件、生成配置、ABI、Module.symvers,以及原版 fixdep、genksyms、modpost 和 Kbuild " -"输入。它不带内核实现源码,也不通过 重新编译整个内核来构建树外模块。源码/输出树仍可用时直接调用 M=;部署后的 /lib/modules//build 指向同一前缀内的 " -"prepared SDK。" +"prepared SDK 带匹配头文件、生成配置、ABI、Module.symvers,以及原版 fixdep、genksyms、modpost " +"和 Kbuild 输入。它不带内核实现源码,也不通过 重新编译整个内核来构建树外模块。源码/输出树仍可用时直接调用 M=;部署后的 " +"/lib/modules//build 指向同一前缀内的 prepared SDK。" msgstr "" -"prepared SDK には対応するヘッダー、生成済み設定、ABI、Module.symvers、および元の fixdep、genksyms、modpost、Kbuild " -"入力を含みます。カーネル実装のソースは含まず、カーネル全体を再コンパイルせずにツリー外モジュールをビルドします。ソース/出力ツリーが利用できる間は直接 M= を呼びます。配置後の " -"/lib/modules//build は同じプレフィックス内の prepared SDK を指します。" +"prepared SDK には対応するヘッダー、生成済み設定、ABI、Module.symvers、および元の " +"fixdep、genksyms、modpost、Kbuild " +"入力を含みます。カーネル実装のソースは含まず、カーネル全体を再コンパイルせずにツリー外モジュールをビルドします。ソース/出力ツリーが利用できる間は直接" +" M= を呼びます。配置後の /lib/modules//build は同じプレフィックス内の prepared SDK " +"を指します。" msgid "" -"该 SDK 支持与生成它的 Linux x86_64 宿主工具环境相匹配的构建。目标工具 必须具有匹配身份;允许同一工具搬到其他目录,并可显式传入 CC、AR、LD、 " -"OBJCOPY。改变内核架构、PROFILE、编译策略或头文件应从完整源码重新构建并 导出新的 SDK,不能继续沿用旧 ABI 标记。SDK 本身可只读,构建产物与临时 文件写入 M= " -"目录;模块安装仍需指定可写的 INSTALL_MOD_PATH。 沿用 Linux Kbuild 的路径要求,SDK 和构建目录不能包含空白字符。" +"该 SDK 支持与生成它的 Linux x86_64 宿主工具环境相匹配的构建。目标工具 必须具有匹配身份;允许同一工具搬到其他目录,并可显式传入" +" CC、AR、LD、 OBJCOPY。改变内核架构、PROFILE、编译策略或头文件应从完整源码重新构建并 导出新的 SDK,不能继续沿用旧 " +"ABI 标记。SDK 本身可只读,构建产物与临时 文件写入 M= 目录;模块安装仍需指定可写的 INSTALL_MOD_PATH。 沿用 " +"Linux Kbuild 的路径要求,SDK 和构建目录不能包含空白字符。" msgstr "" "この SDK は、生成に使った Linux x86_64 " -"ホストツール環境に対応するビルドを支援します。ターゲットツールの識別情報は一致する必要があります。同じツールを別のディレクトリーへ移すことは可能で、CC、AR、LD、OBJCOPY " -"を明示的に渡せます。カーネルアーキテクチャー、PROFILE、コンパイル方針、ヘッダーを変更する場合は完全なソースから再ビルドして新しい SDK をエクスポートし、古い ABI " -"マーカーを流用してはなりません。SDK 自体は読み取り専用にでき、成果物と一時ファイルは M= ディレクトリーに書き込みます。モジュールのインストールには引き続き書き込み可能な " -"INSTALL_MOD_PATH が必要です。Linux Kbuild のパス要件に従い、SDK とビルドディレクトリーに空白文字を含めてはなりません。" +"ホストツール環境に対応するビルドを支援します。ターゲットツールの識別情報は一致する必要があります。同じツールを別のディレクトリーへ移すことは可能で、CC、AR、LD、OBJCOPY" +" を明示的に渡せます。カーネルアーキテクチャー、PROFILE、コンパイル方針、ヘッダーを変更する場合は完全なソースから再ビルドして新しい SDK" +" をエクスポートし、古い ABI マーカーを流用してはなりません。SDK 自体は読み取り専用にでき、成果物と一時ファイルは M= " +"ディレクトリーに書き込みます。モジュールのインストールには引き続き書き込み可能な INSTALL_MOD_PATH が必要です。Linux " +"Kbuild のパス要件に従い、SDK とビルドディレクトリーに空白文字を含めてはなりません。" msgid "加载诊断" msgstr "読み込みの診断" msgid "" -"加载器校验完整 vermagic、类型 CRC、依赖和参数,并实现 Linux 编号的 init_module、finit_module、delete_module;调用者需要 " -"CAP_SYS_MODULE。 finit_module 不支持的装载标志明确返回错误。delete_module 与 Linux 6.12 禁用强制卸载的配置一致,接受 BusyBox 使用的 " +"加载器校验完整 vermagic、类型 CRC、依赖和参数,并实现 Linux 编号的 " +"init_module、finit_module、delete_module;调用者需要 CAP_SYS_MODULE。 finit_module" +" 不支持的装载标志明确返回错误。delete_module 与 Linux 6.12 禁用强制卸载的配置一致,接受用户态模块工具传入的 " "O_EXCL,并忽略额外位; O_TRUNC 也不会绕过引用、exit 或硬件停止检查。finit_module 使用独立文件快照,不移动共享 " "文件偏移;已有可写文件描述会阻止快照,快照期间也不能新增可写打开。" msgstr "" -"ローダーは完全な vermagic、型 CRC、依存関係、パラメーターを検査し、Linux 番号の init_module、finit_module、delete_module " -"を実装します。呼び出し側には CAP_SYS_MODULE が必要です。finit_module の非対応読み込みフラグは明示的なエラーを返します。delete_module " -"は強制アンロードを無効にした Linux 6.12 と同様に、BusyBox が使う O_EXCL を受け付け、追加ビットを無視します。O_TRUNC " -"でも参照、exit、ハードウェア停止の検査は迂回できません。finit_module " -"は独立したファイルスナップショットを使い、共有ファイルオフセットを動かしません。既存の書き込み可能なファイル記述はスナップショットを阻止し、取得中も新しい書き込み可能な open はできません。" +"ローダーは vermagic、型 CRC、依存関係、引数を検証します。Linux 番号の " +"init_module、finit_module、delete_module を実装し、CAP_SYS_MODULE " +"を要求します。finit_module は未対応のフラグを拒否します。強制取り外しを無効にした Linux 6.12 " +"と同様、delete_module は O_EXCL を受け付け、余分なビットを無視します。O_TRUNC " +"でも参照、exit、ハードウェア停止の検査を行います。finit_module " +"は共有オフセットを変えずにファイルをスナップショットし、その間の書き込み可能なオープンを排除します。" msgid "" -"模块状态为 COMING、LIVE、GOING。LIVE 表示代码加载成功,是否发现并激活 硬件应检查驱动状态,不能把没有相应硬件的成功注册当作硬件验证。 " -"打开设备、挂载、映射、依赖和执行中的回调会约束卸载;设备停止失败时保留 代码与 DMA 所有权以便诊断和重试。/proc/modules 与 /sys/module 提供状态视图。" +"模块状态为 COMING、LIVE、GOING。LIVE 表示代码加载成功,是否发现并激活 " +"硬件应检查驱动状态,不能把没有相应硬件的成功注册当作硬件验证。 打开设备、挂载、映射、依赖和执行中的回调会约束卸载;设备停止失败时保留 代码与 " +"DMA 所有权以便诊断和重试。/proc/modules 与 /sys/module 提供状态视图。" msgstr "" "モジュールの状態は COMING、LIVE、GOING です。LIVE " "はコードの読み込み成功を意味します。ハードウェアの検出と有効化はドライバー状態で確認し、該当ハードウェアがない場合の登録成功をハードウェア検証としてはなりません。開いているデバイス、マウント、マッピング、依存関係、実行中のコールバックはアンロードを制約します。デバイス停止に失敗した場合は診断と再試行のためコードと" " DMA の所有権を保持します。/proc/modules と /sys/module が状態を表示します。" msgid "" -"模块参数遵循 Linux 风格的 ``module_param`` 类型、命令行解析和 sysfs 权限。 例如 DRM 的只读布尔参数 ``faildiag`` 可在内核命令行中写为 " -"``drm.faildiag=1``,或在装载时使用 ``modprobe drm faildiag=1``。 内置驱动由内核参数框架处理,外置驱动由 modprobe 传入同一参数描述表; " -"诊断在初始化时设置。使用 ``0`` 或 ``N`` 可禁用,非法布尔值会拒绝装载。 只读或权限为零的参数不能从 sysfs 任意修改;卸载后的旧参数句柄不能指向 " -"重新加载模块的存储。模块版本与导出符号类型 CRC 不匹配必须重新构建, 不提供忽略 vermagic 或 CRC 的强制装载选项。模块内存采用独立的代码、只读 " -"和可写区域,页权限与直映射别名同时约束,所有 CPU 保持 WP/NXE。" +"模块参数遵循 Linux 风格的 ``module_param`` 类型、命令行解析和 sysfs 权限。 例如 DRM 的只读布尔参数 " +"``faildiag`` 可在内核命令行中写为 ``drm.faildiag=1``,或在装载时使用 ``modprobe drm " +"faildiag=1``。 内置驱动由内核参数框架处理,外置驱动由 modprobe 传入同一参数描述表; 诊断在初始化时设置。使用 ``0`` " +"或 ``N`` 可禁用,非法布尔值会拒绝装载。 只读或权限为零的参数不能从 sysfs 任意修改;卸载后的旧参数句柄不能指向 " +"重新加载模块的存储。模块版本与导出符号类型 CRC 不匹配必须重新构建, 不提供忽略 vermagic 或 CRC " +"的强制装载选项。模块内存采用独立的代码、只读 和可写区域,页权限与直映射别名同时约束,所有 CPU 保持 WP/NXE。" msgstr "" -"モジュールパラメーターは Linux 形式の ``module_param`` の型、コマンドライン解析、sysfs 権限に従います。たとえば DRM の読み取り専用ブール値 " -"``faildiag`` は、カーネルコマンドラインで ``drm.faildiag=1``、または読み込み時に ``modprobe drm faildiag=1`` " -"と指定できます。組み込みドライバーはカーネルのパラメーターフレームワークが処理し、外部ドライバーには modprobe が同じパラメーター記述表へ渡します。診断は初期化時に設定します。``0`` " -"または ``N`` で無効にでき、不正なブール値は読み込みを拒否します。読み取り専用または権限ゼロのパラメーターは sysfs " -"から任意に変更できません。アンロード後の古いパラメーターハンドルは、再読み込みしたモジュールの記憶領域を指してはなりません。モジュールバージョンやエクスポートシンボルの型 CRC " -"が不一致なら再ビルドが必要で、vermagic や CRC " -"を無視する強制読み込みオプションは提供しません。モジュールメモリーはコード、読み取り専用、書き込み可能の独立した領域を使い、ページ権限とダイレクトマップのエイリアスをともに制約し、全 CPU で " -"WP/NXE を維持します。" +"モジュールパラメーターは Linux 形式の ``module_param`` の型、コマンドライン解析、sysfs 権限に従います。たとえば " +"DRM の読み取り専用ブール値 ``faildiag`` は、カーネルコマンドラインで ``drm.faildiag=1``、または読み込み時に " +"``modprobe drm faildiag=1`` " +"と指定できます。組み込みドライバーはカーネルのパラメーターフレームワークが処理し、外部ドライバーには modprobe " +"が同じパラメーター記述表へ渡します。診断は初期化時に設定します。``0`` または ``N`` " +"で無効にでき、不正なブール値は読み込みを拒否します。読み取り専用または権限ゼロのパラメーターは sysfs " +"から任意に変更できません。アンロード後の古いパラメーターハンドルは、再読み込みしたモジュールの記憶領域を指してはなりません。モジュールバージョンやエクスポートシンボルの型" +" CRC が不一致なら再ビルドが必要で、vermagic や CRC " +"を無視する強制読み込みオプションは提供しません。モジュールメモリーはコード、読み取り専用、書き込み可能の独立した領域を使い、ページ権限とダイレクトマップのエイリアスをともに制約し、全" +" CPU で WP/NXE を維持します。" msgid "" -"未定义弱符号只有在确实没有对应导出时才解析为零。若同名导出存在,但类型 CRC、许可证或 namespace 不匹配,加载仍须失败;弱绑定不能绕过这些检查。 x86_64 加载器支持 " -"NONE、64、32、32S、PC32、PLT32 与 PC64 重定位; 未知类型或不可表示的结果会被拒绝。32S 按符号扩展检查,合法负值不会仅因 其为负而被拒绝;越界时不写入目标位置。" +"未定义弱符号只有在确实没有对应导出时才解析为零。若同名导出存在,但类型 CRC、许可证或 namespace " +"不匹配,加载仍须失败;弱绑定不能绕过这些检查。 x86_64 加载器支持 NONE、64、32、32S、PC32、PLT32 与 PC64 " +"重定位; 未知类型或不可表示的结果会被拒绝。32S 按符号扩展检查,合法负值不会仅因 其为负而被拒绝;越界时不写入目标位置。" msgstr "" -"未定義の弱シンボルは、対応するエクスポートが本当にない場合だけゼロに解決します。同名のエクスポートが存在し、型 CRC、ライセンス、namespace " -"が不一致の場合は、読み込みを失敗させる必要があります。弱い束縛でこれらの検査を迂回することはできません。x86_64 ローダーは NONE、64、32、32S、PC32、PLT32、PC64 " -"再配置に対応し、未知の型や表現不能な結果は拒否します。32S は符号拡張で検査し、有効な負数を負であることだけを理由に拒否しません。範囲外の場合は対象位置へ書き込みません。" +"未定義の弱シンボルは、対応するエクスポートが本当にない場合だけゼロに解決します。同名のエクスポートが存在し、型 " +"CRC、ライセンス、namespace " +"が不一致の場合は、読み込みを失敗させる必要があります。弱い束縛でこれらの検査を迂回することはできません。x86_64 ローダーは " +"NONE、64、32、32S、PC32、PLT32、PC64 再配置に対応し、未知の型や表現不能な結果は拒否します。32S " +"は符号拡張で検査し、有効な負数を負であることだけを理由に拒否しません。範囲外の場合は対象位置へ書き込みません。" -msgid "初始化代码随模块保留到卸载,首版不提供 Linux 内部 ``__init`` API 或 初始化段提前回收。模块初始化结束并不能证明注册的回调已不再引用这些段。" +msgid "" +"初始化代码随模块保留到卸载,首版不提供 Linux 内部 ``__init`` API 或 " +"初始化段提前回收。模块初始化结束并不能证明注册的回调已不再引用这些段。" msgstr "" "初期化コードはアンロードまでモジュールとともに保持します。初版は Linux 内部の ``__init`` API " "や初期化セクションの早期回収を提供しません。モジュール初期化の完了だけでは、登録済みコールバックがそれらのセクションを参照しなくなったとは証明できません。" -msgid "根文件系统模块的启动加载、模块管理命令与镜像更新集成由 ReliefOS 构建链 负责;应分别验证编译、打包、BIOS/UEFI 启动和实际设备操作。" +msgid "" +"根文件系统模块的启动加载、模块管理命令与镜像更新集成由 ReliefOS 构建链 负责;应分别验证编译、打包、BIOS/UEFI " +"启动和实际设备操作。" msgstr "" -"ルートファイルシステム用モジュールの起動時読み込み、モジュール管理コマンド、イメージ更新との統合は ReliefOS のビルドチェーンが担当します。コンパイル、パッケージング、BIOS/UEFI " -"起動、実際のデバイス操作を個別に検証する必要があります。" +"ルートファイルシステム用モジュールの起動時読み込み、モジュール管理コマンド、イメージ更新との統合は ReliefOS " +"のビルドチェーンが担当します。コンパイル、パッケージング、BIOS/UEFI 起動、実際のデバイス操作を個別に検証する必要があります。" diff --git a/Documentation/locale/ja/LC_MESSAGES/process/e1000e-plan.po b/Documentation/locale/ja/LC_MESSAGES/process/e1000e-plan.po index 681577c6..28fb3b46 100644 --- a/Documentation/locale/ja/LC_MESSAGES/process/e1000e-plan.po +++ b/Documentation/locale/ja/LC_MESSAGES/process/e1000e-plan.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "e1000e 实现与验证计划" msgstr "e1000e 実装・検証計画" @@ -20,20 +23,23 @@ msgid "目标与边界" msgstr "目標と範囲" msgid "" -"为 Intel 82574L/82574IT(8086:10d3)和 82583V(8086:150c)提供独立的 原生 PCIe 以太网驱动。沿用现有单 eth0 网络服务、Linux " -"socket/ioctl ABI 及原生模块 owner 管理,不修改 BusyBox 或公开 ABI。其他 e1000e 家族设备 不在本次设备表中。默认内置,允许配置为 e1000e.ko。" +"为 Intel 82574L/82574IT(8086:10d3)和 82583V(8086:150c)提供独立的 原生 PCIe " +"以太网驱动。沿用现有单 eth0 网络服务、Linux socket/ioctl ABI 及原生模块 owner 管理,沿用公开 Linux 网络" +" ABI。其他 e1000e 家族设备 不在本次设备表中。默认内置,允许配置为 e1000e.ko。" msgstr "" -"Intel 82574L/82574IT(8086:10d3)と 82583V(8086:150c)向けに独立したネイティブ PCIe Ethernet ドライバーを提供します。既存の単一 " -"eth0 ネットワークサービス、Linux socket/ioctl ABI、ネイティブモジュールの owner 管理を使い、BusyBox や公開 ABI は変更しません。他の e1000e " -"系デバイスは今回のデバイス表の対象外です。デフォルトは組み込みで、e1000e.ko として設定することもできます。" +"Intel 82574L/82574IT(8086:10d3)と 82583V(8086:150c)向けのネイティブ PCIe Ethernet " +"ドライバーを提供します。既存の eth0 ネットワークサービス、Linux socket/ioctl " +"ABI、ネイティブモジュールの所有管理を利用します。デバイステーブルはこの機種を対象とします。既定では組み込みで、e1000e.ko " +"にも設定できます。" msgid "" -"实现采用本项目 Apache-2.0 源码,依据 Intel 寄存器手册;不复制 Linux GPL 驱动。保留现有 E1000。芯片识别、复位与链路管理、DMA 收发环和模块注册分别 归属 " -"drivers/net/e1000e/ 中的文件,并由该目录 Kbuild 列出。" +"实现采用本项目 Apache-2.0 源码,依据 Intel 寄存器手册;不复制 Linux GPL 驱动。保留现有 " +"E1000。芯片识别、复位与链路管理、DMA 收发环和模块注册分别 归属 drivers/net/e1000e/ 中的文件,并由该目录 " +"Kbuild 列出。" msgstr "" -"Intel のレジスターマニュアルに基づく本プロジェクトの Apache-2.0 ソースを使い、Linux の GPL ドライバーはコピーしません。既存の E1000 " -"は保持します。チップ識別、リセットとリンク管理、DMA 送受信リング、モジュール登録は drivers/net/e1000e/ 内の各ファイルに分け、同ディレクトリーの Kbuild " -"に列挙します。" +"Intel のレジスターマニュアルに基づく本プロジェクトの Apache-2.0 ソースを使い、Linux の GPL " +"ドライバーはコピーしません。既存の E1000 は保持します。チップ識別、リセットとリンク管理、DMA 送受信リング、モジュール登録は " +"drivers/net/e1000e/ 内の各ファイルに分け、同ディレクトリーの Kbuild に列挙します。" msgid "执行清单" msgstr "実施チェックリスト" @@ -69,17 +75,19 @@ msgid "验证约束" msgstr "検証上の制約" msgid "" -"测试驱动初始化、DMA 地址而非 CPU 地址、描述符回收与环回绕、错误 RX、 无网线启动、分配/映射失败、复位超时和卸载后的资源回收。宿主硬件模型只替代 PCI/MMIO/DMA " +"测试驱动初始化、DMA 地址而非 CPU 地址、描述符回收与环回绕、错误 RX、 " +"无网线启动、分配/映射失败、复位超时和卸载后的资源回收。宿主硬件模型只替代 PCI/MMIO/DMA " "外部设备,执行真实驱动入口与回调;不为生产驱动增加测试接口。" msgstr "" "ドライバー初期化、CPU アドレスではなく DMA アドレスの使用、記述子回収とリング周回、不正 " -"RX、ケーブルなしの起動、割り当て/マッピング失敗、リセットタイムアウト、アンロード後のリソース回収をテストします。ホストのハードウェアモデルは PCI/MMIO/DMA " +"RX、ケーブルなしの起動、割り当て/マッピング失敗、リセットタイムアウト、アンロード後のリソース回収をテストします。ホストのハードウェアモデルは " +"PCI/MMIO/DMA " "の外部デバイスだけを代替し、実際のドライバー入口とコールバックを実行します。製品用ドライバーにテスト用インターフェースは追加しません。" msgid "" -"内核行为探针和宿主测试放在 ReliefNT;完整镜像与 QEMU 编排放在 ReliefOS。 仅修改新建的 out/e1000e/ 留证与镜像副本,保留原镜像。TMPDIR 使用父仓 " -"out/tmp。实体硬件与 VMware 未运行时必须明确标记未验证。" +"内核行为探针和宿主测试放在 ReliefNT;完整镜像与 QEMU 编排放在 ReliefOS。 仅修改新建的 out/e1000e/ " +"留证与镜像副本,保留原镜像。TMPDIR 使用父仓 out/tmp。实体硬件与 VMware 未运行时必须明确标记未验证。" msgstr "" -"カーネル動作プローブとホストテストは ReliefNT に、完全なイメージと QEMU 実行管理は ReliefOS に置きます。新規の out/e1000e/ " -"配下の証跡とイメージコピーだけを変更し、元イメージは保持します。TMPDIR は親リポジトリーの out/tmp を使います。物理ハードウェアと VMware " -"を実行していない場合は、未検証と明記する必要があります。" +"カーネル動作プローブとホストテストは ReliefNT に、完全なイメージと QEMU 実行管理は ReliefOS に置きます。新規の " +"out/e1000e/ 配下の証跡とイメージコピーだけを変更し、元イメージは保持します。TMPDIR は親リポジトリーの out/tmp " +"を使います。物理ハードウェアと VMware を実行していない場合は、未検証と明記する必要があります。" diff --git a/Documentation/locale/ja/LC_MESSAGES/process/testing.po b/Documentation/locale/ja/LC_MESSAGES/process/testing.po index a5f7c6fb..5daf05a1 100644 --- a/Documentation/locale/ja/LC_MESSAGES/process/testing.po +++ b/Documentation/locale/ja/LC_MESSAGES/process/testing.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "内核验证" msgstr "カーネルの検証" @@ -20,15 +23,17 @@ msgid "定向检查" msgstr "対象別の検査" msgid "从本仓运行受影响目标;作为父仓子模块时 TMPDIR 使用父仓 out/tmp::" -msgstr "本リポジトリーから影響するターゲットを実行します。親リポジトリーのサブモジュールとして使う場合、TMPDIR は親の out/tmp に設定します::" +msgstr "" +"本リポジトリーから影響するターゲットを実行します。親リポジトリーのサブモジュールとして使う場合、TMPDIR は親の out/tmp " +"に設定します::" msgid "" -"module-layout 检查本地 Kbuild、重复/遗漏对象、生产实现包含和上游引擎摘要。 宿主工具/ASan/UBSan、头导出、自包含 C/C++、ELF 和真实运行是不同层次。 ABI" -" 变化必须明确审查,不通过重生成历史 golden 消除差异。" +"module-layout 检查本地 Kbuild、重复/遗漏对象、生产实现包含和上游引擎摘要。 宿主工具/ASan/UBSan、头导出、自包含 " +"C/C++、ELF 和真实运行是不同层次。 ABI 变化必须明确审查,不通过重生成历史 golden 消除差异。" msgstr "" "module-layout はローカル Kbuild、オブジェクトの重複/欠落、製品用実装の " -"include、上流エンジンのダイジェストを検査します。ホストツール/ASan/UBSan、ヘッダー公開、自己完結した C/C++、ELF、実際の実行は異なる層です。ABI " -"変更は明示的に審査し、差異を消すために過去の golden データを再生成してはなりません。" +"include、上流エンジンのダイジェストを検査します。ホストツール/ASan/UBSan、ヘッダー公開、自己完結した " +"C/C++、ELF、実際の実行は異なる層です。ABI 変更は明示的に審査し、差異を消すために過去の golden データを再生成してはなりません。" msgid "" "``tools/tests/pidfd_probe.c`` 是原生 Linux ABI 对照探针。可用宿主 C 编译器 以 " @@ -44,135 +49,176 @@ msgid "测试归属" msgstr "テストの所属" msgid "" -"``tools/test_*.py``、``tools/tests/`` 与 ``tests/host/`` 保存内核实现、 驱动、文件系统、调度、内存管理和 Linux UAPI " -"的宿主测试、原生系统调用探针、 夹具及参考头。它们使用本仓源码与头文件,不依赖 ReliefOS 父仓的用户态或 构建目录。固定 syscall 表及其维护生成器也由本仓持有。" +"``tools/test_*.py``、``tools/tests/`` 与 ``tests/host/`` 保存内核实现、 " +"驱动、文件系统、调度、内存管理和 Linux UAPI 的宿主测试、原生系统调用探针、 夹具及参考头。它们使用本仓源码与头文件,不依赖 " +"ReliefOS 父仓的用户态或 构建目录。固定 syscall 表及其维护生成器也由本仓持有。" msgstr "" -"``tools/test_*.py``、``tools/tests/``、``tests/host/`` はカーネル実装、ドライバー、ファイルシステム、スケジューリング、メモリー管理、Linux " -"UAPI のホストテスト、ネイティブ syscall プローブ、フィクスチャ、参照ヘッダーを保持します。本リポジトリーのソースとヘッダーを使い、ReliefOS " -"親リポジトリーのユーザー空間やビルドディレクトリーには依存しません。固定 syscall 表とその保守用ジェネレーターも本リポジトリーが管理します。" +"``tools/test_*.py``、``tools/tests/``、``tests/host/`` " +"はカーネル実装、ドライバー、ファイルシステム、スケジューリング、メモリー管理、Linux UAPI のホストテスト、ネイティブ syscall " +"プローブ、フィクスチャ、参照ヘッダーを保持します。本リポジトリーのソースとヘッダーを使い、ReliefOS " +"親リポジトリーのユーザー空間やビルドディレクトリーには依存しません。固定 syscall " +"表とその保守用ジェネレーターも本リポジトリーが管理します。" msgid "独立 checkout 或源码归档中可运行::" msgstr "独立した checkout またはソースアーカイブで実行できます::" msgid "" "``tools/tests/host-suites.list`` 显式登记宿主套件和必要参数;runner 保留各套件 日志及 " -"``results.json``,任何失败均返回非零,后续套件仍会执行以形成完整报告。 ``test-host-smoke`` 是 CI 中的定向门禁;完整 ``test`` 还包括所有宿主套件、" -" ABI golden、导出头、启动、vDSO、徽标、panic、Kconfig 和模块布局检查。 仅有 Linux 参考探针通过,不表示相同接口已在 ReliefNT 来宾运行通过。" -msgstr "" -"``tools/tests/host-suites.list`` はホストスイートと必要な引数を明示的に登録します。runner は各スイートのログと ``results.json`` " -"を保持し、失敗があれば非ゼロを返しますが、完全な報告のため後続スイートも実行します。``test-host-smoke`` は CI の対象別ゲートです。完全な ``test`` " -"には全ホストスイート、ABI golden、公開ヘッダー、起動、vDSO、ロゴ、panic、Kconfig、モジュール配置の検査も含みます。Linux " +"``results.json``,任何失败均返回非零,后续套件仍会执行以形成完整报告。 ``test-host-smoke`` 是 CI " +"中的定向门禁;完整 ``test`` 还包括所有宿主套件、 ABI golden、导出头、启动、vDSO、徽标、panic、Kconfig " +"和模块布局检查。 仅有 Linux 参考探针通过,不表示相同接口已在 ReliefNT 来宾运行通过。" +msgstr "" +"``tools/tests/host-suites.list`` はホストスイートと必要な引数を明示的に登録します。runner " +"は各スイートのログと ``results.json`` を保持し、失敗があれば非ゼロを返しますが、完全な報告のため後続スイートも実行します" +"。``test-host-smoke`` は CI の対象別ゲートです。完全な ``test`` には全ホストスイート、ABI " +"golden、公開ヘッダー、起動、vDSO、ロゴ、panic、Kconfig、モジュール配置の検査も含みます。Linux " "参照プローブの合格だけでは、同じインターフェースが ReliefNT ゲストで合格したことにはなりません。" msgid "" -"``procfs`` 套件执行真实 proc/VFS/fdinfo 的 ASan/UBSan 夹具,并在宿主 Linux 编译运行 ``tools/tests/procfs_probe.c`` " -"作为 ABI 参考。探针检查系统/进程节点、 seek、maps、二进制 auxv、描述符和多线程 thread-self;来宾验证应由操作系统 使用其 SDK " -"编译该探针后实际运行,并与宿主结果分别记录。" +"``procfs`` 套件执行真实 proc/VFS/fdinfo 的 ASan/UBSan 夹具,并在宿主 Linux 编译运行 " +"``tools/tests/procfs_probe.c`` 作为 ABI 参考。探针检查系统/进程节点、 seek、maps、二进制 " +"auxv、描述符和多线程 thread-self;来宾验证应由操作系统 使用其 SDK 编译该探针后实际运行,并与宿主结果分别记录。" msgstr "" "``procfs`` スイートは実際の proc/VFS/fdinfo の ASan/UBSan フィクスチャを実行し、ホスト Linux で " -"``tools/tests/procfs_probe.c`` をコンパイル・実行して ABI 参照とします。プローブはシステム/プロセスノード、seek、maps、バイナリー " -"auxv、記述子、マルチスレッドの thread-self を検査します。ゲスト検証では OS の SDK でコンパイルして実際に実行し、ホスト結果と分けて記録する必要があります。" +"``tools/tests/procfs_probe.c`` をコンパイル・実行して ABI " +"参照とします。プローブはシステム/プロセスノード、seek、maps、バイナリー auxv、記述子、マルチスレッドの thread-self " +"を検査します。ゲスト検証では OS の SDK でコンパイルして実際に実行し、ホスト結果と分けて記録する必要があります。" msgid "" -"同套件还运行无需 libc 的 ``tools/tests/procfs_raw_probe.c``。该探针可编译为 initramfs 的 ``/init``,通过 " -"``rdinit=/init`` 在真实挂载的 procfs 上验收; PID 1 将结果写入串口并等待。编译示例::" +"同套件还运行无需 libc 的 ``tools/tests/procfs_raw_probe.c``。该探针可编译为 initramfs 的 " +"``/init``,通过 ``rdinit=/init`` 在真实挂载的 procfs 上验收; PID 1 将结果写入串口并等待。编译示例::" msgstr "" -"同スイートは libc 不要の ``tools/tests/procfs_raw_probe.c`` も実行します。initramfs の ``/init`` " -"としてコンパイルし、``rdinit=/init`` で実際にマウントした procfs を検証できます。PID 1 は結果をシリアルに出力して待機します。コンパイル例::" +"同スイートは libc 不要の ``tools/tests/procfs_raw_probe.c`` も実行します。initramfs の " +"``/init`` としてコンパイルし、``rdinit=/init`` で実際にマウントした procfs を検証できます。PID 1 " +"は結果をシリアルに出力して待機します。コンパイル例::" -msgid "来宾验收分别记录单核和多核启动的完整串口日志、内核与探针摘要; 出现 PASS 后仍需检查没有 FAIL 或 panic,不能只以启动完成代替 syscall 验证。" +msgid "" +"来宾验收分别记录单核和多核启动的完整串口日志、内核与探针摘要; 出现 PASS 后仍需检查没有 FAIL 或 panic,不能只以启动完成代替 " +"syscall 验证。" msgstr "" -"ゲストの受け入れ検証では、単一コアと複数コアの起動それぞれについて、完全なシリアルログとカーネル/プローブのダイジェストを記録します。PASS が出ても FAIL や panic " -"がないか確認し、起動完了だけを syscall 検証の代わりにしてはなりません。" +"ゲストの受け入れ検証では、単一コアと複数コアの起動それぞれについて、完全なシリアルログとカーネル/プローブのダイジェストを記録します。PASS " +"が出ても FAIL や panic がないか確認し、起動完了だけを syscall 検証の代わりにしてはなりません。" -msgid "``service_roles`` 套件检查旧内核桌面实现未恢复、旧窗口服务权限标志未恢复, 以及 exec 只保留允许的任务标志;这些内核源码检查由本仓持有,父仓不再重复。" +msgid "" +"``seccomp_bpf`` 套件以 ASan/UBSan 直接运行生产用经典 BPF 验证器和解释器。 " +"``tools/tests/seccomp_probe.c`` 可用静态 x86-64 glibc 工具链编译,在测试系统 " +"中以普通进程运行(不可直接作为 PID 1),退出成功时打印 ``SECCOMP_ABI_PASS``。 在 Linux 上不带参数运行,在 " +"ReliefNT 上添加 ``--reliefnt`` 测试原生旧入口和 未支持扩展。来宾串口证据应包含实际在线 CPU 数、探针结果及 " +"guest 退出状态。" msgstr "" -"``service_roles`` スイートは旧カーネル内デスクトップ実装と旧ウィンドウサービス権限フラグが復活していないこと、exec " -"が許可されたタスクフラグだけを保持することを検査します。これらのカーネルソース検査は本リポジトリーが管理し、親では重複実行しません。" +"``seccomp_bpf`` は本番の classic BPF 検証器とインタープリターを ASan/UBSan " +"で実行します。``tools/tests/seccomp_probe.c`` は静的リンク用 x86-64 glibc " +"ツールチェーンでビルドし、一般プロセスとして実行します。成功時に ``SECCOMP_ABI_PASS`` を表示します。Linux " +"では引数なし、ReliefNT では ``--reliefnt`` を使ってネイティブの入口と未対応拡張を検査します。オンライン CPU " +"数、プローブ結果、ゲストの終了状態を保存します。" msgid "" -"``syscall_io`` 套件覆盖真实设备节点标志组合下的 ``/dev/null`` 写入、访问模式、 ``O_PATH`` 和 Linux ``MAX_RW_COUNT`` " -"上限,避免通用设备分片截短空设备写入。 其原生探针 ``tools/tests/syscall_io_runtime_probe.c`` 编译后可用 ``--null`` 单独检查大块写入、原始 " -"write syscall、dup 和 writev;默认模式继续运行综合 POSIX I/O 检查。宿主 Linux 参考运行与 ReliefNT 来宾执行分别记录。" +"``service_roles`` 套件检查旧内核桌面实现未恢复、旧窗口服务权限标志未恢复, 以及 exec " +"只保留允许的任务标志;这些内核源码检查由本仓持有,父仓不再重复。" msgstr "" -"``syscall_io`` スイートは実際のデバイスノードのフラグ組み合わせでの ``/dev/null`` 書き込み、アクセスモード、``O_PATH``、Linux の " -"``MAX_RW_COUNT`` 上限を対象にし、汎用デバイス分割による null デバイス書き込みの切り詰めを防ぎます。ネイティブプローブ " -"``tools/tests/syscall_io_runtime_probe.c`` はコンパイル後に ``--null`` を指定し、大きな書き込み、生の write " -"syscall、dup、writev だけを検査できます。デフォルトでは総合 POSIX I/O 検査を続けます。ホスト Linux 参照実行と ReliefNT ゲスト実行は別々に記録します。" +"``service_roles`` スイートは旧カーネル内デスクトップ実装と旧ウィンドウサービス権限フラグが復活していないこと、exec " +"が許可されたタスクフラグだけを保持することを検査します。これらのカーネルソース検査は本リポジトリーが管理し、親では重複実行しません。" msgid "" -"``test-smp-time``、``test-page-cache-growth``、``test-user-return``、 ``test-syscall-io" -"``、``test-vdso-host`` 和 ``test-version`` 提供定向入口。 ``make test-ext4-reference " -"LINUX_REFERENCE=<目录>`` 检查 ext4 schema, 需要已有 Linux 参考树; 它不会下载参考源码。互操作检查需要宿主 ``e2fsprogs``。 " -"``squashfs`` 宿主套件需要 ``squashfs-tools``,用 ``mksquashfs`` 生成真实镜像, 并用 ``unsquashfs`` " -"交叉检查文件内容;``squashfs_boot`` 检查 Multiboot2 载荷 对应的只读 RAM 设备。两项均不替代来宾挂载与安装测试。 音频探针 ``--build-" -"guest`` 需要显式传入由操作系统提供的 ``--sdk``。" -msgstr "" -"``test-smp-time``、``test-page-cache-growth``、``test-user-return``、``test-syscall-io``、``test-" -"vdso-host``、``test-version`` は対象別の入口を提供します。``make test-ext4-reference LINUX_REFERENCE=<目录>`` " -"は ext4 schema を検査し、既存の Linux 参照ツリーが必要です。参照ソースはダウンロードしません。相互運用検査にはホストの ``e2fsprogs`` " -"が必要です。ホストの ``squashfs`` スイートには ``squashfs-tools`` が必要です。``mksquashfs`` " -"で実際のイメージを作成し、``unsquashfs`` でファイルの内容を照合します。``squashfs_boot`` は Multiboot2 ペイロードに対応する読み取り専用 " -"RAM デバイスを検査します。ゲストでのマウントとインストールの検証は別途必要です。音声プローブの ``--build-guest`` には OS が提供する ``--sdk`` " -"を明示的に渡す必要があります。" +"``syscall_io`` 套件覆盖真实设备节点标志组合下的 ``/dev/null`` 写入、访问模式、 ``O_PATH`` 和 Linux" +" ``MAX_RW_COUNT`` 上限,避免通用设备分片截短空设备写入。 其原生探针 " +"``tools/tests/syscall_io_runtime_probe.c`` 编译后可用 ``--null`` 单独检查大块写入、原始 " +"write syscall、dup 和 writev;默认模式继续运行综合 POSIX I/O 检查。宿主 Linux 参考运行与 " +"ReliefNT 来宾执行分别记录。" +msgstr "" +"``syscall_io`` スイートは実際のデバイスノードのフラグ組み合わせでの ``/dev/null`` " +"書き込み、アクセスモード、``O_PATH``、Linux の ``MAX_RW_COUNT`` 上限を対象にし、汎用デバイス分割による null" +" デバイス書き込みの切り詰めを防ぎます。ネイティブプローブ ``tools/tests/syscall_io_runtime_probe.c`` " +"はコンパイル後に ``--null`` を指定し、大きな書き込み、生の write syscall、dup、writev " +"だけを検査できます。デフォルトでは総合 POSIX I/O 検査を続けます。ホスト Linux 参照実行と ReliefNT " +"ゲスト実行は別々に記録します。" + +msgid "" +"``test-smp-time``、``test-page-cache-growth``、``test-user-return``、 " +"``test-syscall-io``、``test-vdso-host`` 和 ``test-version`` 提供定向入口。 ``make " +"test-ext4-reference LINUX_REFERENCE=<目录>`` 检查 ext4 schema, 需要已有 Linux " +"参考树; 它不会下载参考源码。互操作检查需要宿主 ``e2fsprogs``。 ``squashfs`` 宿主套件需要 ``squashfs-" +"tools``,用 ``mksquashfs`` 生成真实镜像, 并用 ``unsquashfs`` " +"交叉检查文件内容;``squashfs_boot`` 检查 Multiboot2 载荷 对应的只读 RAM 设备。两项均不替代来宾挂载与安装测试。" +" 音频探针 ``--build-guest`` 需要显式传入由操作系统提供的 ``--sdk``。" +msgstr "" +"``test-smp-time``、``test-page-cache-growth``、``test-user-return``、``test-" +"syscall-io``、``test-vdso-host``、``test-version`` は対象別の入口を提供します。``make " +"test-ext4-reference LINUX_REFERENCE=<目录>`` は ext4 schema を検査し、既存の Linux " +"参照ツリーが必要です。参照ソースはダウンロードしません。相互運用検査にはホストの ``e2fsprogs`` が必要です。ホストの " +"``squashfs`` スイートには ``squashfs-tools`` が必要です。``mksquashfs`` " +"で実際のイメージを作成し、``unsquashfs`` でファイルの内容を照合します。``squashfs_boot`` は Multiboot2" +" ペイロードに対応する読み取り専用 RAM デバイスを検査します。ゲストでのマウントとインストールの検証は別途必要です。音声プローブの " +"``--build-guest`` には OS が提供する ``--sdk`` を明示的に渡す必要があります。" msgid "兼容性基线" msgstr "互換性基準" msgid "" -"``tools/tests/abi_layout_golden.json`` 保留原始布局基线; ``tools/tests/fixtures/legacy-abi-layout.json`` " -"保存旧导出面的原始布局记录, 迁移时逐字保留,两份均不能通过重生成来掩盖布局变化。 驱动服务表版本 2 的 17 个追加字段在 ``tools/tests/fixtures/driver-" -"api-v2.json`` 单独冻结:168 字节旧前缀的类型与 偏移仍与原始基线比较,当前服务表总长为 304 字节、对齐为 8。 ``make test-abi`` " -"同时检查旧前缀与追加字段,版本、大小、偏移和类型变化 均需显式审查。``abi_layout_checks`` 套件包含对应的失败反例;驱动管理器的 ``driver_modules`` " -"套件验证旧版本、未知版本和错误描述符大小在 init 前被拒绝。 这不表示版本 1 驱动二进制能在版本 2 内核运行。" -msgstr "" -"``tools/tests/abi_layout_golden.json`` は元のレイアウト基準を保持し、``tools/tests/fixtures/legacy-abi-" -"layout.json`` は旧公開面の元のレイアウト記録を保存します。移行時も両方をそのまま保持し、レイアウト変更を隠すために再生成してはなりません。ドライバーサービス表バージョン 2 の追加 " -"17 フィールドは ``tools/tests/fixtures/driver-api-v2.json`` で別途固定します。168 " -"バイトの旧先頭部分の型とオフセットは引き続き元の基準と比較し、現在の表の全長は 304 バイト、アラインメントは 8 です。``make test-abi`` " -"は旧先頭部分と追加フィールドの両方を検査し、バージョン、サイズ、オフセット、型の変更は明示的な審査を必要とします。``abi_layout_checks`` " -"には対応する失敗例があり、ドライバーマネージャーの ``driver_modules`` は旧版、未知の版、不正な記述子サイズを init 前に拒否することを検証します。バージョン 1 " -"ドライバーバイナリーがバージョン 2 カーネルで動くことは意味しません。" - -msgid "" -"音频 ioctl 支持清单为 ``configs/audio-abi-support.json``。 宿主门禁检查标志类型、构建前提、证据路径和验证范围;来宾、上游 ALSA 与 " -"硬件声明必须有对应说明,缺少证据声明的反例应失败。清单保留已有的验证标志 和未解决项;这些静态检查不重新执行历史来宾测试,不构成新的运行验收。 ``linux_audio`` 的 " -"ASan/UBSan 探针遇到未定义行为立即失败,不将带有 sanitizer 错误的零退出状态计为通过;PCM 回归覆盖尚无 DMA 缓冲区时的 DROP。" -msgstr "" -"音声 ioctl 対応一覧は ``configs/audio-abi-support.json`` です。ホストゲートはフラグ型、ビルド前提、証拠パス、検証範囲を確認します。ゲスト、上流 " +"``tools/tests/abi_layout_golden.json`` 保留原始布局基线; ``tools/tests/fixtures" +"/legacy-abi-layout.json`` 保存旧导出面的原始布局记录, 迁移时逐字保留,两份均不能通过重生成来掩盖布局变化。 " +"驱动服务表版本 2 的 17 个追加字段在 ``tools/tests/fixtures/driver-api-v2.json`` " +"单独冻结:168 字节旧前缀的类型与 偏移仍与原始基线比较,当前服务表总长为 304 字节、对齐为 8。 ``make test-abi`` " +"同时检查旧前缀与追加字段,版本、大小、偏移和类型变化 均需显式审查。``abi_layout_checks`` " +"套件包含对应的失败反例;驱动管理器的 ``driver_modules`` 套件验证旧版本、未知版本和错误描述符大小在 init 前被拒绝。 " +"这不表示版本 1 驱动二进制能在版本 2 内核运行。" +msgstr "" +"``tools/tests/abi_layout_golden.json`` " +"は元のレイアウト基準を保持し、``tools/tests/fixtures/legacy-abi-layout.json`` " +"は旧公開面の元のレイアウト記録を保存します。移行時も両方をそのまま保持し、レイアウト変更を隠すために再生成してはなりません。ドライバーサービス表バージョン" +" 2 の追加 17 フィールドは ``tools/tests/fixtures/driver-api-v2.json`` で別途固定します。168" +" バイトの旧先頭部分の型とオフセットは引き続き元の基準と比較し、現在の表の全長は 304 バイト、アラインメントは 8 です。``make " +"test-abi`` " +"は旧先頭部分と追加フィールドの両方を検査し、バージョン、サイズ、オフセット、型の変更は明示的な審査を必要とします。``abi_layout_checks``" +" には対応する失敗例があり、ドライバーマネージャーの ``driver_modules`` は旧版、未知の版、不正な記述子サイズを init " +"前に拒否することを検証します。バージョン 1 ドライバーバイナリーがバージョン 2 カーネルで動くことは意味しません。" + +msgid "" +"音频 ioctl 支持清单为 ``configs/audio-abi-support.json``。 " +"宿主门禁检查标志类型、构建前提、证据路径和验证范围;来宾、上游 ALSA 与 " +"硬件声明必须有对应说明,缺少证据声明的反例应失败。清单保留已有的验证标志 和未解决项;这些静态检查不重新执行历史来宾测试,不构成新的运行验收。 " +"``linux_audio`` 的 ASan/UBSan 探针遇到未定义行为立即失败,不将带有 sanitizer " +"错误的零退出状态计为通过;PCM 回归覆盖尚无 DMA 缓冲区时的 DROP。" +msgstr "" +"音声 ioctl 対応一覧は ``configs/audio-abi-support.json`` " +"です。ホストゲートはフラグ型、ビルド前提、証拠パス、検証範囲を確認します。ゲスト、上流 " "ALSA、ハードウェアに関する主張には対応する説明が必要で、証拠宣言のない反例は失敗する必要があります。一覧は既存の検証フラグと未解決項目を保持します。静的検査は過去のゲストテストを再実行せず、新しい実行時受け入れ検証にもなりません。``linux_audio``" -" の ASan/UBSan プローブは未定義動作で即座に失敗し、sanitizer エラー付きの終了コードゼロを合格に数えません。PCM 回帰は DMA バッファーがまだない時の DROP " -"を対象とします。" +" の ASan/UBSan プローブは未定義動作で即座に失敗し、sanitizer エラー付きの終了コードゼロを合格に数えません。PCM 回帰は " +"DMA バッファーがまだない時の DROP を対象とします。" msgid "" -"``sched_wakeup`` 套件覆盖生产调度唤醒与 SMP IPI 的逻辑 CPU/APIC 映射、启动 交接、合并通知、本地 IRQ 状态、离线/单核及停止/vfork 任务边界。输入 " -"IRQ 夹具另检查重新调度向量不会被当成 timer 或 PIC 中断。I/O 预算测试在旧 uptime 停止增长时检查续传、偏移与完整结果;vDSO/timekeeper 测试区分内部 CPU" -" 本地工作计数与用户可见时钟。framebuffer 的 guard-page 夹具检查精确 像素范围、未对齐来源和行尾边界,既有 FIFO 满时的损伤重试仍须通过。" +"``sched_wakeup`` 套件覆盖生产调度唤醒与 SMP IPI 的逻辑 CPU/APIC 映射、启动 交接、合并通知、本地 IRQ " +"状态、离线/单核及停止/vfork 任务边界。输入 IRQ 夹具另检查重新调度向量不会被当成 timer 或 PIC 中断。I/O 预算测试在旧 " +"uptime 停止增长时检查续传、偏移与完整结果;vDSO/timekeeper 测试区分内部 CPU " +"本地工作计数与用户可见时钟。framebuffer 的 guard-page 夹具检查精确 像素范围、未对齐来源和行尾边界,既有 FIFO " +"满时的损伤重试仍须通过。" msgstr "" -"``sched_wakeup`` スイートは製品用スケジューラー起床と SMP IPI の論理 CPU/APIC 対応、起動引き渡し、通知統合、ローカル IRQ " -"状態、オフライン/単一コア、停止/vfork タスクの境界を対象にします。入力 IRQ フィクスチャは再スケジュールベクトルを timer や PIC " -"割り込みとして扱わないことも検査します。I/O 予算テストは旧 uptime が増えなくなった際の再開、オフセット、完全な結果を確認し、vDSO/timekeeper テストは内部 CPU " -"ローカル作業カウンターとユーザーに見えるクロックを区別します。framebuffer の guard-page フィクスチャは正確なピクセル範囲、非整列の入力元、行末境界を検査し、既存の FIFO" -" 満杯時の損傷更新再試行も合格する必要があります。" +"``sched_wakeup`` スイートは製品用スケジューラー起床と SMP IPI の論理 CPU/APIC " +"対応、起動引き渡し、通知統合、ローカル IRQ 状態、オフライン/単一コア、停止/vfork タスクの境界を対象にします。入力 IRQ " +"フィクスチャは再スケジュールベクトルを timer や PIC 割り込みとして扱わないことも検査します。I/O 予算テストは旧 uptime " +"が増えなくなった際の再開、オフセット、完全な結果を確認し、vDSO/timekeeper テストは内部 CPU " +"ローカル作業カウンターとユーザーに見えるクロックを区別します。framebuffer の guard-page " +"フィクスチャは正確なピクセル範囲、非整列の入力元、行末境界を検査し、既存の FIFO 満杯時の損傷更新再試行も合格する必要があります。" msgid "" "同一调度套件检查 IRQ 延迟时的公平时间计费、ACPI PM 回绕及源切换;APIC 夹具检查 100/250/1000 Hz " -"的计数与失败回退。``private_fault_transactions`` 使用真实缺页分发、页表和返回谓词,检查无抢占请求时的私有页直接恢复, " -"以及远端通知、信号、停止、亲和性和失效帧仍进入调度路径。" +"的计数与失败回退。``private_fault_transactions`` " +"使用真实缺页分发、页表和返回谓词,检查无抢占请求时的私有页直接恢复, 以及远端通知、信号、停止、亲和性和失效帧仍进入调度路径。" msgstr "" -"同じスケジューラースイートは IRQ 遅延時の公平な時間課金、ACPI PM の周回、時刻源切り替えを検査し、APIC フィクスチャは 100/250/1000 Hz " -"の計数と失敗時フォールバックを確認します。``private_fault_transactions`` " +"同じスケジューラースイートは IRQ 遅延時の公平な時間課金、ACPI PM の周回、時刻源切り替えを検査し、APIC フィクスチャは " +"100/250/1000 Hz の計数と失敗時フォールバックを確認します。``private_fault_transactions`` " "は実際のフォールト分配、ページテーブル、復帰述語を使い、プリエンプション要求がない場合のプライベートページ直接復帰と、遠隔通知、シグナル、停止、アフィニティー、無効フレームが引き続きスケジューリング経路に入ることを検査します。" msgid "" "``process_priority`` 使用真实 syscall 分发验证 PRIO_PROCESS 的同属主父进程 " -"降优先级、跨属主拒绝、CAP_SYS_NICE、升优先级拒绝、数值钳制、ESRCH 和 Linux 返回值编码;不修改宿主进程的调度状态。整机还需验证 XDM/IceWM " -"与用户终端分别继承预期优先级,不能以临时 root 提权实验代替启动链检查。" +"降优先级、跨属主拒绝、CAP_SYS_NICE、升优先级拒绝、数值钳制、ESRCH 和 Linux " +"返回值编码;不修改宿主进程的调度状态。整机还需验证 XDM/IceWM 与用户终端分别继承预期优先级,不能以临时 root " +"提权实验代替启动链检查。" msgstr "" "``process_priority`` は実際の syscall 分配を使い、PRIO_PROCESS " "での同一所有者の親による優先度引き下げ、所有者をまたぐ拒否、CAP_SYS_NICE、優先度引き上げ拒否、値の制限、ESRCH、Linux " -"の戻り値符号化を検証し、ホストプロセスのスケジューリング状態は変更しません。システム全体では XDM/IceWM とユーザー端末がそれぞれ期待した優先度を継承することも検証し、一時的な root " -"昇格実験で起動チェーン検査を代替してはなりません。" +"の戻り値符号化を検証し、ホストプロセスのスケジューリング状態は変更しません。システム全体では XDM/IceWM " +"とユーザー端末がそれぞれ期待した優先度を継承することも検証し、一時的な root 昇格実験で起動チェーン検査を代替してはなりません。" msgid "" "``pat`` 套件覆盖生产 PAT 引导/AP 策略及真实页表的 UC 到 WC 转换: " @@ -187,26 +233,22 @@ msgid "目标运行" msgstr "ターゲットでの実行" msgid "" -"启动检查固件与内核完成、PID 1;系统调用探针必须实际进入来宾。 panic 验证还需真实异常与画面,徽标需检查数量、留距和移除。 主仓提供集成 QEMU " -"工具,但它们不是本仓新增产品;每次记录源码与二进制 摘要,保留源镜像。VMware 与物理硬件未验证不能记作通过。" +"``tools/tests/uname_runtime_probe.c`` 使用 libc 与原始 uname 系统调用,检查 原生/Linux " +"系统名、其他字段不变、prctl 参数拒绝、fork/线程/exec/vfork 继承及相互隔离。编译时使用导出的 " +"```` 和 pthread; 来宾原生运行不带参数,Linux 模式运行时传入 " +"``Linux``,可分别编译静态和 动态程序。仅在 ReliefNT 来宾执行,其扩展不要求宿主 Linux 实现。" +msgstr "" +"``tools/tests/uname_runtime_probe.c`` は libc と uname " +"システムコールの直接呼び出しを使い、ネイティブ/Linux のシステム名、他のフィールドの維持、prctl " +"引数の拒否、fork/スレッド/exec/vfork での継承と相互分離を検証します。公開された ```` と" +" pthread を使用してコンパイルします。ゲストのネイティブモードでは引数なし、Linux モードでは ``Linux`` " +"を指定し、静的版と動的版を別々にビルドできます。ReliefNT ゲストだけで実行し、ホスト Linux にこれらの拡張の実装は要求しません。" + +msgid "" +"启动检查固件与内核完成、PID 1;系统调用探针必须实际进入来宾。 panic 验证还需真实异常与画面,徽标需检查数量、留距和移除。 主仓提供集成" +" QEMU 工具,但它们不是本仓新增产品;每次记录源码与二进制 摘要,保留源镜像。VMware 与物理硬件未验证不能记作通过。" msgstr "" "起動検査はファームウェアとカーネルの完了、PID 1 を確認し、syscall プローブは実際にゲストへ入れる必要があります。panic " "検証には実際の例外と画面も必要で、ロゴは個数、間隔、消去を確認します。メインリポジトリーは統合 QEMU " "ツールを提供しますが、本リポジトリーの新規製品ではありません。毎回ソースとバイナリーのダイジェストを記録し、元イメージを保持します。VMware " "と物理ハードウェアは未検証なら合格と記録してはなりません。" - -msgid "``tools/tests/uname_runtime_probe.c`` 使用 libc 与原始 uname 系统调用,检查 原生/Linux 系统名、其他字段不变、prctl 参数拒绝、fork/线程/exec/vfork 继承及相互隔离。编译时使用导出的 ```` 和 pthread; 来宾原生运行不带参数,Linux 模式运行时传入 ``Linux``,可分别编译静态和 动态程序。仅在 ReliefNT 来宾执行,其扩展不要求宿主 Linux 实现。" -msgstr "``tools/tests/uname_runtime_probe.c`` は libc と uname システムコールの直接呼び出しを使い、ネイティブ/Linux のシステム名、他のフィールドの維持、prctl 引数の拒否、fork/スレッド/exec/vfork での継承と相互分離を検証します。公開された ```` と pthread を使用してコンパイルします。ゲストのネイティブモードでは引数なし、Linux モードでは ``Linux`` を指定し、静的版と動的版を別々にビルドできます。ReliefNT ゲストだけで実行し、ホスト Linux にこれらの拡張の実装は要求しません。" - -msgid "" -"``seccomp_bpf`` 套件以 ASan/UBSan 直接运行生产用经典 BPF 验证器和解释器。 " -"``tools/tests/seccomp_probe.c`` 可用静态 x86-64 musl 工具链编译,在测试系统 中以普通进程运行(不可直接作为" -" PID 1),退出成功时打印 ``SECCOMP_ABI_PASS``。 在 Linux 上不带参数运行,在 ReliefNT 上添加 " -"``--reliefnt`` 测试原生旧入口和 未支持扩展。来宾串口证据应包含实际在线 CPU 数、探针结果及 guest 退出状态。" -msgstr "" -"``seccomp_bpf`` スイートは ASan/UBSan を使い、製品用の古典的 BPF " -"検証器とインタープリターを直接実行します。``tools/tests/seccomp_probe.c`` は静的 x86-64 musl " -"ツールチェーンでコンパイルでき、テストシステムで通常のプロセスとして実行します(PID 1 として直接実行してはいけません)。正常終了時には " -"``SECCOMP_ABI_PASS`` を出力します。Linux では引数なしで実行し、ReliefNT では ``--reliefnt`` " -"を付けてネイティブの旧エントリーと未対応の拡張をテストします。ゲストのシリアルログによる証拠には、実際にオンラインの CPU " -"数、プローブの結果、ゲストの終了ステータスを含める必要があります。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 35b8ecd8..10ac9da6 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "系统调用与 UAPI" msgstr "システムコールと UAPI" @@ -20,37 +23,104 @@ msgid "约定" msgstr "規約" msgid "" -"x86_64 使用 Linux syscall 编号与寄存器约定,未知接口返回 ENOSYS。 公开线协议位于 include/uapi,headers_install 由 " -"configs/header-export.list 控制;私有 task、页表和驱动状态不导出为用户 ABI。固定宽度、长度、版本、 边界和负 errno 都是接口契约的一部分。" +"x86_64 使用 Linux syscall 编号与寄存器约定,未知接口返回 ENOSYS。 公开线协议位于 " +"include/uapi,headers_install 由 configs/header-export.list 控制;私有 " +"task、页表和驱动状态不导出为用户 ABI。固定宽度、长度、版本、 边界和负 errno 都是接口契约的一部分。" msgstr "" -"x86_64 は Linux の syscall 番号とレジスター規約を使い、未知のインターフェースは ENOSYS を返します。公開の受け渡し形式は include/uapi " -"にあり、headers_install は configs/header-export.list で制御します。非公開の task、ページテーブル、ドライバー状態はユーザー ABI " +"x86_64 は Linux の syscall 番号とレジスター規約を使い、未知のインターフェースは ENOSYS " +"を返します。公開の受け渡し形式は include/uapi にあり、headers_install は configs/header-" +"export.list で制御します。非公開の task、ページテーブル、ドライバー状態はユーザー ABI " "として公開しません。固定幅、長さ、バージョン、境界、負の errno はすべてインターフェース契約の一部です。" msgid "vDSO 的 ELF 符号版本、辅助向量、vvar 邻接映射及时间读取均有专用测试。 不支持的时钟或条件继续走真实 syscall,不返回猜测值。" msgstr "" -"vDSO の ELF シンボルバージョン、補助ベクトル、vvar の隣接マッピング、時刻読み取りには専用テストがあります。非対応のクロックや条件では実際の syscall " -"に進み、推測値は返しません。" +"vDSO の ELF シンボルバージョン、補助ベクトル、vvar " +"の隣接マッピング、時刻読み取りには専用テストがあります。非対応のクロックや条件では実際の syscall に進み、推測値は返しません。" msgid "兼容" msgstr "互換性" msgid "" -"公开头保留实际支持的兼容名称,旧用户库不能伪装成新 SONAME。 只实现的接口才可视为可用;头文件存在不能代替完整运行认证。 接口修改同步内核、导出头、用户态包装、消费者和必要验证,不以更新 " -"golden 替代布局或语义审查。" +"公开头保留实际支持的兼容名称,旧用户库不能伪装成新 SONAME。 只实现的接口才可视为可用;头文件存在不能代替完整运行认证。 " +"接口修改同步内核、导出头、用户态包装、消费者和必要验证,不以更新 golden 替代布局或语义审查。" msgstr "" "公開ヘッダーは実際に対応する互換名を保持し、古いユーザーライブラリーを新しい SONAME " "に見せかけてはなりません。利用可能とみなせるのは実装済みのインターフェースだけで、ヘッダーの存在は完全な実行時認証の代わりにはなりません。インターフェース変更はカーネル、公開ヘッダー、ユーザー空間ラッパー、利用側、必要な検証に同期して反映し、golden" " データの更新でレイアウトや意味の審査を代替しません。" +msgid "timerfd 时钟" +msgstr "timerfd のクロック" + +msgid "" +"``timerfd_create()`` 支持 ``CLOCK_REALTIME``、``CLOCK_MONOTONIC`` 和 " +"``CLOCK_BOOTTIME``,接受 ``TFD_CLOEXEC`` 与 ``TFD_NONBLOCK``。绝对截止时间 " +"按创建时选定的时钟解释,周期到期累计可读次数。``timerfd_settime()`` 的 ``it_value`` 为零时解除定时器,包括 " +"``TFD_TIMER_ABSTIME`` 模式。" +msgstr "" +"``timerfd_create()`` は " +"``CLOCK_REALTIME``、``CLOCK_MONOTONIC``、``CLOCK_BOOTTIME`` と " +"``TFD_CLOEXEC``、``TFD_NONBLOCK`` " +"をサポートします。絶対期限は作成時に選択したクロックで解釈され、周期的な満了は読み取り可能な回数に累積されます。``timerfd_settime()``" +" の ``it_value`` がゼロの場合、``TFD_TIMER_ABSTIME`` モードでもタイマーを解除します。" + +msgid "" +"``CLOCK_BOOTTIME`` 使用现有启动时间时钟,当前与单调时钟共用计时来源。 官方 systemd 的 DHCP " +"重传定时器通过该接口运行。" +msgstr "" +"``CLOCK_BOOTTIME`` は既存の起動時刻クロックを使用し、現在は単調クロックと時刻源を共有します。公式 systemd の DHCP" +" 再送タイマーはこのインターフェースを使用します。" + +msgid "按任务选择 uname 系统名" +msgstr "タスクごとの uname システム名の選択" + +msgid "```` 提供以下不需要特权的 ``prctl`` 扩展:" +msgstr "```` は、特権不要の次の ``prctl`` 拡張を提供します。" + +msgid "" +"``RELIEFOS_PR_SET_UNAME_LINUX``(``0x52550001``):arg2 为 0 或 1, 关闭或开启当前任务的 " +"Linux 系统名;arg3、arg4、arg5 必须为零。" +msgstr "" +"``RELIEFOS_PR_SET_UNAME_LINUX``(``0x52550001``):arg2 を 0 または 1 " +"として、呼び出しタスクの Linux システム名を無効または有効にします。arg3、arg4、arg5 はゼロにします。" + +msgid "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):所有参数为零, 返回当前选择 0 或 1。" +msgstr "" +"``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):すべての引数をゼロにし、現在の選択 0 または 1" +" を取得します。" + +msgid "" +"非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone " +"复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 " +"``sysname`` 改为 Linux,其余字段、UTS 命名空间状态及 procfs 均不改变。 使用标准 libc prctl " +"包装或原始系统调用均可;不改变 personality 数值语义。" +msgstr "" +"不正な値やゼロ以外の予約引数には、状態を変更せず EINVAL を返します。新しいタスクは既定で ReliefNT " +"を使用します。fork、vfork、clone は呼び出しタスクの選択をコピーし、exec " +"は選択を保持します。既存の別タスクは影響を受けず、スレッドも独立に選択できます。このスイッチは ``uname(2)`` の " +"``sysname`` だけを Linux に変更し、他のフィールド、UTS 名前空間の状態、procfs は変更しません。標準 libc の " +"prctl ラッパーとシステムコールの直接呼び出しに対応し、personality 値の意味は変更しません。" + msgid "孤儿进程接管" msgstr "孤児プロセスの引き取り" -msgid "``PR_SET_CHILD_SUBREAPER`` 的第二个参数为非零时启用,为零时清除。 ``PR_GET_CHILD_SUBREAPER`` 将当前状态(0 或 1)写入第二个参数指向的用户态 ``int``。不需要特权。同一进程内的线程共享该状态;fork 和创建新进程的 clone 不继承该状态,exec 保留。" -msgstr "``PR_SET_CHILD_SUBREAPER`` は第 2 引数が非ゼロなら設定を有効にし、ゼロなら解除します。``PR_GET_CHILD_SUBREAPER`` は現在の状態(0 または 1)を、第 2 引数が指すユーザー空間の ``int`` に書き込みます。特権は不要です。同じプロセス内のスレッドで状態を共有します。fork や新規プロセスを作成する clone では継承されず、exec では保持されます。" +msgid "" +"``PR_SET_CHILD_SUBREAPER`` 的第二个参数为非零时启用,为零时清除。 ``PR_GET_CHILD_SUBREAPER``" +" 将当前状态(0 或 1)写入第二个参数指向的用户态 ``int``。不需要特权。同一进程内的线程共享该状态;fork 和创建新进程的 clone" +" 不继承该状态,exec 保留。" +msgstr "" +"``PR_SET_CHILD_SUBREAPER`` は第 2 " +"引数が非ゼロなら設定を有効にし、ゼロなら解除します。``PR_GET_CHILD_SUBREAPER`` は現在の状態(0 または 1)を、第 2" +" 引数が指すユーザー空間の ``int`` に書き込みます。特権は不要です。同じプロセス内のスレッドで状態を共有します。fork " +"や新規プロセスを作成する clone では継承されず、exec では保持されます。" -msgid "创建子进程的线程退出时,若其进程仍有活动线程,则不改变子进程的可见父进程。 最后一个活动线程退出后,最近的仍存活且已启用接管的祖先进程成为新父进程; 没有这种祖先则回退到 PID 1。新父进程可等待被接管的子进程,并按 SIGCHLD 规则 接收退出通知。当前不提供独立的 PID 命名空间。" -msgstr "子を作成したスレッドが終了しても、そのプロセスに生存しているスレッドがあれば、子から見える親プロセスは変わりません。最後の生存スレッドが終了すると、引き取りを有効にした最も近い生存祖先が新しい親となり、該当する祖先がいなければ PID 1 が引き取ります。新しい親は引き取った子を待機でき、SIGCHLD の規則に従って終了通知を受け取ります。独立した PID 名前空間は未実装です。" +msgid "" +"创建子进程的线程退出时,若其进程仍有活动线程,则不改变子进程的可见父进程。 " +"最后一个活动线程退出后,最近的仍存活且已启用接管的祖先进程成为新父进程; 没有这种祖先则回退到 PID 1。新父进程可等待被接管的子进程,并按 " +"SIGCHLD 规则 接收退出通知。当前不提供独立的 PID 命名空间。" +msgstr "" +"子を作成したスレッドが終了しても、そのプロセスに生存しているスレッドがあれば、子から見える親プロセスは変わりません。最後の生存スレッドが終了すると、引き取りを有効にした最も近い生存祖先が新しい親となり、該当する祖先がいなければ" +" PID 1 が引き取ります。新しい親は引き取った子を待機でき、SIGCHLD の規則に従って終了通知を受け取ります。独立した PID " +"名前空間は未実装です。" msgid "创建挂载命名空间" msgstr "マウント名前空間の作成" @@ -66,243 +136,330 @@ msgstr "" "ビット引数の未知の上位ビットを含む未対応フラグを指定した場合は、要求を部分的に適用することなく ``EINVAL`` を返します。" msgid "" -"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` 同用,否则返回 " -"``EINVAL``。单独创建挂载命名空间要求当前 用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 ``EPERM``。" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNS`` 只为子任务复制挂载树,不能与 ``CLONE_FS`` " +"同用,否则返回 ``EINVAL``。单独创建挂载命名空间要求当前 用户空间中有效的 ``CAP_SYS_ADMIN``,没有该能力时返回 " +"``EPERM``。" msgstr "" -"``clone()`` と ``clone3()`` の ``CLONE_NEWNS`` は子タスクだけにマウントツリーをコピーします。``CLONE_FS`` との併用は " -"``EINVAL`` を返します。マウント名前空間だけの作成には現在のユーザー名前空間における実効 ``CAP_SYS_ADMIN`` が必要で、なければ ``EPERM`` " -"を返します。" +"``clone()`` と ``clone3()`` の ``CLONE_NEWNS`` " +"は子タスクだけにマウントツリーをコピーします。``CLONE_FS`` との併用は ``EINVAL`` " +"を返します。マウント名前空間だけの作成には現在のユーザー名前空間における実効 ``CAP_SYS_ADMIN`` が必要で、なければ " +"``EPERM`` を返します。" msgid "" -"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。新图由创建者的当前用户空间拥有。相同 owner 的快照保留共享传播; 跨 owner 时 " -"shared 转为 slave,只接收原上游事件,并锁定继承的覆盖关系和 只读、nosuid、nodev、noexec、atime 限制。可用 ``MS_REC | " -"MS_PRIVATE`` 使子树停止传播。" +"新旧挂载树共享文件内容。root 和 cwd 保留原目录身份,既有打开文件不会被重新 绑定。新图由创建者的当前用户空间拥有。相同 owner " +"的快照保留共享传播; 跨 owner 时 shared 转为 slave,只接收原上游事件,并锁定继承的覆盖关系和 " +"只读、nosuid、nodev、noexec、atime 限制。可用 ``MS_REC | MS_PRIVATE`` 使子树停止传播。" msgstr "" "新旧のマウントツリーはファイル内容を共有します。root と cwd " -"は元のディレクトリの同一性を保持し、既存のオープンファイルの結び付けも維持されます。作成者の現在のユーザー名前空間が新しいグラフを所有します。同一 owner " -"のスナップショットは共有伝播を保持します。owner をまたぐ場合、shared は元の上流からのみイベントを受ける slave " -"となり、継承した被覆関係と読み取り専用、nosuid、nodev、noexec、atime の制限がロックされます。``MS_REC | MS_PRIVATE`` " -"でサブツリーの伝播を停止できます。" - -msgid "bind mount" -msgstr "bind mount" - -msgid "``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录与文件绑定。 源和目标必须同为目录或同为非目录,不匹配时返回 ``ENOTDIR``。普通文件、 设备和 FIFO 等非目录对象可以相互作为源或目标。新挂载保留源的实际 inode、 父链和文件系统生命周期,继承源挂载的只读、nosuid、nodev 等策略。 ``/proc/self/mountinfo`` 的 root 字段报告源 在文件系统内的路径;命名空间路径、``..`` 和 chroot 边界按新挂载计算。 源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" -msgstr "``mount(source, target, NULL, MS_BIND, NULL)`` はディレクトリーとファイルの非再帰 bind に対応します。ソースとターゲットはともにディレクトリーか、ともに非ディレクトリーである必要があり、不一致の場合は ``ENOTDIR`` を返します。通常ファイル、デバイス、FIFO などの非ディレクトリーは相互に bind できます。新しいマウントはソースの inode、親チェーン、ファイルシステムの寿命を保持し、読み取り専用、nosuid、nodev などのポリシーを継承します。``/proc/self/mountinfo`` の root フィールドはファイルシステム内のソースパスを示します。名前空間パス、``..``、chroot 境界は新しいマウントを基準に計算します。bind が残る間はソースファイルシステムを通常の方法でアンマウントできず、bind の解除ではソースファイルシステムは破棄されません。" - -msgid "``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑,对非目录源则只绑定该对象。 子挂载在目的树中拥有新的 挂载 ID 和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" -msgstr "``MS_BIND | MS_REC`` はソースディレクトリー配下のマウント構造も複製します。ソースが非ディレクトリーの場合はそのオブジェクトだけを bind します。複製先の子マウントは独立したマウント ID とポリシーを持ち、元の inode とファイルシステムを共有します。ソースディレクトリー外のマウントと unbindable サブツリーは複製されません。準備に失敗しても複製先ツリーと既存のマウントは変化しません。" - -msgid "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` 只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime 选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" -msgstr "``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` は対象マウントポイントのポリシーだけを変更します。ソース、タイプ、ファイルシステムのオプションは読み取りません。元のマウント、子マウント、共有ファイルシステムは変化しません。atime オプションを省略すると既存のポリシーが維持されます。共有ファイルシステムが読み取り専用である場合、マウントポイントの読み取り専用フラグを解除しても書き込み可能にはなりません。" - -msgid "只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork 和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。" -msgstr "対象マウント上の通常ファイルが書き込み用に開かれている間、読み取り専用への切り替えはポリシーを変更せず EBUSY を返します。dup、fork、ファイルマッピングが同じオープンファイル記述を保持する間もこの制限は続きます。他のマウントの書き込み元や O_PATH だけのハンドルは切り替えを妨げません。" +"は元のディレクトリの同一性を保持し、既存のオープンファイルの結び付けも維持されます。作成者の現在のユーザー名前空間が新しいグラフを所有します。同一" +" owner のスナップショットは共有伝播を保持します。owner をまたぐ場合、shared は元の上流からのみイベントを受ける slave " +"となり、継承した被覆関係と読み取り専用、nosuid、nodev、noexec、atime の制限がロックされます。``MS_REC | " +"MS_PRIVATE`` でサブツリーの伝播を停止できます。" -msgid "文件挂载的目标本身是挂载根,也可独立重新挂载、移动和卸载。移动时源挂载根 与目标必须同为目录或同为非目录,不匹配返回 ``EINVAL``。卸载后目标重新显示 被覆盖的原对象;原 inode、挂载 ID 和访问策略在移动期间保持不变。" -msgstr "ファイルマウントのターゲット自体がマウントルートであり、個別に再マウント、移動、アンマウントできます。移動する場合、ソースのマウントルートとターゲットはともにディレクトリーか、ともに非ディレクトリーである必要があり、不一致では ``EINVAL`` を返します。アンマウント後は覆われていた元のオブジェクトが再び見えます。移動中も元の inode、マウント ID、アクセスポリシーは維持されます。" - -msgid "按任务选择 uname 系统名" -msgstr "タスクごとの uname システム名の選択" - -msgid "```` 提供以下不需要特权的 ``prctl`` 扩展:" -msgstr "```` は、特権不要の次の ``prctl`` 拡張を提供します。" - -msgid "``RELIEFOS_PR_SET_UNAME_LINUX``(``0x52550001``):arg2 为 0 或 1, 关闭或开启当前任务的 Linux 系统名;arg3、arg4、arg5 必须为零。" -msgstr "``RELIEFOS_PR_SET_UNAME_LINUX``(``0x52550001``):arg2 を 0 または 1 として、呼び出しタスクの Linux システム名を無効または有効にします。arg3、arg4、arg5 はゼロにします。" +msgid "创建用户命名空间" +msgstr "ユーザー名前空間の作成" -msgid "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):所有参数为零, 返回当前选择 0 或 1。" -msgstr "``RELIEFOS_PR_GET_UNAME_LINUX``(``0x52550002``):すべての引数をゼロにし、現在の選択 0 または 1 を取得します。" +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUSER`` 为子任务建立独立用户空间, 不能与 " +"``CLONE_FS`` 或 ``CLONE_THREAD`` 组合。``unshare(CLONE_NEWUSER)`` " +"在当前任务建立用户空间并隐含取消文件系统状态共享;允许同时指定 ``CLONE_FS`` 或 ``CLONE_THREAD``,活动多线程组返回 " +"``EINVAL``。" +msgstr "" +"``clone()`` と ``clone3()`` の ``CLONE_NEWUSER`` " +"は子タスク用に独立したユーザー名前空間を作成します。``CLONE_FS`` または ``CLONE_THREAD`` との組み合わせは " +"``EINVAL`` を返します。``unshare(CLONE_NEWUSER)`` " +"は呼び出し元にユーザー名前空間を作成し、ファイルシステム状態の共有を暗黙に解除します。``CLONE_FS`` または " +"``CLONE_THREAD`` の明示指定も受け付けます。活動中のマルチスレッドグループでは ``EINVAL`` を返します。" -msgid "非法值及非零保留参数返回 EINVAL,状态不变。新任务默认使用 ReliefNT; fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存在的其他任务 不受影响,线程也可独立设置该值。该开关仅将 ``uname(2)`` 返回的 ``sysname`` 改为 Linux,其余字段、UTS 命名空间状态及 procfs 均不改变。 使用标准 libc prctl 包装或原始系统调用均可;不改变 personality 数值语义。" -msgstr "不正な値やゼロ以外の予約引数には、状態を変更せず EINVAL を返します。新しいタスクは既定で ReliefNT を使用します。fork、vfork、clone は呼び出しタスクの選択をコピーし、exec は選択を保持します。既存の別タスクは影響を受けず、スレッドも独立に選択できます。このスイッチは ``uname(2)`` の ``sysname`` だけを Linux に変更し、他のフィールド、UTS 名前空間の状態、procfs は変更しません。標準 libc の prctl ラッパーとシステムコールの直接呼び出しに対応し、personality 値の意味は変更しません。" +msgid "" +"创建者的有效 UID 和 GID 必须在其当前用户空间有映射,真实 root 必须等于当前 挂载树的根,否则返回 ``EPERM``。最多嵌套 " +"32 层,超过时返回 ``ENOSPC``。 新空间初始 UID/GID 映射为空,通过 :doc:`procfs` 的映射文件建立映射。" +msgstr "" +"作成者の実効 UID と GID は現在のユーザー名前空間にマッピングされ、実際の root " +"はマウントツリーのルートと一致する必要があります。条件を満たさない場合は ``EPERM`` を返します。ネストは 32 階層までで、超過すると " +"``ENOSPC`` を返します。新しい UID/GID マップは空で、:doc:`procfs` のマッピングファイルで設定できます。" -msgid "挂载传播" -msgstr "マウントの伝播" +msgid "" +"内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding " +"能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 " +"能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 dumpability " +"与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 组合 ``CLONE_NEWUSER | CLONE_NEWNS`` " +"以新用户空间作为新挂载图 owner, 使用新空间的能力完成挂载图创建;候选空间或快照准备失败均整体回滚。" +msgstr "" +"内部 UID/GID、補助グループ、および no_new_privs は保持されます。新しい名前空間の " +"permitted、effective、bounding capability 集合には対応済みの全 capability " +"が入り、inheritable、ambient、securebits はクリアされます。capability " +"は名前空間のスコープに従って検査し、その名前空間と子孫に適用します。unshare は dumpability " +"と親死亡シグナルを保持します。準備失敗時は元の資格情報、ファイルシステム共有状態、およびプロセス公開状態を維持します。``CLONE_NEWUSER" +" | CLONE_NEWNS`` の組み合わせでは新しいユーザー名前空間を新しいマウントグラフの owner とし、その capability " +"でグラフを作成します。候補名前空間またはスナップショットの準備に失敗すると全体をロールバックします。" -msgid "``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 ``MS_SLAVE`` 使共享挂载离开对等组,并从剩余组成员接收传播;没有剩余成员时 继承原上游组,若无上游则变成 private。对非共享挂载执行 ``MS_SLAVE`` 不改变 其类型。slave 可再设为 shared,保留其上游关系。bind 副本继承源的传播关系。" -msgstr "``mount(NULL, target, NULL, MS_SHARED, NULL)`` は、共有されていない対象にピアグループを作ります。``MS_SLAVE`` は共有マウントをピアグループから外し、残ったピアからイベントを受け取るようにします。ピアが残らなければ以前の上流グループを引き継ぎ、上流がなければプライベートになります。共有されていないマウントに対する ``MS_SLAVE`` は種別を変えません。スレーブは上流との関係を保ったまま共有にできます。バインドのコピーは元の伝播関係を引き継ぎます。" +msgid "UTS 命名空间与主机名" +msgstr "UTS 名前空間とホスト名" -msgid "``MS_PRIVATE`` 清除目标的对等组和上游关系;``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind 跳过该子树。上游组失去最后一个成员时,其下游改接到该组 原来的上游组,若无上游则不再接收传播。" -msgstr "``MS_PRIVATE`` は対象のピアグループと上流グループとの関係を解除します。``MS_UNBINDABLE`` はさらにバインド元としての使用を禁止し、再帰バインドからそのサブツリーを除外します。上流グループの最後のメンバーが離脱すると、その下流は以前の上流グループを引き継ぎ、上流がなければイベントを受け取らなくなります。" +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUTS`` 为子任务复制调用者当前的 hostname 和 NIS" +" domainname,``unshare(CLONE_NEWUTS)`` 为调用任务创建同样的 副本。新空间由调用者当前用户空间拥有,同时指定 " +"``CLONE_NEWUSER`` 时由新建 用户空间拥有。单独创建 UTS 空间要求当前用户空间的 ``CAP_SYS_ADMIN``,缺少 " +"时返回 ``EPERM``。普通 fork 和未指定 ``CLONE_NEWUTS`` 的 clone 共享原 UTS 空间。UTS 创建可与 " +"``CLONE_FS`` 共享并用,单独 unshare UTS 保留文件系统共享。" +msgstr "" +"``clone()`` と ``clone3()`` の ``CLONE_NEWUTS`` は、呼び出し元の現在の hostname と NIS " +"domainname を子タスク用にコピーします。``unshare(CLONE_NEWUTS)`` " +"は呼び出し元用に同じコピーを作成します。新しい名前空間の owner は呼び出し元の現在のユーザー名前空間です。``CLONE_NEWUSER``" +" も指定すると、新しく作成したユーザー名前空間が owner になります。UTS 名前空間だけを作成する場合、現在のユーザー名前空間の " +"``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。通常の fork と ``CLONE_NEWUTS``" +" を指定しない clone は元の UTS 名前空間を共有します。UTS の作成は ``CLONE_FS`` による共有と併用でき、UTS だけの" +" unshare はファイルシステム状態の共有を保持します。" msgid "" -"``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 " -"``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。对等组号在 VFS 中全局分配。挂载信息报告 " -"``shared:``、``master:`` 或 ``unbindable``。对 slave,``master:`` " -"始终指向即时上游组;如果查看根下可见的最近上游组与该组不同,另报告 ``propagate_from:``。如果没有可见上游组,则不报告 " -"``propagate_from``。" +"``uname()`` 的 ``nodename`` 和 ``domainname`` 来自调用任务的 UTS 空间。 " +"``sethostname()`` 和 ``setdomainname()`` 要求该 UTS 空间 owner 用户空间的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。长度为 0 至 64 字节,超出返回 " +"``EINVAL``。名称按长度复制,保留换行及内嵌 NUL,尾部补零。" msgstr "" -"``MS_REC`` は対象と既存の子マウントに指定のタイプを適用します。異なる子マウントを一つのグループにまとめたり、既存の共有グループの ID" -" を変更したりしません。タイプの変更には ``CAP_SYS_ADMIN`` " -"が必要で、対象はマウントルートでなければなりません。アクセスポリシーやファイルシステムの状態は変わりません。ピアグループ ID は VFS " -"全体で一意に割り当てられます。マウント情報には ``shared:``、``master:``、または " -"``unbindable`` が表示されます。slave の ``master:`` " -"は常に直近の上流グループを示します。表示ルートの下で見える最も近い上流グループがそれと異なる場合は、そのグループを " -"``propagate_from:`` で示します。見える上流グループがなければ ``propagate_from`` は表示されません。" +"``uname()`` の ``nodename`` と ``domainname`` は呼び出し元タスクの UTS " +"名前空間から取得します。``sethostname()`` と ``setdomainname()`` には、この UTS 名前空間の owner" +" ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。長さは 0 から 64 " +"バイトで、範囲外は ``EINVAL`` を返します。名前は長さに従ってコピーし、改行と埋め込み NUL を保持して末尾をゼロで埋めます。" msgid "" -"在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 " -"bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 " -"上游副本组。接收方可以位于其他活动挂载命名空间。非共享父挂载下创建的新文件 系统挂载默认是 " -"private。所有副本一起发布;分配失败不留下部分挂载。接收位置 已有挂载时,副本插入已有挂载下方,原可见内容保持不变。" +"``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 的权限为 " +"``0644``,归全局 UID/GID 0 所有。写打开及每次写入要求调用者的全局有效 UID 为 0,缺少时返回 " +"``EACCES``,该判断独立于 fsuid 和 DAC capabilities,执行权限 检查返回 ``EACCES``。写入按当时调用者的" +" UTS 空间立即生效,已经打开 或经 dup、fork 继承的 FD 也使用实际写入者的当前空间。只读 proc 挂载或只读 bind " +"挂载上的写入返回 ``EROFS``。" msgstr "" -"共有の親の下でマウントやバインド(再帰バインドを含む)を作成すると、ピアと下流の slave " -"は同じディレクトリオブジェクトで複製を受け取ります。イベントは上流には伝播しません。対象が受信側のバインドルートの外にある場合は、その受信側のみをスキップし、対象を含む下流の受信側は妨げません。同じ受信ピアグループの複製は同じ" -" ID " -"を持ち、最も近い上流の複製グループに従います。受信側は別の稼働中のマウント名前空間にあっても構いません。非共有の親の下で新しいファイルシステムをマウントすると、既定では" -" private " -"になります。複製は一括して公開され、割り当てに失敗しても一部だけが残ることはありません。受信位置に既存のマウントがある場合、複製はその下に挿入され、見えている内容は変わりません。" +"``/proc/sys/kernel/hostname`` と ``/proc/sys/kernel/domainname`` のモードは " +"``0644`` で、所有者はグローバル UID/GID 0 です。書き込み用のオープンと毎回の書き込みで、呼び出し元のグローバル実効 UID が" +" 0 である必要があり、満たさない場合は ``EACCES`` を返します。この判定は fsuid と DAC capabilities " +"に依存せず、実行権限の検査は ``EACCES`` を返します。書き込みはその時点の呼び出し元の UTS " +"名前空間に直ちに反映されます。オープン済み FD や dup、fork で継承した FD " +"も、実際の書き込み元の現在の名前空間を使用します。読み取り専用の proc マウントまたは bind マウント経由の書き込みは ``EROFS``" +" を返します。" -msgid "``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, 为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable 挂载的子树移入共享父挂载, 返回 EINVAL。" -msgstr "``MS_MOVE`` で共有の親の下へ移動しても、元のサブツリーのマウント ID、既存のピアグループ、上流関係、保持中のパスは変わりません。まだ共有されていない元のマウントごとに別々のピアグループを割り当て、受信側にはサブツリー全体をコピーします。割り当てに失敗しても、位置、グループ、受信側の既存のオーバーマウントは変わりません。共有の親から移動する場合や、バインド不可のマウントを含むサブツリーを共有の親の下へ移動する場合は、EINVAL を返します。" +msgid "" +"这两个 sysctl 读取名称至首个 NUL,并追加换行。写入最多保留 64 字节的名称, 在首个换行或 NUL " +"处停止并补零,成功时报告接受的输入字节数。零长度写入保留 名称。它们与 ``uname()`` 及主机名系统调用访问同一份 UTS 名称。" +msgstr "" +"この 2 つの sysctl の読み取りは、最初の NUL までの名前に改行を追加して返します。書き込みは名前を最大 64 " +"バイト保持し、最初の改行または NUL " +"で停止して末尾をゼロで埋めます。成功時は受け付けた入力バイト数を返します。長さゼロの書き込みは名前を保持します。これらのファイルは " +"``uname()`` およびホスト名システムコールと同じ UTS 名を参照します。" msgid "" -"卸载从目标挂载的父挂载传播到对应位置;普通卸载在任一选中的挂载仍有忙引用, " -"或最终后端拒绝卸载时失败,且不移除任何挂载。与事件无关的子挂载通常使该接收 " -"分支保留;但覆盖副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标 " -"子树中的每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方 保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" -msgstr "アンマウントは対象マウントの親から対応する位置へ伝播します。通常のアンマウントは、対象のいずれかに使用中の参照があるか、最後のバックエンドがアンマウントを拒否すると、何も切り離さずに失敗します。無関係な子マウントがある受信側の枝は通常そのまま残ります。ただし、複製のルートに重なるマウントは複製の切り離しを妨げず、その後も表示されます。遅延アンマウントは対象サブツリー内のマウントごとにイベントを伝播し、開いているパスを待たず、受信側の無関係なマウントを残します。開始側のマウントが切り離された後も、残ったマウントはバックエンドを利用できます。" +"当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 文件 I/O 规则推进。此处尚未实现 Linux strict " +"sysctl 对忽略写入保留偏移的行为。" +msgstr "" +"現在位置が名前の末尾を超える書き込みは名前を保持し、受け付けた入力バイト数を返します。ファイル位置は通常のファイル I/O " +"規則に従って進みます。Linux strict sysctl のように無視した書き込みの位置を保持する動作は未実装です。" -msgid "延迟卸载" -msgstr "遅延アンマウント" +msgid "创建网络命名空间" +msgstr "ネットワーク名前空間の作成" -msgid "``umount2(target, MNT_DETACH)`` 立即移除目标挂载及其子挂载的命名空间连接, 不等待持有者或同步刷盘。新的路径查找会看到原挂载点下的内容,挂载表不再列出 已摘除的挂载。永久的命名空间基准根不可摘除。" -msgstr "``umount2(target, MNT_DETACH)`` は、参照の解放や同期フラッシュを待たずに、対象とその子マウントを名前空間から直ちに切り離します。新しいパス検索ではマウントポイントの元の内容が見え、切り離されたマウントはマウントテーブルに表示されません。名前空間の恒久的な基準ルートは切り離せません。" +msgid "" +"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNET`` 为子任务建立独立网络空间, " +"``unshare(CLONE_NEWNET)`` 为调用任务建立独立网络空间。单独创建要求当前用户 空间的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。同时指定 ``CLONE_NEWUSER`` " +"时,新网络由候选用户空间拥有。普通 fork 及未指定该标志的 clone 共享原网络。" +msgstr "" +"``clone()`` と ``clone3()`` の ``CLONE_NEWNET`` " +"は、子タスク用の独立したネットワークを作成します。``unshare(CLONE_NEWNET)`` " +"は呼び出し元用に作成します。単独での作成には現在のユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、不足時は ``EPERM`` " +"を返します。``CLONE_NEWUSER`` と組み合わせると、候補ユーザー名前空間が新しいネットワークを所有します。通常の fork " +"と、このフラグを指定しない clone は元のネットワークを共有します。" -msgid "已打开的文件及持有的目录仍可使用,子挂载的独立引用亦有效。从保留的目录开始 查找时不再跨越被摘除的挂载边,``..`` 不越过已摘除的挂载根。当工作目录不再 连接到任务根时,原始 ``getcwd`` 返回以 ``(unreachable)`` 开头的路径。 最后的引用释放后由 VFS 工作队列完成文件系统清理。" -msgstr "開いたファイルと保持中のディレクトリは、子マウントへの独立した参照も含めて引き続き使用できます。保持したディレクトリからの検索は切り離されたマウント境界を通過せず、``..`` は切り離されたマウントのルートで止まります。作業ディレクトリがタスクのルートにつながっていない場合、生の ``getcwd`` は ``(unreachable)`` で始まるパスを返します。最後の参照が解放された後、VFS のワークキューがファイルシステムの後処理を行います。" +msgid "" +"新网络仅包含默认 down 的 ``lo``,置为 up 时配置回环地址。接口、路由、IPv6 " +"协议状态和套接字匹配按网络隔离。已有套接字保留创建时的网络,任务切换后也 " +"继续使用该网络。单独创建或切换网络保留文件系统共享状态。组合创建先准备全部 " +"候选状态,准备失败保留原空间、凭据、路径和进程发布状态。内部生命周期和已 实现网络范围见 :doc:`../core-api/mount-" +"namespaces`。" +msgstr "" +"新しいネットワークには、初期状態が down の ``lo`` だけが存在します。up " +"にするとループバックアドレスを設定します。インターフェース、経路、IPv6 " +"プロトコル状態、ソケットの照合はネットワークごとに分離されます。既存ソケットはタスクの移動後も作成時のネットワークを保持します。ネットワークだけの作成や切り替えは、ファイルシステム状態の共有を維持します。組み合わせた作成では、すべての候補を先に準備します。準備に失敗すると、元の名前空間、資格情報、パス、プロセスの公開状態を保持します。ライフタイムと実装済みのネットワーク範囲は" +" :doc:`../core-api/mount-namespaces` を参照してください。" -msgid "glibc 线程与 CPU 状态兼容" -msgstr "glibc のスレッドと CPU 状態の互換性" +msgid "加入命名空间" +msgstr "名前空間への参加" msgid "" -"以下行为按 x86_64 Linux ABI 实现。``rseq``、futex PI 操作和扩展信号帧使用 Linux 的接口及布局。POSIX 线程、互斥锁和 CPU " -"时间接口由用户态 libc 提供。" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 " +"``/proc//ns/mnt`` 句柄。调用者需要当前用户空间中有效的 ``CAP_SYS_ADMIN`` 和 " +"``CAP_SYS_CHROOT``,以及目标挂载图 owner 的 ``CAP_SYS_ADMIN``,否则 返回 " +"``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" msgstr "" -"以下の動作は x86_64 Linux ABI に従って実装されています。``rseq``、futex PI 操作、拡張シグナルフレームは Linux " -"のインターフェースとレイアウトを使用します。POSIX のスレッド、ミューテックス、CPU 時間のインターフェースはユーザー空間の libc が提供します。" +"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNS)`` は、通常の読み取り専用で開いた " +"``/proc//ns/mnt`` ハンドルを受け付けます。呼び出し元には現在のユーザー名前空間の実効 " +"``CAP_SYS_ADMIN`` と ``CAP_SYS_CHROOT``、および対象マウントグラフの owner における " +"``CAP_SYS_ADMIN`` が必要で、満たさなければ ``EPERM`` を返します。他タスクと ``CLONE_FS`` " +"状態を共有している場合は ``EINVAL`` を返します。" -msgid "rseq" -msgstr "rseq" +msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" +msgstr "" +"切り替え後の root と cwd は対象マウントグラフの可視ルートを指します。既存の FD と umask " +"は保持されます。元のプロセスが終了した後や名前空間を切り替えた後もハンドルを使用できます。" msgid "" -"注册后向用户区域发布实际运行 CPU,线程迁移后在返回用户态前更新 ``cpu_id_start``、``cpu_id``、``node_id`` 和 ``mm_cid``。当前 " -"NUMA 节点为 0, ``mm_cid`` 使用执行 CPU 的逻辑索引。抢占或信号中断活动临界区时,内核验证 描述符、地址范围及 abort 签名,清除 " -"``rseq_cs``,并跳转至 abort 地址。 无效描述符或不可访问的注册区域触发同步 SIGSEGV。" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 " +"``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 " +"``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 " +"``EPERM``。所属空间的祖先无法通过这项权限检查。" msgstr "" -"登録後、実際に実行している CPU をユーザー領域へ通知します。スレッドの移動後は、ユーザー空間に戻る前に " -"``cpu_id_start``、``cpu_id``、``node_id``、``mm_cid`` を更新します。現在の NUMA ノードは 0 で、``mm_cid`` は実行 " -"CPU の論理インデックスを使用します。プリエンプションやシグナルが実行中のクリティカルセクションを中断すると、カーネルは記述子、アドレス範囲、abort " -"シグネチャを検証し、``rseq_cs`` をクリアして abort アドレスへジャンプします。不正な記述子やアクセス不能な登録領域は同期 SIGSEGV を発生させます。" +"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUSER)`` は通常の読み取り専用 " +"``/proc//ns/user`` " +"ハンドルを受け付けます。現在のユーザー名前空間への再参加、同じグループの別の活動中スレッド、他のタスクとのファイルシステム状態の共有は " +"``EINVAL`` になります。対象ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` " +"を返します。現在の名前空間の祖先はこの権限検査を通過できません。" msgid "" -"``fork`` 复制注册信息,共享地址空间的新线程独立注册,``exec`` 清除注册。 注册保留用户提供的临界区指针及 flags。glibc 可直接读取其 TLS rseq 区域以" -" 实现 ``sched_getcpu``,并可按其自身配置关闭 rseq 使用。" +"成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask " +"保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 " +"securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" msgstr "" -"``fork`` は登録情報をコピーします。アドレス空間を共有する新しいスレッドは独立して登録し、``exec`` " -"は登録をクリアします。登録時にはユーザーが指定したクリティカルセクションのポインターと flags を保持します。glibc は自身の TLS rseq 領域を直接読み取って " -"``sched_getcpu`` を実装でき、自身の設定で rseq の使用を無効にすることもできます。" +"ユーザー名前空間への参加が成功すると、グローバル UID/GID、補助グループ、no_new_privs、root、cwd、umask " +"を保持します。permitted、effective、bounding " +"にはサポートする全能力を設定し、inheritable、ambient、securebits " +"をクリアします。作用域内の権限が増加すると親死亡シグナルを解除してダンプ可能性を制限します。検査失敗時は元の資格情報とファイルシステム状態を保持します。" -msgid "PI futex" -msgstr "PI futex" +msgid "" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUTS)`` 接受普通只读的 " +"``/proc//ns/uts`` 句柄。调用者需要当前用户空间和目标 UTS owner 用户 空间两侧的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。切换允许共享 ``CLONE_FS`` 状态,root、cwd 和 umask" +" 保留。句柄持有目标 UTS 空间的引用, 目标进程退出或切换空间后仍可使用。" +msgstr "" +"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUTS)`` は、通常の読み取り専用 " +"``/proc//ns/uts`` ハンドルを受け付けます。現在のユーザー名前空間と、対象 UTS 名前空間の owner " +"ユーザー名前空間の両方で ``CAP_SYS_ADMIN`` が必要です。欠けていれば ``EPERM`` を返します。切り替え時に " +"``CLONE_FS`` 状態を共有でき、root、cwd、umask を保持します。ハンドルは対象 UTS " +"名前空間の参照を保持し、対象プロセスの終了や名前空間の切り替え後も使用できます。" msgid "" -"实现 ``FUTEX_LOCK_PI``、``FUTEX_TRYLOCK_PI``、``FUTEX_UNLOCK_PI`` 和 ``FUTEX_LOCK_PI2``,支持私有及共享 " -"futex、竞争交接、死锁检查、超时和 robust owner death。共享等待队列保留物理页,退出时释放等待关系。 普通 futex 与 PI 等待队列混用返回 EINVAL。" +"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNET)`` 接受普通只读的 " +"``/proc//ns/net`` 句柄。调用者需要当前用户空间和目标网络 owner 用户 空间两侧的 " +"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。成功后替换任务网络 引用,root、cwd、umask " +"和已有套接字的创建网络保留。允许共享 ``CLONE_FS``, 句柄继续保留目标网络,权限或类型检查失败时保留调用者原网络。" msgstr "" -"``FUTEX_LOCK_PI``、``FUTEX_TRYLOCK_PI``、``FUTEX_UNLOCK_PI``、``FUTEX_LOCK_PI2`` " -"を実装し、プライベートおよび共有 futex、競合時の所有権引き継ぎ、デッドロック検査、タイムアウト、robust futex " -"の所有者死亡に対応します。共有待機キューは物理ページを保持し、終了時に待機関係を解放します。通常の futex と PI 待機キューを混用すると EINVAL を返します。" +"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNET)`` は、通常の読み取り専用 " +"``/proc//ns/net`` ハンドルを受け付けます。呼び出し元には、現在のユーザー名前空間と、対象ネットワーク owner " +"のユーザー名前空間の両方で ``CAP_SYS_ADMIN`` が必要です。不足時は ``EPERM`` " +"を返します。成功時はタスクのネットワーク参照を置き換え、root、cwd、umask、既存ソケットの作成時ネットワークを維持します。``CLONE_FS``" +" の共有を許可します。ハンドルは対象ネットワークを保持し、権限や型の検査に失敗すると呼び出し元の元のネットワークを維持します。" msgid "" -"``LOCK_PI`` 使用绝对 CLOCK_REALTIME 超时。``LOCK_PI2`` 默认使用绝对 CLOCK_MONOTONIC,可通过 " -"``FUTEX_CLOCK_REALTIME`` 选择实时钟。 PI 等待被信号打断后按 Linux 规则重启,包括未设置 ``SA_RESTART`` 的处理器。 " -"已完成的锁所有权交接先结束该次等待,再交付待处理信号。" +"无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 " +"``EINVAL``。当前支持 mount、user、UTS 与 network 句柄,pidfd 和 nsfs 句柄的 bind mount " +"仍未接通。参见 :doc:`../core-api/mount-namespaces`。" msgstr "" -"``LOCK_PI`` は CLOCK_REALTIME の絶対時刻によるタイムアウトを使用します。``LOCK_PI2`` は既定で CLOCK_MONOTONIC " -"の絶対時刻を使用し、``FUTEX_CLOCK_REALTIME`` でリアルタイムクロックを選択できます。シグナルで中断された PI 待機は、``SA_RESTART`` " -"が設定されていないハンドラーも含め、Linux の規則に従って再開します。ロック所有権の引き継ぎが完了した場合は、待機を終了してから保留中のシグナルを配送します。" +"無効な FD と ``O_PATH`` FD は ``EBADF`` を返します。nsfs 以外の FD、型の不一致、未対応の型は " +"``EINVAL`` を返します。mount、user、UTS、network ハンドルに対応します。pidfd と nsfs ハンドルの " +"bind mount は未実装です。:doc:`../core-api/mount-namespaces` を参照してください。" msgid "" -"当前调度器仅接纳 SCHED_OTHER,PI 队列按相同有效优先级的 FIFO 顺序交接。 SCHED_FIFO、SCHED_RR 的实时调度与优先级提升仍需对应调度策略支持。 " -"``FUTEX_WAIT_REQUEUE_PI`` 和 ``FUTEX_CMP_REQUEUE_PI`` 尚未实现,返回 ENOSYS。" +"nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` " +"忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 " +"``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 " +"``CLONE_NEWNS``、``CLONE_NEWUSER``、 ``CLONE_NEWUTS`` 或 ``CLONE_NEWNET``。 " +"``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD " +"可用于元数据查询,但不能 读写、定位或执行 ioctl。" msgstr "" -"現在のスケジューラーは SCHED_OTHER のみを受け付けます。PI キューは実効優先度が等しいタスク間で FIFO 順に所有権を引き継ぎます。SCHED_FIFO と " -"SCHED_RR のリアルタイムスケジューリングおよび優先度の引き上げには、対応するスケジューリング方針のサポートが必要です。``FUTEX_WAIT_REQUEUE_PI`` と " -"``FUTEX_CMP_REQUEUE_PI`` は未実装で、ENOSYS を返します。" +"nsfs ハンドルはメタデータと ioctl を提供します。書き込み用または ``O_TRUNC`` を指定したオープンは ``EPERM`` " +"を返します。``O_PATH`` はこれらのフラグを無視します。通常の FD のスカラー読み取り、位置指定読み取り、ベクトル読み取りは " +"``EINVAL``、書き込みは ``EBADF``、有効な ``whence`` での ``lseek()`` は ``ESPIPE`` " +"を返します。``NS_GET_NSTYPE`` はハンドルに応じて " +"``CLONE_NEWNS``、``CLONE_NEWUSER``、``CLONE_NEWUTS``、``CLONE_NEWNET`` " +"を返します。``FIONREAD`` はゼロを書き戻し、未対応の namespace ioctl は ``ENOTTY`` " +"を返します。``O_PATH`` FD はメタデータ照会に対応し、読み書き、シーク、ioctl は拒否します。" -msgid "CPU 时间时钟" -msgstr "CPU 時間クロック" +msgid "bind mount" +msgstr "bind mount" msgid "" -"除当前进程和线程的固定 clock ID 外,支持 Linux 编码的进程及线程 CPU 时钟, 供 ``clock_getcpuclockid`` 和 " -"``pthread_getcpuclockid`` 使用。PROF 和 SCHED 报告用户态与内核态累计时间,VIRT 报告用户态时间。进程时钟汇总线程组。 线程目标遵守 Linux " -"的线程组限制。``clock_gettime`` 和 ``clock_getres`` 按各自的目标验证规则处理编码 ID,非法 ID 返回 EINVAL。 当前时间统计及报告分辨率为 " -"10 ms。" +"``mount(source, target, NULL, MS_BIND, NULL)`` 支持非递归目录与文件绑定。 " +"源和目标必须同为目录或同为非目录,不匹配时返回 ``ENOTDIR``。普通文件、 设备和 FIFO " +"等非目录对象可以相互作为源或目标。新挂载保留源的实际 inode、 父链和文件系统生命周期,继承源挂载的只读、nosuid、nodev 等策略。 " +"``/proc/self/mountinfo`` 的 root 字段报告源 在文件系统内的路径;命名空间路径、``..`` 和 chroot " +"边界按新挂载计算。 源文件系统在绑定仍存在时不能正常卸载,解绑不销毁源文件系统。" msgstr "" -"現在のプロセスとスレッドに対する固定 clock ID に加え、``clock_getcpuclockid`` と ``pthread_getcpuclockid`` で使用する " -"Linux エンコードのプロセスおよびスレッド CPU クロックに対応します。PROF と SCHED はユーザー空間とカーネルでの累積時間を、VIRT " -"はユーザー空間での時間を報告します。プロセスクロックはスレッドグループを集計します。対象スレッドには Linux のスレッドグループ制限が適用されます。``clock_gettime``" -" と ``clock_getres`` は、それぞれの対象検証規則に従ってエンコードされた ID を処理し、不正な ID には EINVAL を返します。現在の時間計測と報告の分解能は " -"10 ms です。" +"``mount(source, target, NULL, MS_BIND, NULL)`` はディレクトリーとファイルの非再帰 bind " +"に対応します。ソースとターゲットはともにディレクトリーか、ともに非ディレクトリーである必要があり、不一致の場合は ``ENOTDIR`` " +"を返します。通常ファイル、デバイス、FIFO などの非ディレクトリーは相互に bind できます。新しいマウントはソースの " +"inode、親チェーン、ファイルシステムの寿命を保持し、読み取り専用、nosuid、nodev " +"などのポリシーを継承します。``/proc/self/mountinfo`` の root " +"フィールドはファイルシステム内のソースパスを示します。名前空間パス、``..``、chroot 境界は新しいマウントを基準に計算します。bind " +"が残る間はソースファイルシステムを通常の方法でアンマウントできず、bind の解除ではソースファイルシステムは破棄されません。" -msgid "XSAVE 与信号帧" -msgstr "XSAVE とシグナルフレーム" +msgid "" +"``MS_BIND | MS_REC`` 还会复制源目录下的挂载拓扑,对非目录源则只绑定该对象。 子挂载在目的树中拥有新的 挂载 ID " +"和独立策略,但仍共享各自的源 inode 和文件系统。源目录之外的挂载和 unbindable 子树不复制。准备失败时目的树和现有挂载保持原样。" +msgstr "" +"``MS_BIND | MS_REC`` " +"はソースディレクトリー配下のマウント構造も複製します。ソースが非ディレクトリーの場合はそのオブジェクトだけを bind " +"します。複製先の子マウントは独立したマウント ID とポリシーを持ち、元の inode " +"とファイルシステムを共有します。ソースディレクトリー外のマウントと unbindable " +"サブツリーは複製されません。準備に失敗しても複製先ツリーと既存のマウントは変化しません。" msgid "" -"支持 AVX 的 CPU 启用统一的 x87、SSE、AVX XSAVE 状态,任务保存区保持 64 字节对齐,调度切换保留全部启用状态。缺少所需 CPU 能力时使用 512 字节 " -"FXSAVE 状态。当前 XSAVE mask 为 0x7,保存区为 832 字节。" +"bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 " +"owner 的覆盖挂载不能单独移动或卸载,普通与 lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 " +"``EINVAL``, 递归 bind 剪除锁定的 unbindable 子树返回 ``EPERM``。新 bind 根与跨 owner " +"传播的新根允许整树摘除,后代的覆盖锁继续有效。" msgstr "" -"AVX 対応 CPU では x87、SSE、AVX を統合した XSAVE 状態を有効にします。タスクの保存領域は 64 " -"バイト境界に配置し、スケジューリングによる切り替えでは有効な状態をすべて保持します。必要な CPU 機能がない場合は 512 バイトの FXSAVE 状態を使用します。現在の XSAVE" -" マスクは 0x7、保存領域は 832 バイトです。" +"bind、bind-remount、move、伝播タイプ変更、およびアンマウントには、マウントグラフの owner における " +"``CAP_SYS_ADMIN`` が必要です。他の owner " +"から継承した被覆マウントは個別に移動またはアンマウントできず、通常のアンマウントも lazy unmount も ``EINVAL`` " +"を返します。非再帰 bind がロック済み子マウントを省略すると ``EINVAL``、再帰 bind がロック済み unbindable " +"サブツリーを除外すると ``EPERM`` を返します。新しい bind ルートと owner " +"をまたいで伝播した新しいルートはツリー全体として切り離せますが、子孫の被覆ロックは保持されます。" msgid "" -"信号帧包含 Linux 的 ``_fpx_sw_bytes``、XSAVE bitmap 和末尾 magic。 ``rt_sigreturn`` 验证对齐、长度、feature " -"位、保留字段和 MXCSR,并恢复 x87、SSE、YMM 状态。传统 fpstate 及空 fpstate 按其 Linux 语义处理。" +"``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` " +"只更新目标挂载点的策略,不读取源、类型或文件系统选项。源挂载、子挂载和共享 文件系统保持原样。省略 atime " +"选项时保留原策略;共享文件系统只读时,清除 挂载点的只读标志不会使其可写。" msgstr "" -"シグナルフレームには Linux の ``_fpx_sw_bytes``、XSAVE ビットマップ、末尾のマジック値を含みます。``rt_sigreturn`` " -"はアラインメント、長さ、機能ビット、予約フィールド、MXCSR を検証し、x87、SSE、YMM 状態を復元します。従来の fpstate と NULL の fpstate は、それぞれ" -" Linux の意味規則に従って処理します。" +"``mount(NULL, target, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL)`` " +"は対象マウントポイントのポリシーだけを変更します。ソース、タイプ、ファイルシステムのオプションは読み取りません。元のマウント、子マウント、共有ファイルシステムは変化しません。atime" +" " +"オプションを省略すると既存のポリシーが維持されます。共有ファイルシステムが読み取り専用である場合、マウントポイントの読み取り専用フラグを解除しても書き込み可能にはなりません。" -msgid "定向验证" -msgstr "対象を絞った検証" +msgid "" +"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略。新建 " +"tmpfs/devpts 使用调用者用户空间的文件系统 owner,其他后端使用初始用户空间 owner。共享后端 remount 要求文件系统 " +"owner 的 ``CAP_SYS_ADMIN``,bind 别名保留同一 owner。" +msgstr "" +"継承した readonly、nosuid、nodev、noexec の解除や、固定された atime 設定の変更は ``EPERM`` " +"を返し、アタッチメントのポリシーを保持します。新しい tmpfs/devpts は、呼び出し元のユーザー名前空間をファイルシステム owner " +"とします。他のバックエンドは初期ユーザー名前空間を owner とします。共有バックエンドの remount には、ファイルシステム owner " +"における ``CAP_SYS_ADMIN`` が必要です。bind エイリアスも同じ owner を保持します。" msgid "" -"``tools/test_linux_threads.py`` 覆盖 rseq 生命周期、PI 等待队列与信号恢复。 CPU accounting 和用户态返回路径另有宿主回归测试。 " -"``tools/tests/glibc_runtime_probe.c`` 可由原版 glibc 工具链编译,覆盖 编码 CPU 时钟、rseq 迁移与临界区中断、PI mutex " -"竞争、信号、双时钟超时、 robust 恢复、AVX 调度切换和扩展信号帧。" +"只读转换在目标挂载上仍有以写入模式打开的普通文件时返回 EBUSY,且不改变策略。 dup、fork " +"和文件映射持有的同一打开文件描述也会延续这项限制。其他挂载上的写者 或仅持有 O_PATH 不会阻止此转换。" msgstr "" -"``tools/test_linux_threads.py`` は rseq のライフサイクル、PI 待機キュー、シグナルからの復元を検証します。CPU " -"時間計測とユーザー空間への復帰経路には、別途ホスト上の回帰テストがあります。``tools/tests/glibc_runtime_probe.c`` は未変更の glibc " -"ツールチェーンでコンパイルでき、エンコードされた CPU クロック、rseq の移動とクリティカルセクションの中断、PI " -"ミューテックスの競合、シグナル、両クロックでのタイムアウト、robust 回復、AVX 状態のスケジューリング時の切り替え、拡張シグナルフレームを検証します。" +"対象マウント上の通常ファイルが書き込み用に開かれている間、読み取り専用への切り替えはポリシーを変更せず EBUSY " +"を返します。dup、fork、ファイルマッピングが同じオープンファイル記述を保持する間もこの制限は続きます。他のマウントの書き込み元や " +"O_PATH だけのハンドルは切り替えを妨げません。" msgid "" -"此次使用未修改的 Debian glibc 2.41,在双核 QEMU/KVM 中分别验证启用 AVX/XSAVE 和关闭 AVX/XSAVE 的 CPU 配置。动态 " -"ELF、pthread/TLS、 ``posix_spawn``、``dlopen/dlsym``、localhost NSS 和普通 robust mutex 也已运行。关闭 AVX " -"时跳过 AVX 专项。该覆盖范围以外的应用及 glibc 版本 仍需各自验证。VMware 验证未完成,实体硬件未验证。" +"文件挂载的目标本身是挂载根,也可独立重新挂载、移动和卸载。移动时源挂载根 与目标必须同为目录或同为非目录,不匹配返回 " +"``EINVAL``。卸载后目标重新显示 被覆盖的原对象;原 inode、挂载 ID 和访问策略在移动期间保持不变。" msgstr "" -"今回の検証では未変更の Debian glibc 2.41 を使用し、デュアルコアの QEMU/KVM で AVX/XSAVE を有効および無効にした CPU " -"構成をそれぞれ確認しました。動的 ELF、pthread/TLS、``posix_spawn``、``dlopen/dlsym``、localhost NSS、通常の robust " -"ミューテックスも実行しました。AVX が無効な場合は AVX 固有の検査をスキップします。この範囲外のアプリケーションと glibc バージョンは個別の検証が必要です。VMware " -"での検証は未完了で、実機ハードウェアは未検証です。" +"ファイルマウントのターゲット自体がマウントルートであり、個別に再マウント、移動、アンマウントできます。移動する場合、ソースのマウントルートとターゲットはともにディレクトリーか、ともに非ディレクトリーである必要があり、不一致では" +" ``EINVAL`` を返します。アンマウント後は覆われていた元のオブジェクトが再び見えます。移動中も元の inode、マウント " +"ID、アクセスポリシーは維持されます。" msgid "文件系统上下文和游离挂载" msgstr "ファイルシステムコンテキストと未接続マウント" -msgid "由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 ``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 mountinfo 报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 inode 引用释放且相关缓存回收后,设备号才能重用。" -msgstr "``mount(2)`` またはファイルシステムコンテキストで作成した tmpfs インスタンスと、起動時の ``/dev/shm`` は、ディスクのボリュームスロットを消費しません。各インスタンスは個別の匿名デバイス番号を持ち、``stat`` と mountinfo は同じ番号を報告します。バインドマウントは元のインスタンスの番号を共有します。最後のマウント参照と inode 参照が解放され、関連するキャッシュが破棄された後にのみ、番号を再利用できます。" - msgid "" "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` 创建文件系统上下文,捕获打开者的用户 空间作为文件系统 " "owner。``fsopen``、``fsmount`` 和 ``move_mount`` 要求 挂载图 owner 的 " -"``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括 " -"``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 " -"``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE`` " -"要求上下文 owner 的 ``CAP_SYS_ADMIN``,使用已设置 选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup 或 " -"fork 后共享,最后一个引用释放时清理。" +"``CAP_SYS_ADMIN``。``fsconfig`` 的 ``FSCONFIG_SET_STRING`` 接受现有 tmpfs 选项,包括" +" ``size``、``nr_blocks``、``nr_inodes``、``mode``、``uid`` 和 " +"``gid``。``FSCONFIG_SET_FLAG`` 接受 ``ro`` 和 ``rw``。 ``FSCONFIG_CMD_CREATE``" +" 要求上下文 owner 的 ``CAP_SYS_ADMIN``,使用已设置 选项创建文件系统,创建失败可重试。 上下文由打开文件描述持有,dup" +" 或 fork 后共享,最后一个引用释放时清理。" msgstr "" "``fsopen(\"tmpfs\", FSOPEN_CLOEXEC)`` " "はファイルシステムコンテキストを作成し、オープンしたタスクのユーザー名前空間をファイルシステム owner " @@ -314,6 +471,37 @@ msgstr "" "を要求し、設定済みのオプションでファイルシステムを作成します。作成失敗後は再試行できます。コンテキストはオープンファイル記述が所有し、dup や " "fork で共有され、最後の参照の解放時に破棄されます。" +msgid "" +"tmpfs、devtmpfs、devpts 的 ``uid/gid`` 和 proc 的 ``gid`` 在 mount、remount 或 " +"``FSCONFIG_SET_STRING`` 时按实际写入者的用户空间转换为全局 ID。tmpfs 和 devtmpfs 还要求该 ID " +"能在文件系统 owner 空间表示。十进制输入支持前导零, 未映射、溢出或无效 ID 返回 " +"``EINVAL``。上下文保存转换后的值,CREATE 和 RECONFIGURE 使用这些值;参数写入只要求有效上下文描述符,失败保留原配置。" +msgstr "" +"tmpfs、devtmpfs、devpts の ``uid/gid`` と proc の ``gid`` " +"は、mount、remount、``FSCONFIG_SET_STRING`` の実行時に、実際の書き込み元のユーザー名前空間からグローバル ID" +" に変換されます。tmpfs と devtmpfs では、その ID がファイルシステム owner " +"の名前空間でも表現可能である必要があります。10 進入力は先頭のゼロを受け付けます。未マッピング、オーバーフロー、無効な ID は " +"``EINVAL`` を返します。コンテキストは変換後の値を保存し、CREATE と RECONFIGURE " +"が使用します。パラメーターの書き込みには有効なコンテキスト記述子が必要で、失敗時は以前の設定を保持します。" + +msgid "" +"由 ``mount(2)`` 或文件系统上下文创建的 tmpfs 实例,以及启动时的 " +"``/dev/shm``,不占用磁盘卷槽。不同实例使用不同的匿名设备号;``stat`` 和 mountinfo " +"报告同一设备号,绑定挂载则沿用原实例的设备号。最后的挂载和 inode 引用释放且相关缓存回收后,设备号才能重用。" +msgstr "" +"``mount(2)`` またはファイルシステムコンテキストで作成した tmpfs インスタンスと、起動時の ``/dev/shm`` " +"は、ディスクのボリュームスロットを消費しません。各インスタンスは個別の匿名デバイス番号を持ち、``stat`` と mountinfo " +"は同じ番号を報告します。バインドマウントは元のインスタンスの番号を共有します。最後のマウント参照と inode " +"参照が解放され、関連するキャッシュが破棄された後にのみ、番号を再利用できます。" + +msgid "" +"tmpfs 支持最长 255 字节的路径分量。 ``statfs`` 报告该上限, ``getdents`` 和 ``getdents64`` " +"返回完整名称。旧 ReliefOS 目录接口只枚举固定字段 可以容纳的名称。" +msgstr "" +"tmpfs は最大 255 バイトのパス構成要素に対応します。``statfs`` はその上限を返し、``getdents`` と " +"``getdents64`` は名前を完全な形で返します。以前の ReliefOS ディレクトリ API " +"では、固定長フィールドに収まる名前を列挙します。" + msgid "" "``fsopen(\"proc\", FSOPEN_CLOEXEC)`` 也可创建独立 proc 上下文,随后通过 " "``FSCONFIG_CMD_CREATE``、``fsmount`` 和 ``move_mount`` 创建并接入挂载。 " @@ -328,237 +516,390 @@ msgstr "" "として保持し、CREATE にはその owner における ``CAP_SYS_ADMIN`` が必要です。ポリシーと再構成の意味は " ":doc:`procfs` を参照してください。" -msgid "``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 同时保留当前网络空间及其 user owner,并要求该 owner 的 ``CAP_SYS_ADMIN``。CREATE 再次检查捕获的 owner,并使用捕获的网络创建 sysfs 视图。上下文传递或调用者随后切换网络时,这两项捕获继续生效。传统 sysfs mount 同样使用挂载时的网络及其 owner。sysfs 上下文接受通用 ``source``、``ro`` 和 ``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE 的只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` 的独立只读属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" -msgstr "``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` は現在のネットワーク名前空間とその user owner の両方を保持し、その owner の ``CAP_SYS_ADMIN`` を要求します。CREATE は取得済み owner を再検査し、取得済みネットワーク内の sysfs ビューを作成します。コンテキストの受け渡しや呼び出し元のネットワーク切り替え後も、両方の取得内容を維持します。従来の sysfs mount もマウント時のネットワークとその owner を使用します。sysfs コンテキストは共通の ``source``、``ro``、``rw`` パラメーターを受け付けます。未知の固有オプションは ``EINVAL`` を返します。CREATE の読み取り専用設定は共有バックエンドに保持され、RECONFIGURE で更新できます。``fsmount`` による独立した読み取り専用属性は対応するマウントを引き続き制限します。割り当て、記述子の登録、作成に失敗した場合は候補の参照を解放し、再試行できます。" - msgid "" -"tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 255 " -"字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 ``fsmount`` 成功前,设置参数返回 " -"``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 ``source``;重配置不会改变已有挂载在 mountinfo " -"中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" -msgstr "" -"tmpfs、proc、sysfs のコンテキストは ``FSCONFIG_SET_STRING`` の ``source`` パラメーターを受け付けます。値は最大 255 " -"バイトで、空文字列やカンマを含む文字列も使用できます。未設定の場合、ソースは ``none`` と表示されます。同じ設定段階で重複して設定すると ``EINVAL`` " -"を返します。作成が成功した後、``fsmount`` が成功する前にパラメーターを設定すると ``EBUSY`` を返します。``fsmount`` " +"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` 同时保留当前网络空间及其 user owner,并要求该 owner " +"的 ``CAP_SYS_ADMIN``。CREATE 再次检查捕获的 owner,并使用捕获的网络创建 sysfs " +"视图。上下文传递或调用者随后切换网络时,这两项捕获继续生效。传统 sysfs mount 同样使用挂载时的网络及其 owner。sysfs " +"上下文接受通用 ``source``、``ro`` 和 ``rw`` 参数,未知私有选项返回 ``EINVAL``。CREATE " +"的只读设置由共享后端保留,RECONFIGURE 可更新该状态,``fsmount`` " +"的独立只读属性继续约束对应挂载。分配、描述符安装或创建失败时释放候选引用并允许重试。" +msgstr "" +"``fsopen(\"sysfs\", FSOPEN_CLOEXEC)`` は現在のネットワーク名前空間とその user owner " +"の両方を保持し、その owner の ``CAP_SYS_ADMIN`` を要求します。CREATE は取得済み owner " +"を再検査し、取得済みネットワーク内の sysfs " +"ビューを作成します。コンテキストの受け渡しや呼び出し元のネットワーク切り替え後も、両方の取得内容を維持します。従来の sysfs mount " +"もマウント時のネットワークとその owner を使用します。sysfs コンテキストは共通の ``source``、``ro``、``rw`` " +"パラメーターを受け付けます。未知の固有オプションは ``EINVAL`` を返します。CREATE " +"の読み取り専用設定は共有バックエンドに保持され、RECONFIGURE で更新できます。``fsmount`` " +"による独立した読み取り専用属性は対応するマウントを引き続き制限します。割り当て、記述子の登録、作成に失敗した場合は候補の参照を解放し、再試行できます。" + +msgid "" +"sysfs 已公开的 block、PCI 和 DRM 设备 ``uevent`` 控制由 kernel UID 0 所有,模式为 " +"0644,权限检查沿用现有 DAC 与 kernel UID 语义。支持 ``O_TRUNC`` " +"的零长度截断,截断本身不发布事件。写入直接提交事件,action 与可选 UUID 的格式同网络 ``uevent``,见 " +":doc:`ipv6`。非法输入、只读挂载或权限检查失败均不发布事件。" +msgstr "" +"sysfs が公開する block、PCI、DRM デバイスの ``uevent`` 制御は kernel UID 0 が所有し、モードは " +"0644 です。権限検査には既存の DAC と kernel UID の意味論を適用します。``O_TRUNC`` の長さ 0 " +"の切り詰めをサポートし、切り詰め自体はイベントを発行しません。書き込みはイベントを直ちにコミットします。action と任意の UUID " +"の形式はネットワーク ``uevent`` と共通で、:doc:`ipv6` " +"に記載されています。不正な入力、読み取り専用マウント、権限検査の失敗ではイベントを発行しません。" + +msgid "" +"已注册的块文件系统也支持 ``fsopen``、``fsconfig``、``fsmount`` 和 ``move_mount``。 " +"上下文持有文件系统提供者引用,CREATE 要求初始用户空间的 ``CAP_SYS_ADMIN``。 ``source`` 必须为非空设备路径,在" +" CREATE 时按调用者的实际 root、cwd 和目录搜索权限 解析并跟随符号链接;非块设备返回 ``ENOTBLK``。支持 " +"``ro``、``rw``,vfat/exfat 接受既有 ``uid``、``gid``、``umask``、``fmask`` 和 " +"``dmask`` 参数,ext3 接受 ``data=ordered``。只读设备拒绝可写创建,调用者可在同一上下文设置 ``ro`` 后重试。" +" 创建或描述符安装失败保留配置,释放所有候选挂载;``fsmount`` 的独立挂载属性继续 " +"受共享后端只读状态约束。最后一个上下文引用关闭时释放提供者引用。" +msgstr "" +"登録済みのブロックファイルシステムも ``fsopen``、``fsconfig``、``fsmount``、``move_mount`` " +"に対応します。コンテキストはファイルシステム提供者への参照を保持し、CREATE には初期ユーザー名前空間の ``CAP_SYS_ADMIN`` " +"が必要です。``source`` は空でないデバイスパスで、CREATE 時に呼び出し元の実際の " +"root、cwd、ディレクトリ検索権限を使い、シンボリックリンクをたどって解決します。ブロックデバイス以外は ``ENOTBLK`` " +"を返します。``ro`` と ``rw`` に対応し、vfat/exfat は既存の " +"``uid``、``gid``、``umask``、``fmask``、``dmask`` を、ext3 は ``data=ordered`` " +"を受け付けます。読み取り専用デバイスへの書き込み可能な作成は拒否されます。同じコンテキストで ``ro`` " +"を設定して再試行できます。作成や記述子登録に失敗すると設定を保持して候補マウントをすべて解放します。``fsmount`` " +"の独立属性にも共有バックエンドの読み取り専用状態が適用されます。最後のコンテキスト参照を閉じると提供者参照を解放します。" + +msgid "" +"tmpfs、proc 和 sysfs 上下文均接受 ``FSCONFIG_SET_STRING`` 的 ``source`` 参数。其值 最多为 " +"255 字节,可为空并可包含逗号,未设置时来源显示为 ``none``。同一配置 阶段重复设置返回 ``EINVAL``。成功创建后到 " +"``fsmount`` 成功前,设置参数返回 ``EBUSY``。成功 ``fsmount`` 后和每次成功重配置后,均可为下一配置阶段设置新的 " +"``source``;重配置不会改变已有挂载在 mountinfo 中的来源。创建或重配置失败时 待处理的来源保留,调用方可重试。" +msgstr "" +"tmpfs、proc、sysfs のコンテキストは ``FSCONFIG_SET_STRING`` の ``source`` " +"パラメーターを受け付けます。値は最大 255 バイトで、空文字列やカンマを含む文字列も使用できます。未設定の場合、ソースは ``none`` " +"と表示されます。同じ設定段階で重複して設定すると ``EINVAL`` を返します。作成が成功した後、``fsmount`` " +"が成功する前にパラメーターを設定すると ``EBUSY`` を返します。``fsmount`` " "の成功後と各再設定の成功後には、次の設定段階で新しい ``source`` を設定できます。再設定は既存マウントの mountinfo " "に表示されるソースを保持します。作成または再設定に失敗した場合、保留中のソースは保持され、再試行できます。" msgid "" "``fsmount`` 返回指向游离挂载根的 ``O_PATH`` 描述符,支持 ``FSMOUNT_CLOEXEC`` " -"以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd`` " -"重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` " +"以及只读、nosuid、nodev、noexec 和 atime 属性。可通过该描述符相对访问文件, 也可通过 ``/proc/self/fd``" +" 重新打开目录。成功后,上下文可使用 ``fsconfig`` 设置新选项并通过 ``FSCONFIG_CMD_RECONFIGURE`` " "更新共享文件系统。配置失败时 待处理选项保留,关闭阻止只读转换的写入描述符后可重试。RECONFIGURE 要求 实际文件系统 owner 的 " "``CAP_SYS_ADMIN``,上下文传递后也执行此权限检查。" msgstr "" -"``fsmount`` は、切り離されたマウントのルートを指す ``O_PATH`` 記述子を返します。``FSMOUNT_CLOEXEC`` と " -"readonly、nosuid、nodev、noexec、atime " +"``fsmount`` は、切り離されたマウントのルートを指す ``O_PATH`` 記述子を返します。``FSMOUNT_CLOEXEC`` と" +" readonly、nosuid、nodev、noexec、atime " "属性に対応します。この記述子を基準にファイルへアクセスでき、``/proc/self/fd`` からディレクトリを再オープンできます。成功後は " "``fsconfig`` で新しいオプションを設定し、``FSCONFIG_CMD_RECONFIGURE`` " "で共有ファイルシステムを更新できます。設定失敗時は保留中のオプションを保持し、読み取り専用への移行を妨げる書き込み記述子を閉じた後に再試行できます。RECONFIGURE" -" には、実際のファイルシステム owner における ``CAP_SYS_ADMIN`` が必要です。コンテキストの受け渡し後もこの権限を検査します。" - -msgid "``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 ``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" -msgstr "``move_mount`` は保持しているマウントルートを宛先に接続し、接続元と宛先の空パスおよびシンボリックリンクのフラグをサポートします。宛先のマウントが共有されている場合、接続には既存の伝播規則が適用されます。``MOUNT_ATTR_NOSYMFOLLOW`` と ``MOVE_MOUNT_BENEATH`` は ``EINVAL`` を返すため、呼び出し元はそれぞれの互換フォールバックを利用できます。" - -msgid "字节范围文件锁" -msgstr "バイト範囲ファイルロック" - -msgid "``fcntl`` 支持 ``F_GETLK``、``F_SETLK``、``F_SETLKW`` 及 ``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW``。POSIX 锁归描述符表 所有,关闭该表中指向同一 inode 的任意描述符会释放其 POSIX 锁。OFD 锁归打开 文件描述所有,dup 和 fork 共享锁,最后一个引用释放时清锁并唤醒等待者。 在途系统调用和传递中的描述符引用也会延长 OFD 锁的生命周期。" -msgstr "``fcntl`` は ``F_GETLK``、``F_SETLK``、``F_SETLKW``、``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW`` をサポートします。POSIX ロックは記述子テーブルに属し、そのテーブル内で同じ inode を指す記述子を閉じると解放されます。OFD ロックはオープンファイル記述に属し、dup と fork で共有され、最後の参照の解放時に解除されて待機者を起こします。実行中のシステムコールと転送中の記述子の参照も OFD ロックの寿命を延長します。" +" には、実際のファイルシステム owner における ``CAP_SYS_ADMIN`` " +"が必要です。コンテキストの受け渡し後もこの権限を検査します。" -msgid "两类锁使用同一 inode 和范围冲突规则,包括同一进程持有的不同类型锁。相同 OFD 上的锁可转换、拆分和合并。OFD 请求的 ``l_pid`` 必须为零,否则返回 ``EINVAL``。查询到 OFD 冲突时 ``l_pid`` 为 -1,查询到 POSIX 冲突时为持锁 进程的 PID。``F_OFD_SETLK`` 遇到冲突返回 ``EAGAIN``。" -msgstr "両種のロックは同じ inode と範囲の競合規則を使用し、同一プロセスが保持する異種ロックも競合します。同じ OFD 上のロックは変換、分割、結合できます。OFD 要求の ``l_pid`` はゼロである必要があり、それ以外は ``EINVAL`` を返します。競合照会の ``l_pid`` は OFD ロックでは -1、POSIX ロックでは所有プロセスの PID です。``F_OFD_SETLK`` は競合時に ``EAGAIN`` を返します。" - -msgid "``F_OFD_SETLKW`` 等待锁释放,信号处理沿用现有系统调用中断和重启规则。 OFD 等待不参与 POSIX 锁的死锁检测。六种锁命令均保留实际 OFD,阻塞期间其他 线程关闭并复用数字 FD 后,重试仍使用原打开文件描述。任务退出或调用取消会 移除待处理的锁请求,最终 OFD 引用释放后才能回收其锁。" -msgstr "``F_OFD_SETLKW`` はロック解放を待ち、既存のシステムコールのシグナル中断と再開規則に従います。OFD の待機は POSIX ロックのデッドロック検出対象外です。6 種のロック命令は実際の OFD を保持します。待機中に別スレッドが数値 FD を閉じて再利用しても、再試行は元のオープンファイル記述を使用します。タスク終了または呼び出しのキャンセルで保留中の要求を削除し、保持済み OFD ロックは最後の参照の解放まで存続します。" - -msgid "``tools/test_record_locks.py`` 和 ``tools/test_linux_descriptors.py`` 覆盖范围 变更、冲突查询、内存不足回滚、dup/fork、最终引用释放及阻塞期间的 FD 复用。 ``tools/tests/record_locks_runtime_probe.c`` 提供原生用户态运行探针。" -msgstr "``tools/test_record_locks.py`` と ``tools/test_linux_descriptors.py`` は範囲変更、競合照会、メモリ不足時のロールバック、dup/fork、最終参照の解放、待機中の FD 再利用を検証します。``tools/tests/record_locks_runtime_probe.c`` はネイティブユーザー空間の実行プローブです。" +msgid "" +"``move_mount`` 将持有的挂载根接入目标,支持来源和目标的空路径及符号链接标志。 " +"目标所在挂载为共享挂载时,附着遵循既有传播规则。``MOUNT_ATTR_NOSYMFOLLOW`` 和 " +"``MOVE_MOUNT_BENEATH`` 返回 ``EINVAL``,调用方可使用对应的兼容回退。" +msgstr "" +"``move_mount`` " +"は保持しているマウントルートを宛先に接続し、接続元と宛先の空パスおよびシンボリックリンクのフラグをサポートします。宛先のマウントが共有されている場合、接続には既存の伝播規則が適用されます。``MOUNT_ATTR_NOSYMFOLLOW``" +" と ``MOVE_MOUNT_BENEATH`` は ``EINVAL`` を返すため、呼び出し元はそれぞれの互換フォールバックを利用できます。" msgid "statx 挂载标识和根属性" msgstr "statx のマウント ID とルート属性" -msgid "``statx()`` 成功时在 ``stx_attributes_mask`` 中报告支持 ``STATX_ATTR_MOUNT_ROOT``。只有实际查询到的路径是其所在挂载的根时,才在 ``stx_attributes`` 中设置该位。因此,目录绑定的目标是挂载根,同一 inode 经原挂载查询时不一定是。``AT_EMPTY_PATH`` 使用描述符持有的路径,不重新查找 可见名称;没有路径的匿名描述符不设置该属性。" -msgstr "``statx()`` は成功時に ``stx_attributes_mask`` で ``STATX_ATTR_MOUNT_ROOT`` のサポートを報告する。実際に照会したパスが所属するマウントのルートである場合に限り、``stx_attributes`` にそのビットを設定する。したがってディレクトリのバインド先はマウントルートだが、同じ inode を元のマウントから照会してもルートとは限らない。``AT_EMPTY_PATH`` は可視の名前を再検索せず、ディスクリプターが保持するパスを使う。パスのない匿名ディスクリプターではこの属性を設定しない。" - -msgid "实际路径有挂载 ID 时,``statx()`` 在 ``stx_mask`` 中设置 ``STATX_MNT_ID``, 并在 ``stx_mnt_id`` 中返回与 ``/proc/self/mountinfo`` 一致的 ID,即使请求掩码 未指定该位。同一 inode 经不同挂载访问时可得到不同 ID。只有合成元数据、没有 实际挂载路径的对象不报告 ID。不支持 ``STATX_MNT_ID_UNIQUE``,不会将旧式 ID 标记为唯一 ID。输出页争用后重试时沿用同一份已完成的 inode 元数据、ID 和属性。" -msgstr "実際のパスにマウント ID がある場合、``statx()`` は要求マスクに該当ビットがなくても ``stx_mask`` に ``STATX_MNT_ID`` を設定し、``stx_mnt_id`` に ``/proc/self/mountinfo`` と一致する ID を返す。同じ inode でも異なるマウント経由では別の ID が返り得る。合成メタデータしかなく実際のマウントパスを持たないオブジェクトは ID を報告しない。``STATX_MNT_ID_UNIQUE`` は未対応であり、従来の ID を一意とはみなさない。出力ページの競合による再試行では、取得済みの inode メタデータ、ID、属性をそのまま使う。" +msgid "" +"``statx()`` 成功时在 ``stx_attributes_mask`` 中报告支持 " +"``STATX_ATTR_MOUNT_ROOT``。只有实际查询到的路径是其所在挂载的根时,才在 ``stx_attributes`` " +"中设置该位。因此,目录绑定的目标是挂载根,同一 inode 经原挂载查询时不一定是。``AT_EMPTY_PATH`` " +"使用描述符持有的路径,不重新查找 可见名称;没有路径的匿名描述符不设置该属性。" +msgstr "" +"``statx()`` は成功時に ``stx_attributes_mask`` で ``STATX_ATTR_MOUNT_ROOT`` " +"のサポートを報告する。実際に照会したパスが所属するマウントのルートである場合に限り、``stx_attributes`` " +"にそのビットを設定する。したがってディレクトリのバインド先はマウントルートだが、同じ inode " +"を元のマウントから照会してもルートとは限らない。``AT_EMPTY_PATH`` " +"は可視の名前を再検索せず、ディスクリプターが保持するパスを使う。パスのない匿名ディスクリプターではこの属性を設定しない。" -msgid "创建用户命名空间" -msgstr "ユーザー名前空間の作成" +msgid "" +"实际路径有挂载 ID 时,``statx()`` 在 ``stx_mask`` 中设置 ``STATX_MNT_ID``, 并在 " +"``stx_mnt_id`` 中返回与 ``/proc/self/mountinfo`` 一致的 ID,即使请求掩码 未指定该位。同一 inode" +" 经不同挂载访问时可得到不同 ID。只有合成元数据、没有 实际挂载路径的对象不报告 ID。不支持 " +"``STATX_MNT_ID_UNIQUE``,不会将旧式 ID 标记为唯一 ID。输出页争用后重试时沿用同一份已完成的 inode 元数据、ID" +" 和属性。" +msgstr "" +"実際のパスにマウント ID がある場合、``statx()`` は要求マスクに該当ビットがなくても ``stx_mask`` に " +"``STATX_MNT_ID`` を設定し、``stx_mnt_id`` に ``/proc/self/mountinfo`` と一致する ID " +"を返す。同じ inode でも異なるマウント経由では別の ID が返り得る。合成メタデータしかなく実際のマウントパスを持たないオブジェクトは ID" +" を報告しない。``STATX_MNT_ID_UNIQUE`` は未対応であり、従来の ID " +"を一意とはみなさない。出力ページの競合による再試行では、取得済みの inode メタデータ、ID、属性をそのまま使う。" -msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUSER`` 为子任务建立独立用户空间, 不能与 ``CLONE_FS`` 或 ``CLONE_THREAD`` 组合。``unshare(CLONE_NEWUSER)`` 在当前任务建立用户空间并隐含取消文件系统状态共享;允许同时指定 ``CLONE_FS`` 或 ``CLONE_THREAD``,活动多线程组返回 ``EINVAL``。" -msgstr "``clone()`` と ``clone3()`` の ``CLONE_NEWUSER`` は子タスク用に独立したユーザー名前空間を作成します。``CLONE_FS`` または ``CLONE_THREAD`` との組み合わせは ``EINVAL`` を返します。``unshare(CLONE_NEWUSER)`` は呼び出し元にユーザー名前空間を作成し、ファイルシステム状態の共有を暗黙に解除します。``CLONE_FS`` または ``CLONE_THREAD`` の明示指定も受け付けます。活動中のマルチスレッドグループでは ``EINVAL`` を返します。" +msgid "挂载传播" +msgstr "マウントの伝播" -msgid "创建者的有效 UID 和 GID 必须在其当前用户空间有映射,真实 root 必须等于当前 挂载树的根,否则返回 ``EPERM``。最多嵌套 32 层,超过时返回 ``ENOSPC``。 新空间初始 UID/GID 映射为空,通过 :doc:`procfs` 的映射文件建立映射。" -msgstr "作成者の実効 UID と GID は現在のユーザー名前空間にマッピングされ、実際の root はマウントツリーのルートと一致する必要があります。条件を満たさない場合は ``EPERM`` を返します。ネストは 32 階層までで、超過すると ``ENOSPC`` を返します。新しい UID/GID マップは空で、:doc:`procfs` のマッピングファイルで設定できます。" +msgid "" +"``mount(NULL, target, NULL, MS_SHARED, NULL)`` 为尚未共享的目标创建一个对等组。 " +"``MS_SLAVE`` 使共享挂载离开对等组,并从剩余组成员接收传播;没有剩余成员时 继承原上游组,若无上游则变成 " +"private。对非共享挂载执行 ``MS_SLAVE`` 不改变 其类型。slave 可再设为 shared,保留其上游关系。bind " +"副本继承源的传播关系。" +msgstr "" +"``mount(NULL, target, NULL, MS_SHARED, NULL)`` " +"は、共有されていない対象にピアグループを作ります。``MS_SLAVE`` " +"は共有マウントをピアグループから外し、残ったピアからイベントを受け取るようにします。ピアが残らなければ以前の上流グループを引き継ぎ、上流がなければプライベートになります。共有されていないマウントに対する" +" ``MS_SLAVE`` は種別を変えません。スレーブは上流との関係を保ったまま共有にできます。バインドのコピーは元の伝播関係を引き継ぎます。" msgid "" -"内部 UID/GID、补充组和 no_new_privs 保留。新空间内 permitted、effective 和 bounding " -"能力集包含全部已支持能力,inheritable、ambient 和 securebits 清零。 能力按空间作用域检查,新空间内能力作用于本空间及后代。unshare 保留 " -"dumpability 与父死亡信号。准备失败保留原凭据、文件系统共享状态及进程发布状态。 组合 ``CLONE_NEWUSER | CLONE_NEWNS`` 以新用户空间作为新挂载图" -" owner, 使用新空间的能力完成挂载图创建;候选空间或快照准备失败均整体回滚。" +"``MS_PRIVATE`` 清除目标的对等组和上游关系;``MS_UNBINDABLE`` 还禁止把目标作为 bind 源,并使递归 bind " +"跳过该子树。上游组失去最后一个成员时,其下游改接到该组 原来的上游组,若无上游则不再接收传播。" msgstr "" -"内部 UID/GID、補助グループ、および no_new_privs は保持されます。新しい名前空間の permitted、effective、bounding capability " -"集合には対応済みの全 capability が入り、inheritable、ambient、securebits はクリアされます。capability " -"は名前空間のスコープに従って検査し、その名前空間と子孫に適用します。unshare は dumpability " -"と親死亡シグナルを保持します。準備失敗時は元の資格情報、ファイルシステム共有状態、およびプロセス公開状態を維持します。``CLONE_NEWUSER | CLONE_NEWNS`` " -"の組み合わせでは新しいユーザー名前空間を新しいマウントグラフの owner とし、その capability " -"でグラフを作成します。候補名前空間またはスナップショットの準備に失敗すると全体をロールバックします。" +"``MS_PRIVATE`` は対象のピアグループと上流グループとの関係を解除します。``MS_UNBINDABLE`` " +"はさらにバインド元としての使用を禁止し、再帰バインドからそのサブツリーを除外します。上流グループの最後のメンバーが離脱すると、その下流は以前の上流グループを引き継ぎ、上流がなければイベントを受け取らなくなります。" msgid "" -"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNS)`` 接受以普通只读方式打开的 ``/proc//ns/mnt`` " -"句柄。调用者需要当前用户空间中有效的 ``CAP_SYS_ADMIN`` 和 ``CAP_SYS_CHROOT``,以及目标挂载图 owner 的 " -"``CAP_SYS_ADMIN``,否则 返回 ``EPERM``。仍与其他任务共享 ``CLONE_FS`` 状态时返回 ``EINVAL``。" +"``MS_REC`` 对目标及其现有子挂载应用所选类型;不会把不同子挂载合并到同一组, 也不会更改已经共享的组号。类型变更要求 " +"``CAP_SYS_ADMIN`` 且目标为挂载根, 不改变挂载访问策略或文件系统状态。对等组号在 VFS 中全局分配。挂载信息报告 " +"``shared:``、``master:`` 或 ``unbindable``。对 slave,``master:`` " +"始终指向即时上游组;如果查看根下可见的最近上游组与该组不同,另报告 ``propagate_from:``。如果没有可见上游组,则不报告 " +"``propagate_from``。" msgstr "" -"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNS)`` は、通常の読み取り専用で開いた ``/proc//ns/mnt`` " -"ハンドルを受け付けます。呼び出し元には現在のユーザー名前空間の実効 ``CAP_SYS_ADMIN`` と ``CAP_SYS_CHROOT``、および対象マウントグラフの owner " -"における ``CAP_SYS_ADMIN`` が必要で、満たさなければ ``EPERM`` を返します。他タスクと ``CLONE_FS`` 状態を共有している場合は " -"``EINVAL`` を返します。" +"``MS_REC`` は対象と既存の子マウントに指定のタイプを適用します。異なる子マウントを一つのグループにまとめたり、既存の共有グループの ID" +" を変更したりしません。タイプの変更には ``CAP_SYS_ADMIN`` " +"が必要で、対象はマウントルートでなければなりません。アクセスポリシーやファイルシステムの状態は変わりません。ピアグループ ID は VFS " +"全体で一意に割り当てられます。マウント情報には ``shared:``、``master:``、または " +"``unbindable`` が表示されます。slave の ``master:`` " +"は常に直近の上流グループを示します。表示ルートの下で見える最も近い上流グループがそれと異なる場合は、そのグループを " +"``propagate_from:`` で示します。見える上流グループがなければ ``propagate_from`` は表示されません。" -msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUSER)`` 接受普通只读的 ``/proc//ns/user`` 句柄。加入当前用户空间、存在活动的同组线程或与其他 任务共享文件系统状态时返回 ``EINVAL``。调用者需要目标用户空间的 ``CAP_SYS_ADMIN``,否则返回 ``EPERM``。所属空间的祖先无法通过这项权限检查。" -msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUSER)`` は通常の読み取り専用 ``/proc//ns/user`` ハンドルを受け付けます。現在のユーザー名前空間への再参加、同じグループの別の活動中スレッド、他のタスクとのファイルシステム状態の共有は ``EINVAL`` になります。対象ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。現在の名前空間の祖先はこの権限検査を通過できません。" +msgid "" +"在共享父挂载下创建挂载或 bind(包括递归 bind)时,对等挂载和下游 slave 在 相同目录对象处接收副本,不向上游传播。目标在接收方 " +"bind 根之外时跳过该接收方, 但不阻断有相应目录的下游挂载。同一接收对等组内的副本共享组号,并跟随最近的 " +"上游副本组。接收方可以位于其他活动挂载命名空间。非共享父挂载下创建的新文件 系统挂载默认是 " +"private。所有副本一起发布;分配失败不留下部分挂载。接收位置 已有挂载时,副本插入已有挂载下方,原可见内容保持不变。" +msgstr "" +"共有の親の下でマウントやバインド(再帰バインドを含む)を作成すると、ピアと下流の slave " +"は同じディレクトリオブジェクトで複製を受け取ります。イベントは上流には伝播しません。対象が受信側のバインドルートの外にある場合は、その受信側のみをスキップし、対象を含む下流の受信側は妨げません。同じ受信ピアグループの複製は同じ" +" ID " +"を持ち、最も近い上流の複製グループに従います。受信側は別の稼働中のマウント名前空間にあっても構いません。非共有の親の下で新しいファイルシステムをマウントすると、既定では" +" private " +"になります。複製は一括して公開され、割り当てに失敗しても一部だけが残ることはありません。受信位置に既存のマウントがある場合、複製はその下に挿入され、見えている内容は変わりません。" -msgid "切换后 root 和 cwd 均为目标挂载图的可见根,已有 FD 和 umask 保持不变。句柄 仍可在原进程退出或切换命名空间后使用。" -msgstr "切り替え後の root と cwd は対象マウントグラフの可視ルートを指します。既存の FD と umask は保持されます。元のプロセスが終了した後や名前空間を切り替えた後もハンドルを使用できます。" +msgid "" +"``MS_MOVE`` 移入共享父挂载时保留原子树的挂载 ID、已有对等组、上游关系和持有路径, " +"为尚未共享的原挂载分别创建对等组,并向接收方复制整个子树。分配失败时位置、组和 接收方覆盖层都不变。移出共享父挂载,或把含有 unbindable" +" 挂载的子树移入共享父挂载, 返回 EINVAL。" +msgstr "" +"``MS_MOVE`` で共有の親の下へ移動しても、元のサブツリーのマウント " +"ID、既存のピアグループ、上流関係、保持中のパスは変わりません。まだ共有されていない元のマウントごとに別々のピアグループを割り当て、受信側にはサブツリー全体をコピーします。割り当てに失敗しても、位置、グループ、受信側の既存のオーバーマウントは変わりません。共有の親から移動する場合や、バインド不可のマウントを含むサブツリーを共有の親の下へ移動する場合は、EINVAL" +" を返します。" -msgid "加入命名空间" -msgstr "名前空間への参加" +msgid "" +"卸载从目标挂载的父挂载传播到对应位置;普通卸载在任一选中的挂载仍有忙引用, " +"或最终后端拒绝卸载时失败,且不移除任何挂载。与事件无关的子挂载通常使该接收 " +"分支保留;但覆盖副本根的挂载不阻止移除该副本,且仍然可见。延迟卸载为目标 " +"子树中的每个挂载传播事件,不因打开路径阻塞,同样保留接收方的无关挂载。接收方 保留的挂载可以继续使用其后端,即使发起挂载已被摘除。" +msgstr "アンマウントは対象マウントの親から対応する位置へ伝播します。通常のアンマウントは、対象のいずれかに使用中の参照があるか、最後のバックエンドがアンマウントを拒否すると、何も切り離さずに失敗します。無関係な子マウントがある受信側の枝は通常そのまま残ります。ただし、複製のルートに重なるマウントは複製の切り離しを妨げず、その後も表示されます。遅延アンマウントは対象サブツリー内のマウントごとにイベントを伝播し、開いているパスを待たず、受信側の無関係なマウントを残します。開始側のマウントが切り離された後も、残ったマウントはバックエンドを利用できます。" -msgid "成功加入用户空间后,全局 UID/GID、补充组、no_new_privs、root、cwd 和 umask 保留。permitted、effective 和 bounding 包含全部已支持能力,inheritable、 ambient 和 securebits 清零。作用域权限增加时清除父死亡信号并限制可转储状态。 检查失败保留原凭据与文件系统状态。" -msgstr "ユーザー名前空間への参加が成功すると、グローバル UID/GID、補助グループ、no_new_privs、root、cwd、umask を保持します。permitted、effective、bounding にはサポートする全能力を設定し、inheritable、ambient、securebits をクリアします。作用域内の権限が増加すると親死亡シグナルを解除してダンプ可能性を制限します。検査失敗時は元の資格情報とファイルシステム状態を保持します。" +msgid "延迟卸载" +msgstr "遅延アンマウント" msgid "" -"bind、bind-remount、move、传播类型修改及卸载要求挂载图 owner 的 ``CAP_SYS_ADMIN``。继承自其他 owner " -"的覆盖挂载不能单独移动或卸载,普通与 lazy unmount 均返回 ``EINVAL``。非递归 bind 遗漏锁定子挂载返回 ``EINVAL``, 递归 bind 剪除锁定的 " -"unbindable 子树返回 ``EPERM``。新 bind 根与跨 owner 传播的新根允许整树摘除,后代的覆盖锁继续有效。" +"``umount2(target, MNT_DETACH)`` 立即移除目标挂载及其子挂载的命名空间连接, " +"不等待持有者或同步刷盘。新的路径查找会看到原挂载点下的内容,挂载表不再列出 已摘除的挂载。永久的命名空间基准根不可摘除。" msgstr "" -"bind、bind-remount、move、伝播タイプ変更、およびアンマウントには、マウントグラフの owner における ``CAP_SYS_ADMIN`` が必要です。他の " -"owner から継承した被覆マウントは個別に移動またはアンマウントできず、通常のアンマウントも lazy unmount も ``EINVAL`` を返します。非再帰 bind " -"がロック済み子マウントを省略すると ``EINVAL``、再帰 bind がロック済み unbindable サブツリーを除外すると ``EPERM`` を返します。新しい bind " -"ルートと owner をまたいで伝播した新しいルートはツリー全体として切り離せますが、子孫の被覆ロックは保持されます。" +"``umount2(target, MNT_DETACH)`` " +"は、参照の解放や同期フラッシュを待たずに、対象とその子マウントを名前空間から直ちに切り離します。新しいパス検索ではマウントポイントの元の内容が見え、切り離されたマウントはマウントテーブルに表示されません。名前空間の恒久的な基準ルートは切り離せません。" msgid "" -"清除继承的只读、nosuid、nodev、noexec,或改变锁定的 atime 选择时,返回 ``EPERM``,保留附件策略。新建 " -"tmpfs/devpts 使用调用者用户空间的文件系统 owner,其他后端使用初始用户空间 owner。共享后端 remount 要求文件系统 " -"owner 的 ``CAP_SYS_ADMIN``,bind 别名保留同一 owner。" +"已打开的文件及持有的目录仍可使用,子挂载的独立引用亦有效。从保留的目录开始 查找时不再跨越被摘除的挂载边,``..`` " +"不越过已摘除的挂载根。当工作目录不再 连接到任务根时,原始 ``getcwd`` 返回以 ``(unreachable)`` 开头的路径。 " +"最后的引用释放后由 VFS 工作队列完成文件系统清理。" msgstr "" -"継承した readonly、nosuid、nodev、noexec の解除や、固定された atime 設定の変更は ``EPERM`` " -"を返し、アタッチメントのポリシーを保持します。新しい tmpfs/devpts は、呼び出し元のユーザー名前空間をファイルシステム owner " -"とします。他のバックエンドは初期ユーザー名前空間を owner とします。共有バックエンドの remount には、ファイルシステム owner " -"における ``CAP_SYS_ADMIN`` が必要です。bind エイリアスも同じ owner を保持します。" +"開いたファイルと保持中のディレクトリは、子マウントへの独立した参照も含めて引き続き使用できます。保持したディレクトリからの検索は切り離されたマウント境界を通過せず、``..``" +" は切り離されたマウントのルートで止まります。作業ディレクトリがタスクのルートにつながっていない場合、生の ``getcwd`` は " +"``(unreachable)`` で始まるパスを返します。最後の参照が解放された後、VFS のワークキューがファイルシステムの後処理を行います。" + +msgid "字节范围文件锁" +msgstr "バイト範囲ファイルロック" msgid "" -"tmpfs、devtmpfs、devpts 的 ``uid/gid`` 和 proc 的 ``gid`` 在 mount、remount 或 " -"``FSCONFIG_SET_STRING`` 时按实际写入者的用户空间转换为全局 ID。tmpfs 和 devtmpfs 还要求该 ID " -"能在文件系统 owner 空间表示。十进制输入支持前导零, 未映射、溢出或无效 ID 返回 ``EINVAL``。上下文保存转换后的值,CREATE " -"和 RECONFIGURE 使用这些值;参数写入只要求有效上下文描述符,失败保留原配置。" +"``fcntl`` 支持 ``F_GETLK``、``F_SETLK``、``F_SETLKW`` 及 " +"``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW``。POSIX 锁归描述符表 " +"所有,关闭该表中指向同一 inode 的任意描述符会释放其 POSIX 锁。OFD 锁归打开 文件描述所有,dup 和 fork " +"共享锁,最后一个引用释放时清锁并唤醒等待者。 在途系统调用和传递中的描述符引用也会延长 OFD 锁的生命周期。" msgstr "" -"tmpfs、devtmpfs、devpts の ``uid/gid`` と proc の ``gid`` " -"は、mount、remount、``FSCONFIG_SET_STRING`` の実行時に、実際の書き込み元のユーザー名前空間からグローバル ID " -"に変換されます。tmpfs と devtmpfs では、その ID がファイルシステム owner の名前空間でも表現可能である必要があります。10 " -"進入力は先頭のゼロを受け付けます。未マッピング、オーバーフロー、無効な ID は ``EINVAL`` " -"を返します。コンテキストは変換後の値を保存し、CREATE と RECONFIGURE " -"が使用します。パラメーターの書き込みには有効なコンテキスト記述子が必要で、失敗時は以前の設定を保持します。" +"``fcntl`` は " +"``F_GETLK``、``F_SETLK``、``F_SETLKW``、``F_OFD_GETLK``、``F_OFD_SETLK``、``F_OFD_SETLKW``" +" をサポートします。POSIX ロックは記述子テーブルに属し、そのテーブル内で同じ inode を指す記述子を閉じると解放されます。OFD " +"ロックはオープンファイル記述に属し、dup と fork " +"で共有され、最後の参照の解放時に解除されて待機者を起こします。実行中のシステムコールと転送中の記述子の参照も OFD ロックの寿命を延長します。" -msgid "UTS 命名空间与主机名" -msgstr "UTS 名前空間とホスト名" +msgid "" +"普通文件和 socket 均可使用这些锁命令。socket 按完整的匿名 inode 编号识别, " +"同一端点的别名共享冲突范围,不同端点的锁独立。socket 的 ``SEEK_END`` 基准 为零,``O_PATH`` 描述符返回 " +"``EBADF``。关闭 socket 的 POSIX 锁释放规则与 普通文件相同,OFD 锁持续到最后一个引用释放。" +msgstr "" +"通常ファイルと socket はこれらのロックコマンドを使用できます。socket は匿名 inode " +"番号全体で識別し、同じエンドポイントの別名は競合範囲を共有します。異なるエンドポイントのロックは独立します。socket の " +"``SEEK_END`` 基準はゼロで、``O_PATH`` 記述子は ``EBADF`` を返します。socket を閉じた際の POSIX " +"ロック解放規則は通常ファイルと同じです。OFD ロックは最後の参照が解放されるまで保持されます。" -msgid "``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWUTS`` 为子任务复制调用者当前的 hostname 和 NIS domainname,``unshare(CLONE_NEWUTS)`` 为调用任务创建同样的 副本。新空间由调用者当前用户空间拥有,同时指定 ``CLONE_NEWUSER`` 时由新建 用户空间拥有。单独创建 UTS 空间要求当前用户空间的 ``CAP_SYS_ADMIN``,缺少 时返回 ``EPERM``。普通 fork 和未指定 ``CLONE_NEWUTS`` 的 clone 共享原 UTS 空间。UTS 创建可与 ``CLONE_FS`` 共享并用,单独 unshare UTS 保留文件系统共享。" -msgstr "``clone()`` と ``clone3()`` の ``CLONE_NEWUTS`` は、呼び出し元の現在の hostname と NIS domainname を子タスク用にコピーします。``unshare(CLONE_NEWUTS)`` は呼び出し元用に同じコピーを作成します。新しい名前空間の owner は呼び出し元の現在のユーザー名前空間です。``CLONE_NEWUSER`` も指定すると、新しく作成したユーザー名前空間が owner になります。UTS 名前空間だけを作成する場合、現在のユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。通常の fork と ``CLONE_NEWUTS`` を指定しない clone は元の UTS 名前空間を共有します。UTS の作成は ``CLONE_FS`` による共有と併用でき、UTS だけの unshare はファイルシステム状態の共有を保持します。" +msgid "" +"两类锁使用同一 inode 和范围冲突规则,包括同一进程持有的不同类型锁。相同 OFD 上的锁可转换、拆分和合并。OFD 请求的 " +"``l_pid`` 必须为零,否则返回 ``EINVAL``。查询到 OFD 冲突时 ``l_pid`` 为 -1,查询到 POSIX " +"冲突时为持锁 进程的 PID。``F_OFD_SETLK`` 遇到冲突返回 ``EAGAIN``。" +msgstr "" +"両種のロックは同じ inode と範囲の競合規則を使用し、同一プロセスが保持する異種ロックも競合します。同じ OFD " +"上のロックは変換、分割、結合できます。OFD 要求の ``l_pid`` はゼロである必要があり、それ以外は ``EINVAL`` " +"を返します。競合照会の ``l_pid`` は OFD ロックでは -1、POSIX ロックでは所有プロセスの PID " +"です。``F_OFD_SETLK`` は競合時に ``EAGAIN`` を返します。" -msgid "``uname()`` 的 ``nodename`` 和 ``domainname`` 来自调用任务的 UTS 空间。 ``sethostname()`` 和 ``setdomainname()`` 要求该 UTS 空间 owner 用户空间的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。长度为 0 至 64 字节,超出返回 ``EINVAL``。名称按长度复制,保留换行及内嵌 NUL,尾部补零。" -msgstr "``uname()`` の ``nodename`` と ``domainname`` は呼び出し元タスクの UTS 名前空間から取得します。``sethostname()`` と ``setdomainname()`` には、この UTS 名前空間の owner ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、欠けていれば ``EPERM`` を返します。長さは 0 から 64 バイトで、範囲外は ``EINVAL`` を返します。名前は長さに従ってコピーし、改行と埋め込み NUL を保持して末尾をゼロで埋めます。" +msgid "" +"``F_OFD_SETLKW`` 等待锁释放,信号处理沿用现有系统调用中断和重启规则。 OFD 等待不参与 POSIX " +"锁的死锁检测。六种锁命令均保留实际 OFD,阻塞期间其他 线程关闭并复用数字 FD 后,重试仍使用原打开文件描述。任务退出或调用取消会 " +"移除待处理的锁请求,最终 OFD 引用释放后才能回收其锁。" +msgstr "" +"``F_OFD_SETLKW`` はロック解放を待ち、既存のシステムコールのシグナル中断と再開規則に従います。OFD の待機は POSIX " +"ロックのデッドロック検出対象外です。6 種のロック命令は実際の OFD を保持します。待機中に別スレッドが数値 FD " +"を閉じて再利用しても、再試行は元のオープンファイル記述を使用します。タスク終了または呼び出しのキャンセルで保留中の要求を削除し、保持済み OFD " +"ロックは最後の参照の解放まで存続します。" -msgid "``/proc/sys/kernel/hostname`` 和 ``/proc/sys/kernel/domainname`` 的权限为 ``0644``,归全局 UID/GID 0 所有。写打开及每次写入要求调用者的全局有效 UID 为 0,缺少时返回 ``EACCES``,该判断独立于 fsuid 和 DAC capabilities,执行权限 检查返回 ``EACCES``。写入按当时调用者的 UTS 空间立即生效,已经打开 或经 dup、fork 继承的 FD 也使用实际写入者的当前空间。只读 proc 挂载或只读 bind 挂载上的写入返回 ``EROFS``。" -msgstr "``/proc/sys/kernel/hostname`` と ``/proc/sys/kernel/domainname`` のモードは ``0644`` で、所有者はグローバル UID/GID 0 です。書き込み用のオープンと毎回の書き込みで、呼び出し元のグローバル実効 UID が 0 である必要があり、満たさない場合は ``EACCES`` を返します。この判定は fsuid と DAC capabilities に依存せず、実行権限の検査は ``EACCES`` を返します。書き込みはその時点の呼び出し元の UTS 名前空間に直ちに反映されます。オープン済み FD や dup、fork で継承した FD も、実際の書き込み元の現在の名前空間を使用します。読み取り専用の proc マウントまたは bind マウント経由の書き込みは ``EROFS`` を返します。" +msgid "" +"``tools/test_record_locks.py`` 和 ``tools/test_linux_descriptors.py`` 覆盖范围" +" 变更、冲突查询、内存不足回滚、dup/fork、最终引用释放及阻塞期间的 FD 复用。 " +"``tools/tests/record_locks_runtime_probe.c`` 提供原生用户态运行探针。" +msgstr "" +"``tools/test_record_locks.py`` と ``tools/test_linux_descriptors.py`` " +"は範囲変更、競合照会、メモリ不足時のロールバック、dup/fork、最終参照の解放、待機中の FD " +"再利用を検証します。``tools/tests/record_locks_runtime_probe.c`` " +"はネイティブユーザー空間の実行プローブです。" -msgid "这两个 sysctl 读取名称至首个 NUL,并追加换行。写入最多保留 64 字节的名称, 在首个换行或 NUL 处停止并补零,成功时报告接受的输入字节数。零长度写入保留 名称。它们与 ``uname()`` 及主机名系统调用访问同一份 UTS 名称。" -msgstr "この 2 つの sysctl の読み取りは、最初の NUL までの名前に改行を追加して返します。書き込みは名前を最大 64 バイト保持し、最初の改行または NUL で停止して末尾をゼロで埋めます。成功時は受け付けた入力バイト数を返します。長さゼロの書き込みは名前を保持します。これらのファイルは ``uname()`` およびホスト名システムコールと同じ UTS 名を参照します。" +msgid "glibc 线程与 CPU 状态兼容" +msgstr "glibc のスレッドと CPU 状態の互換性" -msgid "``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWUTS)`` 接受普通只读的 ``/proc//ns/uts`` 句柄。调用者需要当前用户空间和目标 UTS owner 用户 空间两侧的 ``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。切换允许共享 ``CLONE_FS`` 状态,root、cwd 和 umask 保留。句柄持有目标 UTS 空间的引用, 目标进程退出或切换空间后仍可使用。" -msgstr "``setns(fd, 0)`` と ``setns(fd, CLONE_NEWUTS)`` は、通常の読み取り専用 ``/proc//ns/uts`` ハンドルを受け付けます。現在のユーザー名前空間と、対象 UTS 名前空間の owner ユーザー名前空間の両方で ``CAP_SYS_ADMIN`` が必要です。欠けていれば ``EPERM`` を返します。切り替え時に ``CLONE_FS`` 状態を共有でき、root、cwd、umask を保持します。ハンドルは対象 UTS 名前空間の参照を保持し、対象プロセスの終了や名前空間の切り替え後も使用できます。" +msgid "" +"以下行为按 x86_64 Linux ABI 实现。``rseq``、futex PI 操作和扩展信号帧使用 Linux 的接口及布局。POSIX" +" 线程、互斥锁和 CPU 时间接口由用户态 libc 提供。" +msgstr "" +"以下の動作は x86_64 Linux ABI に従って実装されています。``rseq``、futex PI 操作、拡張シグナルフレームは " +"Linux のインターフェースとレイアウトを使用します。POSIX のスレッド、ミューテックス、CPU 時間のインターフェースはユーザー空間の " +"libc が提供します。" -msgid "当前位置超过名称末尾时,写入保留名称并报告接受的输入字节数,文件偏移仍按通用 文件 I/O 规则推进。此处尚未实现 Linux strict sysctl 对忽略写入保留偏移的行为。" -msgstr "現在位置が名前の末尾を超える書き込みは名前を保持し、受け付けた入力バイト数を返します。ファイル位置は通常のファイル I/O 規則に従って進みます。Linux strict sysctl のように無視した書き込みの位置を保持する動作は未実装です。" +msgid "rseq" +msgstr "rseq" -msgid "创建网络命名空间" -msgstr "ネットワーク名前空間の作成" +msgid "" +"注册后向用户区域发布实际运行 CPU,线程迁移后在返回用户态前更新 ``cpu_id_start``、``cpu_id``、``node_id``" +" 和 ``mm_cid``。当前 NUMA 节点为 0, ``mm_cid`` 使用执行 CPU 的逻辑索引。抢占或信号中断活动临界区时,内核验证" +" 描述符、地址范围及 abort 签名,清除 ``rseq_cs``,并跳转至 abort 地址。 无效描述符或不可访问的注册区域触发同步 " +"SIGSEGV。" +msgstr "" +"登録後、実際に実行している CPU をユーザー領域へ通知します。スレッドの移動後は、ユーザー空間に戻る前に " +"``cpu_id_start``、``cpu_id``、``node_id``、``mm_cid`` を更新します。現在の NUMA ノードは 0" +" で、``mm_cid`` は実行 CPU " +"の論理インデックスを使用します。プリエンプションやシグナルが実行中のクリティカルセクションを中断すると、カーネルは記述子、アドレス範囲、abort" +" シグネチャを検証し、``rseq_cs`` をクリアして abort アドレスへジャンプします。不正な記述子やアクセス不能な登録領域は同期 " +"SIGSEGV を発生させます。" msgid "" -"``clone()`` 和 ``clone3()`` 的 ``CLONE_NEWNET`` 为子任务建立独立网络空间, " -"``unshare(CLONE_NEWNET)`` 为调用任务建立独立网络空间。单独创建要求当前用户 空间的 " -"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。同时指定 ``CLONE_NEWUSER`` 时,新网络由候选用户空间拥有。普通 " -"fork 及未指定该标志的 clone 共享原网络。" +"``fork`` 复制注册信息,共享地址空间的新线程独立注册,``exec`` 清除注册。 注册保留用户提供的临界区指针及 flags。glibc" +" 可直接读取其 TLS rseq 区域以 实现 ``sched_getcpu``,并可按其自身配置关闭 rseq 使用。" msgstr "" -"``clone()`` と ``clone3()`` の ``CLONE_NEWNET`` " -"は、子タスク用の独立したネットワークを作成します。``unshare(CLONE_NEWNET)`` " -"は呼び出し元用に作成します。単独での作成には現在のユーザー名前空間の ``CAP_SYS_ADMIN`` が必要で、不足時は ``EPERM`` " -"を返します。``CLONE_NEWUSER`` と組み合わせると、候補ユーザー名前空間が新しいネットワークを所有します。通常の fork " -"と、このフラグを指定しない clone は元のネットワークを共有します。" +"``fork`` は登録情報をコピーします。アドレス空間を共有する新しいスレッドは独立して登録し、``exec`` " +"は登録をクリアします。登録時にはユーザーが指定したクリティカルセクションのポインターと flags を保持します。glibc は自身の TLS " +"rseq 領域を直接読み取って ``sched_getcpu`` を実装でき、自身の設定で rseq の使用を無効にすることもできます。" + +msgid "PI futex" +msgstr "PI futex" msgid "" -"新网络仅包含默认 down 的 ``lo``,置为 up 时配置回环地址。接口、路由、IPv6 " -"协议状态和套接字匹配按网络隔离。已有套接字保留创建时的网络,任务切换后也 继续使用该网络。单独创建或切换网络保留文件系统共享状态。组合创建先准备全部 " -"候选状态,准备失败保留原空间、凭据、路径和进程发布状态。内部生命周期和已 实现网络范围见 " -":doc:`../core-api/mount-namespaces`。" +"实现 ``FUTEX_LOCK_PI``、``FUTEX_TRYLOCK_PI``、``FUTEX_UNLOCK_PI`` 和 " +"``FUTEX_LOCK_PI2``,支持私有及共享 futex、竞争交接、死锁检查、超时和 robust owner " +"death。共享等待队列保留物理页,退出时释放等待关系。 普通 futex 与 PI 等待队列混用返回 EINVAL。" msgstr "" -"新しいネットワークには、初期状態が down の ``lo`` だけが存在します。up " -"にするとループバックアドレスを設定します。インターフェース、経路、IPv6 " -"プロトコル状態、ソケットの照合はネットワークごとに分離されます。既存ソケットはタスクの移動後も作成時のネットワークを保持します。ネットワークだけの作成や切り替えは、ファイルシステム状態の共有を維持します。組み合わせた作成では、すべての候補を先に準備します。準備に失敗すると、元の名前空間、資格情報、パス、プロセスの公開状態を保持します。ライフタイムと実装済みのネットワーク範囲は" -" :doc:`../core-api/mount-namespaces` を参照してください。" +"``FUTEX_LOCK_PI``、``FUTEX_TRYLOCK_PI``、``FUTEX_UNLOCK_PI``、``FUTEX_LOCK_PI2``" +" を実装し、プライベートおよび共有 futex、競合時の所有権引き継ぎ、デッドロック検査、タイムアウト、robust futex " +"の所有者死亡に対応します。共有待機キューは物理ページを保持し、終了時に待機関係を解放します。通常の futex と PI 待機キューを混用すると " +"EINVAL を返します。" msgid "" -"``setns(fd, 0)`` 和 ``setns(fd, CLONE_NEWNET)`` 接受普通只读的 " -"``/proc//ns/net`` 句柄。调用者需要当前用户空间和目标网络 owner 用户 空间两侧的 " -"``CAP_SYS_ADMIN``,缺少时返回 ``EPERM``。成功后替换任务网络 引用,root、cwd、umask " -"和已有套接字的创建网络保留。允许共享 ``CLONE_FS``, 句柄继续保留目标网络,权限或类型检查失败时保留调用者原网络。" +"``LOCK_PI`` 使用绝对 CLOCK_REALTIME 超时。``LOCK_PI2`` 默认使用绝对 " +"CLOCK_MONOTONIC,可通过 ``FUTEX_CLOCK_REALTIME`` 选择实时钟。 PI 等待被信号打断后按 Linux " +"规则重启,包括未设置 ``SA_RESTART`` 的处理器。 已完成的锁所有权交接先结束该次等待,再交付待处理信号。" msgstr "" -"``setns(fd, 0)`` と ``setns(fd, CLONE_NEWNET)`` は、通常の読み取り専用 " -"``/proc//ns/net`` ハンドルを受け付けます。呼び出し元には、現在のユーザー名前空間と、対象ネットワーク owner " -"のユーザー名前空間の両方で ``CAP_SYS_ADMIN`` が必要です。不足時は ``EPERM`` " -"を返します。成功時はタスクのネットワーク参照を置き換え、root、cwd、umask、既存ソケットの作成時ネットワークを維持します。``CLONE_FS``" -" の共有を許可します。ハンドルは対象ネットワークを保持し、権限や型の検査に失敗すると呼び出し元の元のネットワークを維持します。" +"``LOCK_PI`` は CLOCK_REALTIME の絶対時刻によるタイムアウトを使用します。``LOCK_PI2`` は既定で " +"CLOCK_MONOTONIC の絶対時刻を使用し、``FUTEX_CLOCK_REALTIME`` " +"でリアルタイムクロックを選択できます。シグナルで中断された PI 待機は、``SA_RESTART`` " +"が設定されていないハンドラーも含め、Linux " +"の規則に従って再開します。ロック所有権の引き継ぎが完了した場合は、待機を終了してから保留中のシグナルを配送します。" msgid "" -"无效 FD 或 ``O_PATH`` FD 返回 ``EBADF``。非 nsfs FD、类型不匹配和不支持的 类型返回 " -"``EINVAL``。当前支持 mount、user、UTS 与 network 句柄,pidfd 和 nsfs 句柄的 bind mount " -"仍未接通。参见 :doc:`../core-api/mount-namespaces`。" +"当前调度器仅接纳 SCHED_OTHER,PI 队列按相同有效优先级的 FIFO 顺序交接。 SCHED_FIFO、SCHED_RR " +"的实时调度与优先级提升仍需对应调度策略支持。 ``FUTEX_WAIT_REQUEUE_PI`` 和 " +"``FUTEX_CMP_REQUEUE_PI`` 尚未实现,返回 ENOSYS。" msgstr "" -"無効な FD と ``O_PATH`` FD は ``EBADF`` を返します。nsfs 以外の FD、型の不一致、未対応の型は " -"``EINVAL`` を返します。mount、user、UTS、network ハンドルに対応します。pidfd と nsfs ハンドルの bind " -"mount は未実装です。:doc:`../core-api/mount-namespaces` を参照してください。" +"現在のスケジューラーは SCHED_OTHER のみを受け付けます。PI キューは実効優先度が等しいタスク間で FIFO " +"順に所有権を引き継ぎます。SCHED_FIFO と SCHED_RR " +"のリアルタイムスケジューリングおよび優先度の引き上げには、対応するスケジューリング方針のサポートが必要です。``FUTEX_WAIT_REQUEUE_PI``" +" と ``FUTEX_CMP_REQUEUE_PI`` は未実装で、ENOSYS を返します。" + +msgid "CPU 时间时钟" +msgstr "CPU 時間クロック" msgid "" -"nsfs 句柄提供元数据与 ioctl。写入方式或带 ``O_TRUNC`` 的打开返回 ``EPERM``, ``O_PATH`` " -"忽略这些打开标志。普通 FD 的标量、定位和向量读返回 ``EINVAL``, 写返回 ``EBADF``,合法 ``whence`` 的 " -"``lseek()`` 返回 ``ESPIPE``。 ``NS_GET_NSTYPE`` 按实际句柄返回 " -"``CLONE_NEWNS``、``CLONE_NEWUSER``、 ``CLONE_NEWUTS`` 或 ``CLONE_NEWNET``。 " -"``FIONREAD`` 写回零,不支持的 namespace ioctl 返回 ``ENOTTY``。``O_PATH`` FD " -"可用于元数据查询,但不能 读写、定位或执行 ioctl。" +"除当前进程和线程的固定 clock ID 外,支持 Linux 编码的进程及线程 CPU 时钟, 供 " +"``clock_getcpuclockid`` 和 ``pthread_getcpuclockid`` 使用。PROF 和 SCHED " +"报告用户态与内核态累计时间,VIRT 报告用户态时间。进程时钟汇总线程组。 线程目标遵守 Linux " +"的线程组限制。``clock_gettime`` 和 ``clock_getres`` 按各自的目标验证规则处理编码 ID,非法 ID 返回 " +"EINVAL。 当前时间统计及报告分辨率为 10 ms。" msgstr "" -"nsfs ハンドルはメタデータと ioctl を提供します。書き込み用または ``O_TRUNC`` を指定したオープンは ``EPERM`` " -"を返します。``O_PATH`` はこれらのフラグを無視します。通常の FD のスカラー読み取り、位置指定読み取り、ベクトル読み取りは " -"``EINVAL``、書き込みは ``EBADF``、有効な ``whence`` での ``lseek()`` は ``ESPIPE`` " -"を返します。``NS_GET_NSTYPE`` はハンドルに応じて " -"``CLONE_NEWNS``、``CLONE_NEWUSER``、``CLONE_NEWUTS``、``CLONE_NEWNET`` " -"を返します。``FIONREAD`` はゼロを書き戻し、未対応の namespace ioctl は ``ENOTTY`` " -"を返します。``O_PATH`` FD はメタデータ照会に対応し、読み書き、シーク、ioctl は拒否します。" +"現在のプロセスとスレッドに対する固定 clock ID に加え、``clock_getcpuclockid`` と " +"``pthread_getcpuclockid`` で使用する Linux エンコードのプロセスおよびスレッド CPU " +"クロックに対応します。PROF と SCHED はユーザー空間とカーネルでの累積時間を、VIRT " +"はユーザー空間での時間を報告します。プロセスクロックはスレッドグループを集計します。対象スレッドには Linux " +"のスレッドグループ制限が適用されます。``clock_gettime`` と ``clock_getres`` " +"は、それぞれの対象検証規則に従ってエンコードされた ID を処理し、不正な ID には EINVAL を返します。現在の時間計測と報告の分解能は " +"10 ms です。" -msgid "普通文件和 socket 均可使用这些锁命令。socket 按完整的匿名 inode 编号识别, 同一端点的别名共享冲突范围,不同端点的锁独立。socket 的 ``SEEK_END`` 基准 为零,``O_PATH`` 描述符返回 ``EBADF``。关闭 socket 的 POSIX 锁释放规则与 普通文件相同,OFD 锁持续到最后一个引用释放。" -msgstr "通常ファイルと socket はこれらのロックコマンドを使用できます。socket は匿名 inode 番号全体で識別し、同じエンドポイントの別名は競合範囲を共有します。異なるエンドポイントのロックは独立します。socket の ``SEEK_END`` 基準はゼロで、``O_PATH`` 記述子は ``EBADF`` を返します。socket を閉じた際の POSIX ロック解放規則は通常ファイルと同じです。OFD ロックは最後の参照が解放されるまで保持されます。" +msgid "XSAVE 与信号帧" +msgstr "XSAVE とシグナルフレーム" -msgid "sysfs 已公开的 block、PCI 和 DRM 设备 ``uevent`` 控制由 kernel UID 0 所有,模式为 0644,权限检查沿用现有 DAC 与 kernel UID 语义。支持 ``O_TRUNC`` 的零长度截断,截断本身不发布事件。写入直接提交事件,action 与可选 UUID 的格式同网络 ``uevent``,见 :doc:`ipv6`。非法输入、只读挂载或权限检查失败均不发布事件。" -msgstr "sysfs が公開する block、PCI、DRM デバイスの ``uevent`` 制御は kernel UID 0 が所有し、モードは 0644 です。権限検査には既存の DAC と kernel UID の意味論を適用します。``O_TRUNC`` の長さ 0 の切り詰めをサポートし、切り詰め自体はイベントを発行しません。書き込みはイベントを直ちにコミットします。action と任意の UUID の形式はネットワーク ``uevent`` と共通で、:doc:`ipv6` に記載されています。不正な入力、読み取り専用マウント、権限検査の失敗ではイベントを発行しません。" +msgid "" +"支持 AVX 的 CPU 启用统一的 x87、SSE、AVX XSAVE 状态,任务保存区保持 64 字节对齐,调度切换保留全部启用状态。缺少所需" +" CPU 能力时使用 512 字节 FXSAVE 状态。当前 XSAVE mask 为 0x7,保存区为 832 字节。" +msgstr "" +"AVX 対応 CPU では x87、SSE、AVX を統合した XSAVE 状態を有効にします。タスクの保存領域は 64 " +"バイト境界に配置し、スケジューリングによる切り替えでは有効な状態をすべて保持します。必要な CPU 機能がない場合は 512 バイトの " +"FXSAVE 状態を使用します。現在の XSAVE マスクは 0x7、保存領域は 832 バイトです。" -msgid "timerfd 时钟" -msgstr "timerfd のクロック" +msgid "" +"信号帧包含 Linux 的 ``_fpx_sw_bytes``、XSAVE bitmap 和末尾 magic。 ``rt_sigreturn`` " +"验证对齐、长度、feature 位、保留字段和 MXCSR,并恢复 x87、SSE、YMM 状态。传统 fpstate 及空 fpstate 按其" +" Linux 语义处理。" +msgstr "" +"シグナルフレームには Linux の ``_fpx_sw_bytes``、XSAVE " +"ビットマップ、末尾のマジック値を含みます。``rt_sigreturn`` はアラインメント、長さ、機能ビット、予約フィールド、MXCSR " +"を検証し、x87、SSE、YMM 状態を復元します。従来の fpstate と NULL の fpstate は、それぞれ Linux " +"の意味規則に従って処理します。" -msgid "``timerfd_create()`` 支持 ``CLOCK_REALTIME``、``CLOCK_MONOTONIC`` 和 ``CLOCK_BOOTTIME``,接受 ``TFD_CLOEXEC`` 与 ``TFD_NONBLOCK``。绝对截止时间 按创建时选定的时钟解释,周期到期累计可读次数。``timerfd_settime()`` 的 ``it_value`` 为零时解除定时器,包括 ``TFD_TIMER_ABSTIME`` 模式。" -msgstr "``timerfd_create()`` は ``CLOCK_REALTIME``、``CLOCK_MONOTONIC``、``CLOCK_BOOTTIME`` と ``TFD_CLOEXEC``、``TFD_NONBLOCK`` をサポートします。絶対期限は作成時に選択したクロックで解釈され、周期的な満了は読み取り可能な回数に累積されます。``timerfd_settime()`` の ``it_value`` がゼロの場合、``TFD_TIMER_ABSTIME`` モードでもタイマーを解除します。" +msgid "定向验证" +msgstr "対象を絞った検証" -msgid "``CLOCK_BOOTTIME`` 使用现有启动时间时钟,当前与单调时钟共用计时来源。 官方 systemd 的 DHCP 重传定时器通过该接口运行。" -msgstr "``CLOCK_BOOTTIME`` は既存の起動時刻クロックを使用し、現在は単調クロックと時刻源を共有します。公式 systemd の DHCP 再送タイマーはこのインターフェースを使用します。" +msgid "" +"``tools/test_linux_threads.py`` 覆盖 rseq 生命周期、PI 等待队列与信号恢复。 CPU accounting" +" 和用户态返回路径另有宿主回归测试。 ``tools/tests/glibc_runtime_probe.c`` 可由原版 glibc " +"工具链编译,覆盖 编码 CPU 时钟、rseq 迁移与临界区中断、PI mutex 竞争、信号、双时钟超时、 robust 恢复、AVX " +"调度切换和扩展信号帧。" +msgstr "" +"``tools/test_linux_threads.py`` は rseq のライフサイクル、PI " +"待機キュー、シグナルからの復元を検証します。CPU " +"時間計測とユーザー空間への復帰経路には、別途ホスト上の回帰テストがあります。``tools/tests/glibc_runtime_probe.c``" +" は未変更の glibc ツールチェーンでコンパイルでき、エンコードされた CPU クロック、rseq の移動とクリティカルセクションの中断、PI" +" ミューテックスの競合、シグナル、両クロックでのタイムアウト、robust 回復、AVX " +"状態のスケジューリング時の切り替え、拡張シグナルフレームを検証します。" -msgid "已注册的块文件系统也支持 ``fsopen``、``fsconfig``、``fsmount`` 和 ``move_mount``。 上下文持有文件系统提供者引用,CREATE 要求初始用户空间的 ``CAP_SYS_ADMIN``。 ``source`` 必须为非空设备路径,在 CREATE 时按调用者的实际 root、cwd 和目录搜索权限 解析并跟随符号链接;非块设备返回 ``ENOTBLK``。支持 ``ro``、``rw``,vfat/exfat 接受既有 ``uid``、``gid``、``umask``、``fmask`` 和 ``dmask`` 参数,ext3 接受 ``data=ordered``。只读设备拒绝可写创建,调用者可在同一上下文设置 ``ro`` 后重试。 创建或描述符安装失败保留配置,释放所有候选挂载;``fsmount`` 的独立挂载属性继续 受共享后端只读状态约束。最后一个上下文引用关闭时释放提供者引用。" -msgstr "登録済みのブロックファイルシステムも ``fsopen``、``fsconfig``、``fsmount``、``move_mount`` に対応します。コンテキストはファイルシステム提供者への参照を保持し、CREATE には初期ユーザー名前空間の ``CAP_SYS_ADMIN`` が必要です。``source`` は空でないデバイスパスで、CREATE 時に呼び出し元の実際の root、cwd、ディレクトリ検索権限を使い、シンボリックリンクをたどって解決します。ブロックデバイス以外は ``ENOTBLK`` を返します。``ro`` と ``rw`` に対応し、vfat/exfat は既存の ``uid``、``gid``、``umask``、``fmask``、``dmask`` を、ext3 は ``data=ordered`` を受け付けます。読み取り専用デバイスへの書き込み可能な作成は拒否されます。同じコンテキストで ``ro`` を設定して再試行できます。作成や記述子登録に失敗すると設定を保持して候補マウントをすべて解放します。``fsmount`` の独立属性にも共有バックエンドの読み取り専用状態が適用されます。最後のコンテキスト参照を閉じると提供者参照を解放します。" +msgid "" +"此次使用未修改的 Debian glibc 2.41,在双核 QEMU/KVM 中分别验证启用 AVX/XSAVE 和关闭 AVX/XSAVE 的" +" CPU 配置。动态 ELF、pthread/TLS、 ``posix_spawn``、``dlopen/dlsym``、localhost " +"NSS 和普通 robust mutex 也已运行。关闭 AVX 时跳过 AVX 专项。该覆盖范围以外的应用及 glibc 版本 " +"仍需各自验证。VMware 验证未完成,实体硬件未验证。" +msgstr "" +"今回の検証では未変更の Debian glibc 2.41 を使用し、デュアルコアの QEMU/KVM で AVX/XSAVE " +"を有効および無効にした CPU 構成をそれぞれ確認しました。動的 " +"ELF、pthread/TLS、``posix_spawn``、``dlopen/dlsym``、localhost NSS、通常の robust" +" ミューテックスも実行しました。AVX が無効な場合は AVX 固有の検査をスキップします。この範囲外のアプリケーションと glibc " +"バージョンは個別の検証が必要です。VMware での検証は未完了で、実機ハードウェアは未検証です。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/inotify.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/inotify.po index d370b087..80259e1f 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/inotify.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/inotify.po @@ -4,79 +4,91 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "文件事件通知" msgstr "ファイルイベント通知" msgid "" -"inotify 是 Linux 文件事件接口,不属于 POSIX。应用通过 libc 的 ```` 调用;内核的 ```` 由 " -"``headers_install`` 导出,不需要修改 BusyBox 或 musl。" +"inotify 是 Linux 文件事件接口,不属于 POSIX。应用通过 libc 的 ```` 调用;内核的 " +"```` 由 ``headers_install`` 提供给标准 Linux 用户态。" msgstr "" -"inotify は Linux のファイルイベントインターフェースで、POSIX には含まれません。アプリケーションは libc の ```` " -"を通じて呼び出します。カーネルの ```` は ``headers_install`` で公開され、BusyBox や musl の変更は不要です。" +"inotify は Linux のファイルイベントインターフェイスです。アプリは libc の ```` " +"を使用します。カーネルの ```` は ``headers_install`` が標準 Linux " +"ユーザー空間向けに公開します。" msgid "接口与使用" msgstr "インターフェースと使い方" msgid "" -"x86-64 syscall 编号与 Linux 一致:``inotify_init`` 为 253, ``inotify_add_watch`` 为 " -"254,``inotify_rm_watch`` 为 255, ``inotify_init1`` 为 294。常见事件循环先以 ``IN_NONBLOCK | IN_CLOEXEC`` " -"创建实例,为目录安装监听,再读取初始列表, 通过 ``poll`` 或 ``epoll`` 等待并读取通知。监听前发生的变化没有历史重放。" +"x86-64 syscall 编号与 Linux 一致:``inotify_init`` 为 253, ``inotify_add_watch``" +" 为 254,``inotify_rm_watch`` 为 255, ``inotify_init1`` 为 294。常见事件循环先以 " +"``IN_NONBLOCK | IN_CLOEXEC`` 创建实例,为目录安装监听,再读取初始列表, 通过 ``poll`` 或 " +"``epoll`` 等待并读取通知。监听前发生的变化没有历史重放。" msgstr "" -"x86-64 の syscall 番号は Linux と同じで、``inotify_init`` は 253、``inotify_add_watch`` は " -"254、``inotify_rm_watch`` は 255、``inotify_init1`` は 294 です。一般的なイベントループでは ``IN_NONBLOCK | " -"IN_CLOEXEC`` でインスタンスを作り、ディレクトリー監視を設定して初期一覧を読み、``poll`` または ``epoll`` " +"x86-64 の syscall 番号は Linux と同じで、``inotify_init`` は " +"253、``inotify_add_watch`` は 254、``inotify_rm_watch`` は " +"255、``inotify_init1`` は 294 です。一般的なイベントループでは ``IN_NONBLOCK | IN_CLOEXEC``" +" でインスタンスを作り、ディレクトリー監視を設定して初期一覧を読み、``poll`` または ``epoll`` " "で待機して通知を読みます。監視開始前の変更は再生されません。" msgid "" -"``read`` 返回完整的 ``struct inotify_event`` 记录;固定头为 16 字节, 可选名称包含 NUL 和对齐填充。容量小于下一条记录时返回 ``EINVAL``, " -"不拆分记录;非阻塞空队列返回 ``EAGAIN``。阻塞等待可被信号中断。 ``readv`` 同样以每个 iovec 的容量容纳完整记录,不把一条记录拆到两个 " -"iovec;``FIONREAD`` 返回队列内包含填充的总字节数。" +"``read`` 返回完整的 ``struct inotify_event`` 记录;固定头为 16 字节, 可选名称包含 NUL " +"和对齐填充。容量小于下一条记录时返回 ``EINVAL``, 不拆分记录;非阻塞空队列返回 ``EAGAIN``。阻塞等待可被信号中断。 " +"``readv`` 同样以每个 iovec 的容量容纳完整记录,不把一条记录拆到两个 iovec;``FIONREAD`` " +"返回队列内包含填充的总字节数。" msgstr "" -"``read`` は完全な ``struct inotify_event`` レコードを返します。固定ヘッダーは 16 バイトで、任意の名前には NUL " -"とアラインメント用パディングを含みます。次のレコードより容量が小さい場合は分割せず ``EINVAL`` を返し、非ブロッキングでキューが空なら ``EAGAIN`` " -"を返します。ブロッキング待機はシグナルで中断できます。``readv`` も各 iovec の容量内に完全なレコードを収め、1 レコードを 2 つの iovec " -"に分割しません。``FIONREAD`` はパディングを含むキューの総バイト数を返します。" +"``read`` は完全な ``struct inotify_event`` レコードを返します。固定ヘッダーは 16 バイトで、任意の名前には " +"NUL とアラインメント用パディングを含みます。次のレコードより容量が小さい場合は分割せず ``EINVAL`` " +"を返し、非ブロッキングでキューが空なら ``EAGAIN`` を返します。ブロッキング待機はシグナルで中断できます。``readv`` も各 " +"iovec の容量内に完全なレコードを収め、1 レコードを 2 つの iovec に分割しません。``FIONREAD`` " +"はパディングを含むキューの総バイト数を返します。" msgid "" "``IN_CREATE``、``IN_DELETE``、``IN_MODIFY``、``IN_ATTRIB``、 " "``IN_OPEN``、``IN_CLOSE_WRITE``、``IN_CLOSE_NOWRITE``、 " -"``IN_ACCESS``、``IN_MOVE_SELF``、``IN_DELETE_SELF`` 及移动父目录事件 来自实际 VFS 或 syscall 完成路径。重命名的 " -"``IN_MOVED_FROM`` 和 ``IN_MOVED_TO`` 共用非零 cookie。目录事件按 Linux 语义附带 ``IN_ISDIR``。 内部页缓存读取和 ``mmap`` " -"缺页不产生用户读取事件。" +"``IN_ACCESS``、``IN_MOVE_SELF``、``IN_DELETE_SELF`` 及移动父目录事件 来自实际 VFS 或 " +"syscall 完成路径。重命名的 ``IN_MOVED_FROM`` 和 ``IN_MOVED_TO`` 共用非零 cookie。目录事件按 " +"Linux 语义附带 ``IN_ISDIR``。 内部页缓存读取和 ``mmap`` 缺页不产生用户读取事件。" msgstr "" "``IN_CREATE``、``IN_DELETE``、``IN_MODIFY``、``IN_ATTRIB``、``IN_OPEN``、``IN_CLOSE_WRITE``、``IN_CLOSE_NOWRITE``、``IN_ACCESS``、``IN_MOVE_SELF``、``IN_DELETE_SELF``、親ディレクトリーの移動イベントは実際の" -" VFS または syscall 完了経路から生成します。名前変更の ``IN_MOVED_FROM`` と ``IN_MOVED_TO`` は非ゼロの cookie " -"を共有します。ディレクトリーイベントには Linux の意味に従って ``IN_ISDIR`` を付けます。内部のページキャッシュ読み取りや ``mmap`` " -"のフォールトはユーザー読み取りイベントを生成しません。" +" VFS または syscall 完了経路から生成します。名前変更の ``IN_MOVED_FROM`` と ``IN_MOVED_TO`` " +"は非ゼロの cookie を共有します。ディレクトリーイベントには Linux の意味に従って ``IN_ISDIR`` " +"を付けます。内部のページキャッシュ読み取りや ``mmap`` のフォールトはユーザー読み取りイベントを生成しません。" msgid "" -"监听以 inode 身份关联:重命名不把监听转移给同名新文件,硬链接指向同一个 监听对象。``IN_MASK_ADD`` 合并掩码,``IN_MASK_CREATE`` 拒绝覆盖已有监听, " -"``IN_ONLYDIR``、``IN_DONT_FOLLOW``、``IN_EXCL_UNLINK`` 和 ``IN_ONESHOT`` 按各自语义处理。删除、显式移除和文件系统终止会生成 " -"``IN_IGNORED``;卸载还生成 ``IN_UNMOUNT``。监听本身不保留路径引用, 不会仅因存在监听而阻止卸载。" +"监听以 inode 身份关联:重命名不把监听转移给同名新文件,硬链接指向同一个 监听对象。``IN_MASK_ADD`` " +"合并掩码,``IN_MASK_CREATE`` 拒绝覆盖已有监听, " +"``IN_ONLYDIR``、``IN_DONT_FOLLOW``、``IN_EXCL_UNLINK`` 和 ``IN_ONESHOT`` " +"按各自语义处理。删除、显式移除和文件系统终止会生成 ``IN_IGNORED``;卸载还生成 " +"``IN_UNMOUNT``。监听本身不保留路径引用, 不会仅因存在监听而阻止卸载。" msgstr "" -"監視は inode の同一性に結び付けます。名前変更で同名の新しいファイルへ監視を移すことはなく、ハードリンクは同じ監視対象を指します。``IN_MASK_ADD`` " -"はマスクを統合し、``IN_MASK_CREATE`` " -"は既存監視の上書きを拒否します。``IN_ONLYDIR``、``IN_DONT_FOLLOW``、``IN_EXCL_UNLINK``、``IN_ONESHOT`` " -"はそれぞれの意味に従います。削除、明示的な監視解除、ファイルシステム終了は ``IN_IGNORED`` を生成し、アンマウントはさらに ``IN_UNMOUNT`` " -"を生成します。監視自体はパス参照を保持せず、監視があるだけではアンマウントを妨げません。" +"監視は inode " +"の同一性に結び付けます。名前変更で同名の新しいファイルへ監視を移すことはなく、ハードリンクは同じ監視対象を指します。``IN_MASK_ADD``" +" はマスクを統合し、``IN_MASK_CREATE`` " +"は既存監視の上書きを拒否します。``IN_ONLYDIR``、``IN_DONT_FOLLOW``、``IN_EXCL_UNLINK``、``IN_ONESHOT``" +" はそれぞれの意味に従います。削除、明示的な監視解除、ファイルシステム終了は ``IN_IGNORED`` を生成し、アンマウントはさらに " +"``IN_UNMOUNT`` を生成します。監視自体はパス参照を保持せず、監視があるだけではアンマウントを妨げません。" msgid "" -"``dup``、``fork`` 和传递的描述符共享同一个打开文件描述及队列;最后一个 引用释放时撤销全部监听。``CLOEXEC`` 属于描述符,``O_NONBLOCK`` 属于 " -"共享打开文件描述。对该 fd 写入返回 ``EBADF``,定位读取返回 ``ESPIPE``。 ``lseek`` 遵守 Linux 匿名 inode 的空操作行为,对支持的 whence " -"返回零。" +"``dup``、``fork`` 和传递的描述符共享同一个打开文件描述及队列;最后一个 引用释放时撤销全部监听。``CLOEXEC`` " +"属于描述符,``O_NONBLOCK`` 属于 共享打开文件描述。对该 fd 写入返回 ``EBADF``,定位读取返回 ``ESPIPE``。 " +"``lseek`` 遵守 Linux 匿名 inode 的空操作行为,对支持的 whence 返回零。" msgstr "" -"``dup``、``fork``、受け渡した記述子は同じオープンファイル記述とキューを共有し、最後の参照の解放時に全監視を解除します。``CLOEXEC`` " -"は記述子に、``O_NONBLOCK`` は共有オープンファイル記述に属します。この fd への書き込みは ``EBADF``、位置指定読み取りは ``ESPIPE`` " -"を返します。``lseek`` は Linux の匿名 inode の無操作動作に従い、対応する whence ではゼロを返します。" +"``dup``、``fork``、受け渡した記述子は同じオープンファイル記述とキューを共有し、最後の参照の解放時に全監視を解除します。``CLOEXEC``" +" は記述子に、``O_NONBLOCK`` は共有オープンファイル記述に属します。この fd への書き込みは " +"``EBADF``、位置指定読み取りは ``ESPIPE`` を返します。``lseek`` は Linux の匿名 inode " +"の無操作動作に従い、対応する whence ではゼロを返します。" msgid "容量与恢复" msgstr "容量と復旧" @@ -109,8 +121,9 @@ msgid "16384;新实例的事件队列容量,已有实例保留创建时的 msgstr "16384。新しいインスタンスのイベントキュー容量で、既存インスタンスは作成時の容量を保持します。" msgid "" -"零值可阻止后续资源创建;降低策略不会撤销已有实例或监听。实际内存分配仍可能 失败。通知分配失败或队列已满时,原文件操作保持其结果,队列提供 ``wd == -1`` 的 " -"``IN_Q_OVERFLOW``。应用收到溢出后必须重新扫描,不能继续 把旧缓存当作完整状态。相邻相同的未读事件可合并,通知数量不是操作计数器。" +"零值可阻止后续资源创建;降低策略不会撤销已有实例或监听。实际内存分配仍可能 失败。通知分配失败或队列已满时,原文件操作保持其结果,队列提供 " +"``wd == -1`` 的 ``IN_Q_OVERFLOW``。应用收到溢出后必须重新扫描,不能继续 " +"把旧缓存当作完整状态。相邻相同的未读事件可合并,通知数量不是操作计数器。" msgstr "" "ゼロ値で以後のリソース作成を阻止できます。方針値を下げても既存インスタンスや監視は取り消しません。実際のメモリー割り当ては失敗する場合があります。通知の割り当て失敗やキュー満杯でも元のファイル操作の結果は維持し、キューは" " ``wd == -1`` の ``IN_Q_OVERFLOW`` " @@ -120,32 +133,40 @@ msgid "使用边界" msgstr "使用範囲" msgid "" -"目录监听只覆盖直接子项;递归监听需要应用逐目录安装监听并处理竞态。 通知不能作为审计日志或保证每次写入单独报告,也不能保证读取通知时旧文件名 仍指向同一对象。读事件到无效用户地址时按 Linux " -"语义返回 ``EFAULT``, 该次已出队的记录不会恢复;应用应使用有效、足够大的用户缓冲区。" +"目录监听只覆盖直接子项;递归监听需要应用逐目录安装监听并处理竞态。 通知不能作为审计日志或保证每次写入单独报告,也不能保证读取通知时旧文件名 " +"仍指向同一对象。读事件到无效用户地址时按 Linux 语义返回 ``EFAULT``, " +"该次已出队的记录不会恢复;应用应使用有效、足够大的用户缓冲区。" msgstr "" "ディレクトリー監視は直下の項目だけを対象とします。再帰監視にはアプリケーションによるディレクトリーごとの監視設定と競合処理が必要です。通知は監査ログにはできず、各書き込みの個別報告や、通知を読む時点で古いファイル名が同じ対象を指すことも保証しません。無効なユーザーアドレスへのイベント読み取りは" -" Linux の意味に従い ``EFAULT`` を返し、その呼び出しで取り出し済みのレコードは戻しません。アプリケーションは有効で十分に大きいユーザーバッファーを使う必要があります。" +" Linux の意味に従い ``EFAULT`` " +"を返し、その呼び出しで取り出し済みのレコードは戻しません。アプリケーションは有効で十分に大きいユーザーバッファーを使う必要があります。" -msgid "当前不提供 fanotify、网络文件系统远端事件或可选调试 ioctl ``INOTIFY_IOC_SETNEXTWD`` 的实现;不支持的 ioctl 返回错误,不伪造成功。" +msgid "" +"当前不提供 fanotify、网络文件系统远端事件或可选调试 ioctl ``INOTIFY_IOC_SETNEXTWD`` 的实现;不支持的 " +"ioctl 返回错误,不伪造成功。" msgstr "" -"現在、fanotify、ネットワークファイルシステムのリモートイベント、任意のデバッグ ioctl ``INOTIFY_IOC_SETNEXTWD`` は実装していません。非対応 ioctl " -"はエラーを返し、成功を偽装しません。" +"現在、fanotify、ネットワークファイルシステムのリモートイベント、任意のデバッグ ioctl " +"``INOTIFY_IOC_SETNEXTWD`` は実装していません。非対応 ioctl はエラーを返し、成功を偽装しません。" msgid "验证入口" msgstr "検証の入口" msgid "" -"``tools/test_inotify_core.py``、``tools/test_inotify_vfs.py``、 ``tools/test_inotify_adapter.py`` 和 " -"``tools/test_inotify_proc.py`` 分别检查 实际队列/监听、VFS 生命周期、用户复制/等待及 sysctl 配额。 " -"``tools/test_inotify_abi.py`` 在 Linux 上运行同一份 ABI 对照探针; ``tools/tests/inotify_runtime_probe.c`` " +"``tools/test_inotify_core.py``、``tools/test_inotify_vfs.py``、 " +"``tools/test_inotify_adapter.py`` 和 ``tools/test_inotify_proc.py`` 分别检查 " +"实际队列/监听、VFS 生命周期、用户复制/等待及 sysctl 配额。 ``tools/test_inotify_abi.py`` 在 " +"Linux 上运行同一份 ABI 对照探针; ``tools/tests/inotify_runtime_probe.c`` " "也可静态编译后在来宾执行。 系统镜像及 Fileman 验证脚本由 ReliefOS 仓库持有。" msgstr "" "``tools/test_inotify_core.py``、``tools/test_inotify_vfs.py``、``tools/test_inotify_adapter.py``、``tools/test_inotify_proc.py``" -" は、それぞれ実際のキュー/監視、VFS ライフサイクル、ユーザーコピー/待機、sysctl 割り当て制限を検査します。``tools/test_inotify_abi.py`` は同じ ABI " -"比較プローブを Linux 上で実行し、``tools/tests/inotify_runtime_probe.c`` は静的コンパイルしてゲストでも実行できます。システムイメージと " -"Fileman の検証スクリプトは ReliefOS リポジトリーが管理します。" +" は、それぞれ実際のキュー/監視、VFS ライフサイクル、ユーザーコピー/待機、sysctl " +"割り当て制限を検査します。``tools/test_inotify_abi.py`` は同じ ABI 比較プローブを Linux " +"上で実行し、``tools/tests/inotify_runtime_probe.c`` " +"は静的コンパイルしてゲストでも実行できます。システムイメージと Fileman の検証スクリプトは ReliefOS リポジトリーが管理します。" -msgid "接口依据见 `Linux inotify 手册 `_。" +msgid "" +"接口依据见 `Linux inotify 手册 `_。" msgstr "" -"インターフェースの根拠は `Linux inotify マニュアル `_ " -"を参照してください。" +"インターフェースの根拠は `Linux inotify マニュアル `_ を参照してください。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po index 628f454d..b8c5d8d2 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po @@ -4,14 +4,17 @@ msgid "" msgstr "" "Project-Id-Version: ReliefNT 5.3.2\n" +"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" +"POT-Creation-Date: 2026-12-02 07:09+0800\n" "PO-Revision-Date: 2026-11-14 00:00+0000\n" "Last-Translator: ReliefOS contributors\n" -"Language-Team: Japanese\n" "Language: ja\n" +"Language-Team: Japanese\n" +"Plural-Forms: nplurals=1; plural=0;\n" "MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" +"Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" +"Generated-By: Babel 2.18.0\n" msgid "IPv6 双栈" msgstr "IPv6 デュアルスタック" @@ -20,224 +23,637 @@ msgid "接口与报文" msgstr "インターフェースとパケット" msgid "" -"IPv6 与 IPv4 共用描述符、等待队列、权限和网络执行上下文。应用使用 Linux x86-64 socket ABI 和 POSIX socket 调用,不需要 ReliefNT 私有 " -"IPv6 调用。 ``AF_INET6`` 为 10,``sockaddr_in6`` 大小为 28 字节;地址和端口为网络字节序, ``sin6_scope_id`` 是接口索引。默认 " -"``lo`` 为 1,首个物理接口 ``eth0`` 为 2。 链路本地地址需要正确的区域标识。" +"IPv6 与 IPv4 共用描述符、等待队列、权限和网络执行上下文。应用使用 Linux x86-64 socket ABI 和 POSIX " +"socket 调用,不需要 ReliefNT 私有 IPv6 调用。 ``AF_INET6`` 为 10,``sockaddr_in6`` 大小为" +" 28 字节;地址和端口为网络字节序, ``sin6_scope_id`` 是接口索引。默认 ``lo`` 为 1,首个物理接口 ``eth0``" +" 为 2。 链路本地地址需要正确的区域标识。" msgstr "" -"IPv6 は IPv4 と記述子、待ち行列、権限、ネットワーク実行コンテキストを共有します。アプリケーションは Linux x86-64 socket ABI と POSIX socket " -"呼び出しを使い、ReliefNT 独自の IPv6 呼び出しは不要です。``AF_INET6`` は 10、``sockaddr_in6`` は 28 " -"バイトです。アドレスとポートはネットワークバイト順で、``sin6_scope_id`` はインターフェース索引です。既定では ``lo`` が 1、最初の物理インターフェース ``eth0`` が 2 " -"です。リンクローカルアドレスには正しいスコープ識別子が必要です。" +"IPv6 は IPv4 と記述子、待ち行列、権限、ネットワーク実行コンテキストを共有します。アプリケーションは Linux x86-64 " +"socket ABI と POSIX socket 呼び出しを使い、ReliefNT 独自の IPv6 " +"呼び出しは不要です。``AF_INET6`` は 10、``sockaddr_in6`` は 28 " +"バイトです。アドレスとポートはネットワークバイト順で、``sin6_scope_id`` はインターフェース索引です。既定では ``lo`` が " +"1、最初の物理インターフェース ``eth0`` が 2 です。リンクローカルアドレスには正しいスコープ識別子が必要です。" msgid "" -"实现包含 UDP、TCP、ICMPv6 raw socket、回环、以太网 IPv6、邻居发现、重复地址 检测、路由器发现和 SLAAC。地址与默认路由按通告有效期维护;SLAAC 地址遵守 " -"RFC 4862 的两小时有效期保护。处理 IPv6 校验和、扩展首部、源端分片、乱序重组、 重叠分片拒绝及 Packet Too Big。IPv6 路由器不应在转发路径代替发送端分片。 " +"TCP、UDP 和 raw socket 的 ``bind`` 与 Linux 一样,只对需要区域标识的地址 使用 " +"``sin6_scope_id``。绑定 ``::``、``::1``、IPv4 映射地址或其他无此需求的 地址时忽略该字段,避免将旧版 " +"Netty 留下的未初始化值误判为不存在的网卡。 链路本地地址及接口/链路本地多播地址仍校验接口;``SO_BINDTODEVICE`` " +"指定的设备绑定继续生效。" +msgstr "" +"Linux と同様に、TCP、UDP、および raw socket の bind はスコープ識別子が必要なアドレスに限って " +"sin6_scope_id を使用します。::、::1、IPv4 マップアドレスなど、識別子が不要なアドレスではこのフィールドを無視し、旧版 " +"Netty " +"が残した未初期化の値を存在しないインターフェースとして誤判定することを防ぎます。リンクローカルアドレスとインターフェースローカルまたはリンクローカルのマルチキャストアドレスでは、引き続き有効なインターフェースを検証します。SO_BINDTODEVICE" +" で指定したデバイスへのバインドも維持します。" + +msgid "" +"实现包含 UDP、TCP、ICMPv6 raw socket、回环、以太网 IPv6、邻居发现、重复地址 检测、路由器发现和 " +"SLAAC。地址与默认路由按通告有效期维护;SLAAC 地址遵守 RFC 4862 的两小时有效期保护。处理 IPv6 " +"校验和、扩展首部、源端分片、乱序重组、 重叠分片拒绝及 Packet Too Big。IPv6 路由器不应在转发路径代替发送端分片。 " "协议维护在可调度的任务上下文执行,不在原始中断中进行阻塞内存回收。" msgstr "" -"実装には UDP、TCP、ICMPv6 raw socket、ループバック、Ethernet IPv6、近隣探索、重複アドレス検出、ルーター探索、SLAAC " -"を含みます。アドレスとデフォルト経路は通知された有効期間に従い、SLAAC アドレスは RFC 4862 の 2 時間の有効期間保護規則に従います。IPv6 " +"実装には UDP、TCP、ICMPv6 raw socket、ループバック、Ethernet " +"IPv6、近隣探索、重複アドレス検出、ルーター探索、SLAAC を含みます。アドレスとデフォルト経路は通知された有効期間に従い、SLAAC " +"アドレスは RFC 4862 の 2 時間の有効期間保護規則に従います。IPv6 " "チェックサム、拡張ヘッダー、送信元での断片化、順序外の再構成、重複フラグメントの拒否、Packet Too Big を処理します。IPv6 " "ルーターは転送経路で送信元の代わりに断片化してはなりません。プロトコル保守はスケジュール可能なタスクコンテキストで実行し、生の割り込みコンテキストでブロッキングするメモリー回収は行いません。" msgid "" -"IPv6 socket 默认允许 IPv4 映射地址;应用可在绑定前使用 ``IPV6_V6ONLY`` 限制为 IPv6。``IPV6_RECVPKTINFO`` 和 " -"``IPV6_RECVHOPLIMIT`` 提供接收接口、 目标地址和 hop limit,便于实现标准协议客户端。保留 BusyBox 使用的旧版 hop-limit 辅助数据及 raw " -"ICMPv6 checksum/filter 选项。未知选项返回错误, 不能将未实现功能报告为设置成功。" +"IPv6 socket 默认允许 IPv4 映射地址;应用可在绑定前使用 ``IPV6_V6ONLY`` 限制为 " +"IPv6。``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` 提供接收接口、 目标地址和 hop " +"limit,便于实现标准协议客户端。保留 Linux 客户端使用的兼容 hop-limit 辅助数据及 raw ICMPv6 " +"checksum/filter 选项。未知选项返回错误, 不能将未实现功能报告为设置成功。" msgstr "" -"IPv6 socket はデフォルトで IPv4 マップアドレスを許可し、アプリケーションは bind 前に ``IPV6_V6ONLY`` で IPv6 " -"のみに制限できます。``IPV6_RECVPKTINFO`` と ``IPV6_RECVHOPLIMIT`` は受信インターフェース、宛先アドレス、hop limit " -"を提供し、標準プロトコルクライアントの実装に利用できます。BusyBox が使う旧版の hop-limit 補助データと raw ICMPv6 checksum/filter " -"オプションも保持します。未知のオプションはエラーとし、未実装機能の設定成功を報告してはなりません。" - -msgid "配置与观测" -msgstr "設定と観測" - -msgid "``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 ``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl 使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。" -msgstr "``AF_NETLINK`` / ``NETLINK_ROUTE`` はソケット作成時に保持したネットワーク scope のリンク、IPv4/IPv6 アドレス、経路を照会・変更し、FD 転送後もその scope を使用します。変更にはネットワークの user owner における ``CAP_NET_ADMIN`` が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 アドレスを取得します。IPv6 アドレスと経路の ioctl は対象ネットワークの状態と owner 権限を使用し、引数形式は socket family で選択します。UDP、TCP、raw、AF_PACKET のインターフェース ioctl と、IPv6 ソケットのアドレスおよび経路 ioctl は、すべて作成元ネットワークを使用します。" +"IPv6 ソケットでは既定で IPv4 マップアドレスも使用できます。IPv6 に限定するにはバインド前に ``IPV6_V6ONLY`` " +"を指定します。``IPV6_RECVPKTINFO`` と ``IPV6_RECVHOPLIMIT`` " +"は、プロトコルクライアントに受信インターフェイス、宛先アドレス、hop limit を提供します。互換用の hop limit 補助データと " +"raw ICMPv6 のチェックサムおよびフィルターオプションも利用できます。未知のオプションはエラーになります。" -msgid "路由多播发布链路、IPv4/IPv6 地址和路由的新增、变更与删除。IPv4 路由包含直连、默认及显式路由,metric 替换发布旧路由删除和新路由添加。接口删除时,地址通知保留原接口名称与地址。每个网络空间独立维护订阅快照,全部捕获成功后替换,最后一个订阅关闭或退订时释放。快照捕获失败保留旧基线并报告 overrun,后续变更重新捕获。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 ``ENOBUFS``,调用者应重新查询。" -msgstr "ルートマルチキャストはリンク、IPv4/IPv6 アドレスと経路の追加、変更、削除を配信します。IPv4 経路には直結、デフォルト、明示的な経路が含まれ、metric の置換時は旧経路の削除と新経路の追加を配信します。インターフェース削除後もアドレス通知に元の名前とアドレスを保持します。各ネットワーク名前空間は独立した購読スナップショットを保持し、すべての取得が成功してから置換し、最後の購読者が閉じるか購読を解除すると解放します。取得失敗時は旧ベースラインを保持して overrun を報告し、後続の変更で再取得します。変更通知と overrun はネットワーク scope に従います。受信キューのオーバーフローは ``ENOBUFS`` を報告するため、呼び出し元は再照会してください。" +msgid "" +"``SOL_SOCKET`` 的 ``SO_BINDTODEVICE`` 在 socket " +"创建网络中按名称查找设备,空名称解除绑定。``SO_BINDTOIFINDEX`` 的编号为 62,按 ``int`` " +"接口索引设置或查询同一绑定。正索引允许对应尚不存在或已删除的设备,负值返回 ``EINVAL``,0 解除绑定。两者的绑定均属于 socket " +"创建网络,任务切换网络或传递 FD 后继续使用该网络。当前已有非零绑定时,修改绑定或解绑需要创建网络 user owner 的 " +"``CAP_NET_RAW``。" +msgstr "" +"``SOL_SOCKET`` の ``SO_BINDTODEVICE`` " +"は、ソケット作成時のネットワーク内で名前からデバイスを検索します。空の名前はバインドを解除します。番号 62 の " +"``SO_BINDTOIFINDEX`` は ``int`` " +"型のインターフェース索引で同じバインドを設定または取得します。正の索引は、まだ存在しないデバイスや削除済みのデバイスを指すことができます。負の値は" +" ``EINVAL`` を返し、0 はバインドを解除します。どちらのバインドもソケット作成時のネットワークに属し、タスクのネットワーク切り替えや " +"FD の受け渡し後もそのネットワークを使用します。現在のバインドが非ゼロの場合、変更や解除には作成時ネットワークの user owner における" +" ``CAP_NET_RAW`` が必要です。" -msgid "路由 socket 接受 Linux 6.12 的标准组编号 1 至 36,支持 networkd 和 resolved 的订阅组合。实际事件由对应子系统提供,具体请求仍按其实现能力校验。``sockaddr_nl.nl_groups`` 表示低 32 位,``NETLINK_ADD_MEMBERSHIP`` 和 ``NETLINK_DROP_MEMBERSHIP`` 按组编号操作。初始化后的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 8 字节位图,短缓冲区复制可容纳的完整 32 位字并报告完整所需长度;uevent 位图长度为 4 字节。" -msgstr "ルート socket は Linux 6.12 の標準グループ番号 1 から 36 を受け付け、networkd と resolved の購読の組み合わせに対応します。実際のイベントは対応するサブシステムが提供し、個々の要求は実装済みの能力に従って検証します。``sockaddr_nl.nl_groups`` は下位 32 ビットを表し、``NETLINK_ADD_MEMBERSHIP`` と ``NETLINK_DROP_MEMBERSHIP`` はグループ番号を指定します。初期化後の ``NETLINK_LIST_MEMBERSHIPS`` は 8 バイトのビットマップを返します。短いバッファーには収まる完全な 32 ビット語をコピーし、必要な全長を報告します。uevent のビットマップ長は 4 バイトです。" +msgid "IPv4 选项与 UDP 消息" +msgstr "IPv4 オプションと UDP メッセージ" msgid "" -"多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 " -"每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。" +"UDP 和 packet socket 的 ``SO_PRIORITY`` 保存有符号整数优先级,默认 0。0 至 6 可直接设置,其他值需要 " +"socket 创建网络 user owner 的 ``CAP_NET_RAW`` 或 " +"``CAP_NET_ADMIN``。用户内存或权限检查失败保留原值。" msgstr "" -"複数部分からなる問い合わせでは、データと終端の ``NLMSG_DONE`` を別々のデータグラムとして送信します。終端マーカーは要求のシーケンス番号と受信ポート ID " -"を保持し、結果が空でも送信します。受信側は引き続き各データグラム内の全メッセージを走査し、対応する番号の ``NLMSG_DONE`` またはエラーを待つ必要があります。" +"UDP と packet socket の ``SO_PRIORITY`` は符号付き整数の優先度を保持し、初期値は 0 です。0 から 6 " +"は直接設定でき、それ以外の値には socket 作成ネットワークの user owner に対する ``CAP_NET_RAW`` または " +"``CAP_NET_ADMIN`` が必要です。ユーザーメモリーまたは権限の検査に失敗すると以前の値を保持します。" -msgid "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP、TCP 和 raw 表按调用者当前网络 scope 输出。快照复制出内部状态,跨等待仅保留副本。" -msgstr "``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux のテキスト形式を使用します。アドレス scope の符号化は rtnetlink の値と異なります。アドレス、経路、UDP、TCP、raw の表は呼び出し元の現在のネットワーク scope に従います。スナップショットは内部状態をコピーし、待機をまたいでコピーだけを保持します。" +msgid "" +"UDP 的 ``IP_TOS`` 默认 0,保存输入低八位并写入实际 IPv4 首部,包含 DSCP 和 ECN 位。TOS 变化同时按 " +"Linux 的 TOS 映射更新 socket 优先级。``IP_FREEBIND`` 默认关闭,开启后允许绑定尚未配置的 IPv4 地址及 " +"IPv4 映射地址。端口冲突、设备绑定、特权端口授权和创建网络范围仍按原规则检查,发送继续要求有效路由。" +msgstr "" +"UDP の ``IP_TOS`` は初期値 0 で、入力の下位 8 ビットを DSCP と ECN を含め実際の IPv4 " +"ヘッダーに設定します。TOS の変更時には Linux の TOS マッピングで socket 優先度も更新します。``IP_FREEBIND``" +" は初期状態で無効で、有効にすると未設定の IPv4 アドレスと IPv4 mapped アドレスに bind できます。ポート競合、デバイス " +"bind、特権ポート権限、作成ネットワークの検査を維持し、送信には有効な経路が必要です。" -msgid "范围与标准" -msgstr "範囲と標準" +msgid "" +"UDP 的 ``IP_UNICAST_IF`` 和 ``IPV6_UNICAST_IF`` 分别保存 IPv4 和 IPv6 " +"的默认单播出口。设置与查询均使用网络字节序的 32 位接口索引,设置长度必须恰好为 4 字节。0 清除配置,非零索引必须存在于 socket " +"创建网络中,否则返回 ``EADDRNOTAVAIL``。已有设备绑定时设置非零索引返回 " +"``EINVAL``。普通用户可设置这些选项,接收筛选继续使用原有设备绑定。消息级接口、显式 scope 和设备绑定优先于默认单播出口;IPv4 " +"映射发送使用 IPv4 配置。" +msgstr "" +"UDP の ``IP_UNICAST_IF`` と ``IPV6_UNICAST_IF`` は、IPv4 と IPv6 " +"のデフォルトのユニキャスト送信インターフェースを個別に保持します。設定と取得にはネットワークバイト順の 32 " +"ビットインターフェース索引を使用し、設定値の長さは正確に 4 バイトである必要があります。0 " +"は設定を解除します。非ゼロの索引はソケット作成時のネットワークに存在する必要があり、存在しない場合は ``EADDRNOTAVAIL`` " +"を返します。デバイスにバインド済みのソケットへの非ゼロ索引の設定は ``EINVAL`` " +"を返します。一般ユーザーも設定でき、受信の選別には既存のデバイスバインドを引き続き使用します。メッセージ単位のインターフェース、明示的な " +"scope、デバイスバインドは、デフォルトのユニキャスト送信先より優先されます。IPv4 マップ送信は IPv4 の設定を使用します。" msgid "" -"这是 IPv6 主机实现,不提供 IPv6 路由转发、IPsec、MLDv2 源特定组播过滤或 Redirect 路由更新。DNS 策略、RDNSS 和 DHCPv6 客户端属于用户态。接收和发送" -" 缓存有资源上限,资源不足返回错误;并不宣称覆盖 Linux 的全部网络功能或全部 IPv6 扩展。" +"UDP 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 返回 realtime 微秒时间戳,支持原生 " +"IPv4、IPv6 和 IPv4 映射报文。启用时在入队采样,接收前才启用则在首次接收时采样。``MSG_PEEK`` " +"和切换时间戳格式保留已有样本,关闭选项后停止交付时间戳。时间戳通过 ``SOL_SOCKET`` 辅助消息返回,可与 IP packet info" +" 和 TTL 同时使用。输出内存准备失败保留队列,控制区不足设置 ``MSG_CTRUNC``。" msgstr "" -"これは IPv6 ホスト実装であり、IPv6 のルーティング転送、IPsec、MLDv2 の送信元固有マルチキャストフィルタリング、Redirect による経路更新は提供しません。DNS " -"方針、RDNSS、DHCPv6 クライアントはユーザー空間の担当です。送受信バッファーにはリソース上限があり、不足時はエラーを返します。Linux の全ネットワーク機能や IPv6 " -"の全拡張への対応は表明しません。" +"UDP の ``SO_TIMESTAMP_OLD`` と ``SO_TIMESTAMP_NEW`` は native IPv4、IPv6、IPv4" +" mapped データグラムに realtime " +"のマイクロ秒時刻を返します。有効時はキュー追加時に採取し、到着後に有効にすると最初の受信時に採取します。``MSG_PEEK`` " +"と時刻形式の変更で同じ標本を保持し、無効にすると時刻の出力を停止します。``SOL_SOCKET`` 補助メッセージで IP packet " +"info や TTL と共に返します。出力メモリーの準備失敗ではキューを保持し、制御領域不足では ``MSG_CTRUNC`` を設定します。" msgid "" -"依据 RFC 8200、4291、4443、4861、4862、8201、3493、3542 以及 Linux ``ipv6(7)``、``rtnetlink(7)``。POSIX " -"规定应用接口,线上 IPv6 协议细节由 相应 IETF 标准规定。宿主定向测试与完整系统 VM 测试是不同证据;VMware 和 真实硬件结果不能由 QEMU 结果替代。" +"UDP 和 TCP 的 IPv4 及 IPv4 映射通信支持 ``SOL_IP`` 的 " +"``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL`` 和 ``IP_MTU_DISCOVER``。TTL 默认 " +"64,接受 1 至 255,设置 -1 恢复默认值。接收辅助信息选项默认关闭。MTU discovery 默认 " +"``IP_PMTUDISC_WANT``,接受从 ``IP_PMTUDISC_DONT`` 到 ``IP_PMTUDISC_OMIT`` 的 0 " +"至 5。当前 IPv4 输出仅在 ``DO`` 或 ``PROBE`` 时设置 DF,其余模式清除 " +"DF。这些模式的设置与查询支持有上述报文效果,完整 IPv4 PMTU 探测与分片仍有实现边界。" msgstr "" -"RFC 8200、4291、4443、4861、4862、8201、3493、3542、および Linux の ``ipv6(7)``、``rtnetlink(7)`` に基づきます。POSIX " -"はアプリケーションインターフェースを定め、通信上の IPv6 プロトコル詳細は対応する IETF 標準が定めます。ホストの対象別テストとシステム全体の VM テストは異なる証拠であり、QEMU " -"の結果で VMware や物理ハードウェアの結果を代用することはできません。" +"UDP と TCP の IPv4 および IPv4 マップ通信は、``SOL_IP`` の " +"``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL``、``IP_MTU_DISCOVER`` をサポートします。TTL" +" の既定値は 64 で、1 から 255 を受け付け、-1 で既定値に戻ります。受信補助情報オプションは既定で無効です。MTU discovery" +" の既定値は ``IP_PMTUDISC_WANT`` で、``IP_PMTUDISC_DONT`` から " +"``IP_PMTUDISC_OMIT`` までの 0 から 5 を受け付けます。現在の IPv4 出力は ``DO`` または ``PROBE``" +" でのみ DF を設定し、他のモードでは解除します。これらのモードの設定と取得には、ここに記載したパケットへの効果があります。完全な IPv4 " +"PMTU 探索と断片化には実装上の制限が残っています。" -msgid "TCP、UDP 和 raw socket 的 ``bind`` 与 Linux 一样,只对需要区域标识的地址 使用 ``sin6_scope_id``。绑定 ``::``、``::1``、IPv4 映射地址或其他无此需求的 地址时忽略该字段,避免将旧版 Netty 留下的未初始化值误判为不存在的网卡。 链路本地地址及接口/链路本地多播地址仍校验接口;``SO_BINDTODEVICE`` 指定的设备绑定继续生效。" -msgstr "Linux と同様に、TCP、UDP、および raw socket の bind はスコープ識別子が必要なアドレスに限って sin6_scope_id を使用します。::、::1、IPv4 マップアドレスなど、識別子が不要なアドレスではこのフィールドを無視し、旧版 Netty が残した未初期化の値を存在しないインターフェースとして誤判定することを防ぎます。リンクローカルアドレスとインターフェースローカルまたはリンクローカルのマルチキャストアドレスでは、引き続き有効なインターフェースを検証します。SO_BINDTODEVICE で指定したデバイスへのバインドも維持します。" +msgid "" +"TCP 被动建立的子连接继承上述四项 IPv4 选项,IPv6 hop limit 与 PMTU 配置独立保存。TCP 上的 " +"``IP_PKTINFO`` 和 ``IP_RECVTTL`` 保存配置并由子连接继承,接收辅助数据由 UDP 路径提供。" +msgstr "" +"受動的に確立された TCP 子接続は、上記の 4 つの IPv4 オプションを継承します。IPv6 hop limit と PMTU " +"設定は独立して保存されます。TCP の ``IP_PKTINFO`` と ``IP_RECVTTL`` " +"は設定を保存し、子接続に継承します。受信補助データは UDP 経路で提供されます。" -msgid "raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 ``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD 后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。" -msgstr "raw IPv6 ソケットは作成元ネットワークを独立して保持し、作成にはその user owner における ``CAP_NET_RAW`` が必要です。アドレス bind、経路、送受信、マルチキャスト所属、ICMPv6 エラー、ping ID の競合、デバイスオプションを作成元ネットワークで隔離し、FD 転送後も同じネットワークを使います。最終 close で元のネットワークのマルチキャストから脱退し、参照を解放します。物理デバイス削除は初期ネットワークの該当ソケットだけにエラーを通知します。" +msgid "" +"TCP IPv6 socket 支持 ``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` " +"的独立状态,默认关闭,任意非零设置值查询为 1,零查询为 0。原生 IPv6 和 IPv4 映射的被动子连接继承这两项,建立后各自保存状态。TCP" +" 保存这些接收配置,当前 ``recvmsg()`` 仅交付流数据,UDP 提供上述接收辅助数据。" +msgstr "" +"TCP IPv6 ソケットは ``IPV6_RECVPKTINFO`` と ``IPV6_RECVHOPLIMIT`` " +"の独立した状態をサポートし、既定で無効です。非ゼロの設定値は 1、ゼロは 0 として取得されます。ネイティブ IPv6 と IPv4 " +"マップの受動子接続は両方を継承し、作成後はそれぞれ独立した状態を保持します。TCP はこれらの受信設定を保存し、現在の ``recvmsg()``" +" はストリームデータのみを配送します。上記の受信補助データは UDP が提供します。" msgid "" -"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 ICMP " -"错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host " -"route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态通过 " -"``clone()``、``clone3()`` 或 ``unshare()`` 的 ``CLONE_NEWNET`` 创建网络,通过 " -"``/proc//ns/net`` 句柄和 ``setns()`` 切换网络。授权与失败语义见 :doc:`abi`,内部生命周期与 " -"proc 范围见 :doc:`../core-api/mount-namespaces`。" +"TCP 开放文件描述的最后一个引用关闭时,未连接的绑定端点及 listener " +"立即释放端口、缓冲区和创建网络引用,服务可立即重新绑定监听地址。已有关联对端的端点继续按协议状态回收,排队数据、FIN 和 TIME_WAIT " +"保留各自的生命周期。" msgstr "" -"各ネットワーク名前空間は、インターフェース、loopback、IPv4 経路、IPv6 " -"アドレスと経路、近隣、多播、送信待ちパケット、フラグメント再構成、PMTU、フラグメント ID、ICMP " -"エラーのレート制限を個別に所有します。新しい名前空間の ``lo`` は初期状態が down で、IPv6 アドレスを持ちません。最初に up " -"にすると ``::1/128`` と host route " -"を設定します。各テーブルとキューは容量を独立して計数し、名前空間の破棄時にプロトコル資源を解放します。物理 NIC の登録と ingress " -"は初期名前空間に属します。ユーザー空間は ``clone()``、``clone3()``、``unshare()`` の " -"``CLONE_NEWNET`` でネットワークを作成し、``/proc//ns/net`` ハンドルと ``setns()`` " -"で切り替えます。権限と失敗時の動作は :doc:`abi`、ライフタイムと proc の範囲は " -":doc:`../core-api/mount-namespaces` を参照してください。" +"TCP の最後のオープンファイル記述を閉じると、未接続のバインド済みエンドポイントと listener " +"はポート、バッファー、作成ネットワークへの参照を直ちに解放し、サービスは待ち受けアドレスをすぐに再バインドできます。関連する相手を持つエンドポイントはプロトコル状態に従って回収され、キュー内データ、FIN、TIME_WAIT" +" はそれぞれの寿命を維持します。" -msgid "netlink socket 的 ``SO_SNDBUF`` 和 ``SO_RCVBUF`` 默认有效大小均为 65536 字节。 设置值按无符号整数裁剪到 65536 后乘二,发送和接收的最小有效值分别为 4608 和 2304 字节,查询返回有效大小。发送数据报同时受 8192 字节硬上限及有效发送 缓冲区减 32 字节的限制,超过时返回 ``EMSGSIZE``。短设置值、错误用户指针和 负长度返回错误并保留原设置。" -msgstr "netlink socket の ``SO_SNDBUF`` と ``SO_RCVBUF`` のデフォルト実効サイズはそれぞれ 65536 バイトです。設定値を符号なし整数として 65536 に制限してから 2 倍にし、送信と受信の最小実効値をそれぞれ 4608 バイトと 2304 バイトにします。取得時は実効サイズを返します。送信データグラムには 8192 バイトの上限と実効送信バッファから 32 バイトを引いた制限を適用し、超過時は ``EMSGSIZE`` を返します。短い設定値、不正なユーザーポインター、負の長さはエラーとなり、元の設定を保持します。" +msgid "" +"UDP IPv4 多播提供 " +"``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL``" +" 及 ``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP``。接口选择支持 " +"``in_addr``、``ip_mreq`` 和 ``ip_mreqn``,成员操作支持后两种布局。多播 TTL 默认 1,-1 恢复默认值,0" +" 仅本地投递。loop 和 all 默认开启。接收按创建网络、组地址、入站接口、端口和已连接对端筛选,并向所有匹配的 socket " +"投递。``IP_MULTICAST_ALL=1`` 可使用同网络其他 socket 的组成员资格,设置 0 后仅使用本 socket 成员资格。" +msgstr "" +"UDP IPv4 マルチキャストは " +"``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL``、``IP_ADD_MEMBERSHIP``" +" / ``IP_DROP_MEMBERSHIP`` を提供します。インターフェース選択は " +"``in_addr``、``ip_mreq``、``ip_mreqn`` を受け付け、メンバー操作は後者 2 形式を受け付けます。マルチキャスト " +"TTL の既定値は 1 で、-1 で既定値に戻り、0 ではローカル配送に限定します。loop と all " +"は既定で有効です。受信は作成時ネットワーク、グループアドレス、入力インターフェース、ポート、接続済み相手で選別し、一致するすべてのソケットに配送します。``IP_MULTICAST_ALL=1``" +" は同じネットワークの他のソケットのメンバー資格も利用し、0 では自身のメンバー資格のみを利用します。" -msgid "接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 位置。预留失败时返回 ``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 属于实际 socket,传递 FD 或切换网络后继续保留。" -msgstr "受信キューは各データグラムを 8192 バイトとして保守的に計上します。複数部分の照会ではデータと終了メッセージ用に 2 枠を予約します。予約失敗時はネットワーク状態を変更する前に ``ENOBUFS`` を返します。受信バッファを縮小しても既存のメッセージを保持し、新規メッセージは容量の回復を待ちます。読み取りで容量を解放し、拡張時は書き込み可能状態を更新します。バッファ設定は実際の socket に属し、FD の受け渡しやネットワークの切り替え後も保持します。" +msgid "" +"多播发送在创建网络中选择路由和源地址,以太网目的地址使用 ``01:00:5e`` 加组地址低 23 位的映射。TTL 为 0 或选择 " +"loopback 时仅按 loop 设置进行本地投递。非初始网络的发送受其可见接口限制。当前成员资格用于本地接收筛选,尚未实现 IGMP " +"报告与查询,启用 IGMP snooping 的网络可能需要额外配置才能转发流量。" +msgstr "" +"マルチキャスト送信は作成時ネットワークで経路と送信元を選択します。Ethernet 宛先は ``01:00:5e`` にグループアドレスの下位 " +"23 ビットを組み合わせます。TTL が 0 または loopback を選択した場合は、loop " +"設定に従うローカル配送に限定します。初期以外のネットワークからの送信は、そこで見えるインターフェースに制限されます。現在のメンバー資格はローカル受信の選別に使われます。IGMP" +" レポートとクエリは未実装で、IGMP snooping を有効にしたネットワークでは転送のために追加設定が必要になる場合があります。" msgid "" -"路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含 " -"被忽略的尾部;全部消息无效时不生成回复。预扫描和实际处理使用同一前缀边界。" -msgstr "ルート要求はデータグラム内の有効なメッセージの先頭部分を順番に処理し、最初の不正または不完全なメッセージとそれ以降のバイトを無視します。最後の完全なメッセージではアラインメントのパディングを省略できます。送信が成功すると、無視した末尾を含むデータグラム全体のバイト数を返します。有効なメッセージがない場合は返信を生成しません。事前走査と実際の処理は同じ先頭部分の境界を使用します。" +"UDP ``recvmsg()`` 在启用 IPv4 选项后通过 ``SOL_IP/IP_PKTINFO`` 和 " +"``SOL_IP/IP_TTL`` 返回实际入站接口、目的地址和 TTL,IPv4 " +"映射报文也使用该布局。``in_pktinfo.ipi_addr`` 为报文目的地址,``ipi_spec_dst`` 为接收接口的本地 IPv4" +" 地址,``ipi_ifindex`` 为入站接口索引。原生 IPv6 使用 ``IPV6_PKTINFO`` 和 hop-limit " +"辅助数据。控制缓冲区不足设置 ``MSG_CTRUNC``,载荷截断设置 ``MSG_TRUNC``,支持 ``MSG_PEEK``。向量 I/O" +" 保持单个 UDP 数据报的边界。" +msgstr "" +"IPv4 オプションを有効にすると、UDP ``recvmsg()`` は ``SOL_IP/IP_PKTINFO`` と " +"``SOL_IP/IP_TTL`` で実際の入力インターフェース、宛先、TTL を返します。IPv4 " +"マップパケットも同じ形式を使います。``in_pktinfo.ipi_addr`` はパケット宛先、``ipi_spec_dst`` " +"は受信インターフェースのローカル IPv4 アドレス、``ipi_ifindex`` は入力インターフェース索引です。ネイティブ IPv6 は " +"``IPV6_PKTINFO`` と hop-limit 補助データを使います。制御領域不足では " +"``MSG_CTRUNC``、ペイロード切り詰めでは ``MSG_TRUNC`` を設定し、``MSG_PEEK`` もサポートします。ベクトル " +"I/O は単一 UDP データグラムの境界を保ちます。" -msgid "IPv4 选项与 UDP 消息" -msgstr "IPv4 オプションと UDP メッセージ" +msgid "" +"UDP ``sendmsg()`` 可用 ``SOL_IP/IP_PKTINFO`` 的 ``ipi_ifindex`` 与 " +"``ipi_spec_dst`` 为单条消息选择接口和源地址,用 ``SOL_IP/IP_TTL`` 设置 1 至 255 的 TTL。IPv6 " +"socket 还支持 ``IPV6_PKTINFO`` 与 hop-limit " +"辅助数据。发送前导入并校验控制信息,消息覆盖值不改变持久选项,接口和源地址仍受创建网络及 ``SO_BINDTODEVICE`` 约束。" +msgstr "" +"UDP ``sendmsg()`` は ``SOL_IP/IP_PKTINFO`` の ``ipi_ifindex`` と " +"``ipi_spec_dst`` でメッセージ単位のインターフェースと送信元を選び、``SOL_IP/IP_TTL`` で 1 から 255 の " +"TTL を指定できます。IPv6 ソケットは ``IPV6_PKTINFO`` と hop-limit " +"補助データもサポートします。送信前に制御情報を取り込み検証します。メッセージ単位の指定は永続オプションを変更せず、インターフェースと送信元の選択には作成時ネットワークと" +" ``SO_BINDTODEVICE`` の制約が適用されます。" -msgid "UDP 和 TCP 的 IPv4 及 IPv4 映射通信支持 ``SOL_IP`` 的 ``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL`` 和 ``IP_MTU_DISCOVER``。TTL 默认 64,接受 1 至 255,设置 -1 恢复默认值。接收辅助信息选项默认关闭。MTU discovery 默认 ``IP_PMTUDISC_WANT``,接受从 ``IP_PMTUDISC_DONT`` 到 ``IP_PMTUDISC_OMIT`` 的 0 至 5。当前 IPv4 输出仅在 ``DO`` 或 ``PROBE`` 时设置 DF,其余模式清除 DF。这些模式的设置与查询支持有上述报文效果,完整 IPv4 PMTU 探测与分片仍有实现边界。" -msgstr "UDP と TCP の IPv4 および IPv4 マップ通信は、``SOL_IP`` の ``IP_TTL``、``IP_PKTINFO``、``IP_RECVTTL``、``IP_MTU_DISCOVER`` をサポートします。TTL の既定値は 64 で、1 から 255 を受け付け、-1 で既定値に戻ります。受信補助情報オプションは既定で無効です。MTU discovery の既定値は ``IP_PMTUDISC_WANT`` で、``IP_PMTUDISC_DONT`` から ``IP_PMTUDISC_OMIT`` までの 0 から 5 を受け付けます。現在の IPv4 出力は ``DO`` または ``PROBE`` でのみ DF を設定し、他のモードでは解除します。これらのモードの設定と取得には、ここに記載したパケットへの効果があります。完全な IPv4 PMTU 探索と断片化には実装上の制限が残っています。" +msgid "UDP 扩展错误队列" +msgstr "UDP 拡張エラーキュー" -msgid "TCP 被动建立的子连接继承上述四项 IPv4 选项,IPv6 hop limit 与 PMTU 配置独立保存。TCP 上的 ``IP_PKTINFO`` 和 ``IP_RECVTTL`` 保存配置并由子连接继承,接收辅助数据由 UDP 路径提供。" -msgstr "受動的に確立された TCP 子接続は、上記の 4 つの IPv4 オプションを継承します。IPv6 hop limit と PMTU 設定は独立して保存されます。TCP の ``IP_PKTINFO`` と ``IP_RECVTTL`` は設定を保存し、子接続に継承します。受信補助データは UDP 経路で提供されます。" +msgid "" +"``IP_RECVERR`` 和 ``IPV6_RECVERR`` 默认关闭。启用后,经过校验的 IPv4 ICMP 或 ICMPv6 错误按 " +"socket 创建网络、接口及原始 UDP 地址和端口关联到独立错误队列。记录保存 ``sock_extended_err`` 的 " +"errno、origin、type、code 和 MTU,以及错误发送者、原始目的地址和被引用的 UDP 载荷。IPv4 映射 socket " +"返回原生 IPv6 地址布局。" +msgstr "" +"``IP_RECVERR`` と ``IPV6_RECVERR`` はデフォルトで無効です。有効にすると、検証済みの IPv4 ICMP または " +"ICMPv6 エラーを、ソケット作成時のネットワーク、インターフェース、元の UDP " +"アドレスとポートに基づいて独立したエラーキューに関連付けます。各記録は ``sock_extended_err`` の " +"errno、origin、type、code、MTU と、エラー送信元、元の宛先、引用された UDP ペイロードを保持します。IPv4 " +"マップソケットはネイティブ IPv6 のアドレスレイアウトを返します。" -msgid "UDP IPv4 多播提供 ``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL`` 及 ``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP``。接口选择支持 ``in_addr``、``ip_mreq`` 和 ``ip_mreqn``,成员操作支持后两种布局。多播 TTL 默认 1,-1 恢复默认值,0 仅本地投递。loop 和 all 默认开启。接收按创建网络、组地址、入站接口、端口和已连接对端筛选,并向所有匹配的 socket 投递。``IP_MULTICAST_ALL=1`` 可使用同网络其他 socket 的组成员资格,设置 0 后仅使用本 socket 成员资格。" -msgstr "UDP IPv4 マルチキャストは ``IP_MULTICAST_IF``、``IP_MULTICAST_TTL``、``IP_MULTICAST_LOOP``、``IP_MULTICAST_ALL``、``IP_ADD_MEMBERSHIP`` / ``IP_DROP_MEMBERSHIP`` を提供します。インターフェース選択は ``in_addr``、``ip_mreq``、``ip_mreqn`` を受け付け、メンバー操作は後者 2 形式を受け付けます。マルチキャスト TTL の既定値は 1 で、-1 で既定値に戻り、0 ではローカル配送に限定します。loop と all は既定で有効です。受信は作成時ネットワーク、グループアドレス、入力インターフェース、ポート、接続済み相手で選別し、一致するすべてのソケットに配送します。``IP_MULTICAST_ALL=1`` は同じネットワークの他のソケットのメンバー資格も利用し、0 では自身のメンバー資格のみを利用します。" +msgid "" +"``recvmsg(MSG_ERRQUEUE)`` 通过 ``msg_name`` 返回原始目的地址,通过 " +"``SOL_IP/IP_RECVERR`` 或 ``SOL_IPV6/IPV6_RECVERR`` 辅助消息返回扩展错误及其发送者,并设置输出 " +"``MSG_ERRQUEUE``。队列为空时立即返回 ``EAGAIN``,设置 ``MSG_PEEK`` " +"仍消费该条错误。载荷和控制区不足分别报告 ``MSG_TRUNC`` 和 " +"``MSG_CTRUNC``。用户输出内存准备失败保留记录,成功读取后按下一条错误更新待处理 errno。" +msgstr "" +"``recvmsg(MSG_ERRQUEUE)`` は元の宛先を ``msg_name`` に、拡張エラーとその送信元を " +"``SOL_IP/IP_RECVERR`` または ``SOL_IPV6/IPV6_RECVERR`` の補助メッセージに返し、出力に " +"``MSG_ERRQUEUE`` を設定します。キューが空の場合は直ちに ``EAGAIN`` を返します。``MSG_PEEK`` " +"を指定してもエラー記録を消費します。ペイロードと制御領域の容量不足は、それぞれ ``MSG_TRUNC`` と ``MSG_CTRUNC`` " +"で通知します。ユーザー出力メモリの準備に失敗した場合は記録を保持します。読み取りが成功すると、次のエラーに基づいて保留中の errno " +"を更新します。" -msgid "多播发送在创建网络中选择路由和源地址,以太网目的地址使用 ``01:00:5e`` 加组地址低 23 位的映射。TTL 为 0 或选择 loopback 时仅按 loop 设置进行本地投递。非初始网络的发送受其可见接口限制。当前成员资格用于本地接收筛选,尚未实现 IGMP 报告与查询,启用 IGMP snooping 的网络可能需要额外配置才能转发流量。" -msgstr "マルチキャスト送信は作成時ネットワークで経路と送信元を選択します。Ethernet 宛先は ``01:00:5e`` にグループアドレスの下位 23 ビットを組み合わせます。TTL が 0 または loopback を選択した場合は、loop 設定に従うローカル配送に限定します。初期以外のネットワークからの送信は、そこで見えるインターフェースに制限されます。現在のメンバー資格はローカル受信の選別に使われます。IGMP レポートとクエリは未実装で、IGMP snooping を有効にしたネットワークでは転送のために追加設定が必要になる場合があります。" +msgid "" +"错误记录与普通数据报分别持有存储,待处理 errno 或错误队列可触发 ``POLLERR``。查询 ``SO_ERROR`` 清除待处理 " +"errno,已排队记录继续可读。关闭相应 RECVERR 选项会清空错误队列,保留普通数据和待处理 " +"errno。分配失败或队列达到上限时保留已有记录并继续报告 socket 错误。最后关闭释放全部记录及创建网络引用。" +msgstr "" +"エラー記録と通常のデータグラムは、それぞれ独立した記憶領域を所有します。保留中の errno またはエラーキューにより ``POLLERR`` " +"が発生します。``SO_ERROR`` の取得は保留中の errno をクリアし、キュー内の記録は引き続き読み取れます。対応する RECVERR " +"オプションを無効にするとエラーキューを空にし、通常のデータと保留中の errno " +"は保持します。メモリ割り当ての失敗やキュー上限到達時は既存の記録を保持し、ソケットエラーの通知を継続します。最後のクローズですべての記録と作成時のネットワーク参照を解放します。" -msgid "UDP ``recvmsg()`` 在启用 IPv4 选项后通过 ``SOL_IP/IP_PKTINFO`` 和 ``SOL_IP/IP_TTL`` 返回实际入站接口、目的地址和 TTL,IPv4 映射报文也使用该布局。``in_pktinfo.ipi_addr`` 为报文目的地址,``ipi_spec_dst`` 为接收接口的本地 IPv4 地址,``ipi_ifindex`` 为入站接口索引。原生 IPv6 使用 ``IPV6_PKTINFO`` 和 hop-limit 辅助数据。控制缓冲区不足设置 ``MSG_CTRUNC``,载荷截断设置 ``MSG_TRUNC``,支持 ``MSG_PEEK``。向量 I/O 保持单个 UDP 数据报的边界。" -msgstr "IPv4 オプションを有効にすると、UDP ``recvmsg()`` は ``SOL_IP/IP_PKTINFO`` と ``SOL_IP/IP_TTL`` で実際の入力インターフェース、宛先、TTL を返します。IPv4 マップパケットも同じ形式を使います。``in_pktinfo.ipi_addr`` はパケット宛先、``ipi_spec_dst`` は受信インターフェースのローカル IPv4 アドレス、``ipi_ifindex`` は入力インターフェース索引です。ネイティブ IPv6 は ``IPV6_PKTINFO`` と hop-limit 補助データを使います。制御領域不足では ``MSG_CTRUNC``、ペイロード切り詰めでは ``MSG_TRUNC`` を設定し、``MSG_PEEK`` もサポートします。ベクトル I/O は単一 UDP データグラムの境界を保ちます。" +msgid "packet socket 与链路接收" +msgstr "Packet socket とリンク受信" -msgid "UDP ``sendmsg()`` 可用 ``SOL_IP/IP_PKTINFO`` 的 ``ipi_ifindex`` 与 ``ipi_spec_dst`` 为单条消息选择接口和源地址,用 ``SOL_IP/IP_TTL`` 设置 1 至 255 的 TTL。IPv6 socket 还支持 ``IPV6_PKTINFO`` 与 hop-limit 辅助数据。发送前导入并校验控制信息,消息覆盖值不改变持久选项,接口和源地址仍受创建网络及 ``SO_BINDTODEVICE`` 约束。" -msgstr "UDP ``sendmsg()`` は ``SOL_IP/IP_PKTINFO`` の ``ipi_ifindex`` と ``ipi_spec_dst`` でメッセージ単位のインターフェースと送信元を選び、``SOL_IP/IP_TTL`` で 1 から 255 の TTL を指定できます。IPv6 ソケットは ``IPV6_PKTINFO`` と hop-limit 補助データもサポートします。送信前に制御情報を取り込み検証します。メッセージ単位の指定は永続オプションを変更せず、インターフェースと送信元の選択には作成時ネットワークと ``SO_BINDTODEVICE`` の制約が適用されます。" +msgid "" +"``AF_PACKET`` 的 ``SO_ATTACH_FILTER`` 与 ``SO_DETACH_FILTER`` 复用 classic " +"BPF 校验和执行器。过滤结果为 0 时丢弃报文,正值限制保留长度。替换失败保留旧过滤器。``bind()`` 的零 " +"``sll_protocol`` 保留创建时选择的协议。" +msgstr "" +"``AF_PACKET`` の ``SO_ATTACH_FILTER`` と ``SO_DETACH_FILTER`` は classic BPF" +" の検証器と実行器を使用します。結果が 0 " +"ならフレームを破棄し、正なら保持する長さを制限します。置換に失敗すると以前のフィルターを保持します。``bind()`` の " +"``sll_protocol`` が 0 の場合、作成時のプロトコルを保持します。" -msgid "``NETLINK_GENERIC`` 提供标准控制族 ``nlctrl``,family ID 为 16,版本为 2。``CTRL_CMD_GETFAMILY`` 支持按 ``CTRL_ATTR_FAMILY_NAME`` 或 ``CTRL_ATTR_FAMILY_ID`` 查询,同时提供时优先名称。dump 返回已注册族及独立的 ``NLMSG_DONE``,回复公布查询操作和 ``notify`` 组 16。未知族通过 ``NLMSG_ERROR`` 返回 ``ENOENT``,未实现的控制命令返回 ``EOPNOTSUPP``。当前注册族仅有 ``nlctrl``,无线 ``nl80211`` 族尚未提供。socket 保留创建网络并复用端口、队列、ACK 和错误处理语义。" -msgstr "``NETLINK_GENERIC`` は family ID 16、バージョン 2 の標準制御族 ``nlctrl`` を提供します。``CTRL_CMD_GETFAMILY`` は ``CTRL_ATTR_FAMILY_NAME`` または ``CTRL_ATTR_FAMILY_ID`` で検索し、両方ある場合は名前を優先します。dump は登録済みの族と独立した ``NLMSG_DONE`` を返し、応答は照会操作と ``notify`` グループ 16 を通知します。未知の族は ``NLMSG_ERROR`` で ``ENOENT`` を返し、未実装の制御コマンドは ``EOPNOTSUPP`` を返します。現在登録されている族は ``nlctrl`` のみで、無線の ``nl80211`` 族は未提供です。ソケットは作成時ネットワークを保持し、ポート、キュー、ACK、エラー処理の意味論を共有します。" +msgid "" +"``SOL_PACKET`` 的 ``PACKET_ADD_MEMBERSHIP`` 与 ``PACKET_DROP_MEMBERSHIP`` " +"支持按创建网络、接口及六字节地址管理 " +"``PACKET_MR_MULTICAST``,重复加入按引用计数回收。最后关闭或设备移除释放订阅。额外链路组播按同网络、同接口的订阅执行软件接收筛选。当前其他成员类型返回" +" ``EINVAL``。" +msgstr "" +"``SOL_PACKET`` の ``PACKET_ADD_MEMBERSHIP`` と ``PACKET_DROP_MEMBERSHIP`` " +"は、作成ネットワーク、インターフェース、6 バイトのアドレスで ``PACKET_MR_MULTICAST`` " +"を管理します。重複参加は参照数で管理し、最後の close " +"とデバイス削除で購読を解放します。追加のリンクマルチキャストは同じネットワークとインターフェースの購読に基づきソフトウェアで受信を選別します。他のメンバー種別は現在" +" ``EINVAL`` を返します。" -msgid "IPv4 地址的 ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知投递到 ``RTNLGRP_IPV4_IFADDR``,IPv4 路由的 ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` 通知投递到 ``RTNLGRP_IPV4_ROUTE``。订阅与通知均沿用 socket 创建网络。" -msgstr "IPv4 アドレスの ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知は ``RTNLGRP_IPV4_IFADDR`` に、IPv4 経路の ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` 通知は ``RTNLGRP_IPV4_ROUTE`` に配送します。購読と通知はともにソケットの作成時ネットワークに従います。" +msgid "" +"``PACKET_AUXDATA`` 在 ``recvmsg()`` 返回 " +"``tpacket_auxdata``,包括过滤前长度、保留长度及链路偏移。RAW 报文的网络偏移为 14,DGRAM 为 " +"0。``SO_TIMESTAMP_OLD`` 与 ``SO_TIMESTAMP_NEW`` 提供 realtime " +"微秒时间戳,排队时采样,接收前才启用时延迟采样,重复 ``MSG_PEEK`` 保留同一样本。输出内存准备失败保留队列,控制缓冲区不足设置 " +"``MSG_CTRUNC``。" +msgstr "" +"``PACKET_AUXDATA`` は ``recvmsg()`` で ``tpacket_auxdata`` " +"を返し、フィルター前の長さ、保持長、リンクオフセットを含みます。ネットワークオフセットは RAW で 14、DGRAM で 0 " +"です。``SO_TIMESTAMP_OLD`` と ``SO_TIMESTAMP_NEW`` は realtime " +"のマイクロ秒タイムスタンプを提供します。キュー投入時、または到着後に有効化した場合は受信時に採取し、繰り返す ``MSG_PEEK`` " +"でも同じ値を保持します。出力メモリー準備の失敗ではキューを保持し、制御領域不足は ``MSG_CTRUNC`` を設定します。" -msgid "``NETLINK_GENERIC`` 的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 4 字节位图,控制族 ``notify`` 使用组 16。" -msgstr "``NETLINK_GENERIC`` の ``NETLINK_LIST_MEMBERSHIPS`` は 4 バイトのビットマップを返します。制御族の ``notify`` はグループ 16 を使います。" +msgid "配置与观测" +msgstr "設定と観測" -msgid "TCP IPv6 socket 支持 ``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` 的独立状态,默认关闭,任意非零设置值查询为 1,零查询为 0。原生 IPv6 和 IPv4 映射的被动子连接继承这两项,建立后各自保存状态。TCP 保存这些接收配置,当前 ``recvmsg()`` 仅交付流数据,UDP 提供上述接收辅助数据。" -msgstr "TCP IPv6 ソケットは ``IPV6_RECVPKTINFO`` と ``IPV6_RECVHOPLIMIT`` の独立した状態をサポートし、既定で無効です。非ゼロの設定値は 1、ゼロは 0 として取得されます。ネイティブ IPv6 と IPv4 マップの受動子接続は両方を継承し、作成後はそれぞれ独立した状態を保持します。TCP はこれらの受信設定を保存し、現在の ``recvmsg()`` はストリームデータのみを配送します。上記の受信補助データは UDP が提供します。" +msgid "" +"``AF_NETLINK`` / ``NETLINK_ROUTE`` 按 socket 创建时的网络 scope 提供链路、IPv4/IPv6 " +"地址和路由查询及修改,传递 FD 后继续使用该 scope。修改需要该网络 scope 的 user owner 的 " +"``CAP_NET_ADMIN``。``getifaddrs()`` 通过标准查询获取该空间的 IPv6 地址。IPv6 地址和路由 ioctl " +"使用对应网络的状态与 owner 权限,根据 socket family 选择参数布局。UDP、TCP、raw 和 AF_PACKET " +"socket 的接口 ioctl,以及 IPv6 socket 的地址和路由 ioctl,均使用创建网络。" +msgstr "" +"``AF_NETLINK`` / ``NETLINK_ROUTE`` はソケット作成時に保持したネットワーク scope " +"のリンク、IPv4/IPv6 アドレス、経路を照会・変更し、FD 転送後もその scope を使用します。変更にはネットワークの user " +"owner における ``CAP_NET_ADMIN`` が必要です。``getifaddrs()`` は標準照会でその空間の IPv6 " +"アドレスを取得します。IPv6 アドレスと経路の ioctl は対象ネットワークの状態と owner 権限を使用し、引数形式は socket " +"family で選択します。UDP、TCP、raw、AF_PACKET のインターフェース ioctl と、IPv6 ソケットのアドレスおよび経路" +" ioctl は、すべて作成元ネットワークを使用します。" -msgid "``RTM_GETNEIGH`` dump 从 socket 创建网络的 ARP 和 NDP 快照输出邻居,支持 ``AF_UNSPEC``、``AF_INET``、``AF_INET6`` 及接口索引筛选。IPv4 的 ``NDA_DST`` 转为网络字节序,缓存地址映射以 ``NUD_STALE`` 表示,IPv6 保留现有 NUD 状态。回复包含接口、目的地址及可用的链路层地址。``AF_BRIDGE`` 和 ``NTF_PROXY`` 查询返回空表及 ``NLMSG_DONE``,邻居新增、修改和删除请求返回 ``EOPNOTSUPP``。" -msgstr "``RTM_GETNEIGH`` dump は、ソケットの作成時ネットワークの ARP と NDP スナップショットから隣接エントリを出力し、``AF_UNSPEC``、``AF_INET``、``AF_INET6`` とインターフェース索引による絞り込みをサポートします。IPv4 の ``NDA_DST`` はネットワークバイト順に変換され、キャッシュされたアドレス対応は ``NUD_STALE`` で表されます。IPv6 は既存の NUD 状態を保持します。応答にはインターフェース、宛先アドレス、利用可能なリンク層アドレスが含まれます。``AF_BRIDGE`` と ``NTF_PROXY`` の照会は空の表と ``NLMSG_DONE`` を返し、隣接エントリの追加、変更、削除要求は ``EOPNOTSUPP`` を返します。" +msgid "" +"``RTM_GETNEIGH`` dump 从 socket 创建网络的 ARP 和 NDP 快照输出邻居,支持 " +"``AF_UNSPEC``、``AF_INET``、``AF_INET6`` 及接口索引筛选。IPv4 的 ``NDA_DST`` " +"转为网络字节序,缓存地址映射以 ``NUD_STALE`` 表示,IPv6 保留现有 NUD " +"状态。回复包含接口、目的地址及可用的链路层地址。``AF_BRIDGE`` 和 ``NTF_PROXY`` 查询返回空表及 " +"``NLMSG_DONE``,邻居新增、修改和删除请求返回 ``EOPNOTSUPP``。" +msgstr "" +"``RTM_GETNEIGH`` dump は、ソケットの作成時ネットワークの ARP と NDP " +"スナップショットから隣接エントリを出力し、``AF_UNSPEC``、``AF_INET``、``AF_INET6`` " +"とインターフェース索引による絞り込みをサポートします。IPv4 の ``NDA_DST`` " +"はネットワークバイト順に変換され、キャッシュされたアドレス対応は ``NUD_STALE`` で表されます。IPv6 は既存の NUD " +"状態を保持します。応答にはインターフェース、宛先アドレス、利用可能なリンク層アドレスが含まれます。``AF_BRIDGE`` と " +"``NTF_PROXY`` の照会は空の表と ``NLMSG_DONE`` を返し、隣接エントリの追加、変更、削除要求は " +"``EOPNOTSUPP`` を返します。" msgid "``AF_BRIDGE`` 的 ``RTM_GETLINK`` dump 返回空表及 ``NLMSG_DONE``。" msgstr "``AF_BRIDGE`` の ``RTM_GETLINK`` dump は空の表と ``NLMSG_DONE`` を返します。" -msgid "独立单路径 nexthop 按 socket 创建网络保存。``RTM_NEWNEXTHOP`` 和 ``RTM_DELNEXTHOP`` 按非零 ``NHA_ID`` 创建、替换或删除 IPv4/IPv6 对象,支持 ``NHA_OIF``、``NHA_GATEWAY`` 和 ``RTNH_F_ONLINK``。``RTM_GETNEXTHOP`` 支持按 ID 查询,以及按地址族、ID 和接口筛选的 dump,dump 以 ``NLMSG_DONE`` 结束。路由通过 ``RTA_NH_ID`` 引用同网络、同地址族的对象。替换对象同步更新依赖路由,删除对象或接口同时删除依赖路由,网络销毁释放全部对象。分配失败保留对象和路由状态。nexthop group、blackhole 和封装请求返回 ``EOPNOTSUPP``。" -msgstr "独立した単一路 nexthop はソケット作成時のネットワークに属します。``RTM_NEWNEXTHOP`` と ``RTM_DELNEXTHOP`` は非ゼロの ``NHA_ID`` で IPv4/IPv6 オブジェクトを作成、置換、削除し、``NHA_OIF``、``NHA_GATEWAY``、``RTNH_F_ONLINK`` をサポートします。``RTM_GETNEXTHOP`` は ID による照会と、アドレス族、ID、インターフェースによる dump の絞り込みを提供し、dump は ``NLMSG_DONE`` で終了します。経路は ``RTA_NH_ID`` で同一ネットワーク、同一アドレス族のオブジェクトを参照します。置換は依存経路を更新し、オブジェクトまたはインターフェースの削除は依存経路も削除します。ネットワーク破棄時にはすべてのオブジェクトを解放します。メモリー割り当て失敗時はオブジェクトと経路の状態を保持します。nexthop group、blackhole、カプセル化要求は ``EOPNOTSUPP`` を返します。" +msgid "" +"独立单路径 nexthop 按 socket 创建网络保存。``RTM_NEWNEXTHOP`` 和 ``RTM_DELNEXTHOP`` 按非零" +" ``NHA_ID`` 创建、替换或删除 IPv4/IPv6 对象,支持 ``NHA_OIF``、``NHA_GATEWAY`` 和 " +"``RTNH_F_ONLINK``。``RTM_GETNEXTHOP`` 支持按 ID 查询,以及按地址族、ID 和接口筛选的 dump,dump" +" 以 ``NLMSG_DONE`` 结束。路由通过 ``RTA_NH_ID`` " +"引用同网络、同地址族的对象。替换对象同步更新依赖路由,删除对象或接口同时删除依赖路由,网络销毁释放全部对象。分配失败保留对象和路由状态。nexthop" +" group、blackhole 和封装请求返回 ``EOPNOTSUPP``。" +msgstr "" +"独立した単一路 nexthop はソケット作成時のネットワークに属します。``RTM_NEWNEXTHOP`` と " +"``RTM_DELNEXTHOP`` は非ゼロの ``NHA_ID`` で IPv4/IPv6 " +"オブジェクトを作成、置換、削除し、``NHA_OIF``、``NHA_GATEWAY``、``RTNH_F_ONLINK`` " +"をサポートします。``RTM_GETNEXTHOP`` は ID による照会と、アドレス族、ID、インターフェースによる dump " +"の絞り込みを提供し、dump は ``NLMSG_DONE`` で終了します。経路は ``RTA_NH_ID`` " +"で同一ネットワーク、同一アドレス族のオブジェクトを参照します。置換は依存経路を更新し、オブジェクトまたはインターフェースの削除は依存経路も削除します。ネットワーク破棄時にはすべてのオブジェクトを解放します。メモリー割り当て失敗時はオブジェクトと経路の状態を保持します。nexthop" +" group、blackhole、カプセル化要求は ``EOPNOTSUPP`` を返します。" -msgid "TCP 开放文件描述的最后一个引用关闭时,未连接的绑定端点及 listener 立即释放端口、缓冲区和创建网络引用,服务可立即重新绑定监听地址。已有关联对端的端点继续按协议状态回收,排队数据、FIN 和 TIME_WAIT 保留各自的生命周期。" -msgstr "TCP の最後のオープンファイル記述を閉じると、未接続のバインド済みエンドポイントと listener はポート、バッファー、作成ネットワークへの参照を直ちに解放し、サービスは待ち受けアドレスをすぐに再バインドできます。関連する相手を持つエンドポイントはプロトコル状態に従って回収され、キュー内データ、FIN、TIME_WAIT はそれぞれの寿命を維持します。" +msgid "" +"``NETLINK_GENERIC`` 提供标准控制族 ``nlctrl``,family ID 为 16,版本为 " +"2。``CTRL_CMD_GETFAMILY`` 支持按 ``CTRL_ATTR_FAMILY_NAME`` 或 " +"``CTRL_ATTR_FAMILY_ID`` 查询,同时提供时优先名称。dump 返回已注册族及独立的 " +"``NLMSG_DONE``,回复公布查询操作和 ``notify`` 组 16。未知族通过 ``NLMSG_ERROR`` 返回 " +"``ENOENT``,未实现的控制命令返回 ``EOPNOTSUPP``。当前注册族仅有 ``nlctrl``,无线 ``nl80211`` " +"族尚未提供。socket 保留创建网络并复用端口、队列、ACK 和错误处理语义。" +msgstr "" +"``NETLINK_GENERIC`` は family ID 16、バージョン 2 の標準制御族 ``nlctrl`` " +"を提供します。``CTRL_CMD_GETFAMILY`` は ``CTRL_ATTR_FAMILY_NAME`` または " +"``CTRL_ATTR_FAMILY_ID`` で検索し、両方ある場合は名前を優先します。dump は登録済みの族と独立した " +"``NLMSG_DONE`` を返し、応答は照会操作と ``notify`` グループ 16 を通知します。未知の族は " +"``NLMSG_ERROR`` で ``ENOENT`` を返し、未実装の制御コマンドは ``EOPNOTSUPP`` " +"を返します。現在登録されている族は ``nlctrl`` のみで、無線の ``nl80211`` " +"族は未提供です。ソケットは作成時ネットワークを保持し、ポート、キュー、ACK、エラー処理の意味論を共有します。" -msgid "``SOL_SOCKET`` 的 ``SO_BINDTODEVICE`` 在 socket 创建网络中按名称查找设备,空名称解除绑定。``SO_BINDTOIFINDEX`` 的编号为 62,按 ``int`` 接口索引设置或查询同一绑定。正索引允许对应尚不存在或已删除的设备,负值返回 ``EINVAL``,0 解除绑定。两者的绑定均属于 socket 创建网络,任务切换网络或传递 FD 后继续使用该网络。当前已有非零绑定时,修改绑定或解绑需要创建网络 user owner 的 ``CAP_NET_RAW``。" -msgstr "``SOL_SOCKET`` の ``SO_BINDTODEVICE`` は、ソケット作成時のネットワーク内で名前からデバイスを検索します。空の名前はバインドを解除します。番号 62 の ``SO_BINDTOIFINDEX`` は ``int`` 型のインターフェース索引で同じバインドを設定または取得します。正の索引は、まだ存在しないデバイスや削除済みのデバイスを指すことができます。負の値は ``EINVAL`` を返し、0 はバインドを解除します。どちらのバインドもソケット作成時のネットワークに属し、タスクのネットワーク切り替えや FD の受け渡し後もそのネットワークを使用します。現在のバインドが非ゼロの場合、変更や解除には作成時ネットワークの user owner における ``CAP_NET_RAW`` が必要です。" +msgid "" +"IPv4 地址查询和新增、删除通知携带 ``ifaddrmsg.ifa_flags``、32 位 " +"``IFA_FLAGS``、scope、``IFA_CACHEINFO`` 及可选的 ``IFA_RT_PRIORITY``。每个接口保存一个主 " +"IPv4 地址,支持 ``IFA_F_PERMANENT``、``IFA_F_DEPRECATED`` 和 " +"``IFA_F_NOPREFIXROUTE``。有限有效期清除 PERMANENT,首选期到期设置 " +"DEPRECATED,有效期到期删除地址。NOPREFIXROUTE 抑制自动前缀路由,IFA_RT_PRIORITY 设置其 " +"metric。省略有效期时地址永久有效。" +msgstr "" +"IPv4 アドレスの照会および追加・削除通知は ``ifaddrmsg.ifa_flags``、32 ビットの " +"``IFA_FLAGS``、scope、``IFA_CACHEINFO``、任意の ``IFA_RT_PRIORITY`` " +"を含みます。各インターフェースは主 IPv4 " +"アドレスを一つ保持し、``IFA_F_PERMANENT``、``IFA_F_DEPRECATED``、``IFA_F_NOPREFIXROUTE``" +" をサポートします。有限の有効期間は PERMANENT を解除し、優先期間の満了は DEPRECATED " +"を設定し、有効期間の満了はアドレスを削除します。NOPREFIXROUTE は自動プレフィックス経路を抑制し、IFA_RT_PRIORITY " +"はその metric を設定します。期間を省略したアドレスは永続です。" -msgid "IPv4 地址查询和新增、删除通知携带 ``ifaddrmsg.ifa_flags``、32 位 ``IFA_FLAGS``、scope、``IFA_CACHEINFO`` 及可选的 ``IFA_RT_PRIORITY``。每个接口保存一个主 IPv4 地址,支持 ``IFA_F_PERMANENT``、``IFA_F_DEPRECATED`` 和 ``IFA_F_NOPREFIXROUTE``。有限有效期清除 PERMANENT,首选期到期设置 DEPRECATED,有效期到期删除地址。NOPREFIXROUTE 抑制自动前缀路由,IFA_RT_PRIORITY 设置其 metric。省略有效期时地址永久有效。" -msgstr "IPv4 アドレスの照会および追加・削除通知は ``ifaddrmsg.ifa_flags``、32 ビットの ``IFA_FLAGS``、scope、``IFA_CACHEINFO``、任意の ``IFA_RT_PRIORITY`` を含みます。各インターフェースは主 IPv4 アドレスを一つ保持し、``IFA_F_PERMANENT``、``IFA_F_DEPRECATED``、``IFA_F_NOPREFIXROUTE`` をサポートします。有限の有効期間は PERMANENT を解除し、優先期間の満了は DEPRECATED を設定し、有効期間の満了はアドレスを削除します。NOPREFIXROUTE は自動プレフィックス経路を抑制し、IFA_RT_PRIORITY はその metric を設定します。期間を省略したアドレスは永続です。" +msgid "" +"IPv6 地址使用相同的租期和前缀 metric 属性,支持 NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE 和" +" MANAGETEMPADDR。MANAGETEMPADDR 要求 /64 " +"前缀并保存配置标志,临时隐私地址的自动生成仍待实现。自动前缀路由随地址、metric、标志和有效期维护,同时保留同前缀的其他有效地址及 RA " +"路由贡献。" +msgstr "" +"IPv6 アドレスも同じ期間とプレフィックス metric " +"属性を使用し、NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE、MANAGETEMPADDR " +"をサポートします。MANAGETEMPADDR は /64 " +"プレフィックスを要求して設定フラグを保持します。一時プライバシーアドレスの自動生成は今後の実装です。自動プレフィックス経路はアドレス、metric、フラグ、有効期間に追従し、同じプレフィックスの他の有効アドレスと" +" RA 経路からの寄与を保持します。" -msgid "IPv6 地址使用相同的租期和前缀 metric 属性,支持 NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE 和 MANAGETEMPADDR。MANAGETEMPADDR 要求 /64 前缀并保存配置标志,临时隐私地址的自动生成仍待实现。自动前缀路由随地址、metric、标志和有效期维护,同时保留同前缀的其他有效地址及 RA 路由贡献。" -msgstr "IPv6 アドレスも同じ期間とプレフィックス metric 属性を使用し、NODAD、PERMANENT、DEPRECATED、NOPREFIXROUTE、MANAGETEMPADDR をサポートします。MANAGETEMPADDR は /64 プレフィックスを要求して設定フラグを保持します。一時プライバシーアドレスの自動生成は今後の実装です。自動プレフィックス経路はアドレス、metric、フラグ、有効期間に追従し、同じプレフィックスの他の有効アドレスと RA 経路からの寄与を保持します。" +msgid "" +"IPv4/IPv6 的 ``RTM_NEWADDR`` 允许仅携带 ``NLM_F_REPLACE`` 创建地址。已有地址遇 " +"``NLM_F_EXCL`` 或缺少 REPLACE 时返回 ``EEXIST``,校验失败保留原配置。``RTM_NEWROUTE`` 接受 " +"``NLM_F_APPEND``,新增路由保留同优先级存活路由的插入顺序。修改请求的 ``NLM_F_ECHO`` 和其他修改消息上的 " +"APPEND 返回 ``EOPNOTSUPP``。" +msgstr "" +"IPv4/IPv6 の ``RTM_NEWADDR`` は ``NLM_F_REPLACE`` 単独でアドレスを作成できます。既存アドレスに " +"``NLM_F_EXCL`` がある場合、または REPLACE がない場合は ``EEXIST`` " +"を返します。検証失敗時は元の設定を保持します。``RTM_NEWROUTE`` は ``NLM_F_APPEND`` " +"を受け入れ、新しい経路は同じ優先度の既存経路の挿入順序を維持します。変更要求の ``NLM_F_ECHO`` と他の変更メッセージの APPEND" +" は ``EOPNOTSUPP`` を返します。" -msgid "IPv4/IPv6 的 ``RTM_NEWADDR`` 允许仅携带 ``NLM_F_REPLACE`` 创建地址。已有地址遇 ``NLM_F_EXCL`` 或缺少 REPLACE 时返回 ``EEXIST``,校验失败保留原配置。``RTM_NEWROUTE`` 接受 ``NLM_F_APPEND``,新增路由保留同优先级存活路由的插入顺序。修改请求的 ``NLM_F_ECHO`` 和其他修改消息上的 APPEND 返回 ``EOPNOTSUPP``。" -msgstr "IPv4/IPv6 の ``RTM_NEWADDR`` は ``NLM_F_REPLACE`` 単独でアドレスを作成できます。既存アドレスに ``NLM_F_EXCL`` がある場合、または REPLACE がない場合は ``EEXIST`` を返します。検証失敗時は元の設定を保持します。``RTM_NEWROUTE`` は ``NLM_F_APPEND`` を受け入れ、新しい経路は同じ優先度の既存経路の挿入順序を維持します。変更要求の ``NLM_F_ECHO`` と他の変更メッセージの APPEND は ``EOPNOTSUPP`` を返します。" +msgid "" +"IPv4/IPv6 路由支持 ``RTA_PREFSRC`` 及 ``RTNH_F_ONLINK``,首选源地址须已配置在同网络。IPv6 还支持" +" ``RTA_PREF`` 的低、中、高优先级与 ``RTA_EXPIRES`` 秒级有效期,到期发布删除通知。IPv6 " +"路由身份包含目的前缀、接口、网关、nexthop ID 和 metric,同路径不同 metric 可共存。选路依次比较最长前缀、较低 " +"metric 和较高 preference,完全相同时保留先插入路由。REPLACE 更新匹配条目,目标缺失且未携带 CREATE 时返回 " +"``ESRCH``。" +msgstr "" +"IPv4/IPv6 経路は ``RTA_PREFSRC`` と ``RTNH_F_ONLINK`` " +"をサポートし、優先送信元アドレスは同じネットワークに設定済みである必要があります。IPv6 は ``RTA_PREF`` の低・中・高優先度と " +"``RTA_EXPIRES`` による秒単位の有効期間も提供し、満了時に削除通知を発行します。IPv6 " +"経路の識別には宛先プレフィックス、インターフェース、ゲートウェイ、nexthop ID、metric が含まれ、同じ経路で異なる metric " +"が共存できます。選択は最長プレフィックス、低い metric、高い preference " +"の順に比較し、完全に等しい場合は先に挿入した経路を保持します。REPLACE は一致するエントリを更新し、対象が存在せず CREATE " +"がない場合は ``ESRCH`` を返します。" -msgid "IPv4/IPv6 路由支持 ``RTA_PREFSRC`` 及 ``RTNH_F_ONLINK``,首选源地址须已配置在同网络。IPv6 还支持 ``RTA_PREF`` 的低、中、高优先级与 ``RTA_EXPIRES`` 秒级有效期,到期发布删除通知。IPv6 路由身份包含目的前缀、接口、网关、nexthop ID 和 metric,同路径不同 metric 可共存。选路依次比较最长前缀、较低 metric 和较高 preference,完全相同时保留先插入路由。REPLACE 更新匹配条目,目标缺失且未携带 CREATE 时返回 ``ESRCH``。" -msgstr "IPv4/IPv6 経路は ``RTA_PREFSRC`` と ``RTNH_F_ONLINK`` をサポートし、優先送信元アドレスは同じネットワークに設定済みである必要があります。IPv6 は ``RTA_PREF`` の低・中・高優先度と ``RTA_EXPIRES`` による秒単位の有効期間も提供し、満了時に削除通知を発行します。IPv6 経路の識別には宛先プレフィックス、インターフェース、ゲートウェイ、nexthop ID、metric が含まれ、同じ経路で異なる metric が共存できます。選択は最長プレフィックス、低い metric、高い preference の順に比較し、完全に等しい場合は先に挿入した経路を保持します。REPLACE は一致するエントリを更新し、対象が存在せず CREATE がない場合は ``ESRCH`` を返します。" +msgid "" +"IPv4 地址的 ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知投递到 " +"``RTNLGRP_IPV4_IFADDR``,IPv4 路由的 ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` " +"通知投递到 ``RTNLGRP_IPV4_ROUTE``。订阅与通知均沿用 socket 创建网络。" +msgstr "" +"IPv4 アドレスの ``RTM_NEWADDR`` / ``RTM_DELADDR`` 通知は ``RTNLGRP_IPV4_IFADDR`` " +"に、IPv4 経路の ``RTM_NEWROUTE`` / ``RTM_DELROUTE`` 通知は ``RTNLGRP_IPV4_ROUTE``" +" に配送します。購読と通知はともにソケットの作成時ネットワークに従います。" -msgid "网络 sysfs 与设备事件" -msgstr "ネットワーク sysfs とデバイスイベント" +msgid "" +"路由多播发布链路、IPv4/IPv6 地址和路由的新增、变更与删除。IPv4 路由包含直连、默认及显式路由,metric " +"替换发布旧路由删除和新路由添加。接口删除时,地址通知保留原接口名称与地址。每个网络空间独立维护订阅快照,全部捕获成功后替换,最后一个订阅关闭或退订时释放。快照捕获失败保留旧基线并报告" +" overrun,后续变更重新捕获。变更通知和 overrun 按网络 scope 投递,接收队列溢出报告 " +"``ENOBUFS``,调用者应重新查询。" +msgstr "" +"ルートマルチキャストはリンク、IPv4/IPv6 アドレスと経路の追加、変更、削除を配信します。IPv4 " +"経路には直結、デフォルト、明示的な経路が含まれ、metric " +"の置換時は旧経路の削除と新経路の追加を配信します。インターフェース削除後もアドレス通知に元の名前とアドレスを保持します。各ネットワーク名前空間は独立した購読スナップショットを保持し、すべての取得が成功してから置換し、最後の購読者が閉じるか購読を解除すると解放します。取得失敗時は旧ベースラインを保持して" +" overrun を報告し、後続の変更で再取得します。変更通知と overrun はネットワーク scope " +"に従います。受信キューのオーバーフローは ``ENOBUFS`` を報告するため、呼び出し元は再照会してください。" -msgid "sysfs 挂载保留创建时捕获的网络空间,后续 lookup、readdir、read 和 write 均使用该视图。任务执行 ``setns()``、``unshare()`` 或传递挂载句柄后,已有挂载继续观察原网络。``fsopen(\"sysfs\")`` 的网络与 owner 捕获及 CREATE 授权见 :doc:`abi`。" -msgstr "sysfs マウントは作成時に取得したネットワーク名前空間を保持し、その後の lookup、readdir、read、write はこのビューを使用します。タスクが ``setns()`` や ``unshare()`` を実行した後、またはマウントハンドルを受け渡した後も、既存のマウントは元のネットワークを参照します。``fsopen(\"sysfs\")`` によるネットワークと owner の取得、および CREATE の認可は :doc:`abi` を参照してください。" +msgid "" +"路由 socket 接受 Linux 6.12 的标准组编号 1 至 36,支持 networkd 和 resolved " +"的订阅组合。实际事件由对应子系统提供,具体请求仍按其实现能力校验。``sockaddr_nl.nl_groups`` 表示低 32 " +"位,``NETLINK_ADD_MEMBERSHIP`` 和 ``NETLINK_DROP_MEMBERSHIP`` 按组编号操作。初始化后的 " +"``NETLINK_LIST_MEMBERSHIPS`` 返回 8 字节位图,短缓冲区复制可容纳的完整 32 位字并报告完整所需长度;uevent" +" 位图长度为 4 字节。" +msgstr "" +"ルート socket は Linux 6.12 の標準グループ番号 1 から 36 を受け付け、networkd と resolved " +"の購読の組み合わせに対応します。実際のイベントは対応するサブシステムが提供し、個々の要求は実装済みの能力に従って検証します。``sockaddr_nl.nl_groups``" +" は下位 32 ビットを表し、``NETLINK_ADD_MEMBERSHIP`` と ``NETLINK_DROP_MEMBERSHIP`` " +"はグループ番号を指定します。初期化後の ``NETLINK_LIST_MEMBERSHIPS`` は 8 " +"バイトのビットマップを返します。短いバッファーには収まる完全な 32 ビット語をコピーし、必要な全長を報告します。uevent のビットマップ長は" +" 4 バイトです。" -msgid "``/sys/class/net/`` 是指向 canonical 设备节点的符号链接。loopback 位于 ``/sys/devices/virtual/net/lo``,物理接口位于对应 PCI function 下的 ``net/``,``device`` 链接指向 PCI 父节点,``subsystem`` 链接指向 ``/sys/class/net``。属性包含 ``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier`` 和 ``uevent``。物理接口仅在初始网络中可见。接口移除后,持有的旧 inode 在重新打开、读取或写入时返回 ``ENOENT``。" -msgstr "``/sys/class/net/`` は canonical デバイスノードへのシンボリックリンクです。loopback は ``/sys/devices/virtual/net/lo`` に配置されます。物理インターフェースは対応する PCI function 配下の ``net/`` に配置され、``device`` は PCI 親ノードを、``subsystem`` は ``/sys/class/net`` を指します。属性には ``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier``、``uevent`` が含まれます。物理インターフェースは初期ネットワークでのみ可視です。インターフェース削除後、保持済みの旧 inode を再度開く操作、読み取り、書き込みは ``ENOENT`` を返します。" +msgid "" +"``NETLINK_GENERIC`` 的 ``NETLINK_LIST_MEMBERSHIPS`` 返回 4 字节位图,控制族 " +"``notify`` 使用组 16。" +msgstr "" +"``NETLINK_GENERIC`` の ``NETLINK_LIST_MEMBERSHIPS`` は 4 " +"バイトのビットマップを返します。制御族の ``notify`` はグループ 16 を使います。" -msgid "网络 ``uevent`` 文件由 root 所有,模式为 0644,写入遵循常规 DAC 与挂载只读策略。只读挂载也阻止 root 写入。读取提供 ``INTERFACE`` 和 ``IFINDEX``。写入接受 ``add``、``remove``、``change``、``move``、``online``、``offline``、``bind`` 或 ``unbind``,可在一个空格后附加 36 字符的十六进制 UUID,连字符位于标准位置,末尾可带一个换行。无 UUID 时事件使用 ``SYNTH_UUID=0``,提供 UUID 时按输入传递。无效 action、UUID 或 embedded NUL 返回 ``EINVAL``,并保持事件队列不变。" -msgstr "ネットワークの ``uevent`` ファイルは root 所有で、モードは 0644 です。書き込みには通常の DAC とマウントの読み取り専用ポリシーが適用されます。読み取り専用マウントは root による書き込みも拒否します。読み取りは ``INTERFACE`` と ``IFINDEX`` を提供します。書き込みは ``add``、``remove``、``change``、``move``、``online``、``offline``、``bind``、``unbind`` を受け付け、任意でスペース 1 個と、標準位置にハイフンを持つ 36 文字の 16 進 UUID を続けられます。末尾の改行 1 個も許可されます。UUID がないイベントは ``SYNTH_UUID=0`` を使用し、指定された UUID は入力どおりに渡されます。不正な action、UUID、埋め込み NUL は ``EINVAL`` を返し、イベントキューを維持します。" +msgid "" +"netlink socket 的 ``SO_SNDBUF`` 和 ``SO_RCVBUF`` 默认有效大小均为 65536 字节。 " +"设置值按无符号整数裁剪到 65536 后乘二,发送和接收的最小有效值分别为 4608 和 2304 字节,查询返回有效大小。发送数据报同时受 " +"8192 字节硬上限及有效发送 缓冲区减 32 字节的限制,超过时返回 ``EMSGSIZE``。短设置值、错误用户指针和 " +"负长度返回错误并保留原设置。" +msgstr "" +"netlink socket の ``SO_SNDBUF`` と ``SO_RCVBUF`` のデフォルト実効サイズはそれぞれ 65536 " +"バイトです。設定値を符号なし整数として 65536 に制限してから 2 倍にし、送信と受信の最小実効値をそれぞれ 4608 バイトと 2304 " +"バイトにします。取得時は実効サイズを返します。送信データグラムには 8192 バイトの上限と実効送信バッファから 32 " +"バイトを引いた制限を適用し、超過時は ``EMSGSIZE`` " +"を返します。短い設定値、不正なユーザーポインター、負の長さはエラーとなり、元の設定を保持します。" -msgid "``NETLINK_KOBJECT_UEVENT`` 的网络设备事件按订阅 socket 的创建网络筛选。物理接口注册和移除分别发布 ``add`` 和 ``remove``,移除事件保留注册时的设备身份。sysfs 合成事件使用挂载捕获的网络,事件携带 action、设备路径、``SUBSYSTEM=net``、``INTERFACE`` 和 ``IFINDEX``,合成事件还携带 ``SYNTH_UUID``。其他网络的订阅者不会收到该网络事件,任务随后切换网络也保留已有 socket 的订阅范围。" -msgstr "``NETLINK_KOBJECT_UEVENT`` のネットワークデバイスイベントは、購読ソケット作成時のネットワークに基づいて選別されます。物理インターフェースの登録と削除は、それぞれ ``add`` と ``remove`` を発行します。削除イベントは登録時に取得したデバイス識別情報を保持します。sysfs の合成イベントはマウントが取得したネットワークを使用します。イベントは action、デバイスパス、``SUBSYSTEM=net``、``INTERFACE``、``IFINDEX`` を含み、合成イベントはさらに ``SYNTH_UUID`` を含みます。他のネットワークの購読者にはそのネットワークイベントは届きません。タスクが後でネットワークを切り替えても、既存ソケットの購読範囲を維持します。" +msgid "" +"接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 位置。预留失败时返回 " +"``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 " +"属于实际 socket,传递 FD 或切换网络后继续保留。" +msgstr "" +"受信キューは各データグラムを 8192 バイトとして保守的に計上します。複数部分の照会ではデータと終了メッセージ用に 2 " +"枠を予約します。予約失敗時はネットワーク状態を変更する前に ``ENOBUFS`` " +"を返します。受信バッファを縮小しても既存のメッセージを保持し、新規メッセージは容量の回復を待ちます。読み取りで容量を解放し、拡張時は書き込み可能状態を更新します。バッファ設定は実際の" +" socket に属し、FD の受け渡しやネットワークの切り替え後も保持します。" -msgid "block、PCI 和 DRM 已公开的设备 ``uevent`` 控制同样接受上述 action 与可选 UUID,权限和即时写入语义见 :doc:`abi`。事件属性取自同一设备的当前真实 inventory,``SUBSYSTEM`` 取自该设备的 ``subsystem`` 链接,并附带 ``SYNTH_UUID``。这些 global 设备事件仅投递给初始 user namespace 所拥有的网络空间中的订阅者,包含永久初始网络。网络设备事件继续严格按 socket 创建网络与挂载捕获网络隔离。" -msgstr "block、PCI、DRM デバイスが公開する ``uevent`` 制御も、上記の action と任意の UUID を受け付けます。権限と即時書き込みの意味論は :doc:`abi` を参照してください。イベント属性は同じデバイスの現在の実際の inventory から取得します。``SUBSYSTEM`` はそのデバイスの ``subsystem`` リンクから取得し、``SYNTH_UUID`` を付加します。これらの global デバイスイベントは、永続的な初期ネットワークを含む、初期 user namespace が所有するネットワーク名前空間内の購読者にのみ配送されます。ネットワークデバイスイベントは、ソケット作成時のネットワークとマウントが取得したネットワークによる厳密な隔離を維持します。" +msgid "" +"路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含" +" 被忽略的尾部;全部消息无效时不生成回复。预扫描和实际处理使用同一前缀边界。" +msgstr "ルート要求はデータグラム内の有効なメッセージの先頭部分を順番に処理し、最初の不正または不完全なメッセージとそれ以降のバイトを無視します。最後の完全なメッセージではアラインメントのパディングを省略できます。送信が成功すると、無視した末尾を含むデータグラム全体のバイト数を返します。有効なメッセージがない場合は返信を生成しません。事前走査と実際の処理は同じ先頭部分の境界を使用します。" -msgid "``RTM_SETLINK`` 与 ``RTM_NEWLINK`` 在提供正接口索引和 ``IFLA_IFNAME`` 时执行重命名,索引为 0 时按名称选择已有接口。``SIOCSIFNAME`` 使用相同的创建网络与 ``CAP_NET_ADMIN`` 授权。重命名保留接口索引和 UP 状态,更新 ioctl、socket 设备绑定查询及 sysfs 名称,并发布同网络的 ``RTM_NEWLINK`` 与携带 ``DEVPATH_OLD`` 的 ``move`` 事件。名称最长 15 字节,空白、斜线、冒号、``.`` 和 ``..`` 返回 ``EINVAL``,同网络名称冲突返回 ``EEXIST``。单个 ``%d`` 模板选择 0 至 32767 内首个空闲编号,同名请求不发布事件。``name_assign_type`` 对枚举物理名称报告 1,重命名后报告 4。" -msgstr "``RTM_SETLINK`` と ``RTM_NEWLINK`` は、正のインターフェース索引と ``IFLA_IFNAME`` が指定された場合に名前を変更します。索引 0 は名前で既存のインターフェースを選択します。``SIOCSIFNAME`` も作成時ネットワークの範囲と ``CAP_NET_ADMIN`` による認可を使います。名前変更では索引と UP 状態を保持し、ioctl、socket のデバイス束縛照会、sysfs の名前を更新します。同じネットワークに ``RTM_NEWLINK`` と ``DEVPATH_OLD`` を含む ``move`` イベントを配信します。名前は最大 15 バイトです。空白、スラッシュ、コロン、``.``、``..`` は ``EINVAL``、同じネットワーク内の名前衝突は ``EEXIST`` を返します。単一の ``%d`` テンプレートは 0 から 32767 までの最初の空き番号を選びます。同名への要求はイベントを配信しません。``name_assign_type`` は列挙された物理名で 1、名前変更後は 4 を返します。" +msgid "" +"多部分查询的数据与 ``NLMSG_DONE`` 结束标记分开发送为数据报;结束标记保留 请求序号和接收端口 " +"ID。即使查询没有数据,也会发送结束标记。接收方仍应遍历 每个数据报内的全部消息,直到收到对应序号的 ``NLMSG_DONE`` 或错误。" +msgstr "" +"複数部分からなる問い合わせでは、データと終端の ``NLMSG_DONE`` " +"を別々のデータグラムとして送信します。終端マーカーは要求のシーケンス番号と受信ポート ID " +"を保持し、結果が空でも送信します。受信側は引き続き各データグラム内の全メッセージを走査し、対応する番号の ``NLMSG_DONE`` " +"またはエラーを待つ必要があります。" -msgid "packet socket 与链路接收" -msgstr "Packet socket とリンク受信" +msgid "" +"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` 使用 Linux" +" 文本布局,其中地址 scope 的编码与 rtnetlink 的 scope 值不同。地址、路由、UDP、TCP 和 raw 表按调用者当前网络" +" scope 输出。快照复制出内部状态,跨等待仅保留副本。" +msgstr "" +"``/proc/net/if_inet6``、``ipv6_route``、``tcp6``、``udp6``、``raw6`` は Linux " +"のテキスト形式を使用します。アドレス scope の符号化は rtnetlink の値と異なります。アドレス、経路、UDP、TCP、raw " +"の表は呼び出し元の現在のネットワーク scope に従います。スナップショットは内部状態をコピーし、待機をまたいでコピーだけを保持します。" -msgid "``AF_PACKET`` 的 ``SO_ATTACH_FILTER`` 与 ``SO_DETACH_FILTER`` 复用 classic BPF 校验和执行器。过滤结果为 0 时丢弃报文,正值限制保留长度。替换失败保留旧过滤器。``bind()`` 的零 ``sll_protocol`` 保留创建时选择的协议。" -msgstr "``AF_PACKET`` の ``SO_ATTACH_FILTER`` と ``SO_DETACH_FILTER`` は classic BPF の検証器と実行器を使用します。結果が 0 ならフレームを破棄し、正なら保持する長さを制限します。置換に失敗すると以前のフィルターを保持します。``bind()`` の ``sll_protocol`` が 0 の場合、作成時のプロトコルを保持します。" +msgid "" +"raw IPv6 套接字独立保留创建网络,创建需要该网络 user owner 的 " +"``CAP_NET_RAW``。地址绑定、路由、收发、多播成员、ICMPv6 错误、ping ID 冲突和设备选项按创建网络隔离,传递 FD " +"后继续使用同一网络。最后关闭时在原网络退出多播并释放引用,物理设备移除只向初始网络的相关套接字报告错误。" +msgstr "" +"raw IPv6 ソケットは作成元ネットワークを独立して保持し、作成にはその user owner における ``CAP_NET_RAW`` " +"が必要です。アドレス bind、経路、送受信、マルチキャスト所属、ICMPv6 エラー、ping ID " +"の競合、デバイスオプションを作成元ネットワークで隔離し、FD 転送後も同じネットワークを使います。最終 close " +"で元のネットワークのマルチキャストから脱退し、参照を解放します。物理デバイス削除は初期ネットワークの該当ソケットだけにエラーを通知します。" -msgid "``SOL_PACKET`` 的 ``PACKET_ADD_MEMBERSHIP`` 与 ``PACKET_DROP_MEMBERSHIP`` 支持按创建网络、接口及六字节地址管理 ``PACKET_MR_MULTICAST``,重复加入按引用计数回收。最后关闭或设备移除释放订阅。额外链路组播按同网络、同接口的订阅执行软件接收筛选。当前其他成员类型返回 ``EINVAL``。" -msgstr "``SOL_PACKET`` の ``PACKET_ADD_MEMBERSHIP`` と ``PACKET_DROP_MEMBERSHIP`` は、作成ネットワーク、インターフェース、6 バイトのアドレスで ``PACKET_MR_MULTICAST`` を管理します。重複参加は参照数で管理し、最後の close とデバイス削除で購読を解放します。追加のリンクマルチキャストは同じネットワークとインターフェースの購読に基づきソフトウェアで受信を選別します。他のメンバー種別は現在 ``EINVAL`` を返します。" +msgid "" +"每个网络空间独立持有接口、loopback、IPv4 路由,以及 IPv6 地址、路由、邻居、多播、待发包、分片重组、PMTU、分片编号和 " +"ICMP 错误限速状态。新空间的 ``lo`` 默认 down 且无 IPv6 地址,首次 up 配置 ``::1/128`` 和 host " +"route。各表及队列分别计量容量,空间销毁时释放协议资源。物理 NIC 注册和 ingress 仍归初始空间。用户态通过 " +"``clone()``、``clone3()`` 或 ``unshare()`` 的 ``CLONE_NEWNET`` 创建网络,通过 " +"``/proc//ns/net`` 句柄和 ``setns()`` 切换网络。授权与失败语义见 :doc:`abi`,内部生命周期与 " +"proc 范围见 :doc:`../core-api/mount-namespaces`。" +msgstr "" +"各ネットワーク名前空間は、インターフェース、loopback、IPv4 経路、IPv6 " +"アドレスと経路、近隣、多播、送信待ちパケット、フラグメント再構成、PMTU、フラグメント ID、ICMP " +"エラーのレート制限を個別に所有します。新しい名前空間の ``lo`` は初期状態が down で、IPv6 アドレスを持ちません。最初に up " +"にすると ``::1/128`` と host route " +"を設定します。各テーブルとキューは容量を独立して計数し、名前空間の破棄時にプロトコル資源を解放します。物理 NIC の登録と ingress " +"は初期名前空間に属します。ユーザー空間は ``clone()``、``clone3()``、``unshare()`` の " +"``CLONE_NEWNET`` でネットワークを作成し、``/proc//ns/net`` ハンドルと ``setns()`` " +"で切り替えます。権限と失敗時の動作は :doc:`abi`、ライフタイムと proc の範囲は :doc:`../core-api/mount-" +"namespaces` を参照してください。" -msgid "``PACKET_AUXDATA`` 在 ``recvmsg()`` 返回 ``tpacket_auxdata``,包括过滤前长度、保留长度及链路偏移。RAW 报文的网络偏移为 14,DGRAM 为 0。``SO_TIMESTAMP_OLD`` 与 ``SO_TIMESTAMP_NEW`` 提供 realtime 微秒时间戳,排队时采样,接收前才启用时延迟采样,重复 ``MSG_PEEK`` 保留同一样本。输出内存准备失败保留队列,控制缓冲区不足设置 ``MSG_CTRUNC``。" -msgstr "``PACKET_AUXDATA`` は ``recvmsg()`` で ``tpacket_auxdata`` を返し、フィルター前の長さ、保持長、リンクオフセットを含みます。ネットワークオフセットは RAW で 14、DGRAM で 0 です。``SO_TIMESTAMP_OLD`` と ``SO_TIMESTAMP_NEW`` は realtime のマイクロ秒タイムスタンプを提供します。キュー投入時、または到着後に有効化した場合は受信時に採取し、繰り返す ``MSG_PEEK`` でも同じ値を保持します。出力メモリー準備の失敗ではキューを保持し、制御領域不足は ``MSG_CTRUNC`` を設定します。" +msgid "网络 sysfs 与设备事件" +msgstr "ネットワーク sysfs とデバイスイベント" -msgid "UDP 和 packet socket 的 ``SO_PRIORITY`` 保存有符号整数优先级,默认 0。0 至 6 可直接设置,其他值需要 socket 创建网络 user owner 的 ``CAP_NET_RAW`` 或 ``CAP_NET_ADMIN``。用户内存或权限检查失败保留原值。" -msgstr "UDP と packet socket の ``SO_PRIORITY`` は符号付き整数の優先度を保持し、初期値は 0 です。0 から 6 は直接設定でき、それ以外の値には socket 作成ネットワークの user owner に対する ``CAP_NET_RAW`` または ``CAP_NET_ADMIN`` が必要です。ユーザーメモリーまたは権限の検査に失敗すると以前の値を保持します。" +msgid "" +"sysfs 挂载保留创建时捕获的网络空间,后续 lookup、readdir、read 和 write 均使用该视图。任务执行 " +"``setns()``、``unshare()`` 或传递挂载句柄后,已有挂载继续观察原网络。``fsopen(\"sysfs\")`` 的网络与" +" owner 捕获及 CREATE 授权见 :doc:`abi`。" +msgstr "" +"sysfs マウントは作成時に取得したネットワーク名前空間を保持し、その後の lookup、readdir、read、write " +"はこのビューを使用します。タスクが ``setns()`` や ``unshare()`` " +"を実行した後、またはマウントハンドルを受け渡した後も、既存のマウントは元のネットワークを参照します。``fsopen(\"sysfs\")`` " +"によるネットワークと owner の取得、および CREATE の認可は :doc:`abi` を参照してください。" -msgid "UDP 的 ``IP_TOS`` 默认 0,保存输入低八位并写入实际 IPv4 首部,包含 DSCP 和 ECN 位。TOS 变化同时按 Linux 的 TOS 映射更新 socket 优先级。``IP_FREEBIND`` 默认关闭,开启后允许绑定尚未配置的 IPv4 地址及 IPv4 映射地址。端口冲突、设备绑定、特权端口授权和创建网络范围仍按原规则检查,发送继续要求有效路由。" -msgstr "UDP の ``IP_TOS`` は初期値 0 で、入力の下位 8 ビットを DSCP と ECN を含め実際の IPv4 ヘッダーに設定します。TOS の変更時には Linux の TOS マッピングで socket 優先度も更新します。``IP_FREEBIND`` は初期状態で無効で、有効にすると未設定の IPv4 アドレスと IPv4 mapped アドレスに bind できます。ポート競合、デバイス bind、特権ポート権限、作成ネットワークの検査を維持し、送信には有効な経路が必要です。" +msgid "" +"``/sys/class/net/`` 是指向 canonical 设备节点的符号链接。loopback 位于 " +"``/sys/devices/virtual/net/lo``,物理接口位于对应 PCI function 下的 " +"``net/``,``device`` 链接指向 PCI 父节点,``subsystem`` 链接指向 " +"``/sys/class/net``。属性包含 " +"``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier``" +" 和 ``uevent``。物理接口仅在初始网络中可见。接口移除后,持有的旧 inode 在重新打开、读取或写入时返回 ``ENOENT``。" +msgstr "" +"``/sys/class/net/`` は canonical デバイスノードへのシンボリックリンクです。loopback は " +"``/sys/devices/virtual/net/lo`` に配置されます。物理インターフェースは対応する PCI function 配下の " +"``net/`` に配置され、``device`` は PCI 親ノードを、``subsystem`` は " +"``/sys/class/net`` を指します。属性には " +"``ifindex``、``iflink``、``address``、``broadcast``、``type``、``mtu``、``flags``、``operstate``、``carrier``、``uevent``" +" が含まれます。物理インターフェースは初期ネットワークでのみ可視です。インターフェース削除後、保持済みの旧 inode " +"を再度開く操作、読み取り、書き込みは ``ENOENT`` を返します。" + +#, python-format +msgid "" +"``RTM_SETLINK`` 与 ``RTM_NEWLINK`` 在提供正接口索引和 ``IFLA_IFNAME`` 时执行重命名,索引为 0 " +"时按名称选择已有接口。``SIOCSIFNAME`` 使用相同的创建网络与 ``CAP_NET_ADMIN`` 授权。重命名保留接口索引和 UP " +"状态,更新 ioctl、socket 设备绑定查询及 sysfs 名称,并发布同网络的 ``RTM_NEWLINK`` 与携带 " +"``DEVPATH_OLD`` 的 ``move`` 事件。名称最长 15 字节,空白、斜线、冒号、``.`` 和 ``..`` 返回 " +"``EINVAL``,同网络名称冲突返回 ``EEXIST``。单个 ``%d`` 模板选择 0 至 32767 " +"内首个空闲编号,同名请求不发布事件。``name_assign_type`` 对枚举物理名称报告 1,重命名后报告 4。" +msgstr "" +"``RTM_SETLINK`` と ``RTM_NEWLINK`` は、正のインターフェース索引と ``IFLA_IFNAME`` " +"が指定された場合に名前を変更します。索引 0 は名前で既存のインターフェースを選択します。``SIOCSIFNAME`` " +"も作成時ネットワークの範囲と ``CAP_NET_ADMIN`` による認可を使います。名前変更では索引と UP " +"状態を保持し、ioctl、socket のデバイス束縛照会、sysfs の名前を更新します。同じネットワークに ``RTM_NEWLINK`` と" +" ``DEVPATH_OLD`` を含む ``move`` イベントを配信します。名前は最大 15 " +"バイトです。空白、スラッシュ、コロン、``.``、``..`` は ``EINVAL``、同じネットワーク内の名前衝突は ``EEXIST`` " +"を返します。単一の ``%d`` テンプレートは 0 から 32767 " +"までの最初の空き番号を選びます。同名への要求はイベントを配信しません。``name_assign_type`` は列挙された物理名で " +"1、名前変更後は 4 を返します。" -msgid "UDP 的 ``SO_TIMESTAMP_OLD`` 和 ``SO_TIMESTAMP_NEW`` 返回 realtime 微秒时间戳,支持原生 IPv4、IPv6 和 IPv4 映射报文。启用时在入队采样,接收前才启用则在首次接收时采样。``MSG_PEEK`` 和切换时间戳格式保留已有样本,关闭选项后停止交付时间戳。时间戳通过 ``SOL_SOCKET`` 辅助消息返回,可与 IP packet info 和 TTL 同时使用。输出内存准备失败保留队列,控制区不足设置 ``MSG_CTRUNC``。" -msgstr "UDP の ``SO_TIMESTAMP_OLD`` と ``SO_TIMESTAMP_NEW`` は native IPv4、IPv6、IPv4 mapped データグラムに realtime のマイクロ秒時刻を返します。有効時はキュー追加時に採取し、到着後に有効にすると最初の受信時に採取します。``MSG_PEEK`` と時刻形式の変更で同じ標本を保持し、無効にすると時刻の出力を停止します。``SOL_SOCKET`` 補助メッセージで IP packet info や TTL と共に返します。出力メモリーの準備失敗ではキューを保持し、制御領域不足では ``MSG_CTRUNC`` を設定します。" +msgid "" +"网络 ``uevent`` 文件由 root 所有,模式为 0644,写入遵循常规 DAC 与挂载只读策略。只读挂载也阻止 root " +"写入。读取提供 ``INTERFACE`` 和 ``IFINDEX``。写入接受 " +"``add``、``remove``、``change``、``move``、``online``、``offline``、``bind`` 或 " +"``unbind``,可在一个空格后附加 36 字符的十六进制 UUID,连字符位于标准位置,末尾可带一个换行。无 UUID 时事件使用 " +"``SYNTH_UUID=0``,提供 UUID 时按输入传递。无效 action、UUID 或 embedded NUL 返回 " +"``EINVAL``,并保持事件队列不变。" +msgstr "" +"ネットワークの ``uevent`` ファイルは root 所有で、モードは 0644 です。書き込みには通常の DAC " +"とマウントの読み取り専用ポリシーが適用されます。読み取り専用マウントは root による書き込みも拒否します。読み取りは " +"``INTERFACE`` と ``IFINDEX`` を提供します。書き込みは " +"``add``、``remove``、``change``、``move``、``online``、``offline``、``bind``、``unbind``" +" を受け付け、任意でスペース 1 個と、標準位置にハイフンを持つ 36 文字の 16 進 UUID を続けられます。末尾の改行 1 " +"個も許可されます。UUID がないイベントは ``SYNTH_UUID=0`` を使用し、指定された UUID は入力どおりに渡されます。不正な " +"action、UUID、埋め込み NUL は ``EINVAL`` を返し、イベントキューを維持します。" -msgid "UDP 的 ``IP_UNICAST_IF`` 和 ``IPV6_UNICAST_IF`` 分别保存 IPv4 和 IPv6 的默认单播出口。设置与查询均使用网络字节序的 32 位接口索引,设置长度必须恰好为 4 字节。0 清除配置,非零索引必须存在于 socket 创建网络中,否则返回 ``EADDRNOTAVAIL``。已有设备绑定时设置非零索引返回 ``EINVAL``。普通用户可设置这些选项,接收筛选继续使用原有设备绑定。消息级接口、显式 scope 和设备绑定优先于默认单播出口;IPv4 映射发送使用 IPv4 配置。" -msgstr "UDP の ``IP_UNICAST_IF`` と ``IPV6_UNICAST_IF`` は、IPv4 と IPv6 のデフォルトのユニキャスト送信インターフェースを個別に保持します。設定と取得にはネットワークバイト順の 32 ビットインターフェース索引を使用し、設定値の長さは正確に 4 バイトである必要があります。0 は設定を解除します。非ゼロの索引はソケット作成時のネットワークに存在する必要があり、存在しない場合は ``EADDRNOTAVAIL`` を返します。デバイスにバインド済みのソケットへの非ゼロ索引の設定は ``EINVAL`` を返します。一般ユーザーも設定でき、受信の選別には既存のデバイスバインドを引き続き使用します。メッセージ単位のインターフェース、明示的な scope、デバイスバインドは、デフォルトのユニキャスト送信先より優先されます。IPv4 マップ送信は IPv4 の設定を使用します。" +msgid "" +"``NETLINK_KOBJECT_UEVENT`` 的网络设备事件按订阅 socket 的创建网络筛选。物理接口注册和移除分别发布 " +"``add`` 和 ``remove``,移除事件保留注册时的设备身份。sysfs 合成事件使用挂载捕获的网络,事件携带 " +"action、设备路径、``SUBSYSTEM=net``、``INTERFACE`` 和 ``IFINDEX``,合成事件还携带 " +"``SYNTH_UUID``。其他网络的订阅者不会收到该网络事件,任务随后切换网络也保留已有 socket 的订阅范围。" +msgstr "" +"``NETLINK_KOBJECT_UEVENT`` " +"のネットワークデバイスイベントは、購読ソケット作成時のネットワークに基づいて選別されます。物理インターフェースの登録と削除は、それぞれ " +"``add`` と ``remove`` を発行します。削除イベントは登録時に取得したデバイス識別情報を保持します。sysfs " +"の合成イベントはマウントが取得したネットワークを使用します。イベントは " +"action、デバイスパス、``SUBSYSTEM=net``、``INTERFACE``、``IFINDEX`` を含み、合成イベントはさらに " +"``SYNTH_UUID`` " +"を含みます。他のネットワークの購読者にはそのネットワークイベントは届きません。タスクが後でネットワークを切り替えても、既存ソケットの購読範囲を維持します。" -msgid "UDP 扩展错误队列" -msgstr "UDP 拡張エラーキュー" +msgid "" +"block、PCI 和 DRM 已公开的设备 ``uevent`` 控制同样接受上述 action 与可选 UUID,权限和即时写入语义见 " +":doc:`abi`。事件属性取自同一设备的当前真实 inventory,``SUBSYSTEM`` 取自该设备的 ``subsystem`` " +"链接,并附带 ``SYNTH_UUID``。这些 global 设备事件仅投递给初始 user namespace " +"所拥有的网络空间中的订阅者,包含永久初始网络。网络设备事件继续严格按 socket 创建网络与挂载捕获网络隔离。" +msgstr "" +"block、PCI、DRM デバイスが公開する ``uevent`` 制御も、上記の action と任意の UUID " +"を受け付けます。権限と即時書き込みの意味論は :doc:`abi` を参照してください。イベント属性は同じデバイスの現在の実際の " +"inventory から取得します。``SUBSYSTEM`` はそのデバイスの ``subsystem`` " +"リンクから取得し、``SYNTH_UUID`` を付加します。これらの global デバイスイベントは、永続的な初期ネットワークを含む、初期 " +"user namespace " +"が所有するネットワーク名前空間内の購読者にのみ配送されます。ネットワークデバイスイベントは、ソケット作成時のネットワークとマウントが取得したネットワークによる厳密な隔離を維持します。" -msgid "``IP_RECVERR`` 和 ``IPV6_RECVERR`` 默认关闭。启用后,经过校验的 IPv4 ICMP 或 ICMPv6 错误按 socket 创建网络、接口及原始 UDP 地址和端口关联到独立错误队列。记录保存 ``sock_extended_err`` 的 errno、origin、type、code 和 MTU,以及错误发送者、原始目的地址和被引用的 UDP 载荷。IPv4 映射 socket 返回原生 IPv6 地址布局。" -msgstr "``IP_RECVERR`` と ``IPV6_RECVERR`` はデフォルトで無効です。有効にすると、検証済みの IPv4 ICMP または ICMPv6 エラーを、ソケット作成時のネットワーク、インターフェース、元の UDP アドレスとポートに基づいて独立したエラーキューに関連付けます。各記録は ``sock_extended_err`` の errno、origin、type、code、MTU と、エラー送信元、元の宛先、引用された UDP ペイロードを保持します。IPv4 マップソケットはネイティブ IPv6 のアドレスレイアウトを返します。" +msgid "范围与标准" +msgstr "範囲と標準" -msgid "``recvmsg(MSG_ERRQUEUE)`` 通过 ``msg_name`` 返回原始目的地址,通过 ``SOL_IP/IP_RECVERR`` 或 ``SOL_IPV6/IPV6_RECVERR`` 辅助消息返回扩展错误及其发送者,并设置输出 ``MSG_ERRQUEUE``。队列为空时立即返回 ``EAGAIN``,设置 ``MSG_PEEK`` 仍消费该条错误。载荷和控制区不足分别报告 ``MSG_TRUNC`` 和 ``MSG_CTRUNC``。用户输出内存准备失败保留记录,成功读取后按下一条错误更新待处理 errno。" -msgstr "``recvmsg(MSG_ERRQUEUE)`` は元の宛先を ``msg_name`` に、拡張エラーとその送信元を ``SOL_IP/IP_RECVERR`` または ``SOL_IPV6/IPV6_RECVERR`` の補助メッセージに返し、出力に ``MSG_ERRQUEUE`` を設定します。キューが空の場合は直ちに ``EAGAIN`` を返します。``MSG_PEEK`` を指定してもエラー記録を消費します。ペイロードと制御領域の容量不足は、それぞれ ``MSG_TRUNC`` と ``MSG_CTRUNC`` で通知します。ユーザー出力メモリの準備に失敗した場合は記録を保持します。読み取りが成功すると、次のエラーに基づいて保留中の errno を更新します。" +msgid "" +"这是 IPv6 主机实现,不提供 IPv6 路由转发、IPsec、MLDv2 源特定组播过滤或 Redirect 路由更新。DNS " +"策略、RDNSS 和 DHCPv6 客户端属于用户态。接收和发送 缓存有资源上限,资源不足返回错误;并不宣称覆盖 Linux 的全部网络功能或全部" +" IPv6 扩展。" +msgstr "" +"これは IPv6 ホスト実装であり、IPv6 のルーティング転送、IPsec、MLDv2 " +"の送信元固有マルチキャストフィルタリング、Redirect による経路更新は提供しません。DNS 方針、RDNSS、DHCPv6 " +"クライアントはユーザー空間の担当です。送受信バッファーにはリソース上限があり、不足時はエラーを返します。Linux の全ネットワーク機能や " +"IPv6 の全拡張への対応は表明しません。" -msgid "错误记录与普通数据报分别持有存储,待处理 errno 或错误队列可触发 ``POLLERR``。查询 ``SO_ERROR`` 清除待处理 errno,已排队记录继续可读。关闭相应 RECVERR 选项会清空错误队列,保留普通数据和待处理 errno。分配失败或队列达到上限时保留已有记录并继续报告 socket 错误。最后关闭释放全部记录及创建网络引用。" -msgstr "エラー記録と通常のデータグラムは、それぞれ独立した記憶領域を所有します。保留中の errno またはエラーキューにより ``POLLERR`` が発生します。``SO_ERROR`` の取得は保留中の errno をクリアし、キュー内の記録は引き続き読み取れます。対応する RECVERR オプションを無効にするとエラーキューを空にし、通常のデータと保留中の errno は保持します。メモリ割り当ての失敗やキュー上限到達時は既存の記録を保持し、ソケットエラーの通知を継続します。最後のクローズですべての記録と作成時のネットワーク参照を解放します。" +msgid "" +"依据 RFC 8200、4291、4443、4861、4862、8201、3493、3542 以及 Linux " +"``ipv6(7)``、``rtnetlink(7)``。POSIX 规定应用接口,线上 IPv6 协议细节由 相应 IETF " +"标准规定。宿主定向测试与完整系统 VM 测试是不同证据;VMware 和 真实硬件结果不能由 QEMU 结果替代。" +msgstr "" +"RFC 8200、4291、4443、4861、4862、8201、3493、3542、および Linux の " +"``ipv6(7)``、``rtnetlink(7)`` に基づきます。POSIX はアプリケーションインターフェースを定め、通信上の IPv6 " +"プロトコル詳細は対応する IETF 標準が定めます。ホストの対象別テストとシステム全体の VM テストは異なる証拠であり、QEMU の結果で " +"VMware や物理ハードウェアの結果を代用することはできません。" diff --git a/Documentation/process/e1000e-plan.rst b/Documentation/process/e1000e-plan.rst index 6cad86ae..3a73edba 100644 --- a/Documentation/process/e1000e-plan.rst +++ b/Documentation/process/e1000e-plan.rst @@ -7,7 +7,7 @@ e1000e 实现与验证计划 为 Intel 82574L/82574IT(8086:10d3)和 82583V(8086:150c)提供独立的 原生 PCIe 以太网驱动。沿用现有单 eth0 网络服务、Linux socket/ioctl ABI -及原生模块 owner 管理,不修改 BusyBox 或公开 ABI。其他 e1000e 家族设备 +及原生模块 owner 管理,沿用公开 Linux 网络 ABI。其他 e1000e 家族设备 不在本次设备表中。默认内置,允许配置为 e1000e.ko。 实现采用本项目 Apache-2.0 源码,依据 Intel 寄存器手册;不复制 Linux GPL diff --git a/Documentation/process/testing.rst b/Documentation/process/testing.rst index dbd911e2..db9d71a7 100644 --- a/Documentation/process/testing.rst +++ b/Documentation/process/testing.rst @@ -60,7 +60,7 @@ PID 1 将结果写入串口并等待。编译示例:: 出现 PASS 后仍需检查没有 FAIL 或 panic,不能只以启动完成代替 syscall 验证。 ``seccomp_bpf`` 套件以 ASan/UBSan 直接运行生产用经典 BPF 验证器和解释器。 -``tools/tests/seccomp_probe.c`` 可用静态 x86-64 musl 工具链编译,在测试系统 +``tools/tests/seccomp_probe.c`` 可用静态 x86-64 glibc 工具链编译,在测试系统 中以普通进程运行(不可直接作为 PID 1),退出成功时打印 ``SECCOMP_ABI_PASS``。 在 Linux 上不带参数运行,在 ReliefNT 上添加 ``--reliefnt`` 测试原生旧入口和 未支持扩展。来宾串口证据应包含实际在线 CPU 数、探针结果及 guest 退出状态。 diff --git a/Documentation/userspace-api/inotify.rst b/Documentation/userspace-api/inotify.rst index 4e726ee1..243cea2d 100644 --- a/Documentation/userspace-api/inotify.rst +++ b/Documentation/userspace-api/inotify.rst @@ -4,7 +4,7 @@ inotify 是 Linux 文件事件接口,不属于 POSIX。应用通过 libc 的 ```` 调用;内核的 ```` 由 -``headers_install`` 导出,不需要修改 BusyBox 或 musl。 +``headers_install`` 提供给标准 Linux 用户态。 接口与使用 ========== diff --git a/Documentation/userspace-api/ipv6.rst b/Documentation/userspace-api/ipv6.rst index 5d0738a8..53106e04 100644 --- a/Documentation/userspace-api/ipv6.rst +++ b/Documentation/userspace-api/ipv6.rst @@ -25,7 +25,7 @@ RFC 4862 的两小时有效期保护。处理 IPv6 校验和、扩展首部、 IPv6 socket 默认允许 IPv4 映射地址;应用可在绑定前使用 ``IPV6_V6ONLY`` 限制为 IPv6。``IPV6_RECVPKTINFO`` 和 ``IPV6_RECVHOPLIMIT`` 提供接收接口、 -目标地址和 hop limit,便于实现标准协议客户端。保留 BusyBox 使用的旧版 +目标地址和 hop limit,便于实现标准协议客户端。保留 Linux 客户端使用的兼容 hop-limit 辅助数据及 raw ICMPv6 checksum/filter 选项。未知选项返回错误, 不能将未实现功能报告为设置成功。 diff --git a/block/Kbuild b/block/Kbuild index 214ba55f..6c5db9b5 100644 --- a/block/Kbuild +++ b/block/Kbuild @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 # Objects are owned by this directory; child modules own their own lists. -obj-y := core/ device/ install/ partition/ ramdisk/ +obj-y := core/ device/ install/ partition/ include $(srctree)/scripts/Makefile.module diff --git a/block/core/storage_block.c b/block/core/storage_block.c index f4836bac..8bee0f89 100644 --- a/block/core/storage_block.c +++ b/block/core/storage_block.c @@ -336,8 +336,6 @@ int storage_read_iso_blocks(uint64_t lba,uint32_t block_count,void *buffer) int storage_write_sectors(uint64_t lba, uint32_t sector_count, const void *buffer) { const uint8_t *src = (const uint8_t *)buffer; - /* RAM-backed installer roots are a writable live environment. Changes - * affect the in-memory FAT image only and disappear when it reboots. */ /* From this point the caller may have changed filesystem metadata. Do * not return EAGAIN and replay a partially completed mutation. */ storage_begin_mutation(); @@ -479,8 +477,7 @@ int gpt_find_esp(void) basic_data_candidate_found = 1; basic_data_candidate_lba = entry->first_lba; } - canonical_name = storage_gpt_name_matches(entry->name, "RELIEFOS_ROOT") || - storage_gpt_name_matches(entry->name, "LEONOS4_ROOT"); + canonical_name = storage_gpt_name_matches(entry->name, "RELIEFOS_ROOT"); signature_ret = storage_probe_exfat_signature(entry->first_lba); is_exfat = signature_ret > 0; if (!fat32_candidate_found && storage_probe_fat32_signature(entry->first_lba) > 0) { diff --git a/block/core/storage_state_data.c b/block/core/storage_state_data.c index 0bd2579e..737eeaac 100644 --- a/block/core/storage_state_data.c +++ b/block/core/storage_state_data.c @@ -90,7 +90,6 @@ struct install_disk_state *g_install_disks=initial_disks; uint32_t g_install_disk_capacity=STORAGE_INSTALL_DISK_INITIAL_CAPACITY; uint32_t g_install_disk_count; uint8_t g_devfs_enabled = 1; -uint8_t g_installer_root_active; struct kernel_spinlock storage_transport_lock = KERNEL_SPINLOCK_INIT; diff --git a/block/core/storage_types.h b/block/core/storage_types.h index 00fa07c6..84e8ead1 100644 --- a/block/core/storage_types.h +++ b/block/core/storage_types.h @@ -249,7 +249,6 @@ extern struct install_disk_state *g_install_disks; extern uint32_t g_install_disk_capacity; extern uint32_t g_install_disk_count; extern uint8_t g_devfs_enabled; -extern uint8_t g_installer_root_active; /* AHCI uses shared command RAM and IDE PIO owns channel registers while an * operation is in flight. NVMe has a queue per controller, but it shares a diff --git a/block/partition/disk_io.c b/block/partition/disk_io.c index 3921e64e..d3ecf1ba 100644 --- a/block/partition/disk_io.c +++ b/block/partition/disk_io.c @@ -633,7 +633,7 @@ static int storage_disk_block_reread_owned(uint32_t disk_id) ret=swap_storage_raw_busy(&swap_ref,0,1,true);block_device_put(&swap_ref); if (ret) return ret<0 ? ret : -EBUSY; #endif - if ((disk->boot_root && !storage_installer_root_active()) || + if (disk->boot_root || storage_disk_has_data_mount(disk_id)) { return -16; } diff --git a/block/partition/partition_gpt.c b/block/partition/partition_gpt.c index b848ba57..d0f5f4f2 100644 --- a/block/partition/partition_gpt.c +++ b/block/partition/partition_gpt.c @@ -346,7 +346,7 @@ int disk_partition_mutable(const struct install_disk_state *disk) if (rc) return rc<0 ? rc : -EBUSY; } #endif - return disk->boot_root && !storage_installer_root_active() ? -16 : 0; + return disk->boot_root ? -16 : 0; } /** diff --git a/block/ramdisk/Kbuild b/block/ramdisk/Kbuild deleted file mode 100644 index 67162d9e..00000000 --- a/block/ramdisk/Kbuild +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -obj-y := boot.o -include $(srctree)/scripts/Makefile.module diff --git a/block/ramdisk/boot.c b/block/ramdisk/boot.c deleted file mode 100644 index 5f25f2dc..00000000 --- a/block/ramdisk/boot.c +++ /dev/null @@ -1,186 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 */ -#include -#include -#include -#include -#include - -enum { BOOT_IMAGE_ROOT, BOOT_IMAGE_PAYLOAD, BOOT_IMAGE_COUNT }; - -struct boot_image { - uint8_t *bytes; - uint64_t physical; - uint64_t source_length; - uint64_t length; - bool read_only; -}; - -struct boot_image_slot { - struct boot_image image; - struct block_device_registration registration; - bool registered; -}; - -static struct boot_image_slot boot_slots[BOOT_IMAGE_COUNT]; - -static bool boot_overlap(uint64_t start,uint64_t end,uint64_t other_start,uint64_t other_end) -{ return startUINT64_MAX-511u || physical>UINT64_MAX-length || - (slot==BOOT_IMAGE_ROOT && length%512u))return -ENOEXEC; - const struct boot_image_slot *entry=&boot_slots[slot]; - if(entry->registered && (entry->image.physical!=physical || entry->image.source_length!=length)) - return -EBUSY; - const struct boot_image_slot *other=&boot_slots[slot ^ 1u]; - if(other->registered && boot_overlap(physical,physical+length,other->image.physical, - other->image.physical+other->image.source_length))return -ENOEXEC; - return entry->registered || (paging_kernel_direct_map_range(physical,length) && - paging_kernel_direct_map(physical)) ? 0 : -EINVAL; -} - -/** @brief Validate one request against a sector-padded boot image. */ -static int boot_extent(const struct boot_image *image,uint64_t first,uint32_t count,const void *buffer) -{ - uint64_t blocks=image->length/512u; - return !buffer || !count || first>=blocks || count>blocks-first ? -EINVAL : 0; -} - -/** @brief Read module bytes and zero-fill the last partial device sector. */ -static int boot_read(void *context,uint64_t first,uint32_t count,void *buffer) -{ - struct boot_image *image=context; - int rc=boot_extent(image,first,count,buffer); - if(rc)return rc; - uint64_t offset=first*512u; - size_t length=(size_t)count*512u; - if(offsetsource_length) { - size_t available=(size_t)(image->source_length-offset); - size_t copy=availablebytes+offset,copy); - if(copyread_only)return -EROFS; - uint64_t offset=first*512u; - size_t length=(size_t)count*512u; - if(offset>image->source_length || length>image->source_length-offset)return -EINVAL; - __builtin_memcpy(image->bytes+offset,buffer,length); - return 0; -} - -/** @brief Publish one reserved Multiboot image as a Linux RAM block device. - * @param slot Fixed standard ramN slot. @param physical Reserved source address. - * @param length Exact module byte count. @param device Receives the dev_t. - * @return Zero or negative validation/registration errno. Exclusive early boot; - * backing remains reserved, no full-image allocation or copy is performed. - */ -static int block_boot_image_bind_slot(unsigned slot,uint64_t physical,uint64_t length,uint64_t *device) -{ - if(!device || slot>=BOOT_IMAGE_COUNT)return -EINVAL; - *device=0; - int rc=boot_validate_slot(slot,physical,length); - if(rc)return rc; - uint64_t padded=(length+511u)&~UINT64_C(511); - struct boot_image_slot *entry=&boot_slots[slot]; - if(entry->registered) { - *device=entry->registration.info.device; - return 0; - } - uint8_t *mapping=paging_kernel_direct_map(physical); - - static const struct block_device_operations root_ops={.read=boot_read,.write=boot_write}; - static const struct block_device_operations payload_ops={.read=boot_read}; - bool read_only=slot==BOOT_IMAGE_PAYLOAD; - entry->image=(struct boot_image){ - .bytes=mapping,.physical=physical,.source_length=length,.length=padded,.read_only=read_only - }; - entry->registration=(struct block_device_registration){ - .info={ - .device=block_device_make_number(1u,slot),.blocks=padded/512u,.block_size=512u, - .max_blocks=128u,.flags=BLOCK_DEVICE_WRITE_THROUGH|(read_only?BLOCK_DEVICE_READ_ONLY:0), - .transport=BLOCK_TRANSPORT_MEMORY,.controller=(uint16_t)slot - }, - .operations=read_only?&payload_ops:&root_ops,.context=&entry->image - }; - const char *model=read_only ? "Multiboot installer payload" : "Multiboot installer root"; - size_t model_size=__builtin_strlen(model)+1u; - __builtin_memcpy(entry->registration.info.model,model,model_size); - rc=register_block_device(&entry->registration); - if(rc) { - *entry=(struct boot_image_slot){0}; - return rc; - } - entry->registered=true; - *device=entry->registration.info.device; - return 0; -} - -/** @brief Bind the writable installer-root image to standard /dev/ram0. */ -int block_boot_image_bind(uint64_t physical,uint64_t length,uint64_t *device) -{ return block_boot_image_bind_slot(BOOT_IMAGE_ROOT,physical,length,device); } - -static bool boot_root_name(const char *name) -{ return name && (!__builtin_strcmp(name,"reliefos-installer-root") || - !__builtin_strcmp(name,"leonos-installer-root")); } - -/** @brief Register unique installer-root and optional SquashFS Multiboot modules. - * @param boot Borrowed decoded handoff, NULL means no source. - * @param device Receives ram0 when a root module is present, otherwise zero. - * @return Number of bound modules or negative validation/registration errno. - * Duplicate names, empty ranges and over-limit module lists fail closed. - */ -int block_boot_image_register(const struct boot_info *boot,uint64_t *device) -{ - if(!device)return -EINVAL; - *device=0; - if(!boot)return 0; - if(boot->module_count>sizeof(boot->modules)/sizeof(boot->modules[0]))return -EINVAL; - const struct boot_module *selected[BOOT_IMAGE_COUNT]={0}; - for(uint32_t i=0;imodule_count;++i) { - const struct boot_module *module=&boot->modules[i]; - unsigned slot; - if(boot_root_name(module->name))slot=BOOT_IMAGE_ROOT; - else if(module->name && !__builtin_strcmp(module->name,"reliefos-installer-payload")) - slot=BOOT_IMAGE_PAYLOAD; - else continue; - if(selected[slot])return -EEXIST; - if(module->end<=module->start)return -ENOEXEC; - selected[slot]=module; - } - for(unsigned slot=0;slotstart,module->end-module->start); - if(rc)return rc; - for(uint32_t i=0;imodule_count;++i) { - const struct boot_module *other=&boot->modules[i]; - if(other!=module && other->startend && - boot_overlap(module->start,module->end,other->start,other->end))return -ENOEXEC; - } - } - unsigned count=0; - uint64_t root_device=0; - for(unsigned slot=0;slotstart, - selected[slot]->end-selected[slot]->start,&image_device); - if(rc)return rc; - if(slot==BOOT_IMAGE_ROOT)root_device=image_device; - ++count; - } - *device=root_device; - return (int)count; -} diff --git a/configs/toolchains/llvm-x86_64.mk b/configs/toolchains/llvm-x86_64.mk index 0c83e5c0..fc73ca42 100644 --- a/configs/toolchains/llvm-x86_64.mk +++ b/configs/toolchains/llvm-x86_64.mk @@ -7,9 +7,9 @@ TOOLCHAIN_NAME := llvm-x86_64 # The kernel and the boot loader link at fixed addresses with -# ld.lld; userland targets x86_64-linux-musl against the project sysroot. +# ld.lld; userland targets x86_64-linux-gnu inside the isolated Arch root. TRIPLE_KERNEL := x86_64-unknown-none -TRIPLE_USER := x86_64-linux-musl +TRIPLE_USER := x86_64-linux-gnu TOOLCHAIN_CC := clang TOOLCHAIN_CXX := clang++ diff --git a/drivers/video/framebuffer/fbdev.c b/drivers/video/framebuffer/fbdev.c index f7dee229..acc9c0fc 100644 --- a/drivers/video/framebuffer/fbdev.c +++ b/drivers/video/framebuffer/fbdev.c @@ -31,7 +31,7 @@ bool framebuffer_fbdev_get_fix_info(const struct framebuffer *fb, ? FB_VISUAL_TRUECOLOR : FB_VISUAL_PSEUDOCOLOR, .line_length = fb->pitch, }; - __builtin_memcpy(info->id, "leonos-fb", sizeof("leonos-fb")); + __builtin_memcpy(info->id, "reliefos-fb", sizeof("reliefos-fb")); return true; } diff --git a/fs/proc/procfs.c b/fs/proc/procfs.c index e555ff16..f7cbff3a 100644 --- a/fs/proc/procfs.c +++ b/fs/proc/procfs.c @@ -243,9 +243,9 @@ static int proc_userns_key(const char *name, struct task **target) */ void proc_task_identity_fields(const struct task *task, struct text_stream *stream) { - text_string(stream, "LeonOSRole:\t"); + text_string(stream, "ReliefOSRole:\t"); text_unsigned(stream, task->role); - text_string(stream, "\nLeonOSFlags:\t"); + text_string(stream, "\nReliefOSFlags:\t"); text_unsigned(stream, task->flags); text_string(stream, "\n"); } @@ -1112,7 +1112,7 @@ int proc_lookup(const char *path, struct storage_node *out) if (proc_memory_is_file(path) || proc_mount_view(path,NULL) || proc_text_eq(path, PROCFS_BOOT_ID) || proc_text_eq(path, PROCFS_UUID) || proc_text_eq(path,"/proc/cpuinfo") || - proc_text_eq(path,"/proc/leonos-drivers")) { + proc_text_eq(path,"/proc/reliefos-drivers")) { if (out) *out = (struct storage_node){ .type = RELIEFOS_FS_TYPE_FILE, .flags = STORAGE_NODE_FLAG_PROC, .first_cluster = 0x50524f43u, .size = 0, @@ -1283,7 +1283,7 @@ int proc_read(const char *path, uint64_t offset, void *buffer, uint32_t length, } /* Read-only, versioned driver records from the actual driver manager; * no user pointer reaches driver_manager_list. */ - if (proc_text_eq(path, "/proc/leonos-drivers")) { + if (proc_text_eq(path, "/proc/reliefos-drivers")) { struct reliefos_driver_info drivers[RELIEFOS_DRIVER_MAX]; struct reliefos_driver_list query = {.drivers = drivers, .capacity = RELIEFOS_DRIVER_MAX}; int ret = driver_manager_list(&query); @@ -1464,7 +1464,7 @@ int proc_readdir(const char *path, uint64_t *offset, struct reliefos_dir_entry * "self", "sys", "cpuinfo", - "leonos-drivers", + "reliefos-drivers", "cmdline", "asound", "loadavg", diff --git a/fs/sysfs/sysfs.c b/fs/sysfs/sysfs.c index 4ef59d6d..d0d483be 100644 --- a/fs/sysfs/sysfs.c +++ b/fs/sysfs/sysfs.c @@ -245,7 +245,7 @@ static int sys_blocks(sys_visit visit, void *ctx) char directory[RELIEFOS_FS_PATH_LEN]; sys_path(directory,prefix,-1,"/"); sys_path(diskpath,directory,-1,diskname+5); - } else sys_path(diskpath, "/sys/devices/platform/leonos-block/", -1, diskname + 5); + } else sys_path(diskpath, "/sys/devices/platform/reliefos-block/", -1, diskname + 5); for (int32_t part = -1; part < (int32_t)RELIEFOS_DISK_MAX_PARTITIONS; ++part) { uint64_t start = 0, sectors = info.blocks * (info.block_size / 512u); if (part >= 0) { @@ -424,7 +424,7 @@ static int sys_walk(struct net_namespace *ns, sys_visit visit, void *ctx) "/sys/class/block", "/sys/devices", "/sys/devices/platform", - "/sys/devices/platform/leonos-block", + "/sys/devices/platform/reliefos-block", "/sys/devices/system", "/sys/devices/system/cpu", "/sys/devices/virtual", diff --git a/fs/vfs/internal.h b/fs/vfs/internal.h index 7aee28a2..bb75c091 100644 --- a/fs/vfs/internal.h +++ b/fs/vfs/internal.h @@ -31,12 +31,6 @@ void storage_format_u32(char *out, uint32_t cap, const char *prefix, */ const char *storage_root_filesystem_name(void); -/** - * @brief Report whether the current runtime root is the installer RAM image. - * @return True for an active reserved installer root, false for disk/absent root. - * Execution-owned observation only; retains no pointer or module reference. - */ -bool storage_installer_root_active(void); diff --git a/fs/vfs/mount.c b/fs/vfs/mount.c index c5a5781b..dac470c7 100644 --- a/fs/vfs/mount.c +++ b/fs/vfs/mount.c @@ -1,7 +1,6 @@ #include "../../block/core/storage_internal.h" #include #include -#include /** @brief Retire unpublished discovery instances before a boot-only reset. * @return None. BSP boot setup only, before namespace/inode users; no callback @@ -303,7 +302,7 @@ void storage_boot_reset(void) storage_boot_drop_instances(); storage_memzero(g_volumes,sizeof(g_volumes)); storage_disk_block_cache_reset();storage_refresh_disks(); - g_devfs_enabled=1;g_installer_root_active=0; + g_devfs_enabled=1; storage_io_async_context=false;storage_io_write_started=false; g_active_volume=&g_volumes[0];storage_cache_invalidate(); } @@ -360,179 +359,13 @@ bool storage_try_direct_root(const struct boot_info *boot) } /** - * @brief Look up a named Multiboot module and return its byte range. - * @param boot Parsed boot information; may be NULL. - * @param name Exact module name to find. - * @param out_start Output start address when the module is present. - * @param out_length Output length in bytes when the module is present. - * @return True when a module with that name and a non-empty range was found. + * @brief Probe the physical root when neither initramfs nor direct root is selected. + * @param boot Decoded Multiboot handoff, or NULL to use the default discovery. */ -static bool boot_find_module_range(const struct boot_info *boot, const char *name, - uint64_t *out_start, uint64_t *out_length) +void storage_mount_boot_root(const struct boot_info *boot) { - if (!boot) { - return false; - } - for (uint32_t i = 0; - i < boot->module_count && i < sizeof(boot->modules) / sizeof(boot->modules[0]); - ++i) { - const struct boot_module *module = &boot->modules[i]; - if (storage_text_eq(module->name, name) && module->end > module->start) { - *out_start = module->start; - *out_length = module->end - module->start; - return true; - } - } - return false; -} - -/** - * @brief Mount the root filesystem for this boot. - * @param boot Parsed Multiboot modules and kernel command line. - * @param ramdisk_root True for an installer or live session, whose root is the - * `reliefos-installer-root` module rather than a mounted partition; - * the legacy `leonos-installer-root` tag remains accepted. - * - * The physical disks are always probed first: an installer needs the disk and - * partition inventory even though its own root comes from RAM. When the RAM - * image cannot be mounted the volume table is cleared, so no stale disk root - * is presented to userland; the caller then retries through - * storage_init_installer_root(), which reports the reason. - */ -void storage_mount_boot_root(const struct boot_info *boot, bool ramdisk_root) -{ - uint64_t start = 0; - uint64_t length = 0; - storage_boot_root_configure(!ramdisk_root && boot ? boot->cmdline : NULL); + storage_boot_root_configure(boot ? boot->cmdline : NULL); storage_init(); - if (!ramdisk_root) { - const char *root_fs = g_volumes[STORAGE_VOLUME_ROOT].filesystem == STORAGE_FILESYSTEM_EXT4 - ? "ext4" - : storage_root_filesystem_name(); - console_info("[reliefnt] storage boot root from probed disks root=%s fs=%s\n", - root_fs, root_fs); - return; - } - if (!boot_find_module_range(boot, "reliefos-installer-root", &start, &length) && - !boot_find_module_range(boot, "leonos-installer-root", &start, &length)) { - /* storage_init() probes a physical root before the installer module is - * selected. Do not leave that disk mounted as / when the RAM root is - * absent: an installer would then operate on its own boot media and - * may present a partially valid system instead of failing closed. */ - storage_destroy_volume(&g_volumes[STORAGE_VOLUME_ROOT]); - storage_memzero(&g_volumes[STORAGE_VOLUME_ROOT], - sizeof(g_volumes[STORAGE_VOLUME_ROOT])); - storage_destroy_volume(&g_volumes[STORAGE_VOLUME_BOOT]); - storage_memzero(&g_volumes[STORAGE_VOLUME_BOOT], - sizeof(g_volumes[STORAGE_VOLUME_BOOT])); - g_active_volume = &g_volumes[STORAGE_VOLUME_ROOT]; - g_installer_root_active = 0; - storage_cache_invalidate(); - console_warn("[reliefnt] storage boot root has no installer module; physical root cleared\n"); - return; - } - if (storage_mount_ramdisk_root(start, length) < 0) { - storage_boot_drop_instances(); - storage_memzero(g_volumes, sizeof(g_volumes)); - g_active_volume = &g_volumes[0]; - console_warn("[reliefnt] storage installer ramdisk root not mounted bytes=%llu\n", - (unsigned long long)length); - return; - } - /* Installer mode owns / and later reuses the boot slot for the selected - * target ESP at /target/boot. */ - storage_destroy_volume(&g_volumes[STORAGE_VOLUME_BOOT]); - storage_memzero(&g_volumes[STORAGE_VOLUME_BOOT], sizeof(g_volumes[STORAGE_VOLUME_BOOT])); - g_active_volume = &g_volumes[STORAGE_VOLUME_ROOT]; - console_info("[reliefnt] storage boot root from installer ramdisk root=/\n"); -} - -/** @brief Mount the reserved installer image through the shared block registry. - * @param image_phys Reserved physical source, never a CPU or DMA pointer. - * @param len Sector-aligned reserved source length, retained through shutdown. - * @return Zero or source/geometry/allocation/provider errno. BSP exclusive setup - * before namespace users; a failed selection clears the unpublished root. - * Registration borrows the existing direct map without copying the image. All - * filesystem I/O then uses the same owned block path as a physical disk; writes - * change only session memory. No graph/registry lock spans native parsing. - */ -int storage_mount_ramdisk_root(uint64_t image_phys, uint64_t len) -{ - struct storage_volume *root=&g_volumes[STORAGE_VOLUME_ROOT]; - storage_destroy_volume(root);*root=(struct storage_volume){0}; - g_active_volume=root;g_installer_root_active=0;storage_cache_invalidate(); - uint64_t device;int rc=block_boot_image_bind(image_phys,len,&device);if(rc)return rc; - rc=storage_refresh_disks();if(rc)return rc; - uint32_t disk=0; - while(disk=4096) { - uint8_t sector[512];struct block_device_ref ref={0}; - rc=block_device_get(device,&ref); - if(!rc)rc=block_device_read(&ref,2,1,sector); - block_device_put(&ref);if(rc)return rc; - if(sector[56]==0x53 && sector[57]==0xef) { - uint32_t features[3]; - storage_memcpy(features, sector + 92, sizeof(features)); - enum storage_ext_format format = storage_ext_detect_format(features[0], features[1], features[2]); - filesystem = format == STORAGE_EXT_FORMAT_EXT3 ? "ext3" : - format == STORAGE_EXT_FORMAT_EXT2 ? "ext2" : "ext4"; - } - } - rc=storage_mount_whole_filesystem(root,disk,filesystem); - if(rc){*root=(struct storage_volume){0};return rc;} - for(uint32_t i=0;imodule_count; ++i) { - const struct boot_module *mod = &boot->modules[i]; - if (storage_text_eq(mod->name, "reliefos-installer-root") || - storage_text_eq(mod->name, "leonos-installer-root")) { - found = true; - if (mod->end > mod->start) { - mount_ret = storage_mount_ramdisk_root(mod->start, - mod->end - mod->start); - if (mount_ret == 0) { - return; - } - } else { - mount_ret = -22; - } - console_error("[reliefnt] installer root ramdisk module mount failed ret=%d bytes=%llu\n", - mount_ret, - (unsigned long long)(mod->end > mod->start - ? mod->end - mod->start : 0)); - return; - } - } - } - if (!found) { - console_warn("[reliefnt] installer root ramdisk module not found; ensure GRUB had enough RAM to load /install/root.fat\n"); - } + console_info("[reliefnt] storage boot root from probed disks fs=%s\n", + storage_root_filesystem_name()); } diff --git a/fs/vfs/storage_status.c b/fs/vfs/storage_status.c index b603b1ea..263b6c55 100644 --- a/fs/vfs/storage_status.c +++ b/fs/vfs/storage_status.c @@ -79,13 +79,3 @@ const char *storage_root_filesystem_name(void) return "none"; } } - -/** - * @brief Report whether the current runtime root is the installer RAM image. - * @return True for an active reserved installer root, false for disk/absent root. - * Execution-owned observation only; retains no pointer or module reference. - */ -bool storage_installer_root_active(void) -{ - return g_installer_root_active != 0; -} diff --git a/include/reliefnt/boot_block.h b/include/reliefnt/boot_block.h deleted file mode 100644 index c123e214..00000000 --- a/include/reliefnt/boot_block.h +++ /dev/null @@ -1,27 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 */ -#ifndef RELIEFNT_BOOT_BLOCK_H -#define RELIEFNT_BOOT_BLOCK_H -#include -struct boot_info; -/** @brief Bind a reserved boot-image physical extent to the permanent RAM device. - * @param physical Physical source start, never a CPU pointer; mm already reserved it. - * @param length Sector-aligned source extent, retained through kernel shutdown. - * @param device Required Linux dev_t output, zero on failure. - * @return Zero or EINVAL/ENOEXEC/EBUSY/registration errno. Identical rebinding is - * idempotent; another extent cannot replace live backing. BSP exclusive boot - * setup before storage users, after direct-map initialization. Only registry - * metadata is allocated; payload is never copied. Subsequent writes are coherent - * ephemeral memory writes, never writes to the ISO/disk from which GRUB loaded it. - */ -int block_boot_image_bind(uint64_t physical,uint64_t length,uint64_t *device); -/** @brief Register installer root and optional compressed payload boot modules. - * @param boot Borrowed decoded handoff, NULL means no source. - * @param device Required output for ram0, zero when no root module is present. - * @return Number of registered/already-bound images, zero absent, or a negative - * validation/registration errno. Root aliases map to writable /dev/ram0; - * reliefos-installer-payload maps to read-only /dev/ram1. The initramfs module - * is never interpreted as a block image. Duplicate named modules fail closed. - * BSP exclusive boot setup after memory reservation; no payload copy occurs. - */ -int block_boot_image_register(const struct boot_info *boot,uint64_t *device); -#endif diff --git a/include/reliefnt/elf.h b/include/reliefnt/elf.h index 53d5da2d..eafe0607 100644 --- a/include/reliefnt/elf.h +++ b/include/reliefnt/elf.h @@ -1,6 +1,6 @@ /* * ReliefOS ELF loader interface: declares executable image validation/loading. - * Describes legacy static images and dynamic PIE startup metadata. + * Describes static images, PIE and dynamic interpreter startup metadata. */ #ifndef RELIEFNT_ELF_H #define RELIEFNT_ELF_H @@ -12,6 +12,12 @@ struct address_space; struct vfs_path; struct task; +/** Linux auxiliary-vector inputs and entropy for one executable image. */ +struct reliefos_dynamic_launch { + uint64_t main_base, main_entry, main_phdr, interp_base, interp_entry; + unsigned char random[16]; +}; + struct elf_image_info { bool valid; bool dynamic; /* ET_DYN: needs a load bias; PT_INTERP is independent. */ @@ -25,7 +31,6 @@ struct elf_image_info { uint64_t program_data_size; /* Main ELF data interval used by brk(2). */ uint64_t phdr_vaddr; uint64_t interpreter_entry; - uint32_t abi_major; char interp[RELIEFOS_FS_PATH_LEN]; }; diff --git a/include/reliefnt/storage.h b/include/reliefnt/storage.h index 7a9b7baa..d26af264 100644 --- a/include/reliefnt/storage.h +++ b/include/reliefnt/storage.h @@ -421,27 +421,10 @@ void storage_release_task_io(uint32_t pid); */ void storage_drain_task_io(uint32_t pid); /** - * @brief Mount the installer's root filesystem from boot info. - * @param boot Parsed Multiboot module list; may be NULL. - * @return Nothing. Missing or invalid module data is logged and leaves the - * root volume cleared. - * @context Boot setup before storage syscalls are available. The selected - * module remains reserved for the mounted volume's lifetime. - */ -void storage_init_installer_root(const struct boot_info *boot); -/** - * @brief Mount the root filesystem for this boot. - * @param boot Parsed Multiboot modules and kernel command line; the installer - * RAM disk is located by module name within it. - * @param ramdisk_root True for an installer or live session, whose root is the - * `reliefos-installer-root` module (or its legacy tag) - * instead of a partition. - * @return Nothing. A failed RAM-root mount leaves no root ready; the caller - * retries through storage_init_installer_root() to report why. - * @context Boot phase, before any task can issue storage syscalls. Probes and - * writes disks through the storage subsystem's own locking. - */ -void storage_mount_boot_root(const struct boot_info *boot, bool ramdisk_root); + * @brief Probe the physical root using the kernel boot selector. + * @param boot Decoded Multiboot handoff, or NULL for default discovery. + */ +void storage_mount_boot_root(const struct boot_info *boot); /** @brief Attempt the explicitly named plain ext4 root before loading initramfs. * @param boot Borrowed handoff with a root=PARTUUID selector. @@ -460,21 +443,6 @@ bool storage_ready(void); * @return Stable lowercase filesystem name, or "none" before a root mounts. */ const char *storage_root_filesystem_name(void); -/** - * @brief Report whether the current runtime root is the installer RAM image. - * @return True for an active reserved installer root, false for disk/absent root. - * Execution-owned observation only; retains no pointer or module reference. - */ -bool storage_installer_root_active(void); -/** @brief Mount a reserved boot-module image through the standard RAM block device. - * @param image_phys Reserved physical start; mapped only by the boot transport. - * @param len Sector-aligned bytes, held through shutdown. - * @return Zero or source/geometry/allocation/provider errno; failure clears the - * unpublished root. BSP exclusive setup, before namespace users. The transport - * borrows the direct map, never copies the whole image, and writes only session - * memory. Filesystem/device ownership survives until final native retirement. - */ -int storage_mount_ramdisk_root(uint64_t image_phys, uint64_t len); /** * @brief Read len bytes of node from offset into buf, reporting bytes read in out_read. */ diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index a9fea313..7c1fd58e 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/include/reliefos/elf_abi.h b/include/reliefos/elf_abi.h deleted file mode 100644 index 5d9c4685..00000000 --- a/include/reliefos/elf_abi.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef RELIEFOS_ELF_ABI_H -#define RELIEFOS_ELF_ABI_H - -/* Historical private ABI identification used to diagnose old binaries. - * Current musl executables use the Linux initial stack and do not require - * this note. The old loader/runtime are no longer distributed. */ -#define RELIEFOS_ELF_NOTE_NAME "LeonOS" -#define RELIEFOS_ELF_NOTE_TYPE 0x4c4f5341u /* "LOSA" */ -#define RELIEFOS_ELF_ABI_MAJOR 1u -#define RELIEFOS_ELF_ABI_MINOR 0u - -#include - -#define RELIEFOS_ELF_INTERP_PATH RELIEFOS_PATH_OLD_NATIVE_INTERP -#define RELIEFOS_MUSL_INTERP_PATH RELIEFOS_PATH_MUSL_INTERP -#define RELIEFOS_GLIBC_INTERP_PATH RELIEFOS_PATH_GLIBC_INTERP -#define RELIEFOS_ELF_RUNTIME_SONAME "libleonos.so.1" -#define RELIEFOS_ELF_RUNTIME_PATH RELIEFOS_PATH_LIBRELIEFOS_COMPAT - -struct reliefos_elf_abi_note { - unsigned int major; - unsigned int minor; -}; - -/* Passed by the kernel to ld-reliefos in r8. The normal ReliefOS argc/argv/envp - * register ABI remains unchanged in rdi/rsi/rdx. */ -struct reliefos_dynamic_launch { - unsigned long long main_base; - unsigned long long main_entry; - unsigned long long main_phdr; - unsigned long long interp_base; - unsigned long long interp_entry; - unsigned int abi_major; - unsigned int reserved; - unsigned char random[16]; - char main_path[260]; -}; - -#endif diff --git a/include/reliefos/layout.h b/include/reliefos/layout.h index bbc9d402..3316068d 100644 --- a/include/reliefos/layout.h +++ b/include/reliefos/layout.h @@ -1,117 +1,17 @@ +/* SPDX-License-Identifier: Apache-2.0 */ #ifndef RELIEFOS_LAYOUT_H #define RELIEFOS_LAYOUT_H #include -/* - * ReliefOS guest root filesystem layout contract. - * - * The installed root follows the Alpine Linux FHS shape: /bin, /sbin, /lib, - * /usr/bin, /usr/sbin and /usr/lib are real directories. There is no - * usr-merge and no /lib64. Standard runtime links include: - * - * /var/run -> ../run - * /var/lock -> ../run/lock - * - * The musl ELF PT_INTERP contract is unchanged: executables request - * "/lib/ld-musl-x86_64.so.1", and the real interpreter is stored at that - * path. Do not point ELF PT_INTERP at a glibc loader. - * - * ReliefOS-owned files live below explicitly named subdirectories: - * - * /etc/reliefos persistent configuration - * /var/lib/reliefos persistent mutable state - * /var/cache/reliefos cache data - * /run/reliefos volatile per-boot IPC and session state - * /usr/lib/reliefos private libraries and interpreter payload - * /usr/lib/reliefos/apps application packages (manifest + ELF) - * /usr/lib/reliefos/tests diagnostic guest probes - * /usr/share/reliefos desktop resources - * /usr/share/fonts/reliefos ReliefOS UI fonts - * /usr/share/doc/reliefos bundled help and vendor notices - * - * tools/reliefos_layout.py is the build-side mirror of this header. Keep the - * two files synchronized and do not add competing path literal tables. - */ - -/* Directories (no trailing slash so they concatenate with "/name"). */ -#define RELIEFOS_LAYOUT_BIN "/bin" -#define RELIEFOS_LAYOUT_SBIN "/sbin" -#define RELIEFOS_LAYOUT_LIB "/lib" -#define RELIEFOS_LAYOUT_BOOT "/boot" -#define RELIEFOS_LAYOUT_SRV "/srv" -#define RELIEFOS_LAYOUT_USR_BIN "/usr/bin" -#define RELIEFOS_LAYOUT_USR_SBIN "/usr/sbin" -#define RELIEFOS_LAYOUT_USR_LIB "/usr/lib" -#define RELIEFOS_LAYOUT_USR_SHARE "/usr/share" -#define RELIEFOS_LAYOUT_ETC_RELIEFOS "/etc/reliefos" -#define RELIEFOS_LAYOUT_ETC_SSL_CERTS "/etc/ssl/certs" +/* Paths consumed by kernel-side configuration and diagnostics. */ #define RELIEFOS_LAYOUT_VAR_LIB_RELIEFOS "/var/lib/reliefos" -#define RELIEFOS_LAYOUT_VAR_CACHE_RELIEFOS "/var/cache/reliefos" -#define RELIEFOS_LAYOUT_VAR_LOG "/var/log" -#define RELIEFOS_LAYOUT_VAR_TMP "/var/tmp" -#define RELIEFOS_LAYOUT_RUN_RELIEFOS "/run/reliefos" -#define RELIEFOS_LAYOUT_RELIEFOS_LIB "/usr/lib/reliefos" #define RELIEFOS_LAYOUT_RELIEFOS_APPS "/usr/lib/reliefos/apps" -#define RELIEFOS_LAYOUT_RELIEFOS_TESTS "/usr/lib/reliefos/tests" -#define RELIEFOS_LAYOUT_RELIEFOS_SHARE "/usr/share/reliefos" -#define RELIEFOS_LAYOUT_RELIEFOS_RESOURCES "/usr/share/reliefos/resources" -#define RELIEFOS_LAYOUT_RELIEFOS_FONTS "/usr/share/fonts/reliefos" -#define RELIEFOS_LAYOUT_RELIEFOS_DOC "/usr/share/doc/reliefos" -#define RELIEFOS_LAYOUT_LICENSES "/usr/share/licenses" -#define RELIEFOS_LAYOUT_MISC "/usr/share/misc" -#define RELIEFOS_LAYOUT_TERMINFO "/usr/share/terminfo" -#define RELIEFOS_LAYOUT_LOCALE "/usr/share/locale" - -/* Third-party suites retained under /opt with /usr/bin command entries. */ -#define RELIEFOS_LAYOUT_OPT_DYNE "/opt/dyne" -#define RELIEFOS_LAYOUT_OPT_PYTHON "/opt/python" - -/* Runtime configuration. */ -#define RELIEFOS_PATH_RELIEFOS_CONF RELIEFOS_LAYOUT_ETC_RELIEFOS "/leonos.conf" -#define RELIEFOS_PATH_DISPLAY_CONF RELIEFOS_LAYOUT_ETC_RELIEFOS "/display.conf" -#define RELIEFOS_PATH_NETWORK_CONF RELIEFOS_LAYOUT_ETC_RELIEFOS "/network.conf" -#define RELIEFOS_PATH_NETWORK_BAK RELIEFOS_LAYOUT_ETC_RELIEFOS "/network.conf.bak" -#define RELIEFOS_PATH_NETWORK_TMP RELIEFOS_LAYOUT_ETC_RELIEFOS "/network.conf.tmp" -#define RELIEFOS_PATH_LOCALE_CONF RELIEFOS_LAYOUT_ETC_RELIEFOS "/locale.conf" -#define RELIEFOS_PATH_ENVIRONMENT_CONF RELIEFOS_LAYOUT_ETC_RELIEFOS "/environment.conf" -#define RELIEFOS_PATH_FILEASSOC_CFG RELIEFOS_LAYOUT_ETC_RELIEFOS "/fileassoc.cfg" -#define RELIEFOS_PATH_LESSKEY RELIEFOS_LAYOUT_ETC_RELIEFOS "/lesskey" - -/* Persistent and volatile state. */ -#define RELIEFOS_PATH_USERS_DB RELIEFOS_LAYOUT_VAR_LIB_RELIEFOS "/users.db" -#define RELIEFOS_PATH_ACCOUNTS_DB RELIEFOS_LAYOUT_VAR_LIB_RELIEFOS "/accounts.db" #define RELIEFOS_PATH_STARTUP_DB RELIEFOS_LAYOUT_VAR_LIB_RELIEFOS "/startup.db" #define RELIEFOS_PATH_STARTUP_DENIALS_DB RELIEFOS_LAYOUT_VAR_LIB_RELIEFOS "/startup-denials.db" #define RELIEFOS_PATH_OOBE_DONE RELIEFOS_LAYOUT_VAR_LIB_RELIEFOS "/oobe.done" -#define RELIEFOS_PATH_LICENSE RELIEFOS_LAYOUT_VAR_LIB_RELIEFOS "/license.dat" -#define RELIEFOS_PATH_SESSION_USER RELIEFOS_LAYOUT_RUN_RELIEFOS "/session-user" - -/* Shared resources. */ -#define RELIEFOS_PATH_CACERT RELIEFOS_LAYOUT_ETC_SSL_CERTS "/ca-certificates.crt" -#define RELIEFOS_PATH_MAGIC RELIEFOS_LAYOUT_MISC "/magic.mgc" -#define RELIEFOS_PATH_SYSTEM_FONT RELIEFOS_LAYOUT_RELIEFOS_FONTS "/system.psf" -#define RELIEFOS_PATH_BROWSER_FONT RELIEFOS_LAYOUT_RELIEFOS_FONTS "/times-new-roman.ttf" -#define RELIEFOS_PATH_BROWSER_CJK_FONT RELIEFOS_LAYOUT_RELIEFOS_FONTS "/simsun.ttc" -#define RELIEFOS_PATH_LOGO_PNG RELIEFOS_LAYOUT_RELIEFOS_RESOURCES "/logo.png" -#define RELIEFOS_PATH_MINESWEEPER_MINE_BMP RELIEFOS_LAYOUT_RELIEFOS_RESOURCES "/minesweeper-mine.bmp" -#define RELIEFOS_PATH_MINESWEEPER_FLAG_BMP RELIEFOS_LAYOUT_RELIEFOS_RESOURCES "/minesweeper-flag.bmp" -#define RELIEFOS_PATH_HELP RELIEFOS_LAYOUT_RELIEFOS_DOC "/leonos.hlp" - -/* Shared libraries and interpreter payload. */ -#define RELIEFOS_PATH_MUSL_INTERP "/lib/ld-musl-x86_64.so.1" -#define RELIEFOS_PATH_LIBC RELIEFOS_LAYOUT_LIB "/libc.so" -#define RELIEFOS_PATH_LIBMIMALLOC RELIEFOS_LAYOUT_LIB "/libmimalloc.so.3" -/* Diagnostic-only probe constant. ReliefOS does not ship or claim a glibc - * loader; the musl interpreter above is the only supported PT_INTERP. */ -#define RELIEFOS_PATH_GLIBC_INTERP "/lib64/ld-linux-x86-64.so.2" -#define RELIEFOS_PATH_LIBRELIEFOS RELIEFOS_LAYOUT_RELIEFOS_LIB "/libreliefos.so.2" -#define RELIEFOS_PATH_LIBRELIEFOS_COMPAT RELIEFOS_LAYOUT_RELIEFOS_LIB "/libleonos.so.1" -#define RELIEFOS_PATH_OLD_NATIVE_INTERP RELIEFOS_LAYOUT_RELIEFOS_LIB "/ld-leonos.elf" - -/* Runtime view of the boot partition; the ESP itself normally mounts /boot. */ -#define RELIEFOS_PATH_BOOT_KERNEL "/boot/reliefos/kernel.sys" -#define RELIEFOS_PATH_BOOT_KERNEL_LEGACY "/boot/leonos/kernel.sys" -#define RELIEFOS_PATH_BOOT_DISPLAY_CONF "/boot/reliefos/config/display.conf" +#define RELIEFOS_PATH_DISPLAY_CONF "/etc/reliefos/display.conf" +#define RELIEFOS_PATH_LOCALE_CONF "/etc/locale.conf" +#define RELIEFOS_PATH_SYSTEM_FONT "/usr/share/fonts/reliefos/system.psf" -#endif /* RELIEFOS_LAYOUT_H */ +#endif diff --git a/include/uapi/README.rst b/include/uapi/README.rst index 2a0300f0..8a0b9667 100644 --- a/include/uapi/README.rst +++ b/include/uapi/README.rst @@ -7,13 +7,11 @@ does not implement a call. Export only the headers_install whitelist. Private task state, pointers and helpers remain under include/reliefnt. Public structures, ioctl values, sizes and flags must match the implemented -wire contract. Never patch musl constants to conceal a divergent kernel. +wire contract. Never patch libc constants to conceal a divergent kernel. Declarations, host compilation and guest behavior are separate checks. -The musl runtime uses /lib/ld-musl-x86_64.so.1 and libreliefos.so.2. -libleonos.so.2 is a separately linked compatibility SONAME, not a symlink -substitute. Do not mix its FILE, errno, TLS or allocator objects with the -retired Picolibc runtime. Old private ABI binaries may need rebuilding. +The glibc runtime uses /lib64/ld-linux-x86-64.so.2 and libreliefos.so.2. +Applications use the native Linux ABI and the exported ReliefOS headers. UID/GID and Linux mode bits are independent of desktop roles. O_CREAT/mkdir mode zero means no permissions. Accounts use passwd/shadow/group/gshadow and diff --git a/include/uapi/reliefos/rootfs.h b/include/uapi/reliefos/rootfs.h index b74d8023..5d61abdc 100644 --- a/include/uapi/reliefos/rootfs.h +++ b/include/uapi/reliefos/rootfs.h @@ -1,121 +1,49 @@ +/* SPDX-License-Identifier: Apache-2.0 */ #ifndef RELIEFOS_ROOTFS_H #define RELIEFOS_ROOTFS_H -/* Canonical non-usr-merge rootfs skeleton, based on Alpine baselayout 3.7.2. - * Real directories have root:root ownership. These mount points do not imply - * that Linux sysfs/tmpfs/OpenRC facilities are implemented by ReliefOS. - * Keep the X(path, value) rows machine-readable for tools/reliefos_layout.py. +/* Base directories and aliases used by the Arch merged-usr installation. + * Ownership and installation of the base tree belong to the filesystem + * package. Runtime mounts and their contents belong to the system manager. */ #define RELIEFOS_ROOTFS_DIRECTORIES(X) \ - X("/bin", 0755) \ X("/boot", 0755) \ X("/dev", 0755) \ - X("/dev/pts", 0755) \ - X("/dev/shm", 01777) \ X("/etc", 0755) \ - X("/etc/apk", 0755) \ - X("/etc/apk/commit_hooks.d", 0755) \ - X("/etc/apk/keys", 0755) \ - X("/etc/apk/protected_paths.d", 0755) \ - X("/etc/apk/repositories.d", 0755) \ - X("/etc/crontabs", 0755) \ - X("/etc/reliefos", 0755) \ - X("/etc/modprobe.d", 0755) \ - X("/etc/modules-load.d", 0755) \ - X("/etc/network", 0755) \ - X("/etc/network/if-down.d", 0755) \ - X("/etc/network/if-post-down.d", 0755) \ - X("/etc/network/if-pre-up.d", 0755) \ - X("/etc/network/if-up.d", 0755) \ - X("/etc/opt", 0755) \ - X("/etc/periodic", 0755) \ - X("/etc/periodic/15min", 0755) \ - X("/etc/periodic/daily", 0755) \ - X("/etc/periodic/hourly", 0755) \ - X("/etc/periodic/monthly", 0755) \ - X("/etc/periodic/weekly", 0755) \ - X("/etc/profile.d", 0755) \ - X("/etc/ssl/certs", 0755) \ - X("/etc/sysctl.d", 0755) \ X("/home", 0755) \ - X("/lib", 0755) \ - X("/lib/apk", 0755) \ - X("/lib/apk/commit_hooks.d", 0755) \ - X("/lib/apk/db", 0755) \ - X("/lib/apk/exec", 0755) \ - X("/lib/apk/keys", 0755) \ - X("/lib/apk/repositories.d", 0755) \ - X("/lib/firmware", 0755) \ - X("/lib/modules-load.d", 0755) \ - X("/lib/sysctl.d", 0755) \ - X("/media", 0755) \ - X("/media/cdrom", 0755) \ - X("/media/floppy", 0755) \ - X("/media/usb", 0755) \ X("/mnt", 0755) \ X("/opt", 0755) \ - X("/proc", 0755) \ - X("/root", 0700) \ + X("/proc", 0555) \ + X("/root", 0750) \ X("/run", 0755) \ - X("/run/reliefos", 0755) \ - X("/run/lock", 0755) \ - X("/sbin", 0755) \ X("/srv", 0755) \ - X("/sys", 0755) \ + X("/sys", 0555) \ X("/tmp", 01777) \ X("/usr", 0755) \ X("/usr/bin", 0755) \ X("/usr/include", 0755) \ X("/usr/lib", 0755) \ - X("/usr/lib/leonos", 0755) /* old SONAME search path */ \ - X("/usr/lib/reliefos", 0755) \ - X("/usr/lib/reliefos/apps", 0755) \ - X("/usr/lib/reliefos/tests", 0755) \ - X("/usr/lib/modules-load.d", 0755) \ - X("/usr/lib/sysctl.d", 0755) \ + X("/usr/lib/modules", 0755) \ X("/usr/local", 0755) \ - X("/usr/local/bin", 0755) \ - X("/usr/local/include", 0755) \ - X("/usr/local/lib", 0755) \ - X("/usr/local/sbin", 0755) \ - X("/usr/local/share", 0755) \ - X("/usr/local/share/man", 0755) \ - X("/usr/sbin", 0755) \ X("/usr/share", 0755) \ - X("/usr/share/doc/reliefos", 0755) \ - X("/usr/share/fonts/reliefos", 0755) \ - X("/usr/share/reliefos", 0755) \ - X("/usr/share/reliefos/resources", 0755) \ - X("/usr/share/licenses", 0755) \ - X("/usr/share/man", 0755) \ - X("/usr/share/misc", 0755) \ - X("/usr/src", 0755) \ X("/var", 0755) \ X("/var/cache", 0755) \ - X("/var/cache/apk", 0755) \ - X("/var/cache/reliefos", 0755) \ - X("/var/cache/misc", 0755) \ - X("/var/empty", 0555) \ X("/var/lib", 0755) \ - X("/var/lib/reliefos", 0750) \ - X("/var/lib/misc", 0755) \ - X("/var/local", 0755) \ X("/var/log", 0755) \ - X("/var/mail", 0755) \ - X("/var/opt", 0755) \ - X("/var/spool", 0755) \ - X("/var/spool/cron", 0755) \ X("/var/tmp", 01777) #define RELIEFOS_ROOTFS_SYMLINKS(X) \ + X("/bin", "usr/bin") \ + X("/sbin", "usr/bin") \ + X("/usr/sbin", "bin") \ + X("/lib", "usr/lib") \ + X("/lib64", "usr/lib") \ + X("/usr/lib64", "lib") \ X("/var/run", "../run") \ X("/var/lock", "../run/lock") \ - X("/var/spool/mail", "../mail") \ - X("/var/spool/cron/crontabs", "../../../etc/crontabs") \ - X("/etc/mtab", "../proc/mounts") \ - X("/etc/ssl/cert.pem", "certs/ca-certificates.crt") \ - X("/etc/apk/ca.pem", "../ssl/certs/ca-certificates.crt") + X("/etc/mtab", "../proc/self/mounts") -#define RELIEFOS_DEFAULT_PATH "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +#define RELIEFOS_DEFAULT_PATH "/usr/local/sbin:/usr/local/bin:/usr/bin" +#define RELIEFOS_X86_64_GLIBC_INTERPRETER "/lib64/ld-linux-x86-64.so.2" #endif diff --git a/kernel/exec/elf.c b/kernel/exec/elf.c index ec94ea1b..c34c831c 100644 --- a/kernel/exec/elf.c +++ b/kernel/exec/elf.c @@ -2,7 +2,6 @@ * ReliefOS ELF loader: validates and maps static and dynamic x86_64 images. * Enforces ABI, W^X, PT_INTERP, segment-layout, and ASLR startup rules. */ -#include #include #include #include @@ -22,7 +21,6 @@ #define PT_LOAD 1 #define PT_DYNAMIC 2 #define PT_INTERP 3 -#define PT_NOTE 4 #define PT_PHDR 6 #define PF_X 1 #define PF_W 2 @@ -66,12 +64,6 @@ struct elf64_phdr { uint64_t p_align; }; -struct elf64_nhdr { - uint32_t n_namesz; - uint32_t n_descsz; - uint32_t n_type; -}; - static uint8_t elf_header_scratch[ELF_HEADER_READ_BYTES]; /** @@ -93,17 +85,6 @@ static uint64_t align_up(uint64_t value) return (value + PAGE_SIZE - 1ULL) & ~(PAGE_SIZE - 1ULL); } -/** - * @brief Round value up to a 4-byte boundary; returns 0 on overflow. - */ -static uint64_t align4_up(uint64_t value) -{ - if (value > UINT64_MAX - 3ULL) { - return 0; - } - return (value + 3ULL) & ~3ULL; -} - /** * @brief Return true if every program header fits within len bytes of the image. */ @@ -125,54 +106,6 @@ static const struct elf64_phdr *elf64_phdr_at(const struct elf64_ehdr *eh, (uint64_t)index * eh->e_phentsize); } -/** - * @brief Scan PT_NOTE segments for the ReliefOS ABI note; store its major version and return true only when it matches the kernel's ABI major. - */ -static bool elf64_note_abi(const struct elf64_ehdr *eh, const void *image, size_t len, - uint32_t *out_major) -{ - for (uint16_t i = 0; i < eh->e_phnum; ++i) { - const struct elf64_phdr *ph = elf64_phdr_at(eh, image, i); - uint64_t cursor; - uint64_t end; - if (ph->p_type != PT_NOTE || ph->p_offset > len || ph->p_filesz > len - ph->p_offset) { - continue; - } - cursor = ph->p_offset; - end = ph->p_offset + ph->p_filesz; - while (cursor + sizeof(struct elf64_nhdr) <= end) { - const struct elf64_nhdr *note = - (const struct elf64_nhdr *)((const uint8_t *)image + cursor); - uint64_t names = cursor + sizeof(*note); - uint64_t desc = align4_up(names + note->n_namesz); - uint64_t next = align4_up(desc + note->n_descsz); - if (!desc || !next || desc > end || next > end) { - return false; - } - if (note->n_type == RELIEFOS_ELF_NOTE_TYPE && - note->n_namesz == sizeof(RELIEFOS_ELF_NOTE_NAME) && - note->n_descsz >= sizeof(struct reliefos_elf_abi_note)) { - const char *name = (const char *)image + names; - const struct reliefos_elf_abi_note *abi = - (const struct reliefos_elf_abi_note *)((const uint8_t *)image + desc); - bool match = true; - for (uint32_t n = 0; n < sizeof(RELIEFOS_ELF_NOTE_NAME); ++n) { - if (name[n] != RELIEFOS_ELF_NOTE_NAME[n]) { - match = false; - break; - } - } - if (match) { - *out_major = abi->major; - return abi->major == RELIEFOS_ELF_ABI_MAJOR; - } - } - cursor = next; - } - } - return false; -} - /** * @brief Copy the PT_INTERP path string (if any) into out; returns false when absent or not NUL-terminated within the segment. */ @@ -201,7 +134,7 @@ static bool elf64_interp(const struct elf64_ehdr *eh, const void *image, size_t } /** - * @brief Read interpreter and ABI metadata independently of ET_EXEC/ET_DYN. + * @brief Read the standard Linux interpreter metadata independently of ET_EXEC/ET_DYN. */ static bool elf64_validate_dynamic_header(const struct elf64_ehdr *eh, const void *image, size_t len, bool is_interpreter, @@ -210,7 +143,6 @@ static bool elf64_validate_dynamic_header(const struct elf64_ehdr *eh, const voi bool dynamic = false; bool phdr = out->phdr_vaddr != 0; bool interp = false; - uint32_t abi_major = 0; for (uint16_t i = 0; i < eh->e_phnum; ++i) { const struct elf64_phdr *ph = elf64_phdr_at(eh, image, i); if (ph->p_type == PT_DYNAMIC) { @@ -222,7 +154,6 @@ static bool elf64_validate_dynamic_header(const struct elf64_ehdr *eh, const voi interp = true; } } - bool legacy = elf64_note_abi(eh, image, len, &abi_major); if ((!is_interpreter && !dynamic) || !phdr) { return false; } @@ -231,12 +162,6 @@ static bool elf64_validate_dynamic_header(const struct elf64_ehdr *eh, const voi if (!elf64_interp(eh, image, len, out->interp) || !out->interp[0]) { return false; } - if (legacy) { - const char *expected = RELIEFOS_ELF_INTERP_PATH; - for (uint32_t i = 0; expected[i] || out->interp[i]; ++i) { - if (expected[i] != out->interp[i]) return false; - } - } } /* An ET_DYN image without PT_INTERP is a static PIE: Linux maps it * directly with a load bias and starts at e_entry. Keep accepting @@ -245,7 +170,6 @@ static bool elf64_validate_dynamic_header(const struct elf64_ehdr *eh, const voi } else if (interp) { return false; } - out->abi_major = legacy ? abi_major : 0; return true; } @@ -866,8 +790,7 @@ int elf64_map_task_image(struct task *task, struct task *lookup_task, const stru if(ret)goto done; ret=elf64_read_headers(interp_source,&interp_image,&interp_len); if(ret){if(ret==-8)ret=-80;goto done;} - if(!elf64_probe_image(interp_image,interp_len,vfs_exec_source_node(interp_source)->size,true,&interp_info) || - interp_info.abi_major!=main_info.abi_major){ret=-80;goto done;} + if(!elf64_probe_image(interp_image,interp_len,vfs_exec_source_node(interp_source)->size,true,&interp_info)){ret=-80;goto done;} interp_bias=elf64_choose_bias(&interp_info,true); if(!interp_bias || interp_info.entry>UINT64_MAX-interp_bias){ret=-8;goto done;} ret=elf64_map_one(task,interp_source,interp_image,&interp_info,interp_bias,"interpreter"); @@ -877,10 +800,6 @@ int elf64_map_task_image(struct task *task, struct task *lookup_task, const stru task->dynamic_launch.main_phdr=main_info.phdr_vaddr; task->dynamic_launch.interp_base=interp_bias; task->dynamic_launch.interp_entry=interp_info.entry+interp_bias; - task->dynamic_launch.abi_major=main_info.abi_major; - for(uint32_t i=0;i+1dynamic_launch.main_path) && task->path[i];++i) { - task->dynamic_launch.main_path[i]=task->path[i];task->dynamic_launch.main_path[i+1]=0; - } main_info.interpreter_entry=interp_info.entry+interp_bias;*out=main_info; done: vfs_exec_source_put(interp_source); diff --git a/kernel/exec/userland.c b/kernel/exec/userland.c index 1ffb84f5..7d3a9e49 100644 --- a/kernel/exec/userland.c +++ b/kernel/exec/userland.c @@ -324,7 +324,7 @@ static int write_user_u64(const struct address_space *as, uint64_t vaddr, uint64 * @param execfn Original name for AT_EXECFN, or NULL to use the task path. * @param vdso_ehdr Mapped vDSO ELF header address, or zero when absent. * @return Zero or negative stack budget/mapping errno. Native ELF starts with - * no loader finalizer in RDX; the private interpreter still receives envp. + * no loader finalizer in RDX. * UID/GID auxv entries use the image's user namespace and overflow identity. * Secure-exec decisions retain the stored global identities. */ @@ -363,15 +363,10 @@ static int prepare_user_exec_stack(struct task *task, const char *execfn, uint64 AT_EXECFN = 31, AT_SYSINFO_EHDR = 33, }; - uint64_t launch_base = 0; if (!task) { return -22; } sp = task->stack_top; - if (task->dynamic_launch.abi_major) { - sp = (sp - sizeof(task->dynamic_launch)) & ~(EXEC_STACK_ALIGN - 1ULL); - launch_base = sp; - } argc = task->exec_argc ? task->exec_argc : 1; if (!execfn) execfn = task->path; path_len = __builtin_strlen(execfn); @@ -478,16 +473,6 @@ static int prepare_user_exec_stack(struct task *task, const char *execfn, uint64 } if (write_user_u64(sched_task_as(task), argc_base, argc) < 0) return -12; - if (launch_base) { - for (uint32_t i = 0; i < sizeof(task->dynamic_launch); ++i) { - uint8_t *dst = (uint8_t *)user_ptr_for_phys(sched_task_as(task), launch_base + i); - if (!dst) { - return -12; - } - *dst = ((const uint8_t *)&task->dynamic_launch)[i]; - } - } - struct task_address_space_state *mm=sched_task_mm(task); mm->arg_start=task->exec_argc? strings_base+(uint64_t)(task->exec_argv[0]-task->exec_data):execfn_base+path_len+1; mm->arg_end=task->exec_argc? strings_base+(uint64_t)(task->exec_argv[task->exec_argc-1]-task->exec_data)+ @@ -498,10 +483,9 @@ static int prepare_user_exec_stack(struct task *task, const char *execfn, uint64 task->frame.rsp = argc_base; task->frame.rdi = argc; task->frame.rsi = argv_base; - /* A native CRT registers a nonzero RDX as the loader's exit callback. - * Only the private interpreter ABI expects an environment pointer here. */ - task->frame.rdx = launch_base ? envp_base : 0; - task->frame.r8 = launch_base; + /* A native CRT treats RDX as the dynamic loader's optional finalizer. */ + task->frame.rdx = 0; + task->frame.r8 = 0; return 0; } diff --git a/kernel/init/kernel.c b/kernel/init/kernel.c index 8663ae56..8dc33c8a 100644 --- a/kernel/init/kernel.c +++ b/kernel/init/kernel.c @@ -21,7 +21,6 @@ #include #include #include "../../fs/initramfs/boot.h" -#include #include #include #include @@ -190,14 +189,12 @@ static int boot_capture_efi_acpi(struct boot_info *boot) static uint32_t boot_load_ui_theme(void) { static const char reliefos_path[] = "/reliefos/config/display.conf"; - static const char legacy_path[] = "/leonos/config/display.conf"; static const char win95[] = "theme=win95"; char data[4096]; size_t len = 0; const char *config; - if (efi_fs_read_file_into(reliefos_path, data, sizeof(data), &len) < 0 && - efi_fs_read_file_into(legacy_path, data, sizeof(data), &len) < 0) { + if (efi_fs_read_file_into(reliefos_path, data, sizeof(data), &len) < 0) { return 1u; } config = data; @@ -384,14 +381,6 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) int parameter_ret=module_parameters_boot(boot.cmdline); if(parameter_ret<0)console_error("[boot] builtin parameter error ret=%d\n",parameter_ret); } - { - uint64_t memory_device; - int memory_ret=block_boot_image_register(&boot,&memory_device); - if(memory_ret<0) { - console_fatal("[boot] reserved root image invalid ret=%d; boot stopped\n",memory_ret); - kernel_idle_loop(); - } - } { uint64_t block_flags; kernel_execution_lock_irqsave(&block_flags); @@ -404,8 +393,7 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) if(filesystem_ret<0) console_error("[boot] filesystem registration failed ret=%d\n",filesystem_ret); } - bool ramdisk_root = cmdline_has(&boot, "mode=installer") || cmdline_has(&boot, "mode=live"); - bool direct_root = !ramdisk_root && cmdline_has(&boot, "reliefos.direct_root=1") && + bool direct_root = cmdline_has(&boot, "reliefos.direct_root=1") && storage_try_direct_root(&boot); { int memory_root = direct_root ? 0 : storage_initramfs_boot(&boot); @@ -414,14 +402,9 @@ static void kernel_start(uint32_t magic, uintptr_t multiboot_info) kernel_idle_loop(); } console_info("[boot] selecting root source=%s modules=%u\n", - direct_root ? "direct ext4" : memory_root ? "initramfs" : - ramdisk_root ? "installer/live ramdisk" : "physical disk", + direct_root ? "direct ext4" : memory_root ? "initramfs" : "physical disk", boot.module_count); - if(!memory_root && !direct_root)storage_mount_boot_root(&boot, ramdisk_root); - if (!memory_root && ramdisk_root && !storage_ready()) { - console_warn("[reliefnt] installer ramdisk root not ready, retrying installer module\n"); - storage_init_installer_root(&boot); - } + if (!memory_root && !direct_root) storage_mount_boot_root(&boot); console_log(storage_ready() ? CONSOLE_LOG_INFO : CONSOLE_LOG_ERROR, "[boot] root_ready=%u filesystem=%s\n", (unsigned)storage_ready(), storage_root_filesystem_name()); diff --git a/kernel/module/lifecycle.c b/kernel/module/lifecycle.c index 945285cf..065c3142 100644 --- a/kernel/module/lifecycle.c +++ b/kernel/module/lifecycle.c @@ -221,7 +221,7 @@ int module_unload(const char *name,unsigned int flags) (void)name; (void)flags; return -ENOSYS; #else /* Linux 6.12 delete_module does not reject extra flag bits. In particular - * BusyBox rmmod sets O_EXCL. With forced unloading disabled all requests + * Userspace module tooling can supply O_EXCL. With forced unloading disabled all requests * still take exactly the ordinary reference/exit/drain checks below. */ (void)flags; uint64_t irq_flags; kernel_spin_lock_irqsave(&module_table_lock,&irq_flags); diff --git a/kernel/sched/signal.c b/kernel/sched/signal.c index ccf6ca91..ff415183 100644 --- a/kernel/sched/signal.c +++ b/kernel/sched/signal.c @@ -247,7 +247,8 @@ int sched_signal_user_process_target(struct task *leader, int signal_number, /* Ignore only when the addressed task has neither blocked nor waited for * this signal, matching Linux sig_ignored() and real_blocked semantics. */ if (!((leader->blocked_signals | leader->sigwait_mask) & bit) && - (action->handler == 1 || (!action->handler && kernel_signal_default_ignored(signal_number)))) + (action->handler == 1 || (!action->handler && + (tgid == 1 || kernel_signal_default_ignored(signal_number))))) return 0; if (signal_number == 9 || signal_number == 19) return info ? kernel_signal_queue_task_info(eligible ? eligible : live, signal_number, info) : diff --git a/kernel/signal/signal.c b/kernel/signal/signal.c index 820bd009..338fff64 100644 --- a/kernel/signal/signal.c +++ b/kernel/signal/signal.c @@ -24,7 +24,6 @@ #include #include #include -#include #include #ifdef CONFIG_SWAP /** @brief Cancel an interrupted fork's scalar-only private reclaim state. */ @@ -95,14 +94,9 @@ static void signal_context_restore(struct trap_frame *frame, static void signal_default_action(struct task *task, int sig) { if (!task || task->state == TASK_EXITED) return; - /* BusyBox reboot/poweroff follows the traditional init protocol and - * signals PID 1 after OpenRC has stopped its services. PID 1 is - * deliberately non-terminable in ReliefNT; translate those two power - * signals into the machine transition instead of attempting sched_exit. */ - if (task->pid == 1 && (sig == 15 || sig == 12)) { - if (sig == 15) power_reboot(); - power_shutdown(); - } + /* The global init process survives default signal actions. Caught + * signals and signals blocked for signalfd are handled before this point. */ + if (sched_task_tgid(task) == 1) return; switch (sig) { case 19: /* SIGSTOP */ case 20: /* SIGTSTP */ @@ -185,6 +179,10 @@ int kernel_signal_queue_task_info(struct task *task, int signal_number, if (signal_number >= 19 && signal_number <= 22) sched_signal_discard(task, 18); + if (sched_task_tgid(task) == 1 && action && !action->handler && + !((task->blocked_signals | task->sigwait_mask) & bit)) { + return 0; + } if (signal_number != 9 && signal_number != 19 && !((task->blocked_signals | task->sigwait_mask) & bit) && action && (action->handler == 1 || (!action->handler && kernel_signal_default_ignored(signal_number)))) { diff --git a/kernel/signal/signal_queue.c b/kernel/signal/signal_queue.c index 8f3b61ab..48c2286f 100644 --- a/kernel/signal/signal_queue.c +++ b/kernel/signal/signal_queue.c @@ -44,6 +44,7 @@ bool kernel_signal_default_ignored(int sig) int kernel_signal_fatal_pending(const struct task *task) { + if (sched_task_tgid(task) == 1) return 0; uint64_t pending = sched_task_pending(task) & ~task->blocked_signals; if (sched_task_pending(task) & (1ULL << 8)) return 9; /* Linux complete_signal starts group exit for default non-core signals. diff --git a/kernel/syscall/device/input_ioctl.c b/kernel/syscall/device/input_ioctl.c index fb701f24..6c5c66da 100644 --- a/kernel/syscall/device/input_ioctl.c +++ b/kernel/syscall/device/input_ioctl.c @@ -215,7 +215,7 @@ int task_evdev_ioctl(struct task_file *file, uint64_t request, const char *value; if (_IOC_NR(request) == 0x06) { value = device_kind == STORAGE_DEV_KIND_KEYBOARD - ? "LeonOS PS/2 Keyboard" : "LeonOS PS/2 Mouse"; + ? "ReliefOS PS/2 Keyboard" : "ReliefOS PS/2 Mouse"; } else if (_IOC_NR(request) == 0x07) { value = device_kind == STORAGE_DEV_KIND_KEYBOARD ? "platform/i8042/serio0" : "platform/i8042/serio1"; diff --git a/net/core.c b/net/core.c index c27e14a0..947114aa 100644 --- a/net/core.c +++ b/net/core.c @@ -45,7 +45,6 @@ static void net_log_config(const char *prefix) */ void net_init(void) { - net_load_dns_policy(); e1000_init(); net_ipv6_init(); net_set_static_fallback(); @@ -53,7 +52,7 @@ void net_init(void) console_info("[reliefnt] net unavailable: no active Ethernet link\n"); return; } - net_log_config("[reliefnt] interface ready; OpenRC DHCP client owns configuration"); + net_log_config("[reliefnt] interface ready for userspace network configuration"); } /** diff --git a/net/interface/config.c b/net/interface/config.c index 0958e40e..c3bf586a 100644 --- a/net/interface/config.c +++ b/net/interface/config.c @@ -1,48 +1,9 @@ -#include #include #include #include #include #include "../internal.h" -/** - * Net line value. - * @param line Value supplied by the caller. - * @param len Maximum number of elements available in the related buffer. - * @param key Value supplied by the caller. - * @param out_value Value supplied by the caller. - * @param out_len Value supplied by the caller. - * @return The value or status produced by the operation. - */ -static int net_line_value(const char *line, uint32_t len, const char *key, - const char **out_value, uint32_t *out_len); - -/** - * Net value eq. - * @param value Value supplied by the caller. - * @param len Maximum number of elements available in the related buffer. - * @param expected Value supplied by the caller. - * @return The value or status produced by the operation. - */ -static int net_value_eq(const char *value, uint32_t len, const char *expected); - -/** - * Net parse ipv4. - * @param text NUL-terminated text supplied by the caller. - * @param len Maximum number of elements available in the related buffer. - * @param out_ip Value supplied by the caller. - * @return The value or status produced by the operation. - */ -static int net_parse_ipv4(const char *text, uint32_t len, uint32_t *out_ip); - -/** - * @brief Parse bounded DNS policy through one retained namespace/open instance. - * @param path Absolute trusted configuration filename, required. - * @return Zero or minus one for lookup/type/read failure. Runs synchronously - * under execution ownership; no bare inode or pathname escapes the reader. - */ -static int net_load_dns_policy_file(const char *path); - /** * Net effective dns ip. * @param dhcp_dns_ip Value supplied by the caller. @@ -56,146 +17,6 @@ static uint32_t net_dns_mode = RELIEFOS_NET_DNS_MODE_DHCP; static uint32_t net_dns_custom_ip; static uint32_t net_dhcp_dns_ip; static uint64_t net_dhcp_acquired_ms; -/** - * Net line value. - * @param line Value supplied by the caller. - * @param len Maximum number of elements available in the related buffer. - * @param key Value supplied by the caller. - * @param out_value Value supplied by the caller. - * @param out_len Value supplied by the caller. - * @return The value or status produced by the operation. - */ -static int net_line_value(const char *line, uint32_t len, const char *key, - const char **out_value, uint32_t *out_len) -{ - uint32_t key_len = net_strlen(key, NET_NETWORK_CONFIG_MAX); - if (!line || !key || !out_value || !out_len || !key_len || len <= key_len || - line[key_len] != '=' || !net_text_eq_len(line, key, key_len)) { - return 0; - } - *out_value = line + key_len + 1u; - *out_len = len - key_len - 1u; - return 1; -} - -/** - * Net value eq. - * @param value Value supplied by the caller. - * @param len Maximum number of elements available in the related buffer. - * @param expected Value supplied by the caller. - * @return The value or status produced by the operation. - */ -static int net_value_eq(const char *value, uint32_t len, const char *expected) -{ - uint32_t index = 0; - while (expected && expected[index]) { - if (index >= len || value[index] != expected[index]) { - return 0; - } - ++index; - } - return index == len; -} - -/** - * Net parse ipv4. - * @param text NUL-terminated text supplied by the caller. - * @param len Maximum number of elements available in the related buffer. - * @param out_ip Value supplied by the caller. - * @return The value or status produced by the operation. - */ -static int net_parse_ipv4(const char *text, uint32_t len, uint32_t *out_ip) -{ - uint32_t ip = 0; - uint32_t pos = 0; - for (uint32_t octet = 0; octet < 4u; ++octet) { - uint32_t value = 0; - uint32_t digits = 0; - while (pos < len && text[pos] >= '0' && text[pos] <= '9') { - value = value * 10u + (uint32_t)(text[pos] - '0'); - if (value > 255u || ++digits > 3u) { - return 0; - } - ++pos; - } - if (!digits) { - return 0; - } - ip = (ip << 8) | value; - if (octet != 3u) { - if (pos >= len || text[pos++] != '.') { - return 0; - } - } - } - if (pos != len || ip == 0 || ip == 0xffffffffu) { - return 0; - } - *out_ip = ip; - return 1; -} - -/** - * @brief Parse bounded DNS policy through one retained namespace/open instance. - * @param path Absolute trusted configuration filename, required. - * @return Zero or minus one for lookup/type/read failure. Runs synchronously - * under execution ownership; no bare inode or pathname escapes the reader. - */ -static int net_load_dns_policy_file(const char *path) -{ - char cfg[NET_NETWORK_CONFIG_MAX]; - uint32_t got = 0; - uint32_t pos = 0; - - if (vfs_kernel_read(vfs_system_namespace(),path,0,cfg,sizeof(cfg)-1u,&got)<0) { - return -1; - } - cfg[got] = 0; - while (pos < got) { - const char *value; - uint32_t value_len; - uint32_t start = pos; - uint32_t line_len; - while (pos < got && cfg[pos] != '\n' && cfg[pos] != '\r') { - ++pos; - } - line_len = pos - start; - while (pos < got && (cfg[pos] == '\n' || cfg[pos] == '\r')) { - ++pos; - } - if (net_line_value(cfg + start, line_len, "dns_mode", &value, &value_len)) { - if (net_value_eq(value, value_len, "dhcp")) { - net_dns_mode = RELIEFOS_NET_DNS_MODE_DHCP; - } else if (net_value_eq(value, value_len, "custom")) { - net_dns_mode = RELIEFOS_NET_DNS_MODE_CUSTOM; - } else if (net_value_eq(value, value_len, "cloudflare")) { - net_dns_mode = RELIEFOS_NET_DNS_MODE_CLOUDFLARE; - } - } else if (net_line_value(cfg + start, line_len, "dns_custom", &value, &value_len)) { - uint32_t parsed_ip; - if (net_parse_ipv4(value, value_len, &parsed_ip)) { - net_dns_custom_ip = parsed_ip; - } - } - } - return 0; -} - -/** - * Net load dns policy. - */ -void net_load_dns_policy(void) -{ - net_dns_mode = RELIEFOS_NET_DNS_MODE_DHCP; - net_dns_custom_ip = 0; - if (net_load_dns_policy_file(NET_NETWORK_CONFIG_PATH) < 0) { - (void)net_load_dns_policy_file(NET_NETWORK_CONFIG_BACKUP_PATH); - } - if (net_dns_mode == RELIEFOS_NET_DNS_MODE_CUSTOM && !net_dns_custom_ip) { - net_dns_mode = RELIEFOS_NET_DNS_MODE_CLOUDFLARE; - } -} - /** * Net effective dns ip. * @param dhcp_dns_ip Value supplied by the caller. diff --git a/net/internal.h b/net/internal.h index b25c90e8..ac5219b1 100644 --- a/net/internal.h +++ b/net/internal.h @@ -81,9 +81,6 @@ #endif #define NET_SOCKET_CLOSE_HOLD_MS 10000u #define NET_SOCKET_DEFAULT_TIMEOUT_MS 5000u -#define NET_NETWORK_CONFIG_PATH RELIEFOS_PATH_NETWORK_CONF -#define NET_NETWORK_CONFIG_BACKUP_PATH RELIEFOS_PATH_NETWORK_BAK -#define NET_NETWORK_CONFIG_MAX 256u #define NET_NTP_UNIX_EPOCH_OFFSET 2208988800ULL struct net_arp_wait { @@ -513,11 +510,6 @@ int net_memeq(const uint8_t *a, const uint8_t *b, uint32_t len); */ int net_text_eq_len(const char *a, const char *b, uint32_t len); -/** - * Net load dns policy. - */ -void net_load_dns_policy(void); - /** * Net get u16. * @param p Value supplied by the caller. diff --git a/tools/host/manifest/reliefos-deps.c b/tools/host/manifest/reliefos-deps.c index 9b543fe4..abc32237 100644 --- a/tools/host/manifest/reliefos-deps.c +++ b/tools/host/manifest/reliefos-deps.c @@ -170,7 +170,7 @@ static int kind_is_known(const char *kind) return 0; } return strcmp(kind, "submodule") == 0 || strcmp(kind, "tarball") == 0 - || strcmp(kind, "apk") == 0 || strcmp(kind, "binary") == 0; + || strcmp(kind, "binary") == 0; } /* The cache file name is the last URL path component. It is stored in the fetch @@ -198,7 +198,7 @@ static int validate_entry(const json_value *entry, const char *root_dir, int ind index); } if (!kind_is_known(kind)) { - return report("%s: \"kind\" must be submodule, tarball, apk or binary", id); + return report("%s: \"kind\" must be submodule, tarball or binary", id); } { /* Wherever the source lands, the name comes from the lock file, so an diff --git a/tools/test_boot_block.py b/tools/test_boot_block.py deleted file mode 100644 index 208faab3..00000000 --- a/tools/test_boot_block.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python3 -"""Exercise reserved boot-image block I/O without copying the huge payload.""" -from pathlib import Path -import subprocess -import tempfile -ROOT = Path(__file__).resolve().parents[1] -with tempfile.TemporaryDirectory(prefix="reliefnt-boot-block-") as directory: - binary = Path(directory) / "boot-block" - subprocess.run(["clang", "-std=gnu11", "-O1", "-g", "-Wall", "-Wextra", "-Werror", - "-DCONFIG_MODULES=1", "-DCONFIG_MODULE_UNLOAD=1", "-ffunction-sections", "-fdata-sections", - "-Wl,--gc-sections", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", - "-Iinclude", "-Iinclude/uapi", "tools/tests/boot_block_test.c", "block/ramdisk/boot.c", - "block/device/registry.c", "kernel/module/lifecycle.c", "kernel/params/value.c", "kernel/module/layout.c", "kernel/module/symbols.c", - "-o", str(binary)], cwd=ROOT, check=True) - subprocess.run([str(binary)], cwd=ROOT, check=True, timeout=15) diff --git a/tools/test_boot_policy.py b/tools/test_boot_policy.py index cc8f1782..44398f5b 100644 --- a/tools/test_boot_policy.py +++ b/tools/test_boot_policy.py @@ -1,11 +1,9 @@ #!/usr/bin/env python3 -"""Check canonical and rollback boot identities accepted by the kernel.""" +"""Check the identities used by the native boot path.""" from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -assert '"reliefos-installer-root"' in (ROOT / 'fs/vfs/mount.c').read_text(), 'kernel accepts the canonical installer root tag' -assert '"leonos-installer-root"' in (ROOT / 'fs/vfs/mount.c').read_text(), 'kernel accepts the legacy installer root tag' assert '"RELIEFOS_ROOT"' in (ROOT / 'block/core/storage_block.c').read_text(), 'kernel recognizes the canonical GPT root name' -assert '"LEONOS4_ROOT"' in (ROOT / 'block/core/storage_block.c').read_text(), 'kernel recognizes the legacy GPT root name' +assert 'storage_initramfs_boot(&boot)' in (ROOT / 'kernel/init/kernel.c').read_text() assert "kernel_name=ReliefNT" in (ROOT / "configs/build-version").read_text() assert '#define LINUX_UTS_SYSNAME "ReliefNT"' in (ROOT / "include/reliefnt/uts.h").read_text() -print("PASS kernel boot identity, root tags and rollback identities") +print("PASS kernel boot identities") diff --git a/tools/test_installer_ramdisk.py b/tools/test_installer_ramdisk.py deleted file mode 100644 index 35911c3e..00000000 --- a/tools/test_installer_ramdisk.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python3 -"""Run the installer RAM-root mapping regression against a real ext2 image.""" -from pathlib import Path -from storage_graph_test_sources import STORAGE_GRAPH_SOURCES -import os -import subprocess -import tempfile - - -ROOT = Path(__file__).resolve().parents[1] -TEMP_PARENT = Path(os.environ.get("TMPDIR", str(ROOT / "out/tmp"))) -TEMP_PARENT.mkdir(parents=True, exist_ok=True) -with tempfile.TemporaryDirectory(prefix="reliefos-installer-ramdisk-", dir=TEMP_PARENT) as directory: - work = Path(directory) - image = work / "installer-root.ext2" - executable = work / "installer-ramdisk-test" - subprocess.run([ - "mke2fs", "-q", "-t", "ext2", "-b", "1024", "-I", "256", - "-O", "none", "-F", str(image), "8192", - ], check=True) - subprocess.run([ - "cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", - "-fno-sanitize-recover=all", "-ffunction-sections", "-fdata-sections", - "-Wl,--gc-sections", "-Iinclude", "-Iinclude/uapi", "-Iinclude", - "tools/tests/installer_ramdisk_test.c", "mm/physical/proc.c", "block/ramdisk/boot.c", *STORAGE_GRAPH_SOURCES, "-o", str(executable), - ], cwd=ROOT, check=True) - subprocess.run([str(executable), str(image)], cwd=ROOT, check=True, timeout=30) diff --git a/tools/test_linux_audio.py b/tools/test_linux_audio.py index b19439ac..26aaed86 100644 --- a/tools/test_linux_audio.py +++ b/tools/test_linux_audio.py @@ -327,12 +327,14 @@ def run_abi() -> int: return 0 -def build_guest(output: Path, sdk: Path, period_frames: int = 512, +def build_guest(output: Path, guest_cc: str, period_frames: int = 512, buffer_frames: int = 2048, channels: int = 2) -> int: - """Compile one source against Linux reference, production UAPI and musl. + """Compile one source against Linux reference, production UAPI and glibc. Run only ABI and invalid arguments on the host. Real sound operations are - deferred to H6/U6; an available host microphone is never a prerequisite. + deferred to H6/U6; an available host microphone is never a prerequisite. Run + this command in the target's Arch build environment, or select an equivalent + x86-64 glibc compiler with --guest-cc. """ output = output.resolve() if not output.is_relative_to(ROOT / "out"): @@ -353,13 +355,16 @@ def build_guest(output: Path, sdk: Path, period_frames: int = 512, f"-DAUDIO_GUEST_PERIOD_FRAMES={period_frames}", f"-DAUDIO_GUEST_BUFFER_FRAMES={buffer_frames}", f"-DAUDIO_GUEST_CHANNELS={channels}"] + glibc_check = "#include \n#ifndef __GLIBC__\n#error guest compiler requires glibc\n#endif\n" + subprocess.run([guest_cc, "-x", "c", "-fsyntax-only", "-"], input=glibc_check, + text=True, cwd=ROOT, check=True, timeout=20) host, reference = Path(str(output) + "-host"), Path(str(output) + "-linux-v6.14") commands = [ ["cc", *common, "-I", str(ROOT / "include/uapi"), str(GUEST_PROBE), "-lm", "-o", str(host)], ["cc", *common, "-I", str(FIXTURE), "-D__user=", "-D__force=", "-D__packed=__attribute__((packed))", str(GUEST_PROBE), "-lm", "-o", str(reference)], - [str(sdk.resolve() / "bin/reliefos-musl-cc"), *common, "-static", + [guest_cc, *common, "-static", "-I", str(ROOT / "include/uapi"), str(GUEST_PROBE), "-lm", "-o", str(output)], ] for command in commands: @@ -381,13 +386,13 @@ def build_guest(output: Path, sdk: Path, period_frames: int = 512, str(ROOT / "tools/tests/audio_guest_transport_test.c"), "-lm", "-o", str(fixture)], cwd=ROOT, check=True, timeout=30) subprocess.run([str(fixture)], cwd=ROOT, check=True, timeout=10) - # Both include orders must compile against the actual SDK, not host /usr/include. + # Both include orders must compile against the selected target compiler and UAPI. for first in ("time.h", "sound/asound.h"): second = "sound/asound.h" if first == "time.h" else "time.h" source = f"#include <{first}>\n#include <{second}>\n_Static_assert(sizeof(struct timespec)==16, \"native time64\");\n" include_obj = output.parent / ("audio-guest-include-" + first.replace("/", "-")) - subprocess.run([str(sdk.resolve() / "bin/reliefos-musl-cc"), *common, - "-Wno-unused-command-line-argument", "-x", "c", "-c", "-o", str(include_obj), "-"], input=source, + subprocess.run([guest_cc, *common, "-I", str(ROOT / "include/uapi"), + "-x", "c", "-c", "-o", str(include_obj), "-"], input=source, text=True, cwd=ROOT, check=True, timeout=20) binaries = [host, reference, output, fixture] Path(str(output) + "-build.json").write_text(json.dumps({ @@ -398,10 +403,10 @@ def build_guest(output: Path, sdk: Path, period_frames: int = 512, "buffer_bytes": buffer_frames * channels * 2}, "binaries": [{"path": str(p.relative_to(ROOT)) if p.is_relative_to(ROOT) else str(p), "sha256": hashlib.sha256(p.read_bytes()).hexdigest()} for p in binaries], - "evidence": "host ABI/invalid arguments/transport fixture and musl build only", + "evidence": "host ABI/invalid arguments/transport fixture and glibc build only", "hardware_io_run": False, "guest_run": False, }, indent=2) + "\n") - print(f"PASS guest probe: pinned Linux/production/musl ABI, invalid arguments, transport, include orders; built {output}") + print(f"PASS guest probe: pinned Linux/production/glibc ABI, invalid arguments, transport, include orders; built {output}") return 0 @@ -417,7 +422,7 @@ def main() -> int: parser.add_argument("--guest-channels", type=int, default=2, help="exact channel count from the target PCM HW_REFINE result") parser.add_argument("--output", type=Path, default=ROOT / "out/audio-hda/qa/audio-guest") - parser.add_argument("--sdk", type=Path, default=ROOT / "out/audio-hda/sdk/reliefos-musl-sdk") + parser.add_argument("--guest-cc", default="cc", help="x86-64 glibc compiler in the target build environment") args = parser.parse_args() if not args.modes and not args.build_guest: parser.error("select one or more modes or --build-guest") @@ -428,7 +433,7 @@ def main() -> int: result = modes[mode]() if result: return result - return build_guest(args.output, args.sdk, args.guest_period_frames, + return build_guest(args.output, args.guest_cc, args.guest_period_frames, args.guest_buffer_frames, args.guest_channels) if args.build_guest else 0 diff --git a/tools/test_openrc_network.py b/tools/test_network_time.py similarity index 78% rename from tools/test_openrc_network.py rename to tools/test_network_time.py index 8c0d7e7a..608a412e 100644 --- a/tools/test_openrc_network.py +++ b/tools/test_network_time.py @@ -7,12 +7,12 @@ ROOT = Path(__file__).resolve().parents[1] def main(): - with tempfile.TemporaryDirectory(prefix="reliefos-openrc-network-") as directory: + with tempfile.TemporaryDirectory(prefix="reliefnt-network-time-") as directory: for name in ("net_interface", "net_packet", "time_discipline", "timekeeper_discipline", "driver_control"): binary = Path(directory) / name - subprocess.run(["cc", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", + subprocess.run(["clang", "-std=c11", "-O1", "-g", "-fsanitize=address,undefined", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", - "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", + "-Iinclude", "-Iinclude/uapi", f"tools/tests/{name}_test.c", *(["net/socket/filter.c", "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/sched/user_namespace.c"] if name == "net_packet" else []), diff --git a/tools/test_squashfs.py b/tools/test_squashfs.py index 18ab1120..d51a76d1 100644 --- a/tools/test_squashfs.py +++ b/tools/test_squashfs.py @@ -24,10 +24,12 @@ def run(*args, check=True, **kwargs): def make_image(tree, image, *options, **kwargs): + environment = os.environ.copy() + environment.pop("SOURCE_DATE_EPOCH", None) # The fixture chooses exact timestamps below. return run("mksquashfs", tree, image, "-noappend", "-quiet", "-no-progress", "-processors", "1", "-b", "4096", "-all-time", "1700000000", "-mkfs-time", "1700000000", - "-force-uid", "1234", "-force-gid", "4321", *options, **kwargs) + "-force-uid", "1234", "-force-gid", "4321", *options, env=environment, **kwargs) with tempfile.TemporaryDirectory(prefix="reliefnt-squashfs-") as temporary: diff --git a/tools/test_squashfs_boot.py b/tools/test_squashfs_boot.py deleted file mode 100644 index 2eaf0352..00000000 --- a/tools/test_squashfs_boot.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env python3 -"""Run Multiboot installer-root and SquashFS payload registration checks.""" -import os -from pathlib import Path -import shlex -import subprocess -import tempfile - - -ROOT = Path(__file__).resolve().parents[1] -with tempfile.TemporaryDirectory(prefix="reliefnt-squashfs-boot-") as directory: - executable = Path(directory) / "squashfs-boot-modules-test" - subprocess.run([ - *shlex.split(os.environ.get("HOSTCC", "cc")), "-std=c11", "-O2", "-g", "-Wall", "-Wextra", "-Werror", - "-Wno-error=misleading-indentation", - "-Iinclude", "-Iinclude/uapi", "tools/tests/squashfs_boot_modules_test.c", - "block/ramdisk/boot.c", "-o", str(executable), - ], cwd=ROOT, check=True) - subprocess.run([str(executable)], cwd=ROOT, check=True, timeout=10) diff --git a/tools/tests/Makefile b/tools/tests/Makefile index 70b5dd74..96ad36ca 100644 --- a/tools/tests/Makefile +++ b/tools/tests/Makefile @@ -14,10 +14,10 @@ test-host-smoke: --suite loadavg --suite input --suite input_routing --suite uapi --suite seccomp_bpf \ --suite acpi_pm_timer --suite apic_timer --suite cpu_accounting --suite exit_logging \ --suite fat_async_read --suite fat_read_split \ - --suite squashfs --suite squashfs_boot \ + --suite squashfs \ --suite linux_pty --suite linux_resources --suite mount_backend --suite mount_namespace_task --suite cgroup_scheduler \ --suite user_namespace \ - --suite linux_socket_batches --suite ipv6_control \ + --suite linux_socket_batches --suite ipv6_control --suite network_time \ --suite vdso_mapping --suite vdso_time test-smp-time: diff --git a/tools/tests/boot_block_test.c b/tools/tests/boot_block_test.c deleted file mode 100644 index cee29c15..00000000 --- a/tools/tests/boot_block_test.c +++ /dev/null @@ -1,83 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 */ -#define _GNU_SOURCE 1 -#include -#include -#include -#include -#include -#include -#include -#include -#include "../../kernel/module/internal.h" -/* Boot image transfers run before scheduling in this fixture. */ -struct task *sched_current_task(void) -{ - return NULL; -} -uint32_t sched_current_pid(void) -{ - return 0; -} -uint64_t time_uptime_ms(void) -{ - return 0; -} - -static unsigned char *source; -static const uint64_t physical=0x18000000,source_bytes=1536ULL*1024*1024; -static size_t allocations; -static bool reject_mapping,fail_heap; -void *kernel_malloc(size_t bytes) -{assert(bytes<4096);if(fail_heap)return NULL;void *p=calloc(1,bytes);if(p)++allocations;return p;} -void kernel_free(void *p){if(p){assert(allocations);--allocations;free(p);}} -void module_memory_free(struct module_memory *memory){assert(!memory);} -void kernel_spin_lock_irqsave(struct kernel_spinlock *lock,uint64_t *flags) -{assert(!lock->state);lock->state=1;*flags=0;} -void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock,uint64_t flags) -{assert(lock->state && !flags);lock->state=0;} -bool paging_kernel_direct_map_range(uint64_t start,uint64_t length) -{return !reject_mapping && start==physical && length==source_bytes;} -void *paging_kernel_direct_map(uint64_t start) -{assert(start==physical);return reject_mapping ? NULL : source;} - -int main(void) -{ - /* A 1.5 GiB virtual payload has only two accessible pages. Registration - * must neither read nor copy the body; ASan/guard pages catch an attempt. */ - source=mmap(NULL,source_bytes,PROT_NONE,MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,-1,0); - assert(source!=MAP_FAILED); - assert(!mprotect(source,4096,PROT_READ|PROT_WRITE)); - assert(!mprotect(source+source_bytes-4096,4096,PROT_READ|PROT_WRITE)); - memset(source,0x42,4096);memset(source+source_bytes-4096,0x71,4096); - uint64_t device=9;assert(!block_boot_image_register(NULL,&device) && !device && !allocations); - struct boot_info boot={.module_count=1,.modules={{physical,physical+source_bytes,"initramfs"}}}; - assert(!block_boot_image_register(&boot,&device) && !device); - boot.module_count=17;assert(block_boot_image_register(&boot,&device)==-22 && !device); - boot.module_count=2;boot.modules[0].name="reliefos-installer-root"; - boot.modules[1]=(struct boot_module){physical,physical+source_bytes,"leonos-installer-root"}; - assert(block_boot_image_register(&boot,&device)==-17 && !device && !allocations); - boot.module_count=1;boot.modules[0].end=physical; - assert(block_boot_image_register(&boot,&device)==-8 && !device); - boot.modules[0].end=physical+source_bytes; - reject_mapping=true;assert(block_boot_image_register(&boot,&device)==-22 && !device);reject_mapping=false; - fail_heap=true;assert(block_boot_image_register(&boot,&device)==-12 && !device && !allocations);fail_heap=false; - assert(block_boot_image_register(&boot,&device)==1 && device==0x100 && allocations==1); - assert(block_boot_image_register(&boot,&device)==1 && device==0x100 && allocations==1); - struct block_device_ref ref={0};assert(!block_device_get(device,&ref)); - struct block_device_info info;assert(!block_device_info(&ref,&info)); - assert(info.device==0x100 && info.blocks==source_bytes/512 && info.block_size==512 && - info.transport==BLOCK_TRANSPORT_MEMORY && (info.flags&BLOCK_DEVICE_WRITE_THROUGH)); - unsigned char data[1024];assert(!block_device_read(&ref,0,2,data)); - for(unsigned i=0;ikernel-relative pathreason -compatibility block/core/storage_block.c 识别已有磁盘 GPT 名 LEONOS4_ROOT -compatibility block/ramdisk/boot.c 内存块设备接收已有 leonos-installer-root Multiboot 模块标签,保留旧引导器兼容 -compatibility include/reliefnt/boot_block.h 声明相同历史引导模块标签的兼容接收契约 -compatibility tools/tests/boot_block_test.c 验证历史引导标签与当前标签双接受,并拒绝重复载荷 -compatibility drivers/video/framebuffer/fbdev.c 从 ioctl 分派迁移的 leonos-fb 设备 ID,保持既有 fbdev ABI 值 -compatibility fs/vfs/mount.c 旧 leonos-installer-root 引导 module tag 双接受 -compatibility fs/proc/procfs.c 冻结 LeonOSRole/LeonOSFlags 与 /proc/leonos-drivers 接口值 -compatibility fs/sysfs/sysfs.c 冻结 /sys/devices/platform/leonos-block 运行时设备路径 -compatibility include/reliefos/elf_abi.h published ELF note and runtime SONAME values -compatibility include/reliefos/layout.h frozen task 6 guest layout values -compatibility include/uapi/reliefos/rootfs.h frozen task 6 rootfs paths -compatibility kernel/init/kernel.c 识别旧 installer-root GRUB module tag -compatibility kernel/syscall/device/input_ioctl.c 冻结设备 ioctl 对外 identity:PS/2 名称与 leonos-fb -compatibility kernel/syscall/device/legacy_ioctl.c 冻结设备 ioctl 对外 identity:PS/2 名称与 leonos-fb compatibility tools/tests/fixtures/legacy-abi-layout.json 旧 UAPI sizeof/offsetof/常量布局 golden,值级对比基线不得随意改写 -compatibility tools/tests/installer_ramdisk_test.c 验证旧 leonos-installer-root module tag 的挂载兼容路径 -compatibility tools/tests/linux_inventory_test.c sysfs 冻结 leonos-block 接口值的 Linux 清单探针 -compatibility include/uapi/README.rst 公开旧 libleonos.so.2 独立兼容 SONAME 的使用限制 history configs/kernel-source-map.json 源码拆分映射保留基线名称,仅作审计不进入生产编译 history Documentation/releases/5.1.0.rst 已发布 5.1.0 说明的 RST 归档,迁移指引保留已删除的旧标识和兼容路径 history Documentation/locale/en/LC_MESSAGES/releases/5.1.0.po 已发布 5.1.0 说明的英文 gettext 译文,原文与译文保留迁移指引中已删除的旧标识和兼容路径 @@ -25,4 +8,3 @@ history Documentation/releases/5.1.2.rst 已发布 5.1.2 说明的 RST 归档, compatibility tools/test_brand_identity.py 旧标识审计规则本身 compatibility tools/test_security_regressions.py 审计并拒绝旧私有 ioctl 名称 compatibility tools/tests/brand-allowlist.tsv 逐文件记录冻结旧 ABI 与历史标识 -compatibility tools/test_boot_policy.py 旧磁盘身份和兼容启动标识断言 diff --git a/tools/tests/execution_lock_runtime_probe.c b/tools/tests/execution_lock_runtime_probe.c index fca1c037..1ec5cf18 100644 --- a/tools/tests/execution_lock_runtime_probe.c +++ b/tools/tests/execution_lock_runtime_probe.c @@ -71,6 +71,6 @@ int main(void) for (unsigned long i = 0; i < 2; ++i) assert(pthread_create(&threads[i], NULL, thread_touch, (void *)(i + 41)) == 0); for (unsigned i = 0; i < 2; ++i) assert(pthread_join(threads[i], NULL) == 0); - puts("[apk-probe] DONE failures=0 (private and shared address-space faults)"); + puts("[execution-probe] DONE failures=0 (private and shared address-space faults)"); return 0; } diff --git a/tools/tests/host-suites.list b/tools/tests/host-suites.list index 8877603a..935cc66b 100644 --- a/tools/tests/host-suites.list +++ b/tools/tests/host-suites.list @@ -54,7 +54,6 @@ inotify_core tools/test_inotify_core.py inotify_proc tools/test_inotify_proc.py inotify_vfs tools/test_inotify_vfs.py input_routing tools/test_input_routing.py -installer_ramdisk tools/test_installer_ramdisk.py kernel_memory tools/test_kernel_memory.py kthread tools/test_kthread.py linux_abi_contract tools/test_linux_abi_contract.py @@ -81,7 +80,7 @@ network tools/test_network.py ipv6_protocol tools/test_ipv6_protocol.py ipv6_transport tools/test_ipv6_transport.py ipv6_control tools/test_ipv6_control.py -openrc_network tools/test_openrc_network.py +network_time tools/test_network_time.py page_cache_growth tools/test_page_cache_growth.py memory_reclaim tools/test_memory_reclaim.py cache_clustered_lifetime tools/test_cache_clustered_lifetime.py @@ -182,9 +181,7 @@ initramfs_archive tools/test_initramfs_archive.py initramfs tools/test_initramfs.py initramfs_boot tools/test_initramfs_boot.py devfs_rdev tools/test_devfs_rdev.py -boot_block tools/test_boot_block.py squashfs tools/test_squashfs.py -squashfs_boot tools/test_squashfs_boot.py install_bundle tools/test_install_bundle.py parameter_values tools/test_parameter_values.py builtin_parameters tools/test_builtin_parameters.py diff --git a/tools/tests/initramfs_runtime_probe.c b/tools/tests/initramfs_runtime_probe.c index 02d53928..2405a866 100644 --- a/tools/tests/initramfs_runtime_probe.c +++ b/tools/tests/initramfs_runtime_probe.c @@ -37,53 +37,23 @@ static int owned(int directory,const char *name) ssize_t length=read(file,bytes,sizeof(bytes));int closed=close(file); return !closed && length==sizeof(marker)-1 && !memcmp(bytes,marker,sizeof(marker)-1); } -/** @brief Execute the actual staged static BusyBox and check its guest result. - * @param command Applet name. @param option Optional first applet argument. - * @param name Optional final applet argument. +/** @brief Execute the staged kmod tool and check its guest result. + * @param command kmod command. @param option Optional first command argument. + * @param name Optional final command argument. * @return None. Host/PID1/marker admission precedes all calls; child operations * act only on this guest's staged module tree and actual native module loader. */ -static void busybox_command(const char *command,const char *option,const char *name) +static void kmod_command(const char *command,const char *option,const char *name) { - pid_t child=fork();require(child>=0,"fork actual BusyBox tool"); + pid_t child=fork();require(child>=0,"fork actual kmod tool"); if(!child) { - if(option && name)execl("/bin/busybox","busybox",command,option,name,(char *)NULL); - else if(option)execl("/bin/busybox","busybox",command,option,(char *)NULL); - else execl("/bin/busybox","busybox",command,(char *)NULL); + if(option && name)execl("/usr/bin/kmod","kmod",command,option,name,(char *)NULL); + else if(option)execl("/usr/bin/kmod","kmod",command,option,(char *)NULL); + else execl("/usr/bin/kmod","kmod",command,(char *)NULL); _exit(127); } int status;pid_t waited;do {waited=waitpid(child,&status,0);} while(waited<0 && errno==EINTR); - require(waited==child && WIFEXITED(status) && !WEXITSTATUS(status),"actual BusyBox command completed successfully"); -} -/** @brief Exercise the optional reserved installer image before any controller loads. - * @return None. Entered only after ReliefNT/PID1/owned-root admission; the extra - * marker is present only in the private RAM-image carrier. Native filesystem - * ownership and coherent temporary writes are checked without a physical disk. - */ -static void early_ramdisk(void) -{ - if(access("/.qa-ram-root",F_OK))return; - struct stat status;struct statfs filesystem; - require(!stat("/dev/ram0",&status) && S_ISBLK(status.st_mode) && status.st_rdev==0x100, - "reserved image appears as actual Linux ram0 before storage modules"); - errno=0;require(access("/dev/sda",F_OK)==-1 && errno==ENOENT,"RAM root needs no physical controller"); - const char *modules[]={"/ext_common.ko","/ext4.ko"}; - for(unsigned i=0;i<2;++i) { - int file=open(modules[i],O_RDONLY|O_CLOEXEC); - require(file>=0 && !syscall(SYS_finit_module,file,"",0) && !close(file),"load actual installer root filesystem module"); - } - require(!mount("/dev/ram0","/newroot","ext4",MS_NOATIME,NULL),"mount complete RAM block image at LBA zero"); - require(!statfs("/newroot",&filesystem) && filesystem.f_type==0xef53 && - !stat("/newroot",&status) && status.st_dev==0x100,"RAM mount publishes its native filesystem and device identity"); - int data=open("/newroot/ram-root-write",O_RDWR|O_CREAT|O_EXCL,0600);char bytes[6]={0}; - require(data>=0 && write(data,"image",5)==5 && !fsync(data) && lseek(data,0,SEEK_SET)==0 && - read(data,bytes,5)==5 && !memcmp(bytes,"image",5) && !close(data),"RAM block filesystem supports coherent native writes"); - errno=0;require(syscall(SYS_delete_module,"ext4",O_NONBLOCK)==-1 && - (errno==EBUSY || errno==EWOULDBLOCK),"RAM filesystem mount pins actual module code"); - require(!unlink("/newroot/ram-root-write") && !umount("/newroot"),"retire actual RAM filesystem and transient data"); - require(!syscall(SYS_delete_module,"ext4",O_NONBLOCK) && !syscall(SYS_delete_module,"ext_common",O_NONBLOCK), - "unused RAM root filesystem dependency unloads after final retirement"); - puts("INITRAMFS_RUNTIME reserved RAM block mounts and writes before physical controller modules"); + require(waited==child && WIFEXITED(status) && !WEXITSTATUS(status),"actual kmod command completed successfully"); } /** @brief Load an optional exact module sequence from this private archive. * @return True for the modular-root carrier, false for an all-built-in carrier. @@ -99,16 +69,16 @@ static bool early_modules(void) errno=0;require(syscall(SYS_finit_module,file,"",0)==-1 && errno==ENOENT, "actual root filesystem refuses missing ext_common dependency without corrupting loader state"); require(!close(file),"close rejected dependency candidate"); - bool tools=access("/.qa-busybox-modprobe",F_OK)==0; + bool tools=access("/.qa-kmod",F_OK)==0; if(tools) { - busybox_command("depmod","-a",NULL); - busybox_command("modprobe","serial",NULL); - busybox_command("modprobe","-b","exfat"); + kmod_command("depmod","-a",NULL); + kmod_command("modprobe","serial",NULL); + kmod_command("modprobe","-b","exfat"); errno=0;require(access("/sys/module/exfat/initstate",F_OK)==-1 && errno==ENOENT, "actual modprobe blacklist suppresses module loading"); - busybox_command("modprobe","qa-parameters",NULL); - busybox_command("rmmod","parameters",NULL); - busybox_command("modprobe","-D","ext4"); + kmod_command("modprobe","qa-parameters",NULL); + kmod_command("rmmod","parameters",NULL); + kmod_command("modprobe","-D","ext4"); } char path[256];unsigned loaded=0; while(fgets(path,sizeof(path),list)) { @@ -121,15 +91,15 @@ static bool early_modules(void) *extension=0; const char *request=!strcmp(module,"ext4") ? "qa-root-filesystem" : !strcmp(module,"ahci") ? "pci:v00008086d00002922sv00001AF4sd00001100bc01sc06i01" : module; - busybox_command("modprobe",request,NULL);*extension='.'; + kmod_command("modprobe",request,NULL);*extension='.'; } } else require(!syscall(SYS_finit_module,file,"",0) && !close(file),"load actual early module in dependency order"); printf("INITRAMFS_RUNTIME_LOADED %s\n",path);++loaded; } require(!ferror(list) && !fclose(list) && loaded==9,"complete all filesystem/controller module set"); if(tools) { - busybox_command("lsmod",NULL,NULL); - puts("INITRAMFS_RUNTIME BusyBox real modprobe/rmmod/lsmod, modules.dep, builtin, aliases, blacklist and quoted/ranged parameters"); + kmod_command("lsmod",NULL,NULL); + puts("INITRAMFS_RUNTIME kmod modprobe/rmmod/lsmod, modules.dep, builtin, aliases, blacklist and quoted/ranged parameters"); } puts("INITRAMFS_RUNTIME root controller and filesystem were absent and loaded from actual ko files");return true; } @@ -166,7 +136,6 @@ int main(int argc,char **argv) for(;;)pause(); } require(!statfs("/",&fs) && fs.f_type==0x01021994,"PID1 really executes from newc memory root"); - early_ramdisk(); bool modular=early_modules(); require(!stat("/native-null",&status) && S_ISCHR(status.st_mode) && status.st_rdev==0x103, "unpacked special inode retains Linux rdev"); diff --git a/tools/tests/installer_ramdisk_test.c b/tools/tests/installer_ramdisk_test.c deleted file mode 100644 index f178c201..00000000 --- a/tools/tests/installer_ramdisk_test.c +++ /dev/null @@ -1,401 +0,0 @@ -/* Host regression for the installer RAM-root module's physical-address contract. */ -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../../block/core/storage_internal.h" -#include -/* Storage completion wakeups are outside this host fixture. */ -void storage_completion_notify(void) {} -#include "../../block/core/storage_state.c" -#include "../../block/core/device_number.c" -#include "../../block/core/storage_state_data.c" -#include "../../block/core/volume.c" -#include "../../block/device/registry.c" -#include "../../block/device/inventory.c" -#include "../../block/device/optical.c" -#include "../../block/device/storage_devlinks.c" -#include "../../fs/ext_common/ext2_cache.c" -#include "../../drivers/storage/ide/storage_ide.c" -#include "../../drivers/storage/ahci/storage_ahci.c" -#include "../../drivers/storage/nvme/storage_nvme.c" -#include "../../block/core/storage_block.c" -#include "../../fs/ext_common/format.c" -#include "../../fs/ext_common/checksum.c" -#include "../../fs/ext_common/cache.c" -#include "../../fs/ext_common/alloc.c" -#include "../../fs/ext_common/extent.c" -#include "../../fs/ext_common/ops.c" -#include "../../fs/ext_common/xattr.c" -#include "../../fs/ext_common/journal.c" -#include "../../fs/ext_common/dir.c" -#include "../../block/core/storage_sync.c" -#include "../../fs/iso9660/iso.c" -#include "../../fs/iso9660/native.c" -#include "modules/fat32.h" -#include "../../fs/vfs/inode.c" -#include "../../fs/ext_common/vfs.c" -#include "../../fs/ext_common/ext2.c" -#include "modules/exfat.h" -#include "../../fs/ext_common/mount.c" -#include "../../fs/ext_common/sync.c" -#include "../../fs/ext_common/native.c" -#include "../../fs/vfs/mount.c" -#include "../../sound/core/storage_audio.c" -#include "modules/vfs.h" -#include "../../fs/vfs/mounts.c" -#include "../../fs/tmpfs/core.c" -#include "../../fs/tmpfs/tmpfs.c" -#include "../../fs/tmpfs/native.c" -#include "../../fs/security/permissions.c" -#include "../../fs/security/sidecar.c" -#include "../../fs/vfs/statfs.c" -#include "../../block/install/storage_installer.c" -#include "../../fs/fat/mkfs.c" -#include "../../fs/exfat/mkfs.c" -#include "../../fs/ext_common/mkfs.c" -#include "modules/disk.h" -#include "../../block/partition/boot_root.c" -#include "../../lib/text_utf16.c" - -enum { TEST_RAMDISK_PHYS = 0x12345000u }; - -static uint8_t *test_ramdisk_bytes; -static uint64_t test_ramdisk_length; -static unsigned test_mm_mapping_calls; -static unsigned test_direct_mapping_calls; -static unsigned test_direct_range_calls; -static uint64_t test_last_direct_physical; -static bool test_direct_map_reject; - -/** @brief Provide allocator storage for the actual storage implementation. */ -void *kernel_malloc(size_t size) { return malloc(size); } -/** @brief Release allocator storage for the actual storage implementation. */ -void kernel_free(void *pointer) { free(pointer); } -/** @brief Allocate one host page for code paths retained by the storage fixture. */ -void pci_unmap_mmio(void *pointer, uint64_t bytes) -{ (void)pointer; (void)bytes; abort(); } -void pci_config_write16(uint8_t bus,uint8_t slot,uint8_t function,uint8_t offset,uint16_t value) -{ (void)bus;(void)slot;(void)function;(void)offset;(void)value;abort(); } -uint64_t mm_alloc_pages_below(uint32_t pages, uint64_t mask) -{ (void)pages; (void)mask; abort(); } -uint64_t mm_alloc_page(void) { return (uintptr_t)aligned_alloc(4096, 4096); } -/** @brief Map physical memory to a deliberately nonidentity host alias. */ -void *mm_phys_to_virt(uint64_t physical) -{ - if (physical == TEST_RAMDISK_PHYS) { - ++test_mm_mapping_calls; - return (void *)(uintptr_t)(UINT64_C(0xffff800000000000) | physical); - } - return (void *)(uintptr_t)physical; -} -/** @brief Free a host page allocated by the storage fixture. */ -void mm_free_page(uint64_t physical) { free((void *)(uintptr_t)physical); } -/** @brief Allocate contiguous host pages for storage cache paths. */ -uint64_t mm_alloc_pages(uint32_t pages) -{ return (uint64_t)(uintptr_t)calloc(pages, 4096); } -/** @brief Free contiguous host pages allocated by the storage fixture. */ -void mm_free_pages(uint64_t physical, uint32_t pages) -{ (void)pages; free((void *)(uintptr_t)physical); } -/** @brief Invert only owned host page mappings, never the retained boot image. */ -uint64_t mm_virt_to_phys(const void *address) -{ assert(address!=test_ramdisk_bytes);return (uintptr_t)address; } - -/** @brief Reject file-mapping truncation outside this boot-time host fixture. */ -void sched_truncate_file_mappings(const struct storage_node *node, uint64_t size) -{ (void)node; (void)size; abort(); } -/** @brief Suppress formatted console output during the fixture. */ -void console_printf(const char *format, ...) { (void)format; } -/** @brief Suppress console logging during the fixture. */ -void console_log(enum console_log_level level, const char *format, ...) -{ (void)level; (void)format; } -/** @brief Report no DRM render device in the storage fixture. */ -bool graphics_service_is_registered(void) { return false; } -/** @brief Report no DRM render node in the storage fixture. */ -bool graphics_service_render_node_ready(void) { return false; } -/** @brief Report no audio cards in the storage fixture. */ -int audio_card_snapshot(uint32_t index, uint32_t *out_id, - struct audio_card_identity *identity) -{ (void)index; (void)out_id; (void)identity; return -2; } -/** @brief Reject audio device name parsing in the storage fixture. */ -int audio_device_parse_name(const char *name, uint32_t *card, - uint32_t *device, - enum audio_direction *direction) -{ (void)name; (void)card; (void)device; (void)direction; return -22; } -/** @brief Report no audio PCM capabilities in the storage fixture. */ -int audio_card_pcm_caps(uint32_t card, uint32_t device, - enum audio_direction direction, - struct audio_caps *caps) -{ (void)card; (void)device; (void)direction; (void)caps; return -19; } -/** @brief Stub the kernel execution lock, which is uncontended in host tests. */ -void kernel_execution_lock_irqsave(uint64_t *flags) { *flags = 0; } -/** @brief Stub kernel execution lock release in the single-threaded fixture. */ -void kernel_execution_unlock_irqrestore(uint64_t flags) { (void)flags; } -/** @brief Report a single host CPU. */ -uint32_t smp_cpu_count(void) { return 1; } -/** @brief Provide no scheduled task to boot-time storage code. */ -struct task *sched_current_task(void) { return NULL; } -/** @brief Provide the host fixture's synthetic current pid. */ -uint32_t sched_current_pid(void) { return 1; } -uint64_t time_uptime_ms(void) -{ - return 0; -} /* Synchronous fixture clock. */ -/** @brief Ignore page-cache invalidation for non-page-backed test nodes. */ -void page_cache_invalidate_node(const struct storage_node *node) { (void)node; } -/** @brief Report no cache entries in the installer fixture. - * @param node Borrowed inode. @return Zero. - */ -int page_cache_has_inode(const struct storage_node *node) { (void)node; return 0; } -/** @brief Accept a volume purge in the cache-free fixture. @param volume Slot. */ -void page_cache_forget_volume(uint32_t volume) { (void)volume; } -/** @brief Accept a resize in the cache-free fixture. - * @param node Borrowed inode. @param old_size Previous size. @param new_size New size. - */ -void page_cache_resize_node(const struct storage_node *node,uint64_t old_size,uint64_t new_size) -{ (void)node; (void)old_size; (void)new_size; } -void page_cache_forget_node(const struct storage_node *node) { (void)node; } -void page_cache_zero_range(const struct storage_node *node,uint64_t offset,uint64_t length) -{ (void)node; (void)offset; (void)length; abort(); } -/** @brief Reject PTY lookup in this ramdisk-only fixture. */ -int pty_lookup_path(const char *path, struct storage_node *node) -{ (void)path; (void)node; return -2; } -/** @brief Reject unrelated terminal metadata callbacks in the RAM-root fixture. */ -int pty_inode_permissions(const struct storage_node *node,struct reliefos_permissions *value,bool write) -{ (void)node; (void)value; (void)write; abort(); } -/** @brief Reject VT lookup in this ramdisk-only fixture. */ -int pty_lookup_vt_path(const char *path, struct storage_node *node) -{ (void)path; (void)node; return -2; } -/** @brief Reject unexpected transport locking for the memory-backed root. */ -/** @brief Emulate short registry IRQ critical sections on this single-thread host. */ -void kernel_spin_lock_irqsave(struct kernel_spinlock *lock,uint64_t *flags) -{ assert(!lock->state);lock->state=1;*flags=0; } -/** @brief Restore the host fixture's emulated registry IRQ state. */ -void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock,uint64_t flags) -{ assert(lock->state && !flags);lock->state=0; } -void kernel_spin_lock(struct kernel_spinlock *lock) { assert(!lock->state);lock->state=1; } -/** @brief Reject unexpected transport unlock for the memory-backed root. */ -void kernel_spin_unlock(struct kernel_spinlock *lock) { assert(lock->state);lock->state=0; } -/** @brief Reject port I/O because no physical controller is present. */ -uint8_t x86_64_inb(uint16_t port) { (void)port; abort(); } -/** @brief Reject port I/O because no physical controller is present. */ -uint16_t x86_64_inw(uint16_t port) { (void)port; abort(); } -/** @brief Reject port I/O because no physical controller is present. */ -void x86_64_outb(uint8_t value, uint16_t port) { (void)value; (void)port; abort(); } -/** @brief Reject port I/O because no physical controller is present. */ -void x86_64_outw(uint16_t value, uint16_t port) { (void)value; (void)port; abort(); } -void x86_64_insw(uint16_t port, void *buffer, size_t count) { (void)port; (void)buffer; (void)count; abort(); } -void x86_64_outsw(uint16_t port, const void *buffer, size_t count) { (void)port; (void)buffer; (void)count; abort(); } -/** @brief Reject unexpected controller polling in the memory-backed fixture. */ -uint64_t time_ticks(void) { abort(); } -/** @brief Supply a stable wall clock for retained metadata helpers. */ -int time_wall_clock(struct reliefos_time_info *info) -{ *info = (struct reliefos_time_info){.unix_seconds = 1800000000}; return 0; } -/** @brief Model an empty PCI bus during boot-root storage discovery. */ -uint16_t pci_config_read16(uint8_t bus, uint8_t slot, uint8_t function, - uint8_t offset) -{ (void)bus; (void)slot; (void)function; (void)offset; return 0xffffu; } -/** @brief Model absent PCI devices during boot-root storage discovery. */ -uint32_t pci_config_read32(uint8_t bus, uint8_t slot, uint8_t function, - uint8_t offset) -{ (void)bus; (void)slot; (void)function; (void)offset; return 0; } -/** @brief Refuse MMIO mappings because this fixture contains no devices. */ -bool paging_mmio_uncached(uint64_t physical, uint64_t length) -{ (void)physical; (void)length; return false; } -/** @brief Validate the module's physical range without dereferencing it. */ -bool paging_kernel_direct_map_range(uint64_t physical, uint64_t length) -{ - ++test_direct_range_calls; - return !test_direct_map_reject && physical == TEST_RAMDISK_PHYS && - length <= test_ramdisk_length; -} -/** @brief Map the physical module base to its retained host backing. */ -void *paging_kernel_direct_map(uint64_t physical) -{ - ++test_direct_mapping_calls; - test_last_direct_physical = physical; - return !test_direct_map_reject && physical == TEST_RAMDISK_PHYS - ? test_ramdisk_bytes : NULL; -} - -#include "mount_fixture_ops.h" -/** @brief Read one node through a temporary actual root and retire every path. - * @param name Borrowed absolute test name. @param node Required node output. - * @return Common lookup status. The fixture owns the RAM image throughout; - * namespace destruction completes before either boot-root path is repeated. - */ -static int installer_lookup(const char *name,struct storage_node *node) -{ - struct vfs_namespace ns={0};struct vfs_path root={0}; - int rc=mount_fixture_begin(&ns,&g_volumes[STORAGE_VOLUME_ROOT],&root); - if(rc)return rc; - rc=mount_fixture_lookup(&ns,name,node);vfs_path_put(&root); - assert(!vfs_namespace_destroy(&ns));return rc; -} - -/** @brief Read the test image into the RAM backing retained by the mount. */ -static void load_test_image(const char *path) -{ - FILE *file = fopen(path, "rb"); - assert(file && !fseek(file, 0, SEEK_END)); - long size = ftell(file); - assert(size >= 4096 && !fseek(file, 0, SEEK_SET)); - test_ramdisk_bytes = aligned_alloc(4096, (size_t)size); - assert(test_ramdisk_bytes && fread(test_ramdisk_bytes, 1, (size_t)size, file) == - (size_t)size); - assert(!fclose(file)); - test_ramdisk_length = (uint64_t)size; -} - -/** @brief Build one Multiboot list with an ignored module before the root. */ -static struct boot_info test_boot_info(const char *root_name) -{ - struct boot_info boot = {0}; - boot.module_count = 2; - boot.modules[0] = (struct boot_module){ - .start = TEST_RAMDISK_PHYS + 0x100000u, - .end = TEST_RAMDISK_PHYS + 0x101000u, - .name = "unrelated-module", - }; - boot.modules[1] = (struct boot_module){ - .start = TEST_RAMDISK_PHYS, - .end = TEST_RAMDISK_PHYS + test_ramdisk_length, - .name = (char *)root_name, - }; - return boot; -} - -/** @brief Check both installer root entry points retain the direct-map image. */ -static void test_installer_ramdisk_mount_paths(void) -{ - struct boot_info boot = test_boot_info("reliefos-installer-root"); - struct boot_info legacy_boot; - struct storage_node node; - unsigned prior_direct_calls; - - test_direct_map_reject = false; - test_mm_mapping_calls = 0; - test_direct_mapping_calls = 0; - storage_mount_boot_root(&boot, true); - assert(storage_installer_root_active() && storage_ready()); - assert(g_volumes[STORAGE_VOLUME_ROOT].transport==STORAGE_TRANSPORT_MEMORY); - assert(g_volumes[STORAGE_VOLUME_ROOT].device_ref.device); - assert(storage_volume_device_number(&g_volumes[STORAGE_VOLUME_ROOT]) == 0x100); - char name[32];uint32_t ram_disk=g_volumes[STORAGE_VOLUME_ROOT].source_disk_id; - assert(!storage_disk_device_name(ram_disk,-1,name,sizeof(name)) && !strcmp(name,"/dev/ram0")); - struct vfs_mount *first=NULL,*second=NULL,*rejected=NULL; - assert(storage_new_block_mount(ram_disk,UINT32_MAX,NULL,0,&rejected)==-22 && !rejected); - assert(storage_new_block_mount(ram_disk,UINT32_MAX,"vfat",0,&rejected)==-22 && !rejected); - assert(storage_new_block_mount(ram_disk,UINT32_MAX,"ext4",MS_RDONLY,&rejected)==-16 && !rejected); - assert(!storage_new_block_mount(ram_disk,UINT32_MAX,"ext4",0,&first)); - assert(!storage_new_block_mount(ram_disk,UINT32_MAX,"ext4",0,&second)); - assert(g_volumes[STORAGE_VOLUME_ROOT].vfs_mounts==2); - vfs_mount_put(first);vfs_mount_put(second); - assert(!storage_ready()); - storage_init_installer_root(&boot); - assert(test_last_direct_physical == TEST_RAMDISK_PHYS); - assert(!test_mm_mapping_calls); - assert(installer_lookup("/lost+found", &node) == 0); - assert(node.type == RELIEFOS_FS_TYPE_DIR); - prior_direct_calls = test_direct_mapping_calls; - - storage_init_installer_root(&boot); - assert(storage_installer_root_active() && storage_ready()); - assert(g_active_volume == &g_volumes[STORAGE_VOLUME_ROOT]); - assert(g_volumes[STORAGE_VOLUME_ROOT].device_ref.device && storage_volume_device_number(&g_volumes[STORAGE_VOLUME_ROOT])==0x100); - assert(test_last_direct_physical == TEST_RAMDISK_PHYS); - assert(test_direct_mapping_calls == prior_direct_calls); - assert(!test_mm_mapping_calls); - uint8_t sector[512];assert(!storage_read_device(&g_volumes[STORAGE_VOLUME_ROOT],2,1,sector)); - assert(!memcmp(test_ramdisk_bytes+1024,sector,sizeof(sector))); - assert(installer_lookup("/lost+found", &node) == 0); - assert(node.type == RELIEFOS_FS_TYPE_DIR); - /* The temporary graph was the final native membership. Its context and - * provider reference retire; reserved Multiboot backing is still intact. */ - assert(!storage_ready() && !g_volumes[STORAGE_VOLUME_ROOT].fs_type.type); - - legacy_boot = test_boot_info("leonos-installer-root"); - prior_direct_calls = test_direct_mapping_calls; - storage_init_installer_root(&legacy_boot); - assert(storage_installer_root_active() && storage_ready()); - assert(g_volumes[STORAGE_VOLUME_ROOT].device_ref.device && storage_volume_device_number(&g_volumes[STORAGE_VOLUME_ROOT])==0x100); - assert(test_last_direct_physical == TEST_RAMDISK_PHYS); - assert(test_direct_mapping_calls == prior_direct_calls); - assert(!test_mm_mapping_calls); -} - -/** @brief Check missing and unmappable modules leave no stale mounted root. */ -static void test_installer_ramdisk_failure_cleanup(void) -{ - struct boot_info boot = test_boot_info("wrong-root-name"); - - g_volumes[STORAGE_VOLUME_ROOT].ready = true; - g_volumes[STORAGE_VOLUME_BOOT].ready = true; - g_active_volume = &g_volumes[STORAGE_VOLUME_BOOT]; - g_installer_root_active = 1; - storage_init_installer_root(&boot); - assert(!storage_ready() && !storage_installer_root_active()); - assert(g_active_volume == &g_volumes[STORAGE_VOLUME_ROOT]); - assert(!g_volumes[STORAGE_VOLUME_ROOT].ready && !g_volumes[STORAGE_VOLUME_BOOT].ready); - - g_volumes[STORAGE_VOLUME_ROOT].ready = true; - g_volumes[STORAGE_VOLUME_BOOT].ready = true; - g_active_volume = &g_volumes[STORAGE_VOLUME_BOOT]; - storage_mount_boot_root(&boot, true); - assert(!storage_ready() && !storage_installer_root_active()); - assert(g_active_volume == &g_volumes[STORAGE_VOLUME_ROOT]); - assert(!g_volumes[STORAGE_VOLUME_ROOT].ready && !g_volumes[STORAGE_VOLUME_BOOT].ready); - test_direct_map_reject = false; -} - -/** @brief Exercise installer module mapping, failure cleanup, and image lifetime. */ -#include "../../fs/fat/type.c" -#include "../../fs/exfat/type.c" -#include "../../fs/ext4/type.c" -#include "../../fs/ext2/type.c" -#include "../../fs/iso9660/type.c" -/* Real registration is explicit in the image-construction fixtures; codec-only - * fixtures can keep raw parsers independently linked. */ -static void storage_fixture_register_filesystems(void) -{ - assert(!fat_register_filesystem());assert(!exfat_register_filesystem()); - assert(!ext2_register_filesystem());assert(!ext4_register_filesystem());assert(!iso_register_filesystem()); -} - -int main(int argc, char **argv) -{ - storage_fixture_register_filesystems(); - assert(argc == 2); - load_test_image(argv[1]); - struct boot_info rejected=test_boot_info("reliefos-installer-root"); - test_direct_map_reject=true; - storage_init_installer_root(&rejected); - assert(!storage_ready() && !storage_installer_root_active() && test_direct_range_calls==1); - test_direct_map_reject=false; - test_installer_ramdisk_mount_paths(); - test_installer_ramdisk_failure_cleanup(); - puts("PASS installer ramdisk module mapping, boot-root paths, cleanup, and lifetime"); - return 0; -} - -/* This filesystem fixture keeps the real sound namespace parsers, with - * hardware inventory deliberately absent. Admission/lifetime is covered by the - * service suites; these boundary adapters preserve the original parser calls. */ -int sound_service_timer_node(const char *name,struct storage_node *out) -{return storage_audio_timer_node(name,out);} -int sound_service_control_node(const char *name,struct storage_node *out) -{return storage_audio_control_node(name,out);} -int sound_service_pcm_node(const char *name,struct storage_node *out) -{return storage_audio_pcm_node(name,out);} -int sound_service_snd_readdir(uint64_t *cursor,struct reliefos_dir_entry *entry) -{return storage_audio_snd_readdir(cursor,entry);} - -/* Permanent proc inventory and real sound namespace share this fixture's - * deliberately empty hardware-card inventory; no sound implementation is faked. */ -int sound_service_card_snapshot(uint32_t index,uint32_t *out_id,struct audio_card_identity *identity) -{return audio_card_snapshot(index,out_id,identity);} diff --git a/tools/tests/linux_inventory_test.c b/tools/tests/linux_inventory_test.c index 41a5fcb2..047720c8 100644 --- a/tools/tests/linux_inventory_test.c +++ b/tools/tests/linux_inventory_test.c @@ -580,19 +580,19 @@ int main(void) read_value("/sys/devices/virtual/net/lo/ifindex", value, sizeof(value)); assert(!strcmp(value, "1\n")); assert(proc_lookup("/sys/dev/block", &node) == 0 && node.type == RELIEFOS_FS_TYPE_DIR); - read_value("/sys/devices/platform/leonos-block/sda/dev", value, sizeof(value)); + read_value("/sys/devices/platform/reliefos-block/sda/dev", value, sizeof(value)); assert(!strcmp(value, "259:0\n")); - read_value("/sys/devices/platform/leonos-block/sda/sda1/partition", value, sizeof(value)); + read_value("/sys/devices/platform/reliefos-block/sda/sda1/partition", value, sizeof(value)); assert(!strcmp(value, "1\n")); - read_value("/sys/devices/platform/leonos-block/sda/sda1/size", value, sizeof(value)); + read_value("/sys/devices/platform/reliefos-block/sda/sda1/size", value, sizeof(value)); assert(!strcmp(value, "32768\n")); - read_value("/sys/devices/platform/leonos-block/sda/uevent", value, sizeof(value)); + read_value("/sys/devices/platform/reliefos-block/sda/uevent", value, sizeof(value)); assert(!strcmp(value, "MAJOR=259\nMINOR=0\nDEVNAME=sda\nDEVTYPE=disk\nDISKSEQ=16\n")); const char disk_properties[] = "MAJOR=259\0MINOR=0\0DEVNAME=sda\0DEVTYPE=disk\0DISKSEQ=16\0"; check_device_uevent("class/block/sda/uevent", "block", disk_properties, sizeof(disk_properties) - 1); assert(proc_readlink("/sys/dev/block/259:1", value, sizeof(value)) > 0); - check_block_subsystem("dev/block/259:0", "/devices/platform/leonos-block/sda"); - check_block_subsystem("dev/block/259:1", "/devices/platform/leonos-block/sda/sda1"); + check_block_subsystem("dev/block/259:0", "/devices/platform/reliefos-block/sda"); + check_block_subsystem("dev/block/259:1", "/devices/platform/reliefos-block/sda/sda1"); fixture_block_pci=true; read_value("/sys/devices/pci0000:00/0000:00:03.0/block/sda/dev",value,sizeof(value)); assert(!strcmp(value,"259:0\n")); @@ -613,11 +613,11 @@ int main(void) assert(!strcmp(value,"259:128\n") && !fixture_refs); fixture_second_pci=false; fixture_slot=2; - read_value("/sys/devices/platform/leonos-block/sda/dev",value,sizeof(value)); + read_value("/sys/devices/platform/reliefos-block/sda/dev",value,sizeof(value)); fixture_slot=9; - read_value("/sys/devices/platform/leonos-block/sda/dev",value,sizeof(value)); + read_value("/sys/devices/platform/reliefos-block/sda/dev",value,sizeof(value)); fixture_slot=3;fixture_transport=BLOCK_TRANSPORT_NVME; - read_value("/sys/devices/platform/leonos-block/sda/dev",value,sizeof(value)); + read_value("/sys/devices/platform/reliefos-block/sda/dev",value,sizeof(value)); assert(!fixture_refs); fixture_transport=BLOCK_TRANSPORT_AHCI; fixture_block_pci=false; @@ -763,9 +763,9 @@ int main(void) fixture_drm_present = false; assert(proc_readlink("/sys/class/dmi/id", value, 3) == 3 && !memcmp(value, "../", 3)); fixture_ram=true; - read_value("/sys/devices/platform/leonos-block/ram0/dev",value,sizeof(value)); + read_value("/sys/devices/platform/reliefos-block/ram0/dev",value,sizeof(value)); assert(!strcmp(value,"1:0\n")); - read_value("/sys/devices/platform/leonos-block/ram0/uevent",value,sizeof(value)); + read_value("/sys/devices/platform/reliefos-block/ram0/uevent",value,sizeof(value)); assert(strstr(value,"MAJOR=1\nMINOR=0\nDEVNAME=ram0\n")); assert(proc_lookup("/sys/dev/block/1:0",&node)==0 && node.type==RELIEFOS_FS_TYPE_SYMLINK); walk("/sys", 0); diff --git a/tools/tests/module_drm_probe.c b/tools/tests/module_drm_probe.c index a3b67178..7f58dea0 100644 --- a/tools/tests/module_drm_probe.c +++ b/tools/tests/module_drm_probe.c @@ -60,7 +60,7 @@ static void load_modalias(void) closedir(directory);if(!alias[0])fail("find actual VirtIO-GPU PCI alias"); alias[strcspn(alias,"\r\n")]=0; pid_t child=fork();if(child<0)fail("fork alias modprobe"); - if(!child){execl("/qa-busybox","busybox","modprobe","-b",alias,(char *)NULL);_exit(127);} + if(!child){execl("/usr/bin/kmod","kmod","modprobe","-b",alias,(char *)NULL);_exit(127);} int status;if(waitpid(child,&status,0)!=child || !WIFEXITED(status) || WEXITSTATUS(status))fail("native PCI alias modprobe"); } /** @brief Let real queues progress until nonblocking unload succeeds or times out. diff --git a/tools/tests/module_hda_probe.c b/tools/tests/module_hda_probe.c index 8ae6c920..e0bad87e 100644 --- a/tools/tests/module_hda_probe.c +++ b/tools/tests/module_hda_probe.c @@ -60,13 +60,13 @@ static void playback(void) int status;require(waitpid(child,&status,0)==child && WIFEXITED(status) && !WEXITSTATUS(status),"ALSA playback child"); } /** @brief Exercise actual target modprobe dependency resolution against this release. - * Guest-only task context. The staged BusyBox and indexed module tree are real + * Guest-only task context. The staged kmod and indexed module tree are real * production artifacts; the probe provides no substitute module dependency map. */ static void modprobe_hda(void) { pid_t child=fork();require(child>=0,"fork native modprobe"); - if(!child){execl("/qa-busybox","busybox","modprobe","hda",(char *)NULL);_exit(127);} + if(!child){execl("/usr/bin/kmod","kmod","modprobe","hda",(char *)NULL);_exit(127);} int status;require(waitpid(child,&status,0)==child && WIFEXITED(status) && !WEXITSTATUS(status),"native modprobe hard dependency"); } /** @brief Test real sound-core/HDA ownership through playback and final VMA release. diff --git a/tools/tests/module_lifecycle_test.c b/tools/tests/module_lifecycle_test.c index 78a8be2e..a676bb1f 100644 --- a/tools/tests/module_lifecycle_test.c +++ b/tools/tests/module_lifecycle_test.c @@ -120,7 +120,7 @@ int main(int argc,char **argv) assert(rc==-12);assert(!host_live_heap && !host_live_maps);assert(fail<200); } /* Linux 6.12 ignores delete_module flag bits with force-unload disabled. - * BusyBox supplies O_EXCL by default; none may bypass real external users. */ + * O_EXCL must not bypass real external users. */ const unsigned unload_flags[]={0x800u|0x80u,0x200u,0x80000000u,~0u}; for(unsigned flag=0;flag= 2208988800LL && now.tv_sec < 2208988900LL, "NTP era 2040 and actual CLOCK_REALTIME update"); printf("[network] clock=%lld.%09ld ntp-status=%u\n", (long long)now.tv_sec, now.tv_nsec, sync.status); - char *wget[] = {"/bin/busybox", "wget", "-O", "/tmp/net-download", "http://fixture.test:18080/payload", NULL}; - CHECK(run(wget) == 0, "official BusyBox HTTP download"); + char *wget[] = {"/usr/bin/curl", "--fail", "--output", "/tmp/net-download", "http://fixture.test:18080/payload", NULL}; + CHECK(run(wget) == 0, "HTTP download with curl"); FILE *download = fopen("/tmp/net-download", "rb"); unsigned count = 0; int byte, valid = !!download; diff --git a/tools/tests/signal_wake_test.c b/tools/tests/signal_wake_test.c index 139195c9..8cdd1598 100644 --- a/tools/tests/signal_wake_test.c +++ b/tools/tests/signal_wake_test.c @@ -386,10 +386,47 @@ static void test_pi_signal_restart(void) discard_fixture(); } +/** @brief Check init's default, blocked and caught signal dispositions. */ +static void test_init_signal_dispositions(void) +{ + struct task *task = start_fixture(); + task->pid = 1; + task->tgid = 1; + current_pid[0] = 1; + + const int defaults[] = {9, 12, 15, 19}; + for (size_t i = 0; i < sizeof(defaults) / sizeof(defaults[0]); ++i) { + assert(kernel_signal_queue_task(task, defaults[i]) == 0); + assert(sched_signal_user_process(1, defaults[i]) == 0); + assert(task->state == TASK_RUNNING && !sched_task_pending(task)); + } + + const uint64_t term = 1ULL << (15 - 1); + struct linux_siginfo info; + task->blocked_signals = term; + assert(sched_signal_user_process(1, 15) == 0); + assert(sched_task_pending(task) & term); + assert(kernel_signal_dequeue(task, term, &info) == 15); + assert(kernel_signal_queue_task(task, 15) == 0); + assert(kernel_signal_dequeue(task, term, &info) == 15); + + task->blocked_signals = 0; + sched_task_actions(task)[15] = (struct kernel_signal_action){ + .handler = RELIEFNT_USER_BASE + 0x2000, + .restorer = RELIEFNT_USER_BASE + 0x3000, + }; + struct trap_frame frame = task->frame; + assert(kernel_signal_queue_task(task, 15) == 0); + assert(kernel_signal_deliver_pending(task, &frame) == 1); + assert(frame.rip == RELIEFNT_USER_BASE + 0x2000 && frame.rdi == 15); + discard_fixture(); +} + int main(void) { test_running_signal_then_untimed_futex_park(); test_pi_signal_restart(); + test_init_signal_dispositions(); puts("PASS signal delivery wakes a parked SA_RESTART untimed private futex and preserves scheduler ownership"); return 0; } diff --git a/tools/tests/squashfs_boot_modules_test.c b/tools/tests/squashfs_boot_modules_test.c deleted file mode 100644 index 27a06124..00000000 --- a/tools/tests/squashfs_boot_modules_test.c +++ /dev/null @@ -1,95 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 */ -#include -#include -#include -#include -#include -#include -#include -#include - -static uint8_t root_bytes[1024]; -static uint8_t payload_bytes[513]; -static struct block_device_registration registrations[2]; -static unsigned registration_count; - -bool paging_kernel_direct_map_range(uint64_t physical,uint64_t length) -{ - if(physical==0x100000u)return length<=sizeof(root_bytes); - if(physical==0x200000u)return length<=sizeof(payload_bytes); - return false; -} - -void *paging_kernel_direct_map(uint64_t physical) -{ - if(physical==0x100000u)return root_bytes; - if(physical==0x200000u)return payload_bytes; - return NULL; -} - -int register_block_device(const struct block_device_registration *registration) -{ - assert(registration && registration_count<2); - registrations[registration_count++]=*registration; - return 0; -} - -int main(void) -{ - memcpy(root_bytes,"root",4); - memcpy(payload_bytes,"squashfs",8); - const struct boot_module modules[]={ - {0x100000u,0x100400u,"reliefos-installer-root"}, - {0x200000u,0x200201u,"reliefos-installer-payload"} - }; - struct boot_info boot={.module_count=2}; - memcpy(boot.modules,modules,sizeof(modules)); - uint64_t root_device=0; - boot.modules[1].end=boot.modules[1].start+1; - assert(block_boot_image_register(&boot,&root_device)==-ENOEXEC); - assert(root_device==0 && registration_count==0); - boot.modules[1]=(struct boot_module){0x100000u,0x100201u,"reliefos-installer-payload"}; - assert(block_boot_image_register(&boot,&root_device)==-ENOEXEC); - assert(root_device==0 && registration_count==0); - boot.modules[1]=modules[1]; - assert(block_boot_image_register(&boot,&root_device)==2); - assert(root_device==block_device_make_number(1,0)); - assert(registration_count==2); - assert(registrations[0].info.device==block_device_make_number(1,0)); - assert(registrations[0].info.controller==0); - assert(registrations[0].info.blocks==2); - assert(!(registrations[0].info.flags&BLOCK_DEVICE_READ_ONLY)); - assert(registrations[1].info.device==block_device_make_number(1,1)); - assert(registrations[1].info.controller==1); - assert(registrations[1].info.blocks==2); - assert(registrations[1].info.flags&BLOCK_DEVICE_READ_ONLY); - assert(registrations[1].operations->write==NULL); - uint8_t readback[1024]; - assert(registrations[1].operations->read(registrations[1].context,0,2,readback)==0); - assert(!memcmp(readback,"squashfs",8)); - for(size_t i=513;iread(registrations[1].context,2,1,readback)==-EINVAL); - memset(readback,0xa5,512); - assert(registrations[0].operations->write(registrations[0].context,1,1,readback)==0); - assert(!memcmp(root_bytes+512,readback,512)); - - boot.module_count=1; - assert(block_boot_image_register(&boot,&root_device)==1); - assert(root_device==block_device_make_number(1,0) && registration_count==2); - - boot.module_count=2; - boot.modules[1]=boot.modules[0]; - assert(block_boot_image_register(&boot,&root_device)==-EEXIST); - assert(root_device==0 && registration_count==2); - - boot.module_count=1; - boot.modules[0]=modules[1]; - assert(block_boot_image_register(&boot,&root_device)==1); - assert(root_device==0 && registration_count==2); - - boot.module_count=0; - assert(block_boot_image_register(&boot,&root_device)==0); - assert(root_device==0 && registration_count==2); - puts("PASS SquashFS boot module registration: ram0 root, read-only ram1 payload, padded tail, duplicate and malformed modules"); - return 0; -} diff --git a/tools/tests/syscall_io_test.c b/tools/tests/syscall_io_test.c index 38c560dc..0081cc42 100644 --- a/tools/tests/syscall_io_test.c +++ b/tools/tests/syscall_io_test.c @@ -45,7 +45,6 @@ static _Noreturn int io_unexpected(const char *name, ...) #define task_shm_write IO_UNAVAILABLE #define task_shm_read IO_UNAVAILABLE #define task_effective_role IO_UNAVAILABLE -#define storage_installer_root_active IO_UNAVAILABLE static struct task_file *io_expected_regular; static bool io_expected_writing; static uint8_t user_bytes[131072]; diff --git a/tools/tests/user_mmap_arena_test.c b/tools/tests/user_mmap_arena_test.c index 307e35e4..cc263cd4 100644 --- a/tools/tests/user_mmap_arena_test.c +++ b/tools/tests/user_mmap_arena_test.c @@ -4,7 +4,7 @@ #include -/* Regression fixture for the Alpine Clang dynamic-link failure. +/* Regression fixture for the Clang dynamic-link failure. * * musl's ldso reserves one whole PT_LOAD span per shared object with a single * mmap (map_library in third_party/musl/ldso/dynlink.c), so a program's diff --git a/tools/tests/vdso_auxv_test.c b/tools/tests/vdso_auxv_test.c index 222d23f5..129c596d 100644 --- a/tools/tests/vdso_auxv_test.c +++ b/tools/tests/vdso_auxv_test.c @@ -244,14 +244,7 @@ int main(void) } assert(count == 16 && aux[1] == 0 && seen_vdso == 1 && seen_random == 1); - task->dynamic_launch.abi_major = RELIEFOS_ELF_ABI_MAJOR; - assert(prepare_user_exec_stack(task, task->path, vdso) == 0); - assert(task->frame.rdi == 1 && task->frame.rsi == task->frame.rsp + 8); - assert(task->frame.rdx == task->frame.rsp + 24); - assert(task->frame.r8 > task->frame.rdx && task->frame.r8 < top); - struct reliefos_dynamic_launch launch; - memcpy(&launch, stack + (task->frame.r8 - (top - sizeof(stack))), sizeof(launch)); - assert(launch.abi_major == RELIEFOS_ELF_ABI_MAJOR && launch.main_entry == 0x400100); + assert(!task->frame.rdx && !task->frame.r8); task->uid = 1234; task->euid = 1235; task->gid = 2345; task->egid = 2346; expect_auxv_ids(task, (const uint32_t[]){1234, 1235, 2345, 2346}, true); diff --git a/tools/tests/vt_console_test.c b/tools/tests/vt_console_test.c index 13918347..103599ee 100644 --- a/tools/tests/vt_console_test.c +++ b/tools/tests/vt_console_test.c @@ -230,19 +230,19 @@ int main(void) assert(full_clear_count == boot_clear_count); assert(vt_text[0].length == boot_history_length + 5u); assert(memcmp(vt_text[0].bytes + boot_history_length, "init\n", 5) == 0); - static const char openrc_output[] = "\033[1;32mOpenRC\033[0m starting\r\n"; - size_t before_openrc = vt_text[0].length; - uint32_t before_openrc_present = text_present_count; - console_vt_write(1, openrc_output, sizeof(openrc_output) - 1u); + static const char init_output[] = "\033[1;32msystemd\033[0m starting\r\n"; + size_t before_init = vt_text[0].length; + uint32_t before_init_present = text_present_count; + console_vt_write(1, init_output, sizeof(init_output) - 1u); size_t before_serial_log = log_len; - console_serial_write_len(openrc_output, sizeof(openrc_output) - 1u); + console_serial_write_len(init_output, sizeof(init_output) - 1u); assert(log_len == before_serial_log); - size_t startup_history_length = before_openrc + sizeof(openrc_output) - 1u; + size_t startup_history_length = before_init + sizeof(init_output) - 1u; assert(vt_text[0].length == startup_history_length); - assert(memcmp(vt_text[0].bytes + before_openrc, openrc_output, - sizeof(openrc_output) - 1u) == 0); - assert(strstr(serial_output, openrc_output) != NULL); - assert(text_present_count == before_openrc_present + 1u); + assert(memcmp(vt_text[0].bytes + before_init, init_output, + sizeof(init_output) - 1u) == 0); + assert(strstr(serial_output, init_output) != NULL); + assert(text_present_count == before_init_present + 1u); assert(fb_col == 0 && fb_console_fg_color == console_fg()); assert(full_clear_count == boot_clear_count); uint32_t init_col = fb_col; @@ -254,7 +254,7 @@ int main(void) console_vt_activate(1, false); assert(vt_text[0].length == startup_history_length); assert(strstr(vt_text[0].bytes, "[INFO] [reliefnt] boot ready\ninit\n") != NULL); - assert(strstr(vt_text[0].bytes, openrc_output) != NULL); + assert(strstr(vt_text[0].bytes, init_output) != NULL); console_vt_activate(2, false); assert(fb_console_tty_cursor_visible && fb_console_tty_cursor_x == 0); console_vt_write(2, "a", 1); @@ -285,7 +285,7 @@ int main(void) assert(memcmp(before, pixels, sizeof(pixels)) == 0); assert(strstr(vt_text[0].bytes, graphical_output) != NULL); console_vt_activate(1, false); - assert(strstr(vt_text[0].bytes, openrc_output) != NULL); + assert(strstr(vt_text[0].bytes, init_output) != NULL); assert(strstr(vt_text[0].bytes, service_output) != NULL); assert(strstr(vt_text[0].bytes, graphical_output) != NULL); char key[8]; From 9e8697c126a3d7128af6a254d099ca13a657e169 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Wed, 2 Dec 2026 14:05:24 +0800 Subject: [PATCH 90/97] test: retire the musl guest harness and use the glibc loader --- tools/test_linux_memory.py | 12 +- tools/tests/elf_interpreter_test.c | 2 +- tools/tests/ipv6_control_test.c | 4 +- tools/tests/module_exec_runtime_probe.c | 2 +- tools/tests/module_runtime_probe.c | 6 +- tools/tests/musl_guest_test.c | 3071 ----------------------- 6 files changed, 16 insertions(+), 3081 deletions(-) delete mode 100644 tools/tests/musl_guest_test.c diff --git a/tools/test_linux_memory.py b/tools/test_linux_memory.py index 5dfbd31d..50bc9bb0 100644 --- a/tools/test_linux_memory.py +++ b/tools/test_linux_memory.py @@ -45,13 +45,19 @@ def test_physical_pages(self): subprocess.run([sys.executable, "tools/test_physical_metadata.py"], cwd=ROOT, check=True, timeout=30) def test_memory_ownership_and_elf_page_boundaries(self): + mount_vfs_sources = [ + "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", + "fs/vfs/open.c", "fs/vfs/attributes.c", "kernel/sched/user_namespace.c", + ] cases = (("paging_protection", []), ("private_anon_fault", ["kernel/exec/usercopy.c"]), ("memfd_truncate", ["mm/user/cache.c", "mm/user/mapping.c"]), ("elf_interpreter", []), - ("elf_sparse_reservation", ["fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c","fs/vfs/file.c", "fs/vfs/open.c","fs/vfs/attributes.c","fs/vfs/exec_file.c"]), - ("elf_file_page", ["mm/cache/page_cache.c","fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c","fs/vfs/file.c", "fs/vfs/open.c","fs/vfs/attributes.c","fs/vfs/exec_file.c"]), ("user_mmap_arena", []), + ("elf_sparse_reservation", [*mount_vfs_sources, "fs/vfs/exec_file.c"]), + ("elf_file_page", ["mm/cache/page_cache.c", *mount_vfs_sources, "fs/vfs/exec_file.c"]), + ("user_mmap_arena", []), ("mprotect_vma_growth", [*kernel_sources("scheduler"),"kernel/device/character.c","fs/vfs/lookup_cache.c","fs/vfs/file.c", "fs/vfs/open.c","fs/vfs/attributes.c","fs/vfs/exec_file.c"]), - ("brk_collision", [*kernel_sources("user_memory"),"kernel/syscall/memory/legacy_memory.c","kernel/syscall/memory/swap.c","fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c","fs/vfs/file.c", "fs/vfs/open.c","fs/vfs/attributes.c"])) + ("brk_collision", [*kernel_sources("user_memory"), "kernel/syscall/memory/legacy_memory.c", + "kernel/syscall/memory/swap.c", *mount_vfs_sources])) for name, sources in cases: with self.subTest(name=name), tempfile.TemporaryDirectory(prefix="reliefos-mm-") as tmp: executable = str(Path(tmp) / name) diff --git a/tools/tests/elf_interpreter_test.c b/tools/tests/elf_interpreter_test.c index 5e51109b..4b4f9c9b 100644 --- a/tools/tests/elf_interpreter_test.c +++ b/tools/tests/elf_interpreter_test.c @@ -69,7 +69,7 @@ int main(void) struct elf64_phdr *ph = (void *)(image + eh->e_phoff); ph[0] = (struct elf64_phdr){.p_type = PT_LOAD, .p_flags = 4u | PF_X, .p_vaddr = 0x400000, .p_filesz = sizeof(image), .p_memsz = sizeof(image), .p_align = 4096}; - const char path[] = "/lib/ld-musl-x86_64.so.1"; + const char path[] = "/lib64/ld-linux-x86-64.so.2"; memcpy(image + 512, path, sizeof(path)); ph[1] = (struct elf64_phdr){.p_type = PT_INTERP, .p_offset = 512, .p_filesz = sizeof(path)}; ph[2].p_type = PT_DYNAMIC; diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 08c4f1ac..845725ed 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -2334,7 +2334,7 @@ int main(void) } assert(found_eth); nic_ready=true; - /* musl and BusyBox issue rtgenmsg dumps, only one payload byte plus padding. */ + /* Accept rtgenmsg dumps with one payload byte plus padding. */ struct { struct nlmsghdr h; uint8_t family, pad[3]; } generic = { .h={.nlmsg_len=sizeof(generic),.nlmsg_type=RTM_GETLINK, .nlmsg_flags=NLM_F_REQUEST|NLM_F_DUMP,.nlmsg_seq=71},.family=AF_UNSPEC}; @@ -2450,7 +2450,7 @@ int main(void) task_netlink_release(&files[fd]); net_interface_remove(2); assert(!allocations); - puts("PASS route-netlink dumps/updates, musl requests, multicast/overflow, IPv6 ioctl and proc"); + puts("PASS route-netlink dumps/updates, rtgenmsg requests, multicast/overflow, IPv6 ioctl and proc"); return 0; } #else diff --git a/tools/tests/module_exec_runtime_probe.c b/tools/tests/module_exec_runtime_probe.c index 3733b600..0da62462 100644 --- a/tools/tests/module_exec_runtime_probe.c +++ b/tools/tests/module_exec_runtime_probe.c @@ -50,7 +50,7 @@ static void executable_directory_probe(void) require(directory>=0,"hold private executable directory"); copy_guest_file(directory,"program","/qa-init"); copy_guest_file(directory,"dynamic","/qa-exec-dynamic"); - copy_guest_file(directory,"loader.so","/lib/ld-musl-x86_64.so.1"); + copy_guest_file(directory,"loader.so","/lib64/ld-linux-x86-64.so.2"); require(!fchdir(directory),"enter executable directory before rename"); require(!rename("/dev/shm/exe-source","/dev/shm/exe-moved"),"rename held executable directory"); char *arguments[]={"program","--exec-path-child","/dev/shm/exe-moved/program",NULL}; diff --git a/tools/tests/module_runtime_probe.c b/tools/tests/module_runtime_probe.c index 74b6a4a9..269a7dc8 100644 --- a/tools/tests/module_runtime_probe.c +++ b/tools/tests/module_runtime_probe.c @@ -259,11 +259,11 @@ static void expect_metadata_contract(void) { int memory=(int)syscall(SYS_memfd_create,"module-metadata-contract",2u); require(memory>=0 && write(memory,"meta",4)==4,"populate metadata anonymous inode"); - struct linux_statx extended; + struct statx extended; require(!syscall(SYS_statx,memory,"",AT_EMPTY_PATH,0,&extended) && - (extended.stx_mask&LINUX_STATX_BASIC_STATS)==LINUX_STATX_BASIC_STATS && + (extended.stx_mask&STATX_BASIC_STATS)==STATX_BASIC_STATS && extended.stx_size==4,"statx accepts zero mask and reports available fields"); - require(!syscall(SYS_statx,memory,NULL,AT_EMPTY_PATH,LINUX_STATX_SIZE,&extended) && extended.stx_size==4, + require(!syscall(SYS_statx,memory,NULL,AT_EMPTY_PATH,STATX_SIZE,&extended) && extended.stx_size==4, "statx null empty-path descriptor"); errno=0;require(syscall(SYS_statx,memory,"",AT_EMPTY_PATH,0x80000000u,&extended)==-1 && errno==EINVAL, "statx reserved mask rejected"); diff --git a/tools/tests/musl_guest_test.c b/tools/tests/musl_guest_test.c deleted file mode 100644 index a88f2535..00000000 --- a/tools/tests/musl_guest_test.c +++ /dev/null @@ -1,3071 +0,0 @@ -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef PROBE_KIND -#define PROBE_KIND "dynamic" -#endif -#ifndef CLOSE_RANGE_CLOEXEC -#define CLOSE_RANGE_CLOEXEC (1U << 2) -#endif -#ifndef MFD_CLOEXEC -#define MFD_CLOEXEC 0x0001U -#endif -#ifndef MREMAP_MAYMOVE -#define MREMAP_MAYMOVE 1U -#endif -#ifndef PR_SET_NAME -#define PR_SET_NAME 15 -#define PR_GET_NAME 16 -#endif -static _Thread_local unsigned tls_value = 73; -static unsigned failed; -static volatile sig_atomic_t timer_callback_seen; - -#define CHECK(c) do { if (!(c)) { \ - printf("[musl-abi:" PROBE_KIND "] FAIL %s:%d %s errno=%d\n", \ - __func__, __LINE__, #c, errno); fflush(stdout); return 1; } } while (0) - -#define FUTEX2_EMBEDDED -#include "futex2_abi_test.c" -#define CLONE3_EMBEDDED -#include "clone3_abi_test.c" -#define SYMLINK_EMBEDDED -#include "symlink_abi_test.c" -#define SIGNAL_QUEUE_EMBEDDED -#include "signal_queue_abi_test.c" -#define SOCKET_BATCH_EMBEDDED -#include "socket_batch_abi_test.c" -#define SIGNALFD_EMBEDDED -#include "signalfd_abi_test.c" -#define PROCESS_VM_EMBEDDED -#include "process_vm_abi_test.c" -#define SYSV_MSG_EMBEDDED -#include "sysv_msg_abi_test.c" -#define SYSV_SEM_EMBEDDED -#include "sysv_sem_abi_test.c" -#define PRCTL_EMBEDDED -#include "prctl_abi_test.c" -#define UTSNAME_EMBEDDED -#include "utsname_abi_test.c" -#define MEMBARRIER_EMBEDDED -#include "membarrier_abi_test.c" -#define OPENAT2_EMBEDDED -#include "openat2_abi_test.c" - -static void timer_callback(union sigval value) -{ - (void)value; - timer_callback_seen = 1; -} - -static int timer_abi(void) -{ - timer_t timer; - struct sigevent none = {.sigev_notify = SIGEV_NONE}; - struct itimerspec spec = { - .it_value = {.tv_sec = 0, .tv_nsec = 20000000}, - }; - struct itimerspec old = {0}, current = {0}; - CHECK(timer_create(CLOCK_MONOTONIC, &none, &timer) == 0); - CHECK(timer_settime(timer, 0, &spec, &old) == 0); - CHECK(timer_gettime(timer, ¤t) == 0 && current.it_value.tv_sec >= 0); - CHECK(timer_getoverrun(timer) == 0); - CHECK(timer_delete(timer) == 0); - - timer_callback_seen = 0; - struct sigevent threaded = { - .sigev_notify = SIGEV_THREAD, - .sigev_notify_function = timer_callback, - }; - CHECK(timer_create(CLOCK_MONOTONIC, &threaded, &timer) == 0); - CHECK(timer_settime(timer, 0, &spec, NULL) == 0); - for (unsigned i = 0; i < 20 && !timer_callback_seen; ++i) - usleep(10000); - CHECK(timer_callback_seen); - CHECK(timer_delete(timer) == 0); - return 0; -} - - -static int rseq_abi(void) -{ - struct rseq area __attribute__((aligned(32))) = {0}; - CHECK(syscall(SYS_rseq, &area, sizeof(area), 0, RSEQ_SIG) == 0); - unsigned registered_cpu = UINT_MAX; - CHECK(syscall(SYS_getcpu, ®istered_cpu, NULL, NULL) == 0); - CHECK(area.cpu_id_start == registered_cpu && area.cpu_id == registered_cpu && - area.rseq_cs == 0); - /* A registered area follows the task when the scheduler moves it. This - * is the ABI that glibc's sched_getcpu() fast path reads directly. Keep - * the case optional for single-CPU guests, but exercise it whenever a - * second online CPU is available. */ - uint64_t original_affinity = 0; - unsigned current_cpu = registered_cpu, target_cpu = UINT_MAX; - CHECK(syscall(SYS_sched_getaffinity, 0, sizeof(original_affinity), - &original_affinity) == (long)sizeof(original_affinity)); - for (unsigned cpu = 0; cpu < sizeof(original_affinity) * 8; ++cpu) { - if ((original_affinity & (UINT64_C(1) << cpu)) && cpu != current_cpu) { - target_cpu = cpu; - break; - } - } - if (target_cpu != UINT_MAX) { - uint64_t target_affinity = UINT64_C(1) << target_cpu; - CHECK(syscall(SYS_sched_setaffinity, 0, sizeof(target_affinity), - &target_affinity) == 0); - for (unsigned attempt = 0; attempt < 2000; ++attempt) { - CHECK(syscall(SYS_getcpu, ¤t_cpu, NULL, NULL) == 0); - if (current_cpu == target_cpu && area.cpu_id_start == target_cpu && - area.cpu_id == target_cpu) - break; - sched_yield(); - } - CHECK(current_cpu == target_cpu && area.cpu_id_start == target_cpu && - area.cpu_id == target_cpu); - CHECK(syscall(SYS_sched_setaffinity, 0, sizeof(original_affinity), - &original_affinity) == 0); - } - CHECK(syscall(SYS_rseq, &area, sizeof(area), 0, RSEQ_SIG) == -1 && errno == EBUSY); - CHECK(syscall(SYS_rseq, &area, sizeof(area), 0, RSEQ_SIG ^ 1U) == -1 && errno == EPERM); - CHECK(syscall(SYS_rseq, &area, sizeof(area), RSEQ_FLAG_UNREGISTER, RSEQ_SIG ^ 1U) == -1 && errno == EPERM); - CHECK(syscall(SYS_rseq, &area, sizeof(area), RSEQ_FLAG_UNREGISTER, RSEQ_SIG) == 0); - CHECK(area.cpu_id_start == (uint32_t)RSEQ_CPU_ID_UNINITIALIZED && - area.cpu_id == (uint32_t)RSEQ_CPU_ID_UNINITIALIZED); - CHECK(syscall(SYS_rseq, (void *)((uintptr_t)&area + 1), sizeof(area), 0, RSEQ_SIG) == -1 && errno == EINVAL); - CHECK(syscall(SYS_rseq, &area, RSEQ_SIZE - 1, 0, RSEQ_SIG) == -1 && errno == EINVAL); - return 0; -} - -static int memfd_abi(void) -{ - int fd = syscall(SYS_memfd_create, "musl-abi-memfd", MFD_CLOEXEC); - CHECK(fd >= 0); - struct stat st; - CHECK(fstat(fd, &st) == 0 && st.st_size == 0); - CHECK(ftruncate(fd, 4096) == 0); - CHECK(write(fd, "memfd", 5) == 5); - CHECK(lseek(fd, 0, SEEK_SET) == 0); - char contents[6] = {0}; - CHECK(read(fd, contents, 5) == 5 && !memcmp(contents, "memfd", 5)); - unsigned char *mapping = mmap(NULL, 4096, PROT_READ | PROT_WRITE, - MAP_SHARED, fd, 0); - CHECK(mapping != MAP_FAILED); - CHECK(!memcmp(mapping, "memfd", 5)); - mapping[5] = '!'; - CHECK(munmap(mapping, 4096) == 0); - CHECK(fcntl(fd, F_GETFD) & FD_CLOEXEC); - CHECK(close(fd) == 0); - return 0; -} - -static int epoll_abi(void) -{ - int pipefd[2]; - CHECK(pipe(pipefd) == 0); - int epfd = syscall(SYS_epoll_create1, EPOLL_CLOEXEC); - CHECK(epfd >= 0); - struct epoll_event event = {.events = EPOLLIN, .data.u64 = 0xfeedbeef}; - CHECK(syscall(SYS_epoll_ctl, epfd, EPOLL_CTL_ADD, pipefd[0], &event) == 0); - struct epoll_event output = {0}; - CHECK(syscall(SYS_epoll_wait, epfd, &output, 1, 0) == 0); - CHECK(write(pipefd[1], "e", 1) == 1); - CHECK(syscall(SYS_epoll_wait, epfd, &output, 1, 100) == 1); - CHECK((output.events & EPOLLIN) && output.data.u64 == 0xfeedbeef); - char byte; - CHECK(read(pipefd[0], &byte, 1) == 1 && byte == 'e'); - event.events = EPOLLIN | EPOLLONESHOT; - CHECK(syscall(SYS_epoll_ctl, epfd, EPOLL_CTL_MOD, pipefd[0], &event) == 0); - CHECK(write(pipefd[1], "e", 1) == 1); - CHECK(syscall(SYS_epoll_wait, epfd, &output, 1, 100) == 1); - CHECK(syscall(SYS_epoll_wait, epfd, &output, 1, 0) == 0); - CHECK(syscall(SYS_epoll_ctl, epfd, EPOLL_CTL_DEL, pipefd[0], NULL) == 0); - CHECK(close(epfd) == 0 && close(pipefd[0]) == 0 && close(pipefd[1]) == 0); - return 0; -} - -static int timerfd_abi(void) -{ - int fd = syscall(SYS_timerfd_create, CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK); - struct itimerspec value = {0}, current = {0}; - uint64_t expirations = 0; - struct pollfd pfd; - CHECK(fd >= 0); - value.it_value.tv_nsec = 20 * 1000 * 1000; - value.it_interval.tv_nsec = 20 * 1000 * 1000; - CHECK(syscall(SYS_timerfd_settime, fd, 0, &value, NULL) == 0); - CHECK(syscall(SYS_timerfd_gettime, fd, ¤t) == 0 && current.it_value.tv_sec >= 0); - pfd = (struct pollfd){.fd = fd, .events = POLLIN}; - CHECK(poll(&pfd, 1, 200) == 1 && (pfd.revents & POLLIN)); - CHECK(read(fd, &expirations, sizeof(expirations)) == sizeof(expirations) && expirations >= 1); - CHECK(syscall(SYS_timerfd_settime, fd, 0, &(struct itimerspec){0}, NULL) == 0); - CHECK(close(fd) == 0); - return 0; -} - -static int capabilities_abi(void) -{ - struct __user_cap_header_struct header = { - .version = _LINUX_CAPABILITY_VERSION_3, - .pid = 0, - }; - struct __user_cap_data_struct data[2] = {{0}}; - CHECK(syscall(SYS_capget, &header, data) == 0); - if (data[0].permitted & (1u << CAP_CHOWN)) { - CHECK((data[0].effective & (1u << CAP_SETUID)) != 0); - uint32_t old = data[0].effective; - data[0].effective &= ~(1u << CAP_CHOWN); - CHECK(syscall(SYS_capset, &header, data) == 0); - __builtin_memset(data, 0, sizeof(data)); - CHECK(syscall(SYS_capget, &header, data) == 0 && data[0].effective == (old & ~(1u << CAP_CHOWN))); - data[0].effective = old; - CHECK(syscall(SYS_capset, &header, data) == 0); - } else { - data[0].effective = 1u << CAP_CHOWN; - CHECK(syscall(SYS_capset, &header, data) == -1 && errno == EPERM); - } - return 0; -} - -static int flock_abi(void) -{ - char path[64]; - snprintf(path, sizeof(path), "/tmp/musl-flock-%ld", (long)getpid()); - int first = open(path, O_CREAT | O_RDWR | O_TRUNC, 0600); - CHECK(first >= 0); - int second = open(path, O_RDWR); - CHECK(second >= 0); - CHECK(flock(first, LOCK_EX | LOCK_NB) == 0); - CHECK(flock(second, LOCK_EX | LOCK_NB) == -1 && errno == EWOULDBLOCK); - CHECK(flock(second, LOCK_SH | LOCK_NB) == -1 && errno == EWOULDBLOCK); - int duplicate = dup(first); - CHECK(duplicate >= 0); - CHECK(flock(duplicate, LOCK_UN) == 0); - CHECK(flock(second, LOCK_EX | LOCK_NB) == 0); - CHECK(close(first) == 0); - CHECK(flock(second, LOCK_UN) == 0); - CHECK(close(duplicate) == 0 && close(second) == 0); - CHECK(unlink(path) == 0); - return 0; -} - -static int link_abi(void) -{ - char source[64], target[64]; - snprintf(source, sizeof(source), "/tmp/musl-link-%ld", (long)getpid()); - snprintf(target, sizeof(target), "/tmp/musl-link-%ld.hard", (long)getpid()); - int fd = open(source, O_CREAT | O_RDWR | O_TRUNC, 0600); - CHECK(fd >= 0); - CHECK(write(fd, "link", 4) == 4); - CHECK(syscall(SYS_link, source, target) == 0); - struct stat first, second; - CHECK(fstat(fd, &first) == 0 && stat(target, &second) == 0); - CHECK(first.st_ino == second.st_ino && second.st_nlink >= 2); - CHECK(lseek(fd, 0, SEEK_SET) == 0); - char content[5] = {0}; - CHECK(read(fd, content, 4) == 4 && !memcmp(content, "link", 4)); - CHECK(unlink(source) == 0); - CHECK(stat(target, &second) == 0 && second.st_nlink == 1); - CHECK(lseek(fd, 0, SEEK_SET) == 0); - memset(content, 0, sizeof(content)); - CHECK(read(fd, content, 4) == 4 && !memcmp(content, "link", 4)); - CHECK(unlink(target) == 0 && close(fd) == 0); - return 0; -} - -static int startup(int argc, char **argv) -{ - CHECK(argc >= 1 && argv && argv[argc] == NULL); - CHECK(getauxval(AT_PAGESZ) == 4096); - CHECK(getauxval(AT_PHDR) && getauxval(AT_PHNUM) && getauxval(AT_RANDOM)); - uid_t ruid, euid, suid; - gid_t rgid, egid, sgid; - CHECK(syscall(SYS_getresuid, &ruid, &euid, &suid) == 0); - CHECK(ruid == getuid() && euid == geteuid()); - CHECK(syscall(SYS_getresgid, &rgid, &egid, &sgid) == 0); - CHECK(rgid == getgid() && egid == getegid()); - CHECK(syscall(SYS_setreuid, (unsigned)-1, (unsigned)euid) == 0); - CHECK(syscall(SYS_setregid, (unsigned)-1, (unsigned)egid) == 0); - CHECK(syscall(SYS_setresuid, (unsigned)-1, (unsigned)-1, (unsigned)-1) == 0); - CHECK(syscall(SYS_setresgid, (unsigned)-1, (unsigned)-1, (unsigned)-1) == 0); - CHECK(syscall(SYS_setfsuid, geteuid()) == geteuid()); - CHECK(syscall(SYS_setfsgid, getegid()) == getegid()); - CHECK(syscall(SYS_sched_get_priority_max, SCHED_OTHER) == 0); - CHECK(syscall(SYS_sched_get_priority_min, SCHED_OTHER) == 0); - CHECK(syscall(SYS_sched_get_priority_max, SCHED_FIFO) == 99); - CHECK(syscall(SYS_sched_get_priority_min, SCHED_RR) == 1); - CHECK(syscall(SYS_sched_get_priority_max, 4) == -1 && errno == EINVAL); - struct sched_param sched_value = {.sched_priority = -1}; - CHECK(syscall(SYS_sched_getparam, 0, &sched_value) == 0 && sched_value.sched_priority == 0); - CHECK(syscall(SYS_sched_getscheduler, 0) == SCHED_OTHER); - sched_value.sched_priority = 0; - CHECK(syscall(SYS_sched_setparam, 0, &sched_value) == 0); - CHECK(syscall(SYS_sched_setscheduler, 0, SCHED_OTHER, &sched_value) == SCHED_OTHER); - sched_value.sched_priority = 1; - CHECK(syscall(SYS_sched_setparam, 0, &sched_value) == -1 && errno == EINVAL); - CHECK(syscall(SYS_sched_setscheduler, 0, SCHED_FIFO, &sched_value) == -1 && errno == EINVAL); - struct sched_attr sched_attr_value = { - .size = sizeof(struct sched_attr), - .sched_policy = SCHED_OTHER, - }; - CHECK(syscall(SYS_sched_getattr, 0, &sched_attr_value, - sizeof(sched_attr_value), 0) == 0 && - sched_attr_value.size == sizeof(struct sched_attr) && - sched_attr_value.sched_policy == SCHED_OTHER && - sched_attr_value.sched_priority == 0 && - sched_attr_value.sched_nice == 0); - sched_attr_value.sched_nice = 3; - CHECK(syscall(SYS_sched_setattr, 0, &sched_attr_value, - 0, 0) == 0); - sched_attr_value = (struct sched_attr){.size = sizeof(struct sched_attr)}; - CHECK(syscall(SYS_sched_getattr, 0, &sched_attr_value, - sizeof(sched_attr_value), 0) == 0 && sched_attr_value.sched_nice == 3); - sched_attr_value.size = SCHED_ATTR_SIZE_VER0; - sched_attr_value.sched_nice = 0; - CHECK(syscall(SYS_sched_setattr, 0, &sched_attr_value, - 0, 0) == 0); - CHECK(syscall(SYS_sched_getattr, 0, &sched_attr_value, - SCHED_ATTR_SIZE_VER0 - 1, 0) == -1 && errno == EINVAL); - sched_attr_value.sched_policy = SCHED_FIFO; - CHECK(syscall(SYS_sched_setattr, 0, &sched_attr_value, - 0, 0) == -1 && errno == EINVAL); - sched_attr_value.sched_policy = SCHED_OTHER; - CHECK(syscall(SYS_sched_setattr, 0, &sched_attr_value, 1, 0) == -1 && errno == EINVAL); - struct timespec rr_interval; - CHECK(syscall(SYS_sched_rr_get_interval, 0, &rr_interval) == 0 && - rr_interval.tv_sec == 0 && rr_interval.tv_nsec > 0 && rr_interval.tv_nsec <= 1000000000L); - CHECK(syscall(SYS_sched_rr_get_interval, 0x7fffffff, &rr_interval) == -1 && errno == ESRCH); - CHECK(syscall(SYS_personality, (unsigned long)-1) == 0); - CHECK(syscall(SYS_personality, 0) == 0); - CHECK(syscall(SYS_personality, 0x0040000UL) == -1 && errno == EINVAL); - char task_name[16] = {0}; - CHECK(syscall(SYS_prctl, PR_SET_NAME, "abi-probe-name") == 0); - CHECK(syscall(SYS_prctl, PR_GET_NAME, task_name) == 0 && - !strcmp(task_name, "abi-probe-name")); - CHECK(run_utsname_abi_test() == 0); - CHECK(run_membarrier_abi_test() == 0); - CHECK(run_openat2_abi_test() == 0); - CHECK(timer_abi() == 0); - CHECK(memfd_abi() == 0); - CHECK(epoll_abi() == 0); - CHECK(timerfd_abi() == 0); - CHECK(flock_abi() == 0); - CHECK(link_abi() == 0); - struct timespec invalid_clock = {.tv_sec = 0, .tv_nsec = 1000000000L}; - CHECK(syscall(SYS_clock_settime, CLOCK_REALTIME, &invalid_clock) == -1 && errno == EINVAL); - CHECK(syscall(SYS_sched_getparam, 0x7fffffff, &sched_value) == -1 && errno == ESRCH); - unsigned char *remap = mmap(NULL, 4096, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(remap != MAP_FAILED); - remap[0] = 0xa5; - remap = (unsigned char *)syscall(SYS_mremap, remap, 4096, 8192, MREMAP_MAYMOVE); - CHECK(remap != MAP_FAILED && remap[0] == 0xa5); - CHECK(munmap(remap, 8192) == 0); - unsigned char *locked = mmap(NULL, 4096, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(locked != MAP_FAILED); - CHECK(syscall(SYS_mlock, locked, 4096) == 0); - CHECK(syscall(SYS_munlock, locked, 4096) == 0); - CHECK(syscall(SYS_mlock2, locked, 4096, 2) == -1 && errno == EINVAL); - CHECK(syscall(SYS_mlockall, MCL_CURRENT) == 0); - CHECK(syscall(SYS_munlockall) == 0); - CHECK(munmap(locked, 4096) == 0); - _Alignas(4) uint32_t futex_word = 1; - CHECK(syscall(SYS_futex_wake, &futex_word, UINT32_MAX, 1, FUTEX2_SIZE_U32) == 0); - CHECK(syscall(SYS_futex_wait, &futex_word, 0, UINT32_MAX, FUTEX2_SIZE_U32, - NULL, CLOCK_MONOTONIC) == -1 && errno == EAGAIN); - struct futex_waitv futex_requeue[2] = { - {.val = 1, .uaddr = (uintptr_t)&futex_word, .flags = FUTEX2_SIZE_U32}, - {.val = 1, .uaddr = (uintptr_t)&futex_word, .flags = FUTEX2_SIZE_U32}, - }; - CHECK(syscall(SYS_futex_requeue, futex_requeue, 0, 0, 0) == 0); - int readahead_fd = open("/usr/lib/reliefos/tests/musl-abi-static.elf", O_RDONLY); - CHECK(readahead_fd >= 0); - CHECK(syscall(SYS_readahead, readahead_fd, 0, 4096) == 0); - CHECK(close(readahead_fd) == 0); - const char *path = (const char *)getauxval(AT_EXECFN); - CHECK(path && path[0] == '/'); - CHECK(tls_value == 73); - tls_value = 91; - return 0; -} - -static int heap(void) -{ - char *p = strdup("musl to mimalloc"); - CHECK(p && mi_is_in_heap_region(p)); - p = realloc(p, 32768); - CHECK(p && !strcmp(p, "musl to mimalloc")); - free(p); - void *aligned = NULL; - CHECK(posix_memalign(&aligned, 4096, 8192) == 0); - CHECK(((uintptr_t)aligned & 4095) == 0 && mi_is_in_heap_region(aligned)); - free(aligned); - unsigned char *zero = calloc(512, 1); - CHECK(zero); - for (unsigned i = 0; i < 512; ++i) CHECK(zero[i] == 0); - free(zero); - char *text = NULL; - CHECK(asprintf(&text, "%.3f", 1.25) == 5 && !strcmp(text, "1.250")); - CHECK(mi_is_in_heap_region(text)); - free(text); - return 0; -} - -static int memory(void) -{ - uint64_t initial_break = (uint64_t)syscall(SYS_brk, 0); - CHECK(initial_break > 0 && initial_break < 0x08000000ULL); - CHECK(syscall(SYS_brk, initial_break + 8193) == (long)(initial_break + 8193)); - ((volatile unsigned char *)(uintptr_t)initial_break)[4096] = 0x5a; - CHECK(syscall(SYS_brk, initial_break + 1) == (long)(initial_break + 1)); - CHECK(syscall(SYS_brk, initial_break) == (long)initial_break); - CHECK(syscall(SYS_brk, initial_break - 65536) == (long)initial_break); - char *p = mmap(NULL, 8192, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(p != MAP_FAILED); - CHECK(mprotect(p, 4096, PROT_READ | PROT_WRITE) == 0); - p[0] = 42; - p[4095] = 17; - unsigned char residency[2] = {0, 0}; - CHECK(syscall(SYS_mincore, p, 8192, residency) == 0 && (residency[0] & 1)); - CHECK(syscall(SYS_madvise, p, 8192, MADV_NORMAL) == 0); - CHECK(syscall(SYS_msync, p, 8192, MS_SYNC) == 0); - CHECK(syscall(SYS_msync, p, 8192, MS_ASYNC | MS_SYNC) == -1 && errno == EINVAL); - CHECK(mprotect(p, 4096, PROT_NONE) == 0); - int fds[2]; - CHECK(pipe(fds) == 0); - /* A syscall must reject inaccessible user input without crashing the kernel. */ - CHECK(write(fds[1], p, 1) == -1 && errno == EFAULT); - CHECK(close(fds[0]) == 0 && close(fds[1]) == 0); - CHECK(mprotect(p, 4096, PROT_READ | PROT_WRITE) == 0); - CHECK(p[0] == 42 && p[4095] == 17); - CHECK(munmap(p, 8192) == 0); - CHECK(mprotect(NULL, 4096, PROT_READ) == -1 && errno == ENOMEM); - CHECK(mprotect(NULL, 0, PROT_READ) == 0); - int zero = open("/dev/zero", O_RDONLY); - CHECK(zero >= 0); - p = mmap(NULL, 4096, PROT_READ, MAP_SHARED, zero, 0); - CHECK(p != MAP_FAILED && p[0] == 0); - CHECK(mprotect(p, 4096, PROT_WRITE) == -1 && errno == EACCES); - CHECK(munmap(p, 4096) == 0); - p = mmap(NULL, 4096, PROT_NONE, MAP_PRIVATE, zero, 0); - CHECK(p != MAP_FAILED); - CHECK(mprotect(p, 4096, PROT_READ | PROT_WRITE) == 0); - p[0] = 99; - CHECK(munmap(p, 4096) == 0 && close(zero) == 0); - /* Anonymous mappings ignore fd; shared RAM must retain identity at fork. */ - p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 123, 0); - CHECK(p != MAP_FAILED); - p[0] = 17; - pid_t child = fork(); - CHECK(child >= 0); - if (!child) { - if (p[0] != 17) _exit(2); - if (mprotect(p, 4096, PROT_NONE) || - mprotect(p, 4096, PROT_READ | PROT_WRITE)) _exit(3); - p[0] = 42; - _exit(0); - } - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - CHECK(p[0] == 42); - CHECK(munmap(p, 4096) == 0); - return 0; -} - -static int nonblocking(void) -{ - int fd = socket(AF_UNIX, SOCK_STREAM, 0); - CHECK(fd >= 0); - CHECK(fcntl(fd, F_SETFL, O_NONBLOCK) == 0); - CHECK((syscall(SYS_fcntl, fd, F_GETFL) & 0x800) != 0); - struct sockaddr_un addr = {.sun_family = AF_UNIX}; - snprintf(addr.sun_path, sizeof(addr.sun_path), "/tmp/musl-abi-%ld.sock", (long)getpid()); - unlink(addr.sun_path); - CHECK(bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0); - CHECK(listen(fd, 1) == 0); - CHECK(accept(fd, NULL, NULL) == -1 && errno == EAGAIN); - CHECK(close(fd) == 0); - CHECK(unlink(addr.sun_path) == 0); - return 0; -} - -static int unix_streams(void) -{ - struct sockaddr_un address = {.sun_family = AF_UNIX}, actual; - snprintf(address.sun_path, sizeof(address.sun_path), "/tmp/musl-stream-%ld.sock", (long)getpid()); - socklen_t size = offsetof(struct sockaddr_un, sun_path) + strlen(address.sun_path) + 1; - mode_t mask = umask(0027); - int listener = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); - CHECK(listener >= 0 && (fcntl(listener, F_GETFL) & O_NONBLOCK) && (fcntl(listener, F_GETFD) & FD_CLOEXEC)); - CHECK(bind(listener, (struct sockaddr *)&address, size) == 0); - umask(mask); - struct stat st; - CHECK(stat(address.sun_path, &st) == 0 && S_ISSOCK(st.st_mode) && (st.st_mode & 0777) == 0750); - CHECK(chmod(address.sun_path, 0600) == 0); - CHECK(stat(address.sun_path, &st) == 0 && S_ISSOCK(st.st_mode) && (st.st_mode & 0777) == 0600); - CHECK(open(address.sun_path, O_RDONLY) == -1 && errno == ENXIO); - CHECK(listen(listener, 2) == 0); - int client = socket(AF_UNIX, SOCK_STREAM, 0); - CHECK(client >= 0 && bind(client, (struct sockaddr *)&address, size) == -1 && errno == EADDRINUSE); - CHECK(connect(client, (struct sockaddr *)&address, size) == 0); - socklen_t actual_size = sizeof(actual); - int accepted = accept4(listener, (struct sockaddr *)&actual, &actual_size, SOCK_CLOEXEC); - CHECK(accepted >= 0 && actual.sun_family == AF_UNIX && actual_size == 2); - CHECK((fcntl(accepted, F_GETFL) & O_NONBLOCK) == 0 && (fcntl(accepted, F_GETFD) & FD_CLOEXEC)); - actual_size = sizeof(actual); - CHECK(getsockname(accepted, (struct sockaddr *)&actual, &actual_size) == 0 && actual_size == size && - !strcmp(actual.sun_path, address.sun_path)); - actual_size = sizeof(actual); - CHECK(getpeername(client, (struct sockaddr *)&actual, &actual_size) == 0 && actual_size == size); - struct ucred peer; - socklen_t peer_size = sizeof(peer); - CHECK(getsockopt(client, SOL_SOCKET, SO_PEERCRED, &peer, &peer_size) == 0 && peer.pid == getpid() && peer.uid == getuid()); - CHECK(unlink(address.sun_path) == 0 && stat(address.sun_path, &st) == -1 && errno == ENOENT); - int rebound = socket(AF_UNIX, SOCK_STREAM, 0); - CHECK(rebound >= 0 && bind(rebound, (struct sockaddr *)&address, size) == 0 && listen(rebound, 1) == 0); - CHECK(write(client, "abc", 3) == 3); - char data[16]; - CHECK(read(accepted, data, 3) == 3 && !memcmp(data, "abc", 3)); - CHECK(shutdown(client, SHUT_WR) == 0 && read(accepted, data, 1) == 0); - CHECK(write(accepted, "r", 1) == 1 && read(client, data, 1) == 1 && data[0] == 'r'); - CHECK(close(client) == 0 && close(accepted) == 0 && close(listener) == 0 && close(rebound) == 0); - CHECK(stat(address.sun_path, &st) == 0 && S_ISSOCK(st.st_mode)); - client = socket(AF_UNIX, SOCK_STREAM, 0); - CHECK(client >= 0 && connect(client, (struct sockaddr *)&address, size) == -1 && errno == ECONNREFUSED); - CHECK(close(client) == 0 && unlink(address.sun_path) == 0); - DIR *dir = opendir("/tmp"); - CHECK(dir); - CHECK(closedir(dir) == 0); - int pair[2]; - CHECK(socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0, pair) == 0); - CHECK(read(pair[0], data, 0) == 0 && read(pair[0], data, 1) == -1 && errno == EAGAIN); - char *large = malloc(65536); - CHECK(large); - memset(large, 'x', 65536); - ssize_t sent = write(pair[0], large, 65536); - CHECK(sent > 0 && sent <= 65536); - size_t buffered = sent; - for (unsigned i = 0; i < 64; ++i) { - sent = write(pair[0], large, 65536); - if (sent < 0) break; - CHECK(sent > 0); - buffered += sent; - } - CHECK(sent == -1 && errno == EAGAIN); - struct pollfd ready = {pair[0], POLLOUT, 0}; - CHECK(poll(&ready, 1, 0) == 0); - CHECK(write(pair[0], large, 1) == -1 && errno == EAGAIN); - while (buffered) { - ssize_t got = read(pair[1], large, buffered < 65536 ? buffered : 65536); - CHECK(got > 0 && large[got - 1] == 'x'); - buffered -= got; - } - CHECK(poll(&ready, 1, 0) == 1 && (ready.revents & POLLOUT)); - CHECK(close(pair[0]) == 0 && read(pair[1], data, 1) == 0 && close(pair[1]) == 0); - free(large); - memset(&address, 0, sizeof(address)); - address.sun_family = AF_UNIX; - snprintf(address.sun_path + 1, sizeof(address.sun_path) - 1, "musl-%ld", (long)getpid()); - size = 2 + 1 + strlen(address.sun_path + 1); - listener = socket(AF_UNIX, SOCK_STREAM, 0); - client = socket(AF_UNIX, SOCK_STREAM, 0); - CHECK(listener >= 0 && client >= 0); - CHECK(bind(listener, (struct sockaddr *)&address, size) == 0 && listen(listener, 1) == 0); - CHECK(connect(client, (struct sockaddr *)&address, size) == 0); - accepted = accept(listener, NULL, NULL); - CHECK(accepted >= 0); - CHECK(close(listener) == 0 && close(client) == 0 && close(accepted) == 0); - return 0; -} - -static int rename_replacement(void) -{ - char directory[96], source[128], target[128], left[128], right[128], child[160]; - snprintf(directory, sizeof(directory), "/tmp/musl-rename-%ld", (long)getpid()); - snprintf(source, sizeof(source), "%s/source-long-name", directory); - snprintf(target, sizeof(target), "%s/target", directory); - snprintf(left, sizeof(left), "%s/left", directory); - snprintf(right, sizeof(right), "%s/right", directory); - snprintf(child, sizeof(child), "%s/child", right); - CHECK(mkdir(directory, 0700) == 0); - int fd = open(source, O_CREAT | O_EXCL | O_WRONLY, 0640); - CHECK(fd >= 0 && write(fd, "new", 3) == 3 && close(fd) == 0); - CHECK(chown(source, 12345, 23456) == 0); - fd = open(target, O_CREAT | O_EXCL | O_WRONLY, 0600); - CHECK(fd >= 0 && write(fd, "old data", 8) == 8 && close(fd) == 0); - CHECK(rename(source, target) == 0); - struct stat st; - CHECK(stat(source, &st) == -1 && errno == ENOENT); - CHECK(stat(target, &st) == 0 && st.st_uid == 12345 && st.st_gid == 23456 && - (st.st_mode & 0777) == 0640 && st.st_size == 3); - char text[8] = {0}; - fd = open(target, O_RDONLY); - CHECK(fd >= 0 && read(fd, text, sizeof(text)) == 3 && !strcmp(text, "new") && close(fd) == 0); - CHECK(rename(target, target) == 0); - CHECK(rename(source, source) == -1 && errno == ENOENT); - CHECK(mkdir(left, 0700) == 0 && mkdir(right, 0700) == 0); - CHECK(rename(target, left) == -1 && errno == EISDIR); - CHECK(rename(left, target) == -1 && errno == ENOTDIR); - fd = open(child, O_CREAT | O_EXCL | O_WRONLY, 0600); - CHECK(fd >= 0 && close(fd) == 0); - CHECK(rename(left, right) == -1 && errno == ENOTEMPTY); - CHECK(unlink(child) == 0 && rename(left, right) == 0); - CHECK(stat(left, &st) == -1 && errno == ENOENT); - CHECK(stat(right, &st) == 0 && S_ISDIR(st.st_mode)); - CHECK(rmdir(right) == 0 && unlink(target) == 0 && rmdir(directory) == 0); - return 0; -} - -static int permission_child(const char *path, unsigned uid, unsigned gid, - int can_read, int can_write, int inherited) -{ - CHECK(setgid(gid) == 0 && setuid(uid) == 0); - uid_t ruid, euid, suid; - gid_t rgid, egid, sgid; - CHECK(syscall(SYS_getresuid, &ruid, &euid, &suid) == 0 && - ruid == uid && euid == uid && suid == uid); - CHECK(syscall(SYS_getresgid, &rgid, &egid, &sgid) == 0 && - rgid == gid && egid == gid && sgid == gid); - CHECK(syscall(SYS_setreuid, (unsigned)-1, (unsigned)uid) == 0); - CHECK(syscall(SYS_setregid, (unsigned)-1, (unsigned)gid) == 0); - CHECK(syscall(SYS_setreuid, (unsigned)(uid + 1000), (unsigned)-1) == -1 && errno == EPERM); - CHECK(syscall(SYS_setregid, (unsigned)(gid + 1000), (unsigned)-1) == -1 && errno == EPERM); - CHECK(syscall(SYS_setresuid, (unsigned)-1, (unsigned)-1, (unsigned)-1) == 0); - CHECK(syscall(SYS_setresgid, (unsigned)-1, (unsigned)-1, (unsigned)-1) == 0); - CHECK(setgroups(0, NULL) == -1 && errno == EPERM); - int fd = open(path, O_RDONLY); - CHECK(can_read ? fd >= 0 : fd == -1 && errno == EACCES); - if (fd >= 0) CHECK(close(fd) == 0); - fd = open(path, O_WRONLY); - CHECK(can_write ? fd >= 0 : fd == -1 && errno == EACCES); - if (fd >= 0) CHECK(close(fd) == 0); - if (inherited >= 0) { - CHECK(chmod(path, 0000) == 0); - CHECK(open(path, O_RDONLY) == -1 && errno == EACCES); - CHECK(write(inherited, "x", 1) == 1); - CHECK(fchmod(inherited, 0640) == 0); - CHECK(chown(path, uid + 1, (gid_t)-1) == -1 && errno == EPERM); - } else CHECK(chmod(path, 0777) == -1 && errno == EPERM); - return 0; -} - -static int permissions(void) -{ - char directory[96], path[128]; - snprintf(directory, sizeof(directory), "/tmp/musl-perm-%ld", (long)getpid()); - snprintf(path, sizeof(path), "%s/file", directory); - mode_t old_mask = umask(0); - CHECK(mkdir(directory, 01777) == 0); - CHECK(chmod(directory, 01777) == 0); - umask(0027); - int fd = open(path, O_CREAT | O_EXCL | O_RDWR, 0666); - CHECK(fd >= 0); - struct stat st; - CHECK(fstat(fd, &st) == 0 && (st.st_mode & 0777) == 0640); - struct statfs fs, fd_fs; - CHECK(statfs(directory, &fs) == 0 && fstatfs(fd, &fd_fs) == 0); - CHECK(fs.f_type == fd_fs.f_type && fs.f_bsize > 0 && fs.f_blocks > 0); - CHECK(fs.f_bavail <= fs.f_bfree && fs.f_bfree <= fs.f_blocks); - CHECK(st.st_uid == getuid() && st.st_gid == getgid()); - CHECK(fchown(fd, 10001, 20001) == 0); - CHECK(stat(path, &st) == 0 && st.st_uid == 10001 && st.st_gid == 20001); - int dirfd = open(directory, O_RDONLY | O_DIRECTORY); - CHECK(dirfd >= 0); - char cwd_before[256], cwd_after[256]; - CHECK(getcwd(cwd_before, sizeof(cwd_before))); - int relative = openat(dirfd, "file", O_RDONLY); - CHECK(relative >= 0 && close(relative) == 0); - CHECK(getcwd(cwd_after, sizeof(cwd_after)) && !strcmp(cwd_before, cwd_after)); - CHECK(fstatat(dirfd, "file", &st, 0) == 0 && st.st_uid == 10001); - CHECK(fstatat(-1, path, &st, 0) == 0); - CHECK(fstatat(fd, "", &st, AT_EMPTY_PATH) == 0 && (st.st_mode & 0777) == 0640); - struct statx sx; - CHECK(syscall(SYS_statx, AT_FDCWD, path, 0, - STATX_TYPE | STATX_MODE | STATX_UID | STATX_GID | - STATX_INO | STATX_SIZE | STATX_BLOCKS, &sx) == 0 && - (sx.stx_mask & STATX_BASIC_STATS) == - (STATX_TYPE | STATX_MODE | STATX_UID | STATX_GID | - STATX_INO | STATX_SIZE | STATX_BLOCKS) && - (sx.stx_mode & 0777) == 0640 && sx.stx_uid == 10001 && sx.stx_gid == 20001); - CHECK(syscall(SYS_statx, AT_FDCWD, path, 0, 0, &sx) == -1 && errno == EINVAL); - CHECK(syscall(SYS_statx, fd, "", AT_EMPTY_PATH, STATX_BASIC_STATS, &sx) == 0 && - (sx.stx_mode & 0777) == 0640); - CHECK(syscall(SYS_fchmodat, dirfd, "file", 0600) == 0); - CHECK(fstat(fd, &st) == 0 && (st.st_mode & 0777) == 0600); - CHECK(syscall(SYS_fchmodat2, fd, "", 0640, AT_EMPTY_PATH) == 0); - CHECK(syscall(SYS_fchmodat, -1, path, 0640) == 0); - CHECK(syscall(SYS_fchmodat, dirfd, "", 0640) == -1 && errno == ENOENT); - CHECK(syscall(SYS_fchmodat2, dirfd, "file", 0640, 1) == -1 && errno == EINVAL); - CHECK(syscall(SYS_fchownat, dirfd, "file", -1, 20002, 0) == 0); - CHECK(fstat(fd, &st) == 0 && st.st_uid == 10001 && st.st_gid == 20002); - CHECK(syscall(SYS_fchownat, fd, "", -1, 20001, AT_EMPTY_PATH) == 0); - CHECK(syscall(SYS_faccessat, dirfd, "file", R_OK | W_OK) == 0); - CHECK(syscall(SYS_faccessat2, dirfd, "file", R_OK, AT_EACCESS) == 0); - CHECK(syscall(SYS_mkdirat, dirfd, "child", 0777) == 0); - CHECK(fstatat(dirfd, "child", &st, 0) == 0 && S_ISDIR(st.st_mode) && (st.st_mode & 0777) == 0750); - CHECK(syscall(SYS_unlinkat, dirfd, "child", AT_REMOVEDIR) == 0); - CHECK(syscall(SYS_unlinkat, dirfd, "file", 1) == -1 && errno == EINVAL); - CHECK(fstatat(dirfd, "missing/../file", &st, 0) == -1 && errno == ENOENT); - CHECK(fstatat(dirfd, "file/../file", &st, 0) == -1 && errno == ENOTDIR); - CHECK(syscall(SYS_mkdirat, dirfd, "private", 0700) == 0); - CHECK(close(dirfd) == 0); - CHECK(setgroups(0, NULL) == 0 && getgroups(0, NULL) == 0); - for (unsigned i = 0; i < 4; ++i) { - if (i == 3) { - gid_t groups[] = {30001, 20001}; - CHECK(setgroups(2, groups) == 0 && getgroups(2, groups) == 2); - CHECK(groups[0] == 20001 && groups[1] == 30001); - } - pid_t child = fork(); - CHECK(child >= 0); - if (!child) _exit(permission_child(path, 10001 + i, i >= 2 ? 20002 : 20001, - i != 2, i == 0, i == 0 ? fd : -1)); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - } - CHECK(setgroups(0, NULL) == 0); - pid_t creator = fork(); - CHECK(creator >= 0); - if (!creator) { - CHECK(setgid(30001) == 0 && setuid(30001) == 0); - CHECK(unlink(path) == -1 && errno == EPERM); - char own_path[128]; - snprintf(own_path, sizeof(own_path), "%s/private/../file", directory); - CHECK(stat(own_path, &st) == -1 && errno == EACCES); - snprintf(own_path, sizeof(own_path), "%s/owned", directory); - umask(0027); - int own_fd = open(own_path, O_CREAT | O_EXCL | O_RDWR, 0666); - CHECK(own_fd >= 0); - CHECK(fstat(own_fd, &st) == 0 && (st.st_mode & 0777) == 0640 && - st.st_uid == 30001 && st.st_gid == 30001); - CHECK(write(own_fd, "owner", 5) == 5); - CHECK(chmod(own_path, 0600) == 0 && close(own_fd) == 0); - CHECK(unlink(own_path) == 0); - _exit(0); - } - int creator_status; - CHECK(waitpid(creator, &creator_status, 0) == creator && - WIFEXITED(creator_status) && WEXITSTATUS(creator_status) == 0); - char private_path[128]; - snprintf(private_path, sizeof(private_path), "%s/private", directory); - CHECK(rmdir(private_path) == 0); - CHECK(chmod("/dev/null", 0600) == 0); - pid_t device_child = fork(); - CHECK(device_child >= 0); - if (!device_child) { - CHECK(setgid(10001) == 0 && setuid(10001) == 0); - CHECK(open("/dev/null", O_WRONLY) == -1 && errno == EACCES); - _exit(0); - } - int device_status; - CHECK(waitpid(device_child, &device_status, 0) == device_child && - WIFEXITED(device_status) && WEXITSTATUS(device_status) == 0); - CHECK(chmod("/dev/null", 0666) == 0); - CHECK(stat(path, &st) == 0 && (st.st_mode & 0777) == 0640); - CHECK(chown(path, (uid_t)-1, (gid_t)-1) == 0); - CHECK(stat(path, &st) == 0 && st.st_uid == 10001 && st.st_gid == 20001); - CHECK(close(fd) == 0 && unlink(path) == 0 && rmdir(directory) == 0); - umask(old_mask); - return 0; -} - -static int timestamp_syscalls(void) -{ - char path[64]; - struct stat st; - struct linux_timespec ns[2] = {{1700000000, 0}, {1700000001, 0}}; - struct linux_timeval us[2] = {{1700000010, 123000}, {1700000011, 456000}}; - struct utimbuf old = {1700000020, 1700000021}; - snprintf(path, sizeof(path), "/tmp/musl-abi-time-%ld", (long)getpid()); - int fd = open(path, O_CREAT | O_RDWR | O_TRUNC, 0600); - CHECK(fd >= 0); - CHECK(close(fd) == 0); - CHECK(syscall(SYS_utimensat, AT_FDCWD, path, ns, 0) == 0); - CHECK(stat(path, &st) == 0 && st.st_atim.tv_sec == ns[0].tv_sec && - st.st_mtim.tv_sec == ns[1].tv_sec); - CHECK(syscall(SYS_utimensat, AT_FDCWD, path, NULL, 0) == 0); - CHECK(syscall(SYS_utimensat, AT_FDCWD, path, ns, AT_SYMLINK_NOFOLLOW | 0x4000) == -1 && - errno == EINVAL); - CHECK(syscall(SYS_utimes, path, us) == 0); - CHECK(stat(path, &st) == 0 && st.st_atim.tv_sec == us[0].tv_sec && - st.st_mtim.tv_sec == us[1].tv_sec); - CHECK(syscall(SYS_utime, path, &old) == 0); - CHECK(stat(path, &st) == 0 && st.st_atim.tv_sec == old.actime && - st.st_mtim.tv_sec == old.modtime); - CHECK(syscall(SYS_utime, path, NULL) == 0); - int dirfd = open("/tmp", O_RDONLY | O_DIRECTORY); - CHECK(dirfd >= 0); - struct linux_timeval futimes[2] = { - {1700000030, 111000}, {1700000031, 222000}, - }; - CHECK(syscall(SYS_futimesat, dirfd, strrchr(path, '/') + 1, futimes) == 0); - CHECK(stat(path, &st) == 0 && st.st_atim.tv_sec == futimes[0].tv_sec && - st.st_mtim.tv_sec == futimes[1].tv_sec); - CHECK(close(dirfd) == 0); - CHECK(unlink(path) == 0); - return 0; -} - -static int pty(void) -{ - int master = posix_openpt(O_RDWR | O_NOCTTY); - CHECK(master >= 0); - int number = -1; - CHECK(syscall(SYS_ioctl, master, 0xffffffff80045430ULL, &number) == 0); - CHECK(number >= 0); - CHECK(ioctl(master, TIOCGPTN, &number) == 0); - CHECK(grantpt(master) == 0 && unlockpt(master) == 0); - char name[128]; - CHECK(ptsname_r(master, name, sizeof(name)) == 0); - int slave = open(name, O_RDWR | O_NOCTTY); - CHECK(slave >= 0); - struct termios original, raw, readback; - CHECK(tcgetattr(slave, &original) == 0); - raw = original; - cfmakeraw(&raw); - CHECK(tcsetattr(slave, TCSANOW, &raw) == 0); - CHECK(tcgetattr(slave, &readback) == 0); - CHECK(!(readback.c_lflag & (ICANON | ECHO | ISIG))); - CHECK(readback.c_cc[VMIN] == 1 && readback.c_cc[VTIME] == 0); - CHECK(write(master, "x", 1) == 1); - char ch = 0; - CHECK(read(slave, &ch, 1) == 1 && ch == 'x'); - CHECK(tcsetattr(slave, TCSANOW, &original) == 0); - CHECK(close(slave) == 0 && close(master) == 0); - return 0; -} - -static volatile sig_atomic_t session_child_exited; -static void session_child_signal(int sig) -{ - if (sig == SIGCHLD) session_child_exited = 1; -} - -static int process_sessions(void) -{ - pid_t self = getpid(), sid = getsid(0), group = getpgrp(); - /* Linux init's inherited session may be 0 before any setsid(). */ - CHECK(sid >= 0 && getsid(self) == sid && getpgid(self) == group); - CHECK(syscall(SYS_getsid, 0x100000000ULL) == sid); - CHECK(syscall(SYS_getpgid, 0x100000000ULL) == group); - CHECK(syscall(SYS_getsid, 0x100000000ULL | (unsigned)self) == sid); - CHECK(getsid(-1) == -1 && errno == ESRCH); - CHECK(getpgid(-1) == -1 && errno == ESRCH); - CHECK(getsid(0x7fffffff) == -1 && errno == ESRCH); - CHECK(getpgid(0x7fffffff) == -1 && errno == ESRCH); - int ready[2], release[2]; - CHECK(pipe(ready) == 0 && pipe(release) == 0); - struct sigaction action = {.sa_handler = session_child_signal}, old; - sigemptyset(&action.sa_mask); - session_child_exited = 0; - CHECK(sigaction(SIGCHLD, &action, &old) == 0); - pid_t child = fork(); - CHECK(child >= 0); - if (!child) { - close(ready[0]); close(release[1]); - if (setsid() != getpid()) _exit(51); - if (geteuid() == 0 && setuid(65534)) _exit(52); - /* Linux permits these identity queries across user/session boundaries. */ - if (getsid(self) != sid || getpgid(self) != group) _exit(53); - if (write(ready[1], "r", 1) != 1) _exit(54); - char byte; - if (read(release[0], &byte, 1) != 1) _exit(55); - _exit(0); - } - close(ready[1]); close(release[0]); - char byte; - CHECK(read(ready[0], &byte, 1) == 1); - CHECK(getsid(child) == child && getpgid(child) == child); - CHECK(write(release[1], "x", 1) == 1); - for (unsigned i = 0; !session_child_exited && i < 3000; ++i) usleep(1000); - CHECK(session_child_exited); - /* The exited child retains its PID/session until wait reaps it. */ - CHECK(getsid(child) == child && getpgid(child) == child); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && !WEXITSTATUS(status)); - CHECK(getsid(child) == -1 && errno == ESRCH); - CHECK(getpgid(child) == -1 && errno == ESRCH); - CHECK(sigaction(SIGCHLD, &old, NULL) == 0); - CHECK(close(ready[0]) == 0 && close(release[1]) == 0); - return 0; -} - -static int pty_fork(void) -{ - int master = -1; - struct winsize size = {.ws_row = 25, .ws_col = 80}; - pid_t child = forkpty(&master, NULL, NULL, &size); - CHECK(child >= 0); - if (!child) { - struct winsize got; - if (!isatty(0) || getsid(0) != getpid() || tcgetpgrp(0) != getpgrp() || - ioctl(0, TIOCGWINSZ, &got) || got.ws_row != 25 || got.ws_col != 80) - _exit(41); - if (ioctl(0, TIOCSCTTY, 0)) _exit(42); - int second, slave; - if (openpty(&second, &slave, NULL, NULL, NULL)) _exit(43); - if (ioctl(slave, TIOCSCTTY, 0) != -1 || errno != EPERM) _exit(44); - close(slave); close(second); - if (write(1, "forkpty-ready", 13) != 13) _exit(45); - _exit(0); - } - struct pollfd ready = {.fd = master, .events = POLLIN}; - CHECK(poll(&ready, 1, 3000) > 0); - char text[32] = {0}; - CHECK(read(master, text, sizeof(text)) == 13 && !strcmp(text, "forkpty-ready")); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && !WEXITSTATUS(status)); - CHECK(close(master) == 0); - return 0; -} - -static int stdio_reopen_child(int slave) -{ - CHECK(setsid() >= 0); - CHECK(dup2(slave, STDIN_FILENO) == STDIN_FILENO); - CHECK(close(slave) == 0); - CHECK(syscall(SYS_close, 0x100000000ULL) == 0); - CHECK(syscall(SYS_close, STDIN_FILENO) == -1 && errno == EBADF); - CHECK(syscall(SYS_open, "/dev/null", O_RDONLY, 0) == STDIN_FILENO); - char byte = 0; - CHECK(syscall(SYS_read, STDIN_FILENO, &byte, 1) == 0); - CHECK(syscall(SYS_close, STDIN_FILENO) == 0); - CHECK(syscall(SYS_close, STDIN_FILENO) == -1 && errno == EBADF); - return 0; -} - -static int stdio_reopen(void) -{ - int master = posix_openpt(O_RDWR | O_NOCTTY); - CHECK(master >= 0); - CHECK(grantpt(master) == 0 && unlockpt(master) == 0); - char name[128]; - CHECK(ptsname_r(master, name, sizeof(name)) == 0); - int slave = open(name, O_RDWR | O_NOCTTY); - CHECK(slave >= 0); - pid_t child = fork(); - CHECK(child >= 0); - if (!child) _exit(stdio_reopen_child(slave)); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - CHECK(close(slave) == 0 && close(master) == 0); - return 0; -} - -static int proc_directories(void) -{ - char path[64], name[24]; - snprintf(name, sizeof(name), "%ld", (long)getpid()); - snprintf(path, sizeof(path), "/proc/%s", name); - struct stat st; - CHECK(stat(path, &st) == 0 && S_ISDIR(st.st_mode)); - int root = open("/proc", O_RDONLY | O_DIRECTORY); - CHECK(root >= 0); - int task = openat(root, name, O_RDONLY | O_DIRECTORY); - CHECK(task >= 0); - int info = openat(task, "stat", O_RDONLY); - CHECK(info >= 0); - char content[512]; - CHECK(read(info, content, sizeof(content)) > 0 && close(info) == 0); - _Static_assert(offsetof(struct dirent, d_name) == 19, "native x86-64 dirent64 prefix"); - _Alignas(8) char records[1024], comparison[1024]; - CHECK(syscall(SYS_getdents64, root, records, 1) == -1 && errno == EINVAL); - void *readonly = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(readonly != MAP_FAILED); - CHECK(syscall(SYS_getdents64, root, readonly, 128) == -1 && errno == EFAULT); - CHECK(munmap(readonly, 4096) == 0); - int fresh = open("/proc", O_RDONLY | O_DIRECTORY); - CHECK(fresh >= 0); - long first = syscall(SYS_getdents64, fresh, comparison, sizeof(comparison)); - CHECK(first > 0 && close(fresh) == 0); - long length = syscall(SYS_getdents64, root, records, sizeof(records)); - CHECK(length > 0); - CHECK(!strcmp(((struct dirent *)records)->d_name, ((struct dirent *)comparison)->d_name)); - int found = 0; - do { - for (long offset = 0; offset < length;) { - struct dirent *entry = (struct dirent *)(records + offset); - CHECK(entry->d_reclen >= 24 && !(entry->d_reclen & 7) && offset + entry->d_reclen <= length); - CHECK(memchr(entry->d_name, 0, entry->d_reclen - 19)); - if (!strcmp(entry->d_name, name)) { CHECK(entry->d_type == DT_DIR); found = 1; } - offset += entry->d_reclen; - } - length = syscall(SYS_getdents64, root, records, sizeof(records)); - CHECK(length >= 0); - } while (length); - CHECK(found); - CHECK(syscall(SYS_getdents64, task, records, sizeof(records)) > 0); - CHECK(close(task) == 0 && close(root) == 0); - - /* Exercise the old Linux getdents record and descriptor-relative rename - * through raw syscall numbers, independently of libc wrappers. */ - const char *old_name = "/tmp/linux-abi-creat-old"; - const char *new_name = "/tmp/linux-abi-renameat-new"; - int created = syscall(SYS_creat, old_name, 0600); - CHECK(created >= 0); - CHECK(write(created, "x", 1) == 1 && close(created) == 0); - int tmp = open("/tmp", O_RDONLY | O_DIRECTORY); - CHECK(tmp >= 0); - CHECK(syscall(SYS_renameat, AT_FDCWD, old_name, tmp, "linux-abi-renameat-new") == 0); - _Alignas(8) char old_records[1024]; - int old_found = 0; - long old_length = syscall(SYS_getdents, tmp, old_records, sizeof(old_records)); - CHECK(old_length > 0); - for (long offset = 0; offset < old_length;) { - unsigned long *ino = (unsigned long *)(old_records + offset); - unsigned short *reclen = (unsigned short *)(old_records + offset + 16); - CHECK(*ino != 0 && *reclen >= 24 && !(*reclen & 7) && offset + *reclen <= old_length); - char *entry_name = old_records + offset + 18; - CHECK(memchr(entry_name, 0, *reclen - 18)); - if (!strcmp(entry_name, "linux-abi-renameat-new")) old_found = 1; - offset += *reclen; - } - CHECK(old_found && close(tmp) == 0); - CHECK(unlink(new_name) == 0); - return 0; -} - -static int proc_status(void) -{ - int fd = open("/proc/self/status", O_RDONLY); - CHECK(fd >= 0); - char text[8192]; - ssize_t length = read(fd, text, sizeof(text) - 1); - CHECK(length > 0 && close(fd) == 0); - text[length] = 0; - CHECK(!strncmp(text, "Name:\t", 6)); - char *value = strstr(text, "\nUid:\t"); - unsigned real, effective, saved, fs; - CHECK(value && sscanf(value, "\nUid:\t%u%u%u%u", &real, &effective, &saved, &fs) == 4); - CHECK(real == getuid() && effective == geteuid() && saved == real && fs == effective); - value = strstr(text, "\nGid:\t"); - CHECK(value && sscanf(value, "\nGid:\t%u%u%u%u", &real, &effective, &saved, &fs) == 4); - CHECK(real == getgid() && effective == getegid() && saved == real && fs == effective); - value = strstr(text, "\nPid:\t"); - CHECK(value && sscanf(value, "\nPid:\t%u", &real) == 1 && real == (unsigned)getpid()); - value = strstr(text, "\nTgid:\t"); - CHECK(value && sscanf(value, "\nTgid:\t%u", &real) == 1 && real == (unsigned)getpid()); - value = strstr(text, "\nVmRSS:\t"); - unsigned long rss; - CHECK(value && sscanf(value, "\nVmRSS:\t%lu kB", &rss) == 1 && rss > 0 && !(rss % 4)); - return 0; -} - -static int descriptor_allocation_child(void) -{ - for (int fd = 3; fd < 1024; ++fd) syscall(SYS_close, fd); - int fd = open("/dev/null", O_RDWR); - CHECK(fd == 3 && dup(fd) == 4); - CHECK(fcntl(fd, F_DUPFD_CLOEXEC, 100) == 100); - CHECK(fcntl(100, F_GETFD) == FD_CLOEXEC); - CHECK(dup2(100, 700) == 700 && fcntl(700, F_GETFD) == 0); - CHECK(fcntl(100, F_SETFL, O_NONBLOCK) == 0); - CHECK(fcntl(fd, F_GETFL) & O_NONBLOCK); - CHECK(fcntl(700, F_GETFL) & O_NONBLOCK); - CHECK(dup2(-1, 700) == -1 && errno == EBADF); - CHECK(fcntl(700, F_GETFL) & O_NONBLOCK); - CHECK(close(4) == 0); - int pair[2]; - CHECK(pipe2(pair, O_CLOEXEC) == 0 && pair[0] == 4 && pair[1] == 5); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0 && pair[0] == 4 && pair[1] == 5); - CHECK(close(0) == 0 && dup(pair[0]) == 0); - CHECK(write(pair[1], "s", 1) == 1); - char ch; - CHECK(read(0, &ch, 1) == 1 && ch == 's'); - CHECK(close(0) == 0 && close(3) == 0); - int ends[2]; - CHECK(pipe(ends) == 0 && ends[0] == 0 && ends[1] == 3); - CHECK(write(ends[1], "p", 1) == 1 && read(ends[0], &ch, 1) == 1 && ch == 'p'); - CHECK(close(ends[0]) == 0 && close(ends[1]) == 0); - CHECK(socket(AF_UNIX, SOCK_DGRAM, 0) == 0); - CHECK(close(0) == 0); - int master = posix_openpt(O_RDWR | O_NOCTTY); - CHECK(master == 0); - CHECK(grantpt(master) == 0 && unlockpt(master) == 0); - CHECK(close(master) == 0); - /* recvmsg must allocate SCM_RIGHTS from the same lowest-free namespace. */ - char control[CMSG_SPACE(sizeof(int))] = {0}; - struct iovec vec = {"r", 1}; - struct msghdr message = {.msg_iov = &vec, .msg_iovlen = 1, - .msg_control = control, .msg_controllen = sizeof(control)}; - struct cmsghdr *hdr = CMSG_FIRSTHDR(&message); - hdr->cmsg_level = SOL_SOCKET; hdr->cmsg_type = SCM_RIGHTS; - hdr->cmsg_len = CMSG_LEN(sizeof(int)); - memcpy(CMSG_DATA(hdr), &pair[0], sizeof(int)); - CHECK(sendmsg(pair[0], &message, 0) == 1); - vec.iov_base = &ch; - CHECK(recvmsg(pair[1], &message, MSG_CMSG_CLOEXEC) == 1 && ch == 'r'); - int received = -1; - memcpy(&received, CMSG_DATA(CMSG_FIRSTHDR(&message)), sizeof(int)); - CHECK(received == 0 && fcntl(received, F_GETFD) == FD_CLOEXEC); - return 0; -} - -static int descriptor_limits_child(void) -{ - for (int fd = 3; fd < 1024; ++fd) syscall(SYS_close, fd); - CHECK(open("/dev/null", O_RDWR) == 3 && dup2(3, 100) == 100); - struct rlimit limit; - CHECK(syscall(SYS_getrlimit, RLIMIT_NOFILE, &limit) == 0); - limit.rlim_cur = 8; - CHECK(syscall(SYS_setrlimit, RLIMIT_NOFILE, &limit) == 0); - CHECK(dup2(100, 100) == 100); - CHECK(dup2(3, 8) == -1 && errno == EBADF); - CHECK(fcntl(3, F_DUPFD, 8) == -1 && errno == EINVAL); - CHECK(fcntl(3, F_DUPFD, -1) == -1 && errno == EINVAL); - CHECK(dup2(999, 999) == -1 && errno == EBADF); - CHECK(open("/dev/null", O_RDWR) == 4); - int pair[2]; - CHECK(pipe(pair) == 0 && pair[0] == 5 && pair[1] == 6); - CHECK(socket(AF_UNIX, SOCK_DGRAM, 0) == 7); - CHECK(socket(AF_UNIX, SOCK_DGRAM, 0) == -1 && errno == EMFILE); - CHECK(open("/dev/null", O_RDWR) == -1 && errno == EMFILE); - CHECK(close(3) == 0); - pair[0] = 123; pair[1] = 456; - CHECK(pipe(pair) == -1 && errno == EMFILE && pair[0] == 123 && pair[1] == 456); - CHECK(open("/dev/null", O_RDWR) == 3); - CHECK(close(0) == 0 && socket(AF_UNIX, SOCK_DGRAM, 0) == 0); - CHECK(fcntl(100, F_GETFL) >= 0); - return 0; -} - -static int descriptor_allocation(void) -{ - pid_t child = fork(); - CHECK(child >= 0); - if (!child) _exit(descriptor_allocation_child()); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - return 0; -} - -static int descriptor_boundaries_child(void) -{ - for (int fd = 3; fd < 1024; ++fd) syscall(SYS_close, fd); - void *readonly = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(readonly != MAP_FAILED); - CHECK(syscall(SYS_pipe, readonly) == -1 && errno == EFAULT); - CHECK(syscall(SYS_pipe2, readonly, 0) == -1 && errno == EFAULT); - CHECK(syscall(SYS_socketpair, AF_UNIX, SOCK_STREAM, 0, readonly) == -1 && errno == EFAULT); - CHECK(munmap(readonly, 4096) == 0); - int fd = open("/dev/null", O_RDWR); - CHECK(fd == 3); - CHECK(syscall(SYS_fcntl, fd, 0x100000000ULL | F_GETFD, 0) == 0); - CHECK(syscall(SYS_dup3, fd, 4, 0x100000000ULL | O_CLOEXEC) == 4); - CHECK(fcntl(4, F_GETFD) == FD_CLOEXEC && close(4) == 0); - int pair[2]; - CHECK(syscall(SYS_pipe2, pair, 0x100000000ULL | O_NONBLOCK) == 0); - CHECK(pair[0] == 4 && pair[1] == 5 && (fcntl(4, F_GETFL) & O_NONBLOCK)); - CHECK(close(4) == 0 && close(5) == 0); - CHECK(syscall(SYS_socket, 0x100000000ULL | AF_UNIX, - 0x100000000ULL | SOCK_DGRAM, 0x100000000ULL) == 4); - CHECK(close(4) == 0); - CHECK(syscall(SYS_socketpair, 0x100000000ULL | AF_UNIX, - 0x100000000ULL | SOCK_STREAM, 0x100000000ULL, pair) == 0); - CHECK(pair[0] == 4 && pair[1] == 5); - struct rlimit limit; - CHECK(syscall(SYS_getrlimit, RLIMIT_NOFILE, &limit) == 0); - limit.rlim_cur = 0; - CHECK(syscall(SYS_setrlimit, RLIMIT_NOFILE, &limit) == 0); - CHECK(dup(fd) == -1 && errno == EMFILE); - CHECK(fcntl(fd, F_DUPFD, 0) == -1 && errno == EINVAL); - CHECK(dup2(fd, fd) == fd); - CHECK(dup2(fd, 0) == -1 && errno == EBADF); - return 0; -} - -static int descriptor_boundaries(void) -{ - pid_t child = fork(); - CHECK(child >= 0); - if (!child) _exit(descriptor_boundaries_child()); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - return 0; -} - -static int descriptor_limits(void) -{ - pid_t child = fork(); - CHECK(child >= 0); - if (!child) _exit(descriptor_limits_child()); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - return 0; -} - -struct rlimit_worker_state { - pthread_barrier_t barrier; - struct rlimit limit; - pid_t tid; - int result; -}; - -static void *rlimit_worker(void *argument) -{ - struct rlimit_worker_state *state = argument; - state->tid = syscall(SYS_gettid); - state->result = setrlimit(RLIMIT_NOFILE, &state->limit); - pthread_barrier_wait(&state->barrier); - pthread_barrier_wait(&state->barrier); - struct rlimit observed; - if (getrlimit(RLIMIT_NOFILE, &observed) || observed.rlim_cur != 64) state->result = 2; - return NULL; -} - -static int resource_limits_child(void) -{ - struct rlimit original, old, value; - CHECK(syscall(SYS_prlimit64, 0, RLIMIT_NOFILE, NULL, &original) == 0); - CHECK(original.rlim_cur >= 128 && original.rlim_max >= original.rlim_cur); - CHECK(syscall(SYS_prlimit64, 0x100000000ULL, 0x100000007ULL, NULL, &old) == 0); - CHECK(!memcmp(&old, &original, sizeof(old))); - CHECK(syscall(SYS_prlimit64, -1, -1, (void *)1, NULL) == -1 && errno == EFAULT); - CHECK(syscall(SYS_prlimit64, -1, -1, NULL, (void *)1) == -1 && errno == ESRCH); - CHECK(syscall(SYS_prlimit64, 0, -1, NULL, (void *)1) == -1 && errno == EINVAL); - CHECK(syscall(SYS_getrlimit, -1, (void *)1) == -1 && errno == EINVAL); - CHECK(syscall(SYS_setrlimit, -1, (void *)1) == -1 && errno == EFAULT); - value = (struct rlimit){129,128}; - CHECK(syscall(SYS_prlimit64, 0, RLIMIT_NOFILE, &value, NULL) == -1 && errno == EINVAL); - value = (struct rlimit){0,RLIM_INFINITY}; - CHECK(syscall(SYS_prlimit64, 0, RLIMIT_NOFILE, &value, NULL) == -1 && errno == EPERM); - value = (struct rlimit){128,128}; - CHECK(syscall(SYS_prlimit64, 0, RLIMIT_NOFILE, &value, &old) == 0); - CHECK(!memcmp(&old, &original, sizeof(old))); - CHECK(syscall(SYS_getrlimit, 0x100000007ULL, &old) == 0 && old.rlim_cur == 128 && old.rlim_max == 128); - struct rlimit *readonly = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(readonly != MAP_FAILED); - CHECK(syscall(SYS_getrlimit, RLIMIT_NOFILE, readonly) == -1 && errno == EFAULT); - value.rlim_cur = 100; - CHECK(syscall(SYS_prlimit64, 0, RLIMIT_NOFILE, &value, readonly) == -1 && errno == EFAULT); - CHECK(getrlimit(RLIMIT_NOFILE, &old) == 0 && old.rlim_cur == 100 && old.rlim_max == 128); - CHECK(munmap(readonly, 4096) == 0); - value.rlim_cur = 96; - CHECK(syscall(SYS_prlimit64, 0, RLIMIT_NOFILE, &value, &value) == 0); - CHECK(value.rlim_cur == 100 && value.rlim_max == 128); - CHECK(getrlimit(RLIMIT_NOFILE, &old) == 0 && old.rlim_cur == 96); - struct rlimit_worker_state state = {.limit = {80,128}}; - CHECK(pthread_barrier_init(&state.barrier, NULL, 2) == 0); - pthread_t worker; - CHECK(pthread_create(&worker, NULL, rlimit_worker, &state) == 0); - pthread_barrier_wait(&state.barrier); - CHECK(state.result == 0 && getrlimit(RLIMIT_NOFILE, &old) == 0 && old.rlim_cur == 80); - value = (struct rlimit){64,128}; - CHECK(syscall(SYS_prlimit64, state.tid, RLIMIT_NOFILE, &value, &old) == 0 && old.rlim_cur == 80); - pthread_barrier_wait(&state.barrier); - CHECK(pthread_join(worker, NULL) == 0 && state.result == 0); - CHECK(pthread_barrier_destroy(&state.barrier) == 0); - pid_t child = fork(); - CHECK(child >= 0); - if (!child) { - if (getrlimit(RLIMIT_NOFILE, &old) || old.rlim_cur != 64 || old.rlim_max != 128) _exit(2); - value.rlim_cur = 60; - if (setrlimit(RLIMIT_NOFILE, &value)) _exit(3); - const char *executable = (const char *)getauxval(AT_EXECFN); - execl(executable, executable, "--rlimit-child", NULL); - _exit(4); - } - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - CHECK(getrlimit(RLIMIT_NOFILE, &old) == 0 && old.rlim_cur == 64); - CHECK(setuid(12345) == 0); - value = (struct rlimit){64,129}; - CHECK(setrlimit(RLIMIT_NOFILE, &value) == -1 && errno == EPERM); - CHECK(syscall(SYS_prlimit64, getppid(), RLIMIT_NOFILE, NULL, &old) == -1 && errno == EPERM); - value = (struct rlimit){0,128}; - CHECK(setrlimit(RLIMIT_NOFILE, &value) == 0); - CHECK(open("/dev/null", O_RDONLY) == -1 && errno == EMFILE); - value.rlim_cur = 64; - CHECK(setrlimit(RLIMIT_NOFILE, &value) == 0); - CHECK(getrlimit(RLIMIT_AS, &old) == 0); - value = (struct rlimit){0,old.rlim_max}; - CHECK(setrlimit(RLIMIT_AS, &value) == 0); - CHECK(mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == MAP_FAILED && errno == ENOMEM); - CHECK(setrlimit(RLIMIT_AS, &old) == 0); - return 0; -} - -static int resource_limits(void) -{ - pid_t child = fork(); - CHECK(child >= 0); - if (!child) _exit(resource_limits_child()); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - return 0; -} - -static int resource_address_space_child(void) -{ - char *kept = mmap(NULL, 12288, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(kept != MAP_FAILED && munmap(kept + 8192, 4096) == 0); - kept[0] = 73; - struct rlimit original; - CHECK(getrlimit(RLIMIT_AS, &original) == 0); - /* Find the current VM-size boundary without assuming a loader's layout. */ - unsigned lower = 0, upper = 65536; - while (lower < upper) { - unsigned middle = lower + (upper - lower) / 2; - struct rlimit value = {(rlim_t)middle * 4096, original.rlim_max}; - CHECK(setrlimit(RLIMIT_AS, &value) == 0); - void *page = mmap(NULL, 4096, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - if (page == MAP_FAILED) { CHECK(errno == ENOMEM); lower = middle + 1; } - else { CHECK(munmap(page, 4096) == 0); upper = middle; } - } - CHECK(lower > 1 && lower < 65536); - struct rlimit value = {(rlim_t)(lower - 1) * 4096, original.rlim_max}; - CHECK(setrlimit(RLIMIT_AS, &value) == 0); - CHECK(mmap(NULL, 4096, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == MAP_FAILED && errno == ENOMEM); - CHECK(mmap(kept, 8192, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == kept); - CHECK(kept[0] == 0); - kept[0] = 91; - CHECK(mmap(kept, 12288, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == MAP_FAILED && errno == ENOMEM); - CHECK(kept[0] == 91); - value.rlim_cur = 0; - CHECK(setrlimit(RLIMIT_AS, &value) == 0); - CHECK(mmap(NULL, 0, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == MAP_FAILED && errno == EINVAL); - CHECK(mmap(NULL, 4096, PROT_NONE, MAP_PRIVATE | MAP_SHARED | MAP_ANONYMOUS, -1, 0) == MAP_FAILED && errno == EINVAL); - CHECK(mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, -1, 0) == MAP_FAILED && errno == EBADF); - CHECK(setrlimit(RLIMIT_AS, &original) == 0 && munmap(kept, 8192) == 0); - return 0; -} - -static int resource_address_space(void) -{ - pid_t child = fork(); - CHECK(child >= 0); - if (!child) _exit(resource_address_space_child()); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - return 0; -} - -struct affinity_worker_state { - pthread_barrier_t barrier; - cpu_set_t observed; - int result; -}; - -static void *affinity_worker(void *argument) -{ - struct affinity_worker_state *state = argument; - pthread_barrier_wait(&state->barrier); - state->result = pthread_getaffinity_np(pthread_self(), sizeof(state->observed), &state->observed); - return NULL; -} - -static int thread_affinity(void) -{ - uint64_t raw[3] = {0, 0x123456789abcdef0ULL, 0xfedcba9876543210ULL}; - CHECK(syscall(SYS_sched_getaffinity, 0, sizeof(raw), raw) == 8 && raw[0]); - CHECK(raw[1] == 0x123456789abcdef0ULL && raw[2] == 0xfedcba9876543210ULL); - uint64_t original = raw[0], selected = original & -original; - CHECK(syscall(SYS_sched_getaffinity, 0, 7, (void *)1) == -1 && errno == EINVAL); - CHECK(syscall(SYS_sched_getaffinity, 0, 9, raw) == -1 && errno == EINVAL); - CHECK(syscall(SYS_sched_getaffinity, -1, 8, (void *)1) == -1 && errno == ESRCH); - CHECK(syscall(SYS_sched_getaffinity, 0, 8, (void *)1) == -1 && errno == EFAULT); - CHECK(syscall(SYS_sched_getaffinity, 0x100000000ULL, 0x100000008ULL, raw) == 8); - CHECK(syscall(SYS_sched_setaffinity, 0, 0, NULL) == -1 && errno == EINVAL); - CHECK(syscall(SYS_sched_setaffinity, -1, 0, NULL) == -1 && errno == ESRCH); - CHECK(syscall(SYS_sched_setaffinity, -1, 8, (void *)1) == -1 && errno == EFAULT); - CHECK(syscall(SYS_sched_setaffinity, 0, 1, &selected) == 0); - char *memory = mmap(NULL, 8192, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(memory != MAP_FAILED && mprotect(memory + 4096, 4096, PROT_NONE) == 0); - uint64_t *edge = (void *)(memory + 4096 - 8); - *edge = selected; - CHECK(syscall(SYS_sched_setaffinity, 0, 128, edge) == 0); - CHECK(syscall(SYS_sched_getaffinity, 0, 128, edge) == 8 && *edge == selected); - CHECK(mprotect(memory, 4096, PROT_READ) == 0); - CHECK(syscall(SYS_sched_getaffinity, 0, 8, edge) == -1 && errno == EFAULT); - CHECK(munmap(memory, 8192) == 0); - cpu_set_t set; - memset(&set, 0xff, sizeof(set)); - CHECK(pthread_getaffinity_np(pthread_self(), sizeof(set), &set) == 0); - CHECK(CPU_COUNT(&set) == 1 && *(uint64_t *)&set == selected); - struct affinity_worker_state state = {0}; - CHECK(pthread_barrier_init(&state.barrier, NULL, 2) == 0); - pthread_t thread; - CHECK(pthread_create(&thread, NULL, affinity_worker, &state) == 0); - CHECK(pthread_setaffinity_np(thread, sizeof(set), &set) == 0); - CHECK(pthread_getaffinity_np(thread, sizeof(set), &set) == 0 && CPU_COUNT(&set) == 1); - pthread_barrier_wait(&state.barrier); - CHECK(pthread_join(thread, NULL) == 0 && state.result == 0 && CPU_EQUAL(&set, &state.observed)); - CHECK(pthread_barrier_destroy(&state.barrier) == 0); - CHECK(syscall(SYS_sched_setaffinity, 0, 8, &original) == 0); - pid_t parent = getpid(), child = fork(); - CHECK(child >= 0); - if (!child) { - if (setuid(12345)) _exit(2); - if (syscall(SYS_sched_getaffinity, parent, 8, raw) != 8) _exit(3); - if (syscall(SYS_sched_setaffinity, parent, 8, &selected) != -1 || errno != EPERM) _exit(4); - if (syscall(SYS_sched_setaffinity, 0, 8, &selected)) _exit(5); - _exit(0); - } - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - return 0; -} - -/* No libc/TLS access may occur between setting an unmapped FS base and restoring it. */ -static long temporary_fs_base(uint64_t base, uint64_t original) -{ - register long result __asm__("rax") = SYS_arch_prctl; - register uint64_t saved __asm__("r9") = original; - register long first __asm__("r8"); - register long option __asm__("rdi") = 0x1002; - register uint64_t argument __asm__("rsi") = base; - __asm__ volatile("syscall; mov %%rax, %%r8; mov %%r9, %%rsi; mov $158, %%eax; syscall" - : "+a"(result), "=r"(first), "+D"(option), "+S"(argument) - : "r"(saved) : "rcx", "r11", "memory", "cc"); - return first; -} - -/* Fork-like native clone: the child restores its libc TLS before returning to C. */ -static long clone_with_fs(uint64_t base, uint64_t original) -{ - register long result __asm__("rax") = SYS_clone; - register long flags __asm__("rdi") = SIGCHLD | CLONE_SETTLS; - register long stack __asm__("rsi") = 0; - register long child_tid __asm__("r10") = 0; - register uint64_t tls __asm__("r8") = base; - register uint64_t saved __asm__("r9") = original; - __asm__ volatile("syscall; test %%rax, %%rax; jnz 1f; mov $0x1002, %%edi; " - "mov %%r9, %%rsi; mov $158, %%eax; syscall; 1:" - : "+a"(result), "+D"(flags), "+S"(stack) - : "d"(0L), "r"(child_tid), "r"(tls), "r"(saved) - : "rcx", "r11", "memory", "cc"); - return result; -} - -static int thread_tls_control(void) -{ - uint64_t original = 0, observed = 0; - CHECK(syscall(SYS_arch_prctl, 0x1003, &original) == 0 && original); - CHECK(syscall(SYS_arch_prctl, 0x100001003ULL, &observed) == 0 && observed == original); - CHECK(syscall(SYS_arch_prctl, -1, 0) == -1 && errno == EINVAL); - const uint64_t invalid[] = {0x7ffffffff000ULL, 0x800000000000ULL, - 0x100000000000000ULL, UINT64_MAX}; - for (unsigned i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { - CHECK(syscall(SYS_arch_prctl, 0x1002, invalid[i]) == -1 && errno == EPERM); - CHECK(syscall(SYS_arch_prctl, 0x1003, &observed) == 0 && observed == original); - CHECK(clone_with_fs(invalid[i], original) == -EPERM); - } - CHECK(temporary_fs_base(0, original) == 0); - CHECK(temporary_fs_base(0x100000000ULL, original) == 0); - CHECK(temporary_fs_base(0x7fffffffefffULL, original) == 0); - CHECK(syscall(SYS_arch_prctl, 0x1003, &observed) == 0 && observed == original); - char *page = mmap(NULL, 8192, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(page != MAP_FAILED && mprotect(page + 4096, 4096, PROT_NONE) == 0); - CHECK(syscall(SYS_arch_prctl, 0x1003, page + 4092) == -1 && errno == EFAULT); - CHECK(mprotect(page, 4096, PROT_READ) == 0); - CHECK(syscall(SYS_arch_prctl, 0x1003, page) == -1 && errno == EFAULT); - CHECK(munmap(page, 8192) == 0); - long child = clone_with_fs(0x100000000ULL, original); - CHECK(child >= 0); - if (!child) _exit(tls_value != 91); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - CHECK(tls_value == 91); - return 0; -} - -static int thread_tid_registration(void) -{ - uint32_t *word = mmap(NULL, 4096, PROT_READ | PROT_WRITE, - MAP_SHARED | MAP_ANONYMOUS, -1, 0); - CHECK(word != MAP_FAILED); - for (unsigned test = 0; test < 4; ++test) { - *word = 0x12345678; - pid_t child = fork(); - CHECK(child >= 0); - if (!child) { - void *pointer = test == 0 ? (void *)1 : test == 1 ? (void *)UINT64_MAX : word; - if (test == 3 && mprotect(word, 4096, PROT_READ)) _exit(2); - if (syscall(SYS_set_tid_address, pointer) != syscall(SYS_gettid)) _exit(3); - /* Registration never writes; a private mm must not clear a shared mapping on exit. */ - if (*word != 0x12345678) _exit(4); - _exit(0); - } - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - CHECK(*word == 0x12345678); - } - CHECK(munmap(word, 4096) == 0); - return 0; -} - -/* The child uses only raw syscalls on its private stack, without entering libc. */ -static long clone_register_tid(void *top, void *pointer) -{ - register long result __asm__("rax") = SYS_clone; - register long flags __asm__("rdi") = SIGCHLD | CLONE_VM; - register void *stack __asm__("rsi") = top; - register void *tid __asm__("r10") = pointer; - register long tls __asm__("r8") = 0; - __asm__ volatile("syscall; test %%rax, %%rax; jnz 1f; mov %%r10, %%rdi; " - "mov $218, %%eax; syscall; xor %%edi, %%edi; mov $60, %%eax; syscall; ud2; 1:" - : "+a"(result), "+D"(flags), "+S"(stack) - : "d"(0L), "r"(tid), "r"(tls) : "rcx", "r11", "memory", "cc"); - return result; -} - -static int thread_tid_exit(void) -{ - char *stack = mmap(NULL, 16384, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - char *memory = mmap(NULL, 8192, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(stack != MAP_FAILED && memory != MAP_FAILED); - for (unsigned test = 0; test < 5; ++test) { - unsigned offset = test == 1 ? 1 : test == 2 ? 4094 : 0; - uint32_t sentinel = 0x12345678, observed; - memset(memory, 0xab, 8192); - memcpy(memory + offset, &sentinel, sizeof(sentinel)); - if (test == 3) CHECK(mprotect(memory, 8192, PROT_READ) == 0); - long child = clone_register_tid(stack + 16384, test == 4 ? (void *)1 : memory + offset); - CHECK(child > 0); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - memcpy(&observed, memory + offset, sizeof(observed)); - CHECK(observed == (test < 3 ? 0 : sentinel)); - if (offset) CHECK((unsigned char)memory[offset - 1] == 0xab); - CHECK((unsigned char)memory[offset + 4] == 0xab); - if (test == 3) CHECK(mprotect(memory, 8192, PROT_READ | PROT_WRITE) == 0); - } - CHECK(munmap(memory, 8192) == 0 && munmap(stack, 16384) == 0); - return 0; -} - -static void *thread_main(void *arg) -{ - (void)arg; - if (tls_value != 73) return (void *)1; - tls_value = 19; - void *p = calloc(4096, 1); - if (!p || !mi_is_in_heap_region(p)) return (void *)2; - free(p); - return NULL; -} - -static int threads(void) -{ - pthread_t thread; - int error = pthread_create(&thread, NULL, thread_main, NULL); - if (error) errno = error; - CHECK(error == 0); - void *result = (void *)3; - CHECK(pthread_join(thread, &result) == 0 && result == NULL); - CHECK(tls_value == 91); - return 0; -} - -static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; -static pthread_cond_t counter_cond = PTHREAD_COND_INITIALIZER; -static pthread_once_t counter_once = PTHREAD_ONCE_INIT; -static pthread_key_t counter_key; -static unsigned counter_value, counter_started, counter_go, once_count; -static _Atomic unsigned destructor_count; -static pid_t process_id; -static int shared_fd; -static void once_function(void) { ++once_count; } -static void key_destructor(void *ptr) { free(ptr); atomic_fetch_add(&destructor_count, 1); } - -static void *counter_thread(void *arg) -{ - uintptr_t id = (uintptr_t)arg; - if (getpid() != process_id || syscall(SYS_gettid) == process_id || tls_value != 73) return (void *)1; - tls_value = 100 + id; - if (pthread_once(&counter_once, once_function)) return (void *)2; - void *allocation = malloc(1024); - if (!allocation || pthread_setspecific(counter_key, allocation)) return (void *)3; - if (pthread_mutex_lock(&counter_mutex)) return (void *)4; - ++counter_started; - pthread_cond_broadcast(&counter_cond); - while (!counter_go) if (pthread_cond_wait(&counter_cond, &counter_mutex)) return (void *)5; - pthread_mutex_unlock(&counter_mutex); - for (unsigned i = 0; i < 80; ++i) { - if (pthread_mutex_lock(&counter_mutex)) return (void *)6; - unsigned old = counter_value; - if (!(i % 20)) usleep(1000); - counter_value = old + 1; - pthread_mutex_unlock(&counter_mutex); - void *p = calloc(16, 128); - if (!p || tls_value != 100 + id) return (void *)7; - free(p); - } - if (!id) shared_fd = open("/dev/null", O_RDWR); - return NULL; -} - -static int thread_contention(void) -{ - pthread_t workers[4]; - process_id = getpid(); - shared_fd = -1; - CHECK(pthread_key_create(&counter_key, key_destructor) == 0); - for (unsigned i = 0; i < 4; ++i) CHECK(pthread_create(&workers[i], NULL, counter_thread, (void *)(uintptr_t)i) == 0); - CHECK(pthread_mutex_lock(&counter_mutex) == 0); - while (counter_started != 4) CHECK(pthread_cond_wait(&counter_cond, &counter_mutex) == 0); - counter_go = 1; - CHECK(pthread_cond_broadcast(&counter_cond) == 0 && pthread_mutex_unlock(&counter_mutex) == 0); - for (unsigned i = 0; i < 4; ++i) { - void *result = (void *)99; - CHECK(pthread_join(workers[i], &result) == 0 && result == NULL); - } - CHECK(counter_value == 320 && once_count == 1 && atomic_load(&destructor_count) == 4 && tls_value == 91); - CHECK(shared_fd >= 0 && write(shared_fd, "shared", 6) == 6 && close(shared_fd) == 0); - CHECK(pthread_key_delete(counter_key) == 0); - CHECK(pthread_mutex_lock(&counter_mutex) == 0); - struct timespec timeout; - CHECK(clock_gettime(CLOCK_REALTIME, &timeout) == 0); - timeout.tv_nsec += 20000000; - if (timeout.tv_nsec >= 1000000000) { ++timeout.tv_sec; timeout.tv_nsec -= 1000000000; } - CHECK(pthread_cond_timedwait(&counter_cond, &counter_mutex, &timeout) == ETIMEDOUT); - CHECK(pthread_mutex_unlock(&counter_mutex) == 0); - return 0; -} - -static int send_rights(int socket_fd, const int *fds, unsigned count, const char *text) -{ - char control[CMSG_SPACE(2 * sizeof(int))] = {0}; - struct iovec vectors[2] = {{(void *)text, 1}, {(void *)(text + 1), strlen(text) - 1}}; - struct msghdr message = {.msg_iov = vectors, .msg_iovlen = 2, - .msg_control = control, .msg_controllen = CMSG_SPACE(count * sizeof(int))}; - struct cmsghdr *header = CMSG_FIRSTHDR(&message); - header->cmsg_level = SOL_SOCKET; - header->cmsg_type = SCM_RIGHTS; - header->cmsg_len = CMSG_LEN(count * sizeof(int)); - memcpy(CMSG_DATA(header), fds, count * sizeof(int)); - return sendmsg(socket_fd, &message, MSG_NOSIGNAL); -} - -static int receive_right(int socket_fd, unsigned flags, int *descriptor) -{ - char control[CMSG_SPACE(sizeof(int))] = {0}, data[2]; - struct iovec vectors[2] = {{data, 1}, {data + 1, 1}}; - struct msghdr message = {.msg_iov = vectors, .msg_iovlen = 2, - .msg_control = control, .msg_controllen = sizeof(control)}; - CHECK(recvmsg(socket_fd, &message, flags) == 2); - CHECK(data[0] == 'a' && data[1] == 'b' && !(message.msg_flags & MSG_CTRUNC)); - struct cmsghdr *header = CMSG_FIRSTHDR(&message); - CHECK(header && header->cmsg_level == SOL_SOCKET && header->cmsg_type == SCM_RIGHTS && - header->cmsg_len == CMSG_LEN(sizeof(int)) && message.msg_controllen >= CMSG_LEN(sizeof(int))); - memcpy(descriptor, CMSG_DATA(header), sizeof(int)); - return 0; -} - -static int unix_rights(void) -{ - char path[128], data[2]; - snprintf(path, sizeof(path), "/tmp/musl-ofd-%ld", (long)getpid()); - int original = open(path, O_CREAT | O_EXCL | O_RDWR, 0600); - CHECK(original >= 0 && write(original, "1234", 4) == 4 && lseek(original, 0, SEEK_SET) == 0); - int duplicate = dup(original); - CHECK(duplicate >= 0 && fcntl(duplicate, F_SETFD, FD_CLOEXEC) == 0 && fcntl(original, F_GETFD) == 0); - CHECK(fcntl(duplicate, F_SETFL, O_NONBLOCK) == 0 && (fcntl(original, F_GETFL) & O_NONBLOCK)); - int pair[2]; - CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); - int invalid = -1; - CHECK(send_rights(pair[0], &invalid, 1, "ab") == -1 && errno == EBADF); - CHECK(recv(pair[1], data, 1, MSG_DONTWAIT) == -1 && errno == EAGAIN); - CHECK(send_rights(pair[0], &original, 1, "ab") == 2 && close(original) == 0); - int peeked, received; - CHECK(receive_right(pair[1], MSG_PEEK | MSG_CMSG_CLOEXEC, &peeked) == 0); - CHECK((fcntl(peeked, F_GETFD) & FD_CLOEXEC) && read(peeked, data, 1) == 1 && data[0] == '1'); - CHECK(receive_right(pair[1], 0, &received) == 0 && received != peeked); - CHECK(fcntl(received, F_GETFD) == 0 && read(received, data, 1) == 1 && data[0] == '2'); - CHECK(lseek(duplicate, 0, SEEK_CUR) == 2); - CHECK(close(peeked) == 0 && close(received) == 0 && close(duplicate) == 0); - CHECK(unlink(path) == 0); - int pipe_fds[2]; - CHECK(pipe(pipe_fds) == 0 && send_rights(pair[0], &pipe_fds[0], 1, "ab") == 2 && close(pipe_fds[0]) == 0); - pid_t child = fork(); - CHECK(child >= 0); - if (!child) { - int incoming; - if (receive_right(pair[1], MSG_CMSG_CLOEXEC, &incoming)) _exit(1); - if (read(incoming, data, 1) != 1 || data[0] != 'x') _exit(2); - close(incoming); - _exit(0); - } - CHECK(write(pipe_fds[1], "x", 1) == 1); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - struct pollfd pipe_status = {pipe_fds[1], POLLOUT, 0}; - CHECK(poll(&pipe_status, 1, 0) == 1 && (pipe_status.revents & POLLERR)); - CHECK(close(pipe_fds[1]) == 0 && close(pair[0]) == 0 && close(pair[1]) == 0); - return 0; -} - -static int unix_rights_boundaries(void) -{ - int original = open("/dev/null", O_RDONLY); - CHECK(original >= 0); - for (unsigned test = 0; test < 5; ++test) { - int pair[2]; - CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); - CHECK(write(pair[0], "ab", 2) == 2); - CHECK(send_rights(pair[0], &original, 1, "cde") == 3); - CHECK(write(pair[0], "fg", 2) == 2); - char data[8] = {0}; - union { struct cmsghdr align; char data[CMSG_SPACE(sizeof(int))]; } control; - struct iovec vector = {data, 7}; - struct msghdr message = {.msg_iov = &vector, .msg_iovlen = 1, - .msg_control = control.data, .msg_controllen = sizeof(control.data)}; - if (test == 3) { - CHECK(read(pair[1], data, 7) == 5 && !memcmp(data, "abcde", 5)); - } else if (test == 4) { - struct iovec vectors[2] = {{data, 3}, {data + 3, 4}}; - CHECK(readv(pair[1], vectors, 2) == 5 && !memcmp(data, "abcde", 5)); - } else { - CHECK(recvmsg(pair[1], &message, test == 1 ? MSG_PEEK : test == 2 ? 0 : MSG_WAITALL) == 5); - CHECK(!memcmp(data, "abcde", 5) && !(message.msg_flags & MSG_CTRUNC)); - struct cmsghdr *header = CMSG_FIRSTHDR(&message); - CHECK(header && header->cmsg_type == SCM_RIGHTS && header->cmsg_level == SOL_SOCKET && - header->cmsg_len == CMSG_LEN(sizeof(int))); - int received; - memcpy(&received, CMSG_DATA(header), sizeof(received)); - CHECK(received >= 0 && close(received) == 0); - if (test == 1) { - /* The peeked descriptor must not detach the queued reference. */ - vector.iov_len = 3; - message.msg_controllen = sizeof(control.data); - CHECK(recvmsg(pair[1], &message, 0) == 3 && !memcmp(data, "abc", 3)); - header = CMSG_FIRSTHDR(&message); - CHECK(header && header->cmsg_type == SCM_RIGHTS); - memcpy(&received, CMSG_DATA(header), sizeof(received)); - CHECK(close(received) == 0); - CHECK(recv(pair[1], data, 4, MSG_WAITALL) == 4 && !memcmp(data, "defg", 4)); - } - } - if (test != 1) CHECK(recv(pair[1], data, 7, MSG_DONTWAIT) == 2 && !memcmp(data, "fg", 2)); - CHECK(recv(pair[1], data, 1, MSG_DONTWAIT) == -1 && errno == EAGAIN); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - } - CHECK(close(original) == 0); - return 0; -} - -static void *last_thread(void *arg) -{ - _Atomic int *state = arg; - usleep(30000); - atomic_store(state, 42); - return NULL; -} - -static int thread_exit_lifecycle(void) -{ - struct robust_head { uintptr_t next; intptr_t offset; uintptr_t pending; }; - struct robust_node { uintptr_t next; uint32_t word; }; - unsigned char *shared = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); - CHECK(shared != MAP_FAILED); - struct robust_head *head = (void *)shared; - struct robust_node *node = (void *)(shared + 128); - head->next = (uintptr_t)node; - head->offset = offsetof(struct robust_node, word); - node->next = (uintptr_t)head; - pid_t child = fork(); - CHECK(child >= 0); - if (!child) { - node->word = (uint32_t)syscall(SYS_gettid) | 0x80000000U; - if (syscall(SYS_set_robust_list, head, sizeof(*head))) _exit(3); - uintptr_t actual = 0; - size_t size = 0; - if (syscall(SYS_get_robust_list, 0, &actual, &size) || actual != (uintptr_t)head || size != sizeof(*head)) _exit(4); - syscall(SYS_exit, 0); - __builtin_unreachable(); - } - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - CHECK(node->word == 0xc0000000U); - _Atomic int *state = (void *)(shared + 256); - child = fork(); - CHECK(child >= 0); - if (!child) { - pthread_t worker; - if (pthread_create(&worker, NULL, last_thread, state)) _exit(5); - pthread_exit(NULL); - } - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - CHECK(atomic_load(state) == 42); - CHECK(munmap(shared, 4096) == 0); - return 0; -} - -static atomic_int cancel_ready, cancel_cleaned; -static void cancel_cleanup(void *arg) -{ - (void)arg; - atomic_fetch_add(&cancel_cleaned, 1); -} - -static void *cancel_worker(void *arg) -{ - int fd = *(int *)arg; - pthread_cleanup_push(cancel_cleanup, NULL); - atomic_store(&cancel_ready, 1); - char byte; - read(fd, &byte, 1); - pthread_cleanup_pop(1); - return (void *)1; -} - -static int thread_cancellation(void) -{ - int pair[2]; - CHECK(pipe(pair) == 0); - pthread_t worker; - atomic_store(&cancel_ready, 0); - atomic_store(&cancel_cleaned, 0); - CHECK(pthread_create(&worker, NULL, cancel_worker, &pair[0]) == 0); - while (!atomic_load(&cancel_ready)) sched_yield(); - usleep(20000); - CHECK(pthread_cancel(worker) == 0); - void *result; - CHECK(pthread_join(worker, &result) == 0 && result == PTHREAD_CANCELED); - CHECK(atomic_load(&cancel_cleaned) == 1); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - return 0; -} - -static volatile sig_atomic_t signal_seen, signal_errors, signal_change_return; -static uintptr_t signal_alt_low, signal_alt_high; -static void native_signal_handler(int sig, siginfo_t *info, void *opaque) -{ - ucontext_t *context = opaque; - char local; - if (info->si_signo != sig || !context || !context->uc_mcontext.fpregs) ++signal_errors; - if (signal_alt_low && ((uintptr_t)&local < signal_alt_low || (uintptr_t)&local >= signal_alt_high)) - ++signal_errors; - if (signal_change_return) { - context->uc_mcontext.gregs[REG_RAX] = -EINTR; - __asm__ volatile("pxor %%xmm15, %%xmm15" ::: "xmm15"); - } - ++signal_seen; -} - -static int native_signals(void) -{ - struct sigaction action = {.sa_sigaction = native_signal_handler, - .sa_flags = SA_SIGINFO | SA_ONSTACK}, queried; - sigemptyset(&action.sa_mask); - CHECK(sigaction(SIGRTMAX, &action, NULL) == 0); - CHECK(sigaction(SIGRTMAX, NULL, &queried) == 0 && queried.sa_sigaction == action.sa_sigaction && - (queried.sa_flags & SA_SIGINFO)); - void *stack = mmap(NULL, 16384, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(stack != MAP_FAILED); - stack_t alt = {.ss_sp = stack, .ss_size = 16384}, old; - CHECK(sigaltstack(&alt, &old) == 0 && (old.ss_flags & SS_DISABLE)); - signal_alt_low = (uintptr_t)stack; - signal_alt_high = signal_alt_low + 16384; - signal_seen = signal_errors = 0; - sigset_t blocked, before, pending; - sigemptyset(&blocked); - sigaddset(&blocked, SIGRTMAX); - CHECK(pthread_sigmask(SIG_BLOCK, &blocked, &before) == 0); - CHECK(syscall(SYS_tgkill, getpid(), syscall(SYS_gettid), SIGRTMAX) == 0); - CHECK(signal_seen == 0 && sigpending(&pending) == 0 && sigismember(&pending, SIGRTMAX)); - CHECK(pthread_sigmask(SIG_SETMASK, &before, NULL) == 0 && signal_seen == 1 && !signal_errors); - uint64_t expected[2] = {0x1234567890abcdefULL, 0xfedcba0987654321ULL}, actual[2]; - signal_change_return = 1; - long result = SYS_tgkill; - long pid = getpid(), tid = syscall(SYS_gettid); - __asm__ volatile("movdqu %2, %%xmm15\n\tsyscall\n\tmovdqu %%xmm15, %1" - : "+a"(result), "=m"(actual) : "m"(expected), "D"(pid), "S"(tid), "d"((long)SIGRTMAX) - : "rcx", "r11", "xmm15", "memory"); - signal_change_return = 0; - CHECK(result == -EINTR && !memcmp(expected, actual, sizeof(actual)) && signal_seen == 2 && !signal_errors); - signal_alt_low = signal_alt_high = 0; - alt.ss_flags = SS_DISABLE; - CHECK(sigaltstack(&alt, NULL) == 0 && munmap(stack, 16384) == 0); - action.sa_handler = SIG_DFL; - action.sa_flags = 0; - CHECK(sigaction(SIGRTMAX, &action, NULL) == 0); - return 0; -} - -static atomic_int interrupted_read_ready; -static void *interrupted_reader(void *arg) -{ - atomic_store(&interrupted_read_ready, 1); - char byte; - ssize_t count = read(*(int *)arg, &byte, 1); - return (void *)(intptr_t)(count < 0 ? errno : 100 + count); -} - -static int thread_signal_restart(void) -{ - struct sigaction action = {.sa_sigaction = native_signal_handler, .sa_flags = SA_SIGINFO}; - sigemptyset(&action.sa_mask); - for (unsigned restart = 0; restart < 2; ++restart) { - action.sa_flags = SA_SIGINFO | (restart ? SA_RESTART : 0); - CHECK(sigaction(SIGUSR1, &action, NULL) == 0); - int pipe_fds[2]; - CHECK(pipe(pipe_fds) == 0); - pthread_t worker; - atomic_store(&interrupted_read_ready, 0); - CHECK(pthread_create(&worker, NULL, interrupted_reader, &pipe_fds[0]) == 0); - while (!atomic_load(&interrupted_read_ready)) sched_yield(); - usleep(20000); - CHECK(pthread_kill(worker, SIGUSR1) == 0); - usleep(20000); - if (restart) CHECK(write(pipe_fds[1], "x", 1) == 1); - void *result; - CHECK(pthread_join(worker, &result) == 0 && (intptr_t)result == (restart ? 101 : EINTR)); - CHECK(close(pipe_fds[0]) == 0 && close(pipe_fds[1]) == 0); - } - action.sa_handler = SIG_DFL; - action.sa_flags = 0; - CHECK(sigaction(SIGUSR1, &action, NULL) == 0); - return 0; -} - -static const char *probe_executable; -static void *exec_worker(void *arg) -{ - if (pthread_kill(pthread_self(), SIGUSR1) || alarm(4) != 0) _exit(95); - char expected_pid[24], fd_text[24]; - snprintf(expected_pid, sizeof(expected_pid), "%ld", (long)getpid()); - snprintf(fd_text, sizeof(fd_text), "%d", *(int *)arg); - char *arguments[] = {(char *)probe_executable, "--thread-exec", expected_pid, fd_text, NULL}; - execv(probe_executable, arguments); - _exit(93); -} - -static int thread_exec(void) -{ - int pair[2]; - CHECK(pipe2(pair, O_CLOEXEC) == 0); - pid_t child = fork(); - CHECK(child >= 0); - if (!child) { - sigset_t blocked; - sigemptyset(&blocked); - sigaddset(&blocked, SIGUSR1); - sigaddset(&blocked, SIGUSR2); - if (pthread_sigmask(SIG_BLOCK, &blocked, NULL) || kill(getpid(), SIGUSR2)) _exit(96); - pthread_t worker; - if (pthread_create(&worker, NULL, exec_worker, &pair[0])) _exit(94); - for (;;) pause(); - } - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - CHECK(fcntl(pair[0], F_GETFD) == FD_CLOEXEC); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - return 0; -} - -static int unix_rights_cycles(void) -{ - for (unsigned iteration = 0; iteration < 80; ++iteration) { - int pair[2]; - CHECK(socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, pair) == 0); - CHECK(send_rights(pair[0], &pair[1], 1, "ab") == 2); - CHECK(send_rights(pair[1], &pair[0], 1, "ab") == 2); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - } - return 0; -} - -static int unix_packets(void) -{ - for (unsigned i = 0; i < 2; ++i) { - int pair[2], type = i ? SOCK_SEQPACKET : SOCK_DGRAM; - CHECK(socketpair(AF_UNIX, type | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, pair) == 0); - char data[16]; - CHECK(send(pair[0], "abcdef", 6, 0) == 6 && send(pair[0], "xy", 2, 0) == 2); - CHECK(recv(pair[1], data, 3, MSG_PEEK | MSG_TRUNC) == 6 && !memcmp(data, "abc", 3)); - CHECK(recv(pair[1], data, 3, 0) == 3 && !memcmp(data, "abc", 3)); - CHECK(recv(pair[1], data, sizeof(data), 0) == 2 && !memcmp(data, "xy", 2)); - CHECK(send(pair[0], "", 0, 0) == 0); - struct pollfd event = {pair[1], POLLIN, 0}; - CHECK(poll(&event, 1, 0) == 1 && (event.revents & POLLIN)); - CHECK(recv(pair[1], data, sizeof(data), 0) == 0); - CHECK(recv(pair[1], data, sizeof(data), 0) == -1 && errno == EAGAIN); - int reported = 0; - socklen_t length = sizeof(reported); - CHECK(getsockopt(pair[0], SOL_SOCKET, SO_TYPE, &reported, &length) == 0 && reported == type); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - } - int left = socket(AF_UNIX, SOCK_DGRAM, 0), right = socket(AF_UNIX, SOCK_DGRAM, 0); - CHECK(left >= 0 && right >= 0); - struct sockaddr_un a = {.sun_family = AF_UNIX}, b = {.sun_family = AF_UNIX}, from; - snprintf(a.sun_path + 1, sizeof(a.sun_path) - 1, "musl-a-%ld", (long)getpid()); - snprintf(b.sun_path + 1, sizeof(b.sun_path) - 1, "musl-b-%ld", (long)getpid()); - socklen_t alen = 3 + strlen(a.sun_path + 1), blen = 3 + strlen(b.sun_path + 1); - CHECK(bind(left, (void *)&a, alen) == 0 && bind(right, (void *)&b, blen) == 0); - CHECK(sendto(left, "named", 5, 0, (void *)&b, blen) == 5); - char data[8]; - socklen_t length = sizeof(from); - CHECK(recvfrom(right, data, sizeof(data), 0, (void *)&from, &length) == 5 && length == alen && - !memcmp(&from, &a, alen) && !memcmp(data, "named", 5)); - CHECK(close(left) == 0 && close(right) == 0); - return 0; -} - -struct waitall_sender { int fd; pthread_t receiver; int interrupt; }; -static void *waitall_writer(void *arg) -{ - struct waitall_sender *sender = arg; - if (sender->interrupt) { - if (send(sender->fd, "short", 5, 0) != 5) return (void *)1; - usleep(20000); - return (void *)(intptr_t)pthread_kill(sender->receiver, SIGUSR1); - } - unsigned char bytes[3000]; - for (unsigned offset = 0; offset < 40000;) { - unsigned count = 40000 - offset; - if (count > sizeof(bytes)) count = sizeof(bytes); - for (unsigned i = 0; i < count; ++i) bytes[i] = (unsigned char)(offset + i); - ssize_t written = send(sender->fd, bytes, count, 0); - if (written <= 0) return (void *)1; - offset += (unsigned)written; - usleep(10000); - } - return NULL; -} - -static int unix_waitall(void) -{ - int pair[2]; - CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); - int enabled = 1; - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_PASSCRED, &enabled, sizeof(enabled)) == 0); - struct waitall_sender sender = {pair[0], pthread_self(), 0}; - pthread_t writer; - CHECK(pthread_create(&writer, NULL, waitall_writer, &sender) == 0); - unsigned char *data = malloc(40000); - CHECK(data); - struct iovec vectors[2] = {{data, 13000}, {data + 13000, 27000}}; - union { struct cmsghdr align; unsigned char bytes[CMSG_SPACE(sizeof(struct ucred))]; } control; - struct msghdr message = {.msg_iov = vectors, .msg_iovlen = 2, - .msg_control = control.bytes, .msg_controllen = sizeof(control)}; - CHECK(recvmsg(pair[1], &message, MSG_WAITALL) == 40000); - struct cmsghdr *header = CMSG_FIRSTHDR(&message); - CHECK(header && header->cmsg_type == SCM_CREDENTIALS && !(message.msg_flags & MSG_CTRUNC)); - for (unsigned i = 0; i < 40000; ++i) CHECK(data[i] == (unsigned char)i); - void *result; - CHECK(pthread_join(writer, &result) == 0 && !result); - struct sigaction action = {.sa_sigaction = native_signal_handler, .sa_flags = SA_SIGINFO | SA_RESTART}; - sigemptyset(&action.sa_mask); - CHECK(sigaction(SIGUSR1, &action, NULL) == 0); - sender.interrupt = 1; - CHECK(pthread_create(&writer, NULL, waitall_writer, &sender) == 0); - vectors[0] = (struct iovec){data, 12}; - message = (struct msghdr){.msg_iov = vectors, .msg_iovlen = 1, - .msg_control = control.bytes, .msg_controllen = sizeof(control)}; - CHECK(recvmsg(pair[1], &message, MSG_WAITALL) == 5 && !memcmp(data, "short", 5)); - CHECK(message.msg_controllen == 0 && message.msg_flags == 0); - CHECK(pthread_join(writer, &result) == 0 && !result); - action.sa_handler = SIG_DFL; - action.sa_flags = 0; - CHECK(sigaction(SIGUSR1, &action, NULL) == 0); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - free(data); - return 0; -} - -static volatile sig_atomic_t socket_sigpipe_count; -static void socket_sigpipe(int signo) { socket_sigpipe_count += signo == SIGPIPE; } - -static int unix_credentials(void) -{ - int pair[2], enabled = 1; - CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); - unsigned char value[32]; - memset(value, 0xa5, sizeof(value)); - socklen_t size = 1; - CHECK(getsockopt(pair[0], SOL_SOCKET, SO_TYPE, value, &size) == 0); - CHECK(size == 1 && value[0] == SOCK_STREAM && value[1] == 0xa5); - size = 0; - CHECK(getsockopt(pair[0], SOL_SOCKET, SO_TYPE, NULL, &size) == 0 && !size); - size = (socklen_t)-1; - CHECK(getsockopt(pair[0], SOL_SOCKET, SO_TYPE, value, &size) == -1 && errno == EINVAL); - size = 3; - CHECK(getsockopt(pair[0], SOL_SOCKET, SO_PEERCRED, value, &size) == 0 && size == 3); - CHECK(getsockopt(pair[0], SOL_SOCKET, 0x7fff, value, &size) == -1 && errno == ENOPROTOOPT); - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_PASSCRED, &enabled, 3) == -1 && errno == EINVAL); - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_PASSCRED, &enabled, sizeof(enabled)) == 0); - size = sizeof(enabled); - int state = 0; - CHECK(getsockopt(pair[1], SOL_SOCKET, SO_PASSCRED, &state, &size) == 0 && state == 1); - char byte; - union { struct cmsghdr align; unsigned char bytes[CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int))]; } control; - struct iovec vector = {&byte, 1}; - struct msghdr message; - CHECK(write(pair[0], "ab", 2) == 2); - for (unsigned i = 0; i < 2; ++i) { - message = (struct msghdr){.msg_iov = &vector, .msg_iovlen = 1, - .msg_control = control.bytes, .msg_controllen = sizeof(control)}; - CHECK(recvmsg(pair[1], &message, 0) == 1 && byte == "ab"[i]); - struct cmsghdr *header = CMSG_FIRSTHDR(&message); - CHECK(header && header->cmsg_level == SOL_SOCKET && header->cmsg_type == SCM_CREDENTIALS); - struct ucred credentials; - memcpy(&credentials, CMSG_DATA(header), sizeof(credentials)); - CHECK(credentials.pid == getpid() && credentials.uid == getuid() && credentials.gid == getgid()); - } - pid_t child = fork(); - CHECK(child >= 0); - uid_t child_uid = geteuid() == 0 ? 1234 : getuid(); - gid_t child_gid = geteuid() == 0 ? 1234 : getgid(); - if (!child) { - close(pair[1]); - if (geteuid() == 0 && (setgid(child_gid) || setuid(child_uid))) _exit(20); - struct ucred credentials = {getpid() + 100000, getuid(), getgid()}; - message = (struct msghdr){.msg_iov = &vector, .msg_iovlen = 1, - .msg_control = control.bytes, .msg_controllen = CMSG_SPACE(sizeof(credentials))}; - struct cmsghdr *header = CMSG_FIRSTHDR(&message); - *header = (struct cmsghdr){.cmsg_len = CMSG_LEN(sizeof(credentials)), - .cmsg_level = SOL_SOCKET, .cmsg_type = SCM_CREDENTIALS}; - memcpy(CMSG_DATA(header), &credentials, sizeof(credentials)); - if (sendmsg(pair[0], &message, MSG_NOSIGNAL) != -1 || errno != EPERM) _exit(21); - credentials.pid = getpid(); - memcpy(CMSG_DATA(header), &credentials, sizeof(credentials)); - if (sendmsg(pair[0], &message, MSG_NOSIGNAL) != 1) _exit(22); - _exit(0); - } - message = (struct msghdr){.msg_iov = &vector, .msg_iovlen = 1, - .msg_control = control.bytes, .msg_controllen = sizeof(control)}; - CHECK(recvmsg(pair[1], &message, 0) == 1); - struct cmsghdr *header = CMSG_FIRSTHDR(&message); - CHECK(header && header->cmsg_type == SCM_CREDENTIALS); - struct ucred credentials; - memcpy(&credentials, CMSG_DATA(header), sizeof(credentials)); - CHECK(credentials.pid == child && credentials.uid == child_uid && credentials.gid == child_gid); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); - int source = open("/dev/null", O_RDWR); - CHECK(source >= 0); - message = (struct msghdr){.msg_iov = &vector, .msg_iovlen = 1, - .msg_control = control.bytes, .msg_controllen = CMSG_SPACE(sizeof(source))}; - header = CMSG_FIRSTHDR(&message); - *header = (struct cmsghdr){.cmsg_len = CMSG_LEN(sizeof(source)), .cmsg_level = SOL_SOCKET, .cmsg_type = SCM_RIGHTS}; - memcpy(CMSG_DATA(header), &source, sizeof(source)); - CHECK(sendmsg(pair[0], &message, MSG_NOSIGNAL) == 1); - message.msg_controllen = sizeof(control); - CHECK(recvmsg(pair[1], &message, MSG_CMSG_CLOEXEC) == 1 && !(message.msg_flags & MSG_CTRUNC)); - header = CMSG_FIRSTHDR(&message); - CHECK(header && header->cmsg_type == SCM_CREDENTIALS); - header = CMSG_NXTHDR(&message, header); - CHECK(header && header->cmsg_type == SCM_RIGHTS); - int received; - memcpy(&received, CMSG_DATA(header), sizeof(received)); - CHECK((fcntl(received, F_GETFD) & FD_CLOEXEC) != 0); - CHECK(close(received) == 0 && close(source) == 0); - CHECK(close(pair[1]) == 0); - struct sigaction action = {.sa_handler = socket_sigpipe}, old; - sigemptyset(&action.sa_mask); - CHECK(sigaction(SIGPIPE, &action, &old) == 0); - CHECK(write(pair[0], "x", 1) == -1 && errno == EPIPE && socket_sigpipe_count == 1); - CHECK(send(pair[0], "x", 1, MSG_NOSIGNAL) == -1 && errno == EPIPE && socket_sigpipe_count == 1); - CHECK(sigaction(SIGPIPE, &old, NULL) == 0 && close(pair[0]) == 0); - CHECK(socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) == 0); - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_PASSCRED, &enabled, sizeof(enabled)) == 0); - CHECK(send(pair[0], NULL, 0, 0) == 0); - message = (struct msghdr){.msg_control = control.bytes, .msg_controllen = sizeof(control)}; - CHECK(recvmsg(pair[1], &message, 0) == 0); - header = CMSG_FIRSTHDR(&message); - CHECK(header && header->cmsg_type == SCM_CREDENTIALS); - memcpy(&credentials, CMSG_DATA(header), sizeof(credentials)); - CHECK(credentials.pid == getpid() && credentials.uid == getuid()); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - return 0; -} - -static void *timed_signal_sender(void *arg) -{ - struct timespec delay = {0, 30000000}; - if (nanosleep(&delay, NULL) || pthread_kill(*(pthread_t *)arg, SIGUSR1)) return (void *)1; - return NULL; -} - -static int poll_interrupts(void) -{ - struct sigaction action = {.sa_handler = socket_sigpipe, .sa_flags = SA_RESTART}, old; - sigemptyset(&action.sa_mask); - CHECK(sigaction(SIGUSR1, &action, &old) == 0); - pthread_t self = pthread_self(), sender; - const unsigned long timeouts[] = {-1UL, -7UL, 0xffffffffUL, 0x1ffffffffUL, 500}; - for (unsigned i = 0; i < sizeof(timeouts) / sizeof(timeouts[0]); ++i) { - CHECK(pthread_create(&sender, NULL, timed_signal_sender, &self) == 0); - int result = syscall(SYS_poll, NULL, 0, timeouts[i]); - int error = errno; - void *joined; - CHECK(pthread_join(sender, &joined) == 0 && !joined); - CHECK(result == -1 && error == EINTR); - } - CHECK(pthread_create(&sender, NULL, timed_signal_sender, &self) == 0); - int immediate = syscall(SYS_poll, NULL, 0, 1ULL << 32); - void *joined; - CHECK(pthread_join(sender, &joined) == 0 && !joined); - CHECK(immediate == 0); - CHECK(sigaction(SIGUSR1, &old, NULL) == 0); - CHECK(syscall(SYS_poll, NULL, 1ULL << 32, 0) == 0); - return 0; -} - -static int poll_files(void) -{ - char path[96], sendfile_path[112], copy_range_path[112]; - snprintf(path, sizeof(path), "/tmp/poll-%s-%ld", PROBE_KIND, (long)getpid()); - int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600); - CHECK(fd >= 0); - const short all = POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM | POLLRDHUP | POLLPRI; - struct pollfd p = {fd, all, -1}; - CHECK(poll(&p, 1, 0) == 1 && p.revents == (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM)); - CHECK(close(fd) == 0); - fd = open(path, O_RDONLY); - CHECK(fd >= 0); - p.fd = fd; - CHECK(poll(&p, 1, 0) == 1 && p.revents == (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM)); - struct timespec ppoll_zero = {0, 0}; - p.revents = 0; - CHECK(syscall(SYS_ppoll, &p, 1, &ppoll_zero, NULL, 0) == 1 && - p.revents == (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM)); - ppoll_zero.tv_nsec = 1000000000; - CHECK(syscall(SYS_ppoll, &p, 1, &ppoll_zero, NULL, 0) == -1 && errno == EINVAL); - ppoll_zero.tv_nsec = 0; - uint64_t empty_mask = 0; - CHECK(syscall(SYS_ppoll, &p, 1, &ppoll_zero, &empty_mask, sizeof(empty_mask)) == -1 && - errno == EOPNOTSUPP); - fd_set readfds, writefds, exceptfds; - FD_ZERO(&readfds); - FD_ZERO(&writefds); - FD_ZERO(&exceptfds); - FD_SET(fd, &readfds); - FD_SET(fd, &writefds); - struct timeval select_zero = {0, 0}; - CHECK(syscall(SYS_select, fd + 1, &readfds, &writefds, &exceptfds, &select_zero) == 1 && - FD_ISSET(fd, &readfds) && FD_ISSET(fd, &writefds) && !FD_ISSET(fd, &exceptfds) && - select_zero.tv_sec == 0 && select_zero.tv_usec == 0); - FD_ZERO(&readfds); - FD_SET(fd, &readfds); - struct timespec pselect_zero = {0, 0}; - struct { const sigset_t *ss; size_t ss_len; } pselect_arg = {NULL, sizeof(uint64_t)}; - CHECK(syscall(SYS_pselect6, fd + 1, &readfds, NULL, NULL, &pselect_zero, &pselect_arg) == 1 && - FD_ISSET(fd, &readfds)); - struct pollfd *readonly = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(readonly != MAP_FAILED); - *readonly = p; - CHECK(mprotect(readonly, 4096, PROT_READ) == 0); - CHECK(syscall(SYS_poll, readonly, 1, 0) == -1 && errno == EFAULT); - CHECK(munmap(readonly, 4096) == 0 && close(fd) == 0 && unlink(path) == 0); - struct rlimit limit; - CHECK(getrlimit(RLIMIT_NOFILE, &limit) == 0); - CHECK(syscall(SYS_poll, NULL, limit.rlim_cur + 1, 0) == -1 && errno == EINVAL); - p = (struct pollfd){-1, all, -1}; - CHECK(poll(&p, 1, 20) == 0 && p.revents == 0); - p = (struct pollfd){1234567, 0, -1}; - CHECK(poll(&p, 1, 0) == 1 && p.revents == POLLNVAL); - struct rusage usage; - CHECK(syscall(SYS_getrusage, RUSAGE_SELF, &usage) == 0 && usage.ru_utime.tv_sec >= 0 && - usage.ru_maxrss >= 0); - struct sysinfo info; - CHECK(syscall(SYS_sysinfo, &info) == 0 && info.mem_unit == 1024 && info.totalram >= info.freeram && - info.procs > 0); - struct tms process_times; - long ticks = syscall(SYS_times, &process_times); - CHECK(ticks >= 0 && process_times.tms_utime >= 0 && process_times.tms_stime >= 0 && - process_times.tms_utime <= ticks); - fd = open(path, O_CREAT | O_TRUNC | O_RDWR, 0600); - CHECK(fd >= 0); - CHECK(syscall(SYS_fallocate, fd, 0, 0, 4096) == 0); - struct stat allocated; - CHECK(fstat(fd, &allocated) == 0 && allocated.st_size >= 4096); - CHECK(syscall(SYS_fallocate, fd, 1, 0, 4096) == -1 && errno == EOPNOTSUPP); - CHECK(syscall(SYS_fallocate, fd, 0, -1LL, 1) == -1 && errno == EINVAL); - CHECK(close(fd) == 0); - fd = open(path, O_CREAT | O_TRUNC | O_RDWR, 0600); - CHECK(fd >= 0 && write(fd, "abcdef", 6) == 6); - snprintf(sendfile_path, sizeof(sendfile_path), "%s.sendfile", path); - int send_source = open(path, O_RDONLY); - int send_target = open(sendfile_path, O_CREAT | O_TRUNC | O_RDWR, 0600); - CHECK(send_source >= 0 && send_target >= 0); - off_t send_position = 1; - CHECK(syscall(SYS_sendfile, send_target, send_source, &send_position, 3) == 3 && - send_position == 4 && lseek(send_source, 0, SEEK_CUR) == 0); - CHECK(lseek(send_target, 0, SEEK_SET) == 0); - char send_data[4] = {0}; - CHECK(read(send_target, send_data, 3) == 3 && !memcmp(send_data, "bcd", 3)); - CHECK(close(send_source) == 0 && close(send_target) == 0 && unlink(sendfile_path) == 0); - snprintf(copy_range_path, sizeof(copy_range_path), "%s.copy", path); - int copy_source = open(path, O_RDONLY); - int copy_target = open(copy_range_path, O_CREAT | O_TRUNC | O_RDWR, 0600); - CHECK(copy_source >= 0 && copy_target >= 0); - off_t copy_in = 2, copy_out = 0; - CHECK(syscall(SYS_copy_file_range, copy_source, ©_in, copy_target, ©_out, 2, 0) == 2 && - copy_in == 4 && copy_out == 2 && lseek(copy_source, 0, SEEK_CUR) == 0 && - lseek(copy_target, 0, SEEK_CUR) == 0); - CHECK(lseek(copy_target, 0, SEEK_SET) == 0); - char copy_data[3] = {0}; - CHECK(read(copy_target, copy_data, 2) == 2 && !memcmp(copy_data, "cd", 2)); - CHECK(close(copy_source) == 0 && close(copy_target) == 0 && unlink(copy_range_path) == 0); - int event_fd = eventfd(0, EFD_NONBLOCK); - CHECK(event_fd >= 0); - uint64_t event_value = 3; - CHECK(write(event_fd, &event_value, sizeof(event_value)) == (ssize_t)sizeof(event_value)); - event_value = 0; - CHECK(read(event_fd, &event_value, sizeof(event_value)) == (ssize_t)sizeof(event_value) && event_value == 3); - CHECK(read(event_fd, &event_value, sizeof(event_value)) == -1 && errno == EAGAIN); - struct pollfd event_poll = {event_fd, POLLIN | POLLOUT, 0}; - CHECK(poll(&event_poll, 1, 0) == 1 && !(event_poll.revents & POLLIN) && (event_poll.revents & POLLOUT)); - CHECK(syscall(SYS_eventfd2, 0, 0x40000000u) == -1 && errno == EINVAL); - CHECK(close(event_fd) == 0); - struct iovec vector = {(void *)"XYZ", 3}; - char positioned[4] = {0}; - struct iovec read_vector = {positioned, 3}; - CHECK(syscall(SYS_preadv, fd, &read_vector, 1, 1, 0) == 3 && - !memcmp(positioned, "bcd", 3)); - CHECK(lseek(fd, 0, SEEK_CUR) == 6); - CHECK(syscall(SYS_pwritev, fd, &vector, 1, 2, 0) == 3); - CHECK(lseek(fd, 0, SEEK_CUR) == 6); - memset(positioned, 0, sizeof(positioned)); - CHECK(syscall(SYS_preadv2, fd, &read_vector, 1, 2, 0, 0) == 3 && - !memcmp(positioned, "XYZ", 3)); - CHECK(syscall(SYS_pwritev2, fd, &vector, 1, 0, 0, 1) == -1 && errno == EOPNOTSUPP); - CHECK(syscall(SYS_sync_file_range, fd, 0, 0, 0) == 0); - CHECK(syscall(SYS_sync_file_range, fd, 0, 0, 8) == -1 && errno == EINVAL); - CHECK(syscall(SYS_sync_file_range, fd, -1LL, 0, 0) == -1 && errno == EINVAL); - CHECK(syscall(SYS_syncfs, fd) == 0); - int vector_pipe[2]; - CHECK(pipe(vector_pipe) == 0); - CHECK(syscall(SYS_preadv, vector_pipe[0], &read_vector, 1, 0, 0) == -1 && errno == ESPIPE); - CHECK(close(vector_pipe[0]) == 0 && close(vector_pipe[1]) == 0); - CHECK(close(fd) == 0); - int64_t now = 0; - long time_result = syscall(SYS_time, &now); - CHECK(time_result >= 0 && now == time_result); - CHECK(syscall(SYS_time, (void *)1) == -1 && errno == EFAULT); - unsigned cpu = 0, node = 0; - CHECK(syscall(SYS_getcpu, &cpu, &node, NULL) == 0); - CHECK(syscall(SYS_getcpu, (void *)1, NULL, NULL) == -1 && errno == EFAULT); - fd = open("/dev/null", O_RDONLY); - CHECK(fd >= 0 && syscall(SYS_close_range, fd, fd, 0) == 0 && - fcntl(fd, F_GETFD) == -1 && errno == EBADF); - fd = open("/dev/null", O_RDONLY); - CHECK(fd >= 0 && syscall(SYS_close_range, fd, UINT_MAX, 0) == 0 && - fcntl(fd, F_GETFD) == -1 && errno == EBADF); - fd = open("/dev/null", O_RDONLY); - CHECK(fd >= 0 && syscall(SYS_close_range, fd, fd, CLOSE_RANGE_CLOEXEC) == 0 && - (fcntl(fd, F_GETFD) & FD_CLOEXEC) && close(fd) == 0); - CHECK(syscall(SYS_close_range, 4, 3, 0) == -1 && errno == EINVAL); - return 0; -} - -static int thread_timed_interrupts(void) -{ - struct timespec request = {0, 200000000}, remaining = {77, 88}; - CHECK(syscall(SYS_nanosleep, NULL, NULL) == -1 && errno == EFAULT); - struct timespec invalid = {-1, 0}; - CHECK(syscall(SYS_nanosleep, &invalid, NULL) == -1 && errno == EINVAL); - invalid = (struct timespec){0, 1000000000}; - CHECK(syscall(SYS_nanosleep, &invalid, NULL) == -1 && errno == EINVAL); - struct timespec zero = {0, 0}; - CHECK(nanosleep(&zero, &remaining) == 0 && remaining.tv_sec == 77 && remaining.tv_nsec == 88); - CHECK(clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &zero, &remaining) == 0); - struct sigaction action = {.sa_handler = socket_sigpipe, .sa_flags = SA_RESTART}, old; - sigemptyset(&action.sa_mask); - CHECK(sigaction(SIGUSR1, &action, &old) == 0); - pthread_t self = pthread_self(), sender; - void *result; - for (unsigned mode = 0; mode < 4; ++mode) { - CHECK(pthread_create(&sender, NULL, timed_signal_sender, &self) == 0); - remaining = (struct timespec){77, 88}; - if (mode == 0) { - CHECK(nanosleep(&request, &remaining) == -1 && errno == EINTR); - } else if (mode == 1) { - CHECK(clock_nanosleep(CLOCK_MONOTONIC, 0, &request, &remaining) == EINTR); - } else if (mode == 2) { - uint32_t word = 0; - CHECK(syscall(SYS_futex, &word, 128 /* FUTEX_WAIT_PRIVATE */, 0, - &request, NULL, 0) == -1 && errno == EINTR); - } else { - struct timespec target; - CHECK(clock_gettime(CLOCK_REALTIME, &target) == 0); - target.tv_nsec += request.tv_nsec; - if (target.tv_nsec >= 1000000000) { ++target.tv_sec; target.tv_nsec -= 1000000000; } - CHECK(clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &target, &remaining) == EINTR); - } - if (mode < 2) CHECK(remaining.tv_sec == 0 && remaining.tv_nsec > 0 && remaining.tv_nsec <= request.tv_nsec); - else CHECK(remaining.tv_sec == 77 && remaining.tv_nsec == 88); - CHECK(pthread_join(sender, &result) == 0 && !result); - } - CHECK(sigaction(SIGUSR1, &old, NULL) == 0); - return 0; -} - -struct closing_reader { - int fd, operation; - atomic_int ready; - ssize_t count; - char byte; -}; - -static void *read_while_closed(void *arg) -{ - struct closing_reader *reader = arg; - atomic_store(&reader->ready, 1); - if (!reader->operation) reader->count = read(reader->fd, &reader->byte, 1); - else if (reader->operation == 1) reader->count = recv(reader->fd, &reader->byte, 1, 0); - else { - struct iovec vector = {&reader->byte, 1}; - reader->count = readv(reader->fd, &vector, 1); - } - return NULL; -} - -static int unix_close_during_io(void) -{ - for (int operation = 0; operation < 3; ++operation) { - int original[2], replacement[2]; - CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, original) == 0); - struct closing_reader reader = {.fd = original[1], .operation = operation}; - pthread_t thread; - CHECK(pthread_create(&thread, NULL, read_while_closed, &reader) == 0); - while (!atomic_load(&reader.ready)) sched_yield(); - struct timespec delay = {0, 30000000}; - CHECK(nanosleep(&delay, NULL) == 0); - CHECK(close(original[1]) == 0); - CHECK(socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0, replacement) == 0); - CHECK(replacement[0] == original[1]); - CHECK(send(original[0], "O", 1, MSG_NOSIGNAL) == 1); - CHECK(pthread_join(thread, NULL) == 0 && reader.count == 1 && reader.byte == 'O'); - char byte; - struct iovec vector = {&byte, 1}; - CHECK(readv(replacement[0], &vector, 1) == -1 && errno == EAGAIN); - CHECK(write(replacement[1], "N", 1) == 1); - CHECK(read(replacement[0], &byte, 1) == 1 && byte == 'N'); - CHECK(close(original[0]) == 0 && close(replacement[0]) == 0 && close(replacement[1]) == 0); - } - return 0; -} - -static int unix_timeouts(void) -{ - int pair[2]; - CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); - struct timeval timeout = {0, 40000}, observed; - socklen_t size = sizeof(observed); - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0); - CHECK(getsockopt(pair[1], SOL_SOCKET, SO_RCVTIMEO, &observed, &size) == 0); - CHECK(size == sizeof(observed) && observed.tv_sec == 0 && observed.tv_usec >= 40000 && observed.tv_usec <= 50000); - struct timeval invalid = {0, 1000000}; - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_RCVTIMEO, &invalid, sizeof(invalid)) == -1 && errno == EDOM); - char buffer[8]; - struct timespec before, after; - CHECK(clock_gettime(CLOCK_MONOTONIC, &before) == 0); - CHECK(recv(pair[1], buffer, sizeof(buffer), 0) == -1 && errno == EAGAIN); - CHECK(clock_gettime(CLOCK_MONOTONIC, &after) == 0); - long elapsed = (after.tv_sec - before.tv_sec) * 1000000000L + after.tv_nsec - before.tv_nsec; - CHECK(elapsed >= 30000000L && elapsed < 1000000000L); - CHECK(write(pair[0], "abc", 3) == 3); - CHECK(recv(pair[1], buffer, sizeof(buffer), MSG_WAITALL) == 3 && !memcmp(buffer, "abc", 3)); - struct sigaction action = {.sa_handler = socket_sigpipe, .sa_flags = SA_RESTART}, old; - sigemptyset(&action.sa_mask); - CHECK(sigaction(SIGUSR1, &action, &old) == 0); - timeout.tv_usec = 200000; - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0); - pthread_t self = pthread_self(), sender; - void *result; - CHECK(pthread_create(&sender, NULL, timed_signal_sender, &self) == 0); - CHECK(recv(pair[1], buffer, sizeof(buffer), 0) == -1 && errno == EINTR); - CHECK(pthread_join(sender, &result) == 0 && !result); - CHECK(sigaction(SIGUSR1, &old, NULL) == 0); - timeout.tv_usec = 40000; - CHECK(setsockopt(pair[0], SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) == 0); - char fill[4096] = {0}; - while (send(pair[0], fill, sizeof(fill), MSG_DONTWAIT | MSG_NOSIGNAL) > 0) {} - CHECK(errno == EAGAIN); - CHECK(send(pair[0], "x", 1, MSG_NOSIGNAL) == -1 && errno == EAGAIN); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - - CHECK(socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) == 0); - /* Native x86-64 OLD and NEW timeout records are both two 64-bit fields. */ - CHECK(setsockopt(pair[1], SOL_SOCKET, 66 /* SO_RCVTIMEO_NEW */, &timeout, sizeof(timeout)) == 0); - CHECK(recv(pair[1], buffer, sizeof(buffer), 0) == -1 && errno == EAGAIN); - invalid = (struct timeval){-1, 0}; - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_RCVTIMEO, &invalid, sizeof(invalid)) == 0); - CHECK(recv(pair[1], buffer, sizeof(buffer), 0) == -1 && errno == EAGAIN); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - int namespace_gap = socket(AF_UNIX, SOCK_STREAM, 0); - int listener = socket(AF_UNIX, SOCK_STREAM, 0); - struct sockaddr_un address = {.sun_family = AF_UNIX}; - CHECK(listener >= 0 && bind(listener, (struct sockaddr *)&address, sizeof(sa_family_t)) == 0); - size = sizeof(address); - CHECK(getsockname(listener, (struct sockaddr *)&address, &size) == 0 && listen(listener, 0) == 0); - CHECK(setsockopt(listener, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0); - CHECK(accept(listener, NULL, NULL) == -1 && errno == EAGAIN); - int client = socket(AF_UNIX, SOCK_STREAM, 0), waiting = socket(AF_UNIX, SOCK_STREAM, 0); - CHECK(client >= 0 && waiting >= 0 && namespace_gap >= 0); - /* An accepted endpoint can reuse an object slot before its listener. */ - CHECK(close(namespace_gap) == 0 && connect(client, (struct sockaddr *)&address, size) == 0); - CHECK(setsockopt(waiting, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) == 0); - CHECK(connect(waiting, (struct sockaddr *)&address, size) == -1 && errno == EAGAIN); - int enabled = 1; - CHECK(setsockopt(listener, SOL_SOCKET, SO_PASSCRED, &enabled, sizeof(enabled)) == 0); - int accepted = accept(listener, NULL, NULL); - CHECK(accepted >= 0); - size = sizeof(observed); - CHECK(getsockopt(accepted, SOL_SOCKET, SO_RCVTIMEO, &observed, &size) == 0); - CHECK(observed.tv_sec == 0 && observed.tv_usec == 0); - size = sizeof(enabled); - enabled = 0; - CHECK(getsockopt(accepted, SOL_SOCKET, SO_PASSCRED, &enabled, &size) == 0 && enabled == 1); - CHECK(close(accepted) == 0 && close(client) == 0 && close(waiting) == 0 && close(listener) == 0); - return 0; -} - -static int unix_vectors(void) -{ - int pair[2]; - char first[4] = {0}, second[4] = {0}, joined[8] = {0}; - struct iovec out[] = {{"abc", 3}, {"defg", 4}}; - struct iovec in[] = {{first, 3}, {second, 4}}; - for (int type = SOCK_STREAM; type <= SOCK_SEQPACKET; ++type) { - if (type != SOCK_STREAM && type != SOCK_DGRAM && type != SOCK_SEQPACKET) continue; - CHECK(socketpair(AF_UNIX, type | SOCK_NONBLOCK, 0, pair) == 0); - CHECK(syscall(SYS_readv, pair[1], NULL, 0) == 0); - CHECK(syscall(SYS_writev, pair[0], NULL, 0) == 0); - CHECK(syscall(SYS_readv, -1, NULL, 0) == -1 && errno == EBADF); - CHECK(syscall(SYS_writev, pair[0], NULL, 1025) == -1 && errno == EINVAL); - CHECK(syscall(SYS_readv, pair[1], NULL, -1) == -1 && errno == EINVAL); - CHECK(writev(pair[0], out, 2) == 7); - CHECK(recv(pair[1], joined, sizeof(joined), 0) == 7 && !memcmp(joined, "abcdefg", 7)); - CHECK(recv(pair[1], joined, 1, 0) == -1 && errno == EAGAIN); - CHECK(send(pair[0], "ABCDEFG", 7, 0) == 7); - CHECK(readv(pair[1], in, 2) == 7 && !memcmp(first, "ABC", 3) && !memcmp(second, "DEFG", 4)); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - } - CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); - CHECK(write(pair[0], "abc", 3) == 3); - /* Available bytes end exactly at an iovec boundary. The read must return. */ - CHECK(readv(pair[1], in, 2) == 3 && !memcmp(first, "abc", 3)); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - return 0; -} - -static int futex_park_word; - -static atomic_int process_signal_stage, process_signal_count, process_signal_tid; - -static int unix_nonblock_ioctl(void) -{ - const int types[] = {SOCK_STREAM, SOCK_SEQPACKET, SOCK_DGRAM}; - for (unsigned i = 0; i < 3; ++i) { - int pair[2]; - CHECK(socketpair(AF_UNIX, types[i], 0, pair) == 0); - int alias = dup(pair[0]); - CHECK(alias >= 0); - int value = 7; - CHECK(syscall(SYS_ioctl, alias, FIONBIO, &value) == 0); - CHECK(fcntl(pair[0], F_GETFL) & O_NONBLOCK); - char byte; - CHECK(recv(pair[0], &byte, 1, 0) == -1 && errno == EAGAIN); - CHECK(syscall(SYS_ioctl, alias, FIONBIO, (void *)1) == -1 && errno == EFAULT); - CHECK(fcntl(pair[0], F_GETFL) & O_NONBLOCK); - value = 0; - CHECK(syscall(SYS_ioctl, pair[0], FIONBIO, &value) == 0); - CHECK(!(fcntl(alias, F_GETFL) & O_NONBLOCK)); - CHECK(send(pair[1], "x", 1, MSG_NOSIGNAL) == 1 && recv(alias, &byte, 1, 0) == 1 && byte == 'x'); - CHECK(close(alias) == 0 && close(pair[0]) == 0 && close(pair[1]) == 0); - } - return 0; -} - -static int unix_shutdown_poll(void) -{ - const int types[] = {SOCK_STREAM, SOCK_SEQPACKET, SOCK_DGRAM}; - const short output = POLLOUT | POLLWRNORM | POLLWRBAND; - const short input = POLLIN | POLLRDNORM | POLLRDHUP; - const short events = output | input; - for (unsigned i = 0; i < 3; ++i) { - int fd = socket(AF_UNIX, types[i] | SOCK_NONBLOCK, 0); - CHECK(fd >= 0); - struct pollfd p = {fd, events, 0}; - CHECK(poll(&p, 1, 0) == 1 && p.revents == (output | (types[i] == SOCK_DGRAM ? 0 : POLLHUP))); - CHECK(shutdown(fd, -1) == -1 && errno == EINVAL); - CHECK(shutdown(fd, SHUT_RDWR) == 0); - CHECK(poll(&p, 1, 0) == 1 && p.revents == (events | POLLHUP)); - CHECK(close(fd) == 0); - int pair[2]; - CHECK(socketpair(AF_UNIX, types[i] | SOCK_NONBLOCK, 0, pair) == 0); - CHECK(send(pair[1], "abc", 3, MSG_NOSIGNAL) == 3); - CHECK(shutdown(pair[0], SHUT_RD) == 0); - p = (struct pollfd){pair[0], events, 0}; - CHECK(poll(&p, 1, 0) == 1 && p.revents == events); - char data[8] = {0}; - CHECK(recv(pair[0], data, sizeof(data), 0) == 3 && !memcmp(data, "abc", 3)); - if (types[i] != SOCK_DGRAM) { - CHECK(recv(pair[0], data, sizeof(data), 0) == 0); - CHECK(send(pair[1], "x", 1, MSG_NOSIGNAL) == -1 && errno == EPIPE); - } - p = (struct pollfd){pair[1], events, 0}; - CHECK(poll(&p, 1, 0) == 1 && p.revents == output); - CHECK(shutdown(pair[0], SHUT_RDWR) == 0); - CHECK(poll(&p, 1, 0) == 1 && p.revents == - (types[i] == SOCK_DGRAM ? output : (events | POLLHUP))); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - } - return 0; -} - -static int unix_inq(void) -{ - const int types[] = {SOCK_STREAM, SOCK_SEQPACKET, SOCK_DGRAM}; - for (unsigned i = 0; i < 3; ++i) { - int pair[2], amount = -1; - CHECK(socketpair(AF_UNIX, types[i] | SOCK_NONBLOCK, 0, pair) == 0); - struct { int count; unsigned canary; } result = {-1, 0xaabbccdd}; - CHECK(syscall(SYS_ioctl, pair[0], FIONREAD, &result.count) == 0 && !result.count && result.canary == 0xaabbccdd); - CHECK(syscall(SYS_ioctl, pair[0], FIONREAD, (void *)1) == -1 && errno == EFAULT); - CHECK(send(pair[1], "abc", 3, MSG_NOSIGNAL) == 3 && send(pair[1], "defgh", 5, MSG_NOSIGNAL) == 5); - CHECK(syscall(SYS_ioctl, pair[0], FIONREAD, &amount) == 0 && amount == (types[i] == SOCK_DGRAM ? 3 : 8)); - char data[8]; - CHECK(recv(pair[0], data, 2, MSG_PEEK) == 2); - CHECK(syscall(SYS_ioctl, pair[0], FIONREAD, &amount) == 0 && amount == (types[i] == SOCK_DGRAM ? 3 : 8)); - CHECK(recv(pair[0], data, 2, 0) == 2); - CHECK(syscall(SYS_ioctl, pair[0], FIONREAD, &amount) == 0 && amount == (types[i] == SOCK_STREAM ? 6 : 5)); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - } - int fd = socket(AF_UNIX, SOCK_STREAM, 0); - CHECK(fd >= 0); - struct sockaddr_un address = {.sun_family = AF_UNIX}; - snprintf(address.sun_path + 1, sizeof(address.sun_path) - 1, "inq-%ld", (long)getpid()); - CHECK(bind(fd, (struct sockaddr *)&address, 2 + 1 + strlen(address.sun_path + 1)) == 0 && listen(fd, 1) == 0); - int amount; - CHECK(syscall(SYS_ioctl, fd, FIONREAD, &amount) == -1 && errno == EINVAL); - CHECK(syscall(SYS_ioctl, fd, FIONREAD, (void *)1) == -1 && errno == EINVAL); - CHECK(close(fd) == 0); - return 0; -} - -static int unix_reset(void) -{ - const int types[] = {SOCK_STREAM, SOCK_SEQPACKET}; - for (unsigned type = 0; type < 2; ++type) { - for (unsigned consume = 0; consume < 2; ++consume) { - int pair[2]; - CHECK(socketpair(AF_UNIX, types[type] | SOCK_NONBLOCK, 0, pair) == 0); - CHECK(send(pair[0], "unread", 6, MSG_NOSIGNAL) == 6); - CHECK(close(pair[1]) == 0); - struct pollfd p = {pair[0], POLLIN | POLLOUT | POLLRDHUP, 0}; - CHECK(poll(&p, 1, 0) == 1 && p.revents == (p.events | POLLHUP | POLLERR)); - int error = 0; - socklen_t length = sizeof(error); - char byte; - if (consume) { - CHECK(getsockopt(pair[0], SOL_SOCKET, SO_ERROR, &error, &length) == 0 && error == ECONNRESET); - } else { - CHECK(recv(pair[0], &byte, 1, 0) == -1 && errno == ECONNRESET); - } - CHECK(getsockopt(pair[0], SOL_SOCKET, SO_ERROR, &error, &length) == 0 && error == 0); - CHECK(recv(pair[0], &byte, 1, 0) == 0); - CHECK(poll(&p, 1, 0) == 1 && p.revents == (p.events | POLLHUP)); - CHECK(close(pair[0]) == 0); - } - } - return 0; -} - -static atomic_int alarm_delivered, alarm_tid; -static void alarm_handler(int sig) -{ - if (sig == SIGALRM) { - atomic_store(&alarm_tid, (int)syscall(SYS_gettid)); - atomic_fetch_add(&alarm_delivered, 1); - } -} - -static void *alarm_worker(void *unused) -{ - (void)unused; - sigset_t set; - sigemptyset(&set); - sigaddset(&set, SIGALRM); - if (pthread_sigmask(SIG_UNBLOCK, &set, NULL) || alarm(1)) return (void *)1; - for (unsigned i = 0; i < 300 && !atomic_load(&alarm_delivered); ++i) usleep(10000); - return atomic_load(&alarm_delivered) == 1 && atomic_load(&alarm_tid) == syscall(SYS_gettid) - ? NULL : (void *)2; -} - -static int thread_alarm(void) -{ - CHECK(alarm(0) == 0); - CHECK(syscall(SYS_alarm, 2) == 0 && alarm(0) == 2); - struct itimerval timer = {.it_value.tv_sec = 4}, observed; - CHECK(syscall(SYS_getitimer, ITIMER_REAL, NULL) == -1 && errno == EFAULT); - CHECK(syscall(SYS_getitimer, 99, NULL) == -1 && errno == EINVAL); - CHECK(syscall(SYS_setitimer, ITIMER_REAL, &timer, (void *)1) == -1 && errno == EFAULT); - CHECK(getitimer(ITIMER_REAL, &observed) == 0 && observed.it_value.tv_sec >= 3); - timer.it_value.tv_usec = 1000000; - CHECK(setitimer(ITIMER_REAL, &timer, NULL) == -1 && errno == EINVAL); - CHECK(syscall(SYS_setitimer, ITIMER_REAL, NULL, &observed) == 0 && observed.it_value.tv_sec >= 3); - CHECK(alarm(4) == 0); - pid_t child = fork(); - CHECK(child >= 0); - if (!child) _exit(alarm(0) == 0 ? 0 : 1); - int status; - CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && !WEXITSTATUS(status)); - unsigned remaining = alarm(0); - CHECK(remaining > 0 && remaining <= 4); - struct sigaction action = {.sa_handler = alarm_handler}, old; - sigemptyset(&action.sa_mask); - CHECK(sigaction(SIGALRM, &action, &old) == 0); - sigset_t set, previous; - sigemptyset(&set); - sigaddset(&set, SIGALRM); - CHECK(pthread_sigmask(SIG_BLOCK, &set, &previous) == 0); - atomic_store(&alarm_delivered, 0); - pthread_t worker; - CHECK(pthread_create(&worker, NULL, alarm_worker, NULL) == 0); - void *result = (void *)1; - CHECK(pthread_join(worker, &result) == 0 && result == NULL); - CHECK(alarm(0) == 0); - atomic_store(&alarm_delivered, 0); - timer = (struct itimerval){.it_interval.tv_usec = 40000, .it_value.tv_usec = 10000}; - CHECK(setitimer(ITIMER_REAL, &timer, NULL) == 0); - usleep(90000); - sigset_t pending; - CHECK(sigpending(&pending) == 0 && sigismember(&pending, SIGALRM)); - CHECK(getitimer(ITIMER_REAL, &observed) == 0 && observed.it_interval.tv_usec == 40000 && - observed.it_value.tv_sec == 0 && observed.it_value.tv_usec == 0); - CHECK(pthread_sigmask(SIG_UNBLOCK, &set, NULL) == 0 && atomic_load(&alarm_delivered) == 1); - for (unsigned i = 0; i < 100 && atomic_load(&alarm_delivered) < 3; ++i) usleep(10000); - CHECK(atomic_load(&alarm_delivered) >= 3); - timer = (struct itimerval){0}; - CHECK(setitimer(ITIMER_REAL, &timer, NULL) == 0); - CHECK(getitimer(ITIMER_REAL, &observed) == 0 && observed.it_interval.tv_usec == 0 && - observed.it_value.tv_sec == 0 && observed.it_value.tv_usec == 0); - CHECK(pthread_sigmask(SIG_SETMASK, &previous, NULL) == 0); - CHECK(sigaction(SIGALRM, &old, NULL) == 0); - return 0; -} -static void process_signal_handler(int signal_number) -{ - if (signal_number == SIGUSR2) { - atomic_store(&process_signal_tid, (int)syscall(SYS_gettid)); - atomic_fetch_add(&process_signal_count, 1); - } -} - -static void *process_signal_worker(void *argument) -{ - int directed = *(int *)argument; - while (!atomic_load(&process_signal_stage)) usleep(1000); - sigset_t pending, set; - if (sigpending(&pending) || sigismember(&pending, SIGUSR2) != !directed) return (void *)1; - sigemptyset(&set); - sigaddset(&set, SIGUSR2); - if (pthread_sigmask(SIG_UNBLOCK, &set, NULL)) return (void *)2; - if (!directed) { - for (unsigned n = 0; n < 1000 && !atomic_load(&process_signal_count); ++n) usleep(1000); - if (atomic_load(&process_signal_count) != 1 || - atomic_load(&process_signal_tid) != syscall(SYS_gettid)) return (void *)3; - } else if (atomic_load(&process_signal_count)) return (void *)4; - return NULL; -} - -static int thread_process_signals(void) -{ - struct sigaction action = {.sa_handler = process_signal_handler}, old; - sigemptyset(&action.sa_mask); - CHECK(sigaction(SIGUSR2, &action, &old) == 0); - sigset_t set, previous, pending; - sigemptyset(&set); - sigaddset(&set, SIGUSR2); - CHECK(pthread_sigmask(SIG_BLOCK, &set, &previous) == 0); - for (int directed = 0; directed <= 1; ++directed) { - atomic_store(&process_signal_stage, 0); - atomic_store(&process_signal_count, 0); - atomic_store(&process_signal_tid, 0); - pthread_t worker; - CHECK(pthread_create(&worker, NULL, process_signal_worker, &directed) == 0); - if (directed) CHECK(pthread_kill(pthread_self(), SIGUSR2) == 0); - else CHECK(kill(getpid(), SIGUSR2) == 0); - CHECK(sigpending(&pending) == 0 && sigismember(&pending, SIGUSR2) == 1); - atomic_store(&process_signal_stage, 1); - void *result = (void *)1; - CHECK(pthread_join(worker, &result) == 0 && result == NULL); - CHECK(sigpending(&pending) == 0 && sigismember(&pending, SIGUSR2) == directed); - if (directed) { - CHECK(pthread_sigmask(SIG_UNBLOCK, &set, NULL) == 0); - CHECK(atomic_load(&process_signal_count) == 1 && atomic_load(&process_signal_tid) == syscall(SYS_gettid)); - } - } - CHECK(pthread_sigmask(SIG_SETMASK, &previous, NULL) == 0); - CHECK(sigaction(SIGUSR2, &old, NULL) == 0); - return 0; -} - -static void *unix_lowwater_sender(void *value) -{ - int fd = *(int *)value; - if (write(fd, "abc", 3) != 3) return (void *)1; - usleep(50000); - return write(fd, "def", 3) == 3 ? NULL : (void *)1; -} - -static int unix_lowwater(void) -{ - int pair[2], value; - CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); - socklen_t size = sizeof(value); - CHECK(getsockopt(pair[1], SOL_SOCKET, SO_RCVLOWAT, &value, &size) == 0 && value == 1); - value = -1; - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_RCVLOWAT, &value, sizeof(value)) == 0); - CHECK(getsockopt(pair[1], SOL_SOCKET, SO_RCVLOWAT, &value, &size) == 0 && value == INT32_MAX); - value = 0; - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_RCVLOWAT, &value, sizeof(value)) == 0); - CHECK(getsockopt(pair[1], SOL_SOCKET, SO_RCVLOWAT, &value, &size) == 0 && value == 1); - CHECK(getsockopt(pair[1], SOL_SOCKET, SO_SNDLOWAT, &value, &size) == 0 && value == 1); - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_SNDLOWAT, &value, sizeof(value)) == -1 && errno == ENOPROTOOPT); - value = 6; - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_RCVLOWAT, &value, sizeof(value)) == 0); - char data[8]; - for (int mode = 0; mode < 4; ++mode) { - pthread_t sender; - CHECK(pthread_create(&sender, NULL, unix_lowwater_sender, &pair[0]) == 0); - memset(data, 0, sizeof(data)); - struct iovec vectors[] = {{data, 3}, {data + 3, 5}}; - struct msghdr message = {.msg_iov = vectors, .msg_iovlen = 2}; - ssize_t result; - if (mode == 0) result = read(pair[1], data, sizeof(data)); - else if (mode == 1) result = readv(pair[1], vectors, 2); - else if (mode == 2) result = recvmsg(pair[1], &message, 0); - else result = recv(pair[1], data, sizeof(data), 0); - CHECK(result == 6 && !memcmp(data, "abcdef", 6)); - void *sent = (void *)1; - CHECK(pthread_join(sender, &sent) == 0 && sent == NULL); - } - CHECK(write(pair[0], "abc", 3) == 3); - CHECK(recv(pair[1], data, sizeof(data), MSG_PEEK) == 3 && !memcmp(data, "abc", 3)); - CHECK(recv(pair[1], data, sizeof(data), MSG_PEEK | MSG_WAITALL) == 3); - struct pollfd readable = {.fd = pair[1], .events = POLLIN}; - /* AF_UNIX poll reports queued data even below SO_RCVLOWAT in Linux v6.12. */ - CHECK(poll(&readable, 1, 0) == 1 && (readable.revents & POLLIN)); - CHECK(recv(pair[1], data, sizeof(data), MSG_DONTWAIT) == 3); - struct timeval timeout = {0, 40000}; - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0); - CHECK(write(pair[0], "abc", 3) == 3); - struct timespec before, after; - CHECK(clock_gettime(CLOCK_MONOTONIC, &before) == 0); - CHECK(read(pair[1], data, sizeof(data)) == 3 && !memcmp(data, "abc", 3)); - CHECK(clock_gettime(CLOCK_MONOTONIC, &after) == 0); - CHECK((after.tv_sec - before.tv_sec) * 1000000000LL + after.tv_nsec - before.tv_nsec >= 20000000); - timeout = (struct timeval){0}; - CHECK(setsockopt(pair[1], SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0); - struct sigaction action = {.sa_handler = socket_sigpipe, .sa_flags = SA_RESTART}, old; - sigemptyset(&action.sa_mask); - CHECK(sigaction(SIGUSR1, &action, &old) == 0); - pthread_t self = pthread_self(), sender; - for (int mode = 0; mode < 4; ++mode) { - CHECK(write(pair[0], "abc", 3) == 3); - CHECK(pthread_create(&sender, NULL, timed_signal_sender, &self) == 0); - struct iovec vectors[] = {{data, 2}, {data + 2, 6}}; - struct msghdr message = {.msg_iov = vectors, .msg_iovlen = 2}; - ssize_t result; - if (mode == 0) result = read(pair[1], data, sizeof(data)); - else if (mode == 1) result = readv(pair[1], vectors, 2); - else if (mode == 2) result = recvmsg(pair[1], &message, 0); - else result = recv(pair[1], data, sizeof(data), 0); - CHECK(result == 3 && !memcmp(data, "abc", 3)); - void *sent = (void *)1; - CHECK(pthread_join(sender, &sent) == 0 && sent == NULL); - } - CHECK(sigaction(SIGUSR1, &old, NULL) == 0); - CHECK(close(pair[0]) == 0 && close(pair[1]) == 0); - return 0; -} - -static void *futex_park(void *unused) -{ - (void)unused; - struct timespec limit = {2, 0}; - return (void *)(intptr_t)syscall(SYS_futex, &futex_park_word, - FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &limit, 0, 0); -} - -static int thread_futex_ops(void) -{ - int word = 0, other = 0; - const struct { unsigned op; int arg, before, after; } updates[] = { - {FUTEX_OP_SET, -1, 7, -1}, {FUTEX_OP_ADD, -3, 7, 4}, - {FUTEX_OP_OR, 3, 8, 11}, {FUTEX_OP_ANDN, 3, 11, 8}, - {FUTEX_OP_XOR, 3, 11, 8}, - {FUTEX_OP_SET | FUTEX_OP_OPARG_SHIFT, 31, 0, INT32_MIN}, - {FUTEX_OP_SET | FUTEX_OP_OPARG_SHIFT, 33, 0, 2}, - {FUTEX_OP_SET | FUTEX_OP_OPARG_SHIFT, -1, 0, INT32_MIN}, - }; - for (unsigned i = 0; i < sizeof(updates) / sizeof(updates[0]); ++i) { - other = updates[i].before; - CHECK(syscall(SYS_futex, &word, FUTEX_WAKE_OP | FUTEX_PRIVATE_FLAG, 0, 0, - &other, FUTEX_OP(updates[i].op, updates[i].arg, FUTEX_OP_CMP_EQ, 0)) == 0); - CHECK(other == updates[i].after); - } - other = 7; - CHECK(syscall(SYS_futex, &word, FUTEX_WAKE_OP, 1, 1, &other, - FUTEX_OP(7, 9, 0, 0)) == -1 && errno == ENOSYS && other == 7); - CHECK(syscall(SYS_futex, &word, FUTEX_WAKE_OP, 1, 1, &other, - FUTEX_OP(FUTEX_OP_SET, 9, 7, 0)) == -1 && errno == ENOSYS && other == 9); - int *read_only = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - CHECK(read_only != MAP_FAILED); - CHECK(syscall(SYS_futex, &word, FUTEX_WAKE_OP, 1, 1, read_only, - FUTEX_OP(FUTEX_OP_SET, 0, 0, 0)) == -1 && errno == EFAULT); - CHECK(munmap(read_only, 4096) == 0); - - for (int cmp = FUTEX_OP_CMP_EQ; cmp <= FUTEX_OP_CMP_GE; ++cmp) { - pthread_t thread; - CHECK(pthread_create(&thread, NULL, futex_park, NULL) == 0); - /* Requeue proves the worker has entered the kernel wait before testing wake-op. */ - long parked = 0; - for (int attempt = 0; attempt < 1000 && !parked; ++attempt) { - parked = syscall(SYS_futex, &futex_park_word, - FUTEX_CMP_REQUEUE | FUTEX_PRIVATE_FLAG, 0, 1, &other, 0); - CHECK(parked >= 0); - if (!parked) usleep(1000); - } - CHECK(parked == 1); - const int old[] = {-1, -2, -2, -1, 0, -1}; - other = old[cmp]; - CHECK(syscall(SYS_futex, &word, FUTEX_WAKE_OP | FUTEX_PRIVATE_FLAG, 0, 0, &other, - FUTEX_OP(FUTEX_OP_SET, 8, cmp, -1)) == 1); - void *result = (void *)1; - CHECK(pthread_join(thread, &result) == 0 && result == NULL && other == 8); - } - return 0; -} - -int main(int argc, char **argv) -{ - if (argc > 1 && !strcmp(argv[1], "--membarrier-exec")) return membarrier_exec_check(); - if (argc == 2 && !strcmp(argv[1], "--rlimit-child")) { - struct rlimit value; - return getrlimit(RLIMIT_NOFILE, &value) || value.rlim_cur != 60 || value.rlim_max != 128; - } - probe_executable = (const char *)getauxval(AT_EXECFN); - if (argc == 4 && !strcmp(argv[1], "--thread-exec")) { - if (getpid() != atol(argv[2]) || syscall(SYS_gettid) != getpid()) return 90; - if (fcntl(atoi(argv[3]), F_GETFD) != -1 || errno != EBADF) return 91; - sigset_t pending; - if (sigpending(&pending) || !sigismember(&pending, SIGUSR1) || !sigismember(&pending, SIGUSR2)) return 97; - unsigned remaining = alarm(0); - if (!remaining || remaining > 4) return 98; - return 0; - } - setvbuf(stdout, NULL, _IONBF, 0); - printf("[musl-abi:" PROBE_KIND "] BEGIN\n"); - int status = startup(argc, argv); - failed += status; - printf("[musl-abi:" PROBE_KIND "] startup %s\n", status ? "FAIL" : "PASS"); - const struct { const char *name; int (*run)(void); } tests[] = { - {"heap", heap}, {"memory", memory}, {"nonblocking", nonblocking}, - {"pty", pty}, {"pty_fork", pty_fork}, {"process_sessions", process_sessions}, - {"stdio_reopen", stdio_reopen}, - {"descriptor_allocation", descriptor_allocation}, - {"descriptor_limits", descriptor_limits}, - {"descriptor_boundaries", descriptor_boundaries}, - {"thread_affinity", thread_affinity}, - {"resource_limits", resource_limits}, - {"resource_address_space", resource_address_space}, - {"thread_tls_control", thread_tls_control}, - {"thread_tid_registration", thread_tid_registration}, - {"thread_tid_exit", thread_tid_exit}, - {"permissions", permissions}, {"timestamp_syscalls", timestamp_syscalls}, {"threads", threads}, - {"symlink_syscalls", symlink_syscalls}, - {"signal_queue_syscalls", signal_queue_syscalls}, - {"socket_batch_syscalls", socket_batch_syscalls}, - {"signalfd_syscalls", signalfd_syscalls}, - {"process_vm_syscalls", process_vm_syscalls}, - {"sysv_msg_syscalls", sysv_msg_syscalls}, - {"sysv_sem_syscalls", sysv_sem_syscalls}, - {"proc_directories", proc_directories}, - {"proc_status", proc_status}, - {"rename_replacement", rename_replacement}, - {"unix_streams", unix_streams}, {"thread_contention", thread_contention}, - {"unix_rights", unix_rights}, {"thread_exit_lifecycle", thread_exit_lifecycle}, - {"unix_rights_boundaries", unix_rights_boundaries}, - {"thread_cancellation", thread_cancellation}, - {"native_signals", native_signals}, {"thread_signal_restart", thread_signal_restart}, - {"thread_exec", thread_exec}, {"unix_rights_cycles", unix_rights_cycles}, - {"unix_packets", unix_packets}, - {"unix_waitall", unix_waitall}, - {"unix_credentials", unix_credentials}, - {"thread_timed_interrupts", thread_timed_interrupts}, - {"unix_close_during_io", unix_close_during_io}, - {"unix_vectors", unix_vectors}, - {"unix_timeouts", unix_timeouts}, - {"thread_futex_ops", thread_futex_ops}, - {"capabilities", capabilities_abi}, - {"rseq", rseq_abi}, - {"thread_futex2", thread_futex2}, - {"thread_clone3", thread_clone3}, - {"process_prctl", process_prctl}, - {"unix_lowwater", unix_lowwater}, - {"thread_process_signals", thread_process_signals}, - {"thread_alarm", thread_alarm}, - {"unix_shutdown_poll", unix_shutdown_poll}, - {"unix_inq", unix_inq}, - {"unix_reset", unix_reset}, - {"poll_interrupts", poll_interrupts}, - {"poll_files", poll_files}, - {"unix_nonblock_ioctl", unix_nonblock_ioctl}, - }; - unsigned selected = 0; - for (unsigned i = 0; i < sizeof(tests) / sizeof(tests[0]); ++i) { - if (argc == 3 && !strcmp(argv[1], "--case") && strcmp(argv[2], tests[i].name)) continue; - ++selected; - status = tests[i].run(); - failed += status; - printf("[musl-abi:" PROBE_KIND "] %s %s\n", tests[i].name, status ? "FAIL" : "PASS"); - } - if (!selected) { printf("[musl-abi:" PROBE_KIND "] unknown test case\n"); return 2; } - printf("[musl-abi:" PROBE_KIND "] END failed=%u\n", failed); - return failed != 0; -} From 34d52c7907cd97e17f3840d01c996080ec86bb97 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Wed, 2 Dec 2026 14:22:15 +0800 Subject: [PATCH 91/97] fix(netlink): queue udev coldplug bursts within the receive budget --- .../en/LC_MESSAGES/userspace-api/ipv6.po | 31 ++++++++++------ .../ja/LC_MESSAGES/userspace-api/ipv6.po | 24 ++++++++----- Documentation/userspace-api/ipv6.rst | 7 +++- include/uapi/linux/socket.h | 1 + net/socket/netlink.c | 35 ++++++++++++++----- tools/tests/ipv6_control_test.c | 22 ++++++++++-- 6 files changed, 89 insertions(+), 31 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po index 9388364c..e8b5d7fd 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/ipv6.po @@ -580,17 +580,26 @@ msgstr "" "previous setting." msgid "" -"接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 位置。预留失败时返回 " -"``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 " -"属于实际 socket,传递 FD 或切换网络后继续保留。" -msgstr "" -"The receive queue conservatively charges 8192 bytes per datagram. " -"Multipart queries reserve two slots for data and the terminator. Failed " -"reservation returns ``ENOBUFS`` before the request changes network state." -" Shrinking the receive buffer preserves queued messages and new messages " -"wait for available capacity. Reading releases capacity, and growing the " -"buffer updates writability. Buffer settings belong to the actual socket " -"and survive FD transfer or a network switch." +"初始用户命名空间中拥有 ``CAP_NET_ADMIN`` 的调用者可通过 ``SO_RCVBUFFORCE`` " +"请求更大的接收缓冲区。设置时无需预分配内存,仍通过 ``SO_RCVBUF`` 查询有效大小。" +msgstr "" +"Callers with ``CAP_NET_ADMIN`` in the initial user namespace may request " +"a larger receive buffer with ``SO_RCVBUFFORCE``. The buffer is not " +"allocated up front and ``SO_RCVBUF`` reports its effective size." + +msgid "" +"``NETLINK_KOBJECT_UEVENT`` 按消息头和过滤后的实际数据长度计费。 路由和控制数据报各计 8192 " +"字节,多部分查询预留数据和结束标记两个 位置。预留失败时返回 ``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 " +"已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 属于实际 socket,传递 FD 或切换网络后继续保留。" +msgstr "" +"``NETLINK_KOBJECT_UEVENT`` charges the message header and the actual " +"filtered payload length. Route and control datagrams each charge 8192 " +"bytes. Multipart queries reserve slots for data and the terminator. A " +"failed reservation returns ``ENOBUFS`` before the request changes network" +" state. Shrinking the buffer preserves queued messages, and new messages " +"need available capacity. Reading releases capacity, and growing the " +"buffer updates writability. These settings belong to the socket and " +"survive file descriptor transfer or a network switch." msgid "" "路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po index b8c5d8d2..d5c84c20 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/ipv6.po @@ -484,14 +484,22 @@ msgstr "" "を返します。短い設定値、不正なユーザーポインター、負の長さはエラーとなり、元の設定を保持します。" msgid "" -"接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 位置。预留失败时返回 " -"``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 " -"属于实际 socket,传递 FD 或切换网络后继续保留。" -msgstr "" -"受信キューは各データグラムを 8192 バイトとして保守的に計上します。複数部分の照会ではデータと終了メッセージ用に 2 " -"枠を予約します。予約失敗時はネットワーク状態を変更する前に ``ENOBUFS`` " -"を返します。受信バッファを縮小しても既存のメッセージを保持し、新規メッセージは容量の回復を待ちます。読み取りで容量を解放し、拡張時は書き込み可能状態を更新します。バッファ設定は実際の" -" socket に属し、FD の受け渡しやネットワークの切り替え後も保持します。" +"初始用户命名空间中拥有 ``CAP_NET_ADMIN`` 的调用者可通过 ``SO_RCVBUFFORCE`` " +"请求更大的接收缓冲区。设置时无需预分配内存,仍通过 ``SO_RCVBUF`` 查询有效大小。" +msgstr "" +"初期ユーザー名前空間で ``CAP_NET_ADMIN`` を持つ呼び出し元は、``SO_RCVBUFFORCE`` " +"で受信バッファーの上限を拡張できます。設定時にメモリーは事前確保されず、有効なサイズは引き続き ``SO_RCVBUF`` で取得します。" + +msgid "" +"``NETLINK_KOBJECT_UEVENT`` 按消息头和过滤后的实际数据长度计费。 路由和控制数据报各计 8192 " +"字节,多部分查询预留数据和结束标记两个 位置。预留失败时返回 ``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 " +"已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 属于实际 socket,传递 FD 或切换网络后继续保留。" +msgstr "" +"``NETLINK_KOBJECT_UEVENT`` " +"の受信容量には、メッセージヘッダーとフィルター適用後の実データ長を計上します。経路と制御のデータグラムはそれぞれ 8192 " +"バイトを計上し、複数部分の問い合わせではデータと終端マーカーの二枠を予約します。予約に失敗するとネットワーク状態を変更する前に " +"``ENOBUFS`` " +"を返します。受信バッファーを縮小してもキュー内のメッセージは保持され、新着メッセージには空き容量が必要です。読み取りで容量を解放し、拡張で書き込み可能状態を更新します。設定はソケットに属し、ファイルディスクリプターの受け渡しやネットワークの切り替え後も保持されます。" msgid "" "路由请求按顺序处理数据报中的有效消息前缀,忽略首个无效或不完整消息及后续 字节。末条完整消息可以省略对齐填充。发送成功返回整个数据报的字节数,包含" diff --git a/Documentation/userspace-api/ipv6.rst b/Documentation/userspace-api/ipv6.rst index 53106e04..86a47cbd 100644 --- a/Documentation/userspace-api/ipv6.rst +++ b/Documentation/userspace-api/ipv6.rst @@ -111,7 +111,12 @@ netlink socket 的 ``SO_SNDBUF`` 和 ``SO_RCVBUF`` 默认有效大小均为 6553 缓冲区减 32 字节的限制,超过时返回 ``EMSGSIZE``。短设置值、错误用户指针和 负长度返回错误并保留原设置。 -接收队列按每个数据报 8192 字节保守计费,多部分查询预留数据和结束标记两个 +初始用户命名空间中拥有 ``CAP_NET_ADMIN`` 的调用者可通过 +``SO_RCVBUFFORCE`` 请求更大的接收缓冲区。设置时无需预分配内存,仍通过 +``SO_RCVBUF`` 查询有效大小。 + +``NETLINK_KOBJECT_UEVENT`` 按消息头和过滤后的实际数据长度计费。 +路由和控制数据报各计 8192 字节,多部分查询预留数据和结束标记两个 位置。预留失败时返回 ``ENOBUFS``,请求尚未修改网络状态。缩小接收缓冲区保留 已排队消息,新消息等待预算恢复;读取释放预算,扩容更新可写状态。缓冲区设置 属于实际 socket,传递 FD 或切换网络后继续保留。 diff --git a/include/uapi/linux/socket.h b/include/uapi/linux/socket.h index 9ef9e8eb..b55d9b6f 100644 --- a/include/uapi/linux/socket.h +++ b/include/uapi/linux/socket.h @@ -66,6 +66,7 @@ struct sockaddr_un { #define SO_BINDTOIFINDEX 62 #define SO_ATTACH_FILTER 26 #define SO_DETACH_FILTER 27 +#define SO_RCVBUFFORCE 33 #define SO_TIMESTAMP_OLD 29 #define SO_TIMESTAMP_NEW 63 #define SO_TIMESTAMP SO_TIMESTAMP_OLD diff --git a/net/socket/netlink.c b/net/socket/netlink.c index 6e5403be..e6dd8e9f 100644 --- a/net/socket/netlink.c +++ b/net/socket/netlink.c @@ -110,6 +110,18 @@ static bool nl_queue_room(const struct netlink_socket *s, uint32_t bytes) return bytes <= s->rcvbuf && s->queued_bytes <= s->rcvbuf - bytes; } +/** @brief Compute the receive-buffer charge for a queued datagram. + * @param s Borrowed recipient socket. + * @param length Stored payload length after socket filtering. + * @return Actual uevent allocation size or the bounded route/control message slot. + */ +static uint32_t nl_message_charge(const struct netlink_socket *s, uint32_t length) +{ + if (s->protocol == NETLINK_KOBJECT_UEVENT) + return sizeof(struct netlink_message) + length; + return NL_MESSAGE_MAX; +} + /** @brief Test a nonzero port against bound endpoints in the creating scope. * @param port Proposed ID. @param except Socket excluded from the comparison. * @return True when another socket in the same namespace and protocol owns it. */ @@ -632,7 +644,8 @@ static int nl_queue_datagram(struct netlink_socket *s, uint32_t port, uint32_t g uint32_t admitted = socket_filter_run(s->filter, data, length); if (!admitted) return 0; - if (!nl_queue_room(s, NL_MESSAGE_MAX)) + uint32_t charge = nl_message_charge(s, admitted); + if (!nl_queue_room(s, charge)) return -LINUX_EAGAIN; struct netlink_message *message = kernel_malloc(sizeof(*message) + admitted); if (!message) @@ -646,7 +659,7 @@ static int nl_queue_datagram(struct netlink_socket *s, uint32_t port, uint32_t g else s->head = message; s->tail = message; - s->queued_bytes += NL_MESSAGE_MAX; + s->queued_bytes += charge; return (int)admitted; } @@ -1901,7 +1914,7 @@ static int nl_receive(struct task_file *file,void *data,uint32_t length,uint32_t int result=(flags & MSG_TRUNC) ? (int)m->length : (int)copied; if (!(flags & MSG_PEEK)) { s->head=m->next; if (!s->head) s->tail=NULL; - s->queued_bytes-=NL_MESSAGE_MAX; kernel_free(m); + s->queued_bytes-=nl_message_charge(s, m->length); kernel_free(m); } return result; } @@ -1945,7 +1958,7 @@ short task_netlink_poll(const struct task_file *file,short events) struct netlink_socket *s=nl_socket(file); if (!s) return POLLNVAL; return (s->overrun ? POLLERR : 0) | (s->head ? events&POLLIN : 0) | - (nl_queue_room(s, NL_MESSAGE_MAX) ? events&POLLOUT : 0); + (nl_queue_room(s, nl_message_charge(s, 0)) ? events&POLLOUT : 0); } /** @brief Return the next queued netlink datagram size. @@ -2070,6 +2083,8 @@ static int nl_protocol_option(struct task *task, struct netlink_socket *s, bool * @note SO_REUSEADDR stores per-socket state without allowing duplicate ports. * SO_SNDBUF/SO_RCVBUF clamp unsigned requests before doubling, enforce minima, * and preserve queued messages when shrinking. Getters return effective sizes. + * SO_RCVBUFFORCE accepts a larger receive budget from initial-namespace + * CAP_NET_ADMIN without allocating that budget up front. * Published sockets retain their creating namespace after FD allocation succeeds. * Filter replacement is published only after the candidate is fully validated. */ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, @@ -2152,7 +2167,8 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, s->filter = NULL; return 0; } - if (a2 != SO_REUSEADDR && a2 != SO_SNDBUF && a2 != SO_RCVBUF && + bool forced = a2 == SO_RCVBUFFORCE; + if (a2 != SO_REUSEADDR && a2 != SO_SNDBUF && a2 != SO_RCVBUF && !forced && (a2 != SO_PASSCRED || s->protocol != NETLINK_KOBJECT_UEVENT)) return -LINUX_ENOPROTOOPT; if ((int32_t)a4 < (int32_t)sizeof(int32_t)) @@ -2160,9 +2176,12 @@ int64_t syscall_netlink(uint64_t number,uint64_t a0,uint64_t a1,uint64_t a2, int32_t value; int ret = socket_user_import(task, a3, &value, sizeof(value)); if (ret) return ret; - if (a2 == SO_SNDBUF || a2 == SO_RCVBUF) { - uint32_t size = (uint32_t)value; - if (size > NL_BUFFER_REQUEST_MAX) size = NL_BUFFER_REQUEST_MAX; + if (a2 == SO_SNDBUF || a2 == SO_RCVBUF || forced) { + if (forced && !(task_initial_capabilities(task) & (1ULL << CAP_NET_ADMIN))) + return -LINUX_EPERM; + uint32_t limit = forced ? INT32_MAX / 2u : NL_BUFFER_REQUEST_MAX; + uint32_t size = forced && value < 0 ? 0 : (uint32_t)value; + if (size > limit) size = limit; size *= 2u; uint32_t minimum = a2 == SO_SNDBUF ? NL_SNDBUF_MIN : NL_RCVBUF_MIN; if (size < minimum) size = minimum; diff --git a/tools/tests/ipv6_control_test.c b/tools/tests/ipv6_control_test.c index 845725ed..ccefe189 100644 --- a/tools/tests/ipv6_control_test.c +++ b/tools/tests/ipv6_control_test.c @@ -957,7 +957,7 @@ static void check_netlink_metadata_options(void) puts("PASS netlink metadata options: per-OFD state, short buffers and membership lifecycle"); } -/** @brief Route processed device notifications without exposing the kernel group. */ +/** @brief Verify privileged uevents, sender metadata and burst queue capacity. */ static void check_uevent_userspace_delivery(void) { int sender = (int)call(__NR_socket, AF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT, 0, 0); @@ -982,12 +982,29 @@ static void check_uevent_userspace_delivery(void) assert(!call(__NR_bind, sender, (uintptr_t)&sender_address, sizeof(sender_address), 0, 0)); assert(!call(__NR_bind, worker, (uintptr_t)&worker_address, sizeof(worker_address), 0, 0)); + char output[64]; + int32_t capacity = 1024 * 1024; + assert(call(__NR_setsockopt, kernel, SOL_SOCKET, SO_RCVBUFFORCE, + (uintptr_t)&capacity, sizeof(capacity)) == -LINUX_EPERM); + for (unsigned i = 0; i < 64; ++i) + netlink_uevent_device("add", "/devices/coldplug", "block", "", 0); + for (unsigned i = 0; i < 64; ++i) + assert(receive(kernel, output, sizeof(output)) == sizeof(output)); + assert(!nl_socket(&files[kernel])->queued_bytes); + assert(receive(kernel, output, sizeof(output)) == -LINUX_EAGAIN); + const char payload[] = "processed-device"; assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, (uintptr_t)&udev_address, sizeof(udev_address)) == -LINUX_EPERM); assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, (uintptr_t)&worker_address, sizeof(worker_address)) == -LINUX_EPERM); current.cap_effective = 1ULL << CAP_NET_ADMIN; + uint32_t capacity_size = sizeof(capacity); + assert(!call(__NR_setsockopt, kernel, SOL_SOCKET, SO_RCVBUFFORCE, + (uintptr_t)&capacity, sizeof(capacity))); + assert(!call(__NR_getsockopt, kernel, SOL_SOCKET, SO_RCVBUF, + (uintptr_t)&capacity, (uintptr_t)&capacity_size)); + assert(capacity == 2 * 1024 * 1024); assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, (uintptr_t)&kernel_address, sizeof(kernel_address)) == -LINUX_EPERM); assert(task_netlink_send(&files[sender], payload, sizeof(payload), 0, @@ -998,7 +1015,6 @@ static void check_uevent_userspace_delivery(void) (uintptr_t)&udev_address, sizeof(udev_address)) == sizeof(payload)); current.uid = 2000; current.gid = 2001; - char output[64]; assert(receive(kernel, output, sizeof(output)) == -LINUX_EAGAIN); assert(receive(sender, output, sizeof(output)) == -LINUX_EAGAIN); assert(receive(worker, output, sizeof(output)) == -LINUX_EAGAIN); @@ -1055,7 +1071,7 @@ static void check_uevent_userspace_delivery(void) } current = (struct task){0}; assert(!allocations); - puts("PASS kobject uevent: userspace group isolation, privileged delivery and sender metadata"); + puts("PASS kobject uevent: coldplug bursts, receive budgets, group isolation and sender metadata"); } /** @brief Exercise filter installation and message delivery on both netlink protocols. */ From a459428ea7ddda59d5ba8f9df832ef0c558ca353 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Wed, 2 Dec 2026 14:40:25 +0800 Subject: [PATCH 92/97] test: retire obsolete guest suite fixtures --- Documentation/core-api/network-devices.rst | 2 +- tools/tests/credentials_runtime_probe.c | 2 +- tools/tests/ltp_guest_runner.c | 58 ----- tools/tests/network_guest_test.c | 236 --------------------- tools/tests/pipe_stat_type_test.c | 2 +- 5 files changed, 3 insertions(+), 297 deletions(-) delete mode 100644 tools/tests/ltp_guest_runner.c delete mode 100644 tools/tests/network_guest_test.c diff --git a/Documentation/core-api/network-devices.rst b/Documentation/core-api/network-devices.rst index 23529d53..bbb75171 100644 --- a/Documentation/core-api/network-devices.rst +++ b/Documentation/core-api/network-devices.rst @@ -51,7 +51,7 @@ Linux 网络管理入口覆盖按名称、索引查询,IPv4/IPv6 地址和路 ip route add default via 192.0.2.1 dev eth1 metric 100 ip -6 addr add 2001:db8:1::10/64 dev eth1 ip -6 route add default via fe80::1 dev eth1 - udhcpc -i eth1 + networkctl renew eth1 # Interface managed by systemd-networkd with DHCP enabled. cat /proc/net/dev /proc/net/route /proc/net/arp /proc/net/if_inet6 ``/proc/net/dev`` 列举所有已登记接口,包括未分配 IPv4 地址或行政关闭的设备。 diff --git a/tools/tests/credentials_runtime_probe.c b/tools/tests/credentials_runtime_probe.c index 4c5e5703..a270457e 100644 --- a/tools/tests/credentials_runtime_probe.c +++ b/tools/tests/credentials_runtime_probe.c @@ -198,7 +198,7 @@ int main(int argc, char **argv) CHECK(nnp(PR_SET_NO_NEW_PRIVS, 0) == -1 && errno == EINVAL); return 0; } - puts("[credentials] BEGIN raw Linux syscall and musl setxid contracts"); + puts("[credentials] BEGIN raw Linux syscall and libc credential contracts"); struct { const char *name; int (*run)(void); } cases[] = { {"saved IDs and groups", saved_ids}, {"filesystem IDs", fs_ids}, {"root capability drop", capability_drop}, {"thread credentials", thread_ids}, diff --git a/tools/tests/ltp_guest_runner.c b/tools/tests/ltp_guest_runner.c deleted file mode 100644 index bb1f773b..00000000 --- a/tools/tests/ltp_guest_runner.c +++ /dev/null @@ -1,58 +0,0 @@ -#include -#include -#include -#include -#include -#include - -int main(void) -{ - static const char *tests[] = {"getcwd01", "fcntl01", "fstat02", "mprotect01", "chmod01", "fchmod01", "chown01", - "pthread_create_1-1", "pthread_join_1-1", "pthread_mutex_lock_1-1", "pthread_cond_wait_1-1", - "pthread_cancel_1-1", "pthread_key_create_1-1", "pthread_barrier_wait_1-1", - "pthread_rwlock_rdlock_1-1", "pthread_once_1-1", "pthread_mutex_timedlock_1-1", - "pthread_cond_timedwait_1-1", "pthread_mutex_trylock_1-1", "sem_timedwait_1-1", "pthread_spin_lock_1-1"}; - unsigned failed = 0; - setvbuf(stdout, NULL, _IONBF, 0); - for (unsigned i = 0; i < sizeof(tests) / sizeof(tests[0]); ++i) { - char path[128]; - snprintf(path, sizeof(path), "/usr/lib/reliefos/tests/%s.elf", tests[i]); - printf("[ltp-musl] BEGIN %s\n", tests[i]); - pid_t child = fork(); - if (child == 0) { - char *args[] = {path, NULL}; - char *env[] = {"PATH=/bin:/sbin:/usr/bin:/usr/sbin", "TMPDIR=/tmp", NULL}; - execve(path, args, env); - printf("[ltp-musl] exec %s errno=%d\n", tests[i], errno); - _exit(127); - } - int status = 0; - pid_t result; - struct timespec started, now; - int expired = 0; - if (clock_gettime(CLOCK_MONOTONIC, &started)) return 1; - for (;;) { - result = child < 0 ? -1 : waitpid(child, &status, WNOHANG); - if (result == child || (result < 0 && errno != EINTR)) break; - if (clock_gettime(CLOCK_MONOTONIC, &now)) return 1; - if (now.tv_sec - started.tv_sec >= 30) { - printf("[ltp-musl] TIMEOUT %s after 30 seconds\n", tests[i]); - expired = 1; - if (kill(child, SIGKILL)) return 1; - do { result = waitpid(child, &status, 0); } while (result < 0 && errno == EINTR); - break; - } - struct timespec delay = {0, 10000000}; - nanosleep(&delay, NULL); - } - if (result != child || child < 0) { - printf("[ltp-musl] runner failure %s errno=%d\n", tests[i], errno); - return 1; - } - int code = expired ? 124 : WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status); - printf("[ltp-musl] END %s code=%d wait_status=%d\n", tests[i], code, status); - failed += code != 0; - } - printf("[ltp-musl] DONE failures=%u\n", failed); - return failed != 0; -} diff --git a/tools/tests/network_guest_test.c b/tools/tests/network_guest_test.c deleted file mode 100644 index 1a2cbd58..00000000 --- a/tools/tests/network_guest_test.c +++ /dev/null @@ -1,236 +0,0 @@ -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static int failures; -#define CHECK(test, text) do { int ok = !!(test); printf("[network] %s %s (errno=%d)\n", ok ? "PASS" : "FAIL", text, errno); if (!ok) ++failures; } while (0) - -static int run(char *const command[]) -{ - pid_t child = fork(); - if (child == 0) { execv(command[0], command); _exit(127); } - int status; - if (child < 0 || waitpid(child, &status, 0) != child) return -1; - return WIFEXITED(status) ? WEXITSTATUS(status) : -1; -} - -static int unprivileged_management(void) -{ - if (setgroups(0, NULL) < 0 || setgid(1000) < 0 || setuid(1000) < 0) return 1; - struct reliefos_net_dhcp dhcp; - struct reliefos_net_config config; - CHECK(reliefos_net_config(&config) == 0 && config.local_ip == 0x0a25000f, - "ordinary user reads network service"); - CHECK(reliefos_net_dhcp_renew(4000, &dhcp) < 0 && errno == EACCES, - "ordinary user DHCP requires authorization"); - CHECK(reliefos_net_config(&config) == 0 && config.local_ip == 0x0a25000f, - "network service remains usable after denied update"); - /* The GUI privilege workflow is covered by ReliefOS's Network Controller - * integration test; this kernel network test stays independent of apps. */ - return failures != 0; -} - -int main(int argc, char **argv) -{ - setvbuf(stdout, NULL, _IONBF, 0); - if (argc == 2 && !strcmp(argv[1], "--netmand-unprivileged")) return unprivileged_management(); - puts("[network] START"); - alarm(100); - int control = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); - struct reliefos_net_control request = {.version = RELIEFOS_NET_CONTROL_VERSION, - .operation = RELIEFOS_NET_CONTROL_CONFIG}; - CHECK(control >= 0 && ioctl(control, RELIEFOS_NET_CONTROL_IOCTL, &request) == 0 && !request.result, - "real interface query"); - struct reliefos_net_config *config = &request.data.config; - printf("[network] address=%08x gateway=%08x dns=%08x flags=%x\n", config->local_ip, - config->gateway_ip, config->dns_ip, config->flags); - CHECK(config->local_ip == 0x0a25000f && config->gateway_ip == 0x0a250002 && - config->dns_ip == 0x0a250003, "DHCP custom subnet and DNS"); - close(control); - struct reliefos_net_config managed; - int management = -1; - for (unsigned i = 0; i < 20; ++i) { - management = reliefos_net_config(&managed); - if (!management) break; - usleep(500000); - } - CHECK(management == 0 && managed.local_ip == 0x0a25000f, "production netmand configuration IPC"); - struct reliefos_net_dhcp renewed; - CHECK(reliefos_net_dhcp_renew(4000, &renewed) == 0 && renewed.status == 0 && - renewed.config.local_ip == 0x0a25000f, "root DHCP update through production service"); - char *ordinary[] = {"/usr/lib/reliefos/tests/linux-inventory.elf", "--netmand-unprivileged", NULL}; - CHECK(run(ordinary) == 0, "network controller authorization workflow"); - int datagrams[2] = {socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0), socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0)}; - struct sockaddr_in loop = {.sin_family=AF_INET, .sin_port=htons(53000), .sin_addr={.s_addr=htonl(0x7f000001)}}; - CHECK(bind(datagrams[1], (void *)&loop, sizeof(loop)) == 0, "UDP loopback bind"); - struct iovec outgoing[2] = {{"abc", 3}, {"def", 3}}; - struct msghdr message = {.msg_name=&loop, .msg_namelen=sizeof(loop), .msg_iov=outgoing, .msg_iovlen=2}; - CHECK(sendmsg(datagrams[0], &message, 0) == 6, "UDP sendmsg gathers one datagram"); - char first[2], second[2]; - struct iovec incoming[2] = {{first, 2}, {second, 2}}; - struct sockaddr_in from; - message = (struct msghdr){.msg_name=&from, .msg_namelen=sizeof(from), .msg_iov=incoming, .msg_iovlen=2}; - CHECK(recvmsg(datagrams[1], &message, 0) == 4 && message.msg_flags == MSG_TRUNC && - !memcmp(first, "ab", 2) && !memcmp(second, "cd", 2) && from.sin_family == AF_INET, - "UDP recvmsg source, scatter and MSG_TRUNC"); - close(datagrams[0]); close(datagrams[1]); - /* Wait for the udhcpc hook to publish the actual DHCP resolver. */ - for (unsigned i = 0; i < 100; ++i) { - FILE *file = fopen("/etc/resolv.conf", "r"); - char text[256] = {0}; - if (file) { fread(text, 1, sizeof(text)-1, file); fclose(file); } - if (strstr(text, "10.37.0.3")) break; - usleep(100000); - } - struct addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_STREAM}, *addresses = NULL; - int ret = getaddrinfo("fixture.test", "18080", &hints, &addresses); - CHECK(!ret && addresses && ((struct sockaddr_in *)addresses->ai_addr)->sin_addr.s_addr == htonl(0x0a250002), - "unmodified musl DNS over UDP"); - if (addresses) { - int fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); - ret = connect(fd, addresses->ai_addr, addresses->ai_addrlen); - CHECK(ret == 0 || (ret < 0 && errno == EINPROGRESS), "nonblocking connect result"); - struct pollfd p = {.fd=fd, .events=POLLOUT}; - int error = -1; - socklen_t length = sizeof(error); - CHECK(poll(&p, 1, 15000) > 0 && (p.revents & POLLOUT) && - getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &length) == 0 && error == 0 && length == sizeof(error), - "poll and SO_ERROR handshake completion"); - CHECK(fcntl(fd, F_SETFL, 0) == 0, "TCP blocking flag change"); - pid_t child = fork(); - if (!child) { - const char request[] = "GET /payload HTTP/1.0\r\nHost: fixture.test\r\n\r\n"; - char byte; - usleep(100000); - int ok = write(fd, request, sizeof(request)-1) == sizeof(request)-1 && read(fd, &byte, 1) == 1 && byte == 'H'; - close(fd); - _exit(ok ? 0 : 1); - } - close(fd); - int child_status = -1; - CHECK(child > 0 && waitpid(child, &child_status, 0) == child && WIFEXITED(child_status) && !WEXITSTATUS(child_status), - "inherited TCP descriptor survives parent close"); - freeaddrinfo(addresses); - } - struct reliefos_time_sync sync; - ret = reliefos_time_ntp_sync(4000, &sync); - struct timespec now; - clock_gettime(CLOCK_REALTIME, &now); - CHECK(ret == 0 && sync.valid && sync.status == RELIEFOS_NET_STATUS_OK && - now.tv_sec >= 2208988800LL && now.tv_sec < 2208988900LL, - "NTP era 2040 and actual CLOCK_REALTIME update"); - printf("[network] clock=%lld.%09ld ntp-status=%u\n", (long long)now.tv_sec, now.tv_nsec, sync.status); - char *wget[] = {"/usr/bin/curl", "--fail", "--output", "/tmp/net-download", "http://fixture.test:18080/payload", NULL}; - CHECK(run(wget) == 0, "HTTP download with curl"); - FILE *download = fopen("/tmp/net-download", "rb"); - unsigned count = 0; - int byte, valid = !!download; - if (download) { - while ((byte = fgetc(download)) != EOF) { if (byte != (int)(count % 251)) valid = 0; ++count; } - if (ferror(download)) valid = 0; - fclose(download); - } - CHECK(valid && count == 1024*1024, "one MiB download exact content"); - char *python[] = {"/usr/bin/python3", "/tmp/net-https.py", NULL}; - CHECK(run(python) == 0, "unmodified Python HTTPS and certificate verification"); - { - const size_t expected_size = 1024U * 1024U; - char *body = malloc(expected_size + 1U); - struct reliefos_http_response https_response = {0}; - int native_ok = 0; - if (body) { - int request_result = reliefos_http_get( - "https://fixture.test:18443/payload", 20000U, body, - (uint32_t)(expected_size + 1U), NULL, 0, &https_response); - native_ok = request_result == 0 && - https_response.net_status == RELIEFOS_NET_STATUS_OK && - https_response.http_status == 200U && - https_response.body_len == expected_size; - for (size_t i = 0; native_ok && i < expected_size; ++i) { - if ((unsigned char)body[i] != (unsigned char)(i % 251U)) { - native_ok = 0; - } - } - } - CHECK(native_ok, "native libc HTTPS GET verifies CA and exact payload"); - free(body); - - struct reliefos_http_response download_response = {0}; - int download_result = reliefos_http_download( - "https://fixture.test:18443/payload", "/tmp/net-native-download", - 20000U, NULL, NULL, &download_response); - FILE *native_download = fopen("/tmp/net-native-download", "rb"); - size_t downloaded = 0; - int download_ok = download_result == 0 && native_download != NULL; - if (native_download) { - int byte_value; - while ((byte_value = fgetc(native_download)) != EOF) { - if (byte_value != (int)(downloaded % 251U)) download_ok = 0; - ++downloaded; - } - if (ferror(native_download)) download_ok = 0; - fclose(native_download); - } - CHECK(download_ok && downloaded == expected_size, - "native HTTPS streaming download preserves exact payload"); - - struct reliefos_http_response mismatch = {0}; - char small_body[256]; - int mismatch_result = reliefos_http_get( - "https://10.37.0.2:18443/payload", 20000U, small_body, - sizeof(small_body), NULL, 0, &mismatch); - CHECK(mismatch_result == 0 && - mismatch.net_status == RELIEFOS_NET_STATUS_TLS_FAILED, - "native HTTPS rejects certificate hostname mismatch"); - - struct reliefos_http_response downgrade = {0}; - int downgrade_result = reliefos_http_get( - "https://fixture.test:18443/downgrade", 20000U, small_body, - sizeof(small_body), NULL, 0, &downgrade); - CHECK(downgrade_result == 0 && - downgrade.net_status == RELIEFOS_NET_STATUS_TLS_FAILED, - "native HTTPS rejects cleartext downgrade redirect"); - } - control = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); - puts("[network] LINK_DOWN_REQUEST"); - for (unsigned i = 0; i < 70; ++i) { - request = (struct reliefos_net_control){.version=RELIEFOS_NET_CONTROL_VERSION, .operation=RELIEFOS_NET_CONTROL_CONFIG}; - if (ioctl(control, RELIEFOS_NET_CONTROL_IOCTL, &request) < 0) break; - if (!(request.data.config.flags & RELIEFOS_NET_CONFIG_FLAG_ACTIVE)) break; - usleep(100000); - } - CHECK((request.data.config.flags & (RELIEFOS_NET_CONFIG_FLAG_ACTIVE | RELIEFOS_NET_CONFIG_FLAG_PRESENT)) == - RELIEFOS_NET_CONFIG_FLAG_PRESENT, "disconnected link remains present but inactive"); - puts("[network] LINK_UP_REQUEST"); - for (unsigned i = 0; i < 70; ++i) { - if (ioctl(control, RELIEFOS_NET_CONTROL_IOCTL, &request) < 0) break; - if (request.data.config.flags & RELIEFOS_NET_CONFIG_FLAG_ACTIVE) break; - usleep(100000); - } - CHECK(request.data.config.flags & RELIEFOS_NET_CONFIG_FLAG_ACTIVE, "carrier recovers after reconnect"); - request = (struct reliefos_net_control){.version=RELIEFOS_NET_CONTROL_VERSION, .operation=RELIEFOS_NET_CONTROL_DHCP, - .data.dhcp={.timeout_ms=3000}}; - CHECK(ioctl(control, RELIEFOS_NET_CONTROL_IOCTL, &request) == 0 && !request.result && - !request.data.dhcp.status && request.data.dhcp.config.local_ip == 0x0a25000f, "DHCP reacquires after reconnect"); - close(control); - alarm(0); - printf("[network] DONE failures=%d\n", failures); - return failures != 0; -} diff --git a/tools/tests/pipe_stat_type_test.c b/tools/tests/pipe_stat_type_test.c index 54ed0591..1850b728 100644 --- a/tools/tests/pipe_stat_type_test.c +++ b/tools/tests/pipe_stat_type_test.c @@ -37,6 +37,6 @@ int main(void) struct stat st; assert(nullfd >= 0 && fstat(nullfd, &st) == 0 && S_ISCHR(st.st_mode)); close(nullfd); - puts("PASS pipe stat: raw fstat/newfstatat/statx, musl fstat, dup and character device"); + puts("PASS pipe stat: raw fstat/newfstatat/statx, libc fstat, dup and character device"); return 0; } From c8cc594b3956ac0ca930f1c21d60a72b1a636e83 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Wed, 2 Dec 2026 19:52:04 +0800 Subject: [PATCH 93/97] fix(initramfs): support dracut CPIO filename padding --- Documentation/kbuild/building.rst | 4 +- .../locale/en/LC_MESSAGES/kbuild/building.po | 4 +- .../locale/ja/LC_MESSAGES/kbuild/building.po | 4 +- fs/Kconfig | 6 +++ fs/initramfs/Kbuild | 3 +- fs/initramfs/archive.c | 19 +++++---- fs/initramfs/archive.h | 4 +- include/reliefnt/task/types.h | 2 +- tests/host/test_json.c | 4 +- tools/tests/initramfs_archive_test.c | 41 ++++++++++++++++++- tools/tests/linux_pty_test.c | 8 ++++ 11 files changed, 80 insertions(+), 19 deletions(-) diff --git a/Documentation/kbuild/building.rst b/Documentation/kbuild/building.rst index 4b6c5b47..e23511f7 100644 --- a/Documentation/kbuild/building.rst +++ b/Documentation/kbuild/building.rst @@ -28,7 +28,9 @@ SOURCE_DATE_EPOCH 使用独立 Make 参数。 隐藏配置 ``CONFIG_BLK_DEV_INITRD`` 始终启用并构建内存根加载器。 加载器接受名为 ``initramfs`` 的 Multiboot 模块,内容为未压缩的 -newc 或 crc CPIO 归档。生成 initramfs 时必须选择未压缩格式。 +newc 或 crc CPIO 归档。文件名字段允许在终止符后附加 NUL, +整个字段长度最多为 Linux ``PATH_MAX``,支持 dracut-cpio 的文件数据对齐。 +生成 initramfs 时必须选择未压缩格式。 应用、系统镜像、激活策略和 QEMU 参数只属于 ReliefOS 主仓,内核不 source 主仓 Kconfig。从旧输出复制配置后运行 olddefconfig,会由原版 conf 移除外来符号。 diff --git a/Documentation/locale/en/LC_MESSAGES/kbuild/building.po b/Documentation/locale/en/LC_MESSAGES/kbuild/building.po index f4b42f6f..7b3a5cac 100644 --- a/Documentation/locale/en/LC_MESSAGES/kbuild/building.po +++ b/Documentation/locale/en/LC_MESSAGES/kbuild/building.po @@ -38,8 +38,8 @@ msgstr "" msgid "配置归属" msgstr "Configuration Ownership" -msgid "隐藏配置 ``CONFIG_BLK_DEV_INITRD`` 始终启用并构建内存根加载器。 加载器接受名为 ``initramfs`` 的 Multiboot 模块,内容为未压缩的 newc 或 crc CPIO 归档。生成 initramfs 时必须选择未压缩格式。" -msgstr "The hidden ``CONFIG_BLK_DEV_INITRD`` setting is always enabled and builds the memory-root loader. The loader accepts a Multiboot module named ``initramfs`` containing an uncompressed newc or crc CPIO archive. Generate initramfs images in the uncompressed format." +msgid "隐藏配置 ``CONFIG_BLK_DEV_INITRD`` 始终启用并构建内存根加载器。 加载器接受名为 ``initramfs`` 的 Multiboot 模块,内容为未压缩的 newc 或 crc CPIO 归档。文件名字段允许在终止符后附加 NUL, 整个字段长度最多为 Linux ``PATH_MAX``,支持 dracut-cpio 的文件数据对齐。 生成 initramfs 时必须选择未压缩格式。" +msgstr "The hidden ``CONFIG_BLK_DEV_INITRD`` setting is always enabled and builds the memory-root loader. The loader accepts a Multiboot module named ``initramfs`` containing an uncompressed newc or crc CPIO archive. Filename fields may contain trailing NUL padding up to Linux ``PATH_MAX``, supporting dracut-cpio file-data alignment. Generate initramfs images in the uncompressed format." msgid "" "Kconfig 只提供内核实际消费的选项。生产 defconfig 默认将驱动内建, 已完成生命周期支持的部件可选择 m,构建为针对 ReliefNT 的原生 .ko。 调度、内存、VFS " diff --git a/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po b/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po index 9db58ae8..f3c0efcd 100644 --- a/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po +++ b/Documentation/locale/ja/LC_MESSAGES/kbuild/building.po @@ -37,8 +37,8 @@ msgstr "" msgid "配置归属" msgstr "設定の所属" -msgid "隐藏配置 ``CONFIG_BLK_DEV_INITRD`` 始终启用并构建内存根加载器。 加载器接受名为 ``initramfs`` 的 Multiboot 模块,内容为未压缩的 newc 或 crc CPIO 归档。生成 initramfs 时必须选择未压缩格式。" -msgstr "非表示の設定 ``CONFIG_BLK_DEV_INITRD`` は常に有効で、メモリールートローダーをビルドします。ローダーは ``initramfs`` という名前の Multiboot モジュールを受け付け、その内容は非圧縮の newc または crc CPIO アーカイブです。initramfs イメージは非圧縮形式で生成してください。" +msgid "隐藏配置 ``CONFIG_BLK_DEV_INITRD`` 始终启用并构建内存根加载器。 加载器接受名为 ``initramfs`` 的 Multiboot 模块,内容为未压缩的 newc 或 crc CPIO 归档。文件名字段允许在终止符后附加 NUL, 整个字段长度最多为 Linux ``PATH_MAX``,支持 dracut-cpio 的文件数据对齐。 生成 initramfs 时必须选择未压缩格式。" +msgstr "非表示の設定 ``CONFIG_BLK_DEV_INITRD`` は常に有効で、メモリールートローダーをビルドします。ローダーは ``initramfs`` という名前の Multiboot モジュールを受け付け、その内容は非圧縮の newc または crc CPIO アーカイブです。ファイル名フィールドには Linux ``PATH_MAX`` まで末尾の NUL パディングを含めることができ、dracut-cpio のファイルデータ整列に対応します。initramfs イメージは非圧縮形式で生成してください。" msgid "" "Kconfig 只提供内核实际消费的选项。生产 defconfig 默认将驱动内建, 已完成生命周期支持的部件可选择 m,构建为针对 ReliefNT 的原生 .ko。 调度、内存、VFS " diff --git a/fs/Kconfig b/fs/Kconfig index 924107f7..1c6b95e5 100644 --- a/fs/Kconfig +++ b/fs/Kconfig @@ -8,6 +8,12 @@ config BLK_DEV_INITRD Build the early memory-root loader for uncompressed newc and crc archives supplied as the initramfs Multiboot module. +config RELIEFNT_INITRAMFS_PADDED_NAMES + def_bool BLK_DEV_INITRD + help + Advertise support for extra NUL bytes in newc and crc filename fields + to initramfs generators through the packaged kernel configuration. + config FAT_FS tristate "FAT32 filesystem and formatter" default y diff --git a/fs/initramfs/Kbuild b/fs/initramfs/Kbuild index aa9d082c..937dad7a 100644 --- a/fs/initramfs/Kbuild +++ b/fs/initramfs/Kbuild @@ -1,3 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := archive.o unpack.o view.o records.o source.o boot.o +obj-$(CONFIG_RELIEFNT_INITRAMFS_PADDED_NAMES) := archive.o +obj-y += unpack.o view.o records.o source.o boot.o include $(srctree)/scripts/Makefile.module diff --git a/fs/initramfs/archive.c b/fs/initramfs/archive.c index 231c9b51..7c373415 100644 --- a/fs/initramfs/archive.c +++ b/fs/initramfs/archive.c @@ -3,6 +3,7 @@ * c_check is the specified unsigned byte sum, not a CRC polynomial. */ #include "archive.h" #include +#include #include /** @brief Compare exactly a known wire-field extent without reading its terminator. @@ -51,14 +52,16 @@ static bool archive_type_valid(uint32_t mode,uint32_t size) type==LINUX_S_IFBLK || type==LINUX_S_IFIFO || type==LINUX_S_IFSOCK); } -/** @brief Walk bounded newc/crc records and optional exact archive-end markers. +/** @brief Walk bounded newc/crc records with NUL-padded names and archive markers. * @param image Stable length-byte input, nullable only for empty input. * @param length Complete source length. @param visitor Optional pinned callback; * NULL entry signals trailer, nonNULL fields borrow exact source bytes. * @param context Borrowed caller callback state. * @return Zero or input/format/checksum/unsupported/callback errno. No archive * writes, allocation, lock or I/O. A callback error terminates immediately; - * callers own rollback, source lifetime and any hard-link tuple allocations. + * Filename fields may include trailing NUL padding up to Linux PATH_MAX; + * callbacks receive the actual name length. Callers own rollback, source + * lifetime and any hard-link tuple allocations. */ int initramfs_scan(const void *image,size_t length, int (*visitor)(void *,const struct initramfs_entry *),void *context) @@ -76,16 +79,18 @@ int initramfs_scan(const void *image,size_t length, uint32_t field[13]; for(unsigned i=0;i<13;++i)if(!archive_hex(bytes+header+6+i*8,&field[i]))return -ENOEXEC; uint32_t names=field[11],size=field[6]; - if(!names || names>remaining-110)return -ENOEXEC; + if(!names || names>LINUX_PATH_MAX || names>remaining-110)return -ENOEXEC; const uint8_t *name=bytes+header+110; - if(name[names-1])return -ENOEXEC; - for(uint32_t i=0;i+1SIZE_MAX-3)return -ENOEXEC; size_t data_relative=(name_end+3)&~(size_t)3; if(data_relative>remaining || size>remaining-data_relative)return -ENOEXEC; const uint8_t *data=bytes+header+data_relative; - bool trailer=names==11 && archive_equal(name,"TRAILER!!!",10); + bool trailer=name_length==10 && archive_equal(name,"TRAILER!!!",10); if(trailer ? size!=0 : !archive_type_valid(field[1],size))return -ENOEXEC; if(!crc && field[12])return -ENOEXEC; if(crc) { @@ -93,7 +98,7 @@ int initramfs_scan(const void *image,size_t length, for(uint32_t i=0;i #include #include +#include static unsigned entries,trailers,gnu_entries,gnu_hard_data; static int stop_at; static void hex(char *at,uint32_t value) @@ -19,6 +20,23 @@ static size_t append(unsigned char *out,const char *name,uint32_t mode,const voi uint32_t sum=0;for(uint32_t i=0;i= original_names); + append(out, name, mode, data, bytes, crc); + size_t original_data = (110 + original_names + 3) & ~(size_t)3; + size_t padded_data = (110 + (size_t)names + 3) & ~(size_t)3; + memmove(out + padded_data, out + original_data, bytes); + memset(out + 110 + original_names, 0, padded_data - 110 - original_names); + hex((char *)out + 94, names); + size_t end = padded_data + bytes; + size_t total = (end + 3) & ~(size_t)3; + memset(out + end, 0, total - end); + return total; +} static int visit(void *context,const struct initramfs_entry *entry) { assert(context==&entries);if(!entry){++trailers;return 0;} @@ -40,7 +58,7 @@ static int visit_gnu(void *context,const struct initramfs_entry *entry) } int main(int argc,char **argv) { - assert(argc==2);unsigned char image[1024],invalid[1024]; + assert(argc==2);unsigned char image[8192],invalid[8192]; size_t size=append(image,"sample",0100640,"hello\n",6,false); assert(!initramfs_scan(image,size,visit,&entries) && entries==1 && !trailers); assert(!initramfs_scan(image,size,NULL,NULL)); @@ -60,10 +78,29 @@ int main(int argc,char **argv) image[total++]=0;image[total++]=0;image[total++]=0; total+=append(image+total,"sample",0100640,"hello\n",6,true); entries=trailers=0;assert(!initramfs_scan(image,total,visit,&entries) && entries==2 && trailers==1); + /* dracut-cpio aligns file data with extra NULs inside c_namesize. */ + size_t padded = append_padded(image, "sample", 4096 - 110, + 0100640, "hello\n", 6, false); + entries = trailers = 0; + assert(!initramfs_scan(image, padded, visit, &entries) && entries == 1); + image[117] = 'x'; + assert(initramfs_scan(image, padded, NULL, NULL) == -ENOEXEC); + padded = append_padded(image, "sample", LINUX_PATH_MAX, + 0100640, "hello\n", 6, true); + entries = 0; + assert(!initramfs_scan(image, padded, visit, &entries) && entries == 1); + padded = append_padded(image, "sample", LINUX_PATH_MAX + 1, + 0100640, "hello\n", 6, false); + assert(initramfs_scan(image, padded, NULL, NULL) == -ENOEXEC); + total = append_padded(image, "TRAILER!!!", 64, 0, NULL, 0, false); + total += append_padded(image + total, "sample", 128, + 0100640, "hello\n", 6, true); + entries = trailers = 0; + assert(!initramfs_scan(image, total, visit, &entries) && entries == 1 && trailers == 1); unsigned char gzip[]={0x1f,0x8b,0x08,0};assert(initramfs_scan(gzip,sizeof(gzip),NULL,NULL)==-EOPNOTSUPP); FILE *file=fopen(argv[1],"rb");assert(file && !fseek(file,0,SEEK_END));long length=ftell(file); assert(length>0 && !fseek(file,0,SEEK_SET));unsigned char *gnu=malloc(length);assert(gnu); assert(fread(gnu,1,length,file)==(size_t)length && !fclose(file)); trailers=0;assert(!initramfs_scan(gnu,length,visit_gnu,NULL) && gnu_entries==5 && gnu_hard_data==1 && trailers==1);free(gnu); - puts("PASS actual newc decoder: bounds/hex/NUL/type/CRC, trailers, concatenation, callback errors and independent GNU UTF8/hardlinks"); + puts("PASS actual newc decoder: bounds/hex/NUL/type/CRC, padded names/trailers, PATH_MAX, concatenation, callback errors and independent GNU UTF8/hardlinks"); } diff --git a/tools/tests/linux_pty_test.c b/tools/tests/linux_pty_test.c index 3a06046d..156353f8 100644 --- a/tools/tests/linux_pty_test.c +++ b/tools/tests/linux_pty_test.c @@ -342,6 +342,14 @@ int main(void) assert(pty_read_input(1,response_bytes,sizeof(response_bytes))==4); assert(!memcmp(response_bytes,"\033[0n",4) && vt_written_len==echoed_before); assert(!find_session(1)->canonical_length); + const char cursor_reply[] = "\033[67;240R"; + char cursor_bytes[sizeof(cursor_reply) - 1]; + pty_vt_reply(1, cursor_reply, sizeof(cursor_reply) - 1); + assert(pty_read_input(1, cursor_bytes, 6) == 6); + for (size_t i = 6; i < sizeof(cursor_bytes); ++i) + assert(pty_read_input(1, cursor_bytes + i, 1) == 1); + assert(!memcmp(cursor_bytes, cursor_reply, sizeof(cursor_bytes))); + assert(pty_read_input(1, response_bytes, 1) == -LINUX_EAGAIN); pty_vt_reply(7,"ignored",7); } assert(pty_slave_open_allowed(id)); From d986f12e4c6cc3fc4e97958b3cb0b918cad043c1 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Wed, 2 Dec 2026 20:23:11 +0800 Subject: [PATCH 94/97] fix(socket): expose stable socket cookies and peer pidfds --- .../LC_MESSAGES/userspace-api/descriptors.po | 3 + .../LC_MESSAGES/userspace-api/descriptors.po | 3 + Documentation/userspace-api/descriptors.rst | 5 + include/reliefnt/pidfd.h | 10 ++ include/reliefnt/task/accessors.h | 10 +- include/reliefnt/task/types.h | 1 + include/uapi/linux/socket.h | 2 + kernel/sched/identity.c | 30 ++--- kernel/syscall/ipc/socket.c | 116 +++++++++++++++++- kernel/syscall/process/pidfd.c | 40 +++--- tools/tests/socket_batch_unix_test.c | 24 ++++ .../task8_host_stubs/no_prlimit_identity.c | 28 ++++- tools/tests/task8_wait_swap_test.c | 3 +- tools/tests/task_exit_logging_test.c | 3 +- tools/tests/task_identity_test.c | 12 +- 15 files changed, 242 insertions(+), 48 deletions(-) diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po index b5841fce..4de39d20 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/descriptors.po @@ -449,3 +449,6 @@ msgstr "``AF_UNIX`` abstract addresses match within the network namespace where msgid "文件系统套接字通过路径解析取得的真实 inode 身份匹配,具有相应路径权限的其他网络空间可连接同一 inode。硬链接和 bind 别名共享端点身份,移除后重新创建的同名节点拥有独立身份。套接字持有的 inode 与网络空间引用随最后一个打开文件描述释放。" msgstr "Filesystem sockets match the actual inode identity obtained by path resolution. Other network namespaces with the required path permissions can connect to the same inode. Hard links and bind aliases share endpoint identity. A same-name node recreated after removal has an independent identity. The socket releases its inode and network namespace references when its final open file description is released." + +msgid "``SOL_SOCKET/SO_COOKIE`` 返回原生 64 位套接字标识。复制或传递描述符时保留标识, 新套接字和接受的连接各有独立标识。缓冲区小于 8 字节时返回 ``EINVAL``。 ``SO_PEERPIDFD`` 返回连接时记录的对端进程描述符,并设置 ``FD_CLOEXEC``。 对端进程退出后仍可观察原进程的退出状态。缺少对端身份时返回 ``ENODATA``。" +msgstr "``SOL_SOCKET/SO_COOKIE`` returns the native 64-bit socket identifier. Duplicating or passing a descriptor preserves the identifier. Each new socket and accepted connection gets its own identifier. A buffer shorter than eight bytes returns ``EINVAL``. ``SO_PEERPIDFD`` returns an ``FD_CLOEXEC`` process descriptor for the peer identity recorded at connection time. It can still report the original peer's exit after that process terminates. A socket without a captured identity returns ``ENODATA``." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po index 391d544d..e7175ce6 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/descriptors.po @@ -391,3 +391,6 @@ msgstr "``AF_UNIX`` 抽象アドレスはソケット作成時のネットワー msgid "文件系统套接字通过路径解析取得的真实 inode 身份匹配,具有相应路径权限的其他网络空间可连接同一 inode。硬链接和 bind 别名共享端点身份,移除后重新创建的同名节点拥有独立身份。套接字持有的 inode 与网络空间引用随最后一个打开文件描述释放。" msgstr "ファイルシステムソケットはパス解決で取得した実際の inode 識別で照合されます。必要なパス権限を持つ他のネットワーク名前空間からも同じ inode に接続できます。ハードリンクと bind 別名はエンドポイント識別を共有します。削除後に同名で再作成されたノードは独立した識別を持ちます。ソケットが保持する inode とネットワーク名前空間の参照は最後のオープンファイル記述の解放時に解放されます。" + +msgid "``SOL_SOCKET/SO_COOKIE`` 返回原生 64 位套接字标识。复制或传递描述符时保留标识, 新套接字和接受的连接各有独立标识。缓冲区小于 8 字节时返回 ``EINVAL``。 ``SO_PEERPIDFD`` 返回连接时记录的对端进程描述符,并设置 ``FD_CLOEXEC``。 对端进程退出后仍可观察原进程的退出状态。缺少对端身份时返回 ``ENODATA``。" +msgstr "``SOL_SOCKET/SO_COOKIE`` はネイティブの 64 ビットソケット識別子を返します。記述子を複製または転送しても識別子は維持されます。新しいソケットと受け入れた接続にはそれぞれ固有の識別子があります。8 バイト未満のバッファでは ``EINVAL`` を返します。``SO_PEERPIDFD`` は接続時に記録した相手のプロセス記述子を ``FD_CLOEXEC`` 付きで返します。相手の終了後も元のプロセスの終了状態を確認できます。相手の ID が記録されていない場合は ``ENODATA`` を返します。" diff --git a/Documentation/userspace-api/descriptors.rst b/Documentation/userspace-api/descriptors.rst index 50e91fe2..8efdb444 100644 --- a/Documentation/userspace-api/descriptors.rst +++ b/Documentation/userspace-api/descriptors.rst @@ -139,6 +139,11 @@ TCP 的 ``recvfrom/recvmsg`` 支持 ``MSG_PEEK``:重复预读保留相同的 UNIX 地址和同一网络空间、同协议内的 netlink 端口仍不能重复绑定。UNIX 的 ``accept`` 不继承 监听端的该选项;netlink 的组成员资格、权限和过滤不受影响。 +``SOL_SOCKET/SO_COOKIE`` 返回原生 64 位套接字标识。复制或传递描述符时保留标识, +新套接字和接受的连接各有独立标识。缓冲区小于 8 字节时返回 ``EINVAL``。 +``SO_PEERPIDFD`` 返回连接时记录的对端进程描述符,并设置 ``FD_CLOEXEC``。 +对端进程退出后仍可观察原进程的退出状态。缺少对端身份时返回 ``ENODATA``。 + ``AF_UNIX`` 流套接字的 ``SIOCOUTQ``(与 ``TIOCOUTQ`` 同号)向原生 32 位整数 写入仍由对端队列持有的发送缓冲区计量。每个片段按本内核的分配单位计量, 不是精确的未读有效载荷大小或 Linux 的缓冲区字节数。片段读完时才释放其计量, diff --git a/include/reliefnt/pidfd.h b/include/reliefnt/pidfd.h index 71c571b1..cbc83442 100644 --- a/include/reliefnt/pidfd.h +++ b/include/reliefnt/pidfd.h @@ -6,6 +6,16 @@ struct task; struct task_file; +struct task_identity; + +/** @brief Install a close-on-exec descriptor for a pinned PID identity. + * @param caller Descriptor table owner under execution ownership. + * @param identity Borrowed PID object, which may outlive the original task. + * @param flags Validated Linux PIDFD_NONBLOCK/PIDFD_THREAD flags. + * @return New descriptor or negative Linux errno. The caller keeps its pin. + */ +int task_pidfd_install(struct task *caller, struct task_identity *identity, + uint32_t flags); /** @brief Open a close-on-exec descriptor retaining one stable PID object. * @param caller Calling task, borrowed under execution ownership. diff --git a/include/reliefnt/task/accessors.h b/include/reliefnt/task/accessors.h index ebba193e..523b49e2 100644 --- a/include/reliefnt/task/accessors.h +++ b/include/reliefnt/task/accessors.h @@ -11,19 +11,23 @@ * its own reference until reap/recycle; proc inodes keep independent references. */ int sched_task_identity_get(struct task *task,struct task_identity **out); +/** @brief Retain a borrowed PID object even after its task has been reaped. + * @param identity Caller-pinned PID object. No allocation or locking. + * @return Zero with an independent reference, or -ESRCH/-EOVERFLOW. + */ +int sched_task_identity_retain(struct task_identity *identity); /** @brief Retain an already prepared PID identity without allocating. * @param task Execution-owned live task. @param out Empty identity output. * @return Zero or -EINVAL/-ESRCH/-EOVERFLOW; success transfers one reference. */ int sched_task_identity_get_existing(struct task *task, struct task_identity **out); /** @brief Retain one OFD-owned PID reference and its stable anonymous inode. - * @param task Borrowed published target under execution ownership. - * @param out Required output receiving one reference, NULL on failure. + * @param identity Borrowed PID object under execution ownership. * @param ino Required kernel output receiving the stable inode number. * @return Zero, or -EINVAL/-ESRCH/-EOVERFLOW without retaining a reference. * Caller serializes identity access; no allocation or lock acquisition. */ -int sched_task_pidfd_get(struct task *task, struct task_identity **out, uint64_t *ino); +int sched_task_pidfd_get(struct task_identity *identity, uint64_t *ino); /** @brief Release one OFD's watch and retained PID reference on final close. * @param identity Owned pidfd reference, or NULL, under execution ownership. * Frees only the final reference; no I/O or additional locking. diff --git a/include/reliefnt/task/types.h b/include/reliefnt/task/types.h index ba658686..7312ce77 100644 --- a/include/reliefnt/task/types.h +++ b/include/reliefnt/task/types.h @@ -119,6 +119,7 @@ struct task_file { uint32_t scm_gc_seen; bool proc_counted; uint64_t socket_ino; /* Numeric socket identity, never a pointer. */ + uint64_t socket_cookie; /* Lazily assigned SO_COOKIE on the canonical OFD. */ uint32_t flags; uint32_t fd_flags; uint32_t flock_type; diff --git a/include/uapi/linux/socket.h b/include/uapi/linux/socket.h index b55d9b6f..1b0feaf9 100644 --- a/include/uapi/linux/socket.h +++ b/include/uapi/linux/socket.h @@ -72,6 +72,8 @@ struct sockaddr_un { #define SO_TIMESTAMP SO_TIMESTAMP_OLD #define SO_PROTOCOL 38 #define SO_DOMAIN 39 +#define SO_COOKIE 57 +#define SO_PEERPIDFD 77 #define SCM_RIGHTS 1 #define SCM_CREDENTIALS 2 diff --git a/kernel/sched/identity.c b/kernel/sched/identity.c index ea67d8ef..bc25b291 100644 --- a/kernel/sched/identity.c +++ b/kernel/sched/identity.c @@ -41,6 +41,15 @@ void sched_task_identity_bind(struct task *task, struct task_identity *identity) if (sched_oom_membership_changed) sched_oom_membership_changed(); } +/** @copydoc sched_task_identity_retain */ +int sched_task_identity_retain(struct task_identity *identity) +{ + if (!identity) return -ESRCH; + if (identity->references == UINT64_MAX) return -EOVERFLOW; + ++identity->references; + return 0; +} + /** @brief Retain only a previously prepared PID identity, without heap work. * @param task Execution-owned task. @param out Empty required identity output. * @return Zero with one owned reference or -EINVAL/-ESRCH/-EOVERFLOW. @@ -50,27 +59,20 @@ int sched_task_identity_get_existing(struct task *task, struct task_identity **o if(!out)return -EINVAL; *out=NULL; if(!task || !task->pid || !task->identity_token)return -ESRCH; - struct task_identity *identity=task->identity_token; - if (identity->references==UINT64_MAX) return -EOVERFLOW; - ++identity->references;*out=identity;return 0; + int rc = sched_task_identity_retain(task->identity_token); + if (!rc) *out = task->identity_token; + return rc; } -/** @brief Retain one OFD-owned PID identity and assign its stable inode number. - * @param task Borrowed published target under execution ownership. - * @param out Required output receiving one reference, NULL on failure. - * @param ino Required kernel output receiving the identity's inode number. - * @return Zero, or -EINVAL/-ESRCH/-EOVERFLOW without an acquired reference. - * Does not allocate or take locks; the caller serializes identity access. - */ -int sched_task_pidfd_get(struct task *task, struct task_identity **out, uint64_t *ino) +/** @copydoc sched_task_pidfd_get */ +int sched_task_pidfd_get(struct task_identity *identity, uint64_t *ino) { - int rc = sched_task_identity_get_existing(task, out); + if (!ino) return -EINVAL; + int rc = sched_task_identity_retain(identity); if (rc) return rc; - struct task_identity *identity = *out; if (!identity->pidfd_inode) { if (last_pidfd_inode == UINT64_MAX) { sched_task_identity_put(identity); - *out = NULL; return -EOVERFLOW; } identity->pidfd_inode = ++last_pidfd_inode; diff --git a/kernel/syscall/ipc/socket.c b/kernel/syscall/ipc/socket.c index 580d2240..50222167 100644 --- a/kernel/syscall/ipc/socket.c +++ b/kernel/syscall/ipc/socket.c @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -143,7 +144,7 @@ struct unix_socket { uint32_t state; uint32_t type; uint32_t peer_handle; - uint32_t peer_pid; + struct task_identity *peer_identity; /* Held process identity for peer PIDFD. */ uint32_t shutdown_read; uint32_t shutdown_write; int32_t error; @@ -462,6 +463,31 @@ static int unix_address_out(const struct unix_socket *socket, uint64_t address, return unix_name_out(socket ? socket->path : NULL, socket ? socket->path_len : 0, address, length); } +/** @brief Borrow the caller's process identity under execution ownership. */ +static struct task_identity *unix_process_identity(struct task *task) +{ + uint32_t tgid = sched_task_tgid(task); + struct task *leader = tgid == task->pid ? task : sched_find(tgid); + return leader ? leader->identity_token : NULL; +} + +/** @brief Replace one socket's owned peer identity without a numeric PID lookup. + * @param socket Stable destination endpoint. @param identity Borrowed PID object + * or NULL. A missing identity leaves SO_PEERPIDFD unavailable. + * @return Zero or an overflow error before modifying the endpoint. + */ +static int unix_set_peer_identity(struct unix_socket *socket, + struct task_identity *identity) +{ + if (identity) { + int rc = sched_task_identity_retain(identity); + if (rc) return rc; + } + sched_task_identity_put(socket->peer_identity); + socket->peer_identity = identity; + return 0; +} + /** * @brief Allocate and register a stable AF_UNIX socket object. * @param owner_pid Socket owner process identifier. @@ -590,6 +616,7 @@ static void unix_release_handle(uint32_t handle) while (*link && *link != socket) link = &(*link)->registry_next; if (*link == socket) *link = socket->registry_next; vfs_path_put(&socket->bound_inode); + sched_task_identity_put(socket->peer_identity); net_namespace_put(socket->net_ns); kernel_free(socket); } @@ -3115,12 +3142,18 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, unix_release_handle(left->handle); return -RELIEFOS_ENOMEM; } + struct task_identity *identity = unix_process_identity(task); + int ret = unix_set_peer_identity(left, identity); + if (!ret) ret = unix_set_peer_identity(right, identity); + if (ret) { + unix_release_handle(left->handle); + unix_release_handle(right->handle); + return ret; + } left->state = UNIX_SOCKET_CONNECTED; right->state = UNIX_SOCKET_CONNECTED; left->peer_handle = right->handle; right->peer_handle = left->handle; - left->peer_pid = task->pid; - right->peer_pid = task->pid; left->peer_credentials = right->credentials; right->peer_credentials = left->credentials; left_fd = unix_alloc_fd(task, left); @@ -3160,6 +3193,8 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, uint32_t requested_backlog = (uint32_t)(int32_t)a1; if (socket->type == SOCK_DGRAM) return -LINUX_EOPNOTSUPP; if (!socket->path_len || socket->state == UNIX_SOCKET_CONNECTED) return -RELIEFOS_EINVAL; + int ret = unix_set_peer_identity(socket, unix_process_identity(task)); + if (ret) return ret; if (requested_backlog > UNIX_SOCKET_BACKLOG_MAX) requested_backlog = UNIX_SOCKET_BACKLOG_MAX; socket->backlog = requested_backlog; @@ -3167,6 +3202,7 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, socket->pending_limit = requested_backlog + 1u; socket->state = UNIX_SOCKET_LISTEN; socket->credentials = (struct ucred){(int32_t)sched_task_tgid(task), task->euid, task->egid}; + socket->peer_credentials = socket->credentials; kernel_poll_readiness_notify(); return 0; } @@ -3213,14 +3249,18 @@ static int64_t unix_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, if (ret < 0) return ret; server = unix_alloc(listener->owner_pid, listener->type, listener->net_ns); if (!server) return -RELIEFOS_ENOMEM; + ret = unix_set_peer_identity(server, unix_process_identity(task)); + if (!ret) ret = unix_set_peer_identity(socket, listener->peer_identity); + if (ret) { + unix_release_handle(server->handle); + return ret; + } server->state = UNIX_SOCKET_CONNECTED; server->passcred = listener->passcred; server->unaccepted = 1; socket->state = UNIX_SOCKET_CONNECTED; socket->peer_handle = server->handle; - socket->peer_pid = listener->owner_pid; server->peer_handle = socket->handle; - server->peer_pid = task->pid; server->peer_credentials = (struct ucred){(int32_t)sched_task_tgid(task), task->euid, task->egid}; socket->peer_credentials = listener->credentials; server->credentials = listener->credentials; @@ -3428,6 +3468,66 @@ static int unix_socket_option(struct unix_socket *socket, bool setting, int leve return 0; } +/** + * @brief Return the native 64-bit identifier of an open socket. + * @param task Current userspace task under the syscall execution transaction. + * @param file Borrowed canonical socket description, preserved across aliases. + * @param address User buffer for the cookie. + * @param length User pointer to the buffer capacity and resulting length. + * @return Zero, a user copy error, or EINVAL for a buffer below eight bytes. + * The execution transaction serializes lazy issuance across all socket families. + */ +static int socket_cookie_out(struct task *task, struct task_file *file, + uint64_t address, uint64_t length) +{ + static uint64_t last_cookie; + socklen_t capacity; + int ret = socket_user_length(task, length, &capacity); + if (ret) return ret; + if ((int32_t)capacity < (int32_t)sizeof(file->socket_cookie)) + return -LINUX_EINVAL; + ret = socket_user_prepare(task, address, sizeof(file->socket_cookie), true); + if (ret) return ret; + if (!user_range_writable(address, sizeof(file->socket_cookie))) return -LINUX_EFAULT; + + if (!file->socket_cookie) { + if (++last_cookie == 0) ++last_cookie; + file->socket_cookie = last_cookie; + } + __builtin_memcpy((void *)(uintptr_t)address, &file->socket_cookie, + sizeof(file->socket_cookie)); + *(socklen_t *)(uintptr_t)length = sizeof(file->socket_cookie); + return 0; +} + +/** @brief Copy out a close-on-exec pidfd for the retained peer identity. + * @param task Current userspace task, serialized against descriptor changes. + * @param peer Borrowed socket's peer identity, nullable. + * @param address User buffer for the native integer result. + * @param length In/out Linux socklen_t pointer. + * @return Zero, ENODATA for absent peer identity, or copy/descriptor errno. + * Prepare both user operands before publishing any new descriptor. + */ +static int socket_peer_pidfd_out(struct task *task, struct task_identity *peer, + uint64_t address, uint64_t length) +{ + socklen_t capacity; + int ret = socket_user_length(task, length, &capacity); + if (ret) return ret; + if ((int32_t)capacity < 0) return -LINUX_EINVAL; + if (!peer) return -LINUX_ENODATA; + + socklen_t size = capacity < sizeof(int) ? capacity : sizeof(int); + ret = socket_user_prepare(task, address, size, true); + if (ret) return ret; + if (size && !user_range_writable(address, size)) return -LINUX_EFAULT; + int fd = task_pidfd_install(task, peer, 0); + if (fd < 0) return fd; + if (size) __builtin_memcpy((void *)(uintptr_t)address, &fd, size); + *(socklen_t *)(uintptr_t)length = size; + return 0; +} + /** * @brief Route native socket syscalls to UNIX, TCP, UDP, raw and netlink handlers. * @param number Linux syscall number. @@ -3462,7 +3562,13 @@ int64_t syscall_socket_dispatch(uint64_t number, uint64_t a0, uint64_t a1, task = sched_current_task(); file = task_file_for_io(task, (int)a0); if (!file) return -RELIEFOS_EBADF; + if (number == __NR_getsockopt && (int)a1 == SOL_SOCKET && (int)a2 == SO_COOKIE && + (file->flags & TASK_FILE_FLAG_SOCKET)) + return socket_cookie_out(task, file, a3, a4); struct unix_socket *socket = unix_from_file(file); + if (number == __NR_getsockopt && (int)a1 == SOL_SOCKET && (int)a2 == SO_PEERPIDFD && + (file->flags & TASK_FILE_FLAG_SOCKET)) + return socket_peer_pidfd_out(task, socket ? socket->peer_identity : NULL, a3, a4); if (socket) return unix_socket_option(socket, number == __NR_setsockopt, (int)a1, (int)a2, a3, a4); if (file->flags & TASK_FILE_FLAG_SOCKET_INET) diff --git a/kernel/syscall/process/pidfd.c b/kernel/syscall/process/pidfd.c index c10c16a5..e0a3f87f 100644 --- a/kernel/syscall/process/pidfd.c +++ b/kernel/syscall/process/pidfd.c @@ -16,6 +16,28 @@ static struct task_identity *pidfd_identity(const struct task_file *file) return file && file->kind == TASK_FILE_KIND_PIDFD ? (void *)(uintptr_t)file->aux : NULL; } +/** @copydoc task_pidfd_install */ +int task_pidfd_install(struct task *caller, struct task_identity *identity, + uint32_t flags) +{ + struct task_file *file; + uint64_t ino; + int rc = sched_task_pidfd_get(identity, &ino); + if (rc) return rc; + int fd = task_allocate_fd(caller, 0, &file); + if (fd < 0) { + sched_task_pidfd_put(identity); + return fd; + } + file->kind = TASK_FILE_KIND_PIDFD; + file->flags = LINUX_O_RDWR | flags; + file->fd_flags = LINUX_FD_CLOEXEC; + __builtin_memcpy(file->path, "anon_inode:[pidfd]", sizeof("anon_inode:[pidfd]")); + file->aux = (uint64_t)(uintptr_t)identity; + file->aux2 = ino; + return fd; +} + /** @brief Open a close-on-exec descriptor retaining one stable PID object. * @param caller Calling task under execution ownership. @param pid Positive PID or TID. * @param flags Linux pidfd_open flags. @return New descriptor or negative Linux errno. @@ -33,23 +55,7 @@ int64_t syscall_pidfd_open(struct task *caller, int32_t pid, uint32_t flags) (!leader && (target->flags & TASK_FLAG_RESOURCES_RELEASED)))) return -LINUX_ESRCH; if (!thread && !leader) return -LINUX_EINVAL; - struct task_identity *identity; - struct task_file *file; - uint64_t ino; - int rc = sched_task_pidfd_get(target, &identity, &ino); - if (rc) return rc; - int fd = task_allocate_fd(caller, 0, &file); - if (fd < 0) { - sched_task_pidfd_put(identity); - return fd; - } - file->kind = TASK_FILE_KIND_PIDFD; - file->flags = LINUX_O_RDWR | flags; - file->fd_flags = LINUX_FD_CLOEXEC; - __builtin_memcpy(file->path, "anon_inode:[pidfd]", sizeof("anon_inode:[pidfd]")); - file->aux = (uint64_t)(uintptr_t)identity; - file->aux2 = ino; - return fd; + return task_pidfd_install(caller, target->identity_token, flags); } /** @copydoc syscall_pidfd_send_signal */ diff --git a/tools/tests/socket_batch_unix_test.c b/tools/tests/socket_batch_unix_test.c index 1868fc4b..e88dfa91 100644 --- a/tools/tests/socket_batch_unix_test.c +++ b/tools/tests/socket_batch_unix_test.c @@ -577,6 +577,29 @@ static void check_interface_ioctl_scope(void) puts("PASS UNIX interface ioctl dispatch: moved caller and retained socket network scope"); } +/** @brief Check socket identity and the Linux-width copyout contract. */ +static void check_socket_cookie(void) +{ + uint64_t values[2] = {0, UINT64_MAX}; + socklen_t size = sizeof(values[0]) - 1; + assert(socket_cookie_out(¤t, &endpoints[0], (uintptr_t)values, + (uintptr_t)&size) == -LINUX_EINVAL); + assert(!endpoints[0].socket_cookie && !values[0]); + size = sizeof(values); + assert(socket_cookie_out(¤t, &endpoints[0], 0, + (uintptr_t)&size) == -LINUX_EFAULT); + assert(!endpoints[0].socket_cookie && size == sizeof(values)); + assert(!socket_cookie_out(¤t, &endpoints[0], (uintptr_t)values, + (uintptr_t)&size)); + assert(size == sizeof(values[0]) && values[0] && values[1] == UINT64_MAX); + assert(!socket_cookie_out(¤t, &endpoints[0], (uintptr_t)&values[1], + (uintptr_t)&size)); + assert(values[0] == values[1]); + assert(!socket_cookie_out(¤t, &endpoints[1], (uintptr_t)&values[1], + (uintptr_t)&size)); + assert(values[1] && values[0] != values[1]); +} + int main(void) { current.kind = TASK_KIND_USER; @@ -763,6 +786,7 @@ int main(void) assert(unix_message_rights(¤t, &m, &held, &credential, &explicit) == credential_cases[i].error); assert(!held && !allocations); } + check_socket_cookie(); check_unix_stream_outq(); check_namespace_credentials(); check_netlink_packet_info(); diff --git a/tools/tests/task8_host_stubs/no_prlimit_identity.c b/tools/tests/task8_host_stubs/no_prlimit_identity.c index bd72dad1..d29e741b 100644 --- a/tools/tests/task8_host_stubs/no_prlimit_identity.c +++ b/tools/tests/task8_host_stubs/no_prlimit_identity.c @@ -1,7 +1,29 @@ /* SPDX-License-Identifier: Apache-2.0 */ -/* Fixtures without prlimit identity ownership must never release one. A real - * scheduler identity implementation, when linked, overrides this test stub. */ +/* Fixtures without PID object ownership must never acquire or release one. */ +#include #include #include + +/** @copydoc sched_task_identity_put */ __attribute__((weak)) void sched_task_identity_put(struct task_identity *identity) -{ (void)identity;abort(); } +{ + if (identity) abort(); +} + +/** @copydoc sched_task_identity_retain */ +__attribute__((weak)) int sched_task_identity_retain(struct task_identity *identity) +{ + (void)identity; + abort(); +} + +/** @copydoc task_pidfd_install */ +__attribute__((weak)) int task_pidfd_install(struct task *caller, + struct task_identity *identity, + uint32_t flags) +{ + (void)caller; + (void)identity; + (void)flags; + abort(); +} diff --git a/tools/tests/task8_wait_swap_test.c b/tools/tests/task8_wait_swap_test.c index 6807e279..38d38204 100644 --- a/tools/tests/task8_wait_swap_test.c +++ b/tools/tests/task8_wait_swap_test.c @@ -79,7 +79,8 @@ static void check_pidfd_wait_swap(struct task *child) struct task_identity *identity; uint64_t ino; sched_task_identity_bind(child, sched_task_identity_prepare()); - assert(!sched_task_pidfd_get(child, &identity, &ino)); + identity = child->identity_token; + assert(!sched_task_pidfd_get(identity, &ino)); waited_pidfd = (struct task_file){.kind = TASK_FILE_KIND_PIDFD, .aux = (uintptr_t)identity, .aux2 = ino}; struct linux_siginfo info = {0}; diff --git a/tools/tests/task_exit_logging_test.c b/tools/tests/task_exit_logging_test.c index 925b34f3..e635b18e 100644 --- a/tools/tests/task_exit_logging_test.c +++ b/tools/tests/task_exit_logging_test.c @@ -307,7 +307,8 @@ static void check_retired_thread_usage(void) struct task_identity *identity; uint64_t ino; sched_task_identity_bind(leader, sched_task_identity_prepare()); - assert(sched_task_pidfd_get(leader, &identity, &ino) == 0); + identity = leader->identity_token; + assert(sched_task_pidfd_get(identity, &ino) == 0); struct linux_rusage before, after; assert(sched_wait_identity(parent->pid, identity, LINUX_WEXITED | LINUX_WNOWAIT, NULL, &before) == leader->pid); diff --git a/tools/tests/task_identity_test.c b/tools/tests/task_identity_test.c index fd19566b..ce8235a6 100644 --- a/tools/tests/task_identity_test.c +++ b/tools/tests/task_identity_test.c @@ -50,14 +50,18 @@ int main(void) a=(struct task){.pid=17}; sched_task_identity_bind(&a, sched_task_identity_prepare()); uint64_t first, same, replacement; - assert(sched_task_pidfd_get(&a, &old, &first) == 0 && sched_task_pidfd_watched(&a)); - assert(sched_task_pidfd_get(&a, &alias, &same) == 0 && alias == old && same == first); - sched_task_pidfd_put(alias); + old = a.identity_token; + assert(sched_task_pidfd_get(old, &first) == 0 && sched_task_pidfd_watched(&a)); + assert(sched_task_pidfd_get(old, &same) == 0 && same == first); + sched_task_pidfd_put(old); assert(sched_task_pidfd_watched(&a)); sched_task_identity_detach(&a); sched_task_identity_bind(&a, sched_task_identity_prepare()); assert(!sched_task_pidfd_watched(&a) && !sched_task_identity_task(old)); - assert(sched_task_pidfd_get(&a, &next, &replacement) == 0 && replacement != first); + assert(sched_task_pidfd_get(old, &same) == 0 && same == first); + sched_task_pidfd_put(old); + next = a.identity_token; + assert(sched_task_pidfd_get(next, &replacement) == 0 && replacement != first); assert(sched_task_identity_task(next) == &a && sched_task_identity_task(old) == NULL); sched_task_pidfd_put(next); assert(!sched_task_pidfd_watched(&a)); From 430c7b080a3db6238fb0047ddf251fb3fd47f3a7 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Wed, 2 Dec 2026 22:28:17 +0800 Subject: [PATCH 95/97] fix(build): fall back to the upstream Unifont download Bound stalled connections in clean CI builds and try the alternate locked HTTPS URL on transport failure. Both sources must match the same pinned SHA-256 before the font is cached. --- Makefile | 3 +- configs/dependencies.lock.json | 1 + tools/build/fetch-check.sh | 37 ++++++----- tools/build/fetch.sh | 23 ++++--- tools/host/manifest/reliefos-deps.c | 41 +++++++++++- tools/tests/test-fetch.sh | 96 +++++++++++++++++++++++++++++ 6 files changed, 175 insertions(+), 26 deletions(-) create mode 100644 tools/tests/test-fetch.sh diff --git a/Makefile b/Makefile index 986c1b16..c4e08d6c 100644 --- a/Makefile +++ b/Makefile @@ -355,7 +355,8 @@ endef $(eval $(call RELIEFNT_NATIVE_HOST_TESTS,plain,$(O)/host/tests,$(HOST_CFLAGS),)) $(eval $(call RELIEFNT_NATIVE_HOST_TESTS,sanitised,$(O)/host/tests-sanitised,$(RELIEFNT_TEST_SANITISE) -g -O1,$(RELIEFNT_TEST_SANITISE) -g -O1)) -test-tools: $(RELIEFNT_TEST_HOST_BINS) $(RELIEFNT_TEST_HOST_SANITISED) +test-tools: tools $(RELIEFNT_TEST_HOST_BINS) $(RELIEFNT_TEST_HOST_SANITISED) + $(Q)sh $(RELIEFNT_SRC)/tools/tests/test-fetch.sh $(O)/tools/host/manifest/reliefos-deps $(Q)set -eu; for test_binary in $(RELIEFNT_TEST_HOST_BINS); do "$$test_binary"; done $(Q)set -eu; for test_binary in $(RELIEFNT_TEST_HOST_SANITISED); do \ ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 \ diff --git a/configs/dependencies.lock.json b/configs/dependencies.lock.json index d88931d8..bcc64c5c 100644 --- a/configs/dependencies.lock.json +++ b/configs/dependencies.lock.json @@ -6,6 +6,7 @@ "kind": "binary", "version": "18.0.01", "url": "https://ftp.gnu.org/gnu/unifont/unifont-18.0.01/unifont_all-18.0.01.hex.gz", + "fallback_url": "https://unifoundry.com/pub/unifont/unifont-18.0.01/font-builds/unifont_all-18.0.01.hex.gz", "sha256": "14c96e497466a82e46cf20032ce510e186bdc8658c9158e2290f452cda9bc498", "directory": "unifont_all-18.0.01.hex.gz", "script": "Kbuild", diff --git a/tools/build/fetch-check.sh b/tools/build/fetch-check.sh index 14528118..c4bad438 100755 --- a/tools/build/fetch-check.sh +++ b/tools/build/fetch-check.sh @@ -3,11 +3,10 @@ # the ones that no longer answer. # # fetch.sh is the stage that moves bytes; this script only asks each locked URL -# whether it still serves, so a 404 or a vanished mirror surfaces before a -# build ever has to stop for missing cache bytes. The URL list comes from the -# same reliefos-deps --fetch-list contract fetch.sh consumes, so a check covers -# exactly the packages `make fetch` would download and nothing else. Nothing -# is downloaded here: probes are HEAD requests, confirmed by a one-byte ranged +# whether it still serves, using a locked fallback when needed, so a failure +# surfaces before a build stops for missing cache bytes. Both scripts use the +# reliefos-deps --fetch-list contract to cover the same packages. No files are +# saved: probes are HEAD requests, confirmed by a one-byte ranged # GET only when a mirror refuses HEAD. set -eu @@ -31,8 +30,8 @@ while [ "$#" -gt 0 ]; do printf '%s\n' \ 'usage: fetch-check.sh --deps PATH --lock PATH [--only id[,id]]' \ '' \ - 'Probe every URL fetch.sh would download and fail when one answers' \ - 'with an HTTP error or not at all. Nothing is downloaded.' >&2 + 'Probe the locked download sources and fail if neither the primary' \ + 'nor a configured fallback answers. Nothing is downloaded.' >&2 exit 2 ;; *) printf 'fetch-check: unknown argument: %s\n' "$1" >&2; exit 2 ;; esac @@ -58,22 +57,22 @@ probe() { probe_url=$1 probe_code=000 probe_status=0 - probe_code=$(curl --silent --location --proto '=https' --tlsv1.2 --head \ + probe_code=$(curl --silent --location --proto '=https' --proto-redir '=https' --tlsv1.2 --head \ --output /dev/null --write-out '%{http_code}' \ --connect-timeout 10 --max-time 20 --retry 1 --retry-delay 1 \ "$probe_url") || probe_status=$? - [ -n "$probe_code" ] || probe_code=000 + [ "$probe_status" -eq 0 ] && [ -n "$probe_code" ] || probe_code=000 case "$probe_code" in [23]??) probe_result="HTTP $probe_code"; return 0 ;; esac probe_attempt=1 while :; do probe_status=0 - probe_code=$(curl --silent --location --proto '=https' --tlsv1.2 \ + probe_code=$(curl --silent --location --proto '=https' --proto-redir '=https' --tlsv1.2 \ --range 0-0 --output /dev/null --write-out '%{http_code}' \ --connect-timeout 10 --max-time 20 --retry 1 --retry-delay 1 \ "$probe_url") || probe_status=$? - [ -n "$probe_code" ] || probe_code=000 + [ "$probe_status" -eq 0 ] && [ -n "$probe_code" ] || probe_code=000 case "$probe_code" in [23]??) probe_result="HTTP $probe_code"; return 0 ;; 000) @@ -95,7 +94,7 @@ probe() { TAB=$(printf '\t') checked=0 failed="" -while IFS=$TAB read -r id digest url name; do +while IFS=$TAB read -r id _digest url _name fallback_url; do [ -n "$id" ] || continue if [ -n "$selected" ]; then case ",$selected," in @@ -106,10 +105,18 @@ while IFS=$TAB read -r id digest url name; do checked=$((checked + 1)) if probe "$url"; then reliefos_log OK "$id ($probe_result)" - else - reliefos_log FAIL "$id ($probe_result) $url" - failed="$failed $id" + continue fi + if [ -n "$fallback_url" ]; then + reliefos_log RETRY "$id ($probe_result) $url; trying $fallback_url" + url=$fallback_url + if probe "$url"; then + reliefos_log OK "$id (fallback, $probe_result)" + continue + fi + fi + reliefos_log FAIL "$id ($probe_result) $url" + failed="$failed $id" done <"$work/curl" <<'CURL' +#!/bin/sh +set -eu +probe=no +while [ "$#" -gt 1 ]; do + case $1 in + --output) output=$2; shift ;; + --head|--range) probe=yes ;; + esac + shift +done +url=$1 +printf '%s\n' "$url" >>"$TEST_CURL_LOG" +case "$url" in + "$TEST_PRIMARY"|"$TEST_FALLBACK") ;; + *) exit 99 ;; +esac +if [ "$url" = "$TEST_PRIMARY" ] && [ "${TEST_PRIMARY_AVAILABLE:-no}" != yes ]; then + if [ "$probe" = yes ]; then + printf '503' + else + printf 'partial primary download' >"$output" + exit 28 + fi +elif [ "$probe" = yes ]; then + printf '200' +elif [ "${TEST_BAD_DIGEST:-no}" = yes ]; then + printf 'unverified input' >"$output" +else + printf 'verified input' >"$output" +fi +CURL +chmod +x "$work/curl" + +lock=$work/lock.json +digest=$(printf 'verified input' | sha256sum | cut -d' ' -f1) +cat >"$lock" <"$work/expected" +cmp "$work/expected" "$TEST_CURL_LOG" +run_fetch --cache "$work/cache" --verify-only +cmp "$work/expected" "$TEST_CURL_LOG" + +: >"$TEST_CURL_LOG" +TEST_PRIMARY_AVAILABLE=yes run_fetch --cache "$work/primary" +[ "$(cat "$TEST_CURL_LOG")" = "$primary" ] + +if TEST_BAD_DIGEST=yes run_fetch --cache "$work/rejected" >"$work/error" 2>&1; then + echo 'accepted an input with a mismatched digest' >&2 + exit 1 +fi +grep -Fq 'the lock file pins' "$work/error" +[ -z "$(ls -A "$work/rejected")" ] + +: >"$TEST_CURL_LOG" +if TEST_PRIMARY_AVAILABLE=yes TEST_BAD_DIGEST=yes run_fetch --cache "$work/bad-primary" >"$work/error" 2>&1; then + echo 'accepted an input with a mismatched primary digest' >&2 + exit 1 +fi +grep -Fq 'the lock file pins' "$work/error" +[ "$(cat "$TEST_CURL_LOG")" = "$primary" ] +[ -z "$(ls -A "$work/bad-primary")" ] + +: >"$TEST_CURL_LOG" +"$src/tools/build/fetch-check.sh" --deps "$deps" --lock "$lock" --only font +printf '%s\n' "$primary" "$primary" "$fallback" >"$work/expected" +cmp "$work/expected" "$TEST_CURL_LOG" + +sed 's|https://fallback.invalid/font.hex.gz|https://fallback.invalid/wrong.hex.gz|' "$lock" >"$work/bad.json" +if "$deps" --lock "$work/bad.json" --fetch-list >"$work/bad.out" 2>"$work/error"; then + echo 'accepted a fallback with a different filename' >&2 + exit 1 +fi +grep -Fq 'fallback_url' "$work/error" +printf 'Locked dependency fallback checks passed\n' From 142b56308ab06821a61cc1b79fa752120c4da7a4 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Thu, 3 Dec 2026 01:09:06 +0800 Subject: [PATCH 96/97] perf(storage): batch small ext reads and optimize native formatting --- Documentation/core-api/storage-completion.rst | 13 ++++ block/core/storage_core_api.h | 4 +- block/core/storage_state.c | 15 ++--- fs/ext_common/cache.c | 25 +++++++ fs/ext_common/internal.h | 32 ++++++++- fs/ext_common/ops.c | 11 +++- fs/fat/mkfs.c | 65 +++++++++---------- tools/test_ext4_read.py | 1 + tools/test_filesystem_format.py | 18 +++++ tools/tests/ext4_extent_test.c | 25 +++++++ tools/tests/ext4_read_mapping_test.c | 8 +++ tools/tests/ext4_write_range_alloc_test.c | 8 +++ tools/tests/filesystem_format_test.c | 29 +++++++-- tools/tests/storage_codec_context_fixture.h | 4 ++ 14 files changed, 203 insertions(+), 55 deletions(-) diff --git a/Documentation/core-api/storage-completion.rst b/Documentation/core-api/storage-completion.rst index c8dbb184..10a6d898 100644 --- a/Documentation/core-api/storage-completion.rst +++ b/Documentation/core-api/storage-completion.rst @@ -63,6 +63,19 @@ ext 连续读取在单次调用内复用已验证的逻辑/物理映射值,跨 批量读取只有在全部未缓存数据能由一条原生请求覆盖时保留异步接续。超过设备上限、超过 32 块工作区或混合缓存命中/缺失的范围,临时使用同步上下文,返回后恢复调用方原状态。这样重试前的 inode/extent 缓存驱逐或低内存不会导致已完成前缀反复重读,也不依赖跨 syscall 保留调用者缓冲。真实块层回归覆盖小请求上限、缓存耗尽、脏页、错误及上下文恢复。 +ext 的同步完整块小读在首块未命中缓存时,尝试读取最多 16KiB 的连续窗口。 +窗口受已初始化 extent、文件 EOF 和缓存容量限制,命中已有窗口时继续消费缓存。 +预读使用独立的固定 CPU 缓冲,沿用 storage execution owner;异步请求保持原来的 +请求范围。脏块与 journal overlay 仍由原缓存逻辑保护,预读失败后重新读取调用方 +必需的范围。``tools/test_ext4_read.py`` 覆盖顺序读取的传输次数、EOF、错误回退、 +缓冲边界和脏数据,``tools/test_ext4_io_search.py`` 覆盖读取接续。 + +存储内部的清零与复制复用内核字符串实现的 ``rep stosb`` 和 ``rep movsb``, +不使用 SIMD 状态。原生 FAT32 格式化选择满足 FAT32 数据簇数约束的最大簇, +上限为 4KiB,并直接计算 FAT 扇区数。512MiB ESP 使用 4KiB 簇,较小卷继续 +缩小簇以满足至少 65525 个数据簇的要求。``tools/test_filesystem_format.py`` +通过独立 ``fsck.fat`` 检查几何和元数据。 + 解析块设备来源后,挂载的原生解析、日志恢复及根 inode 读取在同一同步上下文完成。 这样设备的可重试读取不会被 ext4 误记为日志损坏。ext4 在连续元数据事务之间保留 超级块恢复位,在显式同步或卸载时才清除健康空日志的恢复位,避免每次小写入都更新 diff --git a/block/core/storage_core_api.h b/block/core/storage_core_api.h index 467702e2..6da04e5b 100644 --- a/block/core/storage_core_api.h +++ b/block/core/storage_core_api.h @@ -363,8 +363,8 @@ void storage_memzero(void *dst, size_t len); /** * @brief Copy an exact nonoverlapping byte extent without allocating. - * @param dst Writable kernel extent of len bytes. - * @param src Readable kernel extent of len bytes, not overlapping dst. + * @param dst Writable kernel extent of len bytes; nullable only for zero length. + * @param src Readable nonoverlapping extent; nullable only for zero length. * @param len Number of bytes to copy. * @par Context * Caller supplies stable kernel buffers; no user-pointer access, locks, allocation or ownership transfer. diff --git a/block/core/storage_state.c b/block/core/storage_state.c index ecc724e0..4f5113a8 100644 --- a/block/core/storage_state.c +++ b/block/core/storage_state.c @@ -121,10 +121,7 @@ void storage_begin_mutation(void) */ void storage_memzero(void *dst, size_t len) { - uint8_t *p = (uint8_t *)dst; - for (size_t i = 0; i < len; ++i) { - p[i] = 0; - } + if (len) __builtin_memset(dst, 0, len); } /** @brief Dispatch a cache event once to each execution-owned native provider. @@ -223,19 +220,15 @@ void storage_sector_cache_invalidate(void) /** * @brief Copy an exact nonoverlapping byte extent without allocating. - * @param dst Writable kernel extent of len bytes. - * @param src Readable kernel extent of len bytes, not overlapping dst. + * @param dst Writable kernel extent of len bytes; nullable only for zero length. + * @param src Readable nonoverlapping extent; nullable only for zero length. * @param len Number of bytes to copy. * @par Context * Caller supplies stable kernel buffers; no user-pointer access, locks, allocation or ownership transfer. */ void storage_memcpy(void *dst, const void *src, size_t len) { - uint8_t *d = (uint8_t *)dst; - const uint8_t *s = (const uint8_t *)src; - for (size_t i = 0; i < len; ++i) { - d[i] = s[i]; - } + if (len) __builtin_memcpy(dst, src, len); } /** diff --git a/fs/ext_common/cache.c b/fs/ext_common/cache.c index d5d8d386..b4a09861 100644 --- a/fs/ext_common/cache.c +++ b/fs/ext_common/cache.c @@ -62,6 +62,9 @@ static struct ext4_cache_table ext4_cache_tables[] = { * Storage execution ownership keeps it stable across resumable reads. */ static uint8_t ext4_read_dma[EXT4_READAHEAD_BLOCKS * EXT4_MAX_BLOCK_SIZE] __attribute__((aligned(4096))); +/* CPU-only speculative bytes share the storage execution owner's lifetime. + * Keep this separate from ext4_read_dma, whose contents change between runs. */ +static uint8_t ext4_read_window[16384]; /* Translates a filesystem block to partition sectors, refusing anything * outside the volume's geometry or partition range before touching the @@ -377,6 +380,28 @@ int storage_ext4_cache_read_blocks(struct storage_volume *v, uint64_t first, return ret; } +/** @copydoc storage_ext4_cache_read_window */ +int storage_ext4_cache_read_window(struct storage_volume *v, uint64_t first, + uint32_t count, uint32_t window, void *out) +{ + struct ext4_cache_table *table = &ext4_cache_tables[EXT4_CACHE_TABLE_BLOCK]; + if (!v || !v->ext4.block_size || !count || window < count || + window > sizeof(ext4_read_window) / v->ext4.block_size || !out) + return -RELIEFOS_EINVAL; + /* A hit consumes the previous window without advancing its tail. Only + * misses start a window, bounding speculative I/O for sequential faults. */ + if (window > count && !storage_async_can_yield() && ext4_cache_ensure(table) && + table->capacity >= window && !ext4_cache_lookup(table, v, first) && + !storage_ext4_journal_owns(v, first)) { + int ret = storage_ext4_cache_read_blocks(v, first, window, ext4_read_window); + if (!ret) { + storage_memcpy(out, ext4_read_window, (size_t)count * v->ext4.block_size); + return 0; + } + } + return storage_ext4_cache_read_blocks(v, first, count, out); +} + int storage_ext4_cache_get(struct storage_volume *volume, uint64_t block, uint8_t **data, bool for_write) { diff --git a/fs/ext_common/internal.h b/fs/ext_common/internal.h index 7022d445..58d1af56 100644 --- a/fs/ext_common/internal.h +++ b/fs/ext_common/internal.h @@ -143,10 +143,36 @@ int storage_ext4_remove_range_observed(struct storage_volume *v,uint64_t ino,uin * reached EOF, not merely because the output capacity was exhausted. */ int storage_ext4_fiemap(struct storage_volume *, uint64_t, uint64_t, uint64_t, struct storage_ext4_fiemap_extent *, uint32_t, uint32_t *); -int storage_ext4_read_file_range(struct storage_volume *, uint64_t, - const struct ext4_inode_view *, uint64_t, - void *, uint32_t, uint32_t *); +/** @brief Copy a file range using its validated inode and extent mappings. + * @param v Borrowed mounted volume held under storage execution ownership. + * @param ino File inode number used to validate block mappings. + * @param in Borrowed inode view, stable throughout this synchronous call. + * @param offset First requested byte in the file. + * @param buffer Caller-owned writable storage for len bytes, nullable for zero len. + * @param len Requested byte count, clamped to the inode's EOF. + * @param out_read Optional output for bytes copied, including a prefix on error. + * @return Zero at EOF or after success, otherwise a negative validation or I/O + * errno. Holes and unwritten extents yield zeros. Small complete-block reads + * can populate a bounded initialized extent window during synchronous I/O. + * Optional read-ahead failures retry the required range. No caller pointer is + * retained and asynchronous request identity follows only required blocks. + */ +int storage_ext4_read_file_range(struct storage_volume *v, uint64_t ino, + const struct ext4_inode_view *in, uint64_t offset, + void *buffer, uint32_t len, uint32_t *out_read); int storage_ext4_cache_read_blocks(struct storage_volume *, uint64_t, uint32_t, void *); +/** @brief Read required blocks and optionally cache a bounded initialized file window. + * @param v Borrowed volume under storage execution ownership. + * @param first First mapped physical block. + * @param count Required blocks fitting out. + * @param window Initialized mapped blocks before EOF, at most 16 KiB. + * @param out Writable count times block_size bytes. + * @return Zero or the required read's errno. Speculation is synchronous only, + * optional under cache pressure, and tail failures retry the required range. + * No caller buffer is retained and asynchronous request identity is unchanged. + */ +int storage_ext4_cache_read_window(struct storage_volume *v, uint64_t first, + uint32_t count, uint32_t window, void *out); int storage_ext4_dir_iterate(struct storage_volume *,uint64_t,uint64_t *,struct storage_ext4_dirent *); int storage_ext4_dir_lookup(struct storage_volume *,uint64_t,const char *,uint64_t *,uint8_t *); /** @brief Search one directory using a preallocated three-block workspace. diff --git a/fs/ext_common/ops.c b/fs/ext_common/ops.c index f19b44e2..f6ac8a2b 100644 --- a/fs/ext_common/ops.c +++ b/fs/ext_common/ops.c @@ -111,6 +111,7 @@ int storage_ext4_read_inode(struct storage_volume *v, uint64_t ino, struct ext4_ return out->mode ? 0 : -RELIEFOS_ENOENT; } +/** @copydoc storage_ext4_read_file_range */ int storage_ext4_read_file_range(struct storage_volume *v, uint64_t ino, const struct ext4_inode_view *in, uint64_t offset, void *buffer, uint32_t len, uint32_t *out_read) @@ -161,7 +162,15 @@ int storage_ext4_read_file_range(struct storage_volume *v, uint64_t ino, } else { uint32_t blocks = take / bs; if (blocks > EXT4_READAHEAD_BLOCKS) blocks = EXT4_READAHEAD_BLOCKS; - ret = storage_ext4_cache_read_blocks(v, physical, blocks, (uint8_t *)buffer + done); + uint32_t window = 16384 / bs; + uint64_t full_blocks = (in->size - pos) / bs; + if (window > map.length - consumed) window = map.length - consumed; + if (window > full_blocks) window = (uint32_t)full_blocks; + if (blocks * bs <= 4096 && window > blocks) + ret = storage_ext4_cache_read_window(v, physical, blocks, window, + (uint8_t *)buffer + done); + else + ret = storage_ext4_cache_read_blocks(v, physical, blocks, (uint8_t *)buffer + done); if (ret < 0) break; take = blocks * bs; } diff --git a/fs/fat/mkfs.c b/fs/fat/mkfs.c index 7d0e7e53..1f0f9707 100644 --- a/fs/fat/mkfs.c +++ b/fs/fat/mkfs.c @@ -2,19 +2,36 @@ #include "../../block/core/storage_internal.h" #include "internal.h" -/** @brief Choose a FAT32 cluster size preserving the ESP minimum cluster count. - * @param total_sectors Validated extent size in 512-byte sectors. - * @return Sectors per cluster. Pure layout choice, no allocation or I/O. +/** @brief Find a FAT32 layout with the largest permissible clusters up to 4 KiB. + * @param total Total sectors in the new filesystem. + * @param reserved Sectors before the first FAT. + * @param copies Number of mirrored FATs. + * @param fat_size Output sectors per FAT. + * @param clusters Output number of data clusters, including the root. + * @return Sectors per cluster, or zero if the extent cannot be FAT32. */ -static uint32_t install_choose_fat32_spc(uint64_t total_sectors) +static uint32_t install_fat32_layout(uint32_t total, uint32_t reserved, uint32_t copies, + uint32_t *fat_size, uint32_t *clusters) { - uint64_t bytes = total_sectors * SECTOR_SIZE; - /* The ESP is intentionally small but must still meet the FAT32 minimum - * cluster-count rule. One KiB clusters keep a 128 MiB ESP standards-sized; - * the normal high-volume data path uses the separate exFAT root. */ - if (bytes <= 128ULL * 1024ULL * 1024ULL) return 2u; - if (bytes <= 512ULL * 1024ULL * 1024ULL) return 4u; - return 8u; + const uint32_t entries_per_sector = SECTOR_SIZE / sizeof(uint32_t); + if (total <= reserved) return 0; + for (uint32_t spc = 4096 / SECTOR_SIZE; spc; spc >>= 1) { + /* Solve floor((total-reserved-copies*fat)/spc)+2 <= entries*fat + * directly. Iterating in both directions around a rounding boundary + * can oscillate and leave the final data count and FAT size out of sync. */ + uint32_t divisor = copies + entries_per_sector * spc; + uint32_t fat = ((uint64_t)(total - reserved) + spc + divisor) / divisor; + uint32_t overhead = reserved + copies * fat; + if (total <= overhead) continue; + uint32_t count = (total - overhead) / spc; + /* FAT type is determined by data cluster count, not the BPB label. + * Cluster numbers start at 2 and must not enter the reserved range. */ + if (count < 65525u || count > 0x0fffffeeu) continue; + *fat_size = fat; + *clusters = count; + return spc; + } + return 0; } /** @brief Write native FAT32 metadata into an authorized unmounted extent. @@ -29,33 +46,15 @@ int install_format_fat32(struct install_disk_state *disk, uint64_t start_lba, const uint32_t reserved = 32; const uint32_t fat_count = 2; uint32_t total_sectors; - uint32_t sectors_per_cluster; - uint32_t fat_size = 1; - uint32_t data_start; - uint32_t data_sectors; - uint32_t clusters = 0; + uint32_t sectors_per_cluster, fat_size, data_start, clusters; if (!disk || sector_count > 0xffffffffULL || sector_count < 65536ULL) { return -28; } total_sectors = (uint32_t)sector_count; - sectors_per_cluster = install_choose_fat32_spc(sector_count); - for (uint32_t i = 0; i < 16; ++i) { - uint32_t next_fat_size; - if (total_sectors <= reserved + fat_count * fat_size) { - return -28; - } - data_sectors = total_sectors - reserved - fat_count * fat_size; - clusters = data_sectors / sectors_per_cluster; - next_fat_size = ((clusters + 2u) * 4u + SECTOR_SIZE - 1u) / SECTOR_SIZE; - if (next_fat_size == fat_size) { - break; - } - fat_size = next_fat_size; - } + sectors_per_cluster = install_fat32_layout(total_sectors, reserved, fat_count, + &fat_size, &clusters); + if (!sectors_per_cluster) return -28; data_start = reserved + fat_count * fat_size; - if (clusters < 2 || data_start >= total_sectors) { - return -28; - } int ret = install_clear_sectors(disk, start_lba, (uint64_t)data_start + sectors_per_cluster); if (ret < 0) { diff --git a/tools/test_ext4_read.py b/tools/test_ext4_read.py index 619dba11..50395467 100644 --- a/tools/test_ext4_read.py +++ b/tools/test_ext4_read.py @@ -43,6 +43,7 @@ def main(): "-Iinclude", "-Iinclude", "-Iinclude/uapi", "-Iinclude", "tools/tests/ext4_vfs_read_test.c", "fs/tmpfs/core.c", "mm/physical/proc.c", "lib/text_utf16.c", + "drivers/storage/nvme/queue.c", "-o", str(vfs_binary)]) if args.case in ("all", "unit"): run([str(binary)], env=env) diff --git a/tools/test_filesystem_format.py b/tools/test_filesystem_format.py index 1eca618b..85e64b94 100644 --- a/tools/test_filesystem_format.py +++ b/tools/test_filesystem_format.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Validate real registered native formatters with independent fsck tools.""" from pathlib import Path +import struct import subprocess import tempfile import unittest @@ -31,6 +32,23 @@ def test_native_bytes_bounds_and_provider_lifetime(self): subprocess.run([str(binary), name, str(image)], check=True, timeout=30) subprocess.run([*checker, str(image)], check=True, timeout=30) + # A 512 MiB ESP can use 4 KiB clusters, and a 64 MiB ESP must use + # 512-byte clusters to remain FAT32 by the on-disk cluster count. + for sectors, spc in ((1048576, 8), (131072, 1)): + with self.subTest(sectors=sectors): + image = work / f"esp-{sectors}.img" + subprocess.run([str(binary), "vfat", str(image), str(sectors)], + check=True, timeout=30) + with image.open("rb") as file: + bpb = file.read(512) + self.assertEqual(bpb[13], spc) + reserved = struct.unpack_from("ext4.block_size, blocks * v->ext4.block_size); memset(scratch, 0xee, sizeof(scratch)); return 0; } +/* This mapping-only fixture leaves speculation to the real cache suite. */ +int storage_ext4_cache_read_window(struct storage_volume *v, uint64_t first, + uint32_t count, uint32_t window, void *out) +{ + assert(window >= count); + return storage_ext4_cache_read_blocks(v, first, count, out); +} + static uint8_t oracle(uint64_t byte) { diff --git a/tools/tests/ext4_write_range_alloc_test.c b/tools/tests/ext4_write_range_alloc_test.c index 7586f81e..4f046158 100644 --- a/tools/tests/ext4_write_range_alloc_test.c +++ b/tools/tests/ext4_write_range_alloc_test.c @@ -76,6 +76,14 @@ int storage_ext4_cache_read_blocks(struct storage_volume *v, uint64_t physical, assert(v == &volume && blocks == 1 && active); ++reads; memcpy(out, block(physical), volume.ext4.block_size); return 0; } +/* This mapping-only fixture leaves speculation to the real cache suite. */ +int storage_ext4_cache_read_window(struct storage_volume *v, uint64_t first, + uint32_t count, uint32_t window, void *out) +{ + assert(window >= count); + return storage_ext4_cache_read_blocks(v, first, count, out); +} + void storage_ext4_cache_finish(struct storage_volume *v, uint64_t physical, const uint8_t *data) diff --git a/tools/tests/filesystem_format_test.c b/tools/tests/filesystem_format_test.c index 87117b25..0d697f59 100644 --- a/tools/tests/filesystem_format_test.c +++ b/tools/tests/filesystem_format_test.c @@ -13,7 +13,8 @@ static struct module owner; static struct install_disk_state owned_disk; static uint8_t *backing; -static const uint64_t first=2048,sectors=262144; +static const uint64_t first=2048; +static uint64_t sectors=262144; static unsigned writes,allocations; static bool fail_write; /** @brief Reject unexpected journal flushes in this ext2/ext4-only fixture. @@ -44,15 +45,23 @@ static int forbidden_mount(const struct fs_mount_request *request,struct vfs_mou { (void)request;(void)out;abort(); } int main(int argc,char **argv) { - assert(argc==3); + storage_memzero(NULL,0); + storage_memcpy(NULL,NULL,0); + assert(argc==3 || argc==4); + if (argc==4) { + char *end; + sectors=strtoull(argv[3],&end,10); + assert(!*end && sectors && sectors<=1048576); + } int (*format)(struct install_disk_state *,uint64_t,uint64_t)= !strcmp(argv[1],"vfat") ? install_format_fat32 : !strcmp(argv[1],"exfat") ? install_format_exfat : !strcmp(argv[1],"ext2") ? install_format_ext2 : !strcmp(argv[1],"ext4") ? install_format_ext4 : NULL; assert(format); - backing=malloc((size_t)(first+sectors+2048)*512);assert(backing); - memset(backing,0xa5,(size_t)(first+sectors+2048)*512); + backing=calloc((size_t)(first+sectors+2048),512);assert(backing); + memset(backing,0xa5,(size_t)first*512); + memset(backing+(first+sectors)*512,0xa5,2048*512); owned_disk=(struct install_disk_state){.present=true,.sector_count=first+sectors+2048}; struct module_runtime *runtime=kernel_malloc(sizeof(*runtime));assert(runtime); strcpy(runtime->name,"formatfs");strcpy(owner.name,"formatfs"); @@ -68,7 +77,17 @@ int main(int argc,char **argv) for(uint64_t i=0;i Date: Thu, 3 Dec 2026 06:59:12 +0800 Subject: [PATCH 97/97] fix(docs): translate storage performance updates --- .../core-api/storage-completion.po | 31 +++++++++++++++++++ .../core-api/storage-completion.po | 22 +++++++++++++ 2 files changed, 53 insertions(+) diff --git a/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po b/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po index 19edeabf..f9c7381d 100644 --- a/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po +++ b/Documentation/locale/en/LC_MESSAGES/core-api/storage-completion.po @@ -219,6 +219,37 @@ msgstr "``tools/test_fat_read_split.py`` uses the production FAT directory, bloc msgid "FAT32 大于预读缓存的合法簇通过现有簇缓冲区逐簇读取,保留碎片链游标、部分读取和错误语义,不扩大预读缓存。" msgstr "Legal FAT32 clusters larger than the read-ahead cache are read individually through the existing cluster buffer. Fragmented-chain cursors, partial-read and error semantics are retained without enlarging the read-ahead cache." +msgid "" +"ext 的同步完整块小读在首块未命中缓存时,尝试读取最多 16KiB 的连续窗口。 窗口受已初始化 extent、文件 EOF 和缓存容量限制,命中已有窗口时继续消费缓存。 " +"预读使用独立的固定 CPU 缓冲,沿用 storage execution owner;异步请求保持原来的 请求范围。脏块与 journal overlay 仍由原缓存逻辑保护,预读失败后重新读取调用方 " +"必需的范围。``tools/test_ext4_read.py`` 覆盖顺序读取的传输次数、EOF、错误回退、 缓冲边界和脏数据,``tools/test_ext4_io_search.py`` 覆盖读取接续。" +msgstr "" +"For small synchronous reads of complete ext blocks, a cache miss on the " +"first block triggers an attempt to read a contiguous window of up to " +"16KiB. Initialized extents, file EOF and cache capacity bound the window. " +"Reads that hit an existing window consume the cached data. Read-ahead " +"uses a separate fixed CPU buffer under the storage execution owner. " +"Asynchronous requests retain their original ranges. The existing cache " +"logic protects dirty blocks and journal overlays. If read-ahead fails, " +"the caller's required range is read again. ``tools/test_ext4_read.py`` " +"covers transfer counts for sequential reads, EOF, error fallback, buffer " +"boundaries and dirty data. ``tools/test_ext4_io_search.py`` covers read " +"continuations." + +msgid "" +"存储内部的清零与复制复用内核字符串实现的 ``rep stosb`` 和 ``rep movsb``, 不使用 SIMD 状态。原生 FAT32 格式化选择满足 FAT32 数据簇数约束的最大簇, " +"上限为 4KiB,并直接计算 FAT 扇区数。512MiB ESP 使用 4KiB 簇,较小卷继续 缩小簇以满足至少 65525 个数据簇的要求。``tools/test_filesystem_format.py`` " +"通过独立 ``fsck.fat`` 检查几何和元数据。" +msgstr "" +"Storage zeroing and copying reuse ``rep stosb`` and ``rep movsb`` from " +"the kernel string implementation, using general-purpose registers. The " +"native FAT32 formatter selects the largest cluster that meets the FAT32 " +"data-cluster count constraints, up to 4KiB, and calculates the FAT sector " +"count directly. A 512MiB ESP uses 4KiB clusters. Smaller volumes use " +"smaller clusters to provide at least 65525 data clusters. " +"``tools/test_filesystem_format.py`` checks geometry and metadata with " +"the independent ``fsck.fat`` tool." + msgid "常规 ext4 挂载将连续元数据操作合并到有界 JBD2 提交组。共享块缓存驱逐时仍从日志组读取最新镜像;单次操作失败只撤销该操作,不丢弃较早的成功操作。块或 inode 释放在资源可被下一操作重用之前建立持久化边界。" msgstr "Ordinary ext4 mounts combine consecutive metadata operations into bounded JBD2 groups. Reads still see the latest journal image after shared-cache eviction. A failed operation rolls back only its own changes; successful earlier operations remain. Freed blocks and inodes cross a durability barrier before a later operation can reuse them." diff --git a/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po b/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po index 6cf0f283..8bc3ccfb 100644 --- a/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po +++ b/Documentation/locale/ja/LC_MESSAGES/core-api/storage-completion.po @@ -195,6 +195,28 @@ msgstr "``tools/test_fat_read_split.py`` は実際の FAT ディレクトリー msgid "FAT32 大于预读缓存的合法簇通过现有簇缓冲区逐簇读取,保留碎片链游标、部分读取和错误语义,不扩大预读缓存。" msgstr "FAT32 の有効なクラスタが先読みキャッシュより大きい場合、既存のクラスタバッファーを使って一つずつ読み取ります。先読みキャッシュを拡大せず、断片化チェーンのカーソル、部分読み取りとエラーの意味を維持します。" +msgid "" +"ext 的同步完整块小读在首块未命中缓存时,尝试读取最多 16KiB 的连续窗口。 窗口受已初始化 extent、文件 EOF 和缓存容量限制,命中已有窗口时继续消费缓存。 " +"预读使用独立的固定 CPU 缓冲,沿用 storage execution owner;异步请求保持原来的 请求范围。脏块与 journal overlay 仍由原缓存逻辑保护,预读失败后重新读取调用方 " +"必需的范围。``tools/test_ext4_read.py`` 覆盖顺序读取的传输次数、EOF、错误回退、 缓冲边界和脏数据,``tools/test_ext4_io_search.py`` 覆盖读取接续。" +msgstr "" +"ext の完全なブロックを少量ずつ同期読み取りするとき、先頭ブロックがキャッシュにない場合は、最大 16KiB の連続領域の読み取りを試みます。" +"対象範囲は初期化済み extent、ファイルの EOF、キャッシュ容量で制限し、既存の範囲にヒットした場合はキャッシュを使います。" +"先読みには専用の固定 CPU バッファーを使い、storage execution owner による所有権管理を適用します。" +"非同期要求は元の要求範囲を使用します。dirty ブロックと journal overlay は既存のキャッシュ処理で保護し、" +"先読みに失敗した場合は呼び出し側に必要な範囲を再度読み取ります。``tools/test_ext4_read.py`` は連続読み取りの転送回数、EOF、" +"エラー時のフォールバック、バッファー境界、dirty データを検証し、``tools/test_ext4_io_search.py`` は読み取りの継続を検証します。" + +msgid "" +"存储内部的清零与复制复用内核字符串实现的 ``rep stosb`` 和 ``rep movsb``, 不使用 SIMD 状态。原生 FAT32 格式化选择满足 FAT32 数据簇数约束的最大簇, " +"上限为 4KiB,并直接计算 FAT 扇区数。512MiB ESP 使用 4KiB 簇,较小卷继续 缩小簇以满足至少 65525 个数据簇的要求。``tools/test_filesystem_format.py`` " +"通过独立 ``fsck.fat`` 检查几何和元数据。" +msgstr "" +"ストレージ内部のゼロクリアとコピーには、カーネルの文字列実装の ``rep stosb`` と ``rep movsb`` を汎用レジスターで使用します。" +"ネイティブ FAT32 フォーマッターは、FAT32 のデータクラスタ数の制約を満たす最大のクラスタを 4KiB を上限に選び、" +"FAT セクタ数を直接計算します。512MiB の ESP は 4KiB クラスタを使い、小さいボリュームでは最低 65525 個のデータクラスタを" +"確保できるようクラスタを小さくします。``tools/test_filesystem_format.py`` は独立した ``fsck.fat`` でジオメトリーとメタデータを検証します。" + msgid "常规 ext4 挂载将连续元数据操作合并到有界 JBD2 提交组。共享块缓存驱逐时仍从日志组读取最新镜像;单次操作失败只撤销该操作,不丢弃较早的成功操作。块或 inode 释放在资源可被下一操作重用之前建立持久化边界。" msgstr "通常の ext4 マウントでは、連続するメタデータ操作を上限のある JBD2 グループにまとめます。共有キャッシュから追い出されたブロックも、ロググループの最新イメージから読み取ります。失敗した操作だけを取り消し、先に成功した操作は維持します。解放したブロックや inode を後続の操作で再利用する前に、永続化バリアを通過させます。"