Linux path-lookup 翻译

1,339 阅读1小时+

Pathname lookup in Linux.

=========================

This write-up is based on three articles published at lwn.net:

Written by Neil Brown with help from Al Viro and Jon Corbet.

Introduction

The most obvious aspect of pathname lookup, which very little exploration is needed to discover, is that it is complex. There are many rules, special cases, and implementation alternatives that all combine to confuse the unwary reader.

对于路径查找很明显的一个概念就是:需要发现的探索很少,但它又是复杂的。 它有很多规则,特殊的情况,以及不同的实现,这些都会使读者感到困惑。

Computer science has long been acquainted with such complexity and has tools to help manage it.
One tool that we will make extensive use of is "divide and conquer". For the early parts of the analysis we will divide off symlinks - leaving them until the final part.

计算机科学对于这种复杂性情况已经很熟悉了,也有了相关工具帮助我们去解决它。 其中一个广泛使用的工具就是“分而治之”。 所以在早期的分析中,我们不考虑有符号链接的情况,把它留到后面。

Well before we get to symlinks we have another major division based on the VFS's approach to locking which will allow us to review "REF-walk" and "RCU-walk" separately. But we are getting ahead of ourselves. There are some important low level distinctions we need to clarify first.

在考虑符号链接之前,我们先来解决另一个主要部分:基于VFS的方法去锁定,它可以使我们独立地分析 "REF-walk" , "RCU-walk" 这两种情况。 在深入之前,我们需要先了解一些低层次的区别。

There are two sorts of ...

Pathnames (sometimes "file names"), used to identify objects in the filesystem, will be familiar to most readers. They contain two sorts of elements: "slashes" that are sequences of one or more "/" characters, and "components" that are sequences of one or more non-"/" characters. These form two kinds of paths. Those that start with slashes are "absolute" and start from the filesystem root. The others are "relative" and start from the current directory, or from some other location specified by a file descriptor given to a "xxxat" system call such as "openat()".

路径名(或者称为“文件名”),通常用来在文件系统中标识一个对象,大多数 读者对此不陌生。 它们包含了两种元素:一个或多个的 “\”,以及 “components” 也就剩下的非反斜杠字符。 因此就有了两种类型的路径,一种就是从文件系统根目录开始的绝对路径,以反斜杠开头。 另一种就是相对路径,要么是相对于当前目录开始,要么就是从一个指定的目录开始。

It is tempting to describe the second kind as starting with a component, but that isn't always accurate: a pathname can lack both slashes and components, it can be empty, in other words.
把第二种(相对路径)描述为以一个组件名开始的路径是很诱人的,但这种说法并不是 完全正确,因为一个路径名可以没有反斜杠和组件名,换句话说他可以是空的。

This is generally forbidden in POSIX, but some of those "xxxat" system calls in Linux permit it when the AT_EMPTY_PATH flag is given. For example, if you have an open file descriptor on an executable file you can execute it by calling execveat() passing the file descriptor, an empty path, and the AT_EMPTY_PATH flag.

这在 POSIX 中一般是被禁止的,但是一些带有 “AT_EMPTY_PATH” 标志的 “xxx at” 系统调用允许使用空路径。 例如:如果你有个已打开文件的文件描述符,那么你可以把这个文件描述符,空路径, 以及 “AT_EMPTY_PATH” 传递给 “execveat()” 系统调用。

These paths can be divided into two sections: the final component and everything else. The "everything else" is the easy bit. In all cases it must identify a directory that already exists, otherwise an error such as ENOENT or ENOTDIR will be reported.

路径可以被分为两部分:“其他部分” 以及 “最后一项”,对于 “其他部分”,它一定 标识了某个已存在的目录,不然就会返回 ENOENT 或者 ENOTDIR 错误。

The final component is not so simple. Not only do different system calls interpret it quite differently (e.g. some create it, some do not), but it might not even exist: neither the empty pathname nor the pathname that is just slashes have a final component. If it does exist, it could be "." or ".." which are handled quite differently from other components.

“最后一项”并不是那么简单,不只是不同的系统调用对其的处理不同,但还有可能它根本不存在。 要么就是一个空路径名,或者就只是一个反斜杠。假设它存在,那么它可能是一个“.”或者“..”, 这两者与其他正常组件名有很大的区别。

If a pathname ends with a slash, such as "/tmp/foo/" it might be tempting to consider that to have an empty final component. In many ways that would lead to correct results, but not always. In particular, mkdir() and rmdir() each create or remove a directory named by the final component, and they are required to work with pathnames ending in "/". According to POSIX

如果路径名以斜杠结尾,比如 “/tmp/foo/”,那么很可能会认为最后一个组件是空的。 在很多时候,这将导致正确的结果,但并不总是这样。特别是,mkdir()rmdir()各自创建 或删除一个由最终组件命名的目录,并且需要使用以 “/” 结尾的路径名。 根据POSIX:

A pathname that contains at least one non- <slash> character and that ends with one or more trailing <slash> characters shall not be resolved successfully unless the last pathname component before the trailing characters names an existing directory or a directory entry that is to be created for a directory immediately after the pathname is resolved.

一个包含至少一个非 “/” 字符,并以一个或多个 “/” 字符结束的路径名是不应该被成功解析, 除非在结尾处 “/” 之前的最后一个路径名组件(分量)是一个已存在的目录名,或者是一个目录项 它表示了在路径名解析完后需要马上创建的目录。

The Linux pathname walking code (mostly in fs/namei.c) deals with all of these issues: breaking the path into components, handling the "everything else" quite separately from the final component, and checking that the trailing slash is not used where it isn't permitted. It also addresses the important issue of concurrent access.

Linux 路径名遍历代码(主要在 fs/namei.c 中)处理所有这些问题:将路径拆分成组件(分量), “everything else” 的处理与最终组件(分量)的处理完全独立,并检查是否能使用尾反斜杠。 它还解决了并发访问的重要问题。

While one process is looking up a pathname, another might be making changes that affect that lookup. One fairly extreme case is that if "a/b" were renamed to "a/c/b" while another process were looking up "a/b/..", that process might successfully resolve on "a/c". Most races are much more subtle, and a big part of the task of pathname lookup is to prevent them from having damaging effects. Many of the possible races are seen most clearly in the context of the "dcache" and an understanding of that is central to understanding pathname lookup.

当一个进程正在查找路径名时,另一个进程可能正在进行影响查找的更改。一个相当极端的情况是, 如果 a/b 被重命名为 a/c/b,而另一个进程正在查找 a/b/..,该进程也许能成功解析到 a/c 。大多数竞争要微妙得多,而 pathname 查找的主要任务是防止它们产生破坏性的影响。 在 “dcache” 上下文中可以清楚地看到许多可能的竞争,理解这一点对于理解路径名查找非常重要。

More than just a cache.

The "dcache" caches information about names in each filesystem to make them quickly available for lookup. Each entry (known as a "dentry") contains three significant fields: a component name, a pointer to a parent dentry, and a pointer to the "inode" which contains further information about the object in that parent with the given name. The inode pointer can be NULL indicating that the name doesn't exist in the parent. While there can be linkage in the dentry of a directory to the dentries of the children, that linkage is not used for pathname lookup, and so will not be considered here.

dcache 在每个文件系统中缓存关于名称的信息,以便能够快速地进行查找。每个条目(称为 “dentry”) 都包含三个重要字段: 组件名称、指向父目录的 dentry 指针和指向 inode 的指针,后者 包含父目录下对应于给定名称对象的进一步信息。inode 指针可以为空,表示该名称对应的对象在 父节点中不存在。虽然目录的 dentry 中可以有到子目录的 dentries 的链接,但该链接 不用于路径名查找,因此这里不考虑该链接。(这里父目录,父节点,父目录项表示的含义相同。)

The dcache has a number of uses apart from accelerating lookup. One that will be particularly relevant is that it is closely integrated with the mount table that records which filesystem is mounted where. What the mount table actually stores is which dentry is mounted on top of which other dentry.

除了加速查找之外,dcache 还有许多用途。特别相关的一点是,它与记录文件系统挂载位置的 挂载表紧密集成。挂载表实际保存了哪个 dentry 挂载在哪个 dentry 之下。

When considering the dcache, we have another of our "two types" distinctions: there are two types of filesystems. Some filesystems ensure that the information in the dcache is always completely accurate (though not necessarily complete). This can allow the VFS to determine if a particular file does or doesn't exist without checking with the filesystem, and means that the VFS can protect the filesystem against certain races and other problems. These are typically "local" filesystems such as ext3, XFS, and Btrfs.

在考虑 dcache 时,我们还有另一个 “两种类型” 的区别:有两种类型的文件系统。一些文件系统 确保 dcache 中的信息总是完全准确的(尽管不一定是完整的)。这允许 VFS 在不用文件系统 进行检查的情况下确定特定文件是否存在,这意味着 VFS 可以保护文件系统不受某些竞争和其他 问题的影响。这些文件系统通常是 “本地” 文件系统,比如 ext3XFSBtrfs

Other filesystems don't provide that guarantee because they cannot. These are typically filesystems that are shared across a network, whether remote filesystems like NFS and 9P, or cluster filesystems like ocfs2 or cephfs. These filesystems allow the VFS to revalidate cached information, and must provide their own protection against awkward races. The VFS can detect these filesystems by the DCACHE_OP_REVALIDATE flag being set in the dentry.

其他文件系统不提供这种保证,因为它们不能。这些文件系统通常是跨网络共享的文件系统,无论是 NFS9P 这样的远程文件系统,还是 ocfs2cephfs 这样的集群文件系统。这些 文件系统允许 VFS 重新验证缓存的信息,并且必须提供自己的保护,以防止出现尴尬的竞争。 VFS 可以通过在 dentry 中设置的 DCACHE_OP_REVALIDATE 标志检测这些文件系统。

REF-walk: simple concurrency management with refcounts and spinlocks

With all of those divisions carefully classified, we can now start looking at the actual process of walking along a path. In particular we will start with the handling of the "everything else" part of a pathname, and focus on the "REF-walk" approach to concurrency management. This code is found in the link_path_walk() function, if you ignore all the places that only run when "LOOKUP_RCU" (indicating the use of RCU-walk) is set.

将所有这些划分仔细分类之后,我们现在可以开始查看沿着路径行走的实际过程。特别地,我们将 从处理路径名的 “其他所有部分” 开始,重点讨论 REF-walk 模式下并发管理的方式。如果忽略 所有设置了 LOOKUP_RCU (指示使用 RCU-walk)标志分支的代码,剩下的代码基本就是 REF-walk 模式的代码了,可以在 link_path_walk()函数中找到这些代码。

REF-walk is fairly heavy-handed with locks and reference counts. Not as heavy-handed as in the old "big kernel lock" days, but certainly not afraid of taking a lock when one is needed. It uses a variety of different concurrency controls. A background understanding of the various primitives is assumed, or can be gleaned from elsewhere such as in Meet the Lockers.

REF-walk 在锁和引用计数方面相当笨拙。虽然不像过去的“大内核锁”时代那样严厉,但在需要锁 的时候,肯定不会害怕使用锁。它使用各种不同的并发控制。假设您对各种原语(各种锁)有一定的 背景了解,或者您可以从其他地方(比如 Meet the Lockers)了解这些。

The locking mechanisms used by REF-walk include:

REF-walk 锁机制包括了:

“dentry->d_lockref”

This uses the lockref primitive to provide both a spinlock and a reference count. The special-sauce of this primitive is that the conceptual sequence "lock; inc_ref; unlock;" can often be performed with a single atomic memory operation.

这使用了最近引入的 lockref 原语来提供自旋锁和引用计数。这个本原语的特殊之处在于 它概念上的序列 “lock; inc_ref; unlock” 通常可以通过一个原子内存操作来执行。

Holding a reference on a dentry ensures that the dentry won't suddenly be freed and used for something else, so the values in various fields will behave as expected. It also protects the ->d_inode reference to the inode to some extent.

dentry 上保存引用可以确保 dentry 不会突然被释放并用于其他用途,因此各个字段中的值 将按预期运行。它还在一定程度上保护了 ->d_inodeinode 的引用(间接引用了 inode)。

The association between a dentry and its inode is fairly permanent. For example, when a file is renamed, the dentry and inode move together to the new location. When a file is created the dentry will initially be negative (i.e. d_inode is NULL), and will be assigned to the new inode as part of the act of creation.

dentry 与其 inode 之间的关联是相当持久的。例如,当文件被重命名时,dentryinode 一起移动到新位置。创建文件时,dentry 最初为 negative(即 d_inodeNULL ), 并作为创建操作的一部分,之后 dentry 会指向一个新的 inode

When a file is deleted, this can be reflected in the cache either by setting d_inode to NULL, or by removing it from the hash table (described shortly) used to look up the name in the parent directory. If the dentry is still in use the second option is used as it is perfectly legal to keep using an open file after it has been deleted and having the dentry around helps. If the dentry is not otherwise in use (i.e. if the refcount in d_lockref is one), only then will d_inode be set to NULL. Doing it this way is more efficient for a very common case.

当一个文件被删除时,在缓存中的反映可以表现为:将 d_inode 设置为 NULL 或将其 从散列表中删除(稍后将进行描述)。散列表用于在父目录中查找名称。如果 dentry 仍然在使用, 则使用第二个选项,因为打开的文件在从缓存(散列表)被删除后继续使用是完全合法的,因为有 dentry 的协助。 如果 dentry 没有被使用中(例如,如果 d_lockref 中的 refcount1), 那么只有在这种情况下,d_inode 才会被设置为 NULL 。对于常见的情况,这样做更有效。

So as long as a counted reference is held to a dentry, a non-NULL ->d_inode value will never be changed.

因此,只要计数的引用保存到 dentry,就不会更改非 null->d_inode值。

“dentry->d_lock”

d_lock is a synonym for the spinlock that is part of d_lockref above. For our purposes, holding this lock protects against the dentry being renamed or unlinked. In particular, its parent (d_parent), and its name (d_name) cannot be changed, and it cannot be removed from the dentry hash table.

d_lock 是上面 d_lockref 的一部分的自旋锁的同义词。出于我们的目的,持有这个锁可以 防止 dentry 被重命名或取消链接。特别是,它的父目录项 (d_parent) 和名称 (d_name) 字段不能被更改,并且不能从 dentry 散列表中删除它。

When looking for a name in a directory, REF-walk takes d_lock on each candidate dentry that it finds in the hash table and then checks that the parent and name are correct. So it doesn't lock the parent while searching in the cache; it only locks children.

当在目录中查找名称时,REF-walk 对它在散列表中找到的每个候选 dentry 使用 d_lock, 然后检查父目录项(d_parent)和名称 (d_name) 是否正确。它在缓存中搜索时不会锁定父结点; 它只锁住孩子。

注:父节点指的是当前进行搜索所在的目录,孩子指的是候选 dentry。比如路径名: “a/b”,此时我要在目录 “a” 下搜索 “b” 对应的 dentry,那么父节点指的是 “a” 目录, 孩子指的是 “b”,d_lock 加锁对象就是找到的 “b” 对应的 dentry, 然后检查这个 dentry 的内容是否正确。

When looking for the parent for a given name (to handle ".."), REF-walk can take d_lock to get a stable reference to d_parent, but it first tries a more lightweight approach. As seen in dget_parent(), if a reference can be claimed on the parent, and if subsequently d_parent can be seen to have not changed, then there is no need to actually take the lock on the child.

在为给定名称寻找父目录项时(处理“..”),REF-walk 可以使用 d_lock 来获得对 d_parent 的稳定引用,但它首先尝试了一种更轻量级的方法。正如在 dget_parent() 中所看到的,如果 可以在父目录项声明引用,并且随后可以看到 d_parent 没有更改,那么实际上就没有必要对 子目录项使用锁。

“rename_lock”

Looking up a given name in a given directory involves computing a hash from the two values (the name and the dentry of the directory), accessing that slot in a hash table, and searching the linked list that is found there.

在给定目录(父目录)中查找给定名称涉及:根据两个值(name 和 父目录的 dentry)计算哈希值、 访问哈希表中的桶以及在其中找到的链表(桶对应的链表)中进行搜索。

When a dentry is renamed, the name and the parent dentry can both change so the hash will almost certainly change too. This would move the dentry to a different chain in the hash table. If a filename search happened to be looking at a dentry that was moved in this way, it might end up continuing the search down the wrong chain, and so miss out on part of the correct chain.

当重新命名 dentry 时,name 和 父 dentry 都可以更改,所以哈希值几乎肯定也会更改。 这将把 dentry 移到哈希表中的另一个链表上。如果在文件名搜索时碰巧遇到这种 dentry 移动问题,它可能会继续沿着错误的链表进行搜索,从而错过正确链表的一部分。

The name-lookup process (d_lookup()) does not try to prevent this from happening, but only to detect when it happens. rename_lock is a seqlock that is updated whenever any dentry is renamed. If d_lookup finds that a rename happened while it unsuccessfully scanned a chain in the hash table, it simply tries again.

名称查找过程( d_lookup())并不试图阻止这种情况发生,而是仅在发生时进行检测。rename_lock 是一个 seqlock,每当重命名任何 dentry 时都会更新它。如果 d_lookup发现在扫描哈希表中 的链表失败时发生了重命名,它将再次尝试。

“inode->i_mutex”

i_mutex is a mutex that serializes all changes to a particular directory. This ensures that, for example, an unlink() and a rename() cannot both happen at the same time. It also keeps the directory stable while the filesystem is asked to look up a name that is not currently in the dcache.

i_mutex 是一个互斥锁,它将序列化对特定目录的所有更改或者访问。这可以确保,例如, unlink()rename() 不能同时发生。同样当文件系统查找当前不在 dcache 中的 目录项时它能保持目录稳定(不被修改)。

This has a complementary role to that of d_lock: i_mutex on a directory protects all of the names in that directory, while d_lock on a name protects just one name in a directory. Most changes to the dcache hold i_mutex on the relevant directory inode and briefly take d_lock on one or more the dentries while the change happens. One exception is when idle dentries are removed from the dcache due to memory pressure. This uses d_lock, but i_mutex plays no role.

这与 d_lock 的作用互补:目录上的 i_mutex 保护该目录中的所有的 name,而 named_lock 只保护目录中的一个 name。对 dcache 的大多数更改都将在相关目录的 inode 上使用 i_mutex 互斥锁,并在更改发生时对一个或多个 dentry 使用 d_lock。一个例外 是由于内存压力而从 dcache 中删除空闲 dentry。这会使用 d_lock ,但是不需要使用 i_mutex

The mutex affects pathname lookup in two distinct ways. Firstly it serializes lookup of a name in a directory. walk_component() uses lookup_fast() first which, in turn, checks to see if the name is in the cache, using only d_lock locking. If the name isn't found, then walk_component() falls back to lookup_slow() which takes i_mutex, checks again that the name isn't in the cache, and then calls in to the filesystem to get a definitive answer. A new dentry will be added to the cache regardless of the result.

互斥量以两种不同的方式影响路径名查找。首先,它序列化目录中名称的查找。walk_component() 首先使用 lookup_fast() 检查名称是否在缓存中,只使用 d_lock 锁定。如果没有找到这个名称, 那么 walk_component() 将调用 lookup_slow(),它接受 i_mutex,再次检查这个名称是否 不在缓存中,然后调用文件系统具体相关方法来得到一个确定的答案。无论结果如何,都会向缓存添加 一个新的 dentry

Secondly, when pathname lookup reaches the final component, it will sometimes need to take i_mutex before performing the last lookup so that the required exclusion can be achieved. How path lookup chooses to take, or not take, i_mutex is one of the issues addressed in a subsequent section.

其次,当路径名查找到达最后一个组件时,有时需要在执行最后一次查找之前使用 i_mutex,以便 实现所需的排除。路径查找对于接不接受 i_mutex 如何选择的问题是后面一节讨论的问题之一。

“mnt->mnt_count”

mnt_count is a per-CPU reference counter on "mount" structures. Per-CPU here means that incrementing the count is cheap as it only uses CPU-local memory, but checking if the count is zero is expensive as it needs to check with every CPU. Taking a mnt_count reference prevents the mount structure from disappearing as the result of regular unmount operations, but does not prevent a "lazy" unmount. So holding mnt_count doesn't ensure that the mount remains in the namespace and, in particular, doesn't stabilize the link to the mounted-on dentry. It does, however, ensure that the mount data structure remains coherent, and it provides a reference to the root dentry of the mounted filesystem. So a reference through ->mnt_count provides a stable reference to the mounted dentry, but not the mounted-on dentry.

mnt_countmount 描述符的每 cpu 引用计数器。这里的 Per-CPU 意味着增加计数 很便宜,因为它只使用 CPU 本地内存,但是检查计数是否为零很昂贵,因为它需要检查每个 CPU。 使用 mnt_count 引用可以防止 mount 描述符由于常规卸载操作而消失,但不能防止“延迟”卸载。 因此,保存 mnt_count 并不能确保 mount 保持在名称空间中,特别是不能稳定指向挂载点的 dentry 的链接。但是,它确保 mount 数据结构保持一致,并提供对已挂载文件系统根 dentry 的引用。因此,通过 ->mnt_count 的引用提供了对已挂载 dentry 的稳定引用,而不是挂载点的 dentry

“mount_lock”

mount_lock is a global seqlock, a bit like rename_lock. It can be used to check if any change has been made to any mount points.

mount_lock是一个全局 seqlock,有点像 rename_lock。它可以用来检查任何挂载点的任何 修改。

While walking down the tree (away from the root) this lock is used when crossing a mount point to check that the crossing was safe. That is, the value in the seqlock is read, then the code finds the mount that is mounted on the current directory, if there is one, and increments the mnt_count. Finally the value in mount_lock is checked against the old value. If there is no change, then the crossing was safe. If there was a change, the mnt_count is decremented and the whole process is retried.

往下遍历树(远离根)时,当穿过一个挂载点时被用来检查此次穿过是否安全。也就是说,读取 seqlock 中的值,然后找到挂载在当前目录上的 mount 结构体(如果有的话),并增加字段 mnt_count 的值。最后根据旧值检查 mount_lock 中的值。如果没有变化,那么此时通过是 安全的。如果有更改,mnt_count 将递减,并重试整个过程。

When walking up the tree (towards the root) by following a ".." link, a little more care is needed. In this case the seqlock (which contains both a counter and a spinlock) is fully locked to prevent any changes to any mount points while stepping up. This locking is needed to stabilize the link to the mounted-on dentry, which the refcount on the mount itself doesn't ensure.

当沿着“..”链接向上遍历目录树(靠近根)时,需要多加注意。在这种情况下,seqlock(同时包含 计数器和自旋锁)被完全锁定,以防止在遍历时对任何挂载点的任何修改。需要使用此锁来稳定到 挂载点 dentry 的链接,而 mount 结构体本身的 refcount 不能确保这一点。

“RCU”

Finally the global (but extremely lightweight) RCU read lock is held from time to time to ensure certain data structures don't get freed unexpectedly. In particular it is held while scanning chains in the dcache hash table, and the mount point hash table.

最后,全局(但非常轻量级) RCU 读锁会不时被持有,以确保不会意外释放某些数据结构。 特别是,它在扫描 dcache 哈希表中的链表和挂载点哈希表时持有。

Bringing it together with “struct nameidata”

Throughout the process of walking a path, the current status is stored in a struct nameidata, "namei" being the traditional name - dating all the way back to First Edition Unix - of the function that converts a "name" to an "inode". struct nameidata contains (among other fields):

在遍历路径的过程中,当前状态存储在一个 struct nameidata 中,“namei” 是一个传统的名称, 可以追溯到将 “name” 转换为 “inode” 的函数的第一版 Unixstruct nameidata 包含以下 字段:

“struct path path”

A path contains a struct vfsmount (which is embedded in a struct mount) and a struct dentry. Together these record the current status of the walk. They start out referring to the starting point (the current working directory, the root directory, or some other directory identified by a file descriptor), and are updated on each step. A reference through d_lockref and mnt_count is always held.

一个 path 包含一个 struct vfsmount(它嵌入在 struct mount 中)和 struct dentry。 它们共同记录了遍历的当前状态。它们最开始引用的是 “起始点”(当前工作目录、根目录或由文件描述符 标识的其他目录),并在每个步骤中更新。始终保存通过 d_lockrefmnt_count 的引用。

“struct qstr last”

This is a string together with a length (i.e. not nul terminated) that is the "next" component in the pathname.

该结构体包含一个字符串和该字符串(即非 nul 终止)的长度,用来表示路径名中的 “下一个” 需要解析的组件。

“int last_type”

This is one of LAST_NORM, LAST_ROOT, LAST_DOT, LAST_DOTDOT, or LAST_BIND. The last field is only valid if the type is LAST_NORM. LAST_BIND is used when following a symlink and no components of the symlink have been processed yet. Others should be fairly self-explanatory.

LAST_NORMLAST_ROOTLAST_DOTLAST_DOTDOTLAST_BIND 其中之一的值。 只有当类型为 LAST_NORM 时,last 字段才有效。LAST_BIND 在跟踪符号链接时使用, 而该符号链接的组件还没有被处理。其他的应该是相当不言自明的。

“struct path root”

This is used to hold a reference to the effective root of the filesystem. Often that reference won't be needed, so this field is only assigned the first time it is used, or when a non-standard root is requested. Keeping a reference in the nameidata ensures that only one root is in effect for the entire path walk, even if it races with a chroot() system call.

这用于保存对文件系统有效根的引用。通常不需要该引用,因此仅在第一次使用该字段时或者 在请求非标准根时被赋值,在 nameidata 中保存一个引用可以确保在整个路径行走过程中 只有一个根有效,即使它与 chroot() 系统调用有竞争。

The root is needed when either of two conditions holds: (1) either the pathname or a symbolic link starts with a "'/'", or (2) a ".." component is being handled, since ".." from the root must always stay at the root. The value used is usually the current root directory of the calling process. An alternate root can be provided as when sysctl() calls file_open_root(), and when NFSv4 or Btrfs call mount_subtree(). In each case a pathname is being looked up in a very specific part of the filesystem, and the lookup must not be allowed to escape that subtree. It works a bit like a local chroot().

当遇到以下情况时需要使用 root 字段: (1)路径名或符号链接以 “/” 开始; (2)当前处理的是 “..”; 使用的值通常是调用进程的当前根目录。可以提供一个替代的 root,如 sysctl() 调用 file_open_root(),当 NFSv4Btrfs 调用 mount_subtree()时。在每个案例中, 都可以在文件系统的一个非常特定的部分中查找路径名,并且不允许查找操作从该子树中逃脱。 它工作有点像本地的chroot()。

Ignoring the handling of symbolic links, we can now describe the "link_path_walk()" function, which handles the lookup of everything except the final component as:

忽略符号链接的处理,我们现在可以将 link_path_walk() 函数描述为,它处理路径中除了 最后组件之外其他部分的查找。

Given a path (name) and a nameidata structure (nd), check that the current directory has execute permission and then advance name over one component while updating last_type and last. If that was the final component, then return, otherwise call walk_component() and repeat from the top.

给定一个路径 (name)和 nameidata结构(nd),检查当前目录是否具有执行权限, 然后在更新 last_typelast 时把 name 指向下一个组件。如果这是最后一个组件 则返回(此时 name 指向 \0),否则调用 walk_component() 并从顶部重复。

walk_component() is even easier. If the component is LAST_DOTS, it calls handle_dots() which does the necessary locking as already described. If it finds a LAST_NORM component it first calls "lookup_fast()" which only looks in the dcache, but will ask the filesystem to revalidate the result if it is that sort of filesystem. If that doesn't get a good result, it calls "lookup_slow()" which takes the i_mutex, rechecks the cache, and then asks the filesystem to find a definitive answer. Each of these will call follow_managed() (as described below) to handle any mount points.

walk_component() 甚至更简单。如果组件是 LAST_DOTS,它将调用 handle_dots(), 如前所述,handle_dots() 执行必要的锁定。如果它找到 LAST_NORM 组件,它首先调用 lookup_fast(),后者只在 dcache 中查找,对于某些文件系统(比如:网络文件系统) 它会要求文件系统重新验证结果。如果没有得到好的结果,它调用 lookup_slow(),后者接受 i_mutex,重新检查缓存,然后要求文件系统找到一个确定的答案。每个函数都将调用 follow_managed() (如下所述)来处理任何挂载点。

In the absence of symbolic links, walk_component() creates a new struct path containing a counted reference to the new dentry and a reference to the new vfsmount which is only counted if it is different from the previous vfsmount. It then calls path_to_nameidata() to install the new struct path in the struct nameidata and drop the unneeded references.

在没有符号链接的情况下,walk_component() 创建一个新的 struct path,其中包含一个对 新 dentry 的计数引用和一个对新 vfsmount 的引用,这个引用只有在与前一个 vfsmount 不同时才会被计数。然后调用 path_to_nameidata() 使用这个新的 struct path 更新 struct nameidate 中的 path 字段并删除不需要的引用。

This "hand-over-hand" sequencing of getting a reference to the new dentry before dropping the reference to the previous dentry may seem obvious, but is worth pointing out so that we will recognize its analogue in the "RCU-walk" version.

在删除对以前 dentry 的引用之前,先获取对新 dentry 的引用的这种 “hand-over-hand” 顺序可能看起来很明显,但是值得指出,以便我们能够在 “RCU-walk” 版本中识别它的类似物。

Handling the final component.

link_path_walk() only walks as far as setting nd->last and nd->last_type to refer to the final component of the path. It does not call walk_component() that last time. Handling that final component remains for the caller to sort out. Those callers are path_lookupat(), path_parentat(), path_mountpoint() and path_openat() each of which handles the differing requirements of different system calls.

link_path_walk() 只执行到设置 nd->lastnd->last_type 以引用路径的最后一个组件 为止。所以它最后不会调用 walk_component()。处理最后一个组件的工作留给调用者来处理。这些 调用者是 path_lookupat()path_parentat()path_mountpoint()path_openat(), 它们各自处理不同系统调用的不同需求。

path_parentat() is clearly the simplest - it just wraps a little bit of housekeeping around link_path_walk() and returns the parent directory and final component to the caller. The caller will be either aiming to create a name (via filename_create()) or remove or rename a name (in which case user_path_parent() is used). They will use i_mutex to exclude other changes while they validate and then perform their operation.

path_parentat() 显然是最简单的;它只是对 link_path_walk() 进行了一些整理,并将父目录 和最终组件返回给调用者。调用者的目标要么是创建一个名称(通过 filename_create()),要么是 删除或重命名一个名称(在这种情况下使用 user_path_parent())。在验证和执行操作时,它们将 使用 i_mutex 来保证线程安全。

path_lookupat() is nearly as simple - it is used when an existing object is wanted such as by stat() or chmod(). It essentially just calls walk_component() on the final component through a call to lookup_last(). path_lookupat() returns just the final dentry.

path_lookupat() 几乎同样简单; 当需要一个现有的对象被使用它时(如 stat()chmod() 需要使用该对象)。它实际上只是通过调用 lookup_last() 在最后一个组件上调用 walk_component()path_lookupat() 只返回最后一个 dentry

path_mountpoint() handles the special case of unmounting which must not try to revalidate the mounted filesystem. It effectively contains, through a call to mountpoint_last(), an alternate implementation of lookup_slow() which skips that step. This is important when unmounting a filesystem that is inaccessible, such as one provided by a dead NFS server.

path_mountpoint() 处理卸载的特殊情况,它不能尝试重新验证已挂载的文件系统。 它通过调用 mountpoint_last() 有效地包含了 lookup_slow() 的另一个实现,该实现 跳过了这一步。当卸载无法访问的文件系统时,这一点非常重要,比如该文件系统由已死机的 NFS 服务器提供的。

Finally path_openat() is used for the open() system call; it contains, in support functions starting with "do_last()", all the complexity needed to handle the different subtleties of O_CREAT (with or without O_EXCL), final "/" characters, and trailing symbolic links. We will revisit this in the final part of this series, which focuses on those symbolic links. "do_last()" will sometimes, but not always, take i_mutex, depending on what it finds.

最后,将 path_openat() 用于 open() 系统调用;在以 do_last() 开头的支持函数中, 它包含了处理 O_CREAT(有或没有 O_EXCL)的不同细微之处所需的所有复杂性、最后的 “/” 字符和尾随符号链接。在本系列的最后一部分中,我们将重新讨论这个问题,重点是这些符号链接。 do_last() 有时会(但不总是)接受 i_mutex,这取决于它找到了什么。

Each of these, or the functions which call them, need to be alert to the possibility that the final component is not LAST_NORM. If the goal of the lookup is to create something, then any value for last_type other than LAST_NORM will result in an error. For example if path_parentat() reports LAST_DOTDOT, then the caller won't try to create that name. They also check for trailing slashes by testing last.name[last.len]. If there is any character beyond the final component, it must be a trailing slash.

其中的每一个,或者调用它们的函数,都需要警惕最终组件不是 LAST_NORM 的可能性。如果查找 的目标是创建一些东西,那么 last_type (LAST_NORM 除外)的任何值都会导致错误。例如, 如果 path_parentat() 报告 LAST_DOTDOT,那么调用者将不会尝试创建该名称。它们还通过 测试 last.name[last.len]来检查尾随斜杠。如果在最后一个组件之外还有任何字符,那么它必须 是一个尾反斜杠。

Revalidation and automounts

Apart from symbolic links, there are only two parts of the "REF-walk" process not yet covered. One is the handling of stale cache entries and the other is automounts.

除了符号链接之外,“REF-walk” 过程只有两部分尚未涉及。一个是处理旧的缓存条目, 另一个是自动加载。

On filesystems that require it, the lookup routines will call the ->d_revalidate() dentry method to ensure that the cached information is current. This will often confirm validity or update a few details from a server. In some cases it may find that there has been change further up the path and that something that was thought to be valid previously isn't really. When this happens the lookup of the whole path is aborted and retried with the "LOOKUP_REVAL" flag set. This forces revalidation to be more thorough. We will see more details of this retry process in the next article.

在需要它的文件系统上,查找例程将调用 dentry->d_revalidate() 方法,以确保缓存 的信息不是过期的。这通常会从服务器确认有效性或更新一些细节。在某些情况下,它可能会发现在 这条路径上已经有了进一步的改变,而之前被认为是有效的东西可能并不是当前的真实状态。当这种 情况发生时,整个路径的查找将中止,设置 LOOKUP_REVAL 标志并重试。这将迫使重新验证更加 彻底。在下一篇文章中,我们将看到这个重试过程的更多细节。

Automount points are locations in the filesystem where an attempt to lookup a name can trigger changes to how that lookup should be handled, in particular by mounting a filesystem there. These are covered in greater detail in autofs4.txt in the Linux documentation tree, but a few notes specifically related to path lookup are in order here.

自动安装点是文件系统中的一些位置,在这些位置上,尝试查找一个名称可以触发对当前查找的特殊 处理,特别是通过将文件系统挂载在那里。在 Linux 文档树中的 autofs4.txt 中 有更详细的介绍,但是这里介绍一些与路径查找相关的说明。

The Linux VFS has a concept of "managed" dentries which is reflected in function names such as "follow_managed()". There are three potentially interesting things about these dentries corresponding to three different flags that might be set in dentry->d_flags:

Linux VFS 有一个 managed dentries 的概念,它反映在名字为: follow_managed() 等函数中。这些 dentry 有三个潜在的有趣之处,对应于 dentry—>d_flags 可能设置为三个 不同的标志值。

“DCACHE_MANAGE_TRANSIT”

If this flag has been set, then the filesystem has requested that the d_manage() dentry operation be called before handling any possible mount point. This can perform two particular services:

如果设置了这个标志,那么文件系统就要求在处理任何可能的挂载点之前执行 dentryd_manage() 操作。这可以执行两个特定的服务:

It can block to avoid races. If an automount point is being unmounted, the d_manage() function will usually wait for that process to complete before letting the new lookup proceed and possibly trigger a new automount.

它可以阻塞以避免竞争。如果卸载了一个自动挂载点,d_manage() 函数通常会等待该进程完成, 然后继续执行新的查找,并可能触发一个新的自动挂载。

It can selectively allow only some processes to transit through a mount point. When a server process is managing automounts, it may need to access a directory without triggering normal automount processing. That server process can identify itself to the autofs filesystem, which will then give it a special pass through d_manage() by returning -EISDIR.

它可以选择性地只允许某些进程通过挂载点。当服务器进程管理自动挂载时,它可能需要访问一个目录 而不触发正常的自动挂载处理。该服务器进程可以将自己标识为 autofs 文件系统,然后 d_manage() 通过返回 -EISDIR 给它一个特殊的通过(不会阻塞)。

“DCACHE_MOUNTED”

This flag is set on every dentry that is mounted on. As Linux supports multiple filesystem namespaces, it is possible that the dentry may not be mounted on in this namespace, just in some other. So this flag is seen as a hint, not a promise.

每个挂载点的 dentry 会设置该标志。由于 Linux 支持多个文件系统名称空间,所以 dentry 可能不会挂载在这个名称空间中,而是挂载在其他名称空间中。所以这个标志被看作是 一个暗示,而不是一个承诺。

If this flag is set, and d_manage() didn't return -EISDIR, lookup_mnt() is called to examine the mount hash table (honoring the mount_lock described earlier) and possibly return a new vfsmount and a new dentry (both with counted references).

如果设置了这个标志,并且 d_manage() 没有返回 -EISDIR,则调用 lookup_mnt() 来 检查挂载散列表(遵守前面描述的 mount_lock),并可能返回一个新的 vfsmount 和一个新 的 dentry (两者都有已计数的引用)。

“DCACHE_NEED_AUTOMOUNT”

If d_manage() allowed us to get this far, and lookup_mnt() didn't find a mount point, then this flag causes the d_automount() dentry operation to be called.

如果 d_manage() 允许我们走到这一步,而 lookup_mnt() 没有找到挂载点,那么这个标志 将导致调用 dentryd_automount() 操作。

The d_automount() operation can be arbitrarily complex and may communicate with server processes etc. but it should ultimately either report that there was an error, that there was nothing to mount, or should provide an updated struct path with new dentry and vfsmount.

d_automount() 操作可以是任意复杂的,也可以与服务器进程通信等等,但是它最终应该报告 要么是一个错误,要么就是没有什么需要挂载的,或者应该提供带有新的 dentryvfsmount 已更新的 struct path

In the latter case, finish_automount() will be called to safely install the new mount point into the mount table.

在后一种情况下,将调用 finish_automount() 将新的挂载点安全地更新到挂载表中。

There is no new locking of import here and it is important that no locks (only counted references) are held over this processing due to the very real possibility of extended delays. This will become more important next time when we examine RCU-walk which is particularly sensitive to delays.

这里没有新的导入锁,重要的是在这个处理过程中没有锁(只有被计数的引用)被持有, 因为很有可能会有额外的延迟。这将在下次我们研究RCU-walk时变得更加重要,它对延迟 特别敏感。

RCU-walk - faster pathname lookup in Linux

==========================================

RCU-walk is another algorithm for performing pathname lookup in Linux. It is in many ways similar to REF-walk and the two share quite a bit of code. The significant difference in RCU-walk is how it allows for the possibility of concurrent access.

RCU-walk 是一种在 Linux 中执行路径名查找的算法。它在很多方面与我们上次见过的 REF-walk 相似,并且两者共享相当多的代码。RCU-walk 的显著区别在于它允许并发访问的可能性。

We noted that REF-walk is complex because there are numerous details and special cases.RCU-walk reduces this complexity by simply refusing to handle a number of cases -- it instead falls back to REF-walk. The difficulty with RCU-walk comes from a different direction: unfamiliarity. The locking rules when depending on RCU are quite different from traditional locking, so we will spend a little extra time when we come to those.

我们注意到 REF-walk 之所以复杂是因为它需要考虑很多细节以及特殊情况。 RCU-walk 模式之所以减少了复杂度,是因为很多情况它不会去处理,而是直接回退到 REF-walk 模式,在 REF-walk 模式中处理这些情况。RCU-walk 的难度来自于锁的陌生规则。 RCU 锁的规则跟传统锁的不太一样。所以我们会额外花一些时间来解释。

Clear demarcation of roles

The easiest way to manage concurrency is to forcibly stop any other thread from changing the data structures that a given thread is looking at. In cases where no other thread would even think of changing the data and lots of different threads want to read at the same time, this can be very costly.
Even when using locks that permit multiple concurrent readers, the simple act of updating the count of the number of current readers can impose an unwanted cost. So the goal when reading a shared data structure that no other process is changing is to avoid writing anything to memory at all. Take no locks, increment no counts, leave no footprints.

管理并发性最简单的方法是强制停止任何其他线程更改给定线程正在查看的数据结构。 如果没有其他线程考虑修改数据,而有许多不同的线程希望同时读取数据,那么这可能会非常昂贵。 即使使用允许多个并发读取器的锁,更新当前读取器数量的简单操作也会带来不必要的开销。 因此,当读取没有其他进程更改的共享数据结构时,我们的目标是完全避免将任何内容写入内存。 不带锁,不增加计数,不留下脚印。

The REF-walk mechanism already described certainly doesn't follow this principle, but then it is really designed to work when there may well be other threads modifying the data. RCU-walk, in contrast, is designed for the common situation where there are lots of frequent readers and only occasional writers. This may not be common in all parts of the filesystem tree, but in many parts it will be. For the other parts it is important that RCU-walk can quickly fall back to using REF-walk.

前面描述的 REF-walk 机制当然不遵循这一原则,但它确实是为在可能有其他线程修改数据时工作 而设计的。相反,RCU-walk是为常见的情况而设计的,在这种情况下,有很多频繁的读者,只有 偶尔的作者。这在文件系统树的所有部分中可能并不常见,但在许多部分中却会很常见。 对于其他部分,重要的是 RCU-walk 可以快速地回到使用 REF-walk

Pathname lookup always starts in RCU-walk mode but only remains there as long as what it is looking for is in the cache and is stable. It dances lightly down the cached filesystem image, leaving no footprints and carefully watching where it is, to be sure it doesn't trip. If it notices that something has changed or is changing, or if something isn't in the cache, then it tries to stop gracefully and switch to REF-walk.

路径名查找总是在 RCU-walk 模式下启动,但是只要它要查找的对象在缓存中并且是稳定的, 那么路径名查找就始终保持在 RCU-walk 模式下。 它轻快地沿着缓存的文件系统映像移动,没有留下任何足迹,并仔细地监视它的位置, 以确保它不会被绊倒。如果它注意到某些内容已经更改或正在更改,或者缓存中没有这些内容, 那么它将尝试优雅地停止并切换到 REF-walk

This stopping requires getting a counted reference on the current vfsmount and dentry,and ensuring that these are still valid that a path walk with REF-walk would have found the same entries.This is an invariant that RCU-walk must guarantee. It can only make decisions, such as selecting the next step, that are decisions which REF-walk could also have made if it were walking down the tree at the same time. If the graceful stop succeeds, the rest ofthe path is processed with the reliable, if slightly sluggish, REF-walk. If RCU-walk finds it cannot stop gracefully, it simply gives up and restarts from the top with REF-walk.

这个停止动作需要获取当前 vfsmountdentry 的计数引用,并且确保这些引用对使用 REF-walk 模式进行路径查找仍然有效,并将找到相同的条目。这是一个 RCU-walk 必须保证的 不变式。它只能做出决定,比如选择下一步,REF-walk 也可以做出这些决定(也就是切换到 REF-walk 模式后进行的下一步跟切换前 RCU-walk 模式选择的下一步相同)。如果这个停止操作 成功了,剩下的路就会用可靠的,即使有点缓慢的 REF-walk 模式来处理。如果 RCU-walk 发现 它不能优雅地停止,它就会放弃,然后使用 REF-walk 从头开始。

This pattern of "try RCU-walk, if that fails try REF-walk" can be clearly seen in functions like filename_lookup(), filename_parentat(), filename_mountpoint(), do_filp_open(),and do_file_open_root(). These five correspond roughly to the four path_* functions we met last time, each of which calls link_path_walk().
The path_* functions are called using different mode flags until a mode is found which works. They are first called with LOOKUP_RCU set to request "RCU-walk".
If that fails with the error ECHILD they are called again with no special flag to request "REF-walk". If either of those report the error ESTALE a final attempt is made with LOOKUP_REVAL set (and no LOOKUP_RCU) to ensure that entries found in the cache are forcibly revalidated normally entries are only revalidated if the filesystem determines that they are too old to trust.

filename_lookup()filename_parentat()filename_mountpoint()do_filp_open()do_file_open_root() 等函数中可以清楚地看到这种“尝试 RCU-walk,如果失败,则尝试 REF-walk 的模式。这五个函数大致对应于我们上次遇到的四个 path_*函数,每个函数都调用 link_path_walk()。使用不同的 mode 标志调用 path_* 函数,直到找到一个可以工作的 模式为止。首次调用它们时,设置 LOOKUP_RCU 标志来请求 “RCU-walk”。 如果失败(错误码为 ECHILD),则尝试不带标志的 “REF-walk”。 如果其中一个报告错误 ESTALE,则使用带 LOOKUP_REVAL 标志(没有 LOOKUP_RCU) 进行最后一次尝试,以确保强制重新验证缓存中找到的条目。通常,只有当文件系统确定这些条目 太旧而不能信任时,才会重新验证这些条目。

The LOOKUP_RCU attempt may drop that flag internally and switch to REF-walk, but will never then try to switch back to RCU-walk. Places that trip up RCU-walk are much more likely to be near the leaves and so it is very unlikely that there will be much, if any, benefit from switching back.

LOOKUP_RCU 尝试可能会在内部删除该标志并切换到 REF-walk 模式,但永远不会尝试切换回 RCU-walk 模式。在 RCU-walk 模式上绊倒的地方更有可能是在树叶附近,因此,如果有的话, 从返回中(这里指返回到 RCU-walk 模式)获益不大。

RCU and seqlocks: fast and light

RCU is, unsurprisingly, critical to RCU-walk mode. The rcu_read_lock() is held for the entire time that RCU-walk is walking down a path. The particular guarantee it provides is that the key data structures - dentries, inodes, super_blocks, and mounts - will not be freed while the lock is held. They might be unlinked or invalidated in one way or another, but the memory will not be repurposed so values in various fields will still be meaningful. This is the only guarantee that RCU provides; everything else is done using seqlocks.

毫无疑问,RCURCU-walk 模式至关重要。 rcu_read_lock()RCU-walk 沿着路径行走的整个过程中一直被持有。 (也就是在整个过程中会保持锁)它提供的特殊保证是,当锁被持有时,关键数据结构: dentriesinodesuper_blocksmount 等描述符不会被释放。它们(这些描述符) 可能以某种方式被取消链接或失效,但是内存不会被重新使用,因此各个字段中的值仍然有意义。 这是 RCU 提供的唯一保证;其他所有操作都是使用 seqlocks 完成的。

As we saw last time, REF-walk holds a counted reference to the current dentry and the current vfsmount, and does not release those references before taking references to the "next" dentry or vfsmount. It also sometimes takes the d_lock spinlock. These references and locks are taken to prevent certain changes from happening. RCU-walk must not take those references or locks and so cannot prevent such changes. Instead, it checks to see if a change has been made, and aborts or retries if it has.

正如我们上次看到的,REF-walk 持有当前 dentryvfsmount 描述符的计数引用, 并且在引用 “下一个” dentryvfsmount 之前不会释放这些引用。 它有时也使用 d_lock 自旋锁。 这些引用和锁用于防止发生某些更改。 RCU-walk 不能接受这些引用或锁,因此不能阻止此类更改。 相反,它检查是否进行了更改,如果进行了更改,则中止或重试。

总结起来 REF-walk 模式使用一系列的锁来防止其他线程修改当前线程正在访问的数据,而 RCU-walk 模式则不会使用锁来进行防止,而是先尝试访问数据,如果在访问完数据后,通过 检查发现数据有发生改变,那么 就终止当前的操作或者进行重试。

To preserve the invariant mentioned above (that RCU-walk may only make decisions that REF-walk could have made), it must make the checks at or near the same places that REF-walk holds the references. So, when REF-walk increments a reference count or takes a spinlock, RCU-walk samples the status of a seqlock using read_seqcount_begin() or a similar function. When REF-walk decrements the count or drops the lock, RCU-walk checks if the sampled status is still valid using read_seqcount_retry() or similar.

为了保持上面提到的不变式(RCU-walk 可能只做 REF-walk 可以做的决定),它必须在 REF-walk 保存引用的相同位置或附近进行检查。因此,当 REF-walk 增加引用计数或采用自旋锁时, RCU-walk 使用 read_seqcount_begin() 或类似的函数对 seqlock 的状态进行采样。 当 REF-walk 减少计数或删除锁时,RCU-walk 使用 read_seqcount_retry() 或类似方法检查采样 状态是否仍然有效。 上面一段话的意思就是,RCU-walk 在进行操作之前会通过 read_seqcount_begin() 函数来获取 一个初始状态(一般来说就是一个初始 int 值),然后在操作完之后,再使用 read_seqcount_retry() 来检测初始状态有没发生变化,如果发生变化(int 值改变了)那就就进行重试或者终止。

However, there is a little bit more to seqlocks than that. If RCU-walk accesses two different fields in a seqlock-protected structure, or accesses the same field twice, there is no a-priori guarantee of any consistency between those accesses. When consistency is needed which it usually is RCU-walk must take a copy and then use read_seqcount_retry() to validate that copy.

然而,seqlock 还有更多的功能。 如果 RCU-walk 访问 seqlock-protected 结构中的两个不同字段,或者访问同一个字段两次, 那么就不能预先保证这些访问之间的一致性。当需要一致性时,通常做法:RCU-walk 必须 获取一个副本,然后使用 read_seqcount_retry() 验证该副本。

read_seqcount_retry() not only checks the sequence number, but also imposes a memory barrier so that no memory-read instruction from before the call can be delayed until after the call, either by the CPU or by the compiler. A simple example of this can be seen in slow_dentry_cmp() which, for filesystems which do not use simple byte-wise name equality, calls into the filesystem to compare a name against a dentry.

read_seqcount_retry() 不仅检查序列号,还设置了一个内存屏障,这样 CPU 或编译器都不会将 调用之前的内存读取指令延迟到调用之后。一个简单的例子可以在 slow_dentry_cmp() 中看到, 对于不是简单地按字节来比较名称的文件系统中,该函数可以用来比较 dentry 的名称。

The length and name pointer are copied into local variables, then read_seqcount_retry() is called to confirm the two are consistent, and only then is ->d_compare() called. When standard filename comparison is used, dentry_cmp() is called instead. Notably it does not use read_seqcount_retry(), but instead has a large comment explaining why the consistency guarantee isn't necessary. A subsequent read_seqcount_retry() will be sufficient to catch any problem that could occur at this point.

将长度和名称指针复制到本地变量中,调用 read_seqcount_retry() 来确认这两个指针(名称和长度) 的一致性,然后才调用 ->d_compare()。如果是使用标准文件名比较的情况,将调用 dentry_cmp()。 值得注意的是,它(这里指的是 dentry_cmp 函数)没有使用 read_seqcount_retry(),而是用一个 大注释解释为什么没有必要保证一致性。后续的 read_seqcount_retry() 将足以捕获此时可能发生的任何问题。

这里我们可以看到一个很好代码风格,对于同步问题,这里不交给 d_compare() 去考虑,也就是文件系统 设计者不用去考虑,这样能提高开发效率以及安全性。

With that little refresher on seqlocks out of the way we can look at the bigger picture of how RCU-walk uses seqlocks.

通过这个关于 seqlocks 的小复习,我们可以看到 RCU-walk 如何使用 seqlocks 的更大的图景。

这里我结合代码来理解下:

static noinline enum slow_d_compare slow_dentry_cmp(
		const struct dentry *parent,
		struct dentry *dentry,
		unsigned int seq,
		const struct qstr *name)
{
	int tlen = dentry->d_name.len;
	const char* tname = dentry->d_name.name;

	if (read_seqcount_retry(&dentry->d_seq, seq)) {
		cpu_relax();
		return D_COMP_SEQRETRY;
	}
	if (parent->d_op->d_compare(parent, dentry, tlen, tname, name))
		return D_COMP_NOMATCH;
	return D_COMP_OK;
}

 seq = raw_seqcount_begin(&dentry->d_seq);
 slow_dentry_cmp(parent, dentry, seq, name)

看到最后两行,我们先使用 raw_seqcount_begin()函数来获取一个初始状态 (一个初始的 int 值)seq。然后传递给 slow_dentry_cmp()函数。接下来我们看 slow_dentry_cmp() 函数,首先把 dentry 的名字以及长度保存到本地变量 tlentname,接着调用 read_seqcount_retry() 函数。这里要说的是上面 提到的是 read_seqcount_retry() 函数的第一个作用,在调用之前会插入一个 读内存屏障,也就是 smp_rmb(); 其中 smp 表明是多处理器系统(有多个 CPU) 因为现代 CPU 采用的是指令流水线设计,而 read_seqcount_retry()函数的调用与 前面的两条本地赋值指令没有依赖关系,所以 CPU 就可能会出现“顺序流入,乱序流出”的情况, 同样编译器优化也有可能造成指令的重排序。如果上面例子中出现了重排序,那么在 dentry 改变后 才进行赋值,那么就无法进行一致性检验,因此此时的检验已经无用了,会误以为修改后的 dentry 依然有效。read_seqcount_retry()第二个作用就是检验在使用 dentry 期间,有没有其他线程 在对其进行修改。(此时 dentry 就是在内存中一个数据表现,所谓的检测就是检查是否有没有 对该段内存做修改。)如果有(返回 1)那么就直接返回,否则调用 d_compare() 进行实际比较。

“mount_lock” and “nd->m_seq”

We already met the mount_lock seqlock when REF-walk used it to ensure that crossing a mount point is performed safely.
RCU-walk uses it for that too, but for quite a bit more.

前面提到过 REF-walk 使用 mount_lock seqlock 以确保安全地通过挂载点。 RCU-walk 也用它来实现这一点,但它的作用要大得多。

Instead of taking a counted reference to each vfsmount as it descends the tree, RCU-walk samples the state of mount_lock at the start of the walk and stores this initial sequence number in the struct nameidata in the m_seq field.

RCU-walk 没有在下降树的时候(内存中目录结构以树的形式进行组织,这里指的 是从树的根节点向叶节点遍历的过程)对每个 vfsmount 进行计数引用,而是在 该遍历开始时对 mount_lock 的状态进行采样,并将这个初始序列号存储 在 nameidata 结构中的 m_seq 字段中。

This one lock and one sequence number are used to validate all accesses to all vfsmounts, and all mount point crossings. As changes to the mount table are relatively rare, it is reasonable to fall back on REF-walk any time that any "mount" or "unmount" happens.

此一个锁(mout_lock)和一个序列号(m_seq)用于验证对所有 vfsmounts 和 所有挂载点交叉的所有访问,由于对挂载表的更改相对较少,所以在任何“挂载”或“卸载”发生时 都可以回退到 REF-walk

m_seq is checked (using read_seqretry()) at the end of an RCU-walk sequence, whether switching to REF-walk for the rest of the path or when the end of the path is reached. It is also checked when stepping down over a mount point (in __follow_mount_rcu()) or up (in follow_dotdot_rcu()). If it is ever found to have changed, the whole RCU-walk sequence is aborted and the path is processed again by REF-walk.

m_seq 在一个 RCU-walk 序列的末尾被检查(使用 read_seqretry()),无论是 在路径的其余部分切换到 REF-walk,还是在到达路径的末尾时。 同样在下行(follow_mount_rcu() 中--进入挂载点)或上行(在 follow_dotdot_rcu() 中, 也就是返回父目录,一般是遇到 ".." 的情况下调用)遇到挂载点时,也会检查它。 如果发现它发生了更改,则终止整个 RCU-walk 序列,并通过 REF-walk 再次处理该路径。

If RCU-walk finds that mount_lock hasn't changed then it can be sure that, had REF-walk taken counted references on each vfsmount, the results would have been the same. 如果 RCU-walk 发现 mount_lock 没有改变,那么可以肯定, 如果采用 对每个 vfsmount 获取计数引用的 REF-walk 方式进行。那么结果是一样。

在虚拟语气的 if 从句中,若有过去完成时助动词 had,或表 “万一” 的 should 或是 were 出现时,可将这三个词提前,将 if 省略。 Had he done it(if he had done it),he would have felt sorry. 如果他当时做了这件事,他会后悔的

This ensures the invariant holds, at least for vfsmount structures. 这确保了不变式的有效性,至少对于 vfsmount 结构是这样。

“dentry->d_seq” and “nd->seq”.

In place of taking a count or lock on d_reflock, RCU-walk samples the per-dentry d_seq seqlock, and stores the sequence number in the seq field of the nameidata structure, so nd->seq should always be the current sequence number of nd->dentry. This number needs to be revalidated after copying, and before using, the name, parent, or inode of the dentry.

RCU-walk 没有对 d_reflock 进行计数或锁定,而是对对应的 dentryd_seq seqlock 进行采样,并将序列号存储在 nameidata 结构的 seq 字段中,因此 nd->seq 应该始终是 nd->dentry 的当前序列号。在复制这些内容(nameparent 或者 dentry 的索引节点) 之后以及使用之前,需要重新验证这个数字。

The handling of the name we have already looked at, and the parent is only accessed in follow_dotdot_rcu() which fairly trivially follows the required pattern, though it does so for three different cases.

我们已经看到了对名称的处理,父类只在 follow_dotdot_rcu() 中访问,它非常简单地遵循了 所需的模式,尽管它在三种不同的情况下都是这样做的。

When not at a mount point, d_parent is followed and its d_seq is collected. When we are at a mount point, we instead follow the mnt->mnt_mountpoint link to get a new dentry and collect its d_seq. Then, after finally finding a d_parent to follow, we must check if we have landed on a mount point and, if so, must find that mount point and follow the mnt->mnt_root link. This would imply a somewhat unusual, but certainly possible, circumstance where the starting point of the path lookup was in part of the filesystem that was mounted on, and so not visible from the root.

当不在挂载点时,跟随 d_parent 并收集它的 d_seq。 当我们在一个挂载点时,我们按照 mnt->mnt_mountpoint 链接获取一个新的 dentry 并收集 它的 d_seq。然后,在最终找到要跟踪的 d_parent 之后,我们必须检查是否已经到达了挂载点, 如果是,则必须找到该挂载点并遵循 mnt->mnt_root 链接。这将意味着一种不太常见但肯定是 可能的情况,即路径查找的起点位于安装在其上的文件系统的一部分,因此从根目录中是不可见的。

The inode pointer, stored in ->d_inode, is a little more interesting. The inode will always need to be accessed at least twice, once to determine if it is NULL and once to verify access permissions. Symlink handling requires a validated inode pointer too. Rather than revalidating on each access, a copy is made on the first access and it is stored in the inode field of nameidata from where it can be safely accessed without further validation.

存储在 ->d_inode 字段中的 inode 指针更有趣一些。inode 始终需要至少访问两次,一次用于 确定是否为空,一次用于验证访问权限。符号链接处理也需要经过验证的 inode 指针。与其在 每次访问时都进行重新验证,不如在第一次访问时进行复制,并将其存储在 nameidatainode 字段中,在不进行进一步验证的情况下可以安全地访问它。

lookup_fast() is the only lookup routine that is used in RCU-mode, lookup_slow() being too slow and requiring locks. It is in lookup_fast() that we find the important "hand over hand" tracking of the current dentry.

lookup_fast() 是惟一在 RCU 模式下使用的查找例程, lookup_slow() 太慢,需要锁。在 lookup_fast() 中, 我们发现了对当前 dentry 的重要 “hand over hand” 跟踪。

The current dentry and current seq number are passed to __d_lookup_rcu() which, on success, returns a new dentry and a new seq number. lookup_fast() then copies the inode pointer and revalidates the new seq number. It then validates the old dentry with the old seq number one last time and only then continues. This process of getting the seq number of the new dentry and then checking the seq number of the old exactly mirrors the process of getting a counted reference to the new dentry before dropping that for the old dentry which we saw in REF-walk.

当前 dentry 和当前 seq 号被传递给 _d_lookup_rcu(),如果成功,它将返回一个新的 dentry 和一个新的 seq 号。然后,lookup_fast() 复制 inode 指针并重新验证新的 seq 号。然后最后 一次用旧的 seq 号验证旧的 dentry,然后继续。这个过程获取新 dentryseq 号,然后检查 旧 dentryseq 号,这恰好反映了我们在 REF-walk 中看到的流程:在删除旧 dentry 之前,需要先获取对新 dentry的计数引用。

这里旧的 dentry 指的是上面提到的当前 dentryseq,即保存在 nameidata 结构中的 seqpath.dentry

No “inode->i_mutex” or even “rename_lock”

A mutex is a fairly heavyweight lock that can only be taken when it is permissible to sleep. As rcu_read_lock() forbids sleeping, inode->i_mutex plays no role in RCU-walk. If some other thread does take i_mutex and modifies the directory in a way that RCU-walk needs to notice, the result will be either that RCU-walk fails to find the dentry that it is looking for, or it will find a dentry which read_seqretry() won't validate. In either case it will drop down to REF-walk mode which can take whatever locks are needed.

互斥锁是一种重量级的锁,只有在允许休眠的情况下才能使用。由于 rcu_read_lock() 禁止睡眠, 所以 inode->i_mutexRCU-walk 中不起作用。 如果其他线程确实使用 i_mutex 并且修改 RCU-walk 需要注意的某个目录, 那么结果将是要么 RCU-walk 已失败方式结束它正在寻找的 dentry, 要么它将找到一个没有 read_seqretry() 验证的 dentry。 在任何一种情况下,它将下降到 REF-walk 模式,可以采取任何锁需要。

Though rename_lock could be used by RCU-walk as it doesn't require any sleeping, RCU-walk doesn't bother. REF-walk uses rename_lock to protect against the possibility of hash chains in the dcache changing while they are being searched. This can result in failing to find something that actually is there. When RCU-walk fails to find something in the dentry cache, whether it is really there or not, it already drops down to REF-walk and tries again with appropriate locking. This neatly handles all cases, so adding extra checks on rename_lock would bring no significant value.

虽然 rename_lock 可以由 RCU-walk 使用,因为它不需要任何睡眠,但 RCU-walk 不需要。 REF-walk 使用 rename_lock 来防止在搜索 dcache 时哈希链发生变化。否则可能会导致找不到实际 在那的东西。(这里的意思:本来在某个哈希链表上可以找到的对象,由于发生了变化,对象移动到 其他链表上导致找不到)当 RCU-walkdentry 缓存中找不到某些东西时,不管它是否在 dentry 缓存中,它都已经下降到 REF-walk,并使用适当的锁定进行再次尝试。这基本很好地处理了所有的 情况,所以在 RCU 中添加对 rename_lock 额外的检查并没有多大意义。

“unlazy_walk()” and “complete_walk()”

That "dropping down to REF-walk" typically involves a call to unlazy_walk(), so named because "RCU-walk" is also sometimes referred to as "lazy walk". unlazy_walk() is called when following the path down to the current vfsmount/dentry pair seems to have proceeded successfully, but the next step is problematic. This can happen if the next name cannot be found in the dcache, if permission checking or name revalidation couldn't be achieved while the rcu_read_lock() is held (which forbids sleeping), if an automount point is found, or in a couple of cases involving symlinks. It is also called from complete_walk() when the lookup has reached the final component, or the very end of the path, depending on which particular flavor of lookup is used.

“回退到 REF-walk” 通常涉及到对函数 unlazy_walk() 的调用,之所以这样命名是因为 “RCU-walk” 有时也被称为 “lazy walk”。当跟踪到当前 vfsmount/dentry对的路径 似乎已经成功进行时,但是下一步出现问题时,就会调用 unlazy_walk()。比如以下情况: 1.在 dcache 中找不到下一个名称(就是路径下一个分量)时。 2.或者在持有 rcu_read_lock() 时不能实现权限检查或者名称重新验证(这禁止休眠)。 3.如果遇到自动挂载点。 4.涉及符号链接的一些情况下。 当查找到达最后一个组件或路径的末尾时,也会从 complete_walk() 调用它, 这取决于使用的是哪种查找风格(RCU-walk 或者 REF-walk 这两种方式)。

Other reasons for dropping out of RCU-walk that do not trigger a call to unlazy_walk() are when some inconsistency is found that cannot be handled immediately, such as mount_lock or one of the d_seq seqlocks reporting a change. In these cases the relevant function will return -ECHILD which will percolate up until it triggers a new attempt from the top using REF-walk.

在不会触发 unlazy_walk() 调用情况下退出 RCU-walk 的其他原因是:当发现一些不能 立即处理的不一致性问题时,例如 mount_lock 或某一个序列锁 d_seq 发生了改变。 在这些情况下,相关函数将返回 -ECHILD,它将一直渗透,直到使用 REF-walk 从顶部触发 一个新的尝试(这里指的是使用 REF-walk 模式从头开始查找路径)。

For those cases where unlazy_walk() is an option, it essentially takes a reference on each of the pointers that it holds (vfsmount, dentry, and possibly some symbolic links) and then verifies that the relevant seqlocks have not been changed. If there have been changes, it, too, aborts with -ECHILD, otherwise the transition to REF-walk has been a success and the lookup process continues.

对于 unlazy_walk() 是一个选项的情况,本质上是对它所持有的每个指针 (vfsmountdentry,可能还有一些符号链接)进行引用,然后验证相关的 seqlocks 是否没有被更改。如果有更改,它也会使用 -ECHILD 中止,否则成功地转换成 REF-walk 方式,查找过程将继续。

Taking a reference on those pointers is not quite as simple as just incrementing a counter. That works to take a second reference if you already have one (often indirectly through another object), but it isn't sufficient if you don't actually have a counted reference at all. For dentry->d_lockref, it is safe to increment the reference counter to get a reference unless it has been explicitly marked as "dead" which involves setting the counter to -128. lockref_get_not_dead() achieves this.

引用这些指针并不像增加计数器那么简单。如果您已经有了一个引用(通常通过另一个对象间接地), 那么可以使用第二个引用,但是如果您实际上根本没有一个已计数的引用,那么这样做是不够的。 对于 dentry->d_lockref,如果引用计数器没有被显式地标记为“死”(这涉及将计数器设置为**-128**), 那么增加引用计数器以获取引用是安全的。可以通过 lockref_get_not_dead() 实现(获得引用)。

For mnt->mnt_count it is safe to take a reference as long as mount_lock is then used to validate the reference. If that validation fails, it may not be safe to just drop that reference in the standard way of calling mnt_put() - an unmount may have progressed too far. So the code in legitimize_mnt(), when it finds that the reference it got might not be safe, checks the MNT_SYNC_UMOUNT flag to determine if a simple mnt_put() is correct, or if it should just decrement the count and pretend none of this ever happened.

对于 mnt->mnt_count,只要使用 mount_lock 来验证引用,就可以安全地使用引用。 如果验证失败,如果只是简单地调用 mnt_put() 标准方式来删除引用可能会不安全, 卸载可能进行得太过。因此,在 legitimize_mnt() 函数代码中:当发现它得到的引用 可能不安全时,它会检查 MNT_SYNC_UMOUNT 标志,以确定一个简单的 mnt_put() 是正确的,还是应该减少计数并假装这些都没有发生。

Taking care in filesystems

RCU-walk depends almost entirely on cached information and often will not call into the filesystem at all. However there are two places, besides the already-mentioned component-name comparison, where the file system might be included in RCU-walk, and it must know to be careful.

RCU-walk 几乎完全依赖于缓存的信息,而且通常根本不会调用文件系统。但是,除了 已经提到的组件名称比较之外,还有两个地方可能会将文件系统包含在 RCU-walk 中, 并且必须知道要小心。

If the filesystem has non-standard permission-checking requirements - such as a networked filesystem which may need to check with the server - the i_op->permission interface might be called during RCU-walk. In this case an extra "MAY_NOT_BLOCK" flag is passed so that it knows not to sleep, but to return -ECHILD if it cannot complete promptly. i_op->permission is given the inode pointer, not the dentry, so it doesn't need to worry about further consistency checks. However if it accesses any other filesystem data structures, it must ensure they are safe to be accessed with only the rcu_read_lock() held. This typically means they must be freed using kfree_rcu() or similar.

如果文件系统有非标准的权限检查需求,比如需要与服务器进行检查的网络文件系统, 则可能在 RCU-walk 期间调用 i_op->permission 接口。在这种情况下,会传递一个 额外的 “MAY_NOT_BLOCK” 标志,以便让它知道不能休眠,但如果不能立即完成, 则返回 -ECHILDi_op->permission 被赋予 inode 指针(这里指接收一个 inode 参数), 而不是 dentry,因此它不需要担心进一步的一致性检查。但是,如果它访问任何其他 文件系统数据结构,那么必须确保以持有 rcu_read_lock() 的方式安全地访问它们。 这通常意味着必须使用 kfree_rcu() 或类似的方法释放它们。

If the filesystem may need to revalidate dcache entries, then d_op->d_revalidate may be called in RCU-walk too. This interface is passed the dentry but does not have access to the inode or the seq number from the nameidata, so it needs to be extra careful when accessing fields in the dentry. This "extra care" typically involves using ACCESS_ONCE() or the newer READ_ONCE() to access fields, and verifying the result is not NULL before using it. This pattern can be see in nfs_lookup_revalidate().

如果文件系统可能需要重新验证 dcache 条目,那么也可以在 RCU-walk 中调用 d_op->d_revalidate。这个接口被传递给 dentry,但不能访问 inode 或来自 nameidataseq 号,因此在访问 dentry 中的字段时需要格外小心。这种额外的注意通常包括使用 ACCESS_ONCE() 或更新的 READ_ONCE() 访问字段,并在使用它之前验证结果是否为 NULL。这种模式可以在 nfs_lookup_revalidate() 中看到。

A pair of patterns

In various places in the details of REF-walk and RCU-walk, and also in the big picture, there are a couple of related patterns that are worth being aware of.

已经在很多地方的详细介绍了 REF-walkRCU-walk,同时纵观全局,有几个相关的模式是值得了解。

The first is "try quickly and check, if that fails try slowly". We can see that in the high-level approach of first trying RCU-walk and then trying REF-walk, and in places where unlazy_walk() is used to switch to REF-walk for the rest of the path. We also saw it earlier in dget_parent() when following a ".." link. It tries a quick way to get a reference, then falls back to taking locks if needed.

第一个是“尝试快速模式并检查,如果失败了,尝试慢速模式”。我们可以看到,在高级方法中, 首先尝试 RCU-walk,然后再尝试 REF-walk,在有些地方 unlazy_walk() 用于切换到 REF-walk以完成路径的其余部分。我们上次在 dget_parent() 中跟随“..”链接时也看到了它。 它尝试一种快速获取引用的方法,然后在需要时回退到获取锁的方式。

The second pattern is "try quickly and check, if that fails try again - repeatedly". This is seen with the use of rename_lock and mount_lock in REF-walk. RCU-walk doesn't make use of this pattern - if anything goes wrong it is much safer to just abort and try a more sedate approach.

第二种模式:“尝试快速模式并检查,如果失败,再试一次”。在 REF-walk 中使用 rename_lockmount_lock 可以看到这一点。RCU-walk 没有使用这种模式; 如果出了什么问题,直接中止并 尝试更稳定的方法会更安全。

The emphasis here is "try quickly and check". It should probably be "try quickly and carefully, then check". The fact that checking is needed is a reminder that the system is dynamic and only a limited number of things are safe at all. The most likely cause of errors in this whole process is assuming something is safe when in reality it isn't. Careful consideration of what exactly guarantees the safety of each access is sometimes necessary.

这里的重点是“快速尝试并检查”。应该是“快速仔细地尝试,然后检查”。需要进行检查的事实 提醒我们,系统是动态的,并且只有有限数量的东西是安全的。在整个过程中,最可能导致错误的 原因是,假设某样东西是安全的,而实际上它不是。有时需要仔细考虑到底是什么确保了每次访问的 安全性。

A walk among the symlinks

==========================================

There are several basic issues that we will examine to understand the handling of symbolic links: the symlink stack, together with cache lifetimes, will help us understand the overall recursive handling of symlinks and lead to the special care needed for the final component. Then a consideration of access-time updates and summary of the various flags controlling lookup will finish the story.

为了理解符号链接的处理,我们将研究几个基本问题:符号链接堆栈和缓存生存期将帮助我们理解 符号链接的整体递归处理,并为最终组件提供所需的特殊处理。 然后,考虑访问时的更新和控制查找的各种标志的摘要来完成本文。

The symlink stack

There are only two sorts of filesystem objects that can usefully appear in a path prior to the final component: directories and symlinks. Handling directories is quite straightforward: the new directory simply becomes the starting point at which to interpret the next component on the path. Handling symbolic links requires a bit more work.

只有两种文件系统对象可以有效地出现在最终组件之前的路径中:目录和符号链接。 处理目录非常简单:新目录只是成为从路径上获取下一个组件的起点。处理符号链接需要做更多的工作。

Conceptually, symbolic links could be handled by editing the path. If a component name refers to a symbolic link, then that component is replaced by the body of the link and, if that body starts with a '/', then all preceding parts of the path are discarded. This is what the "readlink -f" command does, though it also edits out "." and ".." components.

从概念上讲,符号链接可以通过编辑路径来处理。如果组件名引用符号链接,则该组件将被链接主体 (也就是符号链接指向的目标路径)替换,如果该主体以 '/' 开头,则将丢弃路径的所有前面部分。 这就是 “readlink -f” 命令所做的,尽管它也会编辑 “.” 和 “..” 组件。

Directly editing the path string is not really necessary when looking up a path, and discarding early components is pointless as they aren't looked at anyway. Keeping track of all remaining components is important, but they can of course be kept separately; there is no need to concatenate them. As one symlink may easily refer to another, which in turn can refer to a third, we may need to keep the remaining components of several paths, each to be processed when the preceding ones are completed. These path remnants are kept on a stack of limited size.

在查找路径时,实际上并不需要直接编辑路径字符串,丢弃早期组件是没有意义的,因为它们不会 被查看。跟踪所有剩余的组件很重要,但它们当然可以单独保存;没有必要把它们串联起来。由于 一个符号链接可以很容易地引用另一个符号链接,而另一个符号链接又可以引用第三个符号链接, 因此我们可能需要保留几个路径的其余组件,当前面的路径完成时,将对每个组件进行处理。 路径未完成的剩余部分被保存在有限大小的堆栈中。

There are two reasons for placing limits on how many symlinks can occur in a single path lookup. The most obvious is to avoid loops. If a symlink referred to itself either directly or through intermediaries, then following the symlink can never complete successfully - the error ELOOP must be returned. Loops can be detected without imposing limits, but limits are the simplest solution and, given the second reason for restriction, quite sufficient.

限制在单个路径查找中可以出现多少符号链接有两个原因。最明显的是避免循环。如果解析的符号链接 直接或间接地引用自己(指向本身),那么遵循符号链接的处理是永远无法成功完成,必须返回 错误 ELOOP。循环可以在不施加限制的情况下被检测到,但是限制是最简单的解决方案,并且, 考虑到限制的第二个原因,限制已经足够了。

The second reason was outlined recently by Linus:

Because it's a latency and DoS issue too. We need to react well to true loops, but also to "very deep" non-loops. It's not about memory use, it's about users triggering unreasonable CPU resources.

Linux imposes a limit on the length of any pathname: PATH_MAX, which is 4096. There are a number of reasons for this limit; not letting the kernel spend too much time on just one path is one of them. With symbolic links you can effectively generate much longer paths so some sort of limit is needed for the same reason. Linux imposes a limit of at most 40 symlinks in any one path lookup. It previously imposed a further limit of eight on the maximum depth of recursion, but that was raised to 40 when a separate stack was implemented, so there is now just the one limit.

Linux 对任何路径名的长度施加限制: PATH_MAX,即 4096。造成这种限制的原因有很多; 不让内核在一条路径上花费太多时间就是其中原因之一。使用符号链接,您可以有效地生成更长的 路径,因此出于同样的原因,需要某种限制。Linux 在任何一个路径查找中限制最多 40 个符号链接。 它以前只是对递归的最大深度(8)做了进一步的限制。(以前有两个限制,一个是递归深度, 一个是路径中允许出现符号链接的最大数量),但是当实现一个单独的堆栈时,这个限制 提高到了 40 (这里指的是递归深度,以前是 8),所以现在只有一个限制。

The nameidata structure that we met in an earlier article contains a small stack that can be used to store the remaining part of up to two symlinks. In many cases this will be sufficient. If it isn't, a separate stack is allocated with room for 40 symlinks. Pathname lookup will never exceed that stack as, once the 40th symlink is detected, an error is returned.

我们在前一篇文章中遇到的 nameidata 结构包含一个小堆栈,可用于存储最多两个符号链接的其余部分。 在许多情况下,这就足够了。如果不够用,则分配一个单独的堆栈,其中包含 40 个符号链接。路径名 查找永远不会超过该堆栈,因为一旦检测到第 40 个符号链接,就会返回一个错误。

It might seem that the name remnants are all that needs to be stored on this stack, but we need a bit more. To see that, we need to move on to cache lifetimes.

似乎这个堆栈中只需要存储路径中未解析部分的名称,但是我们还需要更多。为此,我们需要缓存生存期。

Storage and lifetime of cached symlinks

Like other filesystem resources, such as inodes and directory entries, symlinks are cached by Linux to avoid repeated costly access to external storage. It is particularly important for RCU-walk to be able to find and temporarily hold onto these cached entries, so that it doesn't need to drop down into REF-walk.

与其他文件系统资源(如 inode 和 目录项)一样,符号链接被 Linux 系统缓存,以避免对外部存储的 重复昂贵访问。对于 RCU-walk 来说,能够找到并暂时保存这些缓存的条目是特别重要的,这样它就 不需要下拉到 REF-walk 中。

While each filesystem is free to make its own choice, symlinks are typically stored in one of two places. Short symlinks are often stored directly in the inode. When a filesystem allocates a struct inode it typically allocates extra space to store private data (a common object-oriented design pattern in the kernel). This will sometimes include space for a symlink. The other common location is in the page cache, which normally stores the content of files. The pathname in a symlink can be seen as the content of that symlink and can easily be stored in the page cache just like file content.

虽然每个文件系统都可以自由地做出自己的选择,但是符号链接通常存储在两个地方之一。短符号链接 通常直接存储在 inode 中。当文件系统分配 inode 结构体时,它通常分配额外的空间来存储私有数据 (内核中常见的面向对象设计模式)。这有时包括了符号链接的空间。另一个常用位置在页面缓存中, 页面缓存通常存储文件的内容。符号链接中的路径名可以看作符号链接的内容,并且可以像文件内容 一样轻松地存储在页面缓存中。

When neither of these is suitable, the next most likely scenario is that the filesystem will allocate some temporary memory and copy or construct the symlink content into that memory whenever it is needed.

当这两种方法都不合适时,下一个最有可能的场景是文件系统将分配一些临时内存,并在需要时将 符号链接内容复制或构造到该内存中。

When the symlink is stored in the inode, it has the same lifetime as the inode which, itself, is protected by RCU or by a counted reference on the dentry. This means that the mechanisms that pathname lookup uses to access the dcache and icache (inode cache) safely are quite sufficient for accessing some cached symlinks safely. In these cases, the i_link pointer in the inode is set to point to wherever the symlink is stored and it can be accessed directly whenever needed.

当符号链接存储在 inode 中时,它的生存期与 inode 相同,后者本身由 RCUdentry 上的 计数引用保护。这意味着路径名查找过程中用于访问 dcacheicache (inode 缓存)的安全机制 已经足够用来安全地访问某些已缓存的符号链接。在这些情况下,inode 中的 i_link 指针被设置为 指向存储符号链接的位置,并且可以在需要时直接访问它。

When the symlink is stored in the page cache or elsewhere, the situation is not so straightforward. A reference on a dentry or even on an inode does not imply any reference on cached pages of that inode, and even an rcu_read_lock() is not sufficient to ensure that a page will not disappear. So for these symlinks the pathname lookup code needs to ask the filesystem to provide a stable reference and, significantly, needs to release that reference when it is finished with it.

当符号链接存储在页面缓存或其他地方时,情况就不那么简单了。dentry 甚至 inode 上的引用并 不意味着对缓存页面上该 inode 有引用,即使使用 rcu_read_lock() 也不足以确保页面不会消失。 因此,对于这些符号链接,路径名查找代码需要请求文件系统提供一个稳定的引用,而且重要的是, 需要在使用完该引用后释放该引用。

Taking a reference to a cache page is often possible even in RCU-walk mode. It does require making changes to memory, which is best avoided, but that isn't necessarily a big cost and it is better than dropping out of RCU-walk mode completely. Even filesystems that allocate space to copy the symlink into can use GFP_ATOMIC to often successfully allocate memory without the need to drop out of RCU-walk. If a filesystem cannot successfully get a reference in RCU-walk mode, it must return -ECHILD and unlazy_walk() will be called to return to REF-walk mode in which the filesystem is allowed to sleep.

即使在 RCU-walk 模式下,也常常会引用缓存页面。 它确实需要对内存进行更改,理论上最好避免这种修改,但这并不意味着一定需要很大的成本,而且它比 完全退出 RCU-walk 模式要好。即使是分配空间来复制符号链接的文件系统也可以使用 GFP_ATOMIC 成功地分配内存,而不需要退出 RCU-walk。如果文件系统不能成功地在 RCU-walk 模式下获得引用, 那么它必须返回 -ECHILD,并且 unlazy_walk() 将被调用,以回退到允许文件系统休眠的 REF-walk 模式。

The place for all this to happen is the i_op->follow_link() inode method. In the present mainline code this is never actually called in RCU-walk mode as the rewrite is not quite complete. It is likely that in a future release this method will be passed an inode pointer when called in RCU-walk mode so it both (1) knows to be careful, and (2) has the validated pointer. Much like the i_op->permission() method we looked at previously, ->follow_link() would need to be careful that all the data structures it references are safe to be accessed while holding no counted reference, only the RCU lock. Though getting a reference with ->follow_link() is not yet done in RCU-walk mode, the code is ready to release the reference when that does happen.

发生这一切的地方是 i_op->follow_link() inode 方法。在当前的主线代码中,由于重写还没有 完全完成,所以实际上从来没有在 RCU-walk 模式中调用这个函数。在将来的版本中,当以 RCU-walk 模式调用此方法时,很可能会向它传递一个 inode 指针,以便(1)知道要小心,(2)拥有经过验证的指针。 就像我们前面看到的 i_op->permission() 方法一样,->follow_link() 需要注意的是它引用的 所有数据结构都是安全的,可以在只有 RCU 锁,没有计数引用的情况下访问。虽然使用 ->follow_link() 获取引用还没有在 RCU-walk 模式中完成,但是代码已经准备好在这种情况 发生时释放引用。(后面这句话暂时没理解??)

This need to drop the reference to a symlink adds significant complexity. It requires a reference to the inode so that the i_op->put_link() inode operation can be called. In REF-walk, that reference is kept implicitly through a reference to the dentry, so keeping the struct path of the symlink is easiest. For RCU-walk, the pointer to the inode is kept separately. To allow switching from RCU-walk back to REF-walk in the middle of processing nested symlinks we also need the seq number for the dentry so we can confirm that switching back was safe.

这需要删除对符号链接的引用,这增加了极大的复杂性。它需要对 inode 的引用,以便可以调用 i_op->put_link() 操作。在 REF-walk 中,该引用通过对 dentry 的引用隐式地保持,因此 保持符号链接的 struct path 是最简单的。对于 RCU-walk,指向 inode 的指针是单独保存的。 为了允许在处理嵌套符号链接的过程中从 RCU-walk 切换回 REF-walk,我们还需要 dentryseq 号,以便确认切换过程是安全的。

Finally, when providing a reference to a symlink, the filesystem also provides an opaque "cookie" that must be passed to ->put_link() so that it knows what to free. This might be the allocated memory area, or a pointer to the struct page in the page cache, or something else completely. Only the filesystem knows what it is.

最后,当提供对符号链接的引用时,文件系统还提供了一个不透明的 cookie,必须将其传递给 ->put_link(),以便它知道释放什么。这可能是分配的内存区域,或者是指向页面缓存中的 struct page 的指针,或者完全是其他的东西。只有文件系统知道它是什么。

In order for the reference to each symlink to be dropped when the walk completes, whether in RCU-walk or REF-walk, the symlink stack needs to contain, along with the path remnants:

为了在遍历完成时删除对每个符号链接的引用,无论是在 RCU-walk 还是 REF-walk 中,符号链接 堆栈都需要包含路径剩余未解析的部分。

  • the struct path to provide a reference to the inode in REF-walk
  • the struct inode * to provide a reference to the inode in RCU-walk
  • the seq to allow the path to be safely switched from RCU-walk to REF-walk
  • the cookie that tells ->put_path() what to put.
  • struct pathREF-walk 模式下保持了对 inode 的引用。
  • struct inode *RCU-walk 模式下保持了对 inode 的引用。
  • seq 允许路径查找过程中可以安全地由 RCU-walk 模式切换到 REF-walk 模式。
  • cookie 告诉了 ->put_path() 需要释放什么。

This means that each entry in the symlink stack needs to hold five pointers and an integer instead of just one pointer (the path remnant). On a 64-bit system, this is about 40 bytes per entry; with 40 entries it adds up to 1600 bytes total, which is less than half a page. So it might seem like a lot, but is by no means excessive.

这意味着符号链接堆栈中的每个条目需要包含五个指针和一个整数,而不是只有一个指针 (路径中未解析部分的字符串)。在 64 位系统上,每个条目大约 40 个字节;40 个 条目加起来总共 1600 字节,不到半页。所以这看起来很多,但绝不是过度。

Note that, in a given stack frame, the path remnant (name) is not part of the symlink that the other fields refer to. It is the remnant to be followed once that symlink has been fully parsed. 注意,在给定的堆栈帧中,路径剩余部分(名称)不是其他字段引用的符号链接的一部分。 一旦符号链接被完全解析,剩余部分将被继续解析。

Following the symlink

The main loop in link_path_walk() iterates seamlessly over all components in the path and all of the non-final symlinks. As symlinks are processed, the name pointer is adjusted to point to a new symlink, or is restored from the stack, so that much of the loop doesn't need to notice. Getting this name variable on and off the stack is very straightforward; pushing and popping the references is a little more complex.

link_path_walk() 中的主循环无缝地遍历路径中的所有组件和所有非最终符号链接。当符号链接 被处理时,name 指针被调整为指向一个新的符号链接(当符号链接最后一个组件又是另一个符号 链接时),或者从堆栈中恢复,这样大部分循环就不需要注意了。在堆栈上和堆栈外获取 name 变量 非常简单; 入栈和弹出引用稍微复杂一些。

When a symlink is found, walk_component() returns the value 1 (0 is returned for any other sort of success, and a negative number is, as usual, an error indicator). This causes get_link() to be called; it then gets the link from the filesystem. Providing that operation is successful, the old path name is placed on the stack, and the new value is used as the name for a while. When the end of the path is found (i.e. *name is '\0') the old name is restored off the stack and path walking continues.

当找到符号链接时,walk_component() 返回值 1 (对于任何其他类型的成功,都返回0,通常, 负数指示一个错误)。这将调用 get_link();然后,它从文件系统获取链接。如果操作成功,则将 旧路径名 name 保存到堆栈上,并将新值暂时用作 name。当找到路径的末尾时(例如 *name = '\0' ), 旧的名称将从堆栈中恢复并继续执行路径遍历。

Pushing and popping the reference pointers (inode, cookie, etc.) is more complex in part because of the desire to handle tail recursion. When the last component of a symlink itself points to a symlink, we want to pop the symlink-just-completed off the stack before pushing the symlink-just-found to avoid leaving empty path remnants that would just get in the way.

推入和弹出引用指针(inodecookie 等)更加复杂,部分原因是希望处理尾部递归。当一个符号链接 的最后一个组件本身指向一个符号链接时,我们希望在推入刚刚发现的符号链接之前将刚刚完成的 符号链接从堆栈中取出,以避免留下只会碍事的空路径残余物。

It is most convenient to push the new symlink references onto the stack in walk_component() immediately when the symlink is found; walk_component() is also the last piece of code that needs to look at the old symlink as it walks that last component. So it is quite convenient for walk_component() to release the old symlink and pop the references just before pushing the reference information for the new symlink. It is guided in this by two flags; WALK_GET, which gives it permission to follow a symlink if it finds one, and WALK_PUT, which tells it to release the current symlink after it has been followed. WALK_PUT is tested first, leading to a call to put_link(). WALK_GET is tested subsequently (by should_follow_link()) leading to a call to pick_link() which sets up the stack frame.

当发现符号链接时,最方便的方法是立即将新的符号链接引用推入 walk_component() 中的堆栈; walk_component() 也是旧符号链接在遍历最后一个组件时需要查看的最后一段代码。 因此,可以在 walk_component() 中很方便地实现先释放旧符号链接并弹出引用后再为新符号链接 推入引用信息。它由两个 flag 引导;WALK_GETWALK_PUT 允许它在找到符号链接后释放当前 符号链接。首先测试 WALK_PUT,从而调用 put_link()。随后(通过 should_follow_link() ) 测试 WALK_GET,从而调用 pick_link(),后者设置堆栈帧。

Symlinks with no final component

A pair of special-case symlinks deserve a little further explanation. Both result in a new struct path (with mount and dentry) being set up in the nameidata, and result in get_link() returning NULL.

有一对符号链的接特殊情况值得进一步解释。两者都会在 nameidata 中创建一个新的 struct path (带有 moundentry ),并导致 get_link() 返回 NULL

The more obvious case is a symlink to "/". All symlinks starting with "/" are detected in get_link() which resets the nameidata to point to the effective filesystem root. If the symlink only contains "/" then there is nothing more to do, no components at all, so NULL is returned to indicate that the symlink can be released and the stack frame discarded.

比较明显的例子是指向 “/” 的符号链接。当 get_link() 检测到以 “/” 开头的符号链接时,它会 重置 nameidata 以指向有效的文件系统根。如果符号链接只包含 “/”,那么就没有什么要做的了, 根本没有组件,因此返回 NULL,表示可以释放符号链接并丢弃堆栈帧。

The other case involves things in /proc that look like symlinks but aren't really.

另一种情况就是某些涉及到 /proc 的东西,它行为看起来像符号链接,但其实不是。

$ ls -l /proc/self/fd/1

lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4

Every open file descriptor in any process is represented in /proc by something that looks like a symlink. It is really a reference to the target file, not just the name of it. When you readlink these objects you get a name that might refer to the same file - unless it has been unlinked or mounted over. When walk_component() follows one of these, the ->follow_link() method in "procfs" doesn't return a string name, but instead calls nd_jump_link() which updates the nameidata in place to point to that target. ->follow_link() then returns NULL. Again there is no final component and get_link() reports this by leaving the last_type field of nameidata as LAST_BIND.

在任何进程中,每个打开的文件描述符都用 /proc 中的符号链接表示。它实际上是对目标文件的引用, 而不仅仅是它的名称。当您读取这些对象时,您将得到一个可能引用相同文件的名称,除非该文件已被 解除链接或卸载。当 walk_component() 碰到这样的 /proc 符号链接时,“procfs” 中的 ->follow_link()方法不返回字符串名,而是调用 nd_jump_link(),后者更新适当的 nameidata 以指向该目标。->follow_link() 然后返回 NULL。同样,也没有最终的组件,get_link() 通过将 nameidatalast_type 字段设置为 LAST_BIND 来报告这一点。

Following the symlink in the final component

All this leads to link_path_walk() walking down every component, and following all symbolic links it finds, until it reaches the final component. This is just returned in the last field of nameidata. For some callers, this is all they need; they want to create that last name if it doesn't exist or give an error if it does. Other callers will want to follow a symlink if one is found, and possibly apply special handling to the last component of that symlink, rather than just the last component of the original file name. These callers potentially need to call link_path_walk() again and again on successive symlinks until one is found that doesn't point to another symlink.

所有这些导致 link_path_walk( ) 遍历每个组件,并跟踪它找到的所有符号链接,直到到达最后 一个组件。并通过 nameidata 结构中的 last 字段来返回。对于一些调用者来说,这就是它们 所需要的;如果 last 不存在,那么创建它;如果存在,则给出一个错误。如果找到符号链接, 其他某些调用者将希望跟踪该符号链接,并可能对该符号链接的最后一个组件应用特殊处理,而不仅仅 是原始文件名的最后一个组件。这些调用者可能需要对连续的符号链接一次又一次地调用 link_path_walk(), 直到找到一个不指向另一个符号链接的符号链接为止。 这里表达的意思是:当在 link_path_walk() 函数中发现链接时,有些该函数的调用者只是需要返回 找到的符号链接,而有些调用者则会一直跟踪最新找到的符号链接。这个是通过下文中 LOOKUP_FOLLOW 标志来控制的。

This case is handled by the relevant caller of link_path_walk(), such as path_lookupat() using a loop that calls link_path_walk(), and then handles the final component. If the final component is a symlink that needs to be followed, then trailing_symlink() is called to set things up properly and the loop repeats, calling link_path_walk() again. This could loop as many as 40 times if the last component of each symlink is another symlink.

这种情况由 link_path_walk() 的相关调用者 (如 path_lookupat() ) 处理,使用一个循环调用 link_path_walk(),然后处理最后一个组件。如果最后一个组件是一个需要跟踪的符号链接,那么就 调用 trailing_symlink( ) 来正确地设置内容,并重复这个循环,再次调用 link_path_walk()。 如果每个符号链接的最后一个组件是另一个符号链接,则可能会循环多达 40 次。上文中提到符号链接 的限制。

The various functions that examine the final component and possibly report that it is a symlink are lookup_last(), mountpoint_last() and do_last(), each of which use the same convention as walk_component() of returning 1 if a symlink was found that needs to be followed. Of these, do_last() is the most interesting as it is used for opening a file. Part of do_last() runs with i_mutex held and this part is in a separate function: lookup_open().

检查最终组件并可能报告它是符号链接的函数有: lookup_last()mountpoint_last()do_last(),它们都使用与 walk_component() 相同的约定,如果发现需要跟踪的符号链接时, 则返回1。其中,do_last() 最有趣,因为它用于打开文件。do_last() 的一部分在持有 i_mutex 的情况下运行,这一部分在一个单独的函数中: lookup_open()

Explaining do_last() completely is beyond the scope of this article, but a few highlights should help those interested in exploring the code.

对于 do_last() 的详解完全超出这篇文章的范畴了,但还是提一些有助于研究这部分代码的重点部分。

  1. Rather than just finding the target file, do_last() needs to open it. If the file was found in the dcache, then vfs_open() is used for this. If not, then lookup_open() will either call atomic_open() (if the filesystem provides it) to combine the final lookup with the open, or will perform the separate lookup_real() and vfs_create() steps directly. In the later case the actual "open" of this newly found or created file will be performed by vfs_open(), just as if the name were found in the dcache. do_last() 需要打开目标文件,而不仅仅是查找目标文件。如果在 dcache 中找到该文件,则使用 vfs_open()。如果没有,那么 lookup_open() 将调用 atomic_open() (如果文件系统提供了它) 来结合最后的查找和 open 操作,或者直接执行单独的 lookup_real()vfs_create() 步骤。 在后一种情况下,这个新发现的文件或者创建的文件实际 “打开” 操作将由 vfs_open() 执行, 就像在 dcache 中找到名称一样。

  2. vfs_open() can fail with -EOPENSTALE if the cached information wasn't quite current enough. Rather than restarting the lookup from the top with LOOKUP_REVAL set, lookup_open() is called instead, giving the filesystem a chance to resolve small inconsistencies. If that doesn't work, only then is the lookup restarted from the top. 如果缓存的信息不够及时(新鲜),vfs_open() 可能会使用 -EOPENSTALE 来返回失败。这时 不会直接设置 LOOKUP_REVAL 标志来从顶部重新启动查找,而是先调用 lookup_open() 让 文件系统有机会解决一些小的不一致。如果无法解决,才会从顶部重新开始查找。

  3. An open with O_CREAT does follow a symlink in the final component, unlike other creation system calls (like mkdir). So the sequence: 如果一个 open 操作带有 O_CREAT 标志,那么它会跟踪最后一个组件发现的符号链接, 与其他创建系统调用(比如 mkdir)不一样。所以下面的命令:

    ln -s bar /tmp/foo

    echo hello > /tmp/foo

    will create a file called /tmp/bar. This is not permitted if O_EXCL is set but otherwise is handled for an O_CREAT open much like for a non-creating open: should_follow_link() returns 1, and so does do_last() so that trailing_symlink() gets called and the open process continues on the symlink that was found.

    将创建一个名为 /tmp/bar 的文件。如果设置了 O_EXCL,这是不允许的,但是 O_CREAT open 的处理方法与非创建 open 的处理方法非常相似: should_follow_link() 返回 1, do_last() 也返回 1,因此调用 trailing_symlink(),然后打开进程继续在找到的符号链接 上运行。

Updating the access time

We previously said of RCU-walk that it would "take no locks, increment no counts, leave no footprints." We have since seen that some "footprints" can be needed when handling symlinks as a counted reference (or even a memory allocation) may be needed. But these footprints are best kept to a minimum.

我们之前说过 RCU-walk 不需要锁,不增加计数,不留下脚印”。我们已经看到,在处理符号链接 作为计数引用(甚至内存分配)时,可能需要一些 “足迹”。但最好将这些足迹控制在最低限度。

One other place where walking down a symlink can involve leaving footprints in a way that doesn't affect directories is in updating access times. In Unix (and Linux) every filesystem object has a "last accessed time", or "atime". Passing through a directory to access a file within is not considered to be an access for the purposes of atime; only listing the contents of a directory can update its atime. Symlinks are different it seems. Both reading a symlink (with readlink()) and looking up a symlink on the way to some other destination can update the atime on that symlink.

在其他地方,使用符号链接可能会以不影响目录的方式留下足迹,这就是更新访问时间。 在 Unix(和 Linux)中,每个文件系统对象都有一个 “最后访问时间” 或 atime。 通过目录访问文件不被视为具有访问 atime 的意图;只有列出目录的内容才能更新它的 atime。 符号链接看起来是不同的。无论是读取符号链接(使用 readlink()),还是在前往其他目的地的途中 查找符号链接,都可以更新该符号链接的 atime

It is not clear why this is the case; POSIX has little to say on the subject. The clearest statement is that, if a particular implementation updates a timestamp in a place not specified by POSIX, this must be documented "except that any changes caused by pathname resolution need not be documented". This seems to imply that POSIX doesn't really care about access-time updates during pathname lookup.

具体原因尚不清楚;POSIX 对这个问题没什么可说的。最清楚的说明是,如果某个特定的实现在 POSIX 没有指定的地方更新了时间戳,那么必须将其记录下来,“除非不需要记录由路径名解析引起的任何更改”。 这似乎意味着 POSIX 并不真正关心路径名查找期间的访问时更新。

An examination of history shows that prior to Linux 1.3.87, the ext2 filesystem, at least, didn't update atime when following a link. Unfortunately we have no record of why that behavior was changed.

回顾历史可以发现,在 Linux 1.3.87 之前,ext2 文件系统至少在跟踪链接时没有更新 atime。 不幸的是,我们没有记录为什么这种行为会发生改变。

In any case, access time must now be updated and that operation can be quite complex. Trying to stay in RCU-walk while doing it is best avoided. Fortunately it is often permitted to skip the atime update. Because atime updates cause performance problems in various areas, Linux supports the relatime mount option, which generally limits the updates of atime to once per day on files that aren't being changed (and symlinks never change once created). Even without relatime, many filesystems record atime with a one-second granularity, so only one update per second is required.

无论如何,现在必须更新访问时间,而且操作可能非常复杂。在做的时候,尽量避免在 “RCU-walk” 中停留。幸运的是,通常允许跳过 atime 更新。因为 atime 更新会在某些方面导致性能问题, 所以 Linux 支持 relatime 挂载选项,它通常将 atime 的更新限制为每天只更新一次未 更改的文件(并且符号链接一旦创建就不会更改)。即使没有 relatime,许多文件系统也以一秒的 粒度记录 atime,因此每秒只需要一次更新。

It is easy to test if an atime update is needed while in RCU-walk mode and, if it isn't, the update can be skipped and RCU-walk mode continues. Only when an atime update is actually required does the path walk drop down to REF-walk. All of this is handled in the get_link() function. 在 RCU-walk 模式下很容易测试是否需要 atime 更新,如果不需要,则可以跳过更新并继续 RCU-walk 模式。只有在实际需要 atime 更新时,路径查找才会回退到 REF-walk。所有 这些都在 get_link() 函数中处理。

A few flags

A suitable way to wrap up this tour of pathname walking is to list the various flags that can be stored in the nameidata to guide the lookup process. Many of these are only meaningful on the final component, others reflect the current state of the pathname lookup. And then there is LOOKUP_EMPTY, which doesn't fit conceptually with the others. If this is not set, an empty pathname causes an error very early on. If it is set, empty pathnames are not considered to be an error.

结束路径名遍历的一种合适方法是列出可以存储在 nameidata 中的各种标志,以指导查找过程。 其中许多只对最终组件有意义,其他 的则反映了路径名查找的当前状态。然后是 LOOKUP_EMPTY, 它在概念上不符合 其它 类别。如果没有设置此值,则空路径名会在早期导致错误。如果设置了 该标志,则不会将空路径名视为错误。

Global state flags

We have already met two global state flags: LOOKUP_RCU and LOOKUP_REVAL. These select between one of three overall approaches to lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.

我们已经遇到了两个全局状态标志:LOOKUP_RCULOOKUP_REVAL。这些选项在三种全面的 查找方法中进行选择:RCU-walkREF-walk 和 使用强制重新验证的 REF-walk

LOOKUP_PARENT indicates that the final component hasn't been reached yet. This is primarily used to tell the audit subsystem the full context of a particular access being audited.

LOOKUP_PARENT 表示尚未到达最终组件。这主要用于告诉 audit 子系统,当前特定访问的 完整上下文被 audit

LOOKUP_ROOT indicates that the root field in the nameidata was provided by the caller, so it shouldn't be released when it is no longer needed.

LOOKUP_ROOT 指出 nameidata 中的 root 字段是由调用者提供的,因此在不需要它时候 不应该释放它。

LOOKUP_JUMPED means that the current dentry was chosen not because it had the right name but for some other reason. This happens when following "..", following a symlink to /, crossing a mount point or accessing a "/proc/$PID/fd/$FD" symlink. In this case the filesystem has not been asked to revalidate the name (with d_revalidate()). In such cases the inode may still need to be revalidated, so d_op->d_weak_revalidate() is called if LOOKUP_JUMPED is set when the look completes - which may be at the final component or, when creating, unlinking, or renaming, at the penultimate component.

LOOKUP_JUMPED 意味着选择当前 dentry 不是因为它的名称正确,而是出于其他原因。当跟随 “..” 时就会发生这种情况。跟随一个符号链接查找到 “/”,通过挂载点时或访问 “/proc/PID/fd/ fd” 符号链接。在这种情况下,文件系统没有被要求重新验证 name (使用 d_revalidate())。然而 inode 可能仍然需要重新验证,因此,如果设置了 LOOKUP_JUMPED,那么当查找完成时(此时 可能位于最终组件,或者在创建、解除链接或重命名倒数第二个组件)函数 d_op->d_weak_revalidate() 会被调用。

Final-component flags

Some of these flags are only set when the final component is being considered. Others are only checked for when considering that final component.

其中一些标志仅在考虑最终组件时才设置。其他 标志只在考虑最后一个组件时才进行检查。

LOOKUP_AUTOMOUNT ensures that, if the final component is an automount point, then the mount is triggered. Some operations would trigger it anyway, but operations like stat() deliberately don't. statfs() needs to trigger the mount but otherwise behaves a lot like stat(), so it sets LOOKUP_AUTOMOUNT, as does "quotactl()" and the handling of "mount --bind".

LOOKUP_AUTOMOUNT 确保,如果最后一个组件是 automount 点,那么就触发挂载。有些操作 无论如何都会触发它,但是像 stat() 这样的操作故意不触发它。statfs() 需要触发挂载, 但其他方面的行为与 stat() 很相似,因此它设置了 LOOKUP_AUTOMOUNT, quotactl() 和 “mount --bind” 的处理也是如此。

LOOKUP_FOLLOW has a similar function to LOOKUP_AUTOMOUNT but for symlinks. Some system calls set or clear it implicitly, while others have API flags such as AT_SYMLINK_FOLLOW and UMOUNT_NOFOLLOW to control it. Its effect is similar to WALK_GET that we already met, but it is used in a different way.

LOOKUP_FOLLOW 有一个类似于 LOOKUP_AUTOMOUNT 的函数,但用于符号链接。一些系统调用 隐式地设置或清除它,而另一些则使用诸如 AT_SYMLINK_FOLLOWUMOUNT_NOFOLLOW 之类 的 API 标志来控制它。它的效果类似于我们已经见过的 WALK_GET,但是它的用法不同。

LOOKUP_DIRECTORY insists that the final component is a directory. Various callers set this and it is also set when the final component is found to be followed by a slash.

LOOKUP_DIRECTORY 坚持最后一个组件是一个目录。某些调用者都会设置这个值,同样当发现最后 一个组件后面有一个斜杠时,也会设置这个值。

Finally LOOKUP_OPEN, LOOKUP_CREATE, LOOKUP_EXCL, and LOOKUP_RENAME_TARGET are not used directly by the VFS but are made available to the filesystem and particularly the ->d_revalidate() method. A filesystem can choose not to bother revalidating too hard if it knows that it will be asked to open or create the file soon. These flags were previously useful for ->lookup() too but with the introduction of ->atomic_open() they are less relevant there.

最后,LOOKUP_OPENLOOKUP_CREATELOOKUP_EXCLLOOKUP_RENAME_TARGET不是 VFS 直接使用的,而是提供给文件系统,特别是 ->d_revalidate() 方法。如果文件系统知道 很快就会被要求打开或创建文件,那么它可以选择不费力地重新验证。这些标志以前对 ->lookup() 也很有用,但是随着 ->atomic_open() 的引入,它们在这里就不那么相关了。

End of the road

Despite its complexity, all this pathname lookup code appears to be in good shape - various parts are certainly easier to understand now than even a couple of releases ago. But that doesn't mean it is "finished". As already mentioned, RCU-walk currently only follows symlinks that are stored in the inode so, while it handles many ext4 symlinks, it doesn't help with NFS, XFS, or Btrfs. That support is not likely to be long delayed.

尽管它很复杂,但是所有这些路径名查找代码看起来都很好,现在各个部分都比几个版本之前更容易 理解。但这并不意味着它已经“完成”。如前所述,RCU-walk 目前只跟踪存储在 inode 中的 符号链接,因此,虽然它处理许多 ext4 符号链接,但它对 NFSXFSBtrfs没有帮助。 这种支持不太可能拖延太久。