~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/Documentation/filesystems/path-lookup.rst

Version: ~ [ linux-6.11.5 ] ~ [ linux-6.10.14 ] ~ [ linux-6.9.12 ] ~ [ linux-6.8.12 ] ~ [ linux-6.7.12 ] ~ [ linux-6.6.58 ] ~ [ linux-6.5.13 ] ~ [ linux-6.4.16 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.114 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.169 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.228 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.284 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.322 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.336 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

Diff markup

Differences between /Documentation/filesystems/path-lookup.rst (Version linux-6.11.5) and /Documentation/filesystems/path-lookup.rst (Version linux-5.6.19)


  1 ===============                                     1 ===============
  2 Pathname lookup                                     2 Pathname lookup
  3 ===============                                     3 ===============
  4                                                     4 
  5 This write-up is based on three articles publi      5 This write-up is based on three articles published at lwn.net:
  6                                                     6 
  7 - <https://lwn.net/Articles/649115/> Pathname       7 - <https://lwn.net/Articles/649115/> Pathname lookup in Linux
  8 - <https://lwn.net/Articles/649729/> RCU-walk:      8 - <https://lwn.net/Articles/649729/> RCU-walk: faster pathname lookup in Linux
  9 - <https://lwn.net/Articles/650786/> A walk am      9 - <https://lwn.net/Articles/650786/> A walk among the symlinks
 10                                                    10 
 11 Written by Neil Brown with help from Al Viro a     11 Written by Neil Brown with help from Al Viro and Jon Corbet.
 12 It has subsequently been updated to reflect ch     12 It has subsequently been updated to reflect changes in the kernel
 13 including:                                         13 including:
 14                                                    14 
 15 - per-directory parallel name lookup.              15 - per-directory parallel name lookup.
 16 - ``openat2()`` resolution restriction flags.      16 - ``openat2()`` resolution restriction flags.
 17                                                    17 
 18 Introduction to pathname lookup                    18 Introduction to pathname lookup
 19 ===============================                    19 ===============================
 20                                                    20 
 21 The most obvious aspect of pathname lookup, wh     21 The most obvious aspect of pathname lookup, which very little
 22 exploration is needed to discover, is that it      22 exploration is needed to discover, is that it is complex.  There are
 23 many rules, special cases, and implementation      23 many rules, special cases, and implementation alternatives that all
 24 combine to confuse the unwary reader.  Compute     24 combine to confuse the unwary reader.  Computer science has long been
 25 acquainted with such complexity and has tools      25 acquainted with such complexity and has tools to help manage it.  One
 26 tool that we will make extensive use of is "di     26 tool that we will make extensive use of is "divide and conquer".  For
 27 the early parts of the analysis we will divide     27 the early parts of the analysis we will divide off symlinks - leaving
 28 them until the final part.  Well before we get     28 them until the final part.  Well before we get to symlinks we have
 29 another major division based on the VFS's appr     29 another major division based on the VFS's approach to locking which
 30 will allow us to review "REF-walk" and "RCU-wa     30 will allow us to review "REF-walk" and "RCU-walk" separately.  But we
 31 are getting ahead of ourselves.  There are som     31 are getting ahead of ourselves.  There are some important low level
 32 distinctions we need to clarify first.             32 distinctions we need to clarify first.
 33                                                    33 
 34 There are two sorts of ...                         34 There are two sorts of ...
 35 --------------------------                         35 --------------------------
 36                                                    36 
 37 .. _openat: http://man7.org/linux/man-pages/ma     37 .. _openat: http://man7.org/linux/man-pages/man2/openat.2.html
 38                                                    38 
 39 Pathnames (sometimes "file names"), used to id     39 Pathnames (sometimes "file names"), used to identify objects in the
 40 filesystem, will be familiar to most readers.      40 filesystem, will be familiar to most readers.  They contain two sorts
 41 of elements: "slashes" that are sequences of o     41 of elements: "slashes" that are sequences of one or more "``/``"
 42 characters, and "components" that are sequence     42 characters, and "components" that are sequences of one or more
 43 non-"``/``" characters.  These form two kinds      43 non-"``/``" characters.  These form two kinds of paths.  Those that
 44 start with slashes are "absolute" and start fr     44 start with slashes are "absolute" and start from the filesystem root.
 45 The others are "relative" and start from the c     45 The others are "relative" and start from the current directory, or
 46 from some other location specified by a file d !!  46 from some other location specified by a file descriptor given to a
 47 "``*at()``" system calls such as `openat() <op !!  47 "``XXXat``" system call such as `openat() <openat_>`_.
 48                                                    48 
 49 .. _execveat: http://man7.org/linux/man-pages/     49 .. _execveat: http://man7.org/linux/man-pages/man2/execveat.2.html
 50                                                    50 
 51 It is tempting to describe the second kind as      51 It is tempting to describe the second kind as starting with a
 52 component, but that isn't always accurate: a p     52 component, but that isn't always accurate: a pathname can lack both
 53 slashes and components, it can be empty, in ot     53 slashes and components, it can be empty, in other words.  This is
 54 generally forbidden in POSIX, but some of thos !!  54 generally forbidden in POSIX, but some of those "xxx``at``" system calls
 55 in Linux permit it when the ``AT_EMPTY_PATH``      55 in Linux permit it when the ``AT_EMPTY_PATH`` flag is given.  For
 56 example, if you have an open file descriptor o     56 example, if you have an open file descriptor on an executable file you
 57 can execute it by calling `execveat() <execvea     57 can execute it by calling `execveat() <execveat_>`_ passing
 58 the file descriptor, an empty path, and the ``     58 the file descriptor, an empty path, and the ``AT_EMPTY_PATH`` flag.
 59                                                    59 
 60 These paths can be divided into two sections:      60 These paths can be divided into two sections: the final component and
 61 everything else.  The "everything else" is the     61 everything else.  The "everything else" is the easy bit.  In all cases
 62 it must identify a directory that already exis     62 it must identify a directory that already exists, otherwise an error
 63 such as ``ENOENT`` or ``ENOTDIR`` will be repo     63 such as ``ENOENT`` or ``ENOTDIR`` will be reported.
 64                                                    64 
 65 The final component is not so simple.  Not onl     65 The final component is not so simple.  Not only do different system
 66 calls interpret it quite differently (e.g. som     66 calls interpret it quite differently (e.g. some create it, some do
 67 not), but it might not even exist: neither the     67 not), but it might not even exist: neither the empty pathname nor the
 68 pathname that is just slashes have a final com     68 pathname that is just slashes have a final component.  If it does
 69 exist, it could be "``.``" or "``..``" which a     69 exist, it could be "``.``" or "``..``" which are handled quite differently
 70 from other components.                             70 from other components.
 71                                                    71 
 72 .. _POSIX: https://pubs.opengroup.org/onlinepu !!  72 .. _POSIX: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
 73                                                    73 
 74 If a pathname ends with a slash, such as "``/t     74 If a pathname ends with a slash, such as "``/tmp/foo/``" it might be
 75 tempting to consider that to have an empty fin     75 tempting to consider that to have an empty final component.  In many
 76 ways that would lead to correct results, but n     76 ways that would lead to correct results, but not always.  In
 77 particular, ``mkdir()`` and ``rmdir()`` each c     77 particular, ``mkdir()`` and ``rmdir()`` each create or remove a directory named
 78 by the final component, and they are required      78 by the final component, and they are required to work with pathnames
 79 ending in "``/``".  According to POSIX_:       !!  79 ending in "``/``".  According to POSIX_
 80                                                    80 
 81   A pathname that contains at least one non-<s !!  81   A pathname that contains at least one non- &lt;slash> character and
 82   that ends with one or more trailing <slash>  !!  82   that ends with one or more trailing &lt;slash> characters shall not
 83   be resolved successfully unless the last pat     83   be resolved successfully unless the last pathname component before
 84   the trailing <slash> characters names an exi     84   the trailing <slash> characters names an existing directory or a
 85   directory entry that is to be created for a      85   directory entry that is to be created for a directory immediately
 86   after the pathname is resolved.                  86   after the pathname is resolved.
 87                                                    87 
 88 The Linux pathname walking code (mostly in ``f     88 The Linux pathname walking code (mostly in ``fs/namei.c``) deals with
 89 all of these issues: breaking the path into co     89 all of these issues: breaking the path into components, handling the
 90 "everything else" quite separately from the fi     90 "everything else" quite separately from the final component, and
 91 checking that the trailing slash is not used w     91 checking that the trailing slash is not used where it isn't
 92 permitted.  It also addresses the important is     92 permitted.  It also addresses the important issue of concurrent
 93 access.                                            93 access.
 94                                                    94 
 95 While one process is looking up a pathname, an     95 While one process is looking up a pathname, another might be making
 96 changes that affect that lookup.  One fairly e     96 changes that affect that lookup.  One fairly extreme case is that if
 97 "a/b" were renamed to "a/c/b" while another pr     97 "a/b" were renamed to "a/c/b" while another process were looking up
 98 "a/b/..", that process might successfully reso     98 "a/b/..", that process might successfully resolve on "a/c".
 99 Most races are much more subtle, and a big par     99 Most races are much more subtle, and a big part of the task of
100 pathname lookup is to prevent them from having    100 pathname lookup is to prevent them from having damaging effects.  Many
101 of the possible races are seen most clearly in    101 of the possible races are seen most clearly in the context of the
102 "dcache" and an understanding of that is centr    102 "dcache" and an understanding of that is central to understanding
103 pathname lookup.                                  103 pathname lookup.
104                                                   104 
105 More than just a cache                            105 More than just a cache
106 ----------------------                            106 ----------------------
107                                                   107 
108 The "dcache" caches information about names in    108 The "dcache" caches information about names in each filesystem to
109 make them quickly available for lookup.  Each     109 make them quickly available for lookup.  Each entry (known as a
110 "dentry") contains three significant fields: a    110 "dentry") contains three significant fields: a component name, a
111 pointer to a parent dentry, and a pointer to t    111 pointer to a parent dentry, and a pointer to the "inode" which
112 contains further information about the object     112 contains further information about the object in that parent with
113 the given name.  The inode pointer can be ``NU    113 the given name.  The inode pointer can be ``NULL`` indicating that the
114 name doesn't exist in the parent.  While there    114 name doesn't exist in the parent.  While there can be linkage in the
115 dentry of a directory to the dentries of the c    115 dentry of a directory to the dentries of the children, that linkage is
116 not used for pathname lookup, and so will not     116 not used for pathname lookup, and so will not be considered here.
117                                                   117 
118 The dcache has a number of uses apart from acc    118 The dcache has a number of uses apart from accelerating lookup.  One
119 that will be particularly relevant is that it     119 that will be particularly relevant is that it is closely integrated
120 with the mount table that records which filesy    120 with the mount table that records which filesystem is mounted where.
121 What the mount table actually stores is which     121 What the mount table actually stores is which dentry is mounted on top
122 of which other dentry.                            122 of which other dentry.
123                                                   123 
124 When considering the dcache, we have another o    124 When considering the dcache, we have another of our "two types"
125 distinctions: there are two types of filesyste    125 distinctions: there are two types of filesystems.
126                                                   126 
127 Some filesystems ensure that the information i    127 Some filesystems ensure that the information in the dcache is always
128 completely accurate (though not necessarily co    128 completely accurate (though not necessarily complete).  This can allow
129 the VFS to determine if a particular file does    129 the VFS to determine if a particular file does or doesn't exist
130 without checking with the filesystem, and mean    130 without checking with the filesystem, and means that the VFS can
131 protect the filesystem against certain races a    131 protect the filesystem against certain races and other problems.
132 These are typically "local" filesystems such a    132 These are typically "local" filesystems such as ext3, XFS, and Btrfs.
133                                                   133 
134 Other filesystems don't provide that guarantee    134 Other filesystems don't provide that guarantee because they cannot.
135 These are typically filesystems that are share    135 These are typically filesystems that are shared across a network,
136 whether remote filesystems like NFS and 9P, or    136 whether remote filesystems like NFS and 9P, or cluster filesystems
137 like ocfs2 or cephfs.  These filesystems allow    137 like ocfs2 or cephfs.  These filesystems allow the VFS to revalidate
138 cached information, and must provide their own    138 cached information, and must provide their own protection against
139 awkward races.  The VFS can detect these files    139 awkward races.  The VFS can detect these filesystems by the
140 ``DCACHE_OP_REVALIDATE`` flag being set in the    140 ``DCACHE_OP_REVALIDATE`` flag being set in the dentry.
141                                                   141 
142 REF-walk: simple concurrency management with r    142 REF-walk: simple concurrency management with refcounts and spinlocks
143 ----------------------------------------------    143 --------------------------------------------------------------------
144                                                   144 
145 With all of those divisions carefully classifi    145 With all of those divisions carefully classified, we can now start
146 looking at the actual process of walking along    146 looking at the actual process of walking along a path.  In particular
147 we will start with the handling of the "everyt    147 we will start with the handling of the "everything else" part of a
148 pathname, and focus on the "REF-walk" approach    148 pathname, and focus on the "REF-walk" approach to concurrency
149 management.  This code is found in the ``link_    149 management.  This code is found in the ``link_path_walk()`` function, if
150 you ignore all the places that only run when "    150 you ignore all the places that only run when "``LOOKUP_RCU``"
151 (indicating the use of RCU-walk) is set.          151 (indicating the use of RCU-walk) is set.
152                                                   152 
153 .. _Meet the Lockers: https://lwn.net/Articles    153 .. _Meet the Lockers: https://lwn.net/Articles/453685/
154                                                   154 
155 REF-walk is fairly heavy-handed with locks and    155 REF-walk is fairly heavy-handed with locks and reference counts.  Not
156 as heavy-handed as in the old "big kernel lock    156 as heavy-handed as in the old "big kernel lock" days, but certainly not
157 afraid of taking a lock when one is needed.  I    157 afraid of taking a lock when one is needed.  It uses a variety of
158 different concurrency controls.  A background     158 different concurrency controls.  A background understanding of the
159 various primitives is assumed, or can be glean    159 various primitives is assumed, or can be gleaned from elsewhere such
160 as in `Meet the Lockers`_.                        160 as in `Meet the Lockers`_.
161                                                   161 
162 The locking mechanisms used by REF-walk includ    162 The locking mechanisms used by REF-walk include:
163                                                   163 
164 dentry->d_lockref                                 164 dentry->d_lockref
165 ~~~~~~~~~~~~~~~~~                                 165 ~~~~~~~~~~~~~~~~~
166                                                   166 
167 This uses the lockref primitive to provide bot    167 This uses the lockref primitive to provide both a spinlock and a
168 reference count.  The special-sauce of this pr    168 reference count.  The special-sauce of this primitive is that the
169 conceptual sequence "lock; inc_ref; unlock;" c    169 conceptual sequence "lock; inc_ref; unlock;" can often be performed
170 with a single atomic memory operation.            170 with a single atomic memory operation.
171                                                   171 
172 Holding a reference on a dentry ensures that t    172 Holding a reference on a dentry ensures that the dentry won't suddenly
173 be freed and used for something else, so the v    173 be freed and used for something else, so the values in various fields
174 will behave as expected.  It also protects the    174 will behave as expected.  It also protects the ``->d_inode`` reference
175 to the inode to some extent.                      175 to the inode to some extent.
176                                                   176 
177 The association between a dentry and its inode    177 The association between a dentry and its inode is fairly permanent.
178 For example, when a file is renamed, the dentr    178 For example, when a file is renamed, the dentry and inode move
179 together to the new location.  When a file is     179 together to the new location.  When a file is created the dentry will
180 initially be negative (i.e. ``d_inode`` is ``N    180 initially be negative (i.e. ``d_inode`` is ``NULL``), and will be assigned
181 to the new inode as part of the act of creatio    181 to the new inode as part of the act of creation.
182                                                   182 
183 When a file is deleted, this can be reflected     183 When a file is deleted, this can be reflected in the cache either by
184 setting ``d_inode`` to ``NULL``, or by removin    184 setting ``d_inode`` to ``NULL``, or by removing it from the hash table
185 (described shortly) used to look up the name i    185 (described shortly) used to look up the name in the parent directory.
186 If the dentry is still in use the second optio    186 If the dentry is still in use the second option is used as it is
187 perfectly legal to keep using an open file aft    187 perfectly legal to keep using an open file after it has been deleted
188 and having the dentry around helps.  If the de    188 and having the dentry around helps.  If the dentry is not otherwise in
189 use (i.e. if the refcount in ``d_lockref`` is     189 use (i.e. if the refcount in ``d_lockref`` is one), only then will
190 ``d_inode`` be set to ``NULL``.  Doing it this    190 ``d_inode`` be set to ``NULL``.  Doing it this way is more efficient for a
191 very common case.                                 191 very common case.
192                                                   192 
193 So as long as a counted reference is held to a    193 So as long as a counted reference is held to a dentry, a non-``NULL`` ``->d_inode``
194 value will never be changed.                      194 value will never be changed.
195                                                   195 
196 dentry->d_lock                                    196 dentry->d_lock
197 ~~~~~~~~~~~~~~                                    197 ~~~~~~~~~~~~~~
198                                                   198 
199 ``d_lock`` is a synonym for the spinlock that     199 ``d_lock`` is a synonym for the spinlock that is part of ``d_lockref`` above.
200 For our purposes, holding this lock protects a    200 For our purposes, holding this lock protects against the dentry being
201 renamed or unlinked.  In particular, its paren    201 renamed or unlinked.  In particular, its parent (``d_parent``), and its
202 name (``d_name``) cannot be changed, and it ca    202 name (``d_name``) cannot be changed, and it cannot be removed from the
203 dentry hash table.                                203 dentry hash table.
204                                                   204 
205 When looking for a name in a directory, REF-wa    205 When looking for a name in a directory, REF-walk takes ``d_lock`` on
206 each candidate dentry that it finds in the has    206 each candidate dentry that it finds in the hash table and then checks
207 that the parent and name are correct.  So it d    207 that the parent and name are correct.  So it doesn't lock the parent
208 while searching in the cache; it only locks ch    208 while searching in the cache; it only locks children.
209                                                   209 
210 When looking for the parent for a given name (    210 When looking for the parent for a given name (to handle "``..``"),
211 REF-walk can take ``d_lock`` to get a stable r    211 REF-walk can take ``d_lock`` to get a stable reference to ``d_parent``,
212 but it first tries a more lightweight approach    212 but it first tries a more lightweight approach.  As seen in
213 ``dget_parent()``, if a reference can be claim    213 ``dget_parent()``, if a reference can be claimed on the parent, and if
214 subsequently ``d_parent`` can be seen to have     214 subsequently ``d_parent`` can be seen to have not changed, then there is
215 no need to actually take the lock on the child    215 no need to actually take the lock on the child.
216                                                   216 
217 rename_lock                                       217 rename_lock
218 ~~~~~~~~~~~                                       218 ~~~~~~~~~~~
219                                                   219 
220 Looking up a given name in a given directory i    220 Looking up a given name in a given directory involves computing a hash
221 from the two values (the name and the dentry o    221 from the two values (the name and the dentry of the directory),
222 accessing that slot in a hash table, and searc    222 accessing that slot in a hash table, and searching the linked list
223 that is found there.                              223 that is found there.
224                                                   224 
225 When a dentry is renamed, the name and the par    225 When a dentry is renamed, the name and the parent dentry can both
226 change so the hash will almost certainly chang    226 change so the hash will almost certainly change too.  This would move the
227 dentry to a different chain in the hash table.    227 dentry to a different chain in the hash table.  If a filename search
228 happened to be looking at a dentry that was mo    228 happened to be looking at a dentry that was moved in this way,
229 it might end up continuing the search down the    229 it might end up continuing the search down the wrong chain,
230 and so miss out on part of the correct chain.     230 and so miss out on part of the correct chain.
231                                                   231 
232 The name-lookup process (``d_lookup()``) does  !! 232 The name-lookup process (``d_lookup()``) does _not_ try to prevent this
233 from happening, but only to detect when it hap    233 from happening, but only to detect when it happens.
234 ``rename_lock`` is a seqlock that is updated w    234 ``rename_lock`` is a seqlock that is updated whenever any dentry is
235 renamed.  If ``d_lookup`` finds that a rename     235 renamed.  If ``d_lookup`` finds that a rename happened while it
236 unsuccessfully scanned a chain in the hash tab    236 unsuccessfully scanned a chain in the hash table, it simply tries
237 again.                                            237 again.
238                                                   238 
239 ``rename_lock`` is also used to detect and def    239 ``rename_lock`` is also used to detect and defend against potential attacks
240 against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROO    240 against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
241 the parent directory is moved outside the root    241 the parent directory is moved outside the root, bypassing the ``path_equal()``
242 check). If ``rename_lock`` is updated during t    242 check). If ``rename_lock`` is updated during the lookup and the path encounters
243 a "..", a potential attack occurred and ``hand    243 a "..", a potential attack occurred and ``handle_dots()`` will bail out with
244 ``-EAGAIN``.                                      244 ``-EAGAIN``.
245                                                   245 
246 inode->i_rwsem                                    246 inode->i_rwsem
247 ~~~~~~~~~~~~~~                                    247 ~~~~~~~~~~~~~~
248                                                   248 
249 ``i_rwsem`` is a read/write semaphore that ser    249 ``i_rwsem`` is a read/write semaphore that serializes all changes to a particular
250 directory.  This ensures that, for example, an    250 directory.  This ensures that, for example, an ``unlink()`` and a ``rename()``
251 cannot both happen at the same time.  It also     251 cannot both happen at the same time.  It also keeps the directory
252 stable while the filesystem is asked to look u    252 stable while the filesystem is asked to look up a name that is not
253 currently in the dcache or, optionally, when t    253 currently in the dcache or, optionally, when the list of entries in a
254 directory is being retrieved with ``readdir()`    254 directory is being retrieved with ``readdir()``.
255                                                   255 
256 This has a complementary role to that of ``d_l    256 This has a complementary role to that of ``d_lock``: ``i_rwsem`` on a
257 directory protects all of the names in that di    257 directory protects all of the names in that directory, while ``d_lock``
258 on a name protects just one name in a director    258 on a name protects just one name in a directory.  Most changes to the
259 dcache hold ``i_rwsem`` on the relevant direct    259 dcache hold ``i_rwsem`` on the relevant directory inode and briefly take
260 ``d_lock`` on one or more the dentries while t    260 ``d_lock`` on one or more the dentries while the change happens.  One
261 exception is when idle dentries are removed fr    261 exception is when idle dentries are removed from the dcache due to
262 memory pressure.  This uses ``d_lock``, but ``    262 memory pressure.  This uses ``d_lock``, but ``i_rwsem`` plays no role.
263                                                   263 
264 The semaphore affects pathname lookup in two d    264 The semaphore affects pathname lookup in two distinct ways.  Firstly it
265 prevents changes during lookup of a name in a     265 prevents changes during lookup of a name in a directory.  ``walk_component()`` uses
266 ``lookup_fast()`` first which, in turn, checks    266 ``lookup_fast()`` first which, in turn, checks to see if the name is in the cache,
267 using only ``d_lock`` locking.  If the name is    267 using only ``d_lock`` locking.  If the name isn't found, then ``walk_component()``
268 falls back to ``lookup_slow()`` which takes a     268 falls back to ``lookup_slow()`` which takes a shared lock on ``i_rwsem``, checks again that
269 the name isn't in the cache, and then calls in    269 the name isn't in the cache, and then calls in to the filesystem to get a
270 definitive answer.  A new dentry will be added    270 definitive answer.  A new dentry will be added to the cache regardless of
271 the result.                                       271 the result.
272                                                   272 
273 Secondly, when pathname lookup reaches the fin    273 Secondly, when pathname lookup reaches the final component, it will
274 sometimes need to take an exclusive lock on ``    274 sometimes need to take an exclusive lock on ``i_rwsem`` before performing the last lookup so
275 that the required exclusion can be achieved.      275 that the required exclusion can be achieved.  How path lookup chooses
276 to take, or not take, ``i_rwsem`` is one of th    276 to take, or not take, ``i_rwsem`` is one of the
277 issues addressed in a subsequent section.         277 issues addressed in a subsequent section.
278                                                   278 
279 If two threads attempt to look up the same nam    279 If two threads attempt to look up the same name at the same time - a
280 name that is not yet in the dcache - the share    280 name that is not yet in the dcache - the shared lock on ``i_rwsem`` will
281 not prevent them both adding new dentries with    281 not prevent them both adding new dentries with the same name.  As this
282 would result in confusion an extra level of in    282 would result in confusion an extra level of interlocking is used,
283 based around a secondary hash table (``in_look    283 based around a secondary hash table (``in_lookup_hashtable``) and a
284 per-dentry flag bit (``DCACHE_PAR_LOOKUP``).      284 per-dentry flag bit (``DCACHE_PAR_LOOKUP``).
285                                                   285 
286 To add a new dentry to the cache while only ho    286 To add a new dentry to the cache while only holding a shared lock on
287 ``i_rwsem``, a thread must call ``d_alloc_para    287 ``i_rwsem``, a thread must call ``d_alloc_parallel()``.  This allocates a
288 dentry, stores the required name and parent in    288 dentry, stores the required name and parent in it, checks if there
289 is already a matching dentry in the primary or    289 is already a matching dentry in the primary or secondary hash
290 tables, and if not, stores the newly allocated    290 tables, and if not, stores the newly allocated dentry in the secondary
291 hash table, with ``DCACHE_PAR_LOOKUP`` set.       291 hash table, with ``DCACHE_PAR_LOOKUP`` set.
292                                                   292 
293 If a matching dentry was found in the primary     293 If a matching dentry was found in the primary hash table then that is
294 returned and the caller can know that it lost     294 returned and the caller can know that it lost a race with some other
295 thread adding the entry.  If no matching dentr    295 thread adding the entry.  If no matching dentry is found in either
296 cache, the newly allocated dentry is returned     296 cache, the newly allocated dentry is returned and the caller can
297 detect this from the presence of ``DCACHE_PAR_    297 detect this from the presence of ``DCACHE_PAR_LOOKUP``.  In this case it
298 knows that it has won any race and now is resp    298 knows that it has won any race and now is responsible for asking the
299 filesystem to perform the lookup and find the     299 filesystem to perform the lookup and find the matching inode.  When
300 the lookup is complete, it must call ``d_looku    300 the lookup is complete, it must call ``d_lookup_done()`` which clears
301 the flag and does some other house keeping, in    301 the flag and does some other house keeping, including removing the
302 dentry from the secondary hash table - it will    302 dentry from the secondary hash table - it will normally have been
303 added to the primary hash table already.  Note    303 added to the primary hash table already.  Note that a ``struct
304 waitqueue_head`` is passed to ``d_alloc_parall    304 waitqueue_head`` is passed to ``d_alloc_parallel()``, and
305 ``d_lookup_done()`` must be called while this     305 ``d_lookup_done()`` must be called while this ``waitqueue_head`` is still
306 in scope.                                         306 in scope.
307                                                   307 
308 If a matching dentry is found in the secondary    308 If a matching dentry is found in the secondary hash table,
309 ``d_alloc_parallel()`` has a little more work     309 ``d_alloc_parallel()`` has a little more work to do. It first waits for
310 ``DCACHE_PAR_LOOKUP`` to be cleared, using a w    310 ``DCACHE_PAR_LOOKUP`` to be cleared, using a wait_queue that was passed
311 to the instance of ``d_alloc_parallel()`` that    311 to the instance of ``d_alloc_parallel()`` that won the race and that
312 will be woken by the call to ``d_lookup_done()    312 will be woken by the call to ``d_lookup_done()``.  It then checks to see
313 if the dentry has now been added to the primar    313 if the dentry has now been added to the primary hash table.  If it
314 has, the dentry is returned and the caller jus    314 has, the dentry is returned and the caller just sees that it lost any
315 race.  If it hasn't been added to the primary     315 race.  If it hasn't been added to the primary hash table, the most
316 likely explanation is that some other dentry w    316 likely explanation is that some other dentry was added instead using
317 ``d_splice_alias()``.  In any case, ``d_alloc_    317 ``d_splice_alias()``.  In any case, ``d_alloc_parallel()`` repeats all the
318 look ups from the start and will normally retu    318 look ups from the start and will normally return something from the
319 primary hash table.                               319 primary hash table.
320                                                   320 
321 mnt->mnt_count                                    321 mnt->mnt_count
322 ~~~~~~~~~~~~~~                                    322 ~~~~~~~~~~~~~~
323                                                   323 
324 ``mnt_count`` is a per-CPU reference counter o    324 ``mnt_count`` is a per-CPU reference counter on "``mount``" structures.
325 Per-CPU here means that incrementing the count    325 Per-CPU here means that incrementing the count is cheap as it only
326 uses CPU-local memory, but checking if the cou    326 uses CPU-local memory, but checking if the count is zero is expensive as
327 it needs to check with every CPU.  Taking a ``    327 it needs to check with every CPU.  Taking a ``mnt_count`` reference
328 prevents the mount structure from disappearing    328 prevents the mount structure from disappearing as the result of regular
329 unmount operations, but does not prevent a "la    329 unmount operations, but does not prevent a "lazy" unmount.  So holding
330 ``mnt_count`` doesn't ensure that the mount re    330 ``mnt_count`` doesn't ensure that the mount remains in the namespace and,
331 in particular, doesn't stabilize the link to t    331 in particular, doesn't stabilize the link to the mounted-on dentry.  It
332 does, however, ensure that the ``mount`` data     332 does, however, ensure that the ``mount`` data structure remains coherent,
333 and it provides a reference to the root dentry    333 and it provides a reference to the root dentry of the mounted
334 filesystem.  So a reference through ``->mnt_co    334 filesystem.  So a reference through ``->mnt_count`` provides a stable
335 reference to the mounted dentry, but not the m    335 reference to the mounted dentry, but not the mounted-on dentry.
336                                                   336 
337 mount_lock                                        337 mount_lock
338 ~~~~~~~~~~                                        338 ~~~~~~~~~~
339                                                   339 
340 ``mount_lock`` is a global seqlock, a bit like    340 ``mount_lock`` is a global seqlock, a bit like ``rename_lock``.  It can be used to
341 check if any change has been made to any mount    341 check if any change has been made to any mount points.
342                                                   342 
343 While walking down the tree (away from the roo    343 While walking down the tree (away from the root) this lock is used when
344 crossing a mount point to check that the cross    344 crossing a mount point to check that the crossing was safe.  That is,
345 the value in the seqlock is read, then the cod    345 the value in the seqlock is read, then the code finds the mount that
346 is mounted on the current directory, if there     346 is mounted on the current directory, if there is one, and increments
347 the ``mnt_count``.  Finally the value in ``mou    347 the ``mnt_count``.  Finally the value in ``mount_lock`` is checked against
348 the old value.  If there is no change, then th    348 the old value.  If there is no change, then the crossing was safe.  If there
349 was a change, the ``mnt_count`` is decremented    349 was a change, the ``mnt_count`` is decremented and the whole process is
350 retried.                                          350 retried.
351                                                   351 
352 When walking up the tree (towards the root) by    352 When walking up the tree (towards the root) by following a ".." link,
353 a little more care is needed.  In this case th    353 a little more care is needed.  In this case the seqlock (which
354 contains both a counter and a spinlock) is ful    354 contains both a counter and a spinlock) is fully locked to prevent
355 any changes to any mount points while stepping    355 any changes to any mount points while stepping up.  This locking is
356 needed to stabilize the link to the mounted-on    356 needed to stabilize the link to the mounted-on dentry, which the
357 refcount on the mount itself doesn't ensure.      357 refcount on the mount itself doesn't ensure.
358                                                   358 
359 ``mount_lock`` is also used to detect and defe    359 ``mount_lock`` is also used to detect and defend against potential attacks
360 against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROO    360 against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
361 the parent directory is moved outside the root    361 the parent directory is moved outside the root, bypassing the ``path_equal()``
362 check). If ``mount_lock`` is updated during th    362 check). If ``mount_lock`` is updated during the lookup and the path encounters
363 a "..", a potential attack occurred and ``hand    363 a "..", a potential attack occurred and ``handle_dots()`` will bail out with
364 ``-EAGAIN``.                                      364 ``-EAGAIN``.
365                                                   365 
366 RCU                                               366 RCU
367 ~~~                                               367 ~~~
368                                                   368 
369 Finally the global (but extremely lightweight)    369 Finally the global (but extremely lightweight) RCU read lock is held
370 from time to time to ensure certain data struc    370 from time to time to ensure certain data structures don't get freed
371 unexpectedly.                                     371 unexpectedly.
372                                                   372 
373 In particular it is held while scanning chains    373 In particular it is held while scanning chains in the dcache hash
374 table, and the mount point hash table.            374 table, and the mount point hash table.
375                                                   375 
376 Bringing it together with ``struct nameidata``    376 Bringing it together with ``struct nameidata``
377 ----------------------------------------------    377 ----------------------------------------------
378                                                   378 
379 .. _First edition Unix: https://minnie.tuhs.or !! 379 .. _First edition Unix: http://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/u2.s
380                                                   380 
381 Throughout the process of walking a path, the     381 Throughout the process of walking a path, the current status is stored
382 in a ``struct nameidata``, "namei" being the t    382 in a ``struct nameidata``, "namei" being the traditional name - dating
383 all the way back to `First Edition Unix`_ - of    383 all the way back to `First Edition Unix`_ - of the function that
384 converts a "name" to an "inode".  ``struct nam    384 converts a "name" to an "inode".  ``struct nameidata`` contains (among
385 other fields):                                    385 other fields):
386                                                   386 
387 ``struct path path``                              387 ``struct path path``
388 ~~~~~~~~~~~~~~~~~~~~                              388 ~~~~~~~~~~~~~~~~~~~~
389                                                   389 
390 A ``path`` contains a ``struct vfsmount`` (whi    390 A ``path`` contains a ``struct vfsmount`` (which is
391 embedded in a ``struct mount``) and a ``struct    391 embedded in a ``struct mount``) and a ``struct dentry``.  Together these
392 record the current status of the walk.  They s    392 record the current status of the walk.  They start out referring to the
393 starting point (the current working directory,    393 starting point (the current working directory, the root directory, or some other
394 directory identified by a file descriptor), an    394 directory identified by a file descriptor), and are updated on each
395 step.  A reference through ``d_lockref`` and `    395 step.  A reference through ``d_lockref`` and ``mnt_count`` is always
396 held.                                             396 held.
397                                                   397 
398 ``struct qstr last``                              398 ``struct qstr last``
399 ~~~~~~~~~~~~~~~~~~~~                              399 ~~~~~~~~~~~~~~~~~~~~
400                                                   400 
401 This is a string together with a length (i.e.  !! 401 This is a string together with a length (i.e. _not_ ``nul`` terminated)
402 that is the "next" component in the pathname.     402 that is the "next" component in the pathname.
403                                                   403 
404 ``int last_type``                                 404 ``int last_type``
405 ~~~~~~~~~~~~~~~~~                                 405 ~~~~~~~~~~~~~~~~~
406                                                   406 
407 This is one of ``LAST_NORM``, ``LAST_ROOT``, ` !! 407 This is one of ``LAST_NORM``, ``LAST_ROOT``, ``LAST_DOT``, ``LAST_DOTDOT``, or
408 The ``last`` field is only valid if the type i !! 408 ``LAST_BIND``.  The ``last`` field is only valid if the type is
                                                   >> 409 ``LAST_NORM``.  ``LAST_BIND`` is used when following a symlink and no
                                                   >> 410 components of the symlink have been processed yet.  Others should be
                                                   >> 411 fairly self-explanatory.
409                                                   412 
410 ``struct path root``                              413 ``struct path root``
411 ~~~~~~~~~~~~~~~~~~~~                              414 ~~~~~~~~~~~~~~~~~~~~
412                                                   415 
413 This is used to hold a reference to the effect    416 This is used to hold a reference to the effective root of the
414 filesystem.  Often that reference won't be nee    417 filesystem.  Often that reference won't be needed, so this field is
415 only assigned the first time it is used, or wh    418 only assigned the first time it is used, or when a non-standard root
416 is requested.  Keeping a reference in the ``na    419 is requested.  Keeping a reference in the ``nameidata`` ensures that
417 only one root is in effect for the entire path    420 only one root is in effect for the entire path walk, even if it races
418 with a ``chroot()`` system call.                  421 with a ``chroot()`` system call.
419                                                   422 
420 It should be noted that in the case of ``LOOKU    423 It should be noted that in the case of ``LOOKUP_IN_ROOT`` or
421 ``LOOKUP_BENEATH``, the effective root becomes    424 ``LOOKUP_BENEATH``, the effective root becomes the directory file descriptor
422 passed to ``openat2()`` (which exposes these `    425 passed to ``openat2()`` (which exposes these ``LOOKUP_`` flags).
423                                                   426 
424 The root is needed when either of two conditio    427 The root is needed when either of two conditions holds: (1) either the
425 pathname or a symbolic link starts with a "'/'    428 pathname or a symbolic link starts with a "'/'", or (2) a "``..``"
426 component is being handled, since "``..``" fro    429 component is being handled, since "``..``" from the root must always stay
427 at the root.  The value used is usually the cu    430 at the root.  The value used is usually the current root directory of
428 the calling process.  An alternate root can be    431 the calling process.  An alternate root can be provided as when
429 ``sysctl()`` calls ``file_open_root()``, and w    432 ``sysctl()`` calls ``file_open_root()``, and when NFSv4 or Btrfs call
430 ``mount_subtree()``.  In each case a pathname     433 ``mount_subtree()``.  In each case a pathname is being looked up in a very
431 specific part of the filesystem, and the looku    434 specific part of the filesystem, and the lookup must not be allowed to
432 escape that subtree.  It works a bit like a lo    435 escape that subtree.  It works a bit like a local ``chroot()``.
433                                                   436 
434 Ignoring the handling of symbolic links, we ca    437 Ignoring the handling of symbolic links, we can now describe the
435 "``link_path_walk()``" function, which handles    438 "``link_path_walk()``" function, which handles the lookup of everything
436 except the final component as:                    439 except the final component as:
437                                                   440 
438    Given a path (``name``) and a nameidata str    441    Given a path (``name``) and a nameidata structure (``nd``), check that the
439    current directory has execute permission an    442    current directory has execute permission and then advance ``name``
440    over one component while updating ``last_ty    443    over one component while updating ``last_type`` and ``last``.  If that
441    was the final component, then return, other    444    was the final component, then return, otherwise call
442    ``walk_component()`` and repeat from the to    445    ``walk_component()`` and repeat from the top.
443                                                   446 
444 ``walk_component()`` is even easier.  If the c    447 ``walk_component()`` is even easier.  If the component is ``LAST_DOTS``,
445 it calls ``handle_dots()`` which does the nece    448 it calls ``handle_dots()`` which does the necessary locking as already
446 described.  If it finds a ``LAST_NORM`` compon    449 described.  If it finds a ``LAST_NORM`` component it first calls
447 "``lookup_fast()``" which only looks in the dc    450 "``lookup_fast()``" which only looks in the dcache, but will ask the
448 filesystem to revalidate the result if it is t    451 filesystem to revalidate the result if it is that sort of filesystem.
449 If that doesn't get a good result, it calls "`    452 If that doesn't get a good result, it calls "``lookup_slow()``" which
450 takes ``i_rwsem``, rechecks the cache, and the    453 takes ``i_rwsem``, rechecks the cache, and then asks the filesystem
451 to find a definitive answer.                   !! 454 to find a definitive answer.  Each of these will call
                                                   >> 455 ``follow_managed()`` (as described below) to handle any mount points.
452                                                   456 
453 As the last step of walk_component(), step_int !! 457 In the absence of symbolic links, ``walk_component()`` creates a new
454 directly from walk_component() or from handle_ !! 458 ``struct path`` containing a counted reference to the new dentry and a
455 handle_mounts(), to check and handle mount poi !! 459 reference to the new ``vfsmount`` which is only counted if it is
456 ``struct path`` is created containing a counte !! 460 different from the previous ``vfsmount``.  It then calls
457 a reference to the new ``vfsmount`` which is o !! 461 ``path_to_nameidata()`` to install the new ``struct path`` in the
458 different from the previous ``vfsmount``. Then !! 462 ``struct nameidata`` and drop the unneeded references.
459 a symbolic link, step_into() calls pick_link() << 
460 otherwise it installs the new ``struct path``  << 
461 drops the unneeded references.                 << 
462                                                   463 
463 This "hand-over-hand" sequencing of getting a     464 This "hand-over-hand" sequencing of getting a reference to the new
464 dentry before dropping the reference to the pr    465 dentry before dropping the reference to the previous dentry may
465 seem obvious, but is worth pointing out so tha    466 seem obvious, but is worth pointing out so that we will recognize its
466 analogue in the "RCU-walk" version.               467 analogue in the "RCU-walk" version.
467                                                   468 
468 Handling the final component                      469 Handling the final component
469 ----------------------------                      470 ----------------------------
470                                                   471 
471 ``link_path_walk()`` only walks as far as sett    472 ``link_path_walk()`` only walks as far as setting ``nd->last`` and
472 ``nd->last_type`` to refer to the final compon    473 ``nd->last_type`` to refer to the final component of the path.  It does
473 not call ``walk_component()`` that last time.     474 not call ``walk_component()`` that last time.  Handling that final
474 component remains for the caller to sort out.     475 component remains for the caller to sort out. Those callers are
475 path_lookupat(), path_parentat() and           !! 476 ``path_lookupat()``, ``path_parentat()``, ``path_mountpoint()`` and
476 path_openat() each of which handles the differ !! 477 ``path_openat()`` each of which handles the differing requirements of
477 different system calls.                           478 different system calls.
478                                                   479 
479 ``path_parentat()`` is clearly the simplest -     480 ``path_parentat()`` is clearly the simplest - it just wraps a little bit
480 of housekeeping around ``link_path_walk()`` an    481 of housekeeping around ``link_path_walk()`` and returns the parent
481 directory and final component to the caller.      482 directory and final component to the caller.  The caller will be either
482 aiming to create a name (via ``filename_create    483 aiming to create a name (via ``filename_create()``) or remove or rename
483 a name (in which case ``user_path_parent()`` i    484 a name (in which case ``user_path_parent()`` is used).  They will use
484 ``i_rwsem`` to exclude other changes while the    485 ``i_rwsem`` to exclude other changes while they validate and then
485 perform their operation.                          486 perform their operation.
486                                                   487 
487 ``path_lookupat()`` is nearly as simple - it i    488 ``path_lookupat()`` is nearly as simple - it is used when an existing
488 object is wanted such as by ``stat()`` or ``ch    489 object is wanted such as by ``stat()`` or ``chmod()``.  It essentially just
489 calls ``walk_component()`` on the final compon    490 calls ``walk_component()`` on the final component through a call to
490 ``lookup_last()``.  ``path_lookupat()`` return    491 ``lookup_last()``.  ``path_lookupat()`` returns just the final dentry.
491 It is worth noting that when flag ``LOOKUP_MOU !! 492 
492 path_lookupat() will unset LOOKUP_JUMPED in na !! 493 ``path_mountpoint()`` handles the special case of unmounting which must
493 subsequent path traversal d_weak_revalidate()  !! 494 not try to revalidate the mounted filesystem.  It effectively
494 This is important when unmounting a filesystem !! 495 contains, through a call to ``mountpoint_last()``, an alternate
                                                   >> 496 implementation of ``lookup_slow()`` which skips that step.  This is
                                                   >> 497 important when unmounting a filesystem that is inaccessible, such as
495 one provided by a dead NFS server.                498 one provided by a dead NFS server.
496                                                   499 
497 Finally ``path_openat()`` is used for the ``op    500 Finally ``path_openat()`` is used for the ``open()`` system call; it
498 contains, in support functions starting with " !! 501 contains, in support functions starting with "``do_last()``", all the
499 complexity needed to handle the different subt    502 complexity needed to handle the different subtleties of O_CREAT (with
500 or without O_EXCL), final "``/``" characters,     503 or without O_EXCL), final "``/``" characters, and trailing symbolic
501 links.  We will revisit this in the final part    504 links.  We will revisit this in the final part of this series, which
502 focuses on those symbolic links.  "open_last_l !! 505 focuses on those symbolic links.  "``do_last()``" will sometimes, but
503 not always, take ``i_rwsem``, depending on wha    506 not always, take ``i_rwsem``, depending on what it finds.
504                                                   507 
505 Each of these, or the functions which call the    508 Each of these, or the functions which call them, need to be alert to
506 the possibility that the final component is no    509 the possibility that the final component is not ``LAST_NORM``.  If the
507 goal of the lookup is to create something, the    510 goal of the lookup is to create something, then any value for
508 ``last_type`` other than ``LAST_NORM`` will re    511 ``last_type`` other than ``LAST_NORM`` will result in an error.  For
509 example if ``path_parentat()`` reports ``LAST_    512 example if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller
510 won't try to create that name.  They also chec    513 won't try to create that name.  They also check for trailing slashes
511 by testing ``last.name[last.len]``.  If there     514 by testing ``last.name[last.len]``.  If there is any character beyond
512 the final component, it must be a trailing sla    515 the final component, it must be a trailing slash.
513                                                   516 
514 Revalidation and automounts                       517 Revalidation and automounts
515 ---------------------------                       518 ---------------------------
516                                                   519 
517 Apart from symbolic links, there are only two     520 Apart from symbolic links, there are only two parts of the "REF-walk"
518 process not yet covered.  One is the handling     521 process not yet covered.  One is the handling of stale cache entries
519 and the other is automounts.                      522 and the other is automounts.
520                                                   523 
521 On filesystems that require it, the lookup rou    524 On filesystems that require it, the lookup routines will call the
522 ``->d_revalidate()`` dentry method to ensure t    525 ``->d_revalidate()`` dentry method to ensure that the cached information
523 is current.  This will often confirm validity     526 is current.  This will often confirm validity or update a few details
524 from a server.  In some cases it may find that    527 from a server.  In some cases it may find that there has been change
525 further up the path and that something that wa    528 further up the path and that something that was thought to be valid
526 previously isn't really.  When this happens th    529 previously isn't really.  When this happens the lookup of the whole
527 path is aborted and retried with the "``LOOKUP    530 path is aborted and retried with the "``LOOKUP_REVAL``" flag set.  This
528 forces revalidation to be more thorough.  We w    531 forces revalidation to be more thorough.  We will see more details of
529 this retry process in the next article.           532 this retry process in the next article.
530                                                   533 
531 Automount points are locations in the filesyst    534 Automount points are locations in the filesystem where an attempt to
532 lookup a name can trigger changes to how that     535 lookup a name can trigger changes to how that lookup should be
533 handled, in particular by mounting a filesyste    536 handled, in particular by mounting a filesystem there.  These are
534 covered in greater detail in autofs.txt in the    537 covered in greater detail in autofs.txt in the Linux documentation
535 tree, but a few notes specifically related to     538 tree, but a few notes specifically related to path lookup are in order
536 here.                                             539 here.
537                                                   540 
538 The Linux VFS has a concept of "managed" dentr !! 541 The Linux VFS has a concept of "managed" dentries which is reflected
                                                   >> 542 in function names such as "``follow_managed()``".  There are three
539 potentially interesting things about these den    543 potentially interesting things about these dentries corresponding
540 to three different flags that might be set in     544 to three different flags that might be set in ``dentry->d_flags``:
541                                                   545 
542 ``DCACHE_MANAGE_TRANSIT``                         546 ``DCACHE_MANAGE_TRANSIT``
543 ~~~~~~~~~~~~~~~~~~~~~~~~~                         547 ~~~~~~~~~~~~~~~~~~~~~~~~~
544                                                   548 
545 If this flag has been set, then the filesystem    549 If this flag has been set, then the filesystem has requested that the
546 ``d_manage()`` dentry operation be called befo    550 ``d_manage()`` dentry operation be called before handling any possible
547 mount point.  This can perform two particular     551 mount point.  This can perform two particular services:
548                                                   552 
549 It can block to avoid races.  If an automount     553 It can block to avoid races.  If an automount point is being
550 unmounted, the ``d_manage()`` function will us    554 unmounted, the ``d_manage()`` function will usually wait for that
551 process to complete before letting the new loo    555 process to complete before letting the new lookup proceed and possibly
552 trigger a new automount.                          556 trigger a new automount.
553                                                   557 
554 It can selectively allow only some processes t    558 It can selectively allow only some processes to transit through a
555 mount point.  When a server process is managin    559 mount point.  When a server process is managing automounts, it may
556 need to access a directory without triggering     560 need to access a directory without triggering normal automount
557 processing.  That server process can identify     561 processing.  That server process can identify itself to the ``autofs``
558 filesystem, which will then give it a special     562 filesystem, which will then give it a special pass through
559 ``d_manage()`` by returning ``-EISDIR``.          563 ``d_manage()`` by returning ``-EISDIR``.
560                                                   564 
561 ``DCACHE_MOUNTED``                                565 ``DCACHE_MOUNTED``
562 ~~~~~~~~~~~~~~~~~~                                566 ~~~~~~~~~~~~~~~~~~
563                                                   567 
564 This flag is set on every dentry that is mount    568 This flag is set on every dentry that is mounted on.  As Linux
565 supports multiple filesystem namespaces, it is    569 supports multiple filesystem namespaces, it is possible that the
566 dentry may not be mounted on in *this* namespa    570 dentry may not be mounted on in *this* namespace, just in some
567 other.  So this flag is seen as a hint, not a     571 other.  So this flag is seen as a hint, not a promise.
568                                                   572 
569 If this flag is set, and ``d_manage()`` didn't    573 If this flag is set, and ``d_manage()`` didn't return ``-EISDIR``,
570 ``lookup_mnt()`` is called to examine the moun    574 ``lookup_mnt()`` is called to examine the mount hash table (honoring the
571 ``mount_lock`` described earlier) and possibly    575 ``mount_lock`` described earlier) and possibly return a new ``vfsmount``
572 and a new ``dentry`` (both with counted refere    576 and a new ``dentry`` (both with counted references).
573                                                   577 
574 ``DCACHE_NEED_AUTOMOUNT``                         578 ``DCACHE_NEED_AUTOMOUNT``
575 ~~~~~~~~~~~~~~~~~~~~~~~~~                         579 ~~~~~~~~~~~~~~~~~~~~~~~~~
576                                                   580 
577 If ``d_manage()`` allowed us to get this far,     581 If ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't
578 find a mount point, then this flag causes the     582 find a mount point, then this flag causes the ``d_automount()`` dentry
579 operation to be called.                           583 operation to be called.
580                                                   584 
581 The ``d_automount()`` operation can be arbitra    585 The ``d_automount()`` operation can be arbitrarily complex and may
582 communicate with server processes etc. but it     586 communicate with server processes etc. but it should ultimately either
583 report that there was an error, that there was    587 report that there was an error, that there was nothing to mount, or
584 should provide an updated ``struct path`` with    588 should provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``.
585                                                   589 
586 In the latter case, ``finish_automount()`` wil    590 In the latter case, ``finish_automount()`` will be called to safely
587 install the new mount point into the mount tab    591 install the new mount point into the mount table.
588                                                   592 
589 There is no new locking of import here and it     593 There is no new locking of import here and it is important that no
590 locks (only counted references) are held over     594 locks (only counted references) are held over this processing due to
591 the very real possibility of extended delays.     595 the very real possibility of extended delays.
592 This will become more important next time when    596 This will become more important next time when we examine RCU-walk
593 which is particularly sensitive to delays.        597 which is particularly sensitive to delays.
594                                                   598 
595 RCU-walk - faster pathname lookup in Linux        599 RCU-walk - faster pathname lookup in Linux
596 ==========================================        600 ==========================================
597                                                   601 
598 RCU-walk is another algorithm for performing p    602 RCU-walk is another algorithm for performing pathname lookup in Linux.
599 It is in many ways similar to REF-walk and the    603 It is in many ways similar to REF-walk and the two share quite a bit
600 of code.  The significant difference in RCU-wa    604 of code.  The significant difference in RCU-walk is how it allows for
601 the possibility of concurrent access.             605 the possibility of concurrent access.
602                                                   606 
603 We noted that REF-walk is complex because ther    607 We noted that REF-walk is complex because there are numerous details
604 and special cases.  RCU-walk reduces this comp    608 and special cases.  RCU-walk reduces this complexity by simply
605 refusing to handle a number of cases -- it ins    609 refusing to handle a number of cases -- it instead falls back to
606 REF-walk.  The difficulty with RCU-walk comes     610 REF-walk.  The difficulty with RCU-walk comes from a different
607 direction: unfamiliarity.  The locking rules w    611 direction: unfamiliarity.  The locking rules when depending on RCU are
608 quite different from traditional locking, so w    612 quite different from traditional locking, so we will spend a little extra
609 time when we come to those.                       613 time when we come to those.
610                                                   614 
611 Clear demarcation of roles                        615 Clear demarcation of roles
612 --------------------------                        616 --------------------------
613                                                   617 
614 The easiest way to manage concurrency is to fo    618 The easiest way to manage concurrency is to forcibly stop any other
615 thread from changing the data structures that     619 thread from changing the data structures that a given thread is
616 looking at.  In cases where no other thread wo    620 looking at.  In cases where no other thread would even think of
617 changing the data and lots of different thread    621 changing the data and lots of different threads want to read at the
618 same time, this can be very costly.  Even when    622 same time, this can be very costly.  Even when using locks that permit
619 multiple concurrent readers, the simple act of    623 multiple concurrent readers, the simple act of updating the count of
620 the number of current readers can impose an un    624 the number of current readers can impose an unwanted cost.  So the
621 goal when reading a shared data structure that    625 goal when reading a shared data structure that no other process is
622 changing is to avoid writing anything to memor    626 changing is to avoid writing anything to memory at all.  Take no
623 locks, increment no counts, leave no footprint    627 locks, increment no counts, leave no footprints.
624                                                   628 
625 The REF-walk mechanism already described certa    629 The REF-walk mechanism already described certainly doesn't follow this
626 principle, but then it is really designed to w    630 principle, but then it is really designed to work when there may well
627 be other threads modifying the data.  RCU-walk    631 be other threads modifying the data.  RCU-walk, in contrast, is
628 designed for the common situation where there     632 designed for the common situation where there are lots of frequent
629 readers and only occasional writers.  This may    633 readers and only occasional writers.  This may not be common in all
630 parts of the filesystem tree, but in many part    634 parts of the filesystem tree, but in many parts it will be.  For the
631 other parts it is important that RCU-walk can     635 other parts it is important that RCU-walk can quickly fall back to
632 using REF-walk.                                   636 using REF-walk.
633                                                   637 
634 Pathname lookup always starts in RCU-walk mode    638 Pathname lookup always starts in RCU-walk mode but only remains there
635 as long as what it is looking for is in the ca    639 as long as what it is looking for is in the cache and is stable.  It
636 dances lightly down the cached filesystem imag    640 dances lightly down the cached filesystem image, leaving no footprints
637 and carefully watching where it is, to be sure    641 and carefully watching where it is, to be sure it doesn't trip.  If it
638 notices that something has changed or is chang    642 notices that something has changed or is changing, or if something
639 isn't in the cache, then it tries to stop grac    643 isn't in the cache, then it tries to stop gracefully and switch to
640 REF-walk.                                         644 REF-walk.
641                                                   645 
642 This stopping requires getting a counted refer    646 This stopping requires getting a counted reference on the current
643 ``vfsmount`` and ``dentry``, and ensuring that    647 ``vfsmount`` and ``dentry``, and ensuring that these are still valid -
644 that a path walk with REF-walk would have foun    648 that a path walk with REF-walk would have found the same entries.
645 This is an invariant that RCU-walk must guaran    649 This is an invariant that RCU-walk must guarantee.  It can only make
646 decisions, such as selecting the next step, th    650 decisions, such as selecting the next step, that are decisions which
647 REF-walk could also have made if it were walki    651 REF-walk could also have made if it were walking down the tree at the
648 same time.  If the graceful stop succeeds, the    652 same time.  If the graceful stop succeeds, the rest of the path is
649 processed with the reliable, if slightly slugg    653 processed with the reliable, if slightly sluggish, REF-walk.  If
650 RCU-walk finds it cannot stop gracefully, it s    654 RCU-walk finds it cannot stop gracefully, it simply gives up and
651 restarts from the top with REF-walk.              655 restarts from the top with REF-walk.
652                                                   656 
653 This pattern of "try RCU-walk, if that fails t    657 This pattern of "try RCU-walk, if that fails try REF-walk" can be
654 clearly seen in functions like filename_lookup !! 658 clearly seen in functions like ``filename_lookup()``,
655 filename_parentat(),                           !! 659 ``filename_parentat()``, ``filename_mountpoint()``,
656 do_filp_open(), and do_file_open_root().  Thes !! 660 ``do_filp_open()``, and ``do_file_open_root()``.  These five
657 correspond roughly to the three ``path_*()`` f !! 661 correspond roughly to the four ``path_``* functions we met earlier,
658 each of which calls ``link_path_walk()``.  The !! 662 each of which calls ``link_path_walk()``.  The ``path_*`` functions are
659 called using different mode flags until a mode    663 called using different mode flags until a mode is found which works.
660 They are first called with ``LOOKUP_RCU`` set     664 They are first called with ``LOOKUP_RCU`` set to request "RCU-walk".  If
661 that fails with the error ``ECHILD`` they are     665 that fails with the error ``ECHILD`` they are called again with no
662 special flag to request "REF-walk".  If either    666 special flag to request "REF-walk".  If either of those report the
663 error ``ESTALE`` a final attempt is made with     667 error ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no
664 ``LOOKUP_RCU``) to ensure that entries found i    668 ``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly
665 revalidated - normally entries are only revali    669 revalidated - normally entries are only revalidated if the filesystem
666 determines that they are too old to trust.        670 determines that they are too old to trust.
667                                                   671 
668 The ``LOOKUP_RCU`` attempt may drop that flag     672 The ``LOOKUP_RCU`` attempt may drop that flag internally and switch to
669 REF-walk, but will never then try to switch ba    673 REF-walk, but will never then try to switch back to RCU-walk.  Places
670 that trip up RCU-walk are much more likely to     674 that trip up RCU-walk are much more likely to be near the leaves and
671 so it is very unlikely that there will be much    675 so it is very unlikely that there will be much, if any, benefit from
672 switching back.                                   676 switching back.
673                                                   677 
674 RCU and seqlocks: fast and light                  678 RCU and seqlocks: fast and light
675 --------------------------------                  679 --------------------------------
676                                                   680 
677 RCU is, unsurprisingly, critical to RCU-walk m    681 RCU is, unsurprisingly, critical to RCU-walk mode.  The
678 ``rcu_read_lock()`` is held for the entire tim    682 ``rcu_read_lock()`` is held for the entire time that RCU-walk is walking
679 down a path.  The particular guarantee it prov    683 down a path.  The particular guarantee it provides is that the key
680 data structures - dentries, inodes, super_bloc    684 data structures - dentries, inodes, super_blocks, and mounts - will
681 not be freed while the lock is held.  They mig    685 not be freed while the lock is held.  They might be unlinked or
682 invalidated in one way or another, but the mem    686 invalidated in one way or another, but the memory will not be
683 repurposed so values in various fields will st    687 repurposed so values in various fields will still be meaningful.  This
684 is the only guarantee that RCU provides; every    688 is the only guarantee that RCU provides; everything else is done using
685 seqlocks.                                         689 seqlocks.
686                                                   690 
687 As we saw above, REF-walk holds a counted refe    691 As we saw above, REF-walk holds a counted reference to the current
688 dentry and the current vfsmount, and does not     692 dentry and the current vfsmount, and does not release those references
689 before taking references to the "next" dentry     693 before taking references to the "next" dentry or vfsmount.  It also
690 sometimes takes the ``d_lock`` spinlock.  Thes    694 sometimes takes the ``d_lock`` spinlock.  These references and locks are
691 taken to prevent certain changes from happenin    695 taken to prevent certain changes from happening.  RCU-walk must not
692 take those references or locks and so cannot p    696 take those references or locks and so cannot prevent such changes.
693 Instead, it checks to see if a change has been    697 Instead, it checks to see if a change has been made, and aborts or
694 retries if it has.                                698 retries if it has.
695                                                   699 
696 To preserve the invariant mentioned above (tha    700 To preserve the invariant mentioned above (that RCU-walk may only make
697 decisions that REF-walk could have made), it m    701 decisions that REF-walk could have made), it must make the checks at
698 or near the same places that REF-walk holds th    702 or near the same places that REF-walk holds the references.  So, when
699 REF-walk increments a reference count or takes    703 REF-walk increments a reference count or takes a spinlock, RCU-walk
700 samples the status of a seqlock using ``read_s    704 samples the status of a seqlock using ``read_seqcount_begin()`` or a
701 similar function.  When REF-walk decrements th    705 similar function.  When REF-walk decrements the count or drops the
702 lock, RCU-walk checks if the sampled status is    706 lock, RCU-walk checks if the sampled status is still valid using
703 ``read_seqcount_retry()`` or similar.             707 ``read_seqcount_retry()`` or similar.
704                                                   708 
705 However, there is a little bit more to seqlock    709 However, there is a little bit more to seqlocks than that.  If
706 RCU-walk accesses two different fields in a se    710 RCU-walk accesses two different fields in a seqlock-protected
707 structure, or accesses the same field twice, t    711 structure, or accesses the same field twice, there is no a priori
708 guarantee of any consistency between those acc    712 guarantee of any consistency between those accesses.  When consistency
709 is needed - which it usually is - RCU-walk mus    713 is needed - which it usually is - RCU-walk must take a copy and then
710 use ``read_seqcount_retry()`` to validate that    714 use ``read_seqcount_retry()`` to validate that copy.
711                                                   715 
712 ``read_seqcount_retry()`` not only checks the     716 ``read_seqcount_retry()`` not only checks the sequence number, but also
713 imposes a memory barrier so that no memory-rea    717 imposes a memory barrier so that no memory-read instruction from
714 *before* the call can be delayed until *after*    718 *before* the call can be delayed until *after* the call, either by the
715 CPU or by the compiler.  A simple example of t    719 CPU or by the compiler.  A simple example of this can be seen in
716 ``slow_dentry_cmp()`` which, for filesystems w    720 ``slow_dentry_cmp()`` which, for filesystems which do not use simple
717 byte-wise name equality, calls into the filesy    721 byte-wise name equality, calls into the filesystem to compare a name
718 against a dentry.  The length and name pointer    722 against a dentry.  The length and name pointer are copied into local
719 variables, then ``read_seqcount_retry()`` is c    723 variables, then ``read_seqcount_retry()`` is called to confirm the two
720 are consistent, and only then is ``->d_compare    724 are consistent, and only then is ``->d_compare()`` called.  When
721 standard filename comparison is used, ``dentry    725 standard filename comparison is used, ``dentry_cmp()`` is called
722 instead.  Notably it does *not* use ``read_seq !! 726 instead.  Notably it does _not_ use ``read_seqcount_retry()``, but
723 instead has a large comment explaining why the    727 instead has a large comment explaining why the consistency guarantee
724 isn't necessary.  A subsequent ``read_seqcount    728 isn't necessary.  A subsequent ``read_seqcount_retry()`` will be
725 sufficient to catch any problem that could occ    729 sufficient to catch any problem that could occur at this point.
726                                                   730 
727 With that little refresher on seqlocks out of     731 With that little refresher on seqlocks out of the way we can look at
728 the bigger picture of how RCU-walk uses seqloc    732 the bigger picture of how RCU-walk uses seqlocks.
729                                                   733 
730 ``mount_lock`` and ``nd->m_seq``                  734 ``mount_lock`` and ``nd->m_seq``
731 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                  735 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
732                                                   736 
733 We already met the ``mount_lock`` seqlock when    737 We already met the ``mount_lock`` seqlock when REF-walk used it to
734 ensure that crossing a mount point is performe    738 ensure that crossing a mount point is performed safely.  RCU-walk uses
735 it for that too, but for quite a bit more.        739 it for that too, but for quite a bit more.
736                                                   740 
737 Instead of taking a counted reference to each     741 Instead of taking a counted reference to each ``vfsmount`` as it
738 descends the tree, RCU-walk samples the state     742 descends the tree, RCU-walk samples the state of ``mount_lock`` at the
739 start of the walk and stores this initial sequ    743 start of the walk and stores this initial sequence number in the
740 ``struct nameidata`` in the ``m_seq`` field.      744 ``struct nameidata`` in the ``m_seq`` field.  This one lock and one
741 sequence number are used to validate all acces    745 sequence number are used to validate all accesses to all ``vfsmounts``,
742 and all mount point crossings.  As changes to     746 and all mount point crossings.  As changes to the mount table are
743 relatively rare, it is reasonable to fall back    747 relatively rare, it is reasonable to fall back on REF-walk any time
744 that any "mount" or "unmount" happens.            748 that any "mount" or "unmount" happens.
745                                                   749 
746 ``m_seq`` is checked (using ``read_seqretry()`    750 ``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk
747 sequence, whether switching to REF-walk for th    751 sequence, whether switching to REF-walk for the rest of the path or
748 when the end of the path is reached.  It is al    752 when the end of the path is reached.  It is also checked when stepping
749 down over a mount point (in ``__follow_mount_r    753 down over a mount point (in ``__follow_mount_rcu()``) or up (in
750 ``follow_dotdot_rcu()``).  If it is ever found    754 ``follow_dotdot_rcu()``).  If it is ever found to have changed, the
751 whole RCU-walk sequence is aborted and the pat    755 whole RCU-walk sequence is aborted and the path is processed again by
752 REF-walk.                                         756 REF-walk.
753                                                   757 
754 If RCU-walk finds that ``mount_lock`` hasn't c    758 If RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure
755 that, had REF-walk taken counted references on    759 that, had REF-walk taken counted references on each vfsmount, the
756 results would have been the same.  This ensure    760 results would have been the same.  This ensures the invariant holds,
757 at least for vfsmount structures.                 761 at least for vfsmount structures.
758                                                   762 
759 ``dentry->d_seq`` and ``nd->seq``                 763 ``dentry->d_seq`` and ``nd->seq``
760 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                 764 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
761                                                   765 
762 In place of taking a count or lock on ``d_refl    766 In place of taking a count or lock on ``d_reflock``, RCU-walk samples
763 the per-dentry ``d_seq`` seqlock, and stores t    767 the per-dentry ``d_seq`` seqlock, and stores the sequence number in the
764 ``seq`` field of the nameidata structure, so `    768 ``seq`` field of the nameidata structure, so ``nd->seq`` should always be
765 the current sequence number of ``nd->dentry``.    769 the current sequence number of ``nd->dentry``.  This number needs to be
766 revalidated after copying, and before using, t    770 revalidated after copying, and before using, the name, parent, or
767 inode of the dentry.                              771 inode of the dentry.
768                                                   772 
769 The handling of the name we have already looke    773 The handling of the name we have already looked at, and the parent is
770 only accessed in ``follow_dotdot_rcu()`` which    774 only accessed in ``follow_dotdot_rcu()`` which fairly trivially follows
771 the required pattern, though it does so for th    775 the required pattern, though it does so for three different cases.
772                                                   776 
773 When not at a mount point, ``d_parent`` is fol    777 When not at a mount point, ``d_parent`` is followed and its ``d_seq`` is
774 collected.  When we are at a mount point, we i    778 collected.  When we are at a mount point, we instead follow the
775 ``mnt->mnt_mountpoint`` link to get a new dent    779 ``mnt->mnt_mountpoint`` link to get a new dentry and collect its
776 ``d_seq``.  Then, after finally finding a ``d_    780 ``d_seq``.  Then, after finally finding a ``d_parent`` to follow, we must
777 check if we have landed on a mount point and,     781 check if we have landed on a mount point and, if so, must find that
778 mount point and follow the ``mnt->mnt_root`` l    782 mount point and follow the ``mnt->mnt_root`` link.  This would imply a
779 somewhat unusual, but certainly possible, circ    783 somewhat unusual, but certainly possible, circumstance where the
780 starting point of the path lookup was in part     784 starting point of the path lookup was in part of the filesystem that
781 was mounted on, and so not visible from the ro    785 was mounted on, and so not visible from the root.
782                                                   786 
783 The inode pointer, stored in ``->d_inode``, is    787 The inode pointer, stored in ``->d_inode``, is a little more
784 interesting.  The inode will always need to be    788 interesting.  The inode will always need to be accessed at least
785 twice, once to determine if it is NULL and onc    789 twice, once to determine if it is NULL and once to verify access
786 permissions.  Symlink handling requires a vali    790 permissions.  Symlink handling requires a validated inode pointer too.
787 Rather than revalidating on each access, a cop    791 Rather than revalidating on each access, a copy is made on the first
788 access and it is stored in the ``inode`` field    792 access and it is stored in the ``inode`` field of ``nameidata`` from where
789 it can be safely accessed without further vali    793 it can be safely accessed without further validation.
790                                                   794 
791 ``lookup_fast()`` is the only lookup routine t    795 ``lookup_fast()`` is the only lookup routine that is used in RCU-mode,
792 ``lookup_slow()`` being too slow and requiring    796 ``lookup_slow()`` being too slow and requiring locks.  It is in
793 ``lookup_fast()`` that we find the important "    797 ``lookup_fast()`` that we find the important "hand over hand" tracking
794 of the current dentry.                            798 of the current dentry.
795                                                   799 
796 The current ``dentry`` and current ``seq`` num    800 The current ``dentry`` and current ``seq`` number are passed to
797 ``__d_lookup_rcu()`` which, on success, return    801 ``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a
798 new ``seq`` number.  ``lookup_fast()`` then co    802 new ``seq`` number.  ``lookup_fast()`` then copies the inode pointer and
799 revalidates the new ``seq`` number.  It then v    803 revalidates the new ``seq`` number.  It then validates the old ``dentry``
800 with the old ``seq`` number one last time and     804 with the old ``seq`` number one last time and only then continues.  This
801 process of getting the ``seq`` number of the n    805 process of getting the ``seq`` number of the new dentry and then
802 checking the ``seq`` number of the old exactly    806 checking the ``seq`` number of the old exactly mirrors the process of
803 getting a counted reference to the new dentry     807 getting a counted reference to the new dentry before dropping that for
804 the old dentry which we saw in REF-walk.          808 the old dentry which we saw in REF-walk.
805                                                   809 
806 No ``inode->i_rwsem`` or even ``rename_lock``     810 No ``inode->i_rwsem`` or even ``rename_lock``
807 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     811 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
808                                                   812 
809 A semaphore is a fairly heavyweight lock that     813 A semaphore is a fairly heavyweight lock that can only be taken when it is
810 permissible to sleep.  As ``rcu_read_lock()``     814 permissible to sleep.  As ``rcu_read_lock()`` forbids sleeping,
811 ``inode->i_rwsem`` plays no role in RCU-walk.     815 ``inode->i_rwsem`` plays no role in RCU-walk.  If some other thread does
812 take ``i_rwsem`` and modifies the directory in    816 take ``i_rwsem`` and modifies the directory in a way that RCU-walk needs
813 to notice, the result will be either that RCU-    817 to notice, the result will be either that RCU-walk fails to find the
814 dentry that it is looking for, or it will find    818 dentry that it is looking for, or it will find a dentry which
815 ``read_seqretry()`` won't validate.  In either    819 ``read_seqretry()`` won't validate.  In either case it will drop down to
816 REF-walk mode which can take whatever locks ar    820 REF-walk mode which can take whatever locks are needed.
817                                                   821 
818 Though ``rename_lock`` could be used by RCU-wa    822 Though ``rename_lock`` could be used by RCU-walk as it doesn't require
819 any sleeping, RCU-walk doesn't bother.  REF-wa    823 any sleeping, RCU-walk doesn't bother.  REF-walk uses ``rename_lock`` to
820 protect against the possibility of hash chains    824 protect against the possibility of hash chains in the dcache changing
821 while they are being searched.  This can resul    825 while they are being searched.  This can result in failing to find
822 something that actually is there.  When RCU-wa    826 something that actually is there.  When RCU-walk fails to find
823 something in the dentry cache, whether it is r    827 something in the dentry cache, whether it is really there or not, it
824 already drops down to REF-walk and tries again    828 already drops down to REF-walk and tries again with appropriate
825 locking.  This neatly handles all cases, so ad    829 locking.  This neatly handles all cases, so adding extra checks on
826 rename_lock would bring no significant value.     830 rename_lock would bring no significant value.
827                                                   831 
828 ``unlazy walk()`` and ``complete_walk()``         832 ``unlazy walk()`` and ``complete_walk()``
829 -----------------------------------------         833 -----------------------------------------
830                                                   834 
831 That "dropping down to REF-walk" typically inv    835 That "dropping down to REF-walk" typically involves a call to
832 ``unlazy_walk()``, so named because "RCU-walk"    836 ``unlazy_walk()``, so named because "RCU-walk" is also sometimes
833 referred to as "lazy walk".  ``unlazy_walk()``    837 referred to as "lazy walk".  ``unlazy_walk()`` is called when
834 following the path down to the current vfsmoun    838 following the path down to the current vfsmount/dentry pair seems to
835 have proceeded successfully, but the next step    839 have proceeded successfully, but the next step is problematic.  This
836 can happen if the next name cannot be found in    840 can happen if the next name cannot be found in the dcache, if
837 permission checking or name revalidation could    841 permission checking or name revalidation couldn't be achieved while
838 the ``rcu_read_lock()`` is held (which forbids    842 the ``rcu_read_lock()`` is held (which forbids sleeping), if an
839 automount point is found, or in a couple of ca    843 automount point is found, or in a couple of cases involving symlinks.
840 It is also called from ``complete_walk()`` whe    844 It is also called from ``complete_walk()`` when the lookup has reached
841 the final component, or the very end of the pa    845 the final component, or the very end of the path, depending on which
842 particular flavor of lookup is used.              846 particular flavor of lookup is used.
843                                                   847 
844 Other reasons for dropping out of RCU-walk tha    848 Other reasons for dropping out of RCU-walk that do not trigger a call
845 to ``unlazy_walk()`` are when some inconsisten    849 to ``unlazy_walk()`` are when some inconsistency is found that cannot be
846 handled immediately, such as ``mount_lock`` or    850 handled immediately, such as ``mount_lock`` or one of the ``d_seq``
847 seqlocks reporting a change.  In these cases t    851 seqlocks reporting a change.  In these cases the relevant function
848 will return ``-ECHILD`` which will percolate u    852 will return ``-ECHILD`` which will percolate up until it triggers a new
849 attempt from the top using REF-walk.              853 attempt from the top using REF-walk.
850                                                   854 
851 For those cases where ``unlazy_walk()`` is an     855 For those cases where ``unlazy_walk()`` is an option, it essentially
852 takes a reference on each of the pointers that    856 takes a reference on each of the pointers that it holds (vfsmount,
853 dentry, and possibly some symbolic links) and     857 dentry, and possibly some symbolic links) and then verifies that the
854 relevant seqlocks have not been changed.  If t    858 relevant seqlocks have not been changed.  If there have been changes,
855 it, too, aborts with ``-ECHILD``, otherwise th    859 it, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk
856 has been a success and the lookup process cont    860 has been a success and the lookup process continues.
857                                                   861 
858 Taking a reference on those pointers is not qu    862 Taking a reference on those pointers is not quite as simple as just
859 incrementing a counter.  That works to take a     863 incrementing a counter.  That works to take a second reference if you
860 already have one (often indirectly through ano    864 already have one (often indirectly through another object), but it
861 isn't sufficient if you don't actually have a     865 isn't sufficient if you don't actually have a counted reference at
862 all.  For ``dentry->d_lockref``, it is safe to    866 all.  For ``dentry->d_lockref``, it is safe to increment the reference
863 counter to get a reference unless it has been     867 counter to get a reference unless it has been explicitly marked as
864 "dead" which involves setting the counter to `    868 "dead" which involves setting the counter to ``-128``.
865 ``lockref_get_not_dead()`` achieves this.         869 ``lockref_get_not_dead()`` achieves this.
866                                                   870 
867 For ``mnt->mnt_count`` it is safe to take a re    871 For ``mnt->mnt_count`` it is safe to take a reference as long as
868 ``mount_lock`` is then used to validate the re    872 ``mount_lock`` is then used to validate the reference.  If that
869 validation fails, it may *not* be safe to just    873 validation fails, it may *not* be safe to just drop that reference in
870 the standard way of calling ``mnt_put()`` - an    874 the standard way of calling ``mnt_put()`` - an unmount may have
871 progressed too far.  So the code in ``legitimi    875 progressed too far.  So the code in ``legitimize_mnt()``, when it
872 finds that the reference it got might not be s    876 finds that the reference it got might not be safe, checks the
873 ``MNT_SYNC_UMOUNT`` flag to determine if a sim    877 ``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is
874 correct, or if it should just decrement the co    878 correct, or if it should just decrement the count and pretend none of
875 this ever happened.                               879 this ever happened.
876                                                   880 
877 Taking care in filesystems                        881 Taking care in filesystems
878 --------------------------                        882 --------------------------
879                                                   883 
880 RCU-walk depends almost entirely on cached inf    884 RCU-walk depends almost entirely on cached information and often will
881 not call into the filesystem at all.  However     885 not call into the filesystem at all.  However there are two places,
882 besides the already-mentioned component-name c    886 besides the already-mentioned component-name comparison, where the
883 file system might be included in RCU-walk, and    887 file system might be included in RCU-walk, and it must know to be
884 careful.                                          888 careful.
885                                                   889 
886 If the filesystem has non-standard permission-    890 If the filesystem has non-standard permission-checking requirements -
887 such as a networked filesystem which may need     891 such as a networked filesystem which may need to check with the server
888 - the ``i_op->permission`` interface might be     892 - the ``i_op->permission`` interface might be called during RCU-walk.
889 In this case an extra "``MAY_NOT_BLOCK``" flag    893 In this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it
890 knows not to sleep, but to return ``-ECHILD``     894 knows not to sleep, but to return ``-ECHILD`` if it cannot complete
891 promptly.  ``i_op->permission`` is given the i    895 promptly.  ``i_op->permission`` is given the inode pointer, not the
892 dentry, so it doesn't need to worry about furt    896 dentry, so it doesn't need to worry about further consistency checks.
893 However if it accesses any other filesystem da    897 However if it accesses any other filesystem data structures, it must
894 ensure they are safe to be accessed with only     898 ensure they are safe to be accessed with only the ``rcu_read_lock()``
895 held.  This typically means they must be freed    899 held.  This typically means they must be freed using ``kfree_rcu()`` or
896 similar.                                          900 similar.
897                                                   901 
898 .. _READ_ONCE: https://lwn.net/Articles/624126    902 .. _READ_ONCE: https://lwn.net/Articles/624126/
899                                                   903 
900 If the filesystem may need to revalidate dcach    904 If the filesystem may need to revalidate dcache entries, then
901 ``d_op->d_revalidate`` may be called in RCU-wa    905 ``d_op->d_revalidate`` may be called in RCU-walk too.  This interface
902 *is* passed the dentry but does not have acces    906 *is* passed the dentry but does not have access to the ``inode`` or the
903 ``seq`` number from the ``nameidata``, so it n    907 ``seq`` number from the ``nameidata``, so it needs to be extra careful
904 when accessing fields in the dentry.  This "ex    908 when accessing fields in the dentry.  This "extra care" typically
905 involves using  `READ_ONCE() <READ_ONCE_>`_ to    909 involves using  `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the
906 result is not NULL before using it.  This patt    910 result is not NULL before using it.  This pattern can be seen in
907 ``nfs_lookup_revalidate()``.                      911 ``nfs_lookup_revalidate()``.
908                                                   912 
909 A pair of patterns                                913 A pair of patterns
910 ------------------                                914 ------------------
911                                                   915 
912 In various places in the details of REF-walk a    916 In various places in the details of REF-walk and RCU-walk, and also in
913 the big picture, there are a couple of related    917 the big picture, there are a couple of related patterns that are worth
914 being aware of.                                   918 being aware of.
915                                                   919 
916 The first is "try quickly and check, if that f    920 The first is "try quickly and check, if that fails try slowly".  We
917 can see that in the high-level approach of fir    921 can see that in the high-level approach of first trying RCU-walk and
918 then trying REF-walk, and in places where ``un    922 then trying REF-walk, and in places where ``unlazy_walk()`` is used to
919 switch to REF-walk for the rest of the path.      923 switch to REF-walk for the rest of the path.  We also saw it earlier
920 in ``dget_parent()`` when following a "``..``"    924 in ``dget_parent()`` when following a "``..``" link.  It tries a quick way
921 to get a reference, then falls back to taking     925 to get a reference, then falls back to taking locks if needed.
922                                                   926 
923 The second pattern is "try quickly and check,     927 The second pattern is "try quickly and check, if that fails try
924 again - repeatedly".  This is seen with the us    928 again - repeatedly".  This is seen with the use of ``rename_lock`` and
925 ``mount_lock`` in REF-walk.  RCU-walk doesn't     929 ``mount_lock`` in REF-walk.  RCU-walk doesn't make use of this pattern -
926 if anything goes wrong it is much safer to jus    930 if anything goes wrong it is much safer to just abort and try a more
927 sedate approach.                                  931 sedate approach.
928                                                   932 
929 The emphasis here is "try quickly and check".     933 The emphasis here is "try quickly and check".  It should probably be
930 "try quickly *and carefully*, then check".  Th !! 934 "try quickly _and carefully,_ then check".  The fact that checking is
931 needed is a reminder that the system is dynami    935 needed is a reminder that the system is dynamic and only a limited
932 number of things are safe at all.  The most li    936 number of things are safe at all.  The most likely cause of errors in
933 this whole process is assuming something is sa    937 this whole process is assuming something is safe when in reality it
934 isn't.  Careful consideration of what exactly     938 isn't.  Careful consideration of what exactly guarantees the safety of
935 each access is sometimes necessary.               939 each access is sometimes necessary.
936                                                   940 
937 A walk among the symlinks                         941 A walk among the symlinks
938 =========================                         942 =========================
939                                                   943 
940 There are several basic issues that we will ex    944 There are several basic issues that we will examine to understand the
941 handling of symbolic links:  the symlink stack    945 handling of symbolic links:  the symlink stack, together with cache
942 lifetimes, will help us understand the overall    946 lifetimes, will help us understand the overall recursive handling of
943 symlinks and lead to the special care needed f    947 symlinks and lead to the special care needed for the final component.
944 Then a consideration of access-time updates an    948 Then a consideration of access-time updates and summary of the various
945 flags controlling lookup will finish the story    949 flags controlling lookup will finish the story.
946                                                   950 
947 The symlink stack                                 951 The symlink stack
948 -----------------                                 952 -----------------
949                                                   953 
950 There are only two sorts of filesystem objects    954 There are only two sorts of filesystem objects that can usefully
951 appear in a path prior to the final component:    955 appear in a path prior to the final component: directories and symlinks.
952 Handling directories is quite straightforward:    956 Handling directories is quite straightforward: the new directory
953 simply becomes the starting point at which to     957 simply becomes the starting point at which to interpret the next
954 component on the path.  Handling symbolic link    958 component on the path.  Handling symbolic links requires a bit more
955 work.                                             959 work.
956                                                   960 
957 Conceptually, symbolic links could be handled     961 Conceptually, symbolic links could be handled by editing the path.  If
958 a component name refers to a symbolic link, th    962 a component name refers to a symbolic link, then that component is
959 replaced by the body of the link and, if that     963 replaced by the body of the link and, if that body starts with a '/',
960 then all preceding parts of the path are disca    964 then all preceding parts of the path are discarded.  This is what the
961 "``readlink -f``" command does, though it also    965 "``readlink -f``" command does, though it also edits out "``.``" and
962 "``..``" components.                              966 "``..``" components.
963                                                   967 
964 Directly editing the path string is not really    968 Directly editing the path string is not really necessary when looking
965 up a path, and discarding early components is     969 up a path, and discarding early components is pointless as they aren't
966 looked at anyway.  Keeping track of all remain    970 looked at anyway.  Keeping track of all remaining components is
967 important, but they can of course be kept sepa    971 important, but they can of course be kept separately; there is no need
968 to concatenate them.  As one symlink may easil    972 to concatenate them.  As one symlink may easily refer to another,
969 which in turn can refer to a third, we may nee    973 which in turn can refer to a third, we may need to keep the remaining
970 components of several paths, each to be proces    974 components of several paths, each to be processed when the preceding
971 ones are completed.  These path remnants are k    975 ones are completed.  These path remnants are kept on a stack of
972 limited size.                                     976 limited size.
973                                                   977 
974 There are two reasons for placing limits on ho    978 There are two reasons for placing limits on how many symlinks can
975 occur in a single path lookup.  The most obvio    979 occur in a single path lookup.  The most obvious is to avoid loops.
976 If a symlink referred to itself either directl    980 If a symlink referred to itself either directly or through
977 intermediaries, then following the symlink can    981 intermediaries, then following the symlink can never complete
978 successfully - the error ``ELOOP`` must be ret    982 successfully - the error ``ELOOP`` must be returned.  Loops can be
979 detected without imposing limits, but limits a    983 detected without imposing limits, but limits are the simplest solution
980 and, given the second reason for restriction,     984 and, given the second reason for restriction, quite sufficient.
981                                                   985 
982 .. _outlined recently: http://thread.gmane.org    986 .. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550
983                                                   987 
984 The second reason was `outlined recently`_ by     988 The second reason was `outlined recently`_ by Linus:
985                                                   989 
986    Because it's a latency and DoS issue too. W    990    Because it's a latency and DoS issue too. We need to react well to
987    true loops, but also to "very deep" non-loo    991    true loops, but also to "very deep" non-loops. It's not about memory
988    use, it's about users triggering unreasonab    992    use, it's about users triggering unreasonable CPU resources.
989                                                   993 
990 Linux imposes a limit on the length of any pat    994 Linux imposes a limit on the length of any pathname: ``PATH_MAX``, which
991 is 4096.  There are a number of reasons for th    995 is 4096.  There are a number of reasons for this limit; not letting the
992 kernel spend too much time on just one path is    996 kernel spend too much time on just one path is one of them.  With
993 symbolic links you can effectively generate mu    997 symbolic links you can effectively generate much longer paths so some
994 sort of limit is needed for the same reason.      998 sort of limit is needed for the same reason.  Linux imposes a limit of
995 at most 40 (MAXSYMLINKS) symlinks in any one p !! 999 at most 40 symlinks in any one path lookup.  It previously imposed a
996 a further limit of eight on the maximum depth  !! 1000 further limit of eight on the maximum depth of recursion, but that was
997 raised to 40 when a separate stack was impleme    1001 raised to 40 when a separate stack was implemented, so there is now
998 just the one limit.                               1002 just the one limit.
999                                                   1003 
1000 The ``nameidata`` structure that we met in an    1004 The ``nameidata`` structure that we met in an earlier article contains a
1001 small stack that can be used to store the rem    1005 small stack that can be used to store the remaining part of up to two
1002 symlinks.  In many cases this will be suffici    1006 symlinks.  In many cases this will be sufficient.  If it isn't, a
1003 separate stack is allocated with room for 40     1007 separate stack is allocated with room for 40 symlinks.  Pathname
1004 lookup will never exceed that stack as, once     1008 lookup will never exceed that stack as, once the 40th symlink is
1005 detected, an error is returned.                  1009 detected, an error is returned.
1006                                                  1010 
1007 It might seem that the name remnants are all     1011 It might seem that the name remnants are all that needs to be stored on
1008 this stack, but we need a bit more.  To see t    1012 this stack, but we need a bit more.  To see that, we need to move on to
1009 cache lifetimes.                                 1013 cache lifetimes.
1010                                                  1014 
1011 Storage and lifetime of cached symlinks          1015 Storage and lifetime of cached symlinks
1012 ---------------------------------------          1016 ---------------------------------------
1013                                                  1017 
1014 Like other filesystem resources, such as inod    1018 Like other filesystem resources, such as inodes and directory
1015 entries, symlinks are cached by Linux to avoi    1019 entries, symlinks are cached by Linux to avoid repeated costly access
1016 to external storage.  It is particularly impo    1020 to external storage.  It is particularly important for RCU-walk to be
1017 able to find and temporarily hold onto these     1021 able to find and temporarily hold onto these cached entries, so that
1018 it doesn't need to drop down into REF-walk.      1022 it doesn't need to drop down into REF-walk.
1019                                                  1023 
1020 .. _object-oriented design pattern: https://l    1024 .. _object-oriented design pattern: https://lwn.net/Articles/446317/
1021                                                  1025 
1022 While each filesystem is free to make its own    1026 While each filesystem is free to make its own choice, symlinks are
1023 typically stored in one of two places.  Short    1027 typically stored in one of two places.  Short symlinks are often
1024 stored directly in the inode.  When a filesys    1028 stored directly in the inode.  When a filesystem allocates a ``struct
1025 inode`` it typically allocates extra space to    1029 inode`` it typically allocates extra space to store private data (a
1026 common `object-oriented design pattern`_ in t    1030 common `object-oriented design pattern`_ in the kernel).  This will
1027 sometimes include space for a symlink.  The o    1031 sometimes include space for a symlink.  The other common location is
1028 in the page cache, which normally stores the     1032 in the page cache, which normally stores the content of files.  The
1029 pathname in a symlink can be seen as the cont    1033 pathname in a symlink can be seen as the content of that symlink and
1030 can easily be stored in the page cache just l    1034 can easily be stored in the page cache just like file content.
1031                                                  1035 
1032 When neither of these is suitable, the next m    1036 When neither of these is suitable, the next most likely scenario is
1033 that the filesystem will allocate some tempor    1037 that the filesystem will allocate some temporary memory and copy or
1034 construct the symlink content into that memor    1038 construct the symlink content into that memory whenever it is needed.
1035                                                  1039 
1036 When the symlink is stored in the inode, it h    1040 When the symlink is stored in the inode, it has the same lifetime as
1037 the inode which, itself, is protected by RCU     1041 the inode which, itself, is protected by RCU or by a counted reference
1038 on the dentry.  This means that the mechanism    1042 on the dentry.  This means that the mechanisms that pathname lookup
1039 uses to access the dcache and icache (inode c    1043 uses to access the dcache and icache (inode cache) safely are quite
1040 sufficient for accessing some cached symlinks    1044 sufficient for accessing some cached symlinks safely.  In these cases,
1041 the ``i_link`` pointer in the inode is set to    1045 the ``i_link`` pointer in the inode is set to point to wherever the
1042 symlink is stored and it can be accessed dire    1046 symlink is stored and it can be accessed directly whenever needed.
1043                                                  1047 
1044 When the symlink is stored in the page cache     1048 When the symlink is stored in the page cache or elsewhere, the
1045 situation is not so straightforward.  A refer    1049 situation is not so straightforward.  A reference on a dentry or even
1046 on an inode does not imply any reference on c    1050 on an inode does not imply any reference on cached pages of that
1047 inode, and even an ``rcu_read_lock()`` is not    1051 inode, and even an ``rcu_read_lock()`` is not sufficient to ensure that
1048 a page will not disappear.  So for these syml    1052 a page will not disappear.  So for these symlinks the pathname lookup
1049 code needs to ask the filesystem to provide a    1053 code needs to ask the filesystem to provide a stable reference and,
1050 significantly, needs to release that referenc    1054 significantly, needs to release that reference when it is finished
1051 with it.                                         1055 with it.
1052                                                  1056 
1053 Taking a reference to a cache page is often p    1057 Taking a reference to a cache page is often possible even in RCU-walk
1054 mode.  It does require making changes to memo    1058 mode.  It does require making changes to memory, which is best avoided,
1055 but that isn't necessarily a big cost and it     1059 but that isn't necessarily a big cost and it is better than dropping
1056 out of RCU-walk mode completely.  Even filesy    1060 out of RCU-walk mode completely.  Even filesystems that allocate
1057 space to copy the symlink into can use ``GFP_    1061 space to copy the symlink into can use ``GFP_ATOMIC`` to often successfully
1058 allocate memory without the need to drop out     1062 allocate memory without the need to drop out of RCU-walk.  If a
1059 filesystem cannot successfully get a referenc    1063 filesystem cannot successfully get a reference in RCU-walk mode, it
1060 must return ``-ECHILD`` and ``unlazy_walk()``    1064 must return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to
1061 REF-walk mode in which the filesystem is allo    1065 REF-walk mode in which the filesystem is allowed to sleep.
1062                                                  1066 
1063 The place for all this to happen is the ``i_o !! 1067 The place for all this to happen is the ``i_op->follow_link()`` inode
1064 method. This is called both in RCU-walk and R !! 1068 method.  In the present mainline code this is never actually called in
1065 ``dentry*`` argument is NULL, ``->get_link()` !! 1069 RCU-walk mode as the rewrite is not quite complete.  It is likely that
1066 RCU-walk.  Much like the ``i_op->permission() !! 1070 in a future release this method will be passed an ``inode`` pointer when
1067 looked at previously, ``->get_link()`` would  !! 1071 called in RCU-walk mode so it both (1) knows to be careful, and (2) has the
                                                   >> 1072 validated pointer.  Much like the ``i_op->permission()`` method we
                                                   >> 1073 looked at previously, ``->follow_link()`` would need to be careful that
1068 all the data structures it references are saf    1074 all the data structures it references are safe to be accessed while
1069 holding no counted reference, only the RCU lo !! 1075 holding no counted reference, only the RCU lock.  Though getting a
1070 ``struct delayed_called`` will be passed to ` !! 1076 reference with ``->follow_link()`` is not yet done in RCU-walk mode, the
1071 file systems can set their own put_link funct !! 1077 code is ready to release the reference when that does happen.
1072 set_delayed_call(). Later on, when VFS wants  !! 1078 
1073 do_delayed_call() to invoke that callback fun !! 1079 This need to drop the reference to a symlink adds significant
                                                   >> 1080 complexity.  It requires a reference to the inode so that the
                                                   >> 1081 ``i_op->put_link()`` inode operation can be called.  In REF-walk, that
                                                   >> 1082 reference is kept implicitly through a reference to the dentry, so
                                                   >> 1083 keeping the ``struct path`` of the symlink is easiest.  For RCU-walk,
                                                   >> 1084 the pointer to the inode is kept separately.  To allow switching from
                                                   >> 1085 RCU-walk back to REF-walk in the middle of processing nested symlinks
                                                   >> 1086 we also need the seq number for the dentry so we can confirm that
                                                   >> 1087 switching back was safe.
                                                   >> 1088 
                                                   >> 1089 Finally, when providing a reference to a symlink, the filesystem also
                                                   >> 1090 provides an opaque "cookie" that must be passed to ``->put_link()`` so that it
                                                   >> 1091 knows what to free.  This might be the allocated memory area, or a
                                                   >> 1092 pointer to the ``struct page`` in the page cache, or something else
                                                   >> 1093 completely.  Only the filesystem knows what it is.
1074                                                  1094 
1075 In order for the reference to each symlink to    1095 In order for the reference to each symlink to be dropped when the walk completes,
1076 whether in RCU-walk or REF-walk, the symlink     1096 whether in RCU-walk or REF-walk, the symlink stack needs to contain,
1077 along with the path remnants:                    1097 along with the path remnants:
1078                                                  1098 
1079 - the ``struct path`` to provide a reference  !! 1099 - the ``struct path`` to provide a reference to the inode in REF-walk
1080 - the ``const char *`` to provide a reference !! 1100 - the ``struct inode *`` to provide a reference to the inode in RCU-walk
1081 - the ``seq`` to allow the path to be safely     1101 - the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk
1082 - the ``struct delayed_call`` for later invoc !! 1102 - the ``cookie`` that tells ``->put_path()`` what to put.
1083                                                  1103 
1084 This means that each entry in the symlink sta    1104 This means that each entry in the symlink stack needs to hold five
1085 pointers and an integer instead of just one p    1105 pointers and an integer instead of just one pointer (the path
1086 remnant).  On a 64-bit system, this is about     1106 remnant).  On a 64-bit system, this is about 40 bytes per entry;
1087 with 40 entries it adds up to 1600 bytes tota    1107 with 40 entries it adds up to 1600 bytes total, which is less than
1088 half a page.  So it might seem like a lot, bu    1108 half a page.  So it might seem like a lot, but is by no means
1089 excessive.                                       1109 excessive.
1090                                                  1110 
1091 Note that, in a given stack frame, the path r    1111 Note that, in a given stack frame, the path remnant (``name``) is not
1092 part of the symlink that the other fields ref    1112 part of the symlink that the other fields refer to.  It is the remnant
1093 to be followed once that symlink has been ful    1113 to be followed once that symlink has been fully parsed.
1094                                                  1114 
1095 Following the symlink                            1115 Following the symlink
1096 ---------------------                            1116 ---------------------
1097                                                  1117 
1098 The main loop in ``link_path_walk()`` iterate    1118 The main loop in ``link_path_walk()`` iterates seamlessly over all
1099 components in the path and all of the non-fin    1119 components in the path and all of the non-final symlinks.  As symlinks
1100 are processed, the ``name`` pointer is adjust    1120 are processed, the ``name`` pointer is adjusted to point to a new
1101 symlink, or is restored from the stack, so th    1121 symlink, or is restored from the stack, so that much of the loop
1102 doesn't need to notice.  Getting this ``name`    1122 doesn't need to notice.  Getting this ``name`` variable on and off the
1103 stack is very straightforward; pushing and po    1123 stack is very straightforward; pushing and popping the references is
1104 a little more complex.                           1124 a little more complex.
1105                                                  1125 
1106 When a symlink is found, walk_component() cal !! 1126 When a symlink is found, ``walk_component()`` returns the value ``1``
1107 which returns the link from the filesystem.   !! 1127 (``0`` is returned for any other sort of success, and a negative number
1108 Providing that operation is successful, the o !! 1128 is, as usual, an error indicator).  This causes ``get_link()`` to be
1109 stack, and the new value is used as the ``nam !! 1129 called; it then gets the link from the filesystem.  Providing that
                                                   >> 1130 operation is successful, the old path ``name`` is placed on the stack,
                                                   >> 1131 and the new value is used as the ``name`` for a while.  When the end of
1110 the path is found (i.e. ``*name`` is ``'\0'``    1132 the path is found (i.e. ``*name`` is ``'\0'``) the old ``name`` is restored
1111 off the stack and path walking continues.        1133 off the stack and path walking continues.
1112                                                  1134 
1113 Pushing and popping the reference pointers (i    1135 Pushing and popping the reference pointers (inode, cookie, etc.) is more
1114 complex in part because of the desire to hand    1136 complex in part because of the desire to handle tail recursion.  When
1115 the last component of a symlink itself points    1137 the last component of a symlink itself points to a symlink, we
1116 want to pop the symlink-just-completed off th    1138 want to pop the symlink-just-completed off the stack before pushing
1117 the symlink-just-found to avoid leaving empty    1139 the symlink-just-found to avoid leaving empty path remnants that would
1118 just get in the way.                             1140 just get in the way.
1119                                                  1141 
1120 It is most convenient to push the new symlink    1142 It is most convenient to push the new symlink references onto the
1121 stack in ``walk_component()`` immediately whe    1143 stack in ``walk_component()`` immediately when the symlink is found;
1122 ``walk_component()`` is also the last piece o    1144 ``walk_component()`` is also the last piece of code that needs to look at the
1123 old symlink as it walks that last component.     1145 old symlink as it walks that last component.  So it is quite
1124 convenient for ``walk_component()`` to releas    1146 convenient for ``walk_component()`` to release the old symlink and pop
1125 the references just before pushing the refere    1147 the references just before pushing the reference information for the
1126 new symlink.  It is guided in this by three f !! 1148 new symlink.  It is guided in this by two flags; ``WALK_GET``, which
1127 forbids it from following a symlink if it fin !! 1149 gives it permission to follow a symlink if it finds one, and
1128 which indicates that it is yet too early to r !! 1150 ``WALK_PUT``, which tells it to release the current symlink after it has been
1129 current symlink, and ``WALK_TRAILING`` which  !! 1151 followed.  ``WALK_PUT`` is tested first, leading to a call to
1130 component of the lookup, so we will check use !! 1152 ``put_link()``.  ``WALK_GET`` is tested subsequently (by
1131 decide whether follow it when it is a symlink !! 1153 ``should_follow_link()``) leading to a call to ``pick_link()`` which sets
1132 check if we have privilege to follow it.      !! 1154 up the stack frame.
1133                                                  1155 
1134 Symlinks with no final component                 1156 Symlinks with no final component
1135 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                 1157 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1136                                                  1158 
1137 A pair of special-case symlinks deserve a lit    1159 A pair of special-case symlinks deserve a little further explanation.
1138 Both result in a new ``struct path`` (with mo    1160 Both result in a new ``struct path`` (with mount and dentry) being set
1139 up in the ``nameidata``, and result in pick_l !! 1161 up in the ``nameidata``, and result in ``get_link()`` returning ``NULL``.
1140                                                  1162 
1141 The more obvious case is a symlink to "``/``"    1163 The more obvious case is a symlink to "``/``".  All symlinks starting
1142 with "``/``" are detected in pick_link() whic !! 1164 with "``/``" are detected in ``get_link()`` which resets the ``nameidata``
1143 to point to the effective filesystem root.  I    1165 to point to the effective filesystem root.  If the symlink only
1144 contains "``/``" then there is nothing more t    1166 contains "``/``" then there is nothing more to do, no components at all,
1145 so ``NULL`` is returned to indicate that the     1167 so ``NULL`` is returned to indicate that the symlink can be released and
1146 the stack frame discarded.                       1168 the stack frame discarded.
1147                                                  1169 
1148 The other case involves things in ``/proc`` t    1170 The other case involves things in ``/proc`` that look like symlinks but
1149 aren't really (and are therefore commonly ref    1171 aren't really (and are therefore commonly referred to as "magic-links")::
1150                                                  1172 
1151      $ ls -l /proc/self/fd/1                     1173      $ ls -l /proc/self/fd/1
1152      lrwx------ 1 neilb neilb 64 Jun 13 10:19    1174      lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4
1153                                                  1175 
1154 Every open file descriptor in any process is     1176 Every open file descriptor in any process is represented in ``/proc`` by
1155 something that looks like a symlink.  It is r    1177 something that looks like a symlink.  It is really a reference to the
1156 target file, not just the name of it.  When y    1178 target file, not just the name of it.  When you ``readlink`` these
1157 objects you get a name that might refer to th    1179 objects you get a name that might refer to the same file - unless it
1158 has been unlinked or mounted over.  When ``wa    1180 has been unlinked or mounted over.  When ``walk_component()`` follows
1159 one of these, the ``->get_link()`` method in  !! 1181 one of these, the ``->follow_link()`` method in "procfs" doesn't return
1160 a string name, but instead calls nd_jump_link !! 1182 a string name, but instead calls ``nd_jump_link()`` which updates the
1161 ``nameidata`` in place to point to that targe !! 1183 ``nameidata`` in place to point to that target.  ``->follow_link()`` then
1162 returns ``NULL``.  Again there is no final co !! 1184 returns ``NULL``.  Again there is no final component and ``get_link()``
1163 returns ``NULL``.                             !! 1185 reports this by leaving the ``last_type`` field of ``nameidata`` as
                                                   >> 1186 ``LAST_BIND``.
1164                                                  1187 
1165 Following the symlink in the final component     1188 Following the symlink in the final component
1166 --------------------------------------------     1189 --------------------------------------------
1167                                                  1190 
1168 All this leads to ``link_path_walk()`` walkin    1191 All this leads to ``link_path_walk()`` walking down every component, and
1169 following all symbolic links it finds, until     1192 following all symbolic links it finds, until it reaches the final
1170 component.  This is just returned in the ``la    1193 component.  This is just returned in the ``last`` field of ``nameidata``.
1171 For some callers, this is all they need; they    1194 For some callers, this is all they need; they want to create that
1172 ``last`` name if it doesn't exist or give an     1195 ``last`` name if it doesn't exist or give an error if it does.  Other
1173 callers will want to follow a symlink if one     1196 callers will want to follow a symlink if one is found, and possibly
1174 apply special handling to the last component     1197 apply special handling to the last component of that symlink, rather
1175 than just the last component of the original     1198 than just the last component of the original file name.  These callers
1176 potentially need to call ``link_path_walk()``    1199 potentially need to call ``link_path_walk()`` again and again on
1177 successive symlinks until one is found that d    1200 successive symlinks until one is found that doesn't point to another
1178 symlink.                                         1201 symlink.
1179                                                  1202 
1180 This case is handled by relevant callers of l !! 1203 This case is handled by the relevant caller of ``link_path_walk()``, such as
1181 path_lookupat(), path_openat() using a loop t !! 1204 ``path_lookupat()`` using a loop that calls ``link_path_walk()``, and then
1182 and then handles the final component by calli !! 1205 handles the final component.  If the final component is a symlink
1183 lookup_last(). If it is a symlink that needs  !! 1206 that needs to be followed, then ``trailing_symlink()`` is called to set
1184 open_last_lookups() or lookup_last() will set !! 1207 things up properly and the loop repeats, calling ``link_path_walk()``
1185 return the path so that the loop repeats, cal !! 1208 again.  This could loop as many as 40 times if the last component of
1186 link_path_walk() again.  This could loop as m !! 1209 each symlink is another symlink.
1187 component of each symlink is another symlink. !! 1210 
1188                                               !! 1211 The various functions that examine the final component and possibly
1189 Of the various functions that examine the fin !! 1212 report that it is a symlink are ``lookup_last()``, ``mountpoint_last()``
1190 open_last_lookups() is the most interesting a !! 1213 and ``do_last()``, each of which use the same convention as
1191 with do_open() for opening a file.  Part of o !! 1214 ``walk_component()`` of returning ``1`` if a symlink was found that needs
1192 with ``i_rwsem`` held and this part is in a s !! 1215 to be followed.
1193                                               !! 1216 
1194 Explaining open_last_lookups() and do_open()  !! 1217 Of these, ``do_last()`` is the most interesting as it is used for
1195 of this article, but a few highlights should  !! 1218 opening a file.  Part of ``do_last()`` runs with ``i_rwsem`` held and this
1196 the code.                                     !! 1219 part is in a separate function: ``lookup_open()``.
                                                   >> 1220 
                                                   >> 1221 Explaining ``do_last()`` completely is beyond the scope of this article,
                                                   >> 1222 but a few highlights should help those interested in exploring the
                                                   >> 1223 code.
1197                                                  1224 
1198 1. Rather than just finding the target file,  !! 1225 1. Rather than just finding the target file, ``do_last()`` needs to open
1199    open_last_lookup() to open                 << 
1200    it.  If the file was found in the dcache,     1226    it.  If the file was found in the dcache, then ``vfs_open()`` is used for
1201    this.  If not, then ``lookup_open()`` will    1227    this.  If not, then ``lookup_open()`` will either call ``atomic_open()`` (if
1202    the filesystem provides it) to combine the    1228    the filesystem provides it) to combine the final lookup with the open, or
1203    will perform the separate ``i_op->lookup() !! 1229    will perform the separate ``lookup_real()`` and ``vfs_create()`` steps
1204    directly.  In the later case the actual "o    1230    directly.  In the later case the actual "open" of this newly found or
1205    created file will be performed by vfs_open !! 1231    created file will be performed by ``vfs_open()``, just as if the name
1206    were found in the dcache.                     1232    were found in the dcache.
1207                                                  1233 
1208 2. vfs_open() can fail with ``-EOPENSTALE`` i !! 1234 2. ``vfs_open()`` can fail with ``-EOPENSTALE`` if the cached information
1209    wasn't quite current enough.  If it's in R !! 1235    wasn't quite current enough.  Rather than restarting the lookup from
1210    otherwise ``-ESTALE`` is returned.  When ` !! 1236    the top with ``LOOKUP_REVAL`` set, ``lookup_open()`` is called instead,
1211    retry with ``LOOKUP_REVAL`` flag set.      !! 1237    giving the filesystem a chance to resolve small inconsistencies.
                                                   >> 1238    If that doesn't work, only then is the lookup restarted from the top.
1212                                                  1239 
1213 3. An open with O_CREAT **does** follow a sym    1240 3. An open with O_CREAT **does** follow a symlink in the final component,
1214    unlike other creation system calls (like `    1241    unlike other creation system calls (like ``mkdir``).  So the sequence::
1215                                                  1242 
1216           ln -s bar /tmp/foo                     1243           ln -s bar /tmp/foo
1217           echo hello > /tmp/foo                  1244           echo hello > /tmp/foo
1218                                                  1245 
1219    will create a file called ``/tmp/bar``.  T    1246    will create a file called ``/tmp/bar``.  This is not permitted if
1220    ``O_EXCL`` is set but otherwise is handled    1247    ``O_EXCL`` is set but otherwise is handled for an O_CREAT open much
1221    like for a non-creating open: lookup_last( !! 1248    like for a non-creating open: ``should_follow_link()`` returns ``1``, and
1222    returns a non ``NULL`` value, and link_pat !! 1249    so does ``do_last()`` so that ``trailing_symlink()`` gets called and the
1223    open process continues on the symlink that    1250    open process continues on the symlink that was found.
1224                                                  1251 
1225 Updating the access time                         1252 Updating the access time
1226 ------------------------                         1253 ------------------------
1227                                                  1254 
1228 We previously said of RCU-walk that it would     1255 We previously said of RCU-walk that it would "take no locks, increment
1229 no counts, leave no footprints."  We have sin    1256 no counts, leave no footprints."  We have since seen that some
1230 "footprints" can be needed when handling syml    1257 "footprints" can be needed when handling symlinks as a counted
1231 reference (or even a memory allocation) may b    1258 reference (or even a memory allocation) may be needed.  But these
1232 footprints are best kept to a minimum.           1259 footprints are best kept to a minimum.
1233                                                  1260 
1234 One other place where walking down a symlink     1261 One other place where walking down a symlink can involve leaving
1235 footprints in a way that doesn't affect direc    1262 footprints in a way that doesn't affect directories is in updating access times.
1236 In Unix (and Linux) every filesystem object h    1263 In Unix (and Linux) every filesystem object has a "last accessed
1237 time", or "``atime``".  Passing through a dir    1264 time", or "``atime``".  Passing through a directory to access a file
1238 within is not considered to be an access for     1265 within is not considered to be an access for the purposes of
1239 ``atime``; only listing the contents of a dir    1266 ``atime``; only listing the contents of a directory can update its ``atime``.
1240 Symlinks are different it seems.  Both readin    1267 Symlinks are different it seems.  Both reading a symlink (with ``readlink()``)
1241 and looking up a symlink on the way to some o    1268 and looking up a symlink on the way to some other destination can
1242 update the atime on that symlink.                1269 update the atime on that symlink.
1243                                                  1270 
1244 .. _clearest statement: https://pubs.opengrou !! 1271 .. _clearest statement: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08
1245                                                  1272 
1246 It is not clear why this is the case; POSIX h    1273 It is not clear why this is the case; POSIX has little to say on the
1247 subject.  The `clearest statement`_ is that,     1274 subject.  The `clearest statement`_ is that, if a particular implementation
1248 updates a timestamp in a place not specified     1275 updates a timestamp in a place not specified by POSIX, this must be
1249 documented "except that any changes caused by    1276 documented "except that any changes caused by pathname resolution need
1250 not be documented".  This seems to imply that    1277 not be documented".  This seems to imply that POSIX doesn't really
1251 care about access-time updates during pathnam    1278 care about access-time updates during pathname lookup.
1252                                                  1279 
1253 .. _Linux 1.3.87: https://git.kernel.org/cgit    1280 .. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8
1254                                                  1281 
1255 An examination of history shows that prior to    1282 An examination of history shows that prior to `Linux 1.3.87`_, the ext2
1256 filesystem, at least, didn't update atime whe    1283 filesystem, at least, didn't update atime when following a link.
1257 Unfortunately we have no record of why that b    1284 Unfortunately we have no record of why that behavior was changed.
1258                                                  1285 
1259 In any case, access time must now be updated     1286 In any case, access time must now be updated and that operation can be
1260 quite complex.  Trying to stay in RCU-walk wh    1287 quite complex.  Trying to stay in RCU-walk while doing it is best
1261 avoided.  Fortunately it is often permitted t    1288 avoided.  Fortunately it is often permitted to skip the ``atime``
1262 update.  Because ``atime`` updates cause perf    1289 update.  Because ``atime`` updates cause performance problems in various
1263 areas, Linux supports the ``relatime`` mount     1290 areas, Linux supports the ``relatime`` mount option, which generally
1264 limits the updates of ``atime`` to once per d    1291 limits the updates of ``atime`` to once per day on files that aren't
1265 being changed (and symlinks never change once    1292 being changed (and symlinks never change once created).  Even without
1266 ``relatime``, many filesystems record ``atime    1293 ``relatime``, many filesystems record ``atime`` with a one-second
1267 granularity, so only one update per second is    1294 granularity, so only one update per second is required.
1268                                                  1295 
1269 It is easy to test if an ``atime`` update is     1296 It is easy to test if an ``atime`` update is needed while in RCU-walk
1270 mode and, if it isn't, the update can be skip    1297 mode and, if it isn't, the update can be skipped and RCU-walk mode
1271 continues.  Only when an ``atime`` update is     1298 continues.  Only when an ``atime`` update is actually required does the
1272 path walk drop down to REF-walk.  All of this    1299 path walk drop down to REF-walk.  All of this is handled in the
1273 ``get_link()`` function.                         1300 ``get_link()`` function.
1274                                                  1301 
1275 A few flags                                      1302 A few flags
1276 -----------                                      1303 -----------
1277                                                  1304 
1278 A suitable way to wrap up this tour of pathna    1305 A suitable way to wrap up this tour of pathname walking is to list
1279 the various flags that can be stored in the `    1306 the various flags that can be stored in the ``nameidata`` to guide the
1280 lookup process.  Many of these are only meani    1307 lookup process.  Many of these are only meaningful on the final
1281 component, others reflect the current state o    1308 component, others reflect the current state of the pathname lookup, and some
1282 apply restrictions to all path components enc    1309 apply restrictions to all path components encountered in the path lookup.
1283                                                  1310 
1284 And then there is ``LOOKUP_EMPTY``, which doe    1311 And then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with
1285 the others.  If this is not set, an empty pat    1312 the others.  If this is not set, an empty pathname causes an error
1286 very early on.  If it is set, empty pathnames    1313 very early on.  If it is set, empty pathnames are not considered to be
1287 an error.                                        1314 an error.
1288                                                  1315 
1289 Global state flags                               1316 Global state flags
1290 ~~~~~~~~~~~~~~~~~~                               1317 ~~~~~~~~~~~~~~~~~~
1291                                                  1318 
1292 We have already met two global state flags: `    1319 We have already met two global state flags: ``LOOKUP_RCU`` and
1293 ``LOOKUP_REVAL``.  These select between one o    1320 ``LOOKUP_REVAL``.  These select between one of three overall approaches
1294 to lookup: RCU-walk, REF-walk, and REF-walk w    1321 to lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.
1295                                                  1322 
1296 ``LOOKUP_PARENT`` indicates that the final co    1323 ``LOOKUP_PARENT`` indicates that the final component hasn't been reached
1297 yet.  This is primarily used to tell the audi    1324 yet.  This is primarily used to tell the audit subsystem the full
1298 context of a particular access being audited.    1325 context of a particular access being audited.
1299                                                  1326 
1300 ``ND_ROOT_PRESET`` indicates that the ``root` !! 1327 ``LOOKUP_ROOT`` indicates that the ``root`` field in the ``nameidata`` was
1301 provided by the caller, so it shouldn't be re    1328 provided by the caller, so it shouldn't be released when it is no
1302 longer needed.                                   1329 longer needed.
1303                                                  1330 
1304 ``ND_JUMPED`` means that the current dentry w !! 1331 ``LOOKUP_JUMPED`` means that the current dentry was chosen not because
1305 it had the right name but for some other reas    1332 it had the right name but for some other reason.  This happens when
1306 following "``..``", following a symlink to ``    1333 following "``..``", following a symlink to ``/``, crossing a mount point
1307 or accessing a "``/proc/$PID/fd/$FD``" symlin    1334 or accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic
1308 link"). In this case the filesystem has not b    1335 link"). In this case the filesystem has not been asked to revalidate the
1309 name (with ``d_revalidate()``).  In such case    1336 name (with ``d_revalidate()``).  In such cases the inode may still need
1310 to be revalidated, so ``d_op->d_weak_revalida    1337 to be revalidated, so ``d_op->d_weak_revalidate()`` is called if
1311 ``ND_JUMPED`` is set when the look completes  !! 1338 ``LOOKUP_JUMPED`` is set when the look completes - which may be at the
1312 final component or, when creating, unlinking,    1339 final component or, when creating, unlinking, or renaming, at the penultimate component.
1313                                                  1340 
1314 Resolution-restriction flags                     1341 Resolution-restriction flags
1315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~                     1342 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1316                                                  1343 
1317 In order to allow userspace to protect itself    1344 In order to allow userspace to protect itself against certain race conditions
1318 and attack scenarios involving changing path     1345 and attack scenarios involving changing path components, a series of flags are
1319 available which apply restrictions to all pat    1346 available which apply restrictions to all path components encountered during
1320 path lookup. These flags are exposed through     1347 path lookup. These flags are exposed through ``openat2()``'s ``resolve`` field.
1321                                                  1348 
1322 ``LOOKUP_NO_SYMLINKS`` blocks all symlink tra    1349 ``LOOKUP_NO_SYMLINKS`` blocks all symlink traversals (including magic-links).
1323 This is distinctly different from ``LOOKUP_FO    1350 This is distinctly different from ``LOOKUP_FOLLOW``, because the latter only
1324 relates to restricting the following of trail    1351 relates to restricting the following of trailing symlinks.
1325                                                  1352 
1326 ``LOOKUP_NO_MAGICLINKS`` blocks all magic-lin    1353 ``LOOKUP_NO_MAGICLINKS`` blocks all magic-link traversals. Filesystems must
1327 ensure that they return errors from ``nd_jump    1354 ensure that they return errors from ``nd_jump_link()``, because that is how
1328 ``LOOKUP_NO_MAGICLINKS`` and other magic-link    1355 ``LOOKUP_NO_MAGICLINKS`` and other magic-link restrictions are implemented.
1329                                                  1356 
1330 ``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` tr    1357 ``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` traversals (this includes both
1331 bind-mounts and ordinary mounts). Note that t    1358 bind-mounts and ordinary mounts). Note that the ``vfsmount`` which contains the
1332 lookup is determined by the first mountpoint     1359 lookup is determined by the first mountpoint the path lookup reaches --
1333 absolute paths start with the ``vfsmount`` of    1360 absolute paths start with the ``vfsmount`` of ``/``, and relative paths start
1334 with the ``dfd``'s ``vfsmount``. Magic-links     1361 with the ``dfd``'s ``vfsmount``. Magic-links are only permitted if the
1335 ``vfsmount`` of the path is unchanged.           1362 ``vfsmount`` of the path is unchanged.
1336                                                  1363 
1337 ``LOOKUP_BENEATH`` blocks any path components    1364 ``LOOKUP_BENEATH`` blocks any path components which resolve outside the
1338 starting point of the resolution. This is don    1365 starting point of the resolution. This is done by blocking ``nd_jump_root()``
1339 as well as blocking ".." if it would jump out    1366 as well as blocking ".." if it would jump outside the starting point.
1340 ``rename_lock`` and ``mount_lock`` are used t    1367 ``rename_lock`` and ``mount_lock`` are used to detect attacks against the
1341 resolution of "..". Magic-links are also bloc    1368 resolution of "..". Magic-links are also blocked.
1342                                                  1369 
1343 ``LOOKUP_IN_ROOT`` resolves all path componen    1370 ``LOOKUP_IN_ROOT`` resolves all path components as though the starting point
1344 were the filesystem root. ``nd_jump_root()``  !! 1371 were the filesystem root. ``nd_jump_root()`` brings the resolution back to to
1345 the starting point, and ".." at the starting     1372 the starting point, and ".." at the starting point will act as a no-op. As with
1346 ``LOOKUP_BENEATH``, ``rename_lock`` and ``mou    1373 ``LOOKUP_BENEATH``, ``rename_lock`` and ``mount_lock`` are used to detect
1347 attacks against ".." resolution. Magic-links     1374 attacks against ".." resolution. Magic-links are also blocked.
1348                                                  1375 
1349 Final-component flags                            1376 Final-component flags
1350 ~~~~~~~~~~~~~~~~~~~~~                            1377 ~~~~~~~~~~~~~~~~~~~~~
1351                                                  1378 
1352 Some of these flags are only set when the fin    1379 Some of these flags are only set when the final component is being
1353 considered.  Others are only checked for when    1380 considered.  Others are only checked for when considering that final
1354 component.                                       1381 component.
1355                                                  1382 
1356 ``LOOKUP_AUTOMOUNT`` ensures that, if the fin    1383 ``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount
1357 point, then the mount is triggered.  Some ope    1384 point, then the mount is triggered.  Some operations would trigger it
1358 anyway, but operations like ``stat()`` delibe    1385 anyway, but operations like ``stat()`` deliberately don't.  ``statfs()``
1359 needs to trigger the mount but otherwise beha    1386 needs to trigger the mount but otherwise behaves a lot like ``stat()``, so
1360 it sets ``LOOKUP_AUTOMOUNT``, as does "``quot    1387 it sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of
1361 "``mount --bind``".                              1388 "``mount --bind``".
1362                                                  1389 
1363 ``LOOKUP_FOLLOW`` has a similar function to `    1390 ``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for
1364 symlinks.  Some system calls set or clear it     1391 symlinks.  Some system calls set or clear it implicitly, while
1365 others have API flags such as ``AT_SYMLINK_FO    1392 others have API flags such as ``AT_SYMLINK_FOLLOW`` and
1366 ``UMOUNT_NOFOLLOW`` to control it.  Its effec    1393 ``UMOUNT_NOFOLLOW`` to control it.  Its effect is similar to
1367 ``WALK_GET`` that we already met, but it is u    1394 ``WALK_GET`` that we already met, but it is used in a different way.
1368                                                  1395 
1369 ``LOOKUP_DIRECTORY`` insists that the final c    1396 ``LOOKUP_DIRECTORY`` insists that the final component is a directory.
1370 Various callers set this and it is also set w    1397 Various callers set this and it is also set when the final component
1371 is found to be followed by a slash.              1398 is found to be followed by a slash.
1372                                                  1399 
1373 Finally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, `    1400 Finally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and
1374 ``LOOKUP_RENAME_TARGET`` are not used directl    1401 ``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made
1375 available to the filesystem and particularly     1402 available to the filesystem and particularly the ``->d_revalidate()``
1376 method.  A filesystem can choose not to bothe    1403 method.  A filesystem can choose not to bother revalidating too hard
1377 if it knows that it will be asked to open or     1404 if it knows that it will be asked to open or create the file soon.
1378 These flags were previously useful for ``->lo    1405 These flags were previously useful for ``->lookup()`` too but with the
1379 introduction of ``->atomic_open()`` they are     1406 introduction of ``->atomic_open()`` they are less relevant there.
1380                                                  1407 
1381 End of the road                                  1408 End of the road
1382 ---------------                                  1409 ---------------
1383                                                  1410 
1384 Despite its complexity, all this pathname loo    1411 Despite its complexity, all this pathname lookup code appears to be
1385 in good shape - various parts are certainly e    1412 in good shape - various parts are certainly easier to understand now
1386 than even a couple of releases ago.  But that    1413 than even a couple of releases ago.  But that doesn't mean it is
1387 "finished".   As already mentioned, RCU-walk     1414 "finished".   As already mentioned, RCU-walk currently only follows
1388 symlinks that are stored in the inode so, whi    1415 symlinks that are stored in the inode so, while it handles many ext4
1389 symlinks, it doesn't help with NFS, XFS, or B    1416 symlinks, it doesn't help with NFS, XFS, or Btrfs.  That support
1390 is not likely to be long delayed.                1417 is not likely to be long delayed.
                                                      

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

sflogo.php