Back to home page

OSCL-LXR

 
 

    


0001 ===============
0002 Pathname lookup
0003 ===============
0004 
0005 This write-up is based on three articles published at lwn.net:
0006 
0007 - <https://lwn.net/Articles/649115/> Pathname lookup in Linux
0008 - <https://lwn.net/Articles/649729/> RCU-walk: faster pathname lookup in Linux
0009 - <https://lwn.net/Articles/650786/> A walk among the symlinks
0010 
0011 Written by Neil Brown with help from Al Viro and Jon Corbet.
0012 It has subsequently been updated to reflect changes in the kernel
0013 including:
0014 
0015 - per-directory parallel name lookup.
0016 - ``openat2()`` resolution restriction flags.
0017 
0018 Introduction to pathname lookup
0019 ===============================
0020 
0021 The most obvious aspect of pathname lookup, which very little
0022 exploration is needed to discover, is that it is complex.  There are
0023 many rules, special cases, and implementation alternatives that all
0024 combine to confuse the unwary reader.  Computer science has long been
0025 acquainted with such complexity and has tools to help manage it.  One
0026 tool that we will make extensive use of is "divide and conquer".  For
0027 the early parts of the analysis we will divide off symlinks - leaving
0028 them until the final part.  Well before we get to symlinks we have
0029 another major division based on the VFS's approach to locking which
0030 will allow us to review "REF-walk" and "RCU-walk" separately.  But we
0031 are getting ahead of ourselves.  There are some important low level
0032 distinctions we need to clarify first.
0033 
0034 There are two sorts of ...
0035 --------------------------
0036 
0037 .. _openat: http://man7.org/linux/man-pages/man2/openat.2.html
0038 
0039 Pathnames (sometimes "file names"), used to identify objects in the
0040 filesystem, will be familiar to most readers.  They contain two sorts
0041 of elements: "slashes" that are sequences of one or more "``/``"
0042 characters, and "components" that are sequences of one or more
0043 non-"``/``" characters.  These form two kinds of paths.  Those that
0044 start with slashes are "absolute" and start from the filesystem root.
0045 The others are "relative" and start from the current directory, or
0046 from some other location specified by a file descriptor given to
0047 "``*at()``" system calls such as `openat() <openat_>`_.
0048 
0049 .. _execveat: http://man7.org/linux/man-pages/man2/execveat.2.html
0050 
0051 It is tempting to describe the second kind as starting with a
0052 component, but that isn't always accurate: a pathname can lack both
0053 slashes and components, it can be empty, in other words.  This is
0054 generally forbidden in POSIX, but some of those "``*at()``" system calls
0055 in Linux permit it when the ``AT_EMPTY_PATH`` flag is given.  For
0056 example, if you have an open file descriptor on an executable file you
0057 can execute it by calling `execveat() <execveat_>`_ passing
0058 the file descriptor, an empty path, and the ``AT_EMPTY_PATH`` flag.
0059 
0060 These paths can be divided into two sections: the final component and
0061 everything else.  The "everything else" is the easy bit.  In all cases
0062 it must identify a directory that already exists, otherwise an error
0063 such as ``ENOENT`` or ``ENOTDIR`` will be reported.
0064 
0065 The final component is not so simple.  Not only do different system
0066 calls interpret it quite differently (e.g. some create it, some do
0067 not), but it might not even exist: neither the empty pathname nor the
0068 pathname that is just slashes have a final component.  If it does
0069 exist, it could be "``.``" or "``..``" which are handled quite differently
0070 from other components.
0071 
0072 .. _POSIX: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
0073 
0074 If a pathname ends with a slash, such as "``/tmp/foo/``" it might be
0075 tempting to consider that to have an empty final component.  In many
0076 ways that would lead to correct results, but not always.  In
0077 particular, ``mkdir()`` and ``rmdir()`` each create or remove a directory named
0078 by the final component, and they are required to work with pathnames
0079 ending in "``/``".  According to POSIX_:
0080 
0081   A pathname that contains at least one non-<slash> character and
0082   that ends with one or more trailing <slash> characters shall not
0083   be resolved successfully unless the last pathname component before
0084   the trailing <slash> characters names an existing directory or a
0085   directory entry that is to be created for a directory immediately
0086   after the pathname is resolved.
0087 
0088 The Linux pathname walking code (mostly in ``fs/namei.c``) deals with
0089 all of these issues: breaking the path into components, handling the
0090 "everything else" quite separately from the final component, and
0091 checking that the trailing slash is not used where it isn't
0092 permitted.  It also addresses the important issue of concurrent
0093 access.
0094 
0095 While one process is looking up a pathname, another might be making
0096 changes that affect that lookup.  One fairly extreme case is that if
0097 "a/b" were renamed to "a/c/b" while another process were looking up
0098 "a/b/..", that process might successfully resolve on "a/c".
0099 Most races are much more subtle, and a big part of the task of
0100 pathname lookup is to prevent them from having damaging effects.  Many
0101 of the possible races are seen most clearly in the context of the
0102 "dcache" and an understanding of that is central to understanding
0103 pathname lookup.
0104 
0105 More than just a cache
0106 ----------------------
0107 
0108 The "dcache" caches information about names in each filesystem to
0109 make them quickly available for lookup.  Each entry (known as a
0110 "dentry") contains three significant fields: a component name, a
0111 pointer to a parent dentry, and a pointer to the "inode" which
0112 contains further information about the object in that parent with
0113 the given name.  The inode pointer can be ``NULL`` indicating that the
0114 name doesn't exist in the parent.  While there can be linkage in the
0115 dentry of a directory to the dentries of the children, that linkage is
0116 not used for pathname lookup, and so will not be considered here.
0117 
0118 The dcache has a number of uses apart from accelerating lookup.  One
0119 that will be particularly relevant is that it is closely integrated
0120 with the mount table that records which filesystem is mounted where.
0121 What the mount table actually stores is which dentry is mounted on top
0122 of which other dentry.
0123 
0124 When considering the dcache, we have another of our "two types"
0125 distinctions: there are two types of filesystems.
0126 
0127 Some filesystems ensure that the information in the dcache is always
0128 completely accurate (though not necessarily complete).  This can allow
0129 the VFS to determine if a particular file does or doesn't exist
0130 without checking with the filesystem, and means that the VFS can
0131 protect the filesystem against certain races and other problems.
0132 These are typically "local" filesystems such as ext3, XFS, and Btrfs.
0133 
0134 Other filesystems don't provide that guarantee because they cannot.
0135 These are typically filesystems that are shared across a network,
0136 whether remote filesystems like NFS and 9P, or cluster filesystems
0137 like ocfs2 or cephfs.  These filesystems allow the VFS to revalidate
0138 cached information, and must provide their own protection against
0139 awkward races.  The VFS can detect these filesystems by the
0140 ``DCACHE_OP_REVALIDATE`` flag being set in the dentry.
0141 
0142 REF-walk: simple concurrency management with refcounts and spinlocks
0143 --------------------------------------------------------------------
0144 
0145 With all of those divisions carefully classified, we can now start
0146 looking at the actual process of walking along a path.  In particular
0147 we will start with the handling of the "everything else" part of a
0148 pathname, and focus on the "REF-walk" approach to concurrency
0149 management.  This code is found in the ``link_path_walk()`` function, if
0150 you ignore all the places that only run when "``LOOKUP_RCU``"
0151 (indicating the use of RCU-walk) is set.
0152 
0153 .. _Meet the Lockers: https://lwn.net/Articles/453685/
0154 
0155 REF-walk is fairly heavy-handed with locks and reference counts.  Not
0156 as heavy-handed as in the old "big kernel lock" days, but certainly not
0157 afraid of taking a lock when one is needed.  It uses a variety of
0158 different concurrency controls.  A background understanding of the
0159 various primitives is assumed, or can be gleaned from elsewhere such
0160 as in `Meet the Lockers`_.
0161 
0162 The locking mechanisms used by REF-walk include:
0163 
0164 dentry->d_lockref
0165 ~~~~~~~~~~~~~~~~~
0166 
0167 This uses the lockref primitive to provide both a spinlock and a
0168 reference count.  The special-sauce of this primitive is that the
0169 conceptual sequence "lock; inc_ref; unlock;" can often be performed
0170 with a single atomic memory operation.
0171 
0172 Holding a reference on a dentry ensures that the dentry won't suddenly
0173 be freed and used for something else, so the values in various fields
0174 will behave as expected.  It also protects the ``->d_inode`` reference
0175 to the inode to some extent.
0176 
0177 The association between a dentry and its inode is fairly permanent.
0178 For example, when a file is renamed, the dentry and inode move
0179 together to the new location.  When a file is created the dentry will
0180 initially be negative (i.e. ``d_inode`` is ``NULL``), and will be assigned
0181 to the new inode as part of the act of creation.
0182 
0183 When a file is deleted, this can be reflected in the cache either by
0184 setting ``d_inode`` to ``NULL``, or by removing it from the hash table
0185 (described shortly) used to look up the name in the parent directory.
0186 If the dentry is still in use the second option is used as it is
0187 perfectly legal to keep using an open file after it has been deleted
0188 and having the dentry around helps.  If the dentry is not otherwise in
0189 use (i.e. if the refcount in ``d_lockref`` is one), only then will
0190 ``d_inode`` be set to ``NULL``.  Doing it this way is more efficient for a
0191 very common case.
0192 
0193 So as long as a counted reference is held to a dentry, a non-``NULL`` ``->d_inode``
0194 value will never be changed.
0195 
0196 dentry->d_lock
0197 ~~~~~~~~~~~~~~
0198 
0199 ``d_lock`` is a synonym for the spinlock that is part of ``d_lockref`` above.
0200 For our purposes, holding this lock protects against the dentry being
0201 renamed or unlinked.  In particular, its parent (``d_parent``), and its
0202 name (``d_name``) cannot be changed, and it cannot be removed from the
0203 dentry hash table.
0204 
0205 When looking for a name in a directory, REF-walk takes ``d_lock`` on
0206 each candidate dentry that it finds in the hash table and then checks
0207 that the parent and name are correct.  So it doesn't lock the parent
0208 while searching in the cache; it only locks children.
0209 
0210 When looking for the parent for a given name (to handle "``..``"),
0211 REF-walk can take ``d_lock`` to get a stable reference to ``d_parent``,
0212 but it first tries a more lightweight approach.  As seen in
0213 ``dget_parent()``, if a reference can be claimed on the parent, and if
0214 subsequently ``d_parent`` can be seen to have not changed, then there is
0215 no need to actually take the lock on the child.
0216 
0217 rename_lock
0218 ~~~~~~~~~~~
0219 
0220 Looking up a given name in a given directory involves computing a hash
0221 from the two values (the name and the dentry of the directory),
0222 accessing that slot in a hash table, and searching the linked list
0223 that is found there.
0224 
0225 When a dentry is renamed, the name and the parent dentry can both
0226 change so the hash will almost certainly change too.  This would move the
0227 dentry to a different chain in the hash table.  If a filename search
0228 happened to be looking at a dentry that was moved in this way,
0229 it might end up continuing the search down the wrong chain,
0230 and so miss out on part of the correct chain.
0231 
0232 The name-lookup process (``d_lookup()``) does *not* try to prevent this
0233 from happening, but only to detect when it happens.
0234 ``rename_lock`` is a seqlock that is updated whenever any dentry is
0235 renamed.  If ``d_lookup`` finds that a rename happened while it
0236 unsuccessfully scanned a chain in the hash table, it simply tries
0237 again.
0238 
0239 ``rename_lock`` is also used to detect and defend against potential attacks
0240 against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
0241 the parent directory is moved outside the root, bypassing the ``path_equal()``
0242 check). If ``rename_lock`` is updated during the lookup and the path encounters
0243 a "..", a potential attack occurred and ``handle_dots()`` will bail out with
0244 ``-EAGAIN``.
0245 
0246 inode->i_rwsem
0247 ~~~~~~~~~~~~~~
0248 
0249 ``i_rwsem`` is a read/write semaphore that serializes all changes to a particular
0250 directory.  This ensures that, for example, an ``unlink()`` and a ``rename()``
0251 cannot both happen at the same time.  It also keeps the directory
0252 stable while the filesystem is asked to look up a name that is not
0253 currently in the dcache or, optionally, when the list of entries in a
0254 directory is being retrieved with ``readdir()``.
0255 
0256 This has a complementary role to that of ``d_lock``: ``i_rwsem`` on a
0257 directory protects all of the names in that directory, while ``d_lock``
0258 on a name protects just one name in a directory.  Most changes to the
0259 dcache hold ``i_rwsem`` on the relevant directory inode and briefly take
0260 ``d_lock`` on one or more the dentries while the change happens.  One
0261 exception is when idle dentries are removed from the dcache due to
0262 memory pressure.  This uses ``d_lock``, but ``i_rwsem`` plays no role.
0263 
0264 The semaphore affects pathname lookup in two distinct ways.  Firstly it
0265 prevents changes during lookup of a name in a directory.  ``walk_component()`` uses
0266 ``lookup_fast()`` first which, in turn, checks to see if the name is in the cache,
0267 using only ``d_lock`` locking.  If the name isn't found, then ``walk_component()``
0268 falls back to ``lookup_slow()`` which takes a shared lock on ``i_rwsem``, checks again that
0269 the name isn't in the cache, and then calls in to the filesystem to get a
0270 definitive answer.  A new dentry will be added to the cache regardless of
0271 the result.
0272 
0273 Secondly, when pathname lookup reaches the final component, it will
0274 sometimes need to take an exclusive lock on ``i_rwsem`` before performing the last lookup so
0275 that the required exclusion can be achieved.  How path lookup chooses
0276 to take, or not take, ``i_rwsem`` is one of the
0277 issues addressed in a subsequent section.
0278 
0279 If two threads attempt to look up the same name at the same time - a
0280 name that is not yet in the dcache - the shared lock on ``i_rwsem`` will
0281 not prevent them both adding new dentries with the same name.  As this
0282 would result in confusion an extra level of interlocking is used,
0283 based around a secondary hash table (``in_lookup_hashtable``) and a
0284 per-dentry flag bit (``DCACHE_PAR_LOOKUP``).
0285 
0286 To add a new dentry to the cache while only holding a shared lock on
0287 ``i_rwsem``, a thread must call ``d_alloc_parallel()``.  This allocates a
0288 dentry, stores the required name and parent in it, checks if there
0289 is already a matching dentry in the primary or secondary hash
0290 tables, and if not, stores the newly allocated dentry in the secondary
0291 hash table, with ``DCACHE_PAR_LOOKUP`` set.
0292 
0293 If a matching dentry was found in the primary hash table then that is
0294 returned and the caller can know that it lost a race with some other
0295 thread adding the entry.  If no matching dentry is found in either
0296 cache, the newly allocated dentry is returned and the caller can
0297 detect this from the presence of ``DCACHE_PAR_LOOKUP``.  In this case it
0298 knows that it has won any race and now is responsible for asking the
0299 filesystem to perform the lookup and find the matching inode.  When
0300 the lookup is complete, it must call ``d_lookup_done()`` which clears
0301 the flag and does some other house keeping, including removing the
0302 dentry from the secondary hash table - it will normally have been
0303 added to the primary hash table already.  Note that a ``struct
0304 waitqueue_head`` is passed to ``d_alloc_parallel()``, and
0305 ``d_lookup_done()`` must be called while this ``waitqueue_head`` is still
0306 in scope.
0307 
0308 If a matching dentry is found in the secondary hash table,
0309 ``d_alloc_parallel()`` has a little more work to do. It first waits for
0310 ``DCACHE_PAR_LOOKUP`` to be cleared, using a wait_queue that was passed
0311 to the instance of ``d_alloc_parallel()`` that won the race and that
0312 will be woken by the call to ``d_lookup_done()``.  It then checks to see
0313 if the dentry has now been added to the primary hash table.  If it
0314 has, the dentry is returned and the caller just sees that it lost any
0315 race.  If it hasn't been added to the primary hash table, the most
0316 likely explanation is that some other dentry was added instead using
0317 ``d_splice_alias()``.  In any case, ``d_alloc_parallel()`` repeats all the
0318 look ups from the start and will normally return something from the
0319 primary hash table.
0320 
0321 mnt->mnt_count
0322 ~~~~~~~~~~~~~~
0323 
0324 ``mnt_count`` is a per-CPU reference counter on "``mount``" structures.
0325 Per-CPU here means that incrementing the count is cheap as it only
0326 uses CPU-local memory, but checking if the count is zero is expensive as
0327 it needs to check with every CPU.  Taking a ``mnt_count`` reference
0328 prevents the mount structure from disappearing as the result of regular
0329 unmount operations, but does not prevent a "lazy" unmount.  So holding
0330 ``mnt_count`` doesn't ensure that the mount remains in the namespace and,
0331 in particular, doesn't stabilize the link to the mounted-on dentry.  It
0332 does, however, ensure that the ``mount`` data structure remains coherent,
0333 and it provides a reference to the root dentry of the mounted
0334 filesystem.  So a reference through ``->mnt_count`` provides a stable
0335 reference to the mounted dentry, but not the mounted-on dentry.
0336 
0337 mount_lock
0338 ~~~~~~~~~~
0339 
0340 ``mount_lock`` is a global seqlock, a bit like ``rename_lock``.  It can be used to
0341 check if any change has been made to any mount points.
0342 
0343 While walking down the tree (away from the root) this lock is used when
0344 crossing a mount point to check that the crossing was safe.  That is,
0345 the value in the seqlock is read, then the code finds the mount that
0346 is mounted on the current directory, if there is one, and increments
0347 the ``mnt_count``.  Finally the value in ``mount_lock`` is checked against
0348 the old value.  If there is no change, then the crossing was safe.  If there
0349 was a change, the ``mnt_count`` is decremented and the whole process is
0350 retried.
0351 
0352 When walking up the tree (towards the root) by following a ".." link,
0353 a little more care is needed.  In this case the seqlock (which
0354 contains both a counter and a spinlock) is fully locked to prevent
0355 any changes to any mount points while stepping up.  This locking is
0356 needed to stabilize the link to the mounted-on dentry, which the
0357 refcount on the mount itself doesn't ensure.
0358 
0359 ``mount_lock`` is also used to detect and defend against potential attacks
0360 against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
0361 the parent directory is moved outside the root, bypassing the ``path_equal()``
0362 check). If ``mount_lock`` is updated during the lookup and the path encounters
0363 a "..", a potential attack occurred and ``handle_dots()`` will bail out with
0364 ``-EAGAIN``.
0365 
0366 RCU
0367 ~~~
0368 
0369 Finally the global (but extremely lightweight) RCU read lock is held
0370 from time to time to ensure certain data structures don't get freed
0371 unexpectedly.
0372 
0373 In particular it is held while scanning chains in the dcache hash
0374 table, and the mount point hash table.
0375 
0376 Bringing it together with ``struct nameidata``
0377 ----------------------------------------------
0378 
0379 .. _First edition Unix: https://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/u2.s
0380 
0381 Throughout the process of walking a path, the current status is stored
0382 in a ``struct nameidata``, "namei" being the traditional name - dating
0383 all the way back to `First Edition Unix`_ - of the function that
0384 converts a "name" to an "inode".  ``struct nameidata`` contains (among
0385 other fields):
0386 
0387 ``struct path path``
0388 ~~~~~~~~~~~~~~~~~~~~
0389 
0390 A ``path`` contains a ``struct vfsmount`` (which is
0391 embedded in a ``struct mount``) and a ``struct dentry``.  Together these
0392 record the current status of the walk.  They start out referring to the
0393 starting point (the current working directory, the root directory, or some other
0394 directory identified by a file descriptor), and are updated on each
0395 step.  A reference through ``d_lockref`` and ``mnt_count`` is always
0396 held.
0397 
0398 ``struct qstr last``
0399 ~~~~~~~~~~~~~~~~~~~~
0400 
0401 This is a string together with a length (i.e. *not* ``nul`` terminated)
0402 that is the "next" component in the pathname.
0403 
0404 ``int last_type``
0405 ~~~~~~~~~~~~~~~~~
0406 
0407 This is one of ``LAST_NORM``, ``LAST_ROOT``, ``LAST_DOT`` or ``LAST_DOTDOT``.
0408 The ``last`` field is only valid if the type is ``LAST_NORM``.
0409 
0410 ``struct path root``
0411 ~~~~~~~~~~~~~~~~~~~~
0412 
0413 This is used to hold a reference to the effective root of the
0414 filesystem.  Often that reference won't be needed, so this field is
0415 only assigned the first time it is used, or when a non-standard root
0416 is requested.  Keeping a reference in the ``nameidata`` ensures that
0417 only one root is in effect for the entire path walk, even if it races
0418 with a ``chroot()`` system call.
0419 
0420 It should be noted that in the case of ``LOOKUP_IN_ROOT`` or
0421 ``LOOKUP_BENEATH``, the effective root becomes the directory file descriptor
0422 passed to ``openat2()`` (which exposes these ``LOOKUP_`` flags).
0423 
0424 The root is needed when either of two conditions holds: (1) either the
0425 pathname or a symbolic link starts with a "'/'", or (2) a "``..``"
0426 component is being handled, since "``..``" from the root must always stay
0427 at the root.  The value used is usually the current root directory of
0428 the calling process.  An alternate root can be provided as when
0429 ``sysctl()`` calls ``file_open_root()``, and when NFSv4 or Btrfs call
0430 ``mount_subtree()``.  In each case a pathname is being looked up in a very
0431 specific part of the filesystem, and the lookup must not be allowed to
0432 escape that subtree.  It works a bit like a local ``chroot()``.
0433 
0434 Ignoring the handling of symbolic links, we can now describe the
0435 "``link_path_walk()``" function, which handles the lookup of everything
0436 except the final component as:
0437 
0438    Given a path (``name``) and a nameidata structure (``nd``), check that the
0439    current directory has execute permission and then advance ``name``
0440    over one component while updating ``last_type`` and ``last``.  If that
0441    was the final component, then return, otherwise call
0442    ``walk_component()`` and repeat from the top.
0443 
0444 ``walk_component()`` is even easier.  If the component is ``LAST_DOTS``,
0445 it calls ``handle_dots()`` which does the necessary locking as already
0446 described.  If it finds a ``LAST_NORM`` component it first calls
0447 "``lookup_fast()``" which only looks in the dcache, but will ask the
0448 filesystem to revalidate the result if it is that sort of filesystem.
0449 If that doesn't get a good result, it calls "``lookup_slow()``" which
0450 takes ``i_rwsem``, rechecks the cache, and then asks the filesystem
0451 to find a definitive answer.
0452 
0453 As the last step of walk_component(), step_into() will be called either
0454 directly from walk_component() or from handle_dots().  It calls
0455 handle_mounts(), to check and handle mount points, in which a new
0456 ``struct path`` is created containing a counted reference to the new dentry and
0457 a reference to the new ``vfsmount`` which is only counted if it is
0458 different from the previous ``vfsmount``. Then if there is
0459 a symbolic link, step_into() calls pick_link() to deal with it,
0460 otherwise it installs the new ``struct path`` in the ``struct nameidata``, and
0461 drops the unneeded references.
0462 
0463 This "hand-over-hand" sequencing of getting a reference to the new
0464 dentry before dropping the reference to the previous dentry may
0465 seem obvious, but is worth pointing out so that we will recognize its
0466 analogue in the "RCU-walk" version.
0467 
0468 Handling the final component
0469 ----------------------------
0470 
0471 ``link_path_walk()`` only walks as far as setting ``nd->last`` and
0472 ``nd->last_type`` to refer to the final component of the path.  It does
0473 not call ``walk_component()`` that last time.  Handling that final
0474 component remains for the caller to sort out. Those callers are
0475 path_lookupat(), path_parentat() and
0476 path_openat() each of which handles the differing requirements of
0477 different system calls.
0478 
0479 ``path_parentat()`` is clearly the simplest - it just wraps a little bit
0480 of housekeeping around ``link_path_walk()`` and returns the parent
0481 directory and final component to the caller.  The caller will be either
0482 aiming to create a name (via ``filename_create()``) or remove or rename
0483 a name (in which case ``user_path_parent()`` is used).  They will use
0484 ``i_rwsem`` to exclude other changes while they validate and then
0485 perform their operation.
0486 
0487 ``path_lookupat()`` is nearly as simple - it is used when an existing
0488 object is wanted such as by ``stat()`` or ``chmod()``.  It essentially just
0489 calls ``walk_component()`` on the final component through a call to
0490 ``lookup_last()``.  ``path_lookupat()`` returns just the final dentry.
0491 It is worth noting that when flag ``LOOKUP_MOUNTPOINT`` is set,
0492 path_lookupat() will unset LOOKUP_JUMPED in nameidata so that in the
0493 subsequent path traversal d_weak_revalidate() won't be called.
0494 This is important when unmounting a filesystem that is inaccessible, such as
0495 one provided by a dead NFS server.
0496 
0497 Finally ``path_openat()`` is used for the ``open()`` system call; it
0498 contains, in support functions starting with "open_last_lookups()", all the
0499 complexity needed to handle the different subtleties of O_CREAT (with
0500 or without O_EXCL), final "``/``" characters, and trailing symbolic
0501 links.  We will revisit this in the final part of this series, which
0502 focuses on those symbolic links.  "open_last_lookups()" will sometimes, but
0503 not always, take ``i_rwsem``, depending on what it finds.
0504 
0505 Each of these, or the functions which call them, need to be alert to
0506 the possibility that the final component is not ``LAST_NORM``.  If the
0507 goal of the lookup is to create something, then any value for
0508 ``last_type`` other than ``LAST_NORM`` will result in an error.  For
0509 example if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller
0510 won't try to create that name.  They also check for trailing slashes
0511 by testing ``last.name[last.len]``.  If there is any character beyond
0512 the final component, it must be a trailing slash.
0513 
0514 Revalidation and automounts
0515 ---------------------------
0516 
0517 Apart from symbolic links, there are only two parts of the "REF-walk"
0518 process not yet covered.  One is the handling of stale cache entries
0519 and the other is automounts.
0520 
0521 On filesystems that require it, the lookup routines will call the
0522 ``->d_revalidate()`` dentry method to ensure that the cached information
0523 is current.  This will often confirm validity or update a few details
0524 from a server.  In some cases it may find that there has been change
0525 further up the path and that something that was thought to be valid
0526 previously isn't really.  When this happens the lookup of the whole
0527 path is aborted and retried with the "``LOOKUP_REVAL``" flag set.  This
0528 forces revalidation to be more thorough.  We will see more details of
0529 this retry process in the next article.
0530 
0531 Automount points are locations in the filesystem where an attempt to
0532 lookup a name can trigger changes to how that lookup should be
0533 handled, in particular by mounting a filesystem there.  These are
0534 covered in greater detail in autofs.txt in the Linux documentation
0535 tree, but a few notes specifically related to path lookup are in order
0536 here.
0537 
0538 The Linux VFS has a concept of "managed" dentries.  There are three
0539 potentially interesting things about these dentries corresponding
0540 to three different flags that might be set in ``dentry->d_flags``:
0541 
0542 ``DCACHE_MANAGE_TRANSIT``
0543 ~~~~~~~~~~~~~~~~~~~~~~~~~
0544 
0545 If this flag has been set, then the filesystem has requested that the
0546 ``d_manage()`` dentry operation be called before handling any possible
0547 mount point.  This can perform two particular services:
0548 
0549 It can block to avoid races.  If an automount point is being
0550 unmounted, the ``d_manage()`` function will usually wait for that
0551 process to complete before letting the new lookup proceed and possibly
0552 trigger a new automount.
0553 
0554 It can selectively allow only some processes to transit through a
0555 mount point.  When a server process is managing automounts, it may
0556 need to access a directory without triggering normal automount
0557 processing.  That server process can identify itself to the ``autofs``
0558 filesystem, which will then give it a special pass through
0559 ``d_manage()`` by returning ``-EISDIR``.
0560 
0561 ``DCACHE_MOUNTED``
0562 ~~~~~~~~~~~~~~~~~~
0563 
0564 This flag is set on every dentry that is mounted on.  As Linux
0565 supports multiple filesystem namespaces, it is possible that the
0566 dentry may not be mounted on in *this* namespace, just in some
0567 other.  So this flag is seen as a hint, not a promise.
0568 
0569 If this flag is set, and ``d_manage()`` didn't return ``-EISDIR``,
0570 ``lookup_mnt()`` is called to examine the mount hash table (honoring the
0571 ``mount_lock`` described earlier) and possibly return a new ``vfsmount``
0572 and a new ``dentry`` (both with counted references).
0573 
0574 ``DCACHE_NEED_AUTOMOUNT``
0575 ~~~~~~~~~~~~~~~~~~~~~~~~~
0576 
0577 If ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't
0578 find a mount point, then this flag causes the ``d_automount()`` dentry
0579 operation to be called.
0580 
0581 The ``d_automount()`` operation can be arbitrarily complex and may
0582 communicate with server processes etc. but it should ultimately either
0583 report that there was an error, that there was nothing to mount, or
0584 should provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``.
0585 
0586 In the latter case, ``finish_automount()`` will be called to safely
0587 install the new mount point into the mount table.
0588 
0589 There is no new locking of import here and it is important that no
0590 locks (only counted references) are held over this processing due to
0591 the very real possibility of extended delays.
0592 This will become more important next time when we examine RCU-walk
0593 which is particularly sensitive to delays.
0594 
0595 RCU-walk - faster pathname lookup in Linux
0596 ==========================================
0597 
0598 RCU-walk is another algorithm for performing pathname lookup in Linux.
0599 It is in many ways similar to REF-walk and the two share quite a bit
0600 of code.  The significant difference in RCU-walk is how it allows for
0601 the possibility of concurrent access.
0602 
0603 We noted that REF-walk is complex because there are numerous details
0604 and special cases.  RCU-walk reduces this complexity by simply
0605 refusing to handle a number of cases -- it instead falls back to
0606 REF-walk.  The difficulty with RCU-walk comes from a different
0607 direction: unfamiliarity.  The locking rules when depending on RCU are
0608 quite different from traditional locking, so we will spend a little extra
0609 time when we come to those.
0610 
0611 Clear demarcation of roles
0612 --------------------------
0613 
0614 The easiest way to manage concurrency is to forcibly stop any other
0615 thread from changing the data structures that a given thread is
0616 looking at.  In cases where no other thread would even think of
0617 changing the data and lots of different threads want to read at the
0618 same time, this can be very costly.  Even when using locks that permit
0619 multiple concurrent readers, the simple act of updating the count of
0620 the number of current readers can impose an unwanted cost.  So the
0621 goal when reading a shared data structure that no other process is
0622 changing is to avoid writing anything to memory at all.  Take no
0623 locks, increment no counts, leave no footprints.
0624 
0625 The REF-walk mechanism already described certainly doesn't follow this
0626 principle, but then it is really designed to work when there may well
0627 be other threads modifying the data.  RCU-walk, in contrast, is
0628 designed for the common situation where there are lots of frequent
0629 readers and only occasional writers.  This may not be common in all
0630 parts of the filesystem tree, but in many parts it will be.  For the
0631 other parts it is important that RCU-walk can quickly fall back to
0632 using REF-walk.
0633 
0634 Pathname lookup always starts in RCU-walk mode but only remains there
0635 as long as what it is looking for is in the cache and is stable.  It
0636 dances lightly down the cached filesystem image, leaving no footprints
0637 and carefully watching where it is, to be sure it doesn't trip.  If it
0638 notices that something has changed or is changing, or if something
0639 isn't in the cache, then it tries to stop gracefully and switch to
0640 REF-walk.
0641 
0642 This stopping requires getting a counted reference on the current
0643 ``vfsmount`` and ``dentry``, and ensuring that these are still valid -
0644 that a path walk with REF-walk would have found the same entries.
0645 This is an invariant that RCU-walk must guarantee.  It can only make
0646 decisions, such as selecting the next step, that are decisions which
0647 REF-walk could also have made if it were walking down the tree at the
0648 same time.  If the graceful stop succeeds, the rest of the path is
0649 processed with the reliable, if slightly sluggish, REF-walk.  If
0650 RCU-walk finds it cannot stop gracefully, it simply gives up and
0651 restarts from the top with REF-walk.
0652 
0653 This pattern of "try RCU-walk, if that fails try REF-walk" can be
0654 clearly seen in functions like filename_lookup(),
0655 filename_parentat(),
0656 do_filp_open(), and do_file_open_root().  These four
0657 correspond roughly to the three ``path_*()`` functions we met earlier,
0658 each of which calls ``link_path_walk()``.  The ``path_*()`` functions are
0659 called using different mode flags until a mode is found which works.
0660 They are first called with ``LOOKUP_RCU`` set to request "RCU-walk".  If
0661 that fails with the error ``ECHILD`` they are called again with no
0662 special flag to request "REF-walk".  If either of those report the
0663 error ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no
0664 ``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly
0665 revalidated - normally entries are only revalidated if the filesystem
0666 determines that they are too old to trust.
0667 
0668 The ``LOOKUP_RCU`` attempt may drop that flag internally and switch to
0669 REF-walk, but will never then try to switch back to RCU-walk.  Places
0670 that trip up RCU-walk are much more likely to be near the leaves and
0671 so it is very unlikely that there will be much, if any, benefit from
0672 switching back.
0673 
0674 RCU and seqlocks: fast and light
0675 --------------------------------
0676 
0677 RCU is, unsurprisingly, critical to RCU-walk mode.  The
0678 ``rcu_read_lock()`` is held for the entire time that RCU-walk is walking
0679 down a path.  The particular guarantee it provides is that the key
0680 data structures - dentries, inodes, super_blocks, and mounts - will
0681 not be freed while the lock is held.  They might be unlinked or
0682 invalidated in one way or another, but the memory will not be
0683 repurposed so values in various fields will still be meaningful.  This
0684 is the only guarantee that RCU provides; everything else is done using
0685 seqlocks.
0686 
0687 As we saw above, REF-walk holds a counted reference to the current
0688 dentry and the current vfsmount, and does not release those references
0689 before taking references to the "next" dentry or vfsmount.  It also
0690 sometimes takes the ``d_lock`` spinlock.  These references and locks are
0691 taken to prevent certain changes from happening.  RCU-walk must not
0692 take those references or locks and so cannot prevent such changes.
0693 Instead, it checks to see if a change has been made, and aborts or
0694 retries if it has.
0695 
0696 To preserve the invariant mentioned above (that RCU-walk may only make
0697 decisions that REF-walk could have made), it must make the checks at
0698 or near the same places that REF-walk holds the references.  So, when
0699 REF-walk increments a reference count or takes a spinlock, RCU-walk
0700 samples the status of a seqlock using ``read_seqcount_begin()`` or a
0701 similar function.  When REF-walk decrements the count or drops the
0702 lock, RCU-walk checks if the sampled status is still valid using
0703 ``read_seqcount_retry()`` or similar.
0704 
0705 However, there is a little bit more to seqlocks than that.  If
0706 RCU-walk accesses two different fields in a seqlock-protected
0707 structure, or accesses the same field twice, there is no a priori
0708 guarantee of any consistency between those accesses.  When consistency
0709 is needed - which it usually is - RCU-walk must take a copy and then
0710 use ``read_seqcount_retry()`` to validate that copy.
0711 
0712 ``read_seqcount_retry()`` not only checks the sequence number, but also
0713 imposes a memory barrier so that no memory-read instruction from
0714 *before* the call can be delayed until *after* the call, either by the
0715 CPU or by the compiler.  A simple example of this can be seen in
0716 ``slow_dentry_cmp()`` which, for filesystems which do not use simple
0717 byte-wise name equality, calls into the filesystem to compare a name
0718 against a dentry.  The length and name pointer are copied into local
0719 variables, then ``read_seqcount_retry()`` is called to confirm the two
0720 are consistent, and only then is ``->d_compare()`` called.  When
0721 standard filename comparison is used, ``dentry_cmp()`` is called
0722 instead.  Notably it does *not* use ``read_seqcount_retry()``, but
0723 instead has a large comment explaining why the consistency guarantee
0724 isn't necessary.  A subsequent ``read_seqcount_retry()`` will be
0725 sufficient to catch any problem that could occur at this point.
0726 
0727 With that little refresher on seqlocks out of the way we can look at
0728 the bigger picture of how RCU-walk uses seqlocks.
0729 
0730 ``mount_lock`` and ``nd->m_seq``
0731 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0732 
0733 We already met the ``mount_lock`` seqlock when REF-walk used it to
0734 ensure that crossing a mount point is performed safely.  RCU-walk uses
0735 it for that too, but for quite a bit more.
0736 
0737 Instead of taking a counted reference to each ``vfsmount`` as it
0738 descends the tree, RCU-walk samples the state of ``mount_lock`` at the
0739 start of the walk and stores this initial sequence number in the
0740 ``struct nameidata`` in the ``m_seq`` field.  This one lock and one
0741 sequence number are used to validate all accesses to all ``vfsmounts``,
0742 and all mount point crossings.  As changes to the mount table are
0743 relatively rare, it is reasonable to fall back on REF-walk any time
0744 that any "mount" or "unmount" happens.
0745 
0746 ``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk
0747 sequence, whether switching to REF-walk for the rest of the path or
0748 when the end of the path is reached.  It is also checked when stepping
0749 down over a mount point (in ``__follow_mount_rcu()``) or up (in
0750 ``follow_dotdot_rcu()``).  If it is ever found to have changed, the
0751 whole RCU-walk sequence is aborted and the path is processed again by
0752 REF-walk.
0753 
0754 If RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure
0755 that, had REF-walk taken counted references on each vfsmount, the
0756 results would have been the same.  This ensures the invariant holds,
0757 at least for vfsmount structures.
0758 
0759 ``dentry->d_seq`` and ``nd->seq``
0760 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0761 
0762 In place of taking a count or lock on ``d_reflock``, RCU-walk samples
0763 the per-dentry ``d_seq`` seqlock, and stores the sequence number in the
0764 ``seq`` field of the nameidata structure, so ``nd->seq`` should always be
0765 the current sequence number of ``nd->dentry``.  This number needs to be
0766 revalidated after copying, and before using, the name, parent, or
0767 inode of the dentry.
0768 
0769 The handling of the name we have already looked at, and the parent is
0770 only accessed in ``follow_dotdot_rcu()`` which fairly trivially follows
0771 the required pattern, though it does so for three different cases.
0772 
0773 When not at a mount point, ``d_parent`` is followed and its ``d_seq`` is
0774 collected.  When we are at a mount point, we instead follow the
0775 ``mnt->mnt_mountpoint`` link to get a new dentry and collect its
0776 ``d_seq``.  Then, after finally finding a ``d_parent`` to follow, we must
0777 check if we have landed on a mount point and, if so, must find that
0778 mount point and follow the ``mnt->mnt_root`` link.  This would imply a
0779 somewhat unusual, but certainly possible, circumstance where the
0780 starting point of the path lookup was in part of the filesystem that
0781 was mounted on, and so not visible from the root.
0782 
0783 The inode pointer, stored in ``->d_inode``, is a little more
0784 interesting.  The inode will always need to be accessed at least
0785 twice, once to determine if it is NULL and once to verify access
0786 permissions.  Symlink handling requires a validated inode pointer too.
0787 Rather than revalidating on each access, a copy is made on the first
0788 access and it is stored in the ``inode`` field of ``nameidata`` from where
0789 it can be safely accessed without further validation.
0790 
0791 ``lookup_fast()`` is the only lookup routine that is used in RCU-mode,
0792 ``lookup_slow()`` being too slow and requiring locks.  It is in
0793 ``lookup_fast()`` that we find the important "hand over hand" tracking
0794 of the current dentry.
0795 
0796 The current ``dentry`` and current ``seq`` number are passed to
0797 ``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a
0798 new ``seq`` number.  ``lookup_fast()`` then copies the inode pointer and
0799 revalidates the new ``seq`` number.  It then validates the old ``dentry``
0800 with the old ``seq`` number one last time and only then continues.  This
0801 process of getting the ``seq`` number of the new dentry and then
0802 checking the ``seq`` number of the old exactly mirrors the process of
0803 getting a counted reference to the new dentry before dropping that for
0804 the old dentry which we saw in REF-walk.
0805 
0806 No ``inode->i_rwsem`` or even ``rename_lock``
0807 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0808 
0809 A semaphore is a fairly heavyweight lock that can only be taken when it is
0810 permissible to sleep.  As ``rcu_read_lock()`` forbids sleeping,
0811 ``inode->i_rwsem`` plays no role in RCU-walk.  If some other thread does
0812 take ``i_rwsem`` and modifies the directory in a way that RCU-walk needs
0813 to notice, the result will be either that RCU-walk fails to find the
0814 dentry that it is looking for, or it will find a dentry which
0815 ``read_seqretry()`` won't validate.  In either case it will drop down to
0816 REF-walk mode which can take whatever locks are needed.
0817 
0818 Though ``rename_lock`` could be used by RCU-walk as it doesn't require
0819 any sleeping, RCU-walk doesn't bother.  REF-walk uses ``rename_lock`` to
0820 protect against the possibility of hash chains in the dcache changing
0821 while they are being searched.  This can result in failing to find
0822 something that actually is there.  When RCU-walk fails to find
0823 something in the dentry cache, whether it is really there or not, it
0824 already drops down to REF-walk and tries again with appropriate
0825 locking.  This neatly handles all cases, so adding extra checks on
0826 rename_lock would bring no significant value.
0827 
0828 ``unlazy walk()`` and ``complete_walk()``
0829 -----------------------------------------
0830 
0831 That "dropping down to REF-walk" typically involves a call to
0832 ``unlazy_walk()``, so named because "RCU-walk" is also sometimes
0833 referred to as "lazy walk".  ``unlazy_walk()`` is called when
0834 following the path down to the current vfsmount/dentry pair seems to
0835 have proceeded successfully, but the next step is problematic.  This
0836 can happen if the next name cannot be found in the dcache, if
0837 permission checking or name revalidation couldn't be achieved while
0838 the ``rcu_read_lock()`` is held (which forbids sleeping), if an
0839 automount point is found, or in a couple of cases involving symlinks.
0840 It is also called from ``complete_walk()`` when the lookup has reached
0841 the final component, or the very end of the path, depending on which
0842 particular flavor of lookup is used.
0843 
0844 Other reasons for dropping out of RCU-walk that do not trigger a call
0845 to ``unlazy_walk()`` are when some inconsistency is found that cannot be
0846 handled immediately, such as ``mount_lock`` or one of the ``d_seq``
0847 seqlocks reporting a change.  In these cases the relevant function
0848 will return ``-ECHILD`` which will percolate up until it triggers a new
0849 attempt from the top using REF-walk.
0850 
0851 For those cases where ``unlazy_walk()`` is an option, it essentially
0852 takes a reference on each of the pointers that it holds (vfsmount,
0853 dentry, and possibly some symbolic links) and then verifies that the
0854 relevant seqlocks have not been changed.  If there have been changes,
0855 it, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk
0856 has been a success and the lookup process continues.
0857 
0858 Taking a reference on those pointers is not quite as simple as just
0859 incrementing a counter.  That works to take a second reference if you
0860 already have one (often indirectly through another object), but it
0861 isn't sufficient if you don't actually have a counted reference at
0862 all.  For ``dentry->d_lockref``, it is safe to increment the reference
0863 counter to get a reference unless it has been explicitly marked as
0864 "dead" which involves setting the counter to ``-128``.
0865 ``lockref_get_not_dead()`` achieves this.
0866 
0867 For ``mnt->mnt_count`` it is safe to take a reference as long as
0868 ``mount_lock`` is then used to validate the reference.  If that
0869 validation fails, it may *not* be safe to just drop that reference in
0870 the standard way of calling ``mnt_put()`` - an unmount may have
0871 progressed too far.  So the code in ``legitimize_mnt()``, when it
0872 finds that the reference it got might not be safe, checks the
0873 ``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is
0874 correct, or if it should just decrement the count and pretend none of
0875 this ever happened.
0876 
0877 Taking care in filesystems
0878 --------------------------
0879 
0880 RCU-walk depends almost entirely on cached information and often will
0881 not call into the filesystem at all.  However there are two places,
0882 besides the already-mentioned component-name comparison, where the
0883 file system might be included in RCU-walk, and it must know to be
0884 careful.
0885 
0886 If the filesystem has non-standard permission-checking requirements -
0887 such as a networked filesystem which may need to check with the server
0888 - the ``i_op->permission`` interface might be called during RCU-walk.
0889 In this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it
0890 knows not to sleep, but to return ``-ECHILD`` if it cannot complete
0891 promptly.  ``i_op->permission`` is given the inode pointer, not the
0892 dentry, so it doesn't need to worry about further consistency checks.
0893 However if it accesses any other filesystem data structures, it must
0894 ensure they are safe to be accessed with only the ``rcu_read_lock()``
0895 held.  This typically means they must be freed using ``kfree_rcu()`` or
0896 similar.
0897 
0898 .. _READ_ONCE: https://lwn.net/Articles/624126/
0899 
0900 If the filesystem may need to revalidate dcache entries, then
0901 ``d_op->d_revalidate`` may be called in RCU-walk too.  This interface
0902 *is* passed the dentry but does not have access to the ``inode`` or the
0903 ``seq`` number from the ``nameidata``, so it needs to be extra careful
0904 when accessing fields in the dentry.  This "extra care" typically
0905 involves using  `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the
0906 result is not NULL before using it.  This pattern can be seen in
0907 ``nfs_lookup_revalidate()``.
0908 
0909 A pair of patterns
0910 ------------------
0911 
0912 In various places in the details of REF-walk and RCU-walk, and also in
0913 the big picture, there are a couple of related patterns that are worth
0914 being aware of.
0915 
0916 The first is "try quickly and check, if that fails try slowly".  We
0917 can see that in the high-level approach of first trying RCU-walk and
0918 then trying REF-walk, and in places where ``unlazy_walk()`` is used to
0919 switch to REF-walk for the rest of the path.  We also saw it earlier
0920 in ``dget_parent()`` when following a "``..``" link.  It tries a quick way
0921 to get a reference, then falls back to taking locks if needed.
0922 
0923 The second pattern is "try quickly and check, if that fails try
0924 again - repeatedly".  This is seen with the use of ``rename_lock`` and
0925 ``mount_lock`` in REF-walk.  RCU-walk doesn't make use of this pattern -
0926 if anything goes wrong it is much safer to just abort and try a more
0927 sedate approach.
0928 
0929 The emphasis here is "try quickly and check".  It should probably be
0930 "try quickly *and carefully*, then check".  The fact that checking is
0931 needed is a reminder that the system is dynamic and only a limited
0932 number of things are safe at all.  The most likely cause of errors in
0933 this whole process is assuming something is safe when in reality it
0934 isn't.  Careful consideration of what exactly guarantees the safety of
0935 each access is sometimes necessary.
0936 
0937 A walk among the symlinks
0938 =========================
0939 
0940 There are several basic issues that we will examine to understand the
0941 handling of symbolic links:  the symlink stack, together with cache
0942 lifetimes, will help us understand the overall recursive handling of
0943 symlinks and lead to the special care needed for the final component.
0944 Then a consideration of access-time updates and summary of the various
0945 flags controlling lookup will finish the story.
0946 
0947 The symlink stack
0948 -----------------
0949 
0950 There are only two sorts of filesystem objects that can usefully
0951 appear in a path prior to the final component: directories and symlinks.
0952 Handling directories is quite straightforward: the new directory
0953 simply becomes the starting point at which to interpret the next
0954 component on the path.  Handling symbolic links requires a bit more
0955 work.
0956 
0957 Conceptually, symbolic links could be handled by editing the path.  If
0958 a component name refers to a symbolic link, then that component is
0959 replaced by the body of the link and, if that body starts with a '/',
0960 then all preceding parts of the path are discarded.  This is what the
0961 "``readlink -f``" command does, though it also edits out "``.``" and
0962 "``..``" components.
0963 
0964 Directly editing the path string is not really necessary when looking
0965 up a path, and discarding early components is pointless as they aren't
0966 looked at anyway.  Keeping track of all remaining components is
0967 important, but they can of course be kept separately; there is no need
0968 to concatenate them.  As one symlink may easily refer to another,
0969 which in turn can refer to a third, we may need to keep the remaining
0970 components of several paths, each to be processed when the preceding
0971 ones are completed.  These path remnants are kept on a stack of
0972 limited size.
0973 
0974 There are two reasons for placing limits on how many symlinks can
0975 occur in a single path lookup.  The most obvious is to avoid loops.
0976 If a symlink referred to itself either directly or through
0977 intermediaries, then following the symlink can never complete
0978 successfully - the error ``ELOOP`` must be returned.  Loops can be
0979 detected without imposing limits, but limits are the simplest solution
0980 and, given the second reason for restriction, quite sufficient.
0981 
0982 .. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550
0983 
0984 The second reason was `outlined recently`_ by Linus:
0985 
0986    Because it's a latency and DoS issue too. We need to react well to
0987    true loops, but also to "very deep" non-loops. It's not about memory
0988    use, it's about users triggering unreasonable CPU resources.
0989 
0990 Linux imposes a limit on the length of any pathname: ``PATH_MAX``, which
0991 is 4096.  There are a number of reasons for this limit; not letting the
0992 kernel spend too much time on just one path is one of them.  With
0993 symbolic links you can effectively generate much longer paths so some
0994 sort of limit is needed for the same reason.  Linux imposes a limit of
0995 at most 40 (MAXSYMLINKS) symlinks in any one path lookup.  It previously imposed
0996 a further limit of eight on the maximum depth of recursion, but that was
0997 raised to 40 when a separate stack was implemented, so there is now
0998 just the one limit.
0999 
1000 The ``nameidata`` structure that we met in an earlier article contains a
1001 small stack that can be used to store the remaining part of up to two
1002 symlinks.  In many cases this will be sufficient.  If it isn't, a
1003 separate stack is allocated with room for 40 symlinks.  Pathname
1004 lookup will never exceed that stack as, once the 40th symlink is
1005 detected, an error is returned.
1006 
1007 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 that, we need to move on to
1009 cache lifetimes.
1010 
1011 Storage and lifetime of cached symlinks
1012 ---------------------------------------
1013 
1014 Like other filesystem resources, such as inodes and directory
1015 entries, symlinks are cached by Linux to avoid repeated costly access
1016 to external storage.  It is particularly important for RCU-walk to be
1017 able to find and temporarily hold onto these cached entries, so that
1018 it doesn't need to drop down into REF-walk.
1019 
1020 .. _object-oriented design pattern: https://lwn.net/Articles/446317/
1021 
1022 While each filesystem is free to make its own choice, symlinks are
1023 typically stored in one of two places.  Short symlinks are often
1024 stored directly in the inode.  When a filesystem allocates a ``struct
1025 inode`` it typically allocates extra space to store private data (a
1026 common `object-oriented design pattern`_ in the kernel).  This will
1027 sometimes include space for a symlink.  The other common location is
1028 in the page cache, which normally stores the content of files.  The
1029 pathname in a symlink can be seen as the content of that symlink and
1030 can easily be stored in the page cache just like file content.
1031 
1032 When neither of these is suitable, the next most likely scenario is
1033 that the filesystem will allocate some temporary memory and copy or
1034 construct the symlink content into that memory whenever it is needed.
1035 
1036 When the symlink is stored in the inode, it has the same lifetime as
1037 the inode which, itself, is protected by RCU or by a counted reference
1038 on the dentry.  This means that the mechanisms that pathname lookup
1039 uses to access the dcache and icache (inode cache) safely are quite
1040 sufficient for accessing some cached symlinks safely.  In these cases,
1041 the ``i_link`` pointer in the inode is set to point to wherever the
1042 symlink is stored and it can be accessed directly whenever needed.
1043 
1044 When the symlink is stored in the page cache or elsewhere, the
1045 situation is not so straightforward.  A reference on a dentry or even
1046 on an inode does not imply any reference on cached pages of that
1047 inode, and even an ``rcu_read_lock()`` is not sufficient to ensure that
1048 a page will not disappear.  So for these symlinks the pathname lookup
1049 code needs to ask the filesystem to provide a stable reference and,
1050 significantly, needs to release that reference when it is finished
1051 with it.
1052 
1053 Taking a reference to a cache page is often possible even in RCU-walk
1054 mode.  It does require making changes to memory, which is best avoided,
1055 but that isn't necessarily a big cost and it is better than dropping
1056 out of RCU-walk mode completely.  Even filesystems that allocate
1057 space to copy the symlink into can use ``GFP_ATOMIC`` to often successfully
1058 allocate memory without the need to drop out of RCU-walk.  If a
1059 filesystem cannot successfully get a reference in RCU-walk mode, it
1060 must return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to
1061 REF-walk mode in which the filesystem is allowed to sleep.
1062 
1063 The place for all this to happen is the ``i_op->get_link()`` inode
1064 method. This is called both in RCU-walk and REF-walk. In RCU-walk the
1065 ``dentry*`` argument is NULL, ``->get_link()`` can return -ECHILD to drop out of
1066 RCU-walk.  Much like the ``i_op->permission()`` method we
1067 looked at previously, ``->get_link()`` would need to be careful that
1068 all the data structures it references are safe to be accessed while
1069 holding no counted reference, only the RCU lock. A callback
1070 ``struct delayed_called`` will be passed to ``->get_link()``:
1071 file systems can set their own put_link function and argument through
1072 set_delayed_call(). Later on, when VFS wants to put link, it will call
1073 do_delayed_call() to invoke that callback function with the argument.
1074 
1075 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 stack needs to contain,
1077 along with the path remnants:
1078 
1079 - the ``struct path`` to provide a reference to the previous path
1080 - the ``const char *`` to provide a reference to the to previous name
1081 - the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk
1082 - the ``struct delayed_call`` for later invocation.
1083 
1084 This means that each entry in the symlink stack needs to hold five
1085 pointers and an integer instead of just one pointer (the path
1086 remnant).  On a 64-bit system, this is about 40 bytes per entry;
1087 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, but is by no means
1089 excessive.
1090 
1091 Note that, in a given stack frame, the path remnant (``name``) is not
1092 part of the symlink that the other fields refer to.  It is the remnant
1093 to be followed once that symlink has been fully parsed.
1094 
1095 Following the symlink
1096 ---------------------
1097 
1098 The main loop in ``link_path_walk()`` iterates seamlessly over all
1099 components in the path and all of the non-final symlinks.  As symlinks
1100 are processed, the ``name`` pointer is adjusted to point to a new
1101 symlink, or is restored from the stack, so that much of the loop
1102 doesn't need to notice.  Getting this ``name`` variable on and off the
1103 stack is very straightforward; pushing and popping the references is
1104 a little more complex.
1105 
1106 When a symlink is found, walk_component() calls pick_link() via step_into()
1107 which returns the link from the filesystem.
1108 Providing that operation is successful, the old path ``name`` is placed on the
1109 stack, 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'``) the old ``name`` is restored
1111 off the stack and path walking continues.
1112 
1113 Pushing and popping the reference pointers (inode, cookie, etc.) is more
1114 complex in part because of the desire to handle tail recursion.  When
1115 the last component of a symlink itself points to a symlink, we
1116 want to pop the symlink-just-completed off the stack before pushing
1117 the symlink-just-found to avoid leaving empty path remnants that would
1118 just get in the way.
1119 
1120 It is most convenient to push the new symlink references onto the
1121 stack in ``walk_component()`` immediately when the symlink is found;
1122 ``walk_component()`` is also the last piece of code that needs to look at the
1123 old symlink as it walks that last component.  So it is quite
1124 convenient for ``walk_component()`` to release the old symlink and pop
1125 the references just before pushing the reference information for the
1126 new symlink.  It is guided in this by three flags: ``WALK_NOFOLLOW`` which
1127 forbids it from following a symlink if it finds one, ``WALK_MORE``
1128 which indicates that it is yet too early to release the
1129 current symlink, and ``WALK_TRAILING`` which indicates that it is on the final
1130 component of the lookup, so we will check userspace flag ``LOOKUP_FOLLOW`` to
1131 decide whether follow it when it is a symlink and call ``may_follow_link()`` to
1132 check if we have privilege to follow it.
1133 
1134 Symlinks with no final component
1135 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1136 
1137 A pair of special-case symlinks deserve a little further explanation.
1138 Both result in a new ``struct path`` (with mount and dentry) being set
1139 up in the ``nameidata``, and result in pick_link() returning ``NULL``.
1140 
1141 The more obvious case is a symlink to "``/``".  All symlinks starting
1142 with "``/``" are detected in pick_link() which resets the ``nameidata``
1143 to point to the effective filesystem root.  If the symlink only
1144 contains "``/``" then there is nothing more to do, no components at all,
1145 so ``NULL`` is returned to indicate that the symlink can be released and
1146 the stack frame discarded.
1147 
1148 The other case involves things in ``/proc`` that look like symlinks but
1149 aren't really (and are therefore commonly referred to as "magic-links")::
1150 
1151      $ ls -l /proc/self/fd/1
1152      lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4
1153 
1154 Every open file descriptor in any process is represented in ``/proc`` by
1155 something that looks like a symlink.  It is really a reference to the
1156 target file, not just the name of it.  When you ``readlink`` these
1157 objects you get a name that might refer to the same file - unless it
1158 has been unlinked or mounted over.  When ``walk_component()`` follows
1159 one of these, the ``->get_link()`` method in "procfs" doesn't return
1160 a string name, but instead calls nd_jump_link() which updates the
1161 ``nameidata`` in place to point to that target.  ``->get_link()`` then
1162 returns ``NULL``.  Again there is no final component and pick_link()
1163 returns ``NULL``.
1164 
1165 Following the symlink in the final component
1166 --------------------------------------------
1167 
1168 All this leads to ``link_path_walk()`` walking down every component, and
1169 following all symbolic links it finds, until it reaches the final
1170 component.  This is just returned in the ``last`` field of ``nameidata``.
1171 For some callers, this is all they need; they want to create that
1172 ``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 is found, and possibly
1174 apply special handling to the last component of that symlink, rather
1175 than just the last component of the original file name.  These callers
1176 potentially need to call ``link_path_walk()`` again and again on
1177 successive symlinks until one is found that doesn't point to another
1178 symlink.
1179 
1180 This case is handled by relevant callers of link_path_walk(), such as
1181 path_lookupat(), path_openat() using a loop that calls link_path_walk(),
1182 and then handles the final component by calling open_last_lookups() or
1183 lookup_last(). If it is a symlink that needs to be followed,
1184 open_last_lookups() or lookup_last() will set things up properly and
1185 return the path so that the loop repeats, calling
1186 link_path_walk() again.  This could loop as many as 40 times if the last
1187 component of each symlink is another symlink.
1188 
1189 Of the various functions that examine the final component, 
1190 open_last_lookups() is the most interesting as it works in tandem
1191 with do_open() for opening a file.  Part of open_last_lookups() runs
1192 with ``i_rwsem`` held and this part is in a separate function: lookup_open().
1193 
1194 Explaining open_last_lookups() and do_open() completely is beyond the scope
1195 of this article, but a few highlights should help those interested in exploring
1196 the code.
1197 
1198 1. Rather than just finding the target file, do_open() is used after
1199    open_last_lookup() to open
1200    it.  If the file was found in the dcache, then ``vfs_open()`` is used for
1201    this.  If not, then ``lookup_open()`` will either call ``atomic_open()`` (if
1202    the filesystem provides it) to combine the final lookup with the open, or
1203    will perform the separate ``i_op->lookup()`` and ``i_op->create()`` steps
1204    directly.  In the later case the actual "open" of this newly found or
1205    created file will be performed by vfs_open(), just as if the name
1206    were found in the dcache.
1207 
1208 2. vfs_open() can fail with ``-EOPENSTALE`` if the cached information
1209    wasn't quite current enough.  If it's in RCU-walk ``-ECHILD`` will be returned
1210    otherwise ``-ESTALE`` is returned.  When ``-ESTALE`` is returned, the caller may
1211    retry with ``LOOKUP_REVAL`` flag set.
1212 
1213 3. An open with O_CREAT **does** follow a symlink in the final component,
1214    unlike other creation system calls (like ``mkdir``).  So the sequence::
1215 
1216           ln -s bar /tmp/foo
1217           echo hello > /tmp/foo
1218 
1219    will create a file called ``/tmp/bar``.  This is not permitted if
1220    ``O_EXCL`` is set but otherwise is handled for an O_CREAT open much
1221    like for a non-creating open: lookup_last() or open_last_lookup()
1222    returns a non ``NULL`` value, and link_path_walk() gets called and the
1223    open process continues on the symlink that was found.
1224 
1225 Updating the access time
1226 ------------------------
1227 
1228 We previously said of RCU-walk that it would "take no locks, increment
1229 no counts, leave no footprints."  We have since seen that some
1230 "footprints" can be needed when handling symlinks as a counted
1231 reference (or even a memory allocation) may be needed.  But these
1232 footprints are best kept to a minimum.
1233 
1234 One other place where walking down a symlink can involve leaving
1235 footprints in a way that doesn't affect directories is in updating access times.
1236 In Unix (and Linux) every filesystem object has a "last accessed
1237 time", or "``atime``".  Passing through a directory to access a file
1238 within is not considered to be an access for the purposes of
1239 ``atime``; only listing the contents of a directory can update its ``atime``.
1240 Symlinks are different it seems.  Both reading a symlink (with ``readlink()``)
1241 and looking up a symlink on the way to some other destination can
1242 update the atime on that symlink.
1243 
1244 .. _clearest statement: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08
1245 
1246 It is not clear why this is the case; POSIX has little to say on the
1247 subject.  The `clearest statement`_ is that, if a particular implementation
1248 updates a timestamp in a place not specified by POSIX, this must be
1249 documented "except that any changes caused by pathname resolution need
1250 not be documented".  This seems to imply that POSIX doesn't really
1251 care about access-time updates during pathname lookup.
1252 
1253 .. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8
1254 
1255 An examination of history shows that prior to `Linux 1.3.87`_, the ext2
1256 filesystem, at least, didn't update atime when following a link.
1257 Unfortunately we have no record of why that behavior was changed.
1258 
1259 In any case, access time must now be updated and that operation can be
1260 quite complex.  Trying to stay in RCU-walk while doing it is best
1261 avoided.  Fortunately it is often permitted to skip the ``atime``
1262 update.  Because ``atime`` updates cause performance problems in various
1263 areas, Linux supports the ``relatime`` mount option, which generally
1264 limits the updates of ``atime`` to once per day on files that aren't
1265 being changed (and symlinks never change once created).  Even without
1266 ``relatime``, many filesystems record ``atime`` with a one-second
1267 granularity, so only one update per second is required.
1268 
1269 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 skipped and RCU-walk mode
1271 continues.  Only when an ``atime`` update is actually required does the
1272 path walk drop down to REF-walk.  All of this is handled in the
1273 ``get_link()`` function.
1274 
1275 A few flags
1276 -----------
1277 
1278 A suitable way to wrap up this tour of pathname walking is to list
1279 the various flags that can be stored in the ``nameidata`` to guide the
1280 lookup process.  Many of these are only meaningful on the final
1281 component, others reflect the current state of the pathname lookup, and some
1282 apply restrictions to all path components encountered in the path lookup.
1283 
1284 And then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with
1285 the others.  If this is not set, an empty pathname causes an error
1286 very early on.  If it is set, empty pathnames are not considered to be
1287 an error.
1288 
1289 Global state flags
1290 ~~~~~~~~~~~~~~~~~~
1291 
1292 We have already met two global state flags: ``LOOKUP_RCU`` and
1293 ``LOOKUP_REVAL``.  These select between one of three overall approaches
1294 to lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.
1295 
1296 ``LOOKUP_PARENT`` indicates that the final component hasn't been reached
1297 yet.  This is primarily used to tell the audit subsystem the full
1298 context of a particular access being audited.
1299 
1300 ``ND_ROOT_PRESET`` indicates that the ``root`` field in the ``nameidata`` was
1301 provided by the caller, so it shouldn't be released when it is no
1302 longer needed.
1303 
1304 ``ND_JUMPED`` means that the current dentry was chosen not because
1305 it had the right name but for some other reason.  This happens when
1306 following "``..``", following a symlink to ``/``, crossing a mount point
1307 or accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic
1308 link"). In this case the filesystem has not been asked to revalidate the
1309 name (with ``d_revalidate()``).  In such cases the inode may still need
1310 to be revalidated, so ``d_op->d_weak_revalidate()`` is called if
1311 ``ND_JUMPED`` is set when the look completes - which may be at the
1312 final component or, when creating, unlinking, or renaming, at the penultimate component.
1313 
1314 Resolution-restriction flags
1315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1316 
1317 In order to allow userspace to protect itself against certain race conditions
1318 and attack scenarios involving changing path components, a series of flags are
1319 available which apply restrictions to all path components encountered during
1320 path lookup. These flags are exposed through ``openat2()``'s ``resolve`` field.
1321 
1322 ``LOOKUP_NO_SYMLINKS`` blocks all symlink traversals (including magic-links).
1323 This is distinctly different from ``LOOKUP_FOLLOW``, because the latter only
1324 relates to restricting the following of trailing symlinks.
1325 
1326 ``LOOKUP_NO_MAGICLINKS`` blocks all magic-link traversals. Filesystems must
1327 ensure that they return errors from ``nd_jump_link()``, because that is how
1328 ``LOOKUP_NO_MAGICLINKS`` and other magic-link restrictions are implemented.
1329 
1330 ``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` traversals (this includes both
1331 bind-mounts and ordinary mounts). Note that the ``vfsmount`` which contains the
1332 lookup is determined by the first mountpoint the path lookup reaches --
1333 absolute paths start with the ``vfsmount`` of ``/``, and relative paths start
1334 with the ``dfd``'s ``vfsmount``. Magic-links are only permitted if the
1335 ``vfsmount`` of the path is unchanged.
1336 
1337 ``LOOKUP_BENEATH`` blocks any path components which resolve outside the
1338 starting point of the resolution. This is done by blocking ``nd_jump_root()``
1339 as well as blocking ".." if it would jump outside the starting point.
1340 ``rename_lock`` and ``mount_lock`` are used to detect attacks against the
1341 resolution of "..". Magic-links are also blocked.
1342 
1343 ``LOOKUP_IN_ROOT`` resolves all path components as though the starting point
1344 were the filesystem root. ``nd_jump_root()`` brings the resolution back to
1345 the starting point, and ".." at the starting point will act as a no-op. As with
1346 ``LOOKUP_BENEATH``, ``rename_lock`` and ``mount_lock`` are used to detect
1347 attacks against ".." resolution. Magic-links are also blocked.
1348 
1349 Final-component flags
1350 ~~~~~~~~~~~~~~~~~~~~~
1351 
1352 Some of these flags are only set when the final component is being
1353 considered.  Others are only checked for when considering that final
1354 component.
1355 
1356 ``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount
1357 point, then the mount is triggered.  Some operations would trigger it
1358 anyway, but operations like ``stat()`` deliberately don't.  ``statfs()``
1359 needs to trigger the mount but otherwise behaves a lot like ``stat()``, so
1360 it sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of
1361 "``mount --bind``".
1362 
1363 ``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for
1364 symlinks.  Some system calls set or clear it implicitly, while
1365 others have API flags such as ``AT_SYMLINK_FOLLOW`` and
1366 ``UMOUNT_NOFOLLOW`` to control it.  Its effect is similar to
1367 ``WALK_GET`` that we already met, but it is used in a different way.
1368 
1369 ``LOOKUP_DIRECTORY`` insists that the final component is a directory.
1370 Various callers set this and it is also set when the final component
1371 is found to be followed by a slash.
1372 
1373 Finally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and
1374 ``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made
1375 available to the filesystem and particularly the ``->d_revalidate()``
1376 method.  A filesystem can choose not to bother revalidating too hard
1377 if it knows that it will be asked to open or create the file soon.
1378 These flags were previously useful for ``->lookup()`` too but with the
1379 introduction of ``->atomic_open()`` they are less relevant there.
1380 
1381 End of the road
1382 ---------------
1383 
1384 Despite its complexity, all this pathname lookup code appears to be
1385 in good shape - various parts are certainly easier to understand now
1386 than even a couple of releases ago.  But that doesn't mean it is
1387 "finished".   As already mentioned, RCU-walk currently only follows
1388 symlinks that are stored in the inode so, while it handles many ext4
1389 symlinks, it doesn't help with NFS, XFS, or Btrfs.  That support
1390 is not likely to be long delayed.