xref: /linux/Documentation/filesystems/path-lookup.rst (revision 084c86837a3583c7cf56d74f91fb8e6191f99a8a)
14064174bSJonathan Corbet===============
24064174bSJonathan CorbetPathname lookup
34064174bSJonathan Corbet===============
44064174bSJonathan Corbet
54064174bSJonathan CorbetThis write-up is based on three articles published at lwn.net:
64064174bSJonathan Corbet
74064174bSJonathan Corbet- <https://lwn.net/Articles/649115/> Pathname lookup in Linux
84064174bSJonathan Corbet- <https://lwn.net/Articles/649729/> RCU-walk: faster pathname lookup in Linux
94064174bSJonathan Corbet- <https://lwn.net/Articles/650786/> A walk among the symlinks
104064174bSJonathan Corbet
114064174bSJonathan CorbetWritten by Neil Brown with help from Al Viro and Jon Corbet.
124064174bSJonathan CorbetIt has subsequently been updated to reflect changes in the kernel
134064174bSJonathan Corbetincluding:
144064174bSJonathan Corbet
154064174bSJonathan Corbet- per-directory parallel name lookup.
16b55eef87SAleksa Sarai- ``openat2()`` resolution restriction flags.
177bbfd9adSNeilBrown
187bbfd9adSNeilBrownIntroduction to pathname lookup
197bbfd9adSNeilBrown===============================
207bbfd9adSNeilBrown
217bbfd9adSNeilBrownThe most obvious aspect of pathname lookup, which very little
227bbfd9adSNeilBrownexploration is needed to discover, is that it is complex.  There are
237bbfd9adSNeilBrownmany rules, special cases, and implementation alternatives that all
247bbfd9adSNeilBrowncombine to confuse the unwary reader.  Computer science has long been
257bbfd9adSNeilBrownacquainted with such complexity and has tools to help manage it.  One
267bbfd9adSNeilBrowntool that we will make extensive use of is "divide and conquer".  For
277bbfd9adSNeilBrownthe early parts of the analysis we will divide off symlinks - leaving
287bbfd9adSNeilBrownthem until the final part.  Well before we get to symlinks we have
297bbfd9adSNeilBrownanother major division based on the VFS's approach to locking which
307bbfd9adSNeilBrownwill allow us to review "REF-walk" and "RCU-walk" separately.  But we
317bbfd9adSNeilBrownare getting ahead of ourselves.  There are some important low level
327bbfd9adSNeilBrowndistinctions we need to clarify first.
337bbfd9adSNeilBrown
347bbfd9adSNeilBrownThere are two sorts of ...
357bbfd9adSNeilBrown--------------------------
367bbfd9adSNeilBrown
377bbfd9adSNeilBrown.. _openat: http://man7.org/linux/man-pages/man2/openat.2.html
387bbfd9adSNeilBrown
397bbfd9adSNeilBrownPathnames (sometimes "file names"), used to identify objects in the
407bbfd9adSNeilBrownfilesystem, will be familiar to most readers.  They contain two sorts
417bbfd9adSNeilBrownof elements: "slashes" that are sequences of one or more "``/``"
427bbfd9adSNeilBrowncharacters, and "components" that are sequences of one or more
437bbfd9adSNeilBrownnon-"``/``" characters.  These form two kinds of paths.  Those that
447bbfd9adSNeilBrownstart with slashes are "absolute" and start from the filesystem root.
457bbfd9adSNeilBrownThe others are "relative" and start from the current directory, or
4687b92d4bSVegard Nossumfrom some other location specified by a file descriptor given to
4787b92d4bSVegard Nossum"``*at()``" system calls such as `openat() <openat_>`_.
487bbfd9adSNeilBrown
497bbfd9adSNeilBrown.. _execveat: http://man7.org/linux/man-pages/man2/execveat.2.html
507bbfd9adSNeilBrown
517bbfd9adSNeilBrownIt is tempting to describe the second kind as starting with a
527bbfd9adSNeilBrowncomponent, but that isn't always accurate: a pathname can lack both
537bbfd9adSNeilBrownslashes and components, it can be empty, in other words.  This is
5487b92d4bSVegard Nossumgenerally forbidden in POSIX, but some of those "``*at()``" system calls
557bbfd9adSNeilBrownin Linux permit it when the ``AT_EMPTY_PATH`` flag is given.  For
567bbfd9adSNeilBrownexample, if you have an open file descriptor on an executable file you
577bbfd9adSNeilBrowncan execute it by calling `execveat() <execveat_>`_ passing
587bbfd9adSNeilBrownthe file descriptor, an empty path, and the ``AT_EMPTY_PATH`` flag.
597bbfd9adSNeilBrown
607bbfd9adSNeilBrownThese paths can be divided into two sections: the final component and
617bbfd9adSNeilBrowneverything else.  The "everything else" is the easy bit.  In all cases
627bbfd9adSNeilBrownit must identify a directory that already exists, otherwise an error
637bbfd9adSNeilBrownsuch as ``ENOENT`` or ``ENOTDIR`` will be reported.
647bbfd9adSNeilBrown
657bbfd9adSNeilBrownThe final component is not so simple.  Not only do different system
667bbfd9adSNeilBrowncalls interpret it quite differently (e.g. some create it, some do
677bbfd9adSNeilBrownnot), but it might not even exist: neither the empty pathname nor the
687bbfd9adSNeilBrownpathname that is just slashes have a final component.  If it does
697bbfd9adSNeilBrownexist, it could be "``.``" or "``..``" which are handled quite differently
707bbfd9adSNeilBrownfrom other components.
717bbfd9adSNeilBrown
72c69f22f2SAlexander A. Klimov.. _POSIX: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
737bbfd9adSNeilBrown
747bbfd9adSNeilBrownIf a pathname ends with a slash, such as "``/tmp/foo/``" it might be
757bbfd9adSNeilBrowntempting to consider that to have an empty final component.  In many
767bbfd9adSNeilBrownways that would lead to correct results, but not always.  In
777bbfd9adSNeilBrownparticular, ``mkdir()`` and ``rmdir()`` each create or remove a directory named
787bbfd9adSNeilBrownby the final component, and they are required to work with pathnames
79ad551a21SVegard Nossumending in "``/``".  According to POSIX_:
807bbfd9adSNeilBrown
81ad551a21SVegard Nossum  A pathname that contains at least one non-<slash> character and
82ad551a21SVegard Nossum  that ends with one or more trailing <slash> characters shall not
837bbfd9adSNeilBrown  be resolved successfully unless the last pathname component before
847bbfd9adSNeilBrown  the trailing <slash> characters names an existing directory or a
857bbfd9adSNeilBrown  directory entry that is to be created for a directory immediately
867bbfd9adSNeilBrown  after the pathname is resolved.
877bbfd9adSNeilBrown
887bbfd9adSNeilBrownThe Linux pathname walking code (mostly in ``fs/namei.c``) deals with
897bbfd9adSNeilBrownall of these issues: breaking the path into components, handling the
907bbfd9adSNeilBrown"everything else" quite separately from the final component, and
917bbfd9adSNeilBrownchecking that the trailing slash is not used where it isn't
927bbfd9adSNeilBrownpermitted.  It also addresses the important issue of concurrent
937bbfd9adSNeilBrownaccess.
947bbfd9adSNeilBrown
957bbfd9adSNeilBrownWhile one process is looking up a pathname, another might be making
967bbfd9adSNeilBrownchanges that affect that lookup.  One fairly extreme case is that if
977bbfd9adSNeilBrown"a/b" were renamed to "a/c/b" while another process were looking up
987bbfd9adSNeilBrown"a/b/..", that process might successfully resolve on "a/c".
997bbfd9adSNeilBrownMost races are much more subtle, and a big part of the task of
1007bbfd9adSNeilBrownpathname lookup is to prevent them from having damaging effects.  Many
1017bbfd9adSNeilBrownof the possible races are seen most clearly in the context of the
1027bbfd9adSNeilBrown"dcache" and an understanding of that is central to understanding
1037bbfd9adSNeilBrownpathname lookup.
1047bbfd9adSNeilBrown
1057bbfd9adSNeilBrownMore than just a cache
1067bbfd9adSNeilBrown----------------------
1077bbfd9adSNeilBrown
1087bbfd9adSNeilBrownThe "dcache" caches information about names in each filesystem to
1097bbfd9adSNeilBrownmake them quickly available for lookup.  Each entry (known as a
1107bbfd9adSNeilBrown"dentry") contains three significant fields: a component name, a
1117bbfd9adSNeilBrownpointer to a parent dentry, and a pointer to the "inode" which
1127bbfd9adSNeilBrowncontains further information about the object in that parent with
1137bbfd9adSNeilBrownthe given name.  The inode pointer can be ``NULL`` indicating that the
1147bbfd9adSNeilBrownname doesn't exist in the parent.  While there can be linkage in the
1157bbfd9adSNeilBrowndentry of a directory to the dentries of the children, that linkage is
1167bbfd9adSNeilBrownnot used for pathname lookup, and so will not be considered here.
1177bbfd9adSNeilBrown
1187bbfd9adSNeilBrownThe dcache has a number of uses apart from accelerating lookup.  One
1197bbfd9adSNeilBrownthat will be particularly relevant is that it is closely integrated
1207bbfd9adSNeilBrownwith the mount table that records which filesystem is mounted where.
1217bbfd9adSNeilBrownWhat the mount table actually stores is which dentry is mounted on top
1227bbfd9adSNeilBrownof which other dentry.
1237bbfd9adSNeilBrown
1247bbfd9adSNeilBrownWhen considering the dcache, we have another of our "two types"
1257bbfd9adSNeilBrowndistinctions: there are two types of filesystems.
1267bbfd9adSNeilBrown
1277bbfd9adSNeilBrownSome filesystems ensure that the information in the dcache is always
1287bbfd9adSNeilBrowncompletely accurate (though not necessarily complete).  This can allow
1297bbfd9adSNeilBrownthe VFS to determine if a particular file does or doesn't exist
1307bbfd9adSNeilBrownwithout checking with the filesystem, and means that the VFS can
1317bbfd9adSNeilBrownprotect the filesystem against certain races and other problems.
1327bbfd9adSNeilBrownThese are typically "local" filesystems such as ext3, XFS, and Btrfs.
1337bbfd9adSNeilBrown
1347bbfd9adSNeilBrownOther filesystems don't provide that guarantee because they cannot.
1357bbfd9adSNeilBrownThese are typically filesystems that are shared across a network,
1367bbfd9adSNeilBrownwhether remote filesystems like NFS and 9P, or cluster filesystems
1377bbfd9adSNeilBrownlike ocfs2 or cephfs.  These filesystems allow the VFS to revalidate
1387bbfd9adSNeilBrowncached information, and must provide their own protection against
1397bbfd9adSNeilBrownawkward races.  The VFS can detect these filesystems by the
1407bbfd9adSNeilBrown``DCACHE_OP_REVALIDATE`` flag being set in the dentry.
1417bbfd9adSNeilBrown
1427bbfd9adSNeilBrownREF-walk: simple concurrency management with refcounts and spinlocks
1437bbfd9adSNeilBrown--------------------------------------------------------------------
1447bbfd9adSNeilBrown
1457bbfd9adSNeilBrownWith all of those divisions carefully classified, we can now start
1467bbfd9adSNeilBrownlooking at the actual process of walking along a path.  In particular
1477bbfd9adSNeilBrownwe will start with the handling of the "everything else" part of a
1487bbfd9adSNeilBrownpathname, and focus on the "REF-walk" approach to concurrency
1497bbfd9adSNeilBrownmanagement.  This code is found in the ``link_path_walk()`` function, if
1507bbfd9adSNeilBrownyou ignore all the places that only run when "``LOOKUP_RCU``"
1517bbfd9adSNeilBrown(indicating the use of RCU-walk) is set.
1527bbfd9adSNeilBrown
1537bbfd9adSNeilBrown.. _Meet the Lockers: https://lwn.net/Articles/453685/
1547bbfd9adSNeilBrown
1557bbfd9adSNeilBrownREF-walk is fairly heavy-handed with locks and reference counts.  Not
1567bbfd9adSNeilBrownas heavy-handed as in the old "big kernel lock" days, but certainly not
1577bbfd9adSNeilBrownafraid of taking a lock when one is needed.  It uses a variety of
1587bbfd9adSNeilBrowndifferent concurrency controls.  A background understanding of the
1597bbfd9adSNeilBrownvarious primitives is assumed, or can be gleaned from elsewhere such
1607bbfd9adSNeilBrownas in `Meet the Lockers`_.
1617bbfd9adSNeilBrown
1627bbfd9adSNeilBrownThe locking mechanisms used by REF-walk include:
1637bbfd9adSNeilBrown
1647bbfd9adSNeilBrowndentry->d_lockref
1657bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~
1667bbfd9adSNeilBrown
1677bbfd9adSNeilBrownThis uses the lockref primitive to provide both a spinlock and a
1687bbfd9adSNeilBrownreference count.  The special-sauce of this primitive is that the
1697bbfd9adSNeilBrownconceptual sequence "lock; inc_ref; unlock;" can often be performed
1707bbfd9adSNeilBrownwith a single atomic memory operation.
1717bbfd9adSNeilBrown
1727bbfd9adSNeilBrownHolding a reference on a dentry ensures that the dentry won't suddenly
1737bbfd9adSNeilBrownbe freed and used for something else, so the values in various fields
1747bbfd9adSNeilBrownwill behave as expected.  It also protects the ``->d_inode`` reference
1757bbfd9adSNeilBrownto the inode to some extent.
1767bbfd9adSNeilBrown
1777bbfd9adSNeilBrownThe association between a dentry and its inode is fairly permanent.
1787bbfd9adSNeilBrownFor example, when a file is renamed, the dentry and inode move
1797bbfd9adSNeilBrowntogether to the new location.  When a file is created the dentry will
1807bbfd9adSNeilBrowninitially be negative (i.e. ``d_inode`` is ``NULL``), and will be assigned
1817bbfd9adSNeilBrownto the new inode as part of the act of creation.
1827bbfd9adSNeilBrown
1837bbfd9adSNeilBrownWhen a file is deleted, this can be reflected in the cache either by
1847bbfd9adSNeilBrownsetting ``d_inode`` to ``NULL``, or by removing it from the hash table
1857bbfd9adSNeilBrown(described shortly) used to look up the name in the parent directory.
1867bbfd9adSNeilBrownIf the dentry is still in use the second option is used as it is
1877bbfd9adSNeilBrownperfectly legal to keep using an open file after it has been deleted
1887bbfd9adSNeilBrownand having the dentry around helps.  If the dentry is not otherwise in
1897bbfd9adSNeilBrownuse (i.e. if the refcount in ``d_lockref`` is one), only then will
1907bbfd9adSNeilBrown``d_inode`` be set to ``NULL``.  Doing it this way is more efficient for a
1917bbfd9adSNeilBrownvery common case.
1927bbfd9adSNeilBrown
1937bbfd9adSNeilBrownSo as long as a counted reference is held to a dentry, a non-``NULL`` ``->d_inode``
1947bbfd9adSNeilBrownvalue will never be changed.
1957bbfd9adSNeilBrown
1967bbfd9adSNeilBrowndentry->d_lock
1977bbfd9adSNeilBrown~~~~~~~~~~~~~~
1987bbfd9adSNeilBrown
1997bbfd9adSNeilBrown``d_lock`` is a synonym for the spinlock that is part of ``d_lockref`` above.
2007bbfd9adSNeilBrownFor our purposes, holding this lock protects against the dentry being
2017bbfd9adSNeilBrownrenamed or unlinked.  In particular, its parent (``d_parent``), and its
2027bbfd9adSNeilBrownname (``d_name``) cannot be changed, and it cannot be removed from the
2037bbfd9adSNeilBrowndentry hash table.
2047bbfd9adSNeilBrown
2057bbfd9adSNeilBrownWhen looking for a name in a directory, REF-walk takes ``d_lock`` on
2067bbfd9adSNeilBrowneach candidate dentry that it finds in the hash table and then checks
2077bbfd9adSNeilBrownthat the parent and name are correct.  So it doesn't lock the parent
2087bbfd9adSNeilBrownwhile searching in the cache; it only locks children.
2097bbfd9adSNeilBrown
2107bbfd9adSNeilBrownWhen looking for the parent for a given name (to handle "``..``"),
2117bbfd9adSNeilBrownREF-walk can take ``d_lock`` to get a stable reference to ``d_parent``,
2127bbfd9adSNeilBrownbut it first tries a more lightweight approach.  As seen in
2137bbfd9adSNeilBrown``dget_parent()``, if a reference can be claimed on the parent, and if
2147bbfd9adSNeilBrownsubsequently ``d_parent`` can be seen to have not changed, then there is
2157bbfd9adSNeilBrownno need to actually take the lock on the child.
2167bbfd9adSNeilBrown
2177bbfd9adSNeilBrownrename_lock
2187bbfd9adSNeilBrown~~~~~~~~~~~
2197bbfd9adSNeilBrown
2207bbfd9adSNeilBrownLooking up a given name in a given directory involves computing a hash
2217bbfd9adSNeilBrownfrom the two values (the name and the dentry of the directory),
2227bbfd9adSNeilBrownaccessing that slot in a hash table, and searching the linked list
2237bbfd9adSNeilBrownthat is found there.
2247bbfd9adSNeilBrown
2257bbfd9adSNeilBrownWhen a dentry is renamed, the name and the parent dentry can both
2267bbfd9adSNeilBrownchange so the hash will almost certainly change too.  This would move the
2277bbfd9adSNeilBrowndentry to a different chain in the hash table.  If a filename search
2287bbfd9adSNeilBrownhappened to be looking at a dentry that was moved in this way,
2297bbfd9adSNeilBrownit might end up continuing the search down the wrong chain,
2307bbfd9adSNeilBrownand so miss out on part of the correct chain.
2317bbfd9adSNeilBrown
232286b7e24SVegard NossumThe name-lookup process (``d_lookup()``) does *not* try to prevent this
2337bbfd9adSNeilBrownfrom happening, but only to detect when it happens.
2347bbfd9adSNeilBrown``rename_lock`` is a seqlock that is updated whenever any dentry is
2357bbfd9adSNeilBrownrenamed.  If ``d_lookup`` finds that a rename happened while it
2367bbfd9adSNeilBrownunsuccessfully scanned a chain in the hash table, it simply tries
2377bbfd9adSNeilBrownagain.
2387bbfd9adSNeilBrown
239b55eef87SAleksa Sarai``rename_lock`` is also used to detect and defend against potential attacks
240b55eef87SAleksa Saraiagainst ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
241b55eef87SAleksa Saraithe parent directory is moved outside the root, bypassing the ``path_equal()``
242b55eef87SAleksa Saraicheck). If ``rename_lock`` is updated during the lookup and the path encounters
243b55eef87SAleksa Saraia "..", a potential attack occurred and ``handle_dots()`` will bail out with
244b55eef87SAleksa Sarai``-EAGAIN``.
245b55eef87SAleksa Sarai
2467bbfd9adSNeilBrowninode->i_rwsem
2477bbfd9adSNeilBrown~~~~~~~~~~~~~~
2487bbfd9adSNeilBrown
2497bbfd9adSNeilBrown``i_rwsem`` is a read/write semaphore that serializes all changes to a particular
2507bbfd9adSNeilBrowndirectory.  This ensures that, for example, an ``unlink()`` and a ``rename()``
2517bbfd9adSNeilBrowncannot both happen at the same time.  It also keeps the directory
2527bbfd9adSNeilBrownstable while the filesystem is asked to look up a name that is not
2537bbfd9adSNeilBrowncurrently in the dcache or, optionally, when the list of entries in a
2547bbfd9adSNeilBrowndirectory is being retrieved with ``readdir()``.
2557bbfd9adSNeilBrown
2567bbfd9adSNeilBrownThis has a complementary role to that of ``d_lock``: ``i_rwsem`` on a
2577bbfd9adSNeilBrowndirectory protects all of the names in that directory, while ``d_lock``
2587bbfd9adSNeilBrownon a name protects just one name in a directory.  Most changes to the
2597bbfd9adSNeilBrowndcache hold ``i_rwsem`` on the relevant directory inode and briefly take
2607bbfd9adSNeilBrown``d_lock`` on one or more the dentries while the change happens.  One
2617bbfd9adSNeilBrownexception is when idle dentries are removed from the dcache due to
2627bbfd9adSNeilBrownmemory pressure.  This uses ``d_lock``, but ``i_rwsem`` plays no role.
2637bbfd9adSNeilBrown
2647bbfd9adSNeilBrownThe semaphore affects pathname lookup in two distinct ways.  Firstly it
2657bbfd9adSNeilBrownprevents changes during lookup of a name in a directory.  ``walk_component()`` uses
2667bbfd9adSNeilBrown``lookup_fast()`` first which, in turn, checks to see if the name is in the cache,
2677bbfd9adSNeilBrownusing only ``d_lock`` locking.  If the name isn't found, then ``walk_component()``
2687bbfd9adSNeilBrownfalls back to ``lookup_slow()`` which takes a shared lock on ``i_rwsem``, checks again that
2697bbfd9adSNeilBrownthe name isn't in the cache, and then calls in to the filesystem to get a
2707bbfd9adSNeilBrowndefinitive answer.  A new dentry will be added to the cache regardless of
2717bbfd9adSNeilBrownthe result.
2727bbfd9adSNeilBrown
2737bbfd9adSNeilBrownSecondly, when pathname lookup reaches the final component, it will
2747bbfd9adSNeilBrownsometimes need to take an exclusive lock on ``i_rwsem`` before performing the last lookup so
2757bbfd9adSNeilBrownthat the required exclusion can be achieved.  How path lookup chooses
2767bbfd9adSNeilBrownto take, or not take, ``i_rwsem`` is one of the
2777bbfd9adSNeilBrownissues addressed in a subsequent section.
2787bbfd9adSNeilBrown
2797bbfd9adSNeilBrownIf two threads attempt to look up the same name at the same time - a
2807bbfd9adSNeilBrownname that is not yet in the dcache - the shared lock on ``i_rwsem`` will
2817bbfd9adSNeilBrownnot prevent them both adding new dentries with the same name.  As this
2827bbfd9adSNeilBrownwould result in confusion an extra level of interlocking is used,
2837bbfd9adSNeilBrownbased around a secondary hash table (``in_lookup_hashtable``) and a
2847bbfd9adSNeilBrownper-dentry flag bit (``DCACHE_PAR_LOOKUP``).
2857bbfd9adSNeilBrown
2867bbfd9adSNeilBrownTo add a new dentry to the cache while only holding a shared lock on
2877bbfd9adSNeilBrown``i_rwsem``, a thread must call ``d_alloc_parallel()``.  This allocates a
2887bbfd9adSNeilBrowndentry, stores the required name and parent in it, checks if there
2897bbfd9adSNeilBrownis already a matching dentry in the primary or secondary hash
2907bbfd9adSNeilBrowntables, and if not, stores the newly allocated dentry in the secondary
2917bbfd9adSNeilBrownhash table, with ``DCACHE_PAR_LOOKUP`` set.
2927bbfd9adSNeilBrown
2937bbfd9adSNeilBrownIf a matching dentry was found in the primary hash table then that is
2947bbfd9adSNeilBrownreturned and the caller can know that it lost a race with some other
2957bbfd9adSNeilBrownthread adding the entry.  If no matching dentry is found in either
2967bbfd9adSNeilBrowncache, the newly allocated dentry is returned and the caller can
2977bbfd9adSNeilBrowndetect this from the presence of ``DCACHE_PAR_LOOKUP``.  In this case it
2987bbfd9adSNeilBrownknows that it has won any race and now is responsible for asking the
2997bbfd9adSNeilBrownfilesystem to perform the lookup and find the matching inode.  When
3007bbfd9adSNeilBrownthe lookup is complete, it must call ``d_lookup_done()`` which clears
3017bbfd9adSNeilBrownthe flag and does some other house keeping, including removing the
3027bbfd9adSNeilBrowndentry from the secondary hash table - it will normally have been
3037bbfd9adSNeilBrownadded to the primary hash table already.  Note that a ``struct
3047bbfd9adSNeilBrownwaitqueue_head`` is passed to ``d_alloc_parallel()``, and
3057bbfd9adSNeilBrown``d_lookup_done()`` must be called while this ``waitqueue_head`` is still
3067bbfd9adSNeilBrownin scope.
3077bbfd9adSNeilBrown
3087bbfd9adSNeilBrownIf a matching dentry is found in the secondary hash table,
3097bbfd9adSNeilBrown``d_alloc_parallel()`` has a little more work to do. It first waits for
3107bbfd9adSNeilBrown``DCACHE_PAR_LOOKUP`` to be cleared, using a wait_queue that was passed
3117bbfd9adSNeilBrownto the instance of ``d_alloc_parallel()`` that won the race and that
3127bbfd9adSNeilBrownwill be woken by the call to ``d_lookup_done()``.  It then checks to see
3137bbfd9adSNeilBrownif the dentry has now been added to the primary hash table.  If it
3147bbfd9adSNeilBrownhas, the dentry is returned and the caller just sees that it lost any
3157bbfd9adSNeilBrownrace.  If it hasn't been added to the primary hash table, the most
3167bbfd9adSNeilBrownlikely explanation is that some other dentry was added instead using
3177bbfd9adSNeilBrown``d_splice_alias()``.  In any case, ``d_alloc_parallel()`` repeats all the
3187bbfd9adSNeilBrownlook ups from the start and will normally return something from the
3197bbfd9adSNeilBrownprimary hash table.
3207bbfd9adSNeilBrown
3217bbfd9adSNeilBrownmnt->mnt_count
3227bbfd9adSNeilBrown~~~~~~~~~~~~~~
3237bbfd9adSNeilBrown
3247bbfd9adSNeilBrown``mnt_count`` is a per-CPU reference counter on "``mount``" structures.
3257bbfd9adSNeilBrownPer-CPU here means that incrementing the count is cheap as it only
3267bbfd9adSNeilBrownuses CPU-local memory, but checking if the count is zero is expensive as
3277bbfd9adSNeilBrownit needs to check with every CPU.  Taking a ``mnt_count`` reference
3287bbfd9adSNeilBrownprevents the mount structure from disappearing as the result of regular
3297bbfd9adSNeilBrownunmount operations, but does not prevent a "lazy" unmount.  So holding
3307bbfd9adSNeilBrown``mnt_count`` doesn't ensure that the mount remains in the namespace and,
3317bbfd9adSNeilBrownin particular, doesn't stabilize the link to the mounted-on dentry.  It
3327bbfd9adSNeilBrowndoes, however, ensure that the ``mount`` data structure remains coherent,
3337bbfd9adSNeilBrownand it provides a reference to the root dentry of the mounted
3347bbfd9adSNeilBrownfilesystem.  So a reference through ``->mnt_count`` provides a stable
3357bbfd9adSNeilBrownreference to the mounted dentry, but not the mounted-on dentry.
3367bbfd9adSNeilBrown
3377bbfd9adSNeilBrownmount_lock
3387bbfd9adSNeilBrown~~~~~~~~~~
3397bbfd9adSNeilBrown
3407bbfd9adSNeilBrown``mount_lock`` is a global seqlock, a bit like ``rename_lock``.  It can be used to
3417bbfd9adSNeilBrowncheck if any change has been made to any mount points.
3427bbfd9adSNeilBrown
3437bbfd9adSNeilBrownWhile walking down the tree (away from the root) this lock is used when
3447bbfd9adSNeilBrowncrossing a mount point to check that the crossing was safe.  That is,
3457bbfd9adSNeilBrownthe value in the seqlock is read, then the code finds the mount that
3467bbfd9adSNeilBrownis mounted on the current directory, if there is one, and increments
3477bbfd9adSNeilBrownthe ``mnt_count``.  Finally the value in ``mount_lock`` is checked against
3487bbfd9adSNeilBrownthe old value.  If there is no change, then the crossing was safe.  If there
3497bbfd9adSNeilBrownwas a change, the ``mnt_count`` is decremented and the whole process is
3507bbfd9adSNeilBrownretried.
3517bbfd9adSNeilBrown
3527bbfd9adSNeilBrownWhen walking up the tree (towards the root) by following a ".." link,
3537bbfd9adSNeilBrowna little more care is needed.  In this case the seqlock (which
3547bbfd9adSNeilBrowncontains both a counter and a spinlock) is fully locked to prevent
3557bbfd9adSNeilBrownany changes to any mount points while stepping up.  This locking is
3567bbfd9adSNeilBrownneeded to stabilize the link to the mounted-on dentry, which the
3577bbfd9adSNeilBrownrefcount on the mount itself doesn't ensure.
3587bbfd9adSNeilBrown
359b55eef87SAleksa Sarai``mount_lock`` is also used to detect and defend against potential attacks
360b55eef87SAleksa Saraiagainst ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
361b55eef87SAleksa Saraithe parent directory is moved outside the root, bypassing the ``path_equal()``
362b55eef87SAleksa Saraicheck). If ``mount_lock`` is updated during the lookup and the path encounters
363b55eef87SAleksa Saraia "..", a potential attack occurred and ``handle_dots()`` will bail out with
364b55eef87SAleksa Sarai``-EAGAIN``.
365b55eef87SAleksa Sarai
3667bbfd9adSNeilBrownRCU
3677bbfd9adSNeilBrown~~~
3687bbfd9adSNeilBrown
3697bbfd9adSNeilBrownFinally the global (but extremely lightweight) RCU read lock is held
3707bbfd9adSNeilBrownfrom time to time to ensure certain data structures don't get freed
3717bbfd9adSNeilBrownunexpectedly.
3727bbfd9adSNeilBrown
3737bbfd9adSNeilBrownIn particular it is held while scanning chains in the dcache hash
3747bbfd9adSNeilBrowntable, and the mount point hash table.
3757bbfd9adSNeilBrown
3767bbfd9adSNeilBrownBringing it together with ``struct nameidata``
3779f63df26SRandy Dunlap----------------------------------------------
3787bbfd9adSNeilBrown
379c69f22f2SAlexander A. Klimov.. _First edition Unix: https://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/u2.s
3807bbfd9adSNeilBrown
3817bbfd9adSNeilBrownThroughout the process of walking a path, the current status is stored
3827bbfd9adSNeilBrownin a ``struct nameidata``, "namei" being the traditional name - dating
3837bbfd9adSNeilBrownall the way back to `First Edition Unix`_ - of the function that
3847bbfd9adSNeilBrownconverts a "name" to an "inode".  ``struct nameidata`` contains (among
3857bbfd9adSNeilBrownother fields):
3867bbfd9adSNeilBrown
3877bbfd9adSNeilBrown``struct path path``
3889f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~
3897bbfd9adSNeilBrown
3907bbfd9adSNeilBrownA ``path`` contains a ``struct vfsmount`` (which is
3917bbfd9adSNeilBrownembedded in a ``struct mount``) and a ``struct dentry``.  Together these
3927bbfd9adSNeilBrownrecord the current status of the walk.  They start out referring to the
3937bbfd9adSNeilBrownstarting point (the current working directory, the root directory, or some other
3947bbfd9adSNeilBrowndirectory identified by a file descriptor), and are updated on each
3957bbfd9adSNeilBrownstep.  A reference through ``d_lockref`` and ``mnt_count`` is always
3967bbfd9adSNeilBrownheld.
3977bbfd9adSNeilBrown
3987bbfd9adSNeilBrown``struct qstr last``
3999f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~
4007bbfd9adSNeilBrown
401286b7e24SVegard NossumThis is a string together with a length (i.e. *not* ``nul`` terminated)
4027bbfd9adSNeilBrownthat is the "next" component in the pathname.
4037bbfd9adSNeilBrown
4047bbfd9adSNeilBrown``int last_type``
4059f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~
4067bbfd9adSNeilBrown
407b4c03536SAl ViroThis is one of ``LAST_NORM``, ``LAST_ROOT``, ``LAST_DOT`` or ``LAST_DOTDOT``.
408b4c03536SAl ViroThe ``last`` field is only valid if the type is ``LAST_NORM``.
4097bbfd9adSNeilBrown
4107bbfd9adSNeilBrown``struct path root``
4119f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~
4127bbfd9adSNeilBrown
4137bbfd9adSNeilBrownThis is used to hold a reference to the effective root of the
4147bbfd9adSNeilBrownfilesystem.  Often that reference won't be needed, so this field is
4157bbfd9adSNeilBrownonly assigned the first time it is used, or when a non-standard root
4167bbfd9adSNeilBrownis requested.  Keeping a reference in the ``nameidata`` ensures that
4177bbfd9adSNeilBrownonly one root is in effect for the entire path walk, even if it races
4187bbfd9adSNeilBrownwith a ``chroot()`` system call.
4197bbfd9adSNeilBrown
420b55eef87SAleksa SaraiIt should be noted that in the case of ``LOOKUP_IN_ROOT`` or
421b55eef87SAleksa Sarai``LOOKUP_BENEATH``, the effective root becomes the directory file descriptor
422b55eef87SAleksa Saraipassed to ``openat2()`` (which exposes these ``LOOKUP_`` flags).
423b55eef87SAleksa Sarai
4247bbfd9adSNeilBrownThe root is needed when either of two conditions holds: (1) either the
4257bbfd9adSNeilBrownpathname or a symbolic link starts with a "'/'", or (2) a "``..``"
4267bbfd9adSNeilBrowncomponent is being handled, since "``..``" from the root must always stay
4277bbfd9adSNeilBrownat the root.  The value used is usually the current root directory of
4287bbfd9adSNeilBrownthe calling process.  An alternate root can be provided as when
4297bbfd9adSNeilBrown``sysctl()`` calls ``file_open_root()``, and when NFSv4 or Btrfs call
4307bbfd9adSNeilBrown``mount_subtree()``.  In each case a pathname is being looked up in a very
4317bbfd9adSNeilBrownspecific part of the filesystem, and the lookup must not be allowed to
4327bbfd9adSNeilBrownescape that subtree.  It works a bit like a local ``chroot()``.
4337bbfd9adSNeilBrown
4347bbfd9adSNeilBrownIgnoring the handling of symbolic links, we can now describe the
4357bbfd9adSNeilBrown"``link_path_walk()``" function, which handles the lookup of everything
4367bbfd9adSNeilBrownexcept the final component as:
4377bbfd9adSNeilBrown
4387bbfd9adSNeilBrown   Given a path (``name``) and a nameidata structure (``nd``), check that the
4397bbfd9adSNeilBrown   current directory has execute permission and then advance ``name``
4407bbfd9adSNeilBrown   over one component while updating ``last_type`` and ``last``.  If that
4417bbfd9adSNeilBrown   was the final component, then return, otherwise call
4427bbfd9adSNeilBrown   ``walk_component()`` and repeat from the top.
4437bbfd9adSNeilBrown
4447bbfd9adSNeilBrown``walk_component()`` is even easier.  If the component is ``LAST_DOTS``,
4457bbfd9adSNeilBrownit calls ``handle_dots()`` which does the necessary locking as already
4467bbfd9adSNeilBrowndescribed.  If it finds a ``LAST_NORM`` component it first calls
4477bbfd9adSNeilBrown"``lookup_fast()``" which only looks in the dcache, but will ask the
4487bbfd9adSNeilBrownfilesystem to revalidate the result if it is that sort of filesystem.
4497bbfd9adSNeilBrownIf that doesn't get a good result, it calls "``lookup_slow()``" which
4507bbfd9adSNeilBrowntakes ``i_rwsem``, rechecks the cache, and then asks the filesystem
451993b8926SFox Chento find a definitive answer.
4527bbfd9adSNeilBrown
453993b8926SFox ChenAs the last step of ``walk_component()``, ``step_into()`` will be called either
454993b8926SFox Chendirectly from walk_component() or from handle_dots().  It calls
455993b8926SFox Chen``handle_mounts()``, to check and handle mount points, in which a new
456*084c8683SFox Chen``struct path`` is created containing a counted reference to the new dentry and
457*084c8683SFox Chena reference to the new ``vfsmount`` which is only counted if it is
458*084c8683SFox Chendifferent from the previous ``vfsmount``. Then if there is
459*084c8683SFox Chena symbolic link, ``step_into()`` calls ``pick_link()`` to deal with it,
460*084c8683SFox Chenotherwise it installs the new ``struct path`` in the ``struct nameidata``, and
461*084c8683SFox Chendrops the unneeded references.
4627bbfd9adSNeilBrown
4637bbfd9adSNeilBrownThis "hand-over-hand" sequencing of getting a reference to the new
4647bbfd9adSNeilBrowndentry before dropping the reference to the previous dentry may
4657bbfd9adSNeilBrownseem obvious, but is worth pointing out so that we will recognize its
4667bbfd9adSNeilBrownanalogue in the "RCU-walk" version.
4677bbfd9adSNeilBrown
4687bbfd9adSNeilBrownHandling the final component
4697bbfd9adSNeilBrown----------------------------
4707bbfd9adSNeilBrown
4717bbfd9adSNeilBrown``link_path_walk()`` only walks as far as setting ``nd->last`` and
4727bbfd9adSNeilBrown``nd->last_type`` to refer to the final component of the path.  It does
4737bbfd9adSNeilBrownnot call ``walk_component()`` that last time.  Handling that final
4747bbfd9adSNeilBrowncomponent remains for the caller to sort out. Those callers are
4757bbfd9adSNeilBrown``path_lookupat()``, ``path_parentat()``, ``path_mountpoint()`` and
4767bbfd9adSNeilBrown``path_openat()`` each of which handles the differing requirements of
4777bbfd9adSNeilBrowndifferent system calls.
4787bbfd9adSNeilBrown
4797bbfd9adSNeilBrown``path_parentat()`` is clearly the simplest - it just wraps a little bit
4807bbfd9adSNeilBrownof housekeeping around ``link_path_walk()`` and returns the parent
4817bbfd9adSNeilBrowndirectory and final component to the caller.  The caller will be either
4827bbfd9adSNeilBrownaiming to create a name (via ``filename_create()``) or remove or rename
4837bbfd9adSNeilBrowna name (in which case ``user_path_parent()`` is used).  They will use
4847bbfd9adSNeilBrown``i_rwsem`` to exclude other changes while they validate and then
4857bbfd9adSNeilBrownperform their operation.
4867bbfd9adSNeilBrown
4877bbfd9adSNeilBrown``path_lookupat()`` is nearly as simple - it is used when an existing
4887bbfd9adSNeilBrownobject is wanted such as by ``stat()`` or ``chmod()``.  It essentially just
4897bbfd9adSNeilBrowncalls ``walk_component()`` on the final component through a call to
4907bbfd9adSNeilBrown``lookup_last()``.  ``path_lookupat()`` returns just the final dentry.
4917bbfd9adSNeilBrown
4927bbfd9adSNeilBrown``path_mountpoint()`` handles the special case of unmounting which must
4937bbfd9adSNeilBrownnot try to revalidate the mounted filesystem.  It effectively
4947bbfd9adSNeilBrowncontains, through a call to ``mountpoint_last()``, an alternate
4957bbfd9adSNeilBrownimplementation of ``lookup_slow()`` which skips that step.  This is
4967bbfd9adSNeilBrownimportant when unmounting a filesystem that is inaccessible, such as
4977bbfd9adSNeilBrownone provided by a dead NFS server.
4987bbfd9adSNeilBrown
4997bbfd9adSNeilBrownFinally ``path_openat()`` is used for the ``open()`` system call; it
5007bbfd9adSNeilBrowncontains, in support functions starting with "``do_last()``", all the
5017bbfd9adSNeilBrowncomplexity needed to handle the different subtleties of O_CREAT (with
5027bbfd9adSNeilBrownor without O_EXCL), final "``/``" characters, and trailing symbolic
5037bbfd9adSNeilBrownlinks.  We will revisit this in the final part of this series, which
5047bbfd9adSNeilBrownfocuses on those symbolic links.  "``do_last()``" will sometimes, but
5057bbfd9adSNeilBrownnot always, take ``i_rwsem``, depending on what it finds.
5067bbfd9adSNeilBrown
5077bbfd9adSNeilBrownEach of these, or the functions which call them, need to be alert to
5087bbfd9adSNeilBrownthe possibility that the final component is not ``LAST_NORM``.  If the
5097bbfd9adSNeilBrowngoal of the lookup is to create something, then any value for
5107bbfd9adSNeilBrown``last_type`` other than ``LAST_NORM`` will result in an error.  For
5117bbfd9adSNeilBrownexample if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller
5127bbfd9adSNeilBrownwon't try to create that name.  They also check for trailing slashes
5137bbfd9adSNeilBrownby testing ``last.name[last.len]``.  If there is any character beyond
5147bbfd9adSNeilBrownthe final component, it must be a trailing slash.
5157bbfd9adSNeilBrown
5167bbfd9adSNeilBrownRevalidation and automounts
5177bbfd9adSNeilBrown---------------------------
5187bbfd9adSNeilBrown
5197bbfd9adSNeilBrownApart from symbolic links, there are only two parts of the "REF-walk"
5207bbfd9adSNeilBrownprocess not yet covered.  One is the handling of stale cache entries
5217bbfd9adSNeilBrownand the other is automounts.
5227bbfd9adSNeilBrown
5237bbfd9adSNeilBrownOn filesystems that require it, the lookup routines will call the
5247bbfd9adSNeilBrown``->d_revalidate()`` dentry method to ensure that the cached information
5257bbfd9adSNeilBrownis current.  This will often confirm validity or update a few details
5267bbfd9adSNeilBrownfrom a server.  In some cases it may find that there has been change
5277bbfd9adSNeilBrownfurther up the path and that something that was thought to be valid
5287bbfd9adSNeilBrownpreviously isn't really.  When this happens the lookup of the whole
5297bbfd9adSNeilBrownpath is aborted and retried with the "``LOOKUP_REVAL``" flag set.  This
5307bbfd9adSNeilBrownforces revalidation to be more thorough.  We will see more details of
5317bbfd9adSNeilBrownthis retry process in the next article.
5327bbfd9adSNeilBrown
5337bbfd9adSNeilBrownAutomount points are locations in the filesystem where an attempt to
5347bbfd9adSNeilBrownlookup a name can trigger changes to how that lookup should be
5357bbfd9adSNeilBrownhandled, in particular by mounting a filesystem there.  These are
5367bbfd9adSNeilBrowncovered in greater detail in autofs.txt in the Linux documentation
5377bbfd9adSNeilBrowntree, but a few notes specifically related to path lookup are in order
5387bbfd9adSNeilBrownhere.
5397bbfd9adSNeilBrown
540993b8926SFox ChenThe Linux VFS has a concept of "managed" dentries.  There are three
5417bbfd9adSNeilBrownpotentially interesting things about these dentries corresponding
5427bbfd9adSNeilBrownto three different flags that might be set in ``dentry->d_flags``:
5437bbfd9adSNeilBrown
5447bbfd9adSNeilBrown``DCACHE_MANAGE_TRANSIT``
5459f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~
5467bbfd9adSNeilBrown
5477bbfd9adSNeilBrownIf this flag has been set, then the filesystem has requested that the
5487bbfd9adSNeilBrown``d_manage()`` dentry operation be called before handling any possible
5497bbfd9adSNeilBrownmount point.  This can perform two particular services:
5507bbfd9adSNeilBrown
5517bbfd9adSNeilBrownIt can block to avoid races.  If an automount point is being
5527bbfd9adSNeilBrownunmounted, the ``d_manage()`` function will usually wait for that
5537bbfd9adSNeilBrownprocess to complete before letting the new lookup proceed and possibly
5547bbfd9adSNeilBrowntrigger a new automount.
5557bbfd9adSNeilBrown
5567bbfd9adSNeilBrownIt can selectively allow only some processes to transit through a
5577bbfd9adSNeilBrownmount point.  When a server process is managing automounts, it may
5587bbfd9adSNeilBrownneed to access a directory without triggering normal automount
5597bbfd9adSNeilBrownprocessing.  That server process can identify itself to the ``autofs``
5607bbfd9adSNeilBrownfilesystem, which will then give it a special pass through
5617bbfd9adSNeilBrown``d_manage()`` by returning ``-EISDIR``.
5627bbfd9adSNeilBrown
5637bbfd9adSNeilBrown``DCACHE_MOUNTED``
5649f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~
5657bbfd9adSNeilBrown
5667bbfd9adSNeilBrownThis flag is set on every dentry that is mounted on.  As Linux
5677bbfd9adSNeilBrownsupports multiple filesystem namespaces, it is possible that the
5687bbfd9adSNeilBrowndentry may not be mounted on in *this* namespace, just in some
5697bbfd9adSNeilBrownother.  So this flag is seen as a hint, not a promise.
5707bbfd9adSNeilBrown
5717bbfd9adSNeilBrownIf this flag is set, and ``d_manage()`` didn't return ``-EISDIR``,
5727bbfd9adSNeilBrown``lookup_mnt()`` is called to examine the mount hash table (honoring the
5737bbfd9adSNeilBrown``mount_lock`` described earlier) and possibly return a new ``vfsmount``
5747bbfd9adSNeilBrownand a new ``dentry`` (both with counted references).
5757bbfd9adSNeilBrown
5767bbfd9adSNeilBrown``DCACHE_NEED_AUTOMOUNT``
5779f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~
5787bbfd9adSNeilBrown
5797bbfd9adSNeilBrownIf ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't
5807bbfd9adSNeilBrownfind a mount point, then this flag causes the ``d_automount()`` dentry
5817bbfd9adSNeilBrownoperation to be called.
5827bbfd9adSNeilBrown
5837bbfd9adSNeilBrownThe ``d_automount()`` operation can be arbitrarily complex and may
5847bbfd9adSNeilBrowncommunicate with server processes etc. but it should ultimately either
5857bbfd9adSNeilBrownreport that there was an error, that there was nothing to mount, or
5867bbfd9adSNeilBrownshould provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``.
5877bbfd9adSNeilBrown
5887bbfd9adSNeilBrownIn the latter case, ``finish_automount()`` will be called to safely
5897bbfd9adSNeilBrowninstall the new mount point into the mount table.
5907bbfd9adSNeilBrown
5917bbfd9adSNeilBrownThere is no new locking of import here and it is important that no
5927bbfd9adSNeilBrownlocks (only counted references) are held over this processing due to
5937bbfd9adSNeilBrownthe very real possibility of extended delays.
5947bbfd9adSNeilBrownThis will become more important next time when we examine RCU-walk
5957bbfd9adSNeilBrownwhich is particularly sensitive to delays.
5967bbfd9adSNeilBrown
5977bbfd9adSNeilBrownRCU-walk - faster pathname lookup in Linux
5987bbfd9adSNeilBrown==========================================
5997bbfd9adSNeilBrown
6007bbfd9adSNeilBrownRCU-walk is another algorithm for performing pathname lookup in Linux.
6017bbfd9adSNeilBrownIt is in many ways similar to REF-walk and the two share quite a bit
6027bbfd9adSNeilBrownof code.  The significant difference in RCU-walk is how it allows for
6037bbfd9adSNeilBrownthe possibility of concurrent access.
6047bbfd9adSNeilBrown
6057bbfd9adSNeilBrownWe noted that REF-walk is complex because there are numerous details
6067bbfd9adSNeilBrownand special cases.  RCU-walk reduces this complexity by simply
6077bbfd9adSNeilBrownrefusing to handle a number of cases -- it instead falls back to
6087bbfd9adSNeilBrownREF-walk.  The difficulty with RCU-walk comes from a different
6097bbfd9adSNeilBrowndirection: unfamiliarity.  The locking rules when depending on RCU are
6107bbfd9adSNeilBrownquite different from traditional locking, so we will spend a little extra
6117bbfd9adSNeilBrowntime when we come to those.
6127bbfd9adSNeilBrown
6137bbfd9adSNeilBrownClear demarcation of roles
6147bbfd9adSNeilBrown--------------------------
6157bbfd9adSNeilBrown
6167bbfd9adSNeilBrownThe easiest way to manage concurrency is to forcibly stop any other
6177bbfd9adSNeilBrownthread from changing the data structures that a given thread is
6187bbfd9adSNeilBrownlooking at.  In cases where no other thread would even think of
6197bbfd9adSNeilBrownchanging the data and lots of different threads want to read at the
6207bbfd9adSNeilBrownsame time, this can be very costly.  Even when using locks that permit
6217bbfd9adSNeilBrownmultiple concurrent readers, the simple act of updating the count of
6227bbfd9adSNeilBrownthe number of current readers can impose an unwanted cost.  So the
6237bbfd9adSNeilBrowngoal when reading a shared data structure that no other process is
6247bbfd9adSNeilBrownchanging is to avoid writing anything to memory at all.  Take no
6257bbfd9adSNeilBrownlocks, increment no counts, leave no footprints.
6267bbfd9adSNeilBrown
6277bbfd9adSNeilBrownThe REF-walk mechanism already described certainly doesn't follow this
6287bbfd9adSNeilBrownprinciple, but then it is really designed to work when there may well
6297bbfd9adSNeilBrownbe other threads modifying the data.  RCU-walk, in contrast, is
6307bbfd9adSNeilBrowndesigned for the common situation where there are lots of frequent
6317bbfd9adSNeilBrownreaders and only occasional writers.  This may not be common in all
6327bbfd9adSNeilBrownparts of the filesystem tree, but in many parts it will be.  For the
6337bbfd9adSNeilBrownother parts it is important that RCU-walk can quickly fall back to
6347bbfd9adSNeilBrownusing REF-walk.
6357bbfd9adSNeilBrown
6367bbfd9adSNeilBrownPathname lookup always starts in RCU-walk mode but only remains there
6377bbfd9adSNeilBrownas long as what it is looking for is in the cache and is stable.  It
6387bbfd9adSNeilBrowndances lightly down the cached filesystem image, leaving no footprints
6397bbfd9adSNeilBrownand carefully watching where it is, to be sure it doesn't trip.  If it
6407bbfd9adSNeilBrownnotices that something has changed or is changing, or if something
6417bbfd9adSNeilBrownisn't in the cache, then it tries to stop gracefully and switch to
6427bbfd9adSNeilBrownREF-walk.
6437bbfd9adSNeilBrown
6447bbfd9adSNeilBrownThis stopping requires getting a counted reference on the current
6457bbfd9adSNeilBrown``vfsmount`` and ``dentry``, and ensuring that these are still valid -
6467bbfd9adSNeilBrownthat a path walk with REF-walk would have found the same entries.
6477bbfd9adSNeilBrownThis is an invariant that RCU-walk must guarantee.  It can only make
6487bbfd9adSNeilBrowndecisions, such as selecting the next step, that are decisions which
6497bbfd9adSNeilBrownREF-walk could also have made if it were walking down the tree at the
6507bbfd9adSNeilBrownsame time.  If the graceful stop succeeds, the rest of the path is
6517bbfd9adSNeilBrownprocessed with the reliable, if slightly sluggish, REF-walk.  If
6527bbfd9adSNeilBrownRCU-walk finds it cannot stop gracefully, it simply gives up and
6537bbfd9adSNeilBrownrestarts from the top with REF-walk.
6547bbfd9adSNeilBrown
6557bbfd9adSNeilBrownThis pattern of "try RCU-walk, if that fails try REF-walk" can be
6567bbfd9adSNeilBrownclearly seen in functions like ``filename_lookup()``,
6577bbfd9adSNeilBrown``filename_parentat()``, ``filename_mountpoint()``,
6587bbfd9adSNeilBrown``do_filp_open()``, and ``do_file_open_root()``.  These five
65987b92d4bSVegard Nossumcorrespond roughly to the four ``path_*()`` functions we met earlier,
66087b92d4bSVegard Nossumeach of which calls ``link_path_walk()``.  The ``path_*()`` functions are
6617bbfd9adSNeilBrowncalled using different mode flags until a mode is found which works.
6627bbfd9adSNeilBrownThey are first called with ``LOOKUP_RCU`` set to request "RCU-walk".  If
6637bbfd9adSNeilBrownthat fails with the error ``ECHILD`` they are called again with no
6647bbfd9adSNeilBrownspecial flag to request "REF-walk".  If either of those report the
6657bbfd9adSNeilBrownerror ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no
6667bbfd9adSNeilBrown``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly
6677bbfd9adSNeilBrownrevalidated - normally entries are only revalidated if the filesystem
6687bbfd9adSNeilBrowndetermines that they are too old to trust.
6697bbfd9adSNeilBrown
6707bbfd9adSNeilBrownThe ``LOOKUP_RCU`` attempt may drop that flag internally and switch to
6717bbfd9adSNeilBrownREF-walk, but will never then try to switch back to RCU-walk.  Places
6727bbfd9adSNeilBrownthat trip up RCU-walk are much more likely to be near the leaves and
6737bbfd9adSNeilBrownso it is very unlikely that there will be much, if any, benefit from
6747bbfd9adSNeilBrownswitching back.
6757bbfd9adSNeilBrown
6767bbfd9adSNeilBrownRCU and seqlocks: fast and light
6777bbfd9adSNeilBrown--------------------------------
6787bbfd9adSNeilBrown
6797bbfd9adSNeilBrownRCU is, unsurprisingly, critical to RCU-walk mode.  The
6807bbfd9adSNeilBrown``rcu_read_lock()`` is held for the entire time that RCU-walk is walking
6817bbfd9adSNeilBrowndown a path.  The particular guarantee it provides is that the key
6827bbfd9adSNeilBrowndata structures - dentries, inodes, super_blocks, and mounts - will
6837bbfd9adSNeilBrownnot be freed while the lock is held.  They might be unlinked or
6847bbfd9adSNeilBrowninvalidated in one way or another, but the memory will not be
6857bbfd9adSNeilBrownrepurposed so values in various fields will still be meaningful.  This
6867bbfd9adSNeilBrownis the only guarantee that RCU provides; everything else is done using
6877bbfd9adSNeilBrownseqlocks.
6887bbfd9adSNeilBrown
6897bbfd9adSNeilBrownAs we saw above, REF-walk holds a counted reference to the current
6907bbfd9adSNeilBrowndentry and the current vfsmount, and does not release those references
6917bbfd9adSNeilBrownbefore taking references to the "next" dentry or vfsmount.  It also
6927bbfd9adSNeilBrownsometimes takes the ``d_lock`` spinlock.  These references and locks are
6937bbfd9adSNeilBrowntaken to prevent certain changes from happening.  RCU-walk must not
6947bbfd9adSNeilBrowntake those references or locks and so cannot prevent such changes.
6957bbfd9adSNeilBrownInstead, it checks to see if a change has been made, and aborts or
6967bbfd9adSNeilBrownretries if it has.
6977bbfd9adSNeilBrown
6987bbfd9adSNeilBrownTo preserve the invariant mentioned above (that RCU-walk may only make
6997bbfd9adSNeilBrowndecisions that REF-walk could have made), it must make the checks at
7007bbfd9adSNeilBrownor near the same places that REF-walk holds the references.  So, when
7017bbfd9adSNeilBrownREF-walk increments a reference count or takes a spinlock, RCU-walk
7027bbfd9adSNeilBrownsamples the status of a seqlock using ``read_seqcount_begin()`` or a
7037bbfd9adSNeilBrownsimilar function.  When REF-walk decrements the count or drops the
7047bbfd9adSNeilBrownlock, RCU-walk checks if the sampled status is still valid using
7057bbfd9adSNeilBrown``read_seqcount_retry()`` or similar.
7067bbfd9adSNeilBrown
7077bbfd9adSNeilBrownHowever, there is a little bit more to seqlocks than that.  If
7087bbfd9adSNeilBrownRCU-walk accesses two different fields in a seqlock-protected
7097bbfd9adSNeilBrownstructure, or accesses the same field twice, there is no a priori
7107bbfd9adSNeilBrownguarantee of any consistency between those accesses.  When consistency
7117bbfd9adSNeilBrownis needed - which it usually is - RCU-walk must take a copy and then
7127bbfd9adSNeilBrownuse ``read_seqcount_retry()`` to validate that copy.
7137bbfd9adSNeilBrown
7147bbfd9adSNeilBrown``read_seqcount_retry()`` not only checks the sequence number, but also
7157bbfd9adSNeilBrownimposes a memory barrier so that no memory-read instruction from
7167bbfd9adSNeilBrown*before* the call can be delayed until *after* the call, either by the
7177bbfd9adSNeilBrownCPU or by the compiler.  A simple example of this can be seen in
7187bbfd9adSNeilBrown``slow_dentry_cmp()`` which, for filesystems which do not use simple
7197bbfd9adSNeilBrownbyte-wise name equality, calls into the filesystem to compare a name
7207bbfd9adSNeilBrownagainst a dentry.  The length and name pointer are copied into local
7217bbfd9adSNeilBrownvariables, then ``read_seqcount_retry()`` is called to confirm the two
7227bbfd9adSNeilBrownare consistent, and only then is ``->d_compare()`` called.  When
7237bbfd9adSNeilBrownstandard filename comparison is used, ``dentry_cmp()`` is called
724286b7e24SVegard Nossuminstead.  Notably it does *not* use ``read_seqcount_retry()``, but
7257bbfd9adSNeilBrowninstead has a large comment explaining why the consistency guarantee
7267bbfd9adSNeilBrownisn't necessary.  A subsequent ``read_seqcount_retry()`` will be
7277bbfd9adSNeilBrownsufficient to catch any problem that could occur at this point.
7287bbfd9adSNeilBrown
7297bbfd9adSNeilBrownWith that little refresher on seqlocks out of the way we can look at
7307bbfd9adSNeilBrownthe bigger picture of how RCU-walk uses seqlocks.
7317bbfd9adSNeilBrown
7327bbfd9adSNeilBrown``mount_lock`` and ``nd->m_seq``
7339f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7347bbfd9adSNeilBrown
7357bbfd9adSNeilBrownWe already met the ``mount_lock`` seqlock when REF-walk used it to
7367bbfd9adSNeilBrownensure that crossing a mount point is performed safely.  RCU-walk uses
7377bbfd9adSNeilBrownit for that too, but for quite a bit more.
7387bbfd9adSNeilBrown
7397bbfd9adSNeilBrownInstead of taking a counted reference to each ``vfsmount`` as it
7407bbfd9adSNeilBrowndescends the tree, RCU-walk samples the state of ``mount_lock`` at the
7417bbfd9adSNeilBrownstart of the walk and stores this initial sequence number in the
7427bbfd9adSNeilBrown``struct nameidata`` in the ``m_seq`` field.  This one lock and one
7437bbfd9adSNeilBrownsequence number are used to validate all accesses to all ``vfsmounts``,
7447bbfd9adSNeilBrownand all mount point crossings.  As changes to the mount table are
7457bbfd9adSNeilBrownrelatively rare, it is reasonable to fall back on REF-walk any time
7467bbfd9adSNeilBrownthat any "mount" or "unmount" happens.
7477bbfd9adSNeilBrown
7487bbfd9adSNeilBrown``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk
7497bbfd9adSNeilBrownsequence, whether switching to REF-walk for the rest of the path or
7507bbfd9adSNeilBrownwhen the end of the path is reached.  It is also checked when stepping
7517bbfd9adSNeilBrowndown over a mount point (in ``__follow_mount_rcu()``) or up (in
7527bbfd9adSNeilBrown``follow_dotdot_rcu()``).  If it is ever found to have changed, the
7537bbfd9adSNeilBrownwhole RCU-walk sequence is aborted and the path is processed again by
7547bbfd9adSNeilBrownREF-walk.
7557bbfd9adSNeilBrown
7567bbfd9adSNeilBrownIf RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure
7577bbfd9adSNeilBrownthat, had REF-walk taken counted references on each vfsmount, the
7587bbfd9adSNeilBrownresults would have been the same.  This ensures the invariant holds,
7597bbfd9adSNeilBrownat least for vfsmount structures.
7607bbfd9adSNeilBrown
7617bbfd9adSNeilBrown``dentry->d_seq`` and ``nd->seq``
7629f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7637bbfd9adSNeilBrown
7647bbfd9adSNeilBrownIn place of taking a count or lock on ``d_reflock``, RCU-walk samples
7657bbfd9adSNeilBrownthe per-dentry ``d_seq`` seqlock, and stores the sequence number in the
7667bbfd9adSNeilBrown``seq`` field of the nameidata structure, so ``nd->seq`` should always be
7677bbfd9adSNeilBrownthe current sequence number of ``nd->dentry``.  This number needs to be
7687bbfd9adSNeilBrownrevalidated after copying, and before using, the name, parent, or
7697bbfd9adSNeilBrowninode of the dentry.
7707bbfd9adSNeilBrown
7717bbfd9adSNeilBrownThe handling of the name we have already looked at, and the parent is
7727bbfd9adSNeilBrownonly accessed in ``follow_dotdot_rcu()`` which fairly trivially follows
7737bbfd9adSNeilBrownthe required pattern, though it does so for three different cases.
7747bbfd9adSNeilBrown
7757bbfd9adSNeilBrownWhen not at a mount point, ``d_parent`` is followed and its ``d_seq`` is
7767bbfd9adSNeilBrowncollected.  When we are at a mount point, we instead follow the
7777bbfd9adSNeilBrown``mnt->mnt_mountpoint`` link to get a new dentry and collect its
7787bbfd9adSNeilBrown``d_seq``.  Then, after finally finding a ``d_parent`` to follow, we must
7797bbfd9adSNeilBrowncheck if we have landed on a mount point and, if so, must find that
7807bbfd9adSNeilBrownmount point and follow the ``mnt->mnt_root`` link.  This would imply a
7817bbfd9adSNeilBrownsomewhat unusual, but certainly possible, circumstance where the
7827bbfd9adSNeilBrownstarting point of the path lookup was in part of the filesystem that
7837bbfd9adSNeilBrownwas mounted on, and so not visible from the root.
7847bbfd9adSNeilBrown
7857bbfd9adSNeilBrownThe inode pointer, stored in ``->d_inode``, is a little more
7867bbfd9adSNeilBrowninteresting.  The inode will always need to be accessed at least
7877bbfd9adSNeilBrowntwice, once to determine if it is NULL and once to verify access
7887bbfd9adSNeilBrownpermissions.  Symlink handling requires a validated inode pointer too.
7897bbfd9adSNeilBrownRather than revalidating on each access, a copy is made on the first
7907bbfd9adSNeilBrownaccess and it is stored in the ``inode`` field of ``nameidata`` from where
7917bbfd9adSNeilBrownit can be safely accessed without further validation.
7927bbfd9adSNeilBrown
7937bbfd9adSNeilBrown``lookup_fast()`` is the only lookup routine that is used in RCU-mode,
7947bbfd9adSNeilBrown``lookup_slow()`` being too slow and requiring locks.  It is in
7957bbfd9adSNeilBrown``lookup_fast()`` that we find the important "hand over hand" tracking
7967bbfd9adSNeilBrownof the current dentry.
7977bbfd9adSNeilBrown
7987bbfd9adSNeilBrownThe current ``dentry`` and current ``seq`` number are passed to
7997bbfd9adSNeilBrown``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a
8007bbfd9adSNeilBrownnew ``seq`` number.  ``lookup_fast()`` then copies the inode pointer and
8017bbfd9adSNeilBrownrevalidates the new ``seq`` number.  It then validates the old ``dentry``
8027bbfd9adSNeilBrownwith the old ``seq`` number one last time and only then continues.  This
8037bbfd9adSNeilBrownprocess of getting the ``seq`` number of the new dentry and then
8047bbfd9adSNeilBrownchecking the ``seq`` number of the old exactly mirrors the process of
8057bbfd9adSNeilBrowngetting a counted reference to the new dentry before dropping that for
8067bbfd9adSNeilBrownthe old dentry which we saw in REF-walk.
8077bbfd9adSNeilBrown
8087bbfd9adSNeilBrownNo ``inode->i_rwsem`` or even ``rename_lock``
8099f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8107bbfd9adSNeilBrown
8117bbfd9adSNeilBrownA semaphore is a fairly heavyweight lock that can only be taken when it is
8127bbfd9adSNeilBrownpermissible to sleep.  As ``rcu_read_lock()`` forbids sleeping,
8137bbfd9adSNeilBrown``inode->i_rwsem`` plays no role in RCU-walk.  If some other thread does
8147bbfd9adSNeilBrowntake ``i_rwsem`` and modifies the directory in a way that RCU-walk needs
8157bbfd9adSNeilBrownto notice, the result will be either that RCU-walk fails to find the
8167bbfd9adSNeilBrowndentry that it is looking for, or it will find a dentry which
8177bbfd9adSNeilBrown``read_seqretry()`` won't validate.  In either case it will drop down to
8187bbfd9adSNeilBrownREF-walk mode which can take whatever locks are needed.
8197bbfd9adSNeilBrown
8207bbfd9adSNeilBrownThough ``rename_lock`` could be used by RCU-walk as it doesn't require
8217bbfd9adSNeilBrownany sleeping, RCU-walk doesn't bother.  REF-walk uses ``rename_lock`` to
8227bbfd9adSNeilBrownprotect against the possibility of hash chains in the dcache changing
8237bbfd9adSNeilBrownwhile they are being searched.  This can result in failing to find
8247bbfd9adSNeilBrownsomething that actually is there.  When RCU-walk fails to find
8257bbfd9adSNeilBrownsomething in the dentry cache, whether it is really there or not, it
8267bbfd9adSNeilBrownalready drops down to REF-walk and tries again with appropriate
8277bbfd9adSNeilBrownlocking.  This neatly handles all cases, so adding extra checks on
8287bbfd9adSNeilBrownrename_lock would bring no significant value.
8297bbfd9adSNeilBrown
8307bbfd9adSNeilBrown``unlazy walk()`` and ``complete_walk()``
8319f63df26SRandy Dunlap-----------------------------------------
8327bbfd9adSNeilBrown
8337bbfd9adSNeilBrownThat "dropping down to REF-walk" typically involves a call to
8347bbfd9adSNeilBrown``unlazy_walk()``, so named because "RCU-walk" is also sometimes
8357bbfd9adSNeilBrownreferred to as "lazy walk".  ``unlazy_walk()`` is called when
8367bbfd9adSNeilBrownfollowing the path down to the current vfsmount/dentry pair seems to
8377bbfd9adSNeilBrownhave proceeded successfully, but the next step is problematic.  This
8387bbfd9adSNeilBrowncan happen if the next name cannot be found in the dcache, if
8397bbfd9adSNeilBrownpermission checking or name revalidation couldn't be achieved while
8407bbfd9adSNeilBrownthe ``rcu_read_lock()`` is held (which forbids sleeping), if an
8417bbfd9adSNeilBrownautomount point is found, or in a couple of cases involving symlinks.
8427bbfd9adSNeilBrownIt is also called from ``complete_walk()`` when the lookup has reached
8437bbfd9adSNeilBrownthe final component, or the very end of the path, depending on which
8447bbfd9adSNeilBrownparticular flavor of lookup is used.
8457bbfd9adSNeilBrown
8467bbfd9adSNeilBrownOther reasons for dropping out of RCU-walk that do not trigger a call
8477bbfd9adSNeilBrownto ``unlazy_walk()`` are when some inconsistency is found that cannot be
8487bbfd9adSNeilBrownhandled immediately, such as ``mount_lock`` or one of the ``d_seq``
8497bbfd9adSNeilBrownseqlocks reporting a change.  In these cases the relevant function
8507bbfd9adSNeilBrownwill return ``-ECHILD`` which will percolate up until it triggers a new
8517bbfd9adSNeilBrownattempt from the top using REF-walk.
8527bbfd9adSNeilBrown
8537bbfd9adSNeilBrownFor those cases where ``unlazy_walk()`` is an option, it essentially
8547bbfd9adSNeilBrowntakes a reference on each of the pointers that it holds (vfsmount,
8557bbfd9adSNeilBrowndentry, and possibly some symbolic links) and then verifies that the
8567bbfd9adSNeilBrownrelevant seqlocks have not been changed.  If there have been changes,
8577bbfd9adSNeilBrownit, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk
8587bbfd9adSNeilBrownhas been a success and the lookup process continues.
8597bbfd9adSNeilBrown
8607bbfd9adSNeilBrownTaking a reference on those pointers is not quite as simple as just
8617bbfd9adSNeilBrownincrementing a counter.  That works to take a second reference if you
8627bbfd9adSNeilBrownalready have one (often indirectly through another object), but it
8637bbfd9adSNeilBrownisn't sufficient if you don't actually have a counted reference at
8647bbfd9adSNeilBrownall.  For ``dentry->d_lockref``, it is safe to increment the reference
8657bbfd9adSNeilBrowncounter to get a reference unless it has been explicitly marked as
8667bbfd9adSNeilBrown"dead" which involves setting the counter to ``-128``.
8677bbfd9adSNeilBrown``lockref_get_not_dead()`` achieves this.
8687bbfd9adSNeilBrown
8697bbfd9adSNeilBrownFor ``mnt->mnt_count`` it is safe to take a reference as long as
8707bbfd9adSNeilBrown``mount_lock`` is then used to validate the reference.  If that
8717bbfd9adSNeilBrownvalidation fails, it may *not* be safe to just drop that reference in
8727bbfd9adSNeilBrownthe standard way of calling ``mnt_put()`` - an unmount may have
8737bbfd9adSNeilBrownprogressed too far.  So the code in ``legitimize_mnt()``, when it
8747bbfd9adSNeilBrownfinds that the reference it got might not be safe, checks the
8757bbfd9adSNeilBrown``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is
8767bbfd9adSNeilBrowncorrect, or if it should just decrement the count and pretend none of
8777bbfd9adSNeilBrownthis ever happened.
8787bbfd9adSNeilBrown
8797bbfd9adSNeilBrownTaking care in filesystems
8807bbfd9adSNeilBrown--------------------------
8817bbfd9adSNeilBrown
8827bbfd9adSNeilBrownRCU-walk depends almost entirely on cached information and often will
8837bbfd9adSNeilBrownnot call into the filesystem at all.  However there are two places,
8847bbfd9adSNeilBrownbesides the already-mentioned component-name comparison, where the
8857bbfd9adSNeilBrownfile system might be included in RCU-walk, and it must know to be
8867bbfd9adSNeilBrowncareful.
8877bbfd9adSNeilBrown
8887bbfd9adSNeilBrownIf the filesystem has non-standard permission-checking requirements -
8897bbfd9adSNeilBrownsuch as a networked filesystem which may need to check with the server
8907bbfd9adSNeilBrown- the ``i_op->permission`` interface might be called during RCU-walk.
8917bbfd9adSNeilBrownIn this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it
8927bbfd9adSNeilBrownknows not to sleep, but to return ``-ECHILD`` if it cannot complete
8937bbfd9adSNeilBrownpromptly.  ``i_op->permission`` is given the inode pointer, not the
8947bbfd9adSNeilBrowndentry, so it doesn't need to worry about further consistency checks.
8957bbfd9adSNeilBrownHowever if it accesses any other filesystem data structures, it must
8967bbfd9adSNeilBrownensure they are safe to be accessed with only the ``rcu_read_lock()``
8977bbfd9adSNeilBrownheld.  This typically means they must be freed using ``kfree_rcu()`` or
8987bbfd9adSNeilBrownsimilar.
8997bbfd9adSNeilBrown
9007bbfd9adSNeilBrown.. _READ_ONCE: https://lwn.net/Articles/624126/
9017bbfd9adSNeilBrown
9027bbfd9adSNeilBrownIf the filesystem may need to revalidate dcache entries, then
9037bbfd9adSNeilBrown``d_op->d_revalidate`` may be called in RCU-walk too.  This interface
9047bbfd9adSNeilBrown*is* passed the dentry but does not have access to the ``inode`` or the
9057bbfd9adSNeilBrown``seq`` number from the ``nameidata``, so it needs to be extra careful
9067bbfd9adSNeilBrownwhen accessing fields in the dentry.  This "extra care" typically
9077bbfd9adSNeilBrowninvolves using  `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the
9087bbfd9adSNeilBrownresult is not NULL before using it.  This pattern can be seen in
9097bbfd9adSNeilBrown``nfs_lookup_revalidate()``.
9107bbfd9adSNeilBrown
9117bbfd9adSNeilBrownA pair of patterns
9127bbfd9adSNeilBrown------------------
9137bbfd9adSNeilBrown
9147bbfd9adSNeilBrownIn various places in the details of REF-walk and RCU-walk, and also in
9157bbfd9adSNeilBrownthe big picture, there are a couple of related patterns that are worth
9167bbfd9adSNeilBrownbeing aware of.
9177bbfd9adSNeilBrown
9187bbfd9adSNeilBrownThe first is "try quickly and check, if that fails try slowly".  We
9197bbfd9adSNeilBrowncan see that in the high-level approach of first trying RCU-walk and
9207bbfd9adSNeilBrownthen trying REF-walk, and in places where ``unlazy_walk()`` is used to
9217bbfd9adSNeilBrownswitch to REF-walk for the rest of the path.  We also saw it earlier
9227bbfd9adSNeilBrownin ``dget_parent()`` when following a "``..``" link.  It tries a quick way
9237bbfd9adSNeilBrownto get a reference, then falls back to taking locks if needed.
9247bbfd9adSNeilBrown
9257bbfd9adSNeilBrownThe second pattern is "try quickly and check, if that fails try
9267bbfd9adSNeilBrownagain - repeatedly".  This is seen with the use of ``rename_lock`` and
9277bbfd9adSNeilBrown``mount_lock`` in REF-walk.  RCU-walk doesn't make use of this pattern -
9287bbfd9adSNeilBrownif anything goes wrong it is much safer to just abort and try a more
9297bbfd9adSNeilBrownsedate approach.
9307bbfd9adSNeilBrown
9317bbfd9adSNeilBrownThe emphasis here is "try quickly and check".  It should probably be
932286b7e24SVegard Nossum"try quickly *and carefully*, then check".  The fact that checking is
9337bbfd9adSNeilBrownneeded is a reminder that the system is dynamic and only a limited
9347bbfd9adSNeilBrownnumber of things are safe at all.  The most likely cause of errors in
9357bbfd9adSNeilBrownthis whole process is assuming something is safe when in reality it
9367bbfd9adSNeilBrownisn't.  Careful consideration of what exactly guarantees the safety of
9377bbfd9adSNeilBrowneach access is sometimes necessary.
9387bbfd9adSNeilBrown
9397bbfd9adSNeilBrownA walk among the symlinks
9407bbfd9adSNeilBrown=========================
9417bbfd9adSNeilBrown
9427bbfd9adSNeilBrownThere are several basic issues that we will examine to understand the
9437bbfd9adSNeilBrownhandling of symbolic links:  the symlink stack, together with cache
9447bbfd9adSNeilBrownlifetimes, will help us understand the overall recursive handling of
9457bbfd9adSNeilBrownsymlinks and lead to the special care needed for the final component.
9467bbfd9adSNeilBrownThen a consideration of access-time updates and summary of the various
9477bbfd9adSNeilBrownflags controlling lookup will finish the story.
9487bbfd9adSNeilBrown
9497bbfd9adSNeilBrownThe symlink stack
9507bbfd9adSNeilBrown-----------------
9517bbfd9adSNeilBrown
9527bbfd9adSNeilBrownThere are only two sorts of filesystem objects that can usefully
9537bbfd9adSNeilBrownappear in a path prior to the final component: directories and symlinks.
9547bbfd9adSNeilBrownHandling directories is quite straightforward: the new directory
9557bbfd9adSNeilBrownsimply becomes the starting point at which to interpret the next
9567bbfd9adSNeilBrowncomponent on the path.  Handling symbolic links requires a bit more
9577bbfd9adSNeilBrownwork.
9587bbfd9adSNeilBrown
9597bbfd9adSNeilBrownConceptually, symbolic links could be handled by editing the path.  If
9607bbfd9adSNeilBrowna component name refers to a symbolic link, then that component is
9617bbfd9adSNeilBrownreplaced by the body of the link and, if that body starts with a '/',
9627bbfd9adSNeilBrownthen all preceding parts of the path are discarded.  This is what the
9637bbfd9adSNeilBrown"``readlink -f``" command does, though it also edits out "``.``" and
9647bbfd9adSNeilBrown"``..``" components.
9657bbfd9adSNeilBrown
9667bbfd9adSNeilBrownDirectly editing the path string is not really necessary when looking
9677bbfd9adSNeilBrownup a path, and discarding early components is pointless as they aren't
9687bbfd9adSNeilBrownlooked at anyway.  Keeping track of all remaining components is
9697bbfd9adSNeilBrownimportant, but they can of course be kept separately; there is no need
9707bbfd9adSNeilBrownto concatenate them.  As one symlink may easily refer to another,
9717bbfd9adSNeilBrownwhich in turn can refer to a third, we may need to keep the remaining
9727bbfd9adSNeilBrowncomponents of several paths, each to be processed when the preceding
9737bbfd9adSNeilBrownones are completed.  These path remnants are kept on a stack of
9747bbfd9adSNeilBrownlimited size.
9757bbfd9adSNeilBrown
9767bbfd9adSNeilBrownThere are two reasons for placing limits on how many symlinks can
9777bbfd9adSNeilBrownoccur in a single path lookup.  The most obvious is to avoid loops.
9787bbfd9adSNeilBrownIf a symlink referred to itself either directly or through
9797bbfd9adSNeilBrownintermediaries, then following the symlink can never complete
9807bbfd9adSNeilBrownsuccessfully - the error ``ELOOP`` must be returned.  Loops can be
9817bbfd9adSNeilBrowndetected without imposing limits, but limits are the simplest solution
9827bbfd9adSNeilBrownand, given the second reason for restriction, quite sufficient.
9837bbfd9adSNeilBrown
9847bbfd9adSNeilBrown.. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550
9857bbfd9adSNeilBrown
9867bbfd9adSNeilBrownThe second reason was `outlined recently`_ by Linus:
9877bbfd9adSNeilBrown
9887bbfd9adSNeilBrown   Because it's a latency and DoS issue too. We need to react well to
9897bbfd9adSNeilBrown   true loops, but also to "very deep" non-loops. It's not about memory
9907bbfd9adSNeilBrown   use, it's about users triggering unreasonable CPU resources.
9917bbfd9adSNeilBrown
9927bbfd9adSNeilBrownLinux imposes a limit on the length of any pathname: ``PATH_MAX``, which
9937bbfd9adSNeilBrownis 4096.  There are a number of reasons for this limit; not letting the
9947bbfd9adSNeilBrownkernel spend too much time on just one path is one of them.  With
9957bbfd9adSNeilBrownsymbolic links you can effectively generate much longer paths so some
9967bbfd9adSNeilBrownsort of limit is needed for the same reason.  Linux imposes a limit of
9977bbfd9adSNeilBrownat most 40 symlinks in any one path lookup.  It previously imposed a
9987bbfd9adSNeilBrownfurther limit of eight on the maximum depth of recursion, but that was
9997bbfd9adSNeilBrownraised to 40 when a separate stack was implemented, so there is now
10007bbfd9adSNeilBrownjust the one limit.
10017bbfd9adSNeilBrown
10027bbfd9adSNeilBrownThe ``nameidata`` structure that we met in an earlier article contains a
10037bbfd9adSNeilBrownsmall stack that can be used to store the remaining part of up to two
10047bbfd9adSNeilBrownsymlinks.  In many cases this will be sufficient.  If it isn't, a
10057bbfd9adSNeilBrownseparate stack is allocated with room for 40 symlinks.  Pathname
10067bbfd9adSNeilBrownlookup will never exceed that stack as, once the 40th symlink is
10077bbfd9adSNeilBrowndetected, an error is returned.
10087bbfd9adSNeilBrown
10097bbfd9adSNeilBrownIt might seem that the name remnants are all that needs to be stored on
10107bbfd9adSNeilBrownthis stack, but we need a bit more.  To see that, we need to move on to
10117bbfd9adSNeilBrowncache lifetimes.
10127bbfd9adSNeilBrown
10137bbfd9adSNeilBrownStorage and lifetime of cached symlinks
10147bbfd9adSNeilBrown---------------------------------------
10157bbfd9adSNeilBrown
10167bbfd9adSNeilBrownLike other filesystem resources, such as inodes and directory
10177bbfd9adSNeilBrownentries, symlinks are cached by Linux to avoid repeated costly access
10187bbfd9adSNeilBrownto external storage.  It is particularly important for RCU-walk to be
10197bbfd9adSNeilBrownable to find and temporarily hold onto these cached entries, so that
10207bbfd9adSNeilBrownit doesn't need to drop down into REF-walk.
10217bbfd9adSNeilBrown
10227bbfd9adSNeilBrown.. _object-oriented design pattern: https://lwn.net/Articles/446317/
10237bbfd9adSNeilBrown
10247bbfd9adSNeilBrownWhile each filesystem is free to make its own choice, symlinks are
10257bbfd9adSNeilBrowntypically stored in one of two places.  Short symlinks are often
10267bbfd9adSNeilBrownstored directly in the inode.  When a filesystem allocates a ``struct
10277bbfd9adSNeilBrowninode`` it typically allocates extra space to store private data (a
10287bbfd9adSNeilBrowncommon `object-oriented design pattern`_ in the kernel).  This will
10297bbfd9adSNeilBrownsometimes include space for a symlink.  The other common location is
10307bbfd9adSNeilBrownin the page cache, which normally stores the content of files.  The
10317bbfd9adSNeilBrownpathname in a symlink can be seen as the content of that symlink and
10327bbfd9adSNeilBrowncan easily be stored in the page cache just like file content.
10337bbfd9adSNeilBrown
10347bbfd9adSNeilBrownWhen neither of these is suitable, the next most likely scenario is
10357bbfd9adSNeilBrownthat the filesystem will allocate some temporary memory and copy or
10367bbfd9adSNeilBrownconstruct the symlink content into that memory whenever it is needed.
10377bbfd9adSNeilBrown
10387bbfd9adSNeilBrownWhen the symlink is stored in the inode, it has the same lifetime as
10397bbfd9adSNeilBrownthe inode which, itself, is protected by RCU or by a counted reference
10407bbfd9adSNeilBrownon the dentry.  This means that the mechanisms that pathname lookup
10417bbfd9adSNeilBrownuses to access the dcache and icache (inode cache) safely are quite
10427bbfd9adSNeilBrownsufficient for accessing some cached symlinks safely.  In these cases,
10437bbfd9adSNeilBrownthe ``i_link`` pointer in the inode is set to point to wherever the
10447bbfd9adSNeilBrownsymlink is stored and it can be accessed directly whenever needed.
10457bbfd9adSNeilBrown
10467bbfd9adSNeilBrownWhen the symlink is stored in the page cache or elsewhere, the
10477bbfd9adSNeilBrownsituation is not so straightforward.  A reference on a dentry or even
10487bbfd9adSNeilBrownon an inode does not imply any reference on cached pages of that
10497bbfd9adSNeilBrowninode, and even an ``rcu_read_lock()`` is not sufficient to ensure that
10507bbfd9adSNeilBrowna page will not disappear.  So for these symlinks the pathname lookup
10517bbfd9adSNeilBrowncode needs to ask the filesystem to provide a stable reference and,
10527bbfd9adSNeilBrownsignificantly, needs to release that reference when it is finished
10537bbfd9adSNeilBrownwith it.
10547bbfd9adSNeilBrown
10557bbfd9adSNeilBrownTaking a reference to a cache page is often possible even in RCU-walk
10567bbfd9adSNeilBrownmode.  It does require making changes to memory, which is best avoided,
10577bbfd9adSNeilBrownbut that isn't necessarily a big cost and it is better than dropping
10587bbfd9adSNeilBrownout of RCU-walk mode completely.  Even filesystems that allocate
10597bbfd9adSNeilBrownspace to copy the symlink into can use ``GFP_ATOMIC`` to often successfully
10607bbfd9adSNeilBrownallocate memory without the need to drop out of RCU-walk.  If a
10617bbfd9adSNeilBrownfilesystem cannot successfully get a reference in RCU-walk mode, it
10627bbfd9adSNeilBrownmust return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to
10637bbfd9adSNeilBrownREF-walk mode in which the filesystem is allowed to sleep.
10647bbfd9adSNeilBrown
10657bbfd9adSNeilBrownThe place for all this to happen is the ``i_op->follow_link()`` inode
10667bbfd9adSNeilBrownmethod.  In the present mainline code this is never actually called in
10677bbfd9adSNeilBrownRCU-walk mode as the rewrite is not quite complete.  It is likely that
10687bbfd9adSNeilBrownin a future release this method will be passed an ``inode`` pointer when
10697bbfd9adSNeilBrowncalled in RCU-walk mode so it both (1) knows to be careful, and (2) has the
10707bbfd9adSNeilBrownvalidated pointer.  Much like the ``i_op->permission()`` method we
10717bbfd9adSNeilBrownlooked at previously, ``->follow_link()`` would need to be careful that
10727bbfd9adSNeilBrownall the data structures it references are safe to be accessed while
10737bbfd9adSNeilBrownholding no counted reference, only the RCU lock.  Though getting a
10747bbfd9adSNeilBrownreference with ``->follow_link()`` is not yet done in RCU-walk mode, the
10757bbfd9adSNeilBrowncode is ready to release the reference when that does happen.
10767bbfd9adSNeilBrown
10777bbfd9adSNeilBrownThis need to drop the reference to a symlink adds significant
10787bbfd9adSNeilBrowncomplexity.  It requires a reference to the inode so that the
10797bbfd9adSNeilBrown``i_op->put_link()`` inode operation can be called.  In REF-walk, that
10807bbfd9adSNeilBrownreference is kept implicitly through a reference to the dentry, so
10817bbfd9adSNeilBrownkeeping the ``struct path`` of the symlink is easiest.  For RCU-walk,
10827bbfd9adSNeilBrownthe pointer to the inode is kept separately.  To allow switching from
10837bbfd9adSNeilBrownRCU-walk back to REF-walk in the middle of processing nested symlinks
10847bbfd9adSNeilBrownwe also need the seq number for the dentry so we can confirm that
10857bbfd9adSNeilBrownswitching back was safe.
10867bbfd9adSNeilBrown
10877bbfd9adSNeilBrownFinally, when providing a reference to a symlink, the filesystem also
10887bbfd9adSNeilBrownprovides an opaque "cookie" that must be passed to ``->put_link()`` so that it
10897bbfd9adSNeilBrownknows what to free.  This might be the allocated memory area, or a
10907bbfd9adSNeilBrownpointer to the ``struct page`` in the page cache, or something else
10917bbfd9adSNeilBrowncompletely.  Only the filesystem knows what it is.
10927bbfd9adSNeilBrown
10937bbfd9adSNeilBrownIn order for the reference to each symlink to be dropped when the walk completes,
10947bbfd9adSNeilBrownwhether in RCU-walk or REF-walk, the symlink stack needs to contain,
10957bbfd9adSNeilBrownalong with the path remnants:
10967bbfd9adSNeilBrown
10977bbfd9adSNeilBrown- the ``struct path`` to provide a reference to the inode in REF-walk
10987bbfd9adSNeilBrown- the ``struct inode *`` to provide a reference to the inode in RCU-walk
10997bbfd9adSNeilBrown- the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk
11007bbfd9adSNeilBrown- the ``cookie`` that tells ``->put_path()`` what to put.
11017bbfd9adSNeilBrown
11027bbfd9adSNeilBrownThis means that each entry in the symlink stack needs to hold five
11037bbfd9adSNeilBrownpointers and an integer instead of just one pointer (the path
11047bbfd9adSNeilBrownremnant).  On a 64-bit system, this is about 40 bytes per entry;
11057bbfd9adSNeilBrownwith 40 entries it adds up to 1600 bytes total, which is less than
11067bbfd9adSNeilBrownhalf a page.  So it might seem like a lot, but is by no means
11077bbfd9adSNeilBrownexcessive.
11087bbfd9adSNeilBrown
11097bbfd9adSNeilBrownNote that, in a given stack frame, the path remnant (``name``) is not
11107bbfd9adSNeilBrownpart of the symlink that the other fields refer to.  It is the remnant
11117bbfd9adSNeilBrownto be followed once that symlink has been fully parsed.
11127bbfd9adSNeilBrown
11137bbfd9adSNeilBrownFollowing the symlink
11147bbfd9adSNeilBrown---------------------
11157bbfd9adSNeilBrown
11167bbfd9adSNeilBrownThe main loop in ``link_path_walk()`` iterates seamlessly over all
11177bbfd9adSNeilBrowncomponents in the path and all of the non-final symlinks.  As symlinks
11187bbfd9adSNeilBrownare processed, the ``name`` pointer is adjusted to point to a new
11197bbfd9adSNeilBrownsymlink, or is restored from the stack, so that much of the loop
11207bbfd9adSNeilBrowndoesn't need to notice.  Getting this ``name`` variable on and off the
11217bbfd9adSNeilBrownstack is very straightforward; pushing and popping the references is
11227bbfd9adSNeilBrowna little more complex.
11237bbfd9adSNeilBrown
11247bbfd9adSNeilBrownWhen a symlink is found, ``walk_component()`` returns the value ``1``
11257bbfd9adSNeilBrown(``0`` is returned for any other sort of success, and a negative number
11267bbfd9adSNeilBrownis, as usual, an error indicator).  This causes ``get_link()`` to be
11277bbfd9adSNeilBrowncalled; it then gets the link from the filesystem.  Providing that
11287bbfd9adSNeilBrownoperation is successful, the old path ``name`` is placed on the stack,
11297bbfd9adSNeilBrownand the new value is used as the ``name`` for a while.  When the end of
11307bbfd9adSNeilBrownthe path is found (i.e. ``*name`` is ``'\0'``) the old ``name`` is restored
11317bbfd9adSNeilBrownoff the stack and path walking continues.
11327bbfd9adSNeilBrown
11337bbfd9adSNeilBrownPushing and popping the reference pointers (inode, cookie, etc.) is more
11347bbfd9adSNeilBrowncomplex in part because of the desire to handle tail recursion.  When
11357bbfd9adSNeilBrownthe last component of a symlink itself points to a symlink, we
11367bbfd9adSNeilBrownwant to pop the symlink-just-completed off the stack before pushing
11377bbfd9adSNeilBrownthe symlink-just-found to avoid leaving empty path remnants that would
11387bbfd9adSNeilBrownjust get in the way.
11397bbfd9adSNeilBrown
11407bbfd9adSNeilBrownIt is most convenient to push the new symlink references onto the
11417bbfd9adSNeilBrownstack in ``walk_component()`` immediately when the symlink is found;
11427bbfd9adSNeilBrown``walk_component()`` is also the last piece of code that needs to look at the
11437bbfd9adSNeilBrownold symlink as it walks that last component.  So it is quite
11447bbfd9adSNeilBrownconvenient for ``walk_component()`` to release the old symlink and pop
11457bbfd9adSNeilBrownthe references just before pushing the reference information for the
11467bbfd9adSNeilBrownnew symlink.  It is guided in this by two flags; ``WALK_GET``, which
11477bbfd9adSNeilBrowngives it permission to follow a symlink if it finds one, and
11487bbfd9adSNeilBrown``WALK_PUT``, which tells it to release the current symlink after it has been
11497bbfd9adSNeilBrownfollowed.  ``WALK_PUT`` is tested first, leading to a call to
11507bbfd9adSNeilBrown``put_link()``.  ``WALK_GET`` is tested subsequently (by
11517bbfd9adSNeilBrown``should_follow_link()``) leading to a call to ``pick_link()`` which sets
11527bbfd9adSNeilBrownup the stack frame.
11537bbfd9adSNeilBrown
11547bbfd9adSNeilBrownSymlinks with no final component
11557bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11567bbfd9adSNeilBrown
11577bbfd9adSNeilBrownA pair of special-case symlinks deserve a little further explanation.
11587bbfd9adSNeilBrownBoth result in a new ``struct path`` (with mount and dentry) being set
11597bbfd9adSNeilBrownup in the ``nameidata``, and result in ``get_link()`` returning ``NULL``.
11607bbfd9adSNeilBrown
11617bbfd9adSNeilBrownThe more obvious case is a symlink to "``/``".  All symlinks starting
11627bbfd9adSNeilBrownwith "``/``" are detected in ``get_link()`` which resets the ``nameidata``
11637bbfd9adSNeilBrownto point to the effective filesystem root.  If the symlink only
11647bbfd9adSNeilBrowncontains "``/``" then there is nothing more to do, no components at all,
11657bbfd9adSNeilBrownso ``NULL`` is returned to indicate that the symlink can be released and
11667bbfd9adSNeilBrownthe stack frame discarded.
11677bbfd9adSNeilBrown
11687bbfd9adSNeilBrownThe other case involves things in ``/proc`` that look like symlinks but
1169b55eef87SAleksa Saraiaren't really (and are therefore commonly referred to as "magic-links")::
11707bbfd9adSNeilBrown
11717bbfd9adSNeilBrown     $ ls -l /proc/self/fd/1
11727bbfd9adSNeilBrown     lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4
11737bbfd9adSNeilBrown
11747bbfd9adSNeilBrownEvery open file descriptor in any process is represented in ``/proc`` by
11757bbfd9adSNeilBrownsomething that looks like a symlink.  It is really a reference to the
11767bbfd9adSNeilBrowntarget file, not just the name of it.  When you ``readlink`` these
11777bbfd9adSNeilBrownobjects you get a name that might refer to the same file - unless it
11787bbfd9adSNeilBrownhas been unlinked or mounted over.  When ``walk_component()`` follows
11797bbfd9adSNeilBrownone of these, the ``->follow_link()`` method in "procfs" doesn't return
11807bbfd9adSNeilBrowna string name, but instead calls ``nd_jump_link()`` which updates the
11817bbfd9adSNeilBrown``nameidata`` in place to point to that target.  ``->follow_link()`` then
11827bbfd9adSNeilBrownreturns ``NULL``.  Again there is no final component and ``get_link()``
11837bbfd9adSNeilBrownreports this by leaving the ``last_type`` field of ``nameidata`` as
11847bbfd9adSNeilBrown``LAST_BIND``.
11857bbfd9adSNeilBrown
11867bbfd9adSNeilBrownFollowing the symlink in the final component
11877bbfd9adSNeilBrown--------------------------------------------
11887bbfd9adSNeilBrown
11897bbfd9adSNeilBrownAll this leads to ``link_path_walk()`` walking down every component, and
11907bbfd9adSNeilBrownfollowing all symbolic links it finds, until it reaches the final
11917bbfd9adSNeilBrowncomponent.  This is just returned in the ``last`` field of ``nameidata``.
11927bbfd9adSNeilBrownFor some callers, this is all they need; they want to create that
11937bbfd9adSNeilBrown``last`` name if it doesn't exist or give an error if it does.  Other
11947bbfd9adSNeilBrowncallers will want to follow a symlink if one is found, and possibly
11957bbfd9adSNeilBrownapply special handling to the last component of that symlink, rather
11967bbfd9adSNeilBrownthan just the last component of the original file name.  These callers
11977bbfd9adSNeilBrownpotentially need to call ``link_path_walk()`` again and again on
11987bbfd9adSNeilBrownsuccessive symlinks until one is found that doesn't point to another
11997bbfd9adSNeilBrownsymlink.
12007bbfd9adSNeilBrown
12017bbfd9adSNeilBrownThis case is handled by the relevant caller of ``link_path_walk()``, such as
12027bbfd9adSNeilBrown``path_lookupat()`` using a loop that calls ``link_path_walk()``, and then
12037bbfd9adSNeilBrownhandles the final component.  If the final component is a symlink
12047bbfd9adSNeilBrownthat needs to be followed, then ``trailing_symlink()`` is called to set
12057bbfd9adSNeilBrownthings up properly and the loop repeats, calling ``link_path_walk()``
12067bbfd9adSNeilBrownagain.  This could loop as many as 40 times if the last component of
12077bbfd9adSNeilBrowneach symlink is another symlink.
12087bbfd9adSNeilBrown
12097bbfd9adSNeilBrownThe various functions that examine the final component and possibly
12107bbfd9adSNeilBrownreport that it is a symlink are ``lookup_last()``, ``mountpoint_last()``
12117bbfd9adSNeilBrownand ``do_last()``, each of which use the same convention as
12127bbfd9adSNeilBrown``walk_component()`` of returning ``1`` if a symlink was found that needs
12137bbfd9adSNeilBrownto be followed.
12147bbfd9adSNeilBrown
12157bbfd9adSNeilBrownOf these, ``do_last()`` is the most interesting as it is used for
12167bbfd9adSNeilBrownopening a file.  Part of ``do_last()`` runs with ``i_rwsem`` held and this
12177bbfd9adSNeilBrownpart is in a separate function: ``lookup_open()``.
12187bbfd9adSNeilBrown
12197bbfd9adSNeilBrownExplaining ``do_last()`` completely is beyond the scope of this article,
12207bbfd9adSNeilBrownbut a few highlights should help those interested in exploring the
12217bbfd9adSNeilBrowncode.
12227bbfd9adSNeilBrown
12237bbfd9adSNeilBrown1. Rather than just finding the target file, ``do_last()`` needs to open
12247bbfd9adSNeilBrown   it.  If the file was found in the dcache, then ``vfs_open()`` is used for
12257bbfd9adSNeilBrown   this.  If not, then ``lookup_open()`` will either call ``atomic_open()`` (if
12267bbfd9adSNeilBrown   the filesystem provides it) to combine the final lookup with the open, or
12277bbfd9adSNeilBrown   will perform the separate ``lookup_real()`` and ``vfs_create()`` steps
12287bbfd9adSNeilBrown   directly.  In the later case the actual "open" of this newly found or
12297bbfd9adSNeilBrown   created file will be performed by ``vfs_open()``, just as if the name
12307bbfd9adSNeilBrown   were found in the dcache.
12317bbfd9adSNeilBrown
12327bbfd9adSNeilBrown2. ``vfs_open()`` can fail with ``-EOPENSTALE`` if the cached information
12337bbfd9adSNeilBrown   wasn't quite current enough.  Rather than restarting the lookup from
12347bbfd9adSNeilBrown   the top with ``LOOKUP_REVAL`` set, ``lookup_open()`` is called instead,
12357bbfd9adSNeilBrown   giving the filesystem a chance to resolve small inconsistencies.
12367bbfd9adSNeilBrown   If that doesn't work, only then is the lookup restarted from the top.
12377bbfd9adSNeilBrown
12387bbfd9adSNeilBrown3. An open with O_CREAT **does** follow a symlink in the final component,
12397bbfd9adSNeilBrown   unlike other creation system calls (like ``mkdir``).  So the sequence::
12407bbfd9adSNeilBrown
12417bbfd9adSNeilBrown          ln -s bar /tmp/foo
12427bbfd9adSNeilBrown          echo hello > /tmp/foo
12437bbfd9adSNeilBrown
12447bbfd9adSNeilBrown   will create a file called ``/tmp/bar``.  This is not permitted if
12457bbfd9adSNeilBrown   ``O_EXCL`` is set but otherwise is handled for an O_CREAT open much
12467bbfd9adSNeilBrown   like for a non-creating open: ``should_follow_link()`` returns ``1``, and
12477bbfd9adSNeilBrown   so does ``do_last()`` so that ``trailing_symlink()`` gets called and the
12487bbfd9adSNeilBrown   open process continues on the symlink that was found.
12497bbfd9adSNeilBrown
12507bbfd9adSNeilBrownUpdating the access time
12517bbfd9adSNeilBrown------------------------
12527bbfd9adSNeilBrown
12537bbfd9adSNeilBrownWe previously said of RCU-walk that it would "take no locks, increment
12547bbfd9adSNeilBrownno counts, leave no footprints."  We have since seen that some
12557bbfd9adSNeilBrown"footprints" can be needed when handling symlinks as a counted
12567bbfd9adSNeilBrownreference (or even a memory allocation) may be needed.  But these
12577bbfd9adSNeilBrownfootprints are best kept to a minimum.
12587bbfd9adSNeilBrown
12597bbfd9adSNeilBrownOne other place where walking down a symlink can involve leaving
12607bbfd9adSNeilBrownfootprints in a way that doesn't affect directories is in updating access times.
12617bbfd9adSNeilBrownIn Unix (and Linux) every filesystem object has a "last accessed
12627bbfd9adSNeilBrowntime", or "``atime``".  Passing through a directory to access a file
12637bbfd9adSNeilBrownwithin is not considered to be an access for the purposes of
12647bbfd9adSNeilBrown``atime``; only listing the contents of a directory can update its ``atime``.
12657bbfd9adSNeilBrownSymlinks are different it seems.  Both reading a symlink (with ``readlink()``)
12667bbfd9adSNeilBrownand looking up a symlink on the way to some other destination can
12677bbfd9adSNeilBrownupdate the atime on that symlink.
12687bbfd9adSNeilBrown
1269c69f22f2SAlexander A. Klimov.. _clearest statement: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08
12707bbfd9adSNeilBrown
12717bbfd9adSNeilBrownIt is not clear why this is the case; POSIX has little to say on the
12727bbfd9adSNeilBrownsubject.  The `clearest statement`_ is that, if a particular implementation
12737bbfd9adSNeilBrownupdates a timestamp in a place not specified by POSIX, this must be
12747bbfd9adSNeilBrowndocumented "except that any changes caused by pathname resolution need
12757bbfd9adSNeilBrownnot be documented".  This seems to imply that POSIX doesn't really
12767bbfd9adSNeilBrowncare about access-time updates during pathname lookup.
12777bbfd9adSNeilBrown
12787bbfd9adSNeilBrown.. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8
12797bbfd9adSNeilBrown
12807bbfd9adSNeilBrownAn examination of history shows that prior to `Linux 1.3.87`_, the ext2
12817bbfd9adSNeilBrownfilesystem, at least, didn't update atime when following a link.
12827bbfd9adSNeilBrownUnfortunately we have no record of why that behavior was changed.
12837bbfd9adSNeilBrown
12847bbfd9adSNeilBrownIn any case, access time must now be updated and that operation can be
12857bbfd9adSNeilBrownquite complex.  Trying to stay in RCU-walk while doing it is best
12867bbfd9adSNeilBrownavoided.  Fortunately it is often permitted to skip the ``atime``
12877bbfd9adSNeilBrownupdate.  Because ``atime`` updates cause performance problems in various
12887bbfd9adSNeilBrownareas, Linux supports the ``relatime`` mount option, which generally
12897bbfd9adSNeilBrownlimits the updates of ``atime`` to once per day on files that aren't
12907bbfd9adSNeilBrownbeing changed (and symlinks never change once created).  Even without
12917bbfd9adSNeilBrown``relatime``, many filesystems record ``atime`` with a one-second
12927bbfd9adSNeilBrowngranularity, so only one update per second is required.
12937bbfd9adSNeilBrown
12947bbfd9adSNeilBrownIt is easy to test if an ``atime`` update is needed while in RCU-walk
12957bbfd9adSNeilBrownmode and, if it isn't, the update can be skipped and RCU-walk mode
12967bbfd9adSNeilBrowncontinues.  Only when an ``atime`` update is actually required does the
12977bbfd9adSNeilBrownpath walk drop down to REF-walk.  All of this is handled in the
12987bbfd9adSNeilBrown``get_link()`` function.
12997bbfd9adSNeilBrown
13007bbfd9adSNeilBrownA few flags
13017bbfd9adSNeilBrown-----------
13027bbfd9adSNeilBrown
13037bbfd9adSNeilBrownA suitable way to wrap up this tour of pathname walking is to list
13047bbfd9adSNeilBrownthe various flags that can be stored in the ``nameidata`` to guide the
13057bbfd9adSNeilBrownlookup process.  Many of these are only meaningful on the final
1306b55eef87SAleksa Saraicomponent, others reflect the current state of the pathname lookup, and some
1307b55eef87SAleksa Saraiapply restrictions to all path components encountered in the path lookup.
1308b55eef87SAleksa Sarai
13097bbfd9adSNeilBrownAnd then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with
13107bbfd9adSNeilBrownthe others.  If this is not set, an empty pathname causes an error
13117bbfd9adSNeilBrownvery early on.  If it is set, empty pathnames are not considered to be
13127bbfd9adSNeilBrownan error.
13137bbfd9adSNeilBrown
13147bbfd9adSNeilBrownGlobal state flags
13157bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~~
13167bbfd9adSNeilBrown
13177bbfd9adSNeilBrownWe have already met two global state flags: ``LOOKUP_RCU`` and
13187bbfd9adSNeilBrown``LOOKUP_REVAL``.  These select between one of three overall approaches
13197bbfd9adSNeilBrownto lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.
13207bbfd9adSNeilBrown
13217bbfd9adSNeilBrown``LOOKUP_PARENT`` indicates that the final component hasn't been reached
13227bbfd9adSNeilBrownyet.  This is primarily used to tell the audit subsystem the full
13237bbfd9adSNeilBrowncontext of a particular access being audited.
13247bbfd9adSNeilBrown
13257bbfd9adSNeilBrown``LOOKUP_ROOT`` indicates that the ``root`` field in the ``nameidata`` was
13267bbfd9adSNeilBrownprovided by the caller, so it shouldn't be released when it is no
13277bbfd9adSNeilBrownlonger needed.
13287bbfd9adSNeilBrown
13297bbfd9adSNeilBrown``LOOKUP_JUMPED`` means that the current dentry was chosen not because
13307bbfd9adSNeilBrownit had the right name but for some other reason.  This happens when
13317bbfd9adSNeilBrownfollowing "``..``", following a symlink to ``/``, crossing a mount point
1332b55eef87SAleksa Saraior accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic
1333b55eef87SAleksa Sarailink"). In this case the filesystem has not been asked to revalidate the
1334b55eef87SAleksa Sarainame (with ``d_revalidate()``).  In such cases the inode may still need
1335b55eef87SAleksa Saraito be revalidated, so ``d_op->d_weak_revalidate()`` is called if
13367bbfd9adSNeilBrown``LOOKUP_JUMPED`` is set when the look completes - which may be at the
13377bbfd9adSNeilBrownfinal component or, when creating, unlinking, or renaming, at the penultimate component.
13387bbfd9adSNeilBrown
1339b55eef87SAleksa SaraiResolution-restriction flags
1340b55eef87SAleksa Sarai~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1341b55eef87SAleksa Sarai
1342b55eef87SAleksa SaraiIn order to allow userspace to protect itself against certain race conditions
1343b55eef87SAleksa Saraiand attack scenarios involving changing path components, a series of flags are
1344b55eef87SAleksa Saraiavailable which apply restrictions to all path components encountered during
1345b55eef87SAleksa Saraipath lookup. These flags are exposed through ``openat2()``'s ``resolve`` field.
1346b55eef87SAleksa Sarai
1347b55eef87SAleksa Sarai``LOOKUP_NO_SYMLINKS`` blocks all symlink traversals (including magic-links).
1348b55eef87SAleksa SaraiThis is distinctly different from ``LOOKUP_FOLLOW``, because the latter only
1349b55eef87SAleksa Sarairelates to restricting the following of trailing symlinks.
1350b55eef87SAleksa Sarai
1351b55eef87SAleksa Sarai``LOOKUP_NO_MAGICLINKS`` blocks all magic-link traversals. Filesystems must
1352b55eef87SAleksa Saraiensure that they return errors from ``nd_jump_link()``, because that is how
1353b55eef87SAleksa Sarai``LOOKUP_NO_MAGICLINKS`` and other magic-link restrictions are implemented.
1354b55eef87SAleksa Sarai
1355b55eef87SAleksa Sarai``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` traversals (this includes both
1356b55eef87SAleksa Saraibind-mounts and ordinary mounts). Note that the ``vfsmount`` which contains the
1357b55eef87SAleksa Sarailookup is determined by the first mountpoint the path lookup reaches --
1358b55eef87SAleksa Saraiabsolute paths start with the ``vfsmount`` of ``/``, and relative paths start
1359b55eef87SAleksa Saraiwith the ``dfd``'s ``vfsmount``. Magic-links are only permitted if the
1360b55eef87SAleksa Sarai``vfsmount`` of the path is unchanged.
1361b55eef87SAleksa Sarai
1362b55eef87SAleksa Sarai``LOOKUP_BENEATH`` blocks any path components which resolve outside the
1363b55eef87SAleksa Saraistarting point of the resolution. This is done by blocking ``nd_jump_root()``
1364b55eef87SAleksa Saraias well as blocking ".." if it would jump outside the starting point.
1365b55eef87SAleksa Sarai``rename_lock`` and ``mount_lock`` are used to detect attacks against the
1366b55eef87SAleksa Sarairesolution of "..". Magic-links are also blocked.
1367b55eef87SAleksa Sarai
1368b55eef87SAleksa Sarai``LOOKUP_IN_ROOT`` resolves all path components as though the starting point
13699b123556SRandy Dunlapwere the filesystem root. ``nd_jump_root()`` brings the resolution back to
1370b55eef87SAleksa Saraithe starting point, and ".." at the starting point will act as a no-op. As with
1371b55eef87SAleksa Sarai``LOOKUP_BENEATH``, ``rename_lock`` and ``mount_lock`` are used to detect
1372b55eef87SAleksa Saraiattacks against ".." resolution. Magic-links are also blocked.
1373b55eef87SAleksa Sarai
13747bbfd9adSNeilBrownFinal-component flags
13757bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~~~~~
13767bbfd9adSNeilBrown
13777bbfd9adSNeilBrownSome of these flags are only set when the final component is being
13787bbfd9adSNeilBrownconsidered.  Others are only checked for when considering that final
13797bbfd9adSNeilBrowncomponent.
13807bbfd9adSNeilBrown
13817bbfd9adSNeilBrown``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount
13827bbfd9adSNeilBrownpoint, then the mount is triggered.  Some operations would trigger it
13837bbfd9adSNeilBrownanyway, but operations like ``stat()`` deliberately don't.  ``statfs()``
13847bbfd9adSNeilBrownneeds to trigger the mount but otherwise behaves a lot like ``stat()``, so
13857bbfd9adSNeilBrownit sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of
13867bbfd9adSNeilBrown"``mount --bind``".
13877bbfd9adSNeilBrown
13887bbfd9adSNeilBrown``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for
13897bbfd9adSNeilBrownsymlinks.  Some system calls set or clear it implicitly, while
13907bbfd9adSNeilBrownothers have API flags such as ``AT_SYMLINK_FOLLOW`` and
13917bbfd9adSNeilBrown``UMOUNT_NOFOLLOW`` to control it.  Its effect is similar to
13927bbfd9adSNeilBrown``WALK_GET`` that we already met, but it is used in a different way.
13937bbfd9adSNeilBrown
13947bbfd9adSNeilBrown``LOOKUP_DIRECTORY`` insists that the final component is a directory.
13957bbfd9adSNeilBrownVarious callers set this and it is also set when the final component
13967bbfd9adSNeilBrownis found to be followed by a slash.
13977bbfd9adSNeilBrown
13987bbfd9adSNeilBrownFinally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and
13997bbfd9adSNeilBrown``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made
14007bbfd9adSNeilBrownavailable to the filesystem and particularly the ``->d_revalidate()``
14017bbfd9adSNeilBrownmethod.  A filesystem can choose not to bother revalidating too hard
14027bbfd9adSNeilBrownif it knows that it will be asked to open or create the file soon.
14037bbfd9adSNeilBrownThese flags were previously useful for ``->lookup()`` too but with the
14047bbfd9adSNeilBrownintroduction of ``->atomic_open()`` they are less relevant there.
14057bbfd9adSNeilBrown
14067bbfd9adSNeilBrownEnd of the road
14077bbfd9adSNeilBrown---------------
14087bbfd9adSNeilBrown
14097bbfd9adSNeilBrownDespite its complexity, all this pathname lookup code appears to be
14107bbfd9adSNeilBrownin good shape - various parts are certainly easier to understand now
14117bbfd9adSNeilBrownthan even a couple of releases ago.  But that doesn't mean it is
14127bbfd9adSNeilBrown"finished".   As already mentioned, RCU-walk currently only follows
14137bbfd9adSNeilBrownsymlinks that are stored in the inode so, while it handles many ext4
14147bbfd9adSNeilBrownsymlinks, it doesn't help with NFS, XFS, or Btrfs.  That support
14157bbfd9adSNeilBrownis not likely to be long delayed.
1416