=========================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
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" 這兩種狀況。 在深刻以前,咱們須要先了解一些低層次的區別。緩存
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」
上下文中能夠清楚地看到許多可能的競爭,理解這一點對於理解路徑名查找很是重要。
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
能夠保護文件系統不受某些競爭和其餘 問題的影響。這些文件系統一般是 「本地」 文件系統,好比 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
標誌檢測這些文件系統。
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
鎖機制包括了:
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_inode
對 inode
的引用(間接引用了 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
最初爲 negative
(即 d_inode
爲 NULL
), 並做爲建立操做的一部分,以後 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
中的 refcount
爲 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
值。
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
沒有更改,那麼實際上就沒有必要對 子目錄項使用鎖。
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
發如今掃描哈希表中 的鏈表失敗時發生了重命名,它將再次嘗試。
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
,而 name
的 d_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_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
引用計數器。這裏的 Per-CPU
意味着增長計數 很便宜,由於它只使用 CPU
本地內存,可是檢查計數是否爲零很昂貴,由於它須要檢查每一個 CPU
。 使用 mnt_count
引用能夠防止 mount
描述符因爲常規卸載操做而消失,但不能防止「延遲」卸載。 所以,保存 mnt_count
並不能確保 mount
保持在名稱空間中,特別是不能穩定指向掛載點的 dentry
的連接。可是,它確保 mount
數據結構保持一致,並提供對已掛載文件系統根 dentry
的引用。所以,經過 ->mnt_count
的引用提供了對已掛載 dentry
的穩定引用,而不是掛載點的 dentry
。
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
不能確保這一點。
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
哈希表中的鏈表和掛載點哈希表時持有。
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」 的函數的初版 Unix
。struct nameidata
包含如下 字段:
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_lockref
和 mnt_count
的引用。
This is a string together with a length (i.e. not nul
terminated) that is the "next" component in the pathname.
該結構體包含一個字符串和該字符串(即非 nul 終止)的長度,用來表示路徑名中的 「下一個」 須要解析的組件。
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_NORM
、LAST_ROOT
、LAST_DOT
、LAST_DOTDOT
或 LAST_BIND
其中之一的值。 只有當類型爲 LAST_NORM
時,last
字段纔有效。LAST_BIND
在跟蹤符號連接時使用, 而該符號連接的組件尚未被處理。其餘的應該是至關不言自明的。
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()
,當 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 advancename
over one component while updatinglast_type
andlast
. If that was the final component, then return, otherwise callwalk_component()
and repeat from the top.給定一個路徑 (
name
)和nameidata
結構(nd),檢查當前目錄是否具備執行權限, 而後在更新last_type
和last
時把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」 版本中識別它的相似物。
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->last
和 nd->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]
來檢查尾隨斜槓。若是在最後一個組件以外還有任何字符,那麼它必須 是一個尾反斜槓。
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
可能設置爲三個 不一樣的標誌值。
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:
若是設置了這個標誌,那麼文件系統就要求在處理任何可能的掛載點以前執行 dentry
的 d_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
給它一個特殊的經過(不會阻塞)。
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
(二者都有已計數的引用)。
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()
沒有找到掛載點,那麼這個標誌 將致使調用 dentry
的 d_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()
操做能夠是任意複雜的,也能夠與服務器進程通訊等等,可是它最終應該報告 要麼是一個錯誤,要麼就是沒有什麼須要掛載的,或者應該提供帶有新的 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 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
鎖的規則跟傳統鎖的不太同樣。因此咱們會額外花一些時間來解釋。
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.
這個中止動做須要獲取當前 vfsmount
和 dentry
的計數引用,而且確保這些引用對使用 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 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
對 RCU-walk
模式相當重要。 rcu_read_lock()
在 RCU-walk
沿着路徑行走的整個過程當中一直被持有。 (也就是在整個過程當中會保持鎖)它提供的特殊保證是,當鎖被持有時,關鍵數據結構: dentries
、inode
、super_blocks
和 mount
等描述符不會被釋放。它們(這些描述符) 可能以某種方式被取消連接或失效,可是內存不會被從新使用,所以各個字段中的值仍然有意義。 這是 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
持有當前 dentry
,vfsmount
描述符的計數引用, 而且在引用 「下一個」 dentry
或 vfsmount
以前不會釋放這些引用。 它有時也使用 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
的名字以及長度保存到本地變量 tlen
和 tname
,接着調用 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()
進行實際比較。
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
結構是這樣。
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
seqlock 進行採樣,並將序列號存儲在 nameidata
結構的 seq
字段中,所以 nd->seq
應該始終是 nd->dentry
的當前序列號。在複製這些內容(name
,parent
或者 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
指針。與其在 每次訪問時都進行從新驗證,不如在第一次訪問時進行復制,並將其存儲在 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
的重要 「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
,而後繼續。這個過程獲取新 dentry
的 seq
號,而後檢查 舊 dentry
的 seq
號,這剛好反映了咱們在 REF-walk
中看到的流程:在刪除舊 dentry
以前,須要先獲取對新 dentry
的計數引用。
這裏舊的
dentry
指的是上面提到的當前dentry
和seq
,即保存在nameidata
結構中的seq
和path.dentry
。
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_mutex
在 RCU-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-walk
在 dentry
緩存中找不到某些東西時,無論它是否在 dentry
緩存中,它都已經降低到 REF-walk
,並使用適當的鎖定進行再次嘗試。這基本很好地處理了全部的 狀況,因此在 RCU
中添加對 rename_lock
額外的檢查並無多大意義。
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()
是一個選項的狀況,本質上是對它所持有的每一個指針 (vfsmount
、dentry
,可能還有一些符號連接)進行引用,而後驗證相關的 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()
是正確的,仍是應該減小計數並僞裝這些都沒有發生。
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
指針(這裏指接收一個 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
或來自 nameidata
的 seq
號,所以在訪問 dentry
中的字段時須要格外當心。這種額外的注意一般包括使用 ACCESS_ONCE()
或更新的 READ_ONCE()
訪問字段,並在使用它以前驗證結果是否爲 NULL
。這種模式能夠在 nfs_lookup_revalidate()
中看到。
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.
這裏的重點是「快速嘗試並檢查」。應該是「快速仔細地嘗試,而後檢查」。須要進行檢查的事實 提醒咱們,系統是動態的,而且只有有限數量的東西是安全的。在整個過程當中,最可能致使錯誤的 緣由是,假設某樣東西是安全的,而實際上它不是。有時須要仔細考慮究竟是什麼確保了每次訪問的 安全性。
==========================================
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:
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.
彷佛這個堆棧中只須要存儲路徑中未解析部分的名稱,可是咱們還須要更多。爲此,咱們須要緩存生存期。
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
相同,後者自己由 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->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
,咱們還須要 dentry
的 seq
號,以便確認切換過程是安全的。
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
中,符號連接 堆棧都須要包含路徑剩餘未解析的部分。
struct path
to provide a reference to the inode in REF-walkstruct inode *
to provide a reference to the inode in RCU-walkseq
to allow the path to be safely switched from RCU-walk to REF-walkcookie
that tells ->put_path()
what to put.struct path
在 REF-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. 注意,在給定的堆棧幀中,路徑剩餘部分(名稱)不是其餘字段引用的符號連接的一部分。 一旦符號連接被徹底解析,剩餘部分將被繼續解析。
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.
推入和彈出引用指針(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 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_GET
和 WALK_PUT
容許它在找到符號連接後釋放當前 符號連接。首先測試 WALK_PUT,從而調用 put_link()
。隨後(經過 should_follow_link()
) 測試 WALK_GET,從而調用 pick_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 get_link()
returning NULL
.
有一對符號鏈的接特殊狀況值得進一步解釋。二者都會在 nameidata 中建立一個新的 struct path
(帶有 moun
和 dentry
),並致使 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()
經過將 nameidata
的 last_type
字段設置爲 LAST_BIND
來報告這一點。
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()
的詳解徹底超出這篇文章的範疇了,但仍是提一些有助於研究這部分代碼的重點部分。
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
中找到名稱同樣。
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()
讓 文件系統有機會解決一些小的不一致。若是沒法解決,纔會從頂部從新開始查找。
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()
,而後打開進程繼續在找到的符號連接 上運行。
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 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
, 它在概念上不符合 其它 類別。若是沒有設置此值,則空路徑名會在早期致使錯誤。若是設置了 該標誌,則不會將空路徑名視爲錯誤。
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
表示還沒有到達最終組件。這主要用於告訴 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/ fd」 符號連接。在這種狀況下,文件系統沒有被要求從新驗證 name
(使用 d_revalidate()
)。然而 inode
可能仍然須要從新驗證,所以,若是設置了 LOOKUP_JUMPED
,那麼當查找完成時(此時 可能位於最終組件,或者在建立、解除連接或重命名倒數第二個組件)函數 d_op->d_weak_revalidate()
會被調用。
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_FOLLOW
和 UMOUNT_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_OPEN
、LOOKUP_CREATE
、LOOKUP_EXCL
和 LOOKUP_RENAME_TARGET
不是 VFS
直接使用的,而是提供給文件系統,特別是 ->d_revalidate()
方法。若是文件系統知道 很快就會被要求打開或建立文件,那麼它能夠選擇不費力地從新驗證。這些標誌之前對 ->lookup()
也頗有用,可是隨着 ->atomic_open()
的引入,它們在這裏就不那麼相關了。
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
沒有幫助。 這種支持不太可能拖延過久。