如何在 ext4 中查找文件名?

How is filename lookup done in ext4?

环境:Linux 内核 5.3;全系统:ext4

请求 stat(const char *pathname, struct stat *statbuf) 时如何检查 const char *pathname 是否存在?

这是必要的,因为万一没有这样的路径stat returns -1 (ENOENT)。这是我正在测试的程序:

static const char *pathname = "/some/fancy/path/name";

int main(void){
    struct stat statbuf;
    unsigned long i = 0;
    int fd = -1;
    while(1){
        if((++i) % 2){
            fd = open(pathname, O_CREAT, 0644);
        }
        stat(pathname, &statbuf);
        if(i % 2){
            close(fd);
            unlink(pathname);
        }
    }
}

每隔 2 次迭代,文件就会被删除并在下一次迭代时重新创建。为了检查内核调用堆栈,我使用了 perf report:

调用栈不符合我的预期。我希望在 vfs_statx 下调用 ext4 以遍历 ext4 内部数据结构,这可能需要磁盘 I/O.

如果它被缓存在 inode 或 dentry 缓存中,如何刷新它以检查 ext4 调用需要什么 stat(const char *pathname, struct stat *statbuf);?

UPD:仔细查看实现,我发现它似乎是从 link_path_walk

中指定的 dentry 缓存中获取的

If it was cached in the inode or dentry cache how to flush it in order to inspect what ext4 calls would require stat(const char *pathname, struct stat *statbuf);?

你应该可以通过 /proc/sys/vm/drop_caches(来自 Documentation/sysctl/vm.txt)来做到这一点:

drop_caches

Writing to this will cause the kernel to drop clean caches, as well as
reclaimable slab objects like dentries and inodes.  Once dropped, their
memory becomes free.

To free pagecache:
  echo 1 > /proc/sys/vm/drop_caches
To free reclaimable slab objects (includes dentries and inodes):
  echo 2 > /proc/sys/vm/drop_caches
To free slab objects and pagecache:
  echo 3 > /proc/sys/vm/drop_caches

基本上就是:echo 2 | sudo tee /proc/sys/vm/drop_caches.


根据真正的问题,为了了解 ext4 如何处理查找,您可以查看 inode_operations 结构 defined in fs/ext4/namei.c. More specifically, you are interested in the .lookup operation, which is ext4_lookup()。查找时会调用此函数。

调用树应该是这样的: