获取内核模块中的所有挂载点

Get all mount points in kernel module

我正在尝试获取内核模块中的所有挂载点。下面是我想出的。由于 strcat,它会出现段错误。这是获取挂载点的正确方法吗?这行得通吗?如果是这样,我该如何修复段错误?如果没有,如何在 linux 内核模块中获取挂载点?

我试过 cycle the whole namespace looking for mountpoint roots that match but its from 2003 and the kernel has changed so much so its basically useless. Also tried get filesystem mount point in kernel module 但还是从 2012 年开始的,所以它已经过时了。

static int __init misc_init(void)
{
    struct path path;
    struct dentry *thedentry;
    struct dentry *curdentry;

    kern_path("/", LOOKUP_FOLLOW, &path);
    thedentry = path.dentry;
    list_for_each_entry(curdentry, &thedentry->d_subdirs, d_child)
    {
        kern_path(strncat("/", curdentry->d_name.name, strlen(curdentry->d_name.name)), LOOKUP_FOLLOW, &path);
        if (path_is_mountpoint(&path))
        {
            printk("%s: is a mountpoint", curdentry->d_name.name);
        }
        else
            printk("%s: is not a mountpoint", curdentry->d_name.name);
    }
    return 0;
}

在 dentry 结构中有它的标志。 d_flags。并且有一个标志 DCACHED_MOUNTED。获取当前指针。 fs_struct 在那里。然后是根。这为您提供了当前文件系统的根目录。从那里循环遍历所有子目录,如果 d_flags & DCACHE_MOUNTED 通过则它是一个挂载点。

ssize_t read_proc(struct file *filp, char *buf, size_t len, loff_t *offp )
{
    struct dentry *curdentry;

    list_for_each_entry(curdentry, &current->fs->root.mnt->mnt_root->d_subdirs, d_child)
    {
        if ( curdentry->d_flags & DCACHE_MOUNTED)
            printk("%s is mounted", curdentry->d_name.name);
    }
    return 0;
}

可能以下是获取所有挂载点的最佳方法 w/o 检查系统的所有目录。

struct mnt_namespace *ns = current->nsproxy->mnt_ns;
struct mount *mnt;

list_for_each_entry(mnt, &ns->list, mnt_list) {
...do something with each mnt...
}

请注意,此代码不成立 namespace_sem,因此无法保证遍历 mnt_list 的结果。然而,恕我直言,它至少不亚于遍历持有挂载锁的所有目录w/o。