Pathname lookup (路径名查找)【ChatGPT】

原文:https://www.kernel.org/doc/html/latest/filesystems/path-lookup.html

内核中文件系统相关的文档汇总:Filesystems in the Linux kernel

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

Written by Neil Brown with help from Al Viro and Jon Corbet. It has subsequently been updated to reflect changes in the kernel including:

  • per-directory parallel name lookup.
  • openat2() resolution restriction flags.

Introduction to pathname lookup

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 "*at()" system calls such as openat().

路径名(有时称为“文件名”)用于标识文件系统中的对象,对大多数读者来说应该很熟悉。它们包含两种类型的元素:“斜杠”,即一个或多个“/”字符的序列,以及“组件”,即一个或多个非“/”字符的序列。这形成了两种类型的路径。以斜杠开头的路径是“绝对路径”,从文件系统根目录开始。其他路径是“相对路径”,从当前目录开始,或者从通过类似于openat()的“*at()”系统调用给定的文件描述符指定的其他位置开始。

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 "*at()" 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中通常是禁止的,但是在Linux中的一些“*at()”系统调用中,当给定AT_EMPTY_PATH标志时,允许这种情况。例如,如果您在可执行文件上有一个打开的文件描述符,可以通过调用execveat()传递文件描述符、空路径和AT_EMPTY_PATH标志来执行它。

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 <slash> characters names an existing directory or a directory entry that is to be created for a directory immediately after the pathname is resolved.

只要路径名中至少包含一个非<slash>字符,并且以一个或多个尾部<slash>字符结尾,就不能成功解析该路径名,除非在尾部<slash>字符之前的最后一个路径名组件指定了一个现有目录或在路径名解析后立即创建一个目录的目录项。

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中)处理了所有这些问题:将路径分解为组件,将“其他所有内容”与最后一个组件分开处理,并检查在不允许的情况下是否使用了尾部斜杠。它还解决了并发访问的重要问题。

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/b”重命名为“a/c/b”,那个进程可能会成功解析为“a/c”。大多数竞争情况要复杂得多,路径名查找的任务的一个重要部分就是防止它们产生破坏性的影响。许多可能的竞争情况在“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指针可以为NULL,表示该名称在父目录中不存在。虽然目录的dentry可以与子目录的dentry存在链接,但该链接不用于路径名查找,因此在此不予考虑。

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.

在考虑"dcache"时,我们有另一个"两种类型"的区分:有两种类型的文件系统。

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"中的信息始终完全准确(尽管不一定完整)。这可以使虚拟文件系统(VFS)在不与文件系统进行检查的情况下确定特定文件是否存在,并意味着VFS可以保护文件系统免受某些竞争和其他问题的影响。这些通常是"本地"文件系统,如ext3、XFS和Btrfs。

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.

其他文件系统无法提供该保证,因为它们无法做到。这些通常是跨网络共享的文件系统,无论是像NFS和9P这样的远程文件系统,还是像ocfs2或cephfs这样的集群文件系统。这些文件系统允许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)时运行的地方,可以在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在锁和引用计数方面相对较重。虽然不像旧的“大内核锁”时代那样重,但在需要时肯定不会害怕使用锁。它使用了各种不同的并发控制机制。假定您具备对各种原语的背景了解,或者可以从其他地方(例如《遇见锁匠》)获取相关信息。

The locking mechanisms used by REF-walk include:

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原语来提供自旋锁和引用计数。这个原语的特殊之处在于,概念上的序列"锁定;增加引用计数;解锁"通常可以通过单个原子内存操作来完成。

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不会突然被释放并用于其他用途,因此各个字段中的值将按预期行为。它还在一定程度上保护了对inode的->d_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之间的关联是相当持久的。例如,当文件被重命名时,dentry和inode一起移动到新位置。当创建文件时,dentry最初将为负(即d_inode为NULL),并作为创建操作的一部分分配给新的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中的引用计数为1)时,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,并检查父节点和名称是否正确。因此,在搜索缓存时,它不会锁定父节点,只会锁定子节点。

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.

在给定的目录中查找给定名称涉及从两个值(名称和目录的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被重命名时,名称和父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是一个序列锁,每当重命名任何dentry时都会更新它。如果d_lookup发现在无法成功扫描哈希表中的链时发生了重命名,它只会再次尝试。

rename_lock is also used to detect and defend against potential attacks against LOOKUP_BENEATH and LOOKUP_IN_ROOT when resolving ".." (where the parent directory is moved outside the root, bypassing the path_equal() check). If rename_lock is updated during the lookup and the path encounters a "..", a potential attack occurred and handle_dots() will bail out with -EAGAIN.

rename_lock还用于检测和防御解析“..”时针对LOOKUP_BENEATH和LOOKUP_IN_ROOT的潜在攻击(其中父目录移动到根目录之外,绕过path_equal()检查)。如果在查找过程中更新了rename_lock并且路径遇到“..”,则发生了潜在攻击,handle_dots()将以-EAGAIN退出。

inode->i_rwsem

i_rwsem is a read/write semaphore 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 or, optionally, when the list of entries in a directory is being retrieved with readdir().

i_rwsem是一个读/写信号量,用于串行化对特定目录的所有更改。这确保了例如unlink()和rename()不能同时发生。它还在文件系统被要求查找当前不在dcache中的名称,或者在使用readdir()检索目录中的条目列表时,保持目录的稳定性。

This has a complementary role to that of d_lock: i_rwsem 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_rwsem 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_rwsem plays no role.

这与d_lock具有互补的作用:目录上的i_rwsem保护该目录中的所有名称,而名称上的d_lock仅保护目录中的一个名称。对dcache的大多数更改都会在相关目录索引节点上持有i_rwsem,并在更改发生时短暂地获取一个或多个dentry上的d_lock。一个例外是当空闲的dentry由于内存压力而从dcache中删除时。这使用d_lock,但i_rwsem不起作用。

The semaphore affects pathname lookup in two distinct ways. Firstly it prevents changes during 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 a shared lock on i_rwsem, 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_rwsem上获取一个共享锁,再次检查名称是否存在于缓存中,然后调用文件系统以获得确定的答案。无论结果如何,都将向缓存中添加一个新的dentry。

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

其次,当路径名查找到达最后一个组件时,有时需要在执行最后一次查找之前对i_rwsem进行独占锁定,以实现所需的排他性。路径查找选择是否获取i_rwsem的方式是后续部分中解决的问题之一。

If two threads attempt to look up the same name at the same time - a name that is not yet in the dcache - the shared lock on i_rwsem will not prevent them both adding new dentries with the same name. As this would result in confusion an extra level of interlocking is used, based around a secondary hash table (in_lookup_hashtable) and a per-dentry flag bit (DCACHE_PAR_LOOKUP).

如果两个线程同时尝试查找相同的尚未在dcache中的名称,则对i_rwsem的共享锁不会阻止它们都添加具有相同名称的新dentry。由于这会导致混乱,使用了额外的互锁级别,基于一个辅助哈希表(in_lookup_hashtable)和一个每个dentry的标志位(DCACHE_PAR_LOOKUP)。

To add a new dentry to the cache while only holding a shared lock on i_rwsem, a thread must call d_alloc_parallel(). This allocates a dentry, stores the required name and parent in it, checks if there is already a matching dentry in the primary or secondary hash tables, and if not, stores the newly allocated dentry in the secondary hash table, with DCACHE_PAR_LOOKUP set.

要在仅持有i_rwsem的共享锁的情况下向缓存中添加一个新的dentry,线程必须调用d_alloc_parallel()。这将分配一个dentry,将所需的名称和父目录存储在其中,检查主哈希表或辅助哈希表中是否已经存在匹配的dentry,如果没有,则将新分配的dentry存储在辅助哈希表中,并设置DCACHE_PAR_LOOKUP。

If a matching dentry was found in the primary hash table then that is returned and the caller can know that it lost a race with some other thread adding the entry. If no matching dentry is found in either cache, the newly allocated dentry is returned and the caller can detect this from the presence of DCACHE_PAR_LOOKUP. In this case it knows that it has won any race and now is responsible for asking the filesystem to perform the lookup and find the matching inode. When the lookup is complete, it must call d_lookup_done() which clears the flag and does some other house keeping, including removing the dentry from the secondary hash table - it will normally have been added to the primary hash table already. Note that a struct waitqueue_head is passed to d_alloc_parallel(), and d_lookup_done() must be called while this waitqueue_head is still in scope.

如果在主哈希表中找到了匹配的dentry,则返回该dentry,并且调用者可以知道它在与其他线程添加该条目的竞争中失败了。如果在任何缓存中都找不到匹配的dentry,则返回新分配的dentry,并且调用者可以通过DCACHE_PAR_LOOKUP的存在来检测到这一点。在这种情况下,它知道它赢得了任何竞争,现在负责要求文件系统执行查找并找到匹配的索引节点。完成查找后,必须调用d_lookup_done(),该函数清除标志并进行其他一些清理工作,包括从辅助哈希表中删除dentry - 它通常已经添加到主哈希表中。请注意,在调用d_alloc_parallel()时传递了一个struct waitqueue_head,并且必须在此waitqueue_head仍然在作用域内时调用d_lookup_done()。

If a matching dentry is found in the secondary hash table, d_alloc_parallel() has a little more work to do. It first waits for DCACHE_PAR_LOOKUP to be cleared, using a wait_queue that was passed to the instance of d_alloc_parallel() that won the race and that will be woken by the call to d_lookup_done(). It then checks to see if the dentry has now been added to the primary hash table. If it has, the dentry is returned and the caller just sees that it lost any race. If it hasn't been added to the primary hash table, the most likely explanation is that some other dentry was added instead using d_splice_alias(). In any case, d_alloc_parallel() repeats all the look ups from the start and will normally return something from the primary hash table.

如果在辅助哈希表中找到了匹配的dentry,d_alloc_parallel()需要做更多的工作。它首先等待DCACHE_PAR_LOOKUP被清除,使用传递给赢得竞争的d_alloc_parallel()实例的等待队列,并在调用d_lookup_done()时唤醒该队列。然后,它检查是否已将dentry添加到主哈希表中。如果已经添加到主哈希表中,则返回dentry,并且调用者只会看到它在任何竞争中失败。如果尚未将其添加到主哈希表中,则最有可能的解释是使用d_splice_alias()添加了其他某个dentry。无论如何,d_alloc_parallel()会从头开始重复所有查找,并且通常会从主哈希表中返回某个结果。

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_count是“mount”结构上的每个CPU的引用计数器。这里的每个CPU表示增加计数是廉价的,因为它只使用CPU本地内存,但是检查计数是否为零是昂贵的,因为它需要与每个CPU进行检查。通过mnt_count引用可以防止挂载结构在常规卸载操作的结果中消失,但不能防止“惰性”卸载。因此,持有mnt_count并不能确保挂载点保留在命名空间中,特别是不能稳定挂载点的链接。然而,它确保挂载数据结构保持一致,并提供对挂载文件系统的根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是一个全局的序列锁,有点像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.

在向下遍历树(远离根目录)时,当穿越一个挂载点时会使用该锁来检查穿越是否安全。也就是说,首先读取序列锁中的值,然后找到当前目录上挂载的挂载点(如果有的话),并增加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.

当通过跟随“..”链接向上遍历树(朝向根目录)时,需要更加小心。在这种情况下,序列锁(包含计数器和自旋锁)被完全锁定,以防止在向上步进时对任何挂载点进行更改。这种锁定是为了稳定与挂载的dentry之间的链接,而挂载本身的引用计数并不能确保这一点。

mount_lock is also used to detect and defend against potential attacks against LOOKUP_BENEATH and LOOKUP_IN_ROOT when resolving ".." (where the parent directory is moved outside the root, bypassing the path_equal() check). If mount_lock is updated during the lookup and the path encounters a "..", a potential attack occurred and handle_dots() will bail out with -EAGAIN.

mount_lock还用于检测和防御解析“..”时针对LOOKUP_BENEATH和LOOKUP_IN_ROOT的潜在攻击(其中父目录移动到根目录之外,绕过了path_equal()检查)。如果在查找过程中更新了mount_lock,并且路径遇到“..”,则发生了潜在攻击,handle_dots()将以-EAGAIN退出。

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.

最后,全局(但非常轻量级)的RCU读锁会不时地被持有,以确保某些数据结构不会意外释放。

In particular it is held while scanning chains in the dcache hash table, and the mount point hash table.

特别是在扫描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):

在走过路径的整个过程中,当前状态存储在一个名为nameidata的结构体中,"namei"是该函数的传统名称,它可以将一个"名称"转换为一个"inode",这个名称可以追溯到第一版的Unix。struct 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.

路径包含一个struct vfsmount(嵌入在struct mount中)和一个struct dentry。它们一起记录了路径的当前状态。它们最初指向起始点(当前工作目录、根目录或由文件描述符标识的其他目录),并在每一步更新。始终保持通过d_lockref和mnt_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.

这是一个字符串,加上一个长度(即非空终止符),它是路径名中的"下一个"组成部分。

int last_type

This is one of LAST_NORM, LAST_ROOT, LAST_DOT or LAST_DOTDOT. The last field is only valid if the type is LAST_NORM.

它可以是LAST_NORM、LAST_ROOT、LAST_DOT或LAST_DOTDOT中的一个。如果类型是LAST_NORM,则最后一个字段才有效。

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()系统调用同时进行。

It should be noted that in the case of LOOKUP_IN_ROOT or LOOKUP_BENEATH, the effective root becomes the directory file descriptor passed to openat2() (which exposes these LOOKUP_ flags).

需要注意的是,在LOOKUP_IN_ROOT或LOOKUP_BENEATH的情况下,有效根目录变为传递给openat2()的目录文件描述符(这暴露了这些LOOKUP_标志)。

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().

当满足以下两个条件之一时,需要使用根目录:(1)路径名或符号链接以“'/'”开头,或者(2)正在处理一个“..”组件,因为“..”从根目录开始必须始终保持在根目录。通常情况下,使用的值是调用进程的当前根目录。可以提供替代根目录,例如当sysctl()调用file_open_root()时,以及当NFSv4或Btrfs调用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.

给定一个路径(名称)和一个nameidata结构(nd),检查当前目录是否具有执行权限,然后将名称移动到下一个组件,同时更新last_type和last。如果这是最后一个组件,则返回,否则调用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 i_rwsem, rechecks the cache, and then asks the filesystem to find a definitive answer.

walk_component()更简单。如果组件是LAST_DOTS,它调用handle_dots()来执行先前描述的必要锁定操作。如果它找到一个LAST_NORM组件,首先调用“lookup_fast()”只在dcache中查找,但如果是这种类型的文件系统,它将要求文件系统重新验证结果。如果没有得到好的结果,它调用“lookup_slow()”,它获取i_rwsem,重新检查缓存,然后要求文件系统找到一个确定的答案。

As the last step of walk_component(), step_into() will be called either directly from walk_component() or from handle_dots(). It calls handle_mounts(), to check and handle mount points, in which a new struct path is created 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. Then if there is a symbolic link, step_into() calls pick_link() to deal with it, otherwise it installs the new struct path in the struct nameidata, and drops the unneeded references.

在walk_component()的最后一步,将直接从walk_component()或handle_dots()调用step_into()。它调用handle_mounts()来检查和处理挂载点,在此过程中创建一个新的struct path,其中包含对新的dentry的计数引用和对新的vfsmount的引用,只有在它与先前的vfsmount不同时才计数。然后,如果存在符号链接,step_into()调用pick_link()来处理它,否则将新的struct path安装在struct nameidata中,并丢弃不需要的引用。

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的引用的这种“逐个传递”的顺序可能显而易见,但值得指出的是,这样我们将能够在“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() and path_openat() each of which handles the differing requirements of different system calls.

link_path_walk()函数只会遍历到设置nd->last和nd->last_type以指向路径的最后一个组件。它不会在最后一次调用时调用walk_component()函数。处理最后一个组件的工作留给调用者来解决。这些调用者分别是path_lookupat()、path_parentat()和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_rwsem to exclude other changes while they validate and then perform their operation.

path_parentat()显然是最简单的 - 它只是在link_path_walk()周围包装了一点点的管理工作,并将父目录和最后一个组件返回给调用者。调用者可能是为了创建一个名称(通过filename_create())或者删除或重命名一个名称(在这种情况下使用user_path_parent())。他们将使用i_rwsem来排除其他更改,同时验证并执行他们的操作。

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. It is worth noting that when flag LOOKUP_MOUNTPOINT is set, path_lookupat() will unset LOOKUP_JUMPED in nameidata so that in the subsequent path traversal d_weak_revalidate() won't be called. This is important when unmounting a filesystem that is inaccessible, such as one provided by a dead NFS server.

path_lookupat()几乎同样简单 - 当需要一个现有对象(例如通过stat()或chmod())时使用它。它基本上只是通过调用lookup_last()在最后一个组件上调用walk_component()。path_lookupat()只返回最后的dentry。值得注意的是,当设置了LOOKUP_MOUNTPOINT标志时,path_lookupat()会在nameidata中取消LOOKUP_JUMPED,以便在后续的路径遍历中不会调用d_weak_revalidate()。这在卸载一个无法访问的文件系统时非常重要,比如由一个已经停止运行的NFS服务器提供的文件系统。

Finally path_openat() is used for the open() system call; it contains, in support functions starting with "open_last_lookups()", 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. "open_last_lookups()" will sometimes, but not always, take i_rwsem, depending on what it finds.

最后,path_openat()用于open()系统调用;它包含了以"open_last_lookups()"开头的支持函数,用于处理O_CREAT(带或不带O_EXCL)、最后的"/"字符和尾部符号链接的不同细节。我们将在本系列的最后一部分重新讨论这个问题,重点关注这些符号链接。"open_last_lookups()"有时会获取i_rwsem,但并不总是,这取决于它找到了什么。

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_NORM之外的任何last_type值都会导致错误。例如,如果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.

在需要的文件系统上,查找例程将调用->d_revalidate() dentry方法以确保缓存的信息是最新的。这通常会确认有效性或从服务器更新一些细节。在某些情况下,它可能会发现路径上方发生了变化,之前认为有效的某些内容实际上并非如此。当发生这种情况时,整个路径的查找将被中止,并使用“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 autofs - how it works in the Linux documentation tree, but a few notes specifically related to path lookup are in order here.

自动挂载点是文件系统中的位置,尝试查找名称可能会触发对如何处理该查找的更改,特别是通过在那里挂载文件系统。这些在Linux文档树中的autofs - how it works中有更详细的介绍,但在这里还有一些与路径查找相关的特定说明。

The Linux VFS has a concept of "managed" dentries. There are three potentially interesting things about these dentries corresponding to three different flags that might be set in dentry->d_flags:

Linux VFS具有“管理”的dentries的概念。与dentry->d_flags中可能设置的三个不同标志相对应,这些dentries可能有三个潜在的有趣之处。

  • 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:

如果设置了此标志,则文件系统在处理任何可能的挂载点之前会请求调用d_manage() dentry操作。这可以执行两个特定的服务:

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文件系统标识自己,然后通过返回-EISDIR来给予它特殊的通过d_manage()的权限。

  • 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()没有找到挂载点,则此标志会导致调用d_automount() dentry操作。

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()操作可以是任意复杂的,并且可能与服务器进程等进行通信,但最终应该报告错误、没有要挂载的内容,或者应该提供一个带有新的dentry和vfsmount的更新的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对延迟特别敏感。

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。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模式开始,但只要它正在查找的内容在缓存中并且是稳定的,它就会保持在该模式下。它轻盈地在缓存的文件系统映像中舞动,不留下任何痕迹,并仔细观察自己的位置,确保不会绊倒。如果它注意到有什么变化或正在发生变化,或者如果某些内容不在缓存中,那么它会尝试优雅地停止并切换到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 of the 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.

这种停止需要对当前的vfsmount和dentry进行计数引用,并确保它们仍然有效-使用REF-walk进行路径遍历将找到相同的条目。这是RCU-walk必须保证的不变条件。它只能做出决策,例如选择下一步,这些决策是REF-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(), do_filp_open(), and do_file_open_root(). These four correspond roughly to the three path_() functions we met earlier, 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.

"尝试RCU-walk,如果失败则尝试REF-walk"的这种模式可以在函数如filename_lookup()、filename_parentat()、do_filp_open()和do_file_open_root()中清楚地看到。这四个函数大致对应我们之前遇到的三个path_()函数,每个函数都调用link_path_walk()。path_()函数使用不同的模式标志调用,直到找到适用的模式为止。它们首先使用设置LOOKUP_RCU标志来请求"RCU-walk"。如果返回错误ECCHILD,则再次调用而不使用特殊标志来请求"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 and seqlocks: fast and light

RCU和序列锁:快速且轻量

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.
RCU(Read-Copy Update)对于RCU-walk模式至关重要,这并不奇怪。在RCU-walk遍历路径时,rcu_read_lock()会一直被持有。它提供的特定保证是,在持有锁的期间,关键数据结构(dentries、inodes、super_blocks和mounts)不会被释放。它们可能会以某种方式被取消链接或无效化,但是内存不会被重新分配,因此各个字段中的值仍然是有意义的。这是RCU提供的唯一保证;其他所有操作都是使用序列锁完成的。

As we saw above, 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会持有当前dentry和当前vfsmount的计数引用,并且在获取“下一个”dentry或vfsmount的引用之前不会释放这些引用。有时还会获取d_lock自旋锁。这些引用和锁是为了防止某些更改的发生。而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()或类似的函数对序列锁的状态进行采样。当REF-walk减少计数或释放锁时,RCU-walk会使用read_seqcount_retry()或类似的函数检查采样的状态是否仍然有效。

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.
然而,序列锁还有更多的内容。如果RCU-walk访问受序列锁保护的结构中的两个不同字段,或者两次访问相同的字段,那么在这些访问之间并没有任何一致性的先验保证。当需要一致性时(通常是需要的),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. 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()不仅会检查序列号,还会施加内存屏障,以确保在调用之前的任何内存读取指令都不会被延迟到调用之后,无论是由CPU还是编译器引起的。一个简单的例子可以在slow_dentry_cmp()中看到,对于不使用简单的逐字节名称相等的文件系统,它会调用文件系统来比较名称和dentry。长度和名称指针被复制到本地变量中,然后调用read_seqcount_retry()来确认两者是一致的,然后才调用->d_compare()。当使用标准文件名比较时,会调用dentry_cmp()。值得注意的是,它不使用read_seqcount_retry(),而是有一个很长的注释解释为什么不需要一致性保证。随后的read_seqcount_retry()将足以捕获此时可能发生的任何问题。

With that little refresher on seqlocks out of the way we can look at the bigger picture of how RCU-walk uses seqlocks.
有了对序列锁的这点温习,我们可以看看RCU-walk如何使用序列锁的更大图景。

mount_lock and nd->m_seq

挂载锁和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.
我们已经遇到了mount_lock序列锁,当REF-walk使用它来确保安全地跨越挂载点时。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. 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.
RCU-walk在下降树时不是对每个vfsmount获取计数引用,而是在遍历开始时对mount_lock的状态进行采样,并将初始序列号存储在struct nameidata的m_seq字段中。这一个锁和一个序列号被用来验证对所有vfsmount的所有访问以及所有挂载点的所有访问。由于挂载表的更改相对较少,所以每当发生“挂载”或“卸载”时,回退到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.
在RCU-walk序列的结束时(无论是切换到REF-walk继续路径还是到达路径的末尾),都会检查m_seq(使用read_seqretry())。在跨越挂载点(在__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. This ensures the invariant holds, at least for vfsmount structures.
如果RCU-walk发现mount_lock没有改变,那么可以确信,如果REF-walk对每个vfsmount都获取了计数引用,结果也会是一样的。这至少确保了不变式对于vfsmount结构是成立的。

dentry->d_seq and nd->seq

dentry->d_seq和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获取计数或锁,而是对每个dentry的d_seq序列锁进行采样,并将序列号存储在nameidata结构的seq字段中,因此nd->seq应该始终是nd->dentry的当前序列号。在复制名称、父项或inode之后,需要重新验证该数字。

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,一次是为了确定它是否为NULL,一次是为了验证访问权限。符号链接处理也需要一个经过验证的inode指针。与其在每次访问时重新验证,不如在第一次访问时进行复制,并将其存储在nameidata的inode字段中,从那里可以安全地访问而无需进一步验证。

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的重要的“手到手”跟踪。

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和当前序列号被传递给__d_lookup_rcu(),成功时返回一个新的dentry和一个新的序列号。然后lookup_fast()会复制inode指针并重新验证新的序列号。然后它最后一次验证旧的dentry和旧的序列号,然后才继续。获取新dentry的序列号然后检查旧的序列号的过程,与我们在REF-walk中看到的获取新dentry的计数引用然后放弃旧dentry的计数引用的过程完全一致。

No inode->i_rwsem or even rename_lock

没有inode->i_rwsem或者rename_lock

A semaphore is a fairly heavyweight lock that can only be taken when it is permissible to sleep. As rcu_read_lock() forbids sleeping, inode->i_rwsem plays no role in RCU-walk. If some other thread does take i_rwsem 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_rwsem在RCU-walk中不起作用。如果其他线程获取了i_rwsem并以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-walk在dentry缓存中找不到某个内容时,无论它是否实际存在,它已经降级为REF-walk,并使用适当的锁再次尝试。这样可以很好地处理所有情况,因此在rename_lock上添加额外的检查不会带来重大价值。

unlazy walk() and complete_walk()

unlazy_walk()和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()。如果在持有rcu_read_lock()(禁止睡眠)的情况下无法完成权限检查或名称重新验证,或者找到了一个自动挂载点,或者涉及符号链接的一些情况,就会发生这种情况。当查找到达最后一个组件或路径的最后时,complete_walk()也会调用unlazy_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 seqlock报告了更改。在这些情况下,相关函数将返回-ECHILD,该错误代码将上升,直到从顶部触发使用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()可选的情况,它基本上会对其持有的每个指针(vfsmount、dentry和可能的符号链接)进行引用,然后验证相关的序列锁是否已更改。如果有更改,它也会中止并返回-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,可以安全地增加引用计数以获取引用,除非它已被显式标记为"dead",这涉及将计数器设置为-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"标志,以便它知道不要睡眠,而是在无法迅速完成时返回-ECHILD。i_op->permission接收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 READ_ONCE() to access fields, and verifying the result is not NULL before using it. This pattern can be seen in nfs_lookup_revalidate().
如果文件系统可能需要重新验证dcache条目,则d_op->d_revalidate也可能在RCU-walk中被调用。此接口接收dentry,但无法访问inode或nameidata的序列号,因此在访问dentry中的字段时需要特别小心。这种"额外小心"通常涉及使用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-walk和RCU-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_lock和mount_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.
我们将研究几个基本问题,以了解符号链接的处理方式:符号链接堆栈以及缓存生命周期将帮助我们了解符号链接的递归处理方式,并导致对最后一个组件需要特别小心的处理。然后,我们将考虑访问时间更新和总结控制查找的各种标志,以完成整个过程。

符号链接堆栈

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:
第二个原因是最近由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.
因为这也是延迟和DoS问题。我们需要对真正的循环和"非常深"的非循环做出良好的反应。这与内存使用无关,而是与用户触发不合理的CPU资源有关。

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 (MAXSYMLINKS) 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(MAXSYMLINKS)。以前还对递归的最大深度施加了额外的限制,但是当实现了一个单独的堆栈时,将该限制提高到40,因此现在只有一个限制。

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.
看起来好像只需要在这个堆栈上存储路径剩余部分,但我们需要更多的东西。为了看清楚这一点,我们需要继续讨论缓存的生命周期。

缓存的符号链接的存储和生命周期

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中。当文件系统分配一个struct 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相同,而inode本身受到RCU或dentry的计数引用保护。这意味着路径名查找用于访问dcache和icache(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->get_link() inode method. This is called both in RCU-walk and REF-walk. In RCU-walk the dentry* argument is NULL, ->get_link() can return -ECHILD to drop out of RCU-walk. Much like the i_op->permission() method we looked at previously, ->get_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. A callback struct delayed_called will be passed to ->get_link(): file systems can set their own put_link function and argument through set_delayed_call(). Later on, when VFS wants to put link, it will call do_delayed_call() to invoke that callback function with the argument.
所有这些操作发生的地方是i_op->get_link() inode方法。它在RCU-walk和REF-walk中都会被调用。在RCU-walk中,dentry*参数为NULL,->get_link()可以返回-ECHILD以退出RCU-walk。就像我们之前看到的i_op->permission()方法一样,->get_link()需要小心,确保在不持有计数引用的情况下访问的所有数据结构都是安全的,只需RCU锁。一个回调结构delayed_called将被传递给->get_link():文件系统可以通过set_delayed_call()设置自己的put_link函数和参数。稍后,当VFS想要放置链接时,它将调用do_delayed_call()来使用该回调函数和参数调用它。

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 previous path
    结构体路径(struct path):提供对先前路径的引用

  • the const char * to provide a reference to the to previous name
    常量字符指针(const char *):提供对先前名称的引用

  • the seq to allow the path to be safely switched from RCU-walk to REF-walk
    序列(seq):允许路径在RCU-walk和REF-walk之间安全切换

  • the struct delayed_call for later invocation.
    延迟调用结构体(struct delayed_call):用于稍后调用

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.
需要注意的是,在给定的堆栈帧中,路径剩余部分(名称)并不是其他字段所指的符号链接的一部分。它是一旦完全解析了该符号链接,就要跟随的剩余部分。

跟随符号链接

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()中的主循环无缝地迭代路径中的所有组件和所有非最终符号链接。随着符号链接的处理,名称指针被调整为指向新的符号链接,或者从堆栈中恢复,因此大部分循环不需要注意。将名称变量推入和弹出堆栈非常简单;推送和弹出引用稍微复杂一些。

When a symlink is found, walk_component() calls pick_link() via step_into() which returns 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()通过step_into()调用pick_link(),后者从文件系统返回链接。只要该操作成功,旧路径名将被放入堆栈,新值将被用作名称一段时间。当找到路径的末尾(即*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.
推送和弹出引用指针(inode、cookie等)更复杂,部分原因是出于处理尾递归的愿望。当符号链接的最后一个组件本身指向一个符号链接时,我们希望在推送新发现的符号链接之前,将刚完成的符号链接从堆栈中弹出,以避免留下空的路径剩余部分,这只会妨碍操作。

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 three flags: WALK_NOFOLLOW which forbids it from following a symlink if it finds one, WALK_MORE which indicates that it is yet too early to release the current symlink, and WALK_TRAILING which indicates that it is on the final component of the lookup, so we will check userspace flag LOOKUP_FOLLOW to decide whether follow it when it is a symlink and call may_follow_link() to check if we have privilege to follow it.
在walk_component()中立即在发现符号链接时将新的符号链接引用推入堆栈是最方便的;walk_component()也是在遍历最后一个组件时需要查看旧符号链接的最后一段代码。因此,walk_component()在推送新符号链接的引用信息之前,释放旧符号链接并弹出引用是非常方便的。它受到三个标志的指导:WALK_NOFOLLOW禁止在发现符号链接时跟随它,WALK_MORE表示现在释放当前符号链接还为时过早,WALK_TRAILING表示正在查找的是查找的最后一个组件,因此我们将检查用户空间标志LOOKUP_FOLLOW来决定是否在它是符号链接时跟随它,并调用may_follow_link()来检查我们是否有权限跟随它。

没有最终组件的符号链接

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 pick_link() returning NULL.
有两种特殊情况的符号链接需要进一步解释。这两种情况都会导致在nameidata中设置一个新的struct path(带有挂载和dentry),并导致pick_link()返回NULL。

The more obvious case is a symlink to "/". All symlinks starting with "/" are detected in pick_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.
更明显的情况是符号链接指向“/”。在pick_link()中检测到所有以“/”开头的符号链接,它会将nameidata重置为指向有效的文件系统根目录。如果符号链接只包含“/”,那么就没有更多的事情要做了,根本没有组件,因此返回NULL表示可以释放符号链接并丢弃堆栈帧。

The other case involves things in /proc that look like symlinks but aren't really (and are therefore commonly referred to as "magic-links"):
另一种情况涉及/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 ->get_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. ->get_link() then returns NULL. Again there is no final component and pick_link() returns NULL.
任何进程中的每个打开文件描述符都在/proc中表示为类似符号链接的东西。它实际上是对目标文件的引用,而不仅仅是它的名称。当读取这些对象的符号链接时,您会得到一个可能指向相同文件的名称,除非它已被取消链接或挂载。当walk_component()跟随其中一个时,“procfs”中的->get_link()方法不会返回一个字符串名称,而是调用nd_jump_link()来直接更新nameidata指向该目标。然后,->get_link()返回NULL。同样,没有最终组件,pick_link()返回NULL。

跟随最终组件中的符号链接

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的最后一个字段。对于一些调用者来说,这就是他们需要的一切;他们希望创建最后一个名称(如果不存在)或者在存在时返回错误。其他调用者可能希望跟随符号链接(如果找到),并可能对该符号链接的最后一个组件应用特殊处理,而不仅仅是原始文件名的最后一个组件。这些调用者可能需要一遍又一遍地在连续的符号链接上调用link_path_walk(),直到找到一个不指向另一个符号链接的符号链接。

This case is handled by relevant callers of link_path_walk(), such as path_lookupat(), path_openat() using a loop that calls link_path_walk(), and then handles the final component by calling open_last_lookups() or lookup_last(). If it is a symlink that needs to be followed, open_last_lookups() or lookup_last() will set things up properly and return the path so that 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()的相关调用者处理,比如使用循环调用link_path_walk()的path_lookupat()、path_openat(),然后通过调用open_last_lookups()或lookup_last()处理最终组件。如果需要跟随符号链接,open_last_lookups()或lookup_last()将适当设置并返回路径,以便循环重复,再次调用link_path_walk()。如果每个符号链接的最后一个组件是另一个符号链接,这可能会循环多达40次。

Of the various functions that examine the final component, open_last_lookups() is the most interesting as it works in tandem with do_open() for opening a file. Part of open_last_lookups() runs with i_rwsem held and this part is in a separate function: lookup_open().
在检查最终组件的各种函数中,open_last_lookups()是最有趣的,因为它与do_open()一起工作,用于打开文件。open_last_lookups()的一部分在持有i_rwsem时运行,这部分在一个单独的函数中:lookup_open()。

Explaining open_last_lookups() and do_open() completely is beyond the scope of this article, but a few highlights should help those interested in exploring the code.
对open_last_lookups()和do_open()进行完整的解释超出了本文的范围,但一些要点应该有助于那些有兴趣探索代码的人。

  1. Rather than just finding the target file, do_open() is used after open_last_lookup() 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 i_op->lookup() and i_op->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.
    与仅查找目标文件不同,open_last_lookups()在open_last_lookup()之后使用do_open()来打开文件。如果文件在dcache中找到,则使用vfs_open()。如果没有找到,则lookup_open()将调用atomic_open()(如果文件系统提供了)来将最终查找与打开结合起来,或者将直接执行分开的i_op->lookup()和i_op->create()步骤。在后一种情况下,对新找到或创建的文件的实际“打开”将由vfs_open()执行,就像在dcache中找到名称一样。

  2. vfs_open() can fail with -EOPENSTALE if the cached information wasn't quite current enough. If it's in RCU-walk -ECHILD will be returned otherwise -ESTALE is returned. When -ESTALE is returned, the caller may retry with LOOKUP_REVAL flag set.
    如果vfs_open()因缓存信息不够及时而失败,可能会返回-EOPENSTALE。如果在RCU-walk中,将返回-ECHILD,否则将返回-ESTALE。当返回-ESTALE时,调用者可以使用设置了LOOKUP_REVAL标志的重试。

  3. An open with O_CREAT does follow a symlink in the final component, unlike other creation system calls (like mkdir). So the sequence:
    使用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: lookup_last() or open_last_lookup() returns a non NULL value, and link_path_walk() gets called and the open process continues on the symlink that was found.
    将创建一个名为/tmp/bar的文件。如果设置了O_EXCL,则不允许这样,但对于O_CREAT打开,处理方式与非创建打开类似:lookup_last()或open_last_lookup()返回一个非NULL值,然后调用link_path_walk(),打开过程继续在找到的符号链接上。

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 some apply restrictions to all path components encountered in the path lookup.
适当的方式来结束这次路径名查找之旅是列出可以存储在nameidata中以指导查找过程的各种标志。其中许多只在最终组件上有意义,其他反映了路径名查找的当前状态,还有一些对路径查找中遇到的所有路径组件施加限制。

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.
然后是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_RCU和LOOKUP_REVAL。它们在RCU-walk、REF-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表示尚未到达最终组件。主要用于告知审计子系统特定访问的完整上下文。

ND_ROOT_PRESET 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.
ND_ROOT_PRESET表示nameidata中的根字段由调用者提供,因此在不再需要时不应释放。

ND_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 (also known as a "magic link"). 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 ND_JUMPED is set when the look completes - which may be at the final component or, when creating, unlinking, or renaming, at the penultimate component.
ND_JUMPED表示当前的dentry之所以被选择,不是因为它具有正确的名称,而是出于其他原因。当跟随“..”、跟随到/、跨越挂载点或访问“/proc/PID/fd/PID/fd/FD”符号链接(也称为“magic link”)时会发生这种情况。在这种情况下,文件系统尚未要求重新验证名称(使用d_revalidate())。在这种情况下,如果在查找完成时设置了ND_JUMPED,则可能仍然需要重新验证inode,因此会调用d_op->d_weak_revalidate() - 这可能发生在最终组件或在创建、取消链接或重命名时发生在倒数第二个组件。

Resolution-restriction flags

解析限制标志

In order to allow userspace to protect itself against certain race conditions and attack scenarios involving changing path components, a series of flags are available which apply restrictions to all path components encountered during path lookup. These flags are exposed through openat2()'s resolve field.
为了允许用户空间保护自身免受某些涉及更改路径组件的竞争条件和攻击场景的影响,提供了一系列标志,这些标志适用于路径查找期间遇到的所有路径组件。这些标志通过openat2()的resolve字段公开。

LOOKUP_NO_SYMLINKS blocks all symlink traversals (including magic-links). This is distinctly different from LOOKUP_FOLLOW, because the latter only relates to restricting the following of trailing symlinks.
LOOKUP_NO_SYMLINKS阻止所有符号链接遍历(包括magic-link)。这与LOOKUP_FOLLOW明显不同,后者仅与限制跟随尾随符号链接有关。

LOOKUP_NO_MAGICLINKS blocks all magic-link traversals. Filesystems must ensure that they return errors from nd_jump_link(), because that is how LOOKUP_NO_MAGICLINKS and other magic-link restrictions are implemented.
LOOKUP_NO_MAGICLINKS阻止所有magic-link遍历。文件系统必须确保从nd_jump_link()返回错误,因为这是实现LOOKUP_NO_MAGICLINKS和其他magic-link限制的方式。

LOOKUP_NO_XDEV blocks all vfsmount traversals (this includes both bind-mounts and ordinary mounts). Note that the vfsmount which contains the lookup is determined by the first mountpoint the path lookup reaches -- absolute paths start with the vfsmount of /, and relative paths start with the dfd's vfsmount. Magic-links are only permitted if the vfsmount of the path is unchanged.
LOOKUP_NO_XDEV阻止所有vfsmount遍历(包括绑定挂载和普通挂载)。请注意,包含查找的vfsmount是由路径查找到达的第一个挂载点确定的 - 绝对路径以/的vfsmount开头,相对路径以dfd的vfsmount开头。只有在路径的vfsmount未更改时,才允许magic-link。

LOOKUP_BENEATH blocks any path components which resolve outside the starting point of the resolution. This is done by blocking nd_jump_root() as well as blocking ".." if it would jump outside the starting point. rename_lock and mount_lock are used to detect attacks against the resolution of "..". Magic-links are also blocked.
LOOKUP_BENEATH阻止解析超出解析起点的任何路径组件。这是通过阻止nd_jump_root()以及在跳出起点时阻止“..”来实现的。rename_lock和mount_lock用于检测针对“..”解析的攻击。也会阻止magic-link。

LOOKUP_IN_ROOT resolves all path components as though the starting point were the filesystem root. nd_jump_root() brings the resolution back to the starting point, and ".." at the starting point will act as a no-op. As with LOOKUP_BENEATH, rename_lock and mount_lock are used to detect attacks against ".." resolution. Magic-links are also blocked.
LOOKUP_IN_ROOT将所有路径组件解析为起点为文件系统根目录。nd_jump_root()将解析带回起点,“..”在起点处将作为无操作。与LOOKUP_BENEATH一样,rename_lock和mount_lock用于检测针对“..”解析的攻击。也会阻止magic-link。

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确保如果最终组件是自动挂载点,则触发挂载。某些操作无论如何都会触发它,但像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类似,但用于符号链接。某些系统调用会隐式设置或清除它,而其他系统调用具有API标志,如AT_SYMLINK_FOLLOW和UMOUNT_NOFOLLOW来控制它。它的效果类似于我们之前遇到的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_OPEN、LOOKUP_CREATE、LOOKUP_EXCL和LOOKUP_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的符号链接,但对于NFS、XFS或Btrfs没有帮助。这种支持不太可能被长时间延迟。

posted @ 2023-12-04 21:46  dolinux  阅读(196)  评论(0)    收藏  举报