Linux path-lookup 翻译

Pathname lookup in Linux.

=========================html

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

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

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.linux

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

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.promise

在考虑符号连接以前,咱们先来解决另外一个主要部分:基于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没有帮助。 这种支持不太可能拖延过久。

相关文章
相关标签/搜索