xref: /linux/Documentation/filesystems/path-lookup.rst (revision 762f99f4f3cb41a775b5157dd761217beba65873)
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
453*8943474aSFox ChenAs the last step of walk_component(), step_into() will be called either
454993b8926SFox Chendirectly from walk_component() or from handle_dots().  It calls
455*8943474aSFox Chenhandle_mounts(), to check and handle mount points, in which a new
456084c8683SFox Chen``struct path`` is created containing a counted reference to the new dentry and
457084c8683SFox Chena reference to the new ``vfsmount`` which is only counted if it is
458084c8683SFox Chendifferent from the previous ``vfsmount``. Then if there is
459*8943474aSFox Chena symbolic link, step_into() calls pick_link() to deal with it,
460084c8683SFox Chenotherwise it installs the new ``struct path`` in the ``struct nameidata``, and
461084c8683SFox 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
475*8943474aSFox Chenpath_lookupat(), path_parentat() and
476*8943474aSFox Chenpath_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.
4918593d2ccSFox ChenIt is worth noting that when flag ``LOOKUP_MOUNTPOINT`` is set,
492*8943474aSFox Chenpath_lookupat() will unset LOOKUP_JUMPED in nameidata so that in the
493*8943474aSFox Chensubsequent path traversal d_weak_revalidate() won't be called.
4948593d2ccSFox ChenThis is important when unmounting a filesystem that is inaccessible, such as
4957bbfd9adSNeilBrownone provided by a dead NFS server.
4967bbfd9adSNeilBrown
4977bbfd9adSNeilBrownFinally ``path_openat()`` is used for the ``open()`` system call; it
498*8943474aSFox Chencontains, in support functions starting with "open_last_lookups()", all the
4997bbfd9adSNeilBrowncomplexity needed to handle the different subtleties of O_CREAT (with
5007bbfd9adSNeilBrownor without O_EXCL), final "``/``" characters, and trailing symbolic
5017bbfd9adSNeilBrownlinks.  We will revisit this in the final part of this series, which
502*8943474aSFox Chenfocuses on those symbolic links.  "open_last_lookups()" will sometimes, but
5037bbfd9adSNeilBrownnot always, take ``i_rwsem``, depending on what it finds.
5047bbfd9adSNeilBrown
5057bbfd9adSNeilBrownEach of these, or the functions which call them, need to be alert to
5067bbfd9adSNeilBrownthe possibility that the final component is not ``LAST_NORM``.  If the
5077bbfd9adSNeilBrowngoal of the lookup is to create something, then any value for
5087bbfd9adSNeilBrown``last_type`` other than ``LAST_NORM`` will result in an error.  For
5097bbfd9adSNeilBrownexample if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller
5107bbfd9adSNeilBrownwon't try to create that name.  They also check for trailing slashes
5117bbfd9adSNeilBrownby testing ``last.name[last.len]``.  If there is any character beyond
5127bbfd9adSNeilBrownthe final component, it must be a trailing slash.
5137bbfd9adSNeilBrown
5147bbfd9adSNeilBrownRevalidation and automounts
5157bbfd9adSNeilBrown---------------------------
5167bbfd9adSNeilBrown
5177bbfd9adSNeilBrownApart from symbolic links, there are only two parts of the "REF-walk"
5187bbfd9adSNeilBrownprocess not yet covered.  One is the handling of stale cache entries
5197bbfd9adSNeilBrownand the other is automounts.
5207bbfd9adSNeilBrown
5217bbfd9adSNeilBrownOn filesystems that require it, the lookup routines will call the
5227bbfd9adSNeilBrown``->d_revalidate()`` dentry method to ensure that the cached information
5237bbfd9adSNeilBrownis current.  This will often confirm validity or update a few details
5247bbfd9adSNeilBrownfrom a server.  In some cases it may find that there has been change
5257bbfd9adSNeilBrownfurther up the path and that something that was thought to be valid
5267bbfd9adSNeilBrownpreviously isn't really.  When this happens the lookup of the whole
5277bbfd9adSNeilBrownpath is aborted and retried with the "``LOOKUP_REVAL``" flag set.  This
5287bbfd9adSNeilBrownforces revalidation to be more thorough.  We will see more details of
5297bbfd9adSNeilBrownthis retry process in the next article.
5307bbfd9adSNeilBrown
5317bbfd9adSNeilBrownAutomount points are locations in the filesystem where an attempt to
5327bbfd9adSNeilBrownlookup a name can trigger changes to how that lookup should be
5337bbfd9adSNeilBrownhandled, in particular by mounting a filesystem there.  These are
5347bbfd9adSNeilBrowncovered in greater detail in autofs.txt in the Linux documentation
5357bbfd9adSNeilBrowntree, but a few notes specifically related to path lookup are in order
5367bbfd9adSNeilBrownhere.
5377bbfd9adSNeilBrown
538993b8926SFox ChenThe Linux VFS has a concept of "managed" dentries.  There are three
5397bbfd9adSNeilBrownpotentially interesting things about these dentries corresponding
5407bbfd9adSNeilBrownto three different flags that might be set in ``dentry->d_flags``:
5417bbfd9adSNeilBrown
5427bbfd9adSNeilBrown``DCACHE_MANAGE_TRANSIT``
5439f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~
5447bbfd9adSNeilBrown
5457bbfd9adSNeilBrownIf this flag has been set, then the filesystem has requested that the
5467bbfd9adSNeilBrown``d_manage()`` dentry operation be called before handling any possible
5477bbfd9adSNeilBrownmount point.  This can perform two particular services:
5487bbfd9adSNeilBrown
5497bbfd9adSNeilBrownIt can block to avoid races.  If an automount point is being
5507bbfd9adSNeilBrownunmounted, the ``d_manage()`` function will usually wait for that
5517bbfd9adSNeilBrownprocess to complete before letting the new lookup proceed and possibly
5527bbfd9adSNeilBrowntrigger a new automount.
5537bbfd9adSNeilBrown
5547bbfd9adSNeilBrownIt can selectively allow only some processes to transit through a
5557bbfd9adSNeilBrownmount point.  When a server process is managing automounts, it may
5567bbfd9adSNeilBrownneed to access a directory without triggering normal automount
5577bbfd9adSNeilBrownprocessing.  That server process can identify itself to the ``autofs``
5587bbfd9adSNeilBrownfilesystem, which will then give it a special pass through
5597bbfd9adSNeilBrown``d_manage()`` by returning ``-EISDIR``.
5607bbfd9adSNeilBrown
5617bbfd9adSNeilBrown``DCACHE_MOUNTED``
5629f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~
5637bbfd9adSNeilBrown
5647bbfd9adSNeilBrownThis flag is set on every dentry that is mounted on.  As Linux
5657bbfd9adSNeilBrownsupports multiple filesystem namespaces, it is possible that the
5667bbfd9adSNeilBrowndentry may not be mounted on in *this* namespace, just in some
5677bbfd9adSNeilBrownother.  So this flag is seen as a hint, not a promise.
5687bbfd9adSNeilBrown
5697bbfd9adSNeilBrownIf this flag is set, and ``d_manage()`` didn't return ``-EISDIR``,
5707bbfd9adSNeilBrown``lookup_mnt()`` is called to examine the mount hash table (honoring the
5717bbfd9adSNeilBrown``mount_lock`` described earlier) and possibly return a new ``vfsmount``
5727bbfd9adSNeilBrownand a new ``dentry`` (both with counted references).
5737bbfd9adSNeilBrown
5747bbfd9adSNeilBrown``DCACHE_NEED_AUTOMOUNT``
5759f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~
5767bbfd9adSNeilBrown
5777bbfd9adSNeilBrownIf ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't
5787bbfd9adSNeilBrownfind a mount point, then this flag causes the ``d_automount()`` dentry
5797bbfd9adSNeilBrownoperation to be called.
5807bbfd9adSNeilBrown
5817bbfd9adSNeilBrownThe ``d_automount()`` operation can be arbitrarily complex and may
5827bbfd9adSNeilBrowncommunicate with server processes etc. but it should ultimately either
5837bbfd9adSNeilBrownreport that there was an error, that there was nothing to mount, or
5847bbfd9adSNeilBrownshould provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``.
5857bbfd9adSNeilBrown
5867bbfd9adSNeilBrownIn the latter case, ``finish_automount()`` will be called to safely
5877bbfd9adSNeilBrowninstall the new mount point into the mount table.
5887bbfd9adSNeilBrown
5897bbfd9adSNeilBrownThere is no new locking of import here and it is important that no
5907bbfd9adSNeilBrownlocks (only counted references) are held over this processing due to
5917bbfd9adSNeilBrownthe very real possibility of extended delays.
5927bbfd9adSNeilBrownThis will become more important next time when we examine RCU-walk
5937bbfd9adSNeilBrownwhich is particularly sensitive to delays.
5947bbfd9adSNeilBrown
5957bbfd9adSNeilBrownRCU-walk - faster pathname lookup in Linux
5967bbfd9adSNeilBrown==========================================
5977bbfd9adSNeilBrown
5987bbfd9adSNeilBrownRCU-walk is another algorithm for performing pathname lookup in Linux.
5997bbfd9adSNeilBrownIt is in many ways similar to REF-walk and the two share quite a bit
6007bbfd9adSNeilBrownof code.  The significant difference in RCU-walk is how it allows for
6017bbfd9adSNeilBrownthe possibility of concurrent access.
6027bbfd9adSNeilBrown
6037bbfd9adSNeilBrownWe noted that REF-walk is complex because there are numerous details
6047bbfd9adSNeilBrownand special cases.  RCU-walk reduces this complexity by simply
6057bbfd9adSNeilBrownrefusing to handle a number of cases -- it instead falls back to
6067bbfd9adSNeilBrownREF-walk.  The difficulty with RCU-walk comes from a different
6077bbfd9adSNeilBrowndirection: unfamiliarity.  The locking rules when depending on RCU are
6087bbfd9adSNeilBrownquite different from traditional locking, so we will spend a little extra
6097bbfd9adSNeilBrowntime when we come to those.
6107bbfd9adSNeilBrown
6117bbfd9adSNeilBrownClear demarcation of roles
6127bbfd9adSNeilBrown--------------------------
6137bbfd9adSNeilBrown
6147bbfd9adSNeilBrownThe easiest way to manage concurrency is to forcibly stop any other
6157bbfd9adSNeilBrownthread from changing the data structures that a given thread is
6167bbfd9adSNeilBrownlooking at.  In cases where no other thread would even think of
6177bbfd9adSNeilBrownchanging the data and lots of different threads want to read at the
6187bbfd9adSNeilBrownsame time, this can be very costly.  Even when using locks that permit
6197bbfd9adSNeilBrownmultiple concurrent readers, the simple act of updating the count of
6207bbfd9adSNeilBrownthe number of current readers can impose an unwanted cost.  So the
6217bbfd9adSNeilBrowngoal when reading a shared data structure that no other process is
6227bbfd9adSNeilBrownchanging is to avoid writing anything to memory at all.  Take no
6237bbfd9adSNeilBrownlocks, increment no counts, leave no footprints.
6247bbfd9adSNeilBrown
6257bbfd9adSNeilBrownThe REF-walk mechanism already described certainly doesn't follow this
6267bbfd9adSNeilBrownprinciple, but then it is really designed to work when there may well
6277bbfd9adSNeilBrownbe other threads modifying the data.  RCU-walk, in contrast, is
6287bbfd9adSNeilBrowndesigned for the common situation where there are lots of frequent
6297bbfd9adSNeilBrownreaders and only occasional writers.  This may not be common in all
6307bbfd9adSNeilBrownparts of the filesystem tree, but in many parts it will be.  For the
6317bbfd9adSNeilBrownother parts it is important that RCU-walk can quickly fall back to
6327bbfd9adSNeilBrownusing REF-walk.
6337bbfd9adSNeilBrown
6347bbfd9adSNeilBrownPathname lookup always starts in RCU-walk mode but only remains there
6357bbfd9adSNeilBrownas long as what it is looking for is in the cache and is stable.  It
6367bbfd9adSNeilBrowndances lightly down the cached filesystem image, leaving no footprints
6377bbfd9adSNeilBrownand carefully watching where it is, to be sure it doesn't trip.  If it
6387bbfd9adSNeilBrownnotices that something has changed or is changing, or if something
6397bbfd9adSNeilBrownisn't in the cache, then it tries to stop gracefully and switch to
6407bbfd9adSNeilBrownREF-walk.
6417bbfd9adSNeilBrown
6427bbfd9adSNeilBrownThis stopping requires getting a counted reference on the current
6437bbfd9adSNeilBrown``vfsmount`` and ``dentry``, and ensuring that these are still valid -
6447bbfd9adSNeilBrownthat a path walk with REF-walk would have found the same entries.
6457bbfd9adSNeilBrownThis is an invariant that RCU-walk must guarantee.  It can only make
6467bbfd9adSNeilBrowndecisions, such as selecting the next step, that are decisions which
6477bbfd9adSNeilBrownREF-walk could also have made if it were walking down the tree at the
6487bbfd9adSNeilBrownsame time.  If the graceful stop succeeds, the rest of the path is
6497bbfd9adSNeilBrownprocessed with the reliable, if slightly sluggish, REF-walk.  If
6507bbfd9adSNeilBrownRCU-walk finds it cannot stop gracefully, it simply gives up and
6517bbfd9adSNeilBrownrestarts from the top with REF-walk.
6527bbfd9adSNeilBrown
6537bbfd9adSNeilBrownThis pattern of "try RCU-walk, if that fails try REF-walk" can be
654*8943474aSFox Chenclearly seen in functions like filename_lookup(),
655*8943474aSFox Chenfilename_parentat(),
656*8943474aSFox Chendo_filp_open(), and do_file_open_root().  These four
65734ef75efSFox Chencorrespond roughly to the three ``path_*()`` functions we met earlier,
65887b92d4bSVegard Nossumeach of which calls ``link_path_walk()``.  The ``path_*()`` functions are
6597bbfd9adSNeilBrowncalled using different mode flags until a mode is found which works.
6607bbfd9adSNeilBrownThey are first called with ``LOOKUP_RCU`` set to request "RCU-walk".  If
6617bbfd9adSNeilBrownthat fails with the error ``ECHILD`` they are called again with no
6627bbfd9adSNeilBrownspecial flag to request "REF-walk".  If either of those report the
6637bbfd9adSNeilBrownerror ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no
6647bbfd9adSNeilBrown``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly
6657bbfd9adSNeilBrownrevalidated - normally entries are only revalidated if the filesystem
6667bbfd9adSNeilBrowndetermines that they are too old to trust.
6677bbfd9adSNeilBrown
6687bbfd9adSNeilBrownThe ``LOOKUP_RCU`` attempt may drop that flag internally and switch to
6697bbfd9adSNeilBrownREF-walk, but will never then try to switch back to RCU-walk.  Places
6707bbfd9adSNeilBrownthat trip up RCU-walk are much more likely to be near the leaves and
6717bbfd9adSNeilBrownso it is very unlikely that there will be much, if any, benefit from
6727bbfd9adSNeilBrownswitching back.
6737bbfd9adSNeilBrown
6747bbfd9adSNeilBrownRCU and seqlocks: fast and light
6757bbfd9adSNeilBrown--------------------------------
6767bbfd9adSNeilBrown
6777bbfd9adSNeilBrownRCU is, unsurprisingly, critical to RCU-walk mode.  The
6787bbfd9adSNeilBrown``rcu_read_lock()`` is held for the entire time that RCU-walk is walking
6797bbfd9adSNeilBrowndown a path.  The particular guarantee it provides is that the key
6807bbfd9adSNeilBrowndata structures - dentries, inodes, super_blocks, and mounts - will
6817bbfd9adSNeilBrownnot be freed while the lock is held.  They might be unlinked or
6827bbfd9adSNeilBrowninvalidated in one way or another, but the memory will not be
6837bbfd9adSNeilBrownrepurposed so values in various fields will still be meaningful.  This
6847bbfd9adSNeilBrownis the only guarantee that RCU provides; everything else is done using
6857bbfd9adSNeilBrownseqlocks.
6867bbfd9adSNeilBrown
6877bbfd9adSNeilBrownAs we saw above, REF-walk holds a counted reference to the current
6887bbfd9adSNeilBrowndentry and the current vfsmount, and does not release those references
6897bbfd9adSNeilBrownbefore taking references to the "next" dentry or vfsmount.  It also
6907bbfd9adSNeilBrownsometimes takes the ``d_lock`` spinlock.  These references and locks are
6917bbfd9adSNeilBrowntaken to prevent certain changes from happening.  RCU-walk must not
6927bbfd9adSNeilBrowntake those references or locks and so cannot prevent such changes.
6937bbfd9adSNeilBrownInstead, it checks to see if a change has been made, and aborts or
6947bbfd9adSNeilBrownretries if it has.
6957bbfd9adSNeilBrown
6967bbfd9adSNeilBrownTo preserve the invariant mentioned above (that RCU-walk may only make
6977bbfd9adSNeilBrowndecisions that REF-walk could have made), it must make the checks at
6987bbfd9adSNeilBrownor near the same places that REF-walk holds the references.  So, when
6997bbfd9adSNeilBrownREF-walk increments a reference count or takes a spinlock, RCU-walk
7007bbfd9adSNeilBrownsamples the status of a seqlock using ``read_seqcount_begin()`` or a
7017bbfd9adSNeilBrownsimilar function.  When REF-walk decrements the count or drops the
7027bbfd9adSNeilBrownlock, RCU-walk checks if the sampled status is still valid using
7037bbfd9adSNeilBrown``read_seqcount_retry()`` or similar.
7047bbfd9adSNeilBrown
7057bbfd9adSNeilBrownHowever, there is a little bit more to seqlocks than that.  If
7067bbfd9adSNeilBrownRCU-walk accesses two different fields in a seqlock-protected
7077bbfd9adSNeilBrownstructure, or accesses the same field twice, there is no a priori
7087bbfd9adSNeilBrownguarantee of any consistency between those accesses.  When consistency
7097bbfd9adSNeilBrownis needed - which it usually is - RCU-walk must take a copy and then
7107bbfd9adSNeilBrownuse ``read_seqcount_retry()`` to validate that copy.
7117bbfd9adSNeilBrown
7127bbfd9adSNeilBrown``read_seqcount_retry()`` not only checks the sequence number, but also
7137bbfd9adSNeilBrownimposes a memory barrier so that no memory-read instruction from
7147bbfd9adSNeilBrown*before* the call can be delayed until *after* the call, either by the
7157bbfd9adSNeilBrownCPU or by the compiler.  A simple example of this can be seen in
7167bbfd9adSNeilBrown``slow_dentry_cmp()`` which, for filesystems which do not use simple
7177bbfd9adSNeilBrownbyte-wise name equality, calls into the filesystem to compare a name
7187bbfd9adSNeilBrownagainst a dentry.  The length and name pointer are copied into local
7197bbfd9adSNeilBrownvariables, then ``read_seqcount_retry()`` is called to confirm the two
7207bbfd9adSNeilBrownare consistent, and only then is ``->d_compare()`` called.  When
7217bbfd9adSNeilBrownstandard filename comparison is used, ``dentry_cmp()`` is called
722286b7e24SVegard Nossuminstead.  Notably it does *not* use ``read_seqcount_retry()``, but
7237bbfd9adSNeilBrowninstead has a large comment explaining why the consistency guarantee
7247bbfd9adSNeilBrownisn't necessary.  A subsequent ``read_seqcount_retry()`` will be
7257bbfd9adSNeilBrownsufficient to catch any problem that could occur at this point.
7267bbfd9adSNeilBrown
7277bbfd9adSNeilBrownWith that little refresher on seqlocks out of the way we can look at
7287bbfd9adSNeilBrownthe bigger picture of how RCU-walk uses seqlocks.
7297bbfd9adSNeilBrown
7307bbfd9adSNeilBrown``mount_lock`` and ``nd->m_seq``
7319f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7327bbfd9adSNeilBrown
7337bbfd9adSNeilBrownWe already met the ``mount_lock`` seqlock when REF-walk used it to
7347bbfd9adSNeilBrownensure that crossing a mount point is performed safely.  RCU-walk uses
7357bbfd9adSNeilBrownit for that too, but for quite a bit more.
7367bbfd9adSNeilBrown
7377bbfd9adSNeilBrownInstead of taking a counted reference to each ``vfsmount`` as it
7387bbfd9adSNeilBrowndescends the tree, RCU-walk samples the state of ``mount_lock`` at the
7397bbfd9adSNeilBrownstart of the walk and stores this initial sequence number in the
7407bbfd9adSNeilBrown``struct nameidata`` in the ``m_seq`` field.  This one lock and one
7417bbfd9adSNeilBrownsequence number are used to validate all accesses to all ``vfsmounts``,
7427bbfd9adSNeilBrownand all mount point crossings.  As changes to the mount table are
7437bbfd9adSNeilBrownrelatively rare, it is reasonable to fall back on REF-walk any time
7447bbfd9adSNeilBrownthat any "mount" or "unmount" happens.
7457bbfd9adSNeilBrown
7467bbfd9adSNeilBrown``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk
7477bbfd9adSNeilBrownsequence, whether switching to REF-walk for the rest of the path or
7487bbfd9adSNeilBrownwhen the end of the path is reached.  It is also checked when stepping
7497bbfd9adSNeilBrowndown over a mount point (in ``__follow_mount_rcu()``) or up (in
7507bbfd9adSNeilBrown``follow_dotdot_rcu()``).  If it is ever found to have changed, the
7517bbfd9adSNeilBrownwhole RCU-walk sequence is aborted and the path is processed again by
7527bbfd9adSNeilBrownREF-walk.
7537bbfd9adSNeilBrown
7547bbfd9adSNeilBrownIf RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure
7557bbfd9adSNeilBrownthat, had REF-walk taken counted references on each vfsmount, the
7567bbfd9adSNeilBrownresults would have been the same.  This ensures the invariant holds,
7577bbfd9adSNeilBrownat least for vfsmount structures.
7587bbfd9adSNeilBrown
7597bbfd9adSNeilBrown``dentry->d_seq`` and ``nd->seq``
7609f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7617bbfd9adSNeilBrown
7627bbfd9adSNeilBrownIn place of taking a count or lock on ``d_reflock``, RCU-walk samples
7637bbfd9adSNeilBrownthe per-dentry ``d_seq`` seqlock, and stores the sequence number in the
7647bbfd9adSNeilBrown``seq`` field of the nameidata structure, so ``nd->seq`` should always be
7657bbfd9adSNeilBrownthe current sequence number of ``nd->dentry``.  This number needs to be
7667bbfd9adSNeilBrownrevalidated after copying, and before using, the name, parent, or
7677bbfd9adSNeilBrowninode of the dentry.
7687bbfd9adSNeilBrown
7697bbfd9adSNeilBrownThe handling of the name we have already looked at, and the parent is
7707bbfd9adSNeilBrownonly accessed in ``follow_dotdot_rcu()`` which fairly trivially follows
7717bbfd9adSNeilBrownthe required pattern, though it does so for three different cases.
7727bbfd9adSNeilBrown
7737bbfd9adSNeilBrownWhen not at a mount point, ``d_parent`` is followed and its ``d_seq`` is
7747bbfd9adSNeilBrowncollected.  When we are at a mount point, we instead follow the
7757bbfd9adSNeilBrown``mnt->mnt_mountpoint`` link to get a new dentry and collect its
7767bbfd9adSNeilBrown``d_seq``.  Then, after finally finding a ``d_parent`` to follow, we must
7777bbfd9adSNeilBrowncheck if we have landed on a mount point and, if so, must find that
7787bbfd9adSNeilBrownmount point and follow the ``mnt->mnt_root`` link.  This would imply a
7797bbfd9adSNeilBrownsomewhat unusual, but certainly possible, circumstance where the
7807bbfd9adSNeilBrownstarting point of the path lookup was in part of the filesystem that
7817bbfd9adSNeilBrownwas mounted on, and so not visible from the root.
7827bbfd9adSNeilBrown
7837bbfd9adSNeilBrownThe inode pointer, stored in ``->d_inode``, is a little more
7847bbfd9adSNeilBrowninteresting.  The inode will always need to be accessed at least
7857bbfd9adSNeilBrowntwice, once to determine if it is NULL and once to verify access
7867bbfd9adSNeilBrownpermissions.  Symlink handling requires a validated inode pointer too.
7877bbfd9adSNeilBrownRather than revalidating on each access, a copy is made on the first
7887bbfd9adSNeilBrownaccess and it is stored in the ``inode`` field of ``nameidata`` from where
7897bbfd9adSNeilBrownit can be safely accessed without further validation.
7907bbfd9adSNeilBrown
7917bbfd9adSNeilBrown``lookup_fast()`` is the only lookup routine that is used in RCU-mode,
7927bbfd9adSNeilBrown``lookup_slow()`` being too slow and requiring locks.  It is in
7937bbfd9adSNeilBrown``lookup_fast()`` that we find the important "hand over hand" tracking
7947bbfd9adSNeilBrownof the current dentry.
7957bbfd9adSNeilBrown
7967bbfd9adSNeilBrownThe current ``dentry`` and current ``seq`` number are passed to
7977bbfd9adSNeilBrown``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a
7987bbfd9adSNeilBrownnew ``seq`` number.  ``lookup_fast()`` then copies the inode pointer and
7997bbfd9adSNeilBrownrevalidates the new ``seq`` number.  It then validates the old ``dentry``
8007bbfd9adSNeilBrownwith the old ``seq`` number one last time and only then continues.  This
8017bbfd9adSNeilBrownprocess of getting the ``seq`` number of the new dentry and then
8027bbfd9adSNeilBrownchecking the ``seq`` number of the old exactly mirrors the process of
8037bbfd9adSNeilBrowngetting a counted reference to the new dentry before dropping that for
8047bbfd9adSNeilBrownthe old dentry which we saw in REF-walk.
8057bbfd9adSNeilBrown
8067bbfd9adSNeilBrownNo ``inode->i_rwsem`` or even ``rename_lock``
8079f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8087bbfd9adSNeilBrown
8097bbfd9adSNeilBrownA semaphore is a fairly heavyweight lock that can only be taken when it is
8107bbfd9adSNeilBrownpermissible to sleep.  As ``rcu_read_lock()`` forbids sleeping,
8117bbfd9adSNeilBrown``inode->i_rwsem`` plays no role in RCU-walk.  If some other thread does
8127bbfd9adSNeilBrowntake ``i_rwsem`` and modifies the directory in a way that RCU-walk needs
8137bbfd9adSNeilBrownto notice, the result will be either that RCU-walk fails to find the
8147bbfd9adSNeilBrowndentry that it is looking for, or it will find a dentry which
8157bbfd9adSNeilBrown``read_seqretry()`` won't validate.  In either case it will drop down to
8167bbfd9adSNeilBrownREF-walk mode which can take whatever locks are needed.
8177bbfd9adSNeilBrown
8187bbfd9adSNeilBrownThough ``rename_lock`` could be used by RCU-walk as it doesn't require
8197bbfd9adSNeilBrownany sleeping, RCU-walk doesn't bother.  REF-walk uses ``rename_lock`` to
8207bbfd9adSNeilBrownprotect against the possibility of hash chains in the dcache changing
8217bbfd9adSNeilBrownwhile they are being searched.  This can result in failing to find
8227bbfd9adSNeilBrownsomething that actually is there.  When RCU-walk fails to find
8237bbfd9adSNeilBrownsomething in the dentry cache, whether it is really there or not, it
8247bbfd9adSNeilBrownalready drops down to REF-walk and tries again with appropriate
8257bbfd9adSNeilBrownlocking.  This neatly handles all cases, so adding extra checks on
8267bbfd9adSNeilBrownrename_lock would bring no significant value.
8277bbfd9adSNeilBrown
8287bbfd9adSNeilBrown``unlazy walk()`` and ``complete_walk()``
8299f63df26SRandy Dunlap-----------------------------------------
8307bbfd9adSNeilBrown
8317bbfd9adSNeilBrownThat "dropping down to REF-walk" typically involves a call to
8327bbfd9adSNeilBrown``unlazy_walk()``, so named because "RCU-walk" is also sometimes
8337bbfd9adSNeilBrownreferred to as "lazy walk".  ``unlazy_walk()`` is called when
8347bbfd9adSNeilBrownfollowing the path down to the current vfsmount/dentry pair seems to
8357bbfd9adSNeilBrownhave proceeded successfully, but the next step is problematic.  This
8367bbfd9adSNeilBrowncan happen if the next name cannot be found in the dcache, if
8377bbfd9adSNeilBrownpermission checking or name revalidation couldn't be achieved while
8387bbfd9adSNeilBrownthe ``rcu_read_lock()`` is held (which forbids sleeping), if an
8397bbfd9adSNeilBrownautomount point is found, or in a couple of cases involving symlinks.
8407bbfd9adSNeilBrownIt is also called from ``complete_walk()`` when the lookup has reached
8417bbfd9adSNeilBrownthe final component, or the very end of the path, depending on which
8427bbfd9adSNeilBrownparticular flavor of lookup is used.
8437bbfd9adSNeilBrown
8447bbfd9adSNeilBrownOther reasons for dropping out of RCU-walk that do not trigger a call
8457bbfd9adSNeilBrownto ``unlazy_walk()`` are when some inconsistency is found that cannot be
8467bbfd9adSNeilBrownhandled immediately, such as ``mount_lock`` or one of the ``d_seq``
8477bbfd9adSNeilBrownseqlocks reporting a change.  In these cases the relevant function
8487bbfd9adSNeilBrownwill return ``-ECHILD`` which will percolate up until it triggers a new
8497bbfd9adSNeilBrownattempt from the top using REF-walk.
8507bbfd9adSNeilBrown
8517bbfd9adSNeilBrownFor those cases where ``unlazy_walk()`` is an option, it essentially
8527bbfd9adSNeilBrowntakes a reference on each of the pointers that it holds (vfsmount,
8537bbfd9adSNeilBrowndentry, and possibly some symbolic links) and then verifies that the
8547bbfd9adSNeilBrownrelevant seqlocks have not been changed.  If there have been changes,
8557bbfd9adSNeilBrownit, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk
8567bbfd9adSNeilBrownhas been a success and the lookup process continues.
8577bbfd9adSNeilBrown
8587bbfd9adSNeilBrownTaking a reference on those pointers is not quite as simple as just
8597bbfd9adSNeilBrownincrementing a counter.  That works to take a second reference if you
8607bbfd9adSNeilBrownalready have one (often indirectly through another object), but it
8617bbfd9adSNeilBrownisn't sufficient if you don't actually have a counted reference at
8627bbfd9adSNeilBrownall.  For ``dentry->d_lockref``, it is safe to increment the reference
8637bbfd9adSNeilBrowncounter to get a reference unless it has been explicitly marked as
8647bbfd9adSNeilBrown"dead" which involves setting the counter to ``-128``.
8657bbfd9adSNeilBrown``lockref_get_not_dead()`` achieves this.
8667bbfd9adSNeilBrown
8677bbfd9adSNeilBrownFor ``mnt->mnt_count`` it is safe to take a reference as long as
8687bbfd9adSNeilBrown``mount_lock`` is then used to validate the reference.  If that
8697bbfd9adSNeilBrownvalidation fails, it may *not* be safe to just drop that reference in
8707bbfd9adSNeilBrownthe standard way of calling ``mnt_put()`` - an unmount may have
8717bbfd9adSNeilBrownprogressed too far.  So the code in ``legitimize_mnt()``, when it
8727bbfd9adSNeilBrownfinds that the reference it got might not be safe, checks the
8737bbfd9adSNeilBrown``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is
8747bbfd9adSNeilBrowncorrect, or if it should just decrement the count and pretend none of
8757bbfd9adSNeilBrownthis ever happened.
8767bbfd9adSNeilBrown
8777bbfd9adSNeilBrownTaking care in filesystems
8787bbfd9adSNeilBrown--------------------------
8797bbfd9adSNeilBrown
8807bbfd9adSNeilBrownRCU-walk depends almost entirely on cached information and often will
8817bbfd9adSNeilBrownnot call into the filesystem at all.  However there are two places,
8827bbfd9adSNeilBrownbesides the already-mentioned component-name comparison, where the
8837bbfd9adSNeilBrownfile system might be included in RCU-walk, and it must know to be
8847bbfd9adSNeilBrowncareful.
8857bbfd9adSNeilBrown
8867bbfd9adSNeilBrownIf the filesystem has non-standard permission-checking requirements -
8877bbfd9adSNeilBrownsuch as a networked filesystem which may need to check with the server
8887bbfd9adSNeilBrown- the ``i_op->permission`` interface might be called during RCU-walk.
8897bbfd9adSNeilBrownIn this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it
8907bbfd9adSNeilBrownknows not to sleep, but to return ``-ECHILD`` if it cannot complete
8917bbfd9adSNeilBrownpromptly.  ``i_op->permission`` is given the inode pointer, not the
8927bbfd9adSNeilBrowndentry, so it doesn't need to worry about further consistency checks.
8937bbfd9adSNeilBrownHowever if it accesses any other filesystem data structures, it must
8947bbfd9adSNeilBrownensure they are safe to be accessed with only the ``rcu_read_lock()``
8957bbfd9adSNeilBrownheld.  This typically means they must be freed using ``kfree_rcu()`` or
8967bbfd9adSNeilBrownsimilar.
8977bbfd9adSNeilBrown
8987bbfd9adSNeilBrown.. _READ_ONCE: https://lwn.net/Articles/624126/
8997bbfd9adSNeilBrown
9007bbfd9adSNeilBrownIf the filesystem may need to revalidate dcache entries, then
9017bbfd9adSNeilBrown``d_op->d_revalidate`` may be called in RCU-walk too.  This interface
9027bbfd9adSNeilBrown*is* passed the dentry but does not have access to the ``inode`` or the
9037bbfd9adSNeilBrown``seq`` number from the ``nameidata``, so it needs to be extra careful
9047bbfd9adSNeilBrownwhen accessing fields in the dentry.  This "extra care" typically
9057bbfd9adSNeilBrowninvolves using  `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the
9067bbfd9adSNeilBrownresult is not NULL before using it.  This pattern can be seen in
9077bbfd9adSNeilBrown``nfs_lookup_revalidate()``.
9087bbfd9adSNeilBrown
9097bbfd9adSNeilBrownA pair of patterns
9107bbfd9adSNeilBrown------------------
9117bbfd9adSNeilBrown
9127bbfd9adSNeilBrownIn various places in the details of REF-walk and RCU-walk, and also in
9137bbfd9adSNeilBrownthe big picture, there are a couple of related patterns that are worth
9147bbfd9adSNeilBrownbeing aware of.
9157bbfd9adSNeilBrown
9167bbfd9adSNeilBrownThe first is "try quickly and check, if that fails try slowly".  We
9177bbfd9adSNeilBrowncan see that in the high-level approach of first trying RCU-walk and
9187bbfd9adSNeilBrownthen trying REF-walk, and in places where ``unlazy_walk()`` is used to
9197bbfd9adSNeilBrownswitch to REF-walk for the rest of the path.  We also saw it earlier
9207bbfd9adSNeilBrownin ``dget_parent()`` when following a "``..``" link.  It tries a quick way
9217bbfd9adSNeilBrownto get a reference, then falls back to taking locks if needed.
9227bbfd9adSNeilBrown
9237bbfd9adSNeilBrownThe second pattern is "try quickly and check, if that fails try
9247bbfd9adSNeilBrownagain - repeatedly".  This is seen with the use of ``rename_lock`` and
9257bbfd9adSNeilBrown``mount_lock`` in REF-walk.  RCU-walk doesn't make use of this pattern -
9267bbfd9adSNeilBrownif anything goes wrong it is much safer to just abort and try a more
9277bbfd9adSNeilBrownsedate approach.
9287bbfd9adSNeilBrown
9297bbfd9adSNeilBrownThe emphasis here is "try quickly and check".  It should probably be
930286b7e24SVegard Nossum"try quickly *and carefully*, then check".  The fact that checking is
9317bbfd9adSNeilBrownneeded is a reminder that the system is dynamic and only a limited
9327bbfd9adSNeilBrownnumber of things are safe at all.  The most likely cause of errors in
9337bbfd9adSNeilBrownthis whole process is assuming something is safe when in reality it
9347bbfd9adSNeilBrownisn't.  Careful consideration of what exactly guarantees the safety of
9357bbfd9adSNeilBrowneach access is sometimes necessary.
9367bbfd9adSNeilBrown
9377bbfd9adSNeilBrownA walk among the symlinks
9387bbfd9adSNeilBrown=========================
9397bbfd9adSNeilBrown
9407bbfd9adSNeilBrownThere are several basic issues that we will examine to understand the
9417bbfd9adSNeilBrownhandling of symbolic links:  the symlink stack, together with cache
9427bbfd9adSNeilBrownlifetimes, will help us understand the overall recursive handling of
9437bbfd9adSNeilBrownsymlinks and lead to the special care needed for the final component.
9447bbfd9adSNeilBrownThen a consideration of access-time updates and summary of the various
9457bbfd9adSNeilBrownflags controlling lookup will finish the story.
9467bbfd9adSNeilBrown
9477bbfd9adSNeilBrownThe symlink stack
9487bbfd9adSNeilBrown-----------------
9497bbfd9adSNeilBrown
9507bbfd9adSNeilBrownThere are only two sorts of filesystem objects that can usefully
9517bbfd9adSNeilBrownappear in a path prior to the final component: directories and symlinks.
9527bbfd9adSNeilBrownHandling directories is quite straightforward: the new directory
9537bbfd9adSNeilBrownsimply becomes the starting point at which to interpret the next
9547bbfd9adSNeilBrowncomponent on the path.  Handling symbolic links requires a bit more
9557bbfd9adSNeilBrownwork.
9567bbfd9adSNeilBrown
9577bbfd9adSNeilBrownConceptually, symbolic links could be handled by editing the path.  If
9587bbfd9adSNeilBrowna component name refers to a symbolic link, then that component is
9597bbfd9adSNeilBrownreplaced by the body of the link and, if that body starts with a '/',
9607bbfd9adSNeilBrownthen all preceding parts of the path are discarded.  This is what the
9617bbfd9adSNeilBrown"``readlink -f``" command does, though it also edits out "``.``" and
9627bbfd9adSNeilBrown"``..``" components.
9637bbfd9adSNeilBrown
9647bbfd9adSNeilBrownDirectly editing the path string is not really necessary when looking
9657bbfd9adSNeilBrownup a path, and discarding early components is pointless as they aren't
9667bbfd9adSNeilBrownlooked at anyway.  Keeping track of all remaining components is
9677bbfd9adSNeilBrownimportant, but they can of course be kept separately; there is no need
9687bbfd9adSNeilBrownto concatenate them.  As one symlink may easily refer to another,
9697bbfd9adSNeilBrownwhich in turn can refer to a third, we may need to keep the remaining
9707bbfd9adSNeilBrowncomponents of several paths, each to be processed when the preceding
9717bbfd9adSNeilBrownones are completed.  These path remnants are kept on a stack of
9727bbfd9adSNeilBrownlimited size.
9737bbfd9adSNeilBrown
9747bbfd9adSNeilBrownThere are two reasons for placing limits on how many symlinks can
9757bbfd9adSNeilBrownoccur in a single path lookup.  The most obvious is to avoid loops.
9767bbfd9adSNeilBrownIf a symlink referred to itself either directly or through
9777bbfd9adSNeilBrownintermediaries, then following the symlink can never complete
9787bbfd9adSNeilBrownsuccessfully - the error ``ELOOP`` must be returned.  Loops can be
9797bbfd9adSNeilBrowndetected without imposing limits, but limits are the simplest solution
9807bbfd9adSNeilBrownand, given the second reason for restriction, quite sufficient.
9817bbfd9adSNeilBrown
9827bbfd9adSNeilBrown.. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550
9837bbfd9adSNeilBrown
9847bbfd9adSNeilBrownThe second reason was `outlined recently`_ by Linus:
9857bbfd9adSNeilBrown
9867bbfd9adSNeilBrown   Because it's a latency and DoS issue too. We need to react well to
9877bbfd9adSNeilBrown   true loops, but also to "very deep" non-loops. It's not about memory
9887bbfd9adSNeilBrown   use, it's about users triggering unreasonable CPU resources.
9897bbfd9adSNeilBrown
9907bbfd9adSNeilBrownLinux imposes a limit on the length of any pathname: ``PATH_MAX``, which
9917bbfd9adSNeilBrownis 4096.  There are a number of reasons for this limit; not letting the
9927bbfd9adSNeilBrownkernel spend too much time on just one path is one of them.  With
9937bbfd9adSNeilBrownsymbolic links you can effectively generate much longer paths so some
9947bbfd9adSNeilBrownsort of limit is needed for the same reason.  Linux imposes a limit of
995d2d3dd5eSFox Chenat most 40 (MAXSYMLINKS) symlinks in any one path lookup.  It previously imposed
996d2d3dd5eSFox Chena further limit of eight on the maximum depth of recursion, but that was
9977bbfd9adSNeilBrownraised to 40 when a separate stack was implemented, so there is now
9987bbfd9adSNeilBrownjust the one limit.
9997bbfd9adSNeilBrown
10007bbfd9adSNeilBrownThe ``nameidata`` structure that we met in an earlier article contains a
10017bbfd9adSNeilBrownsmall stack that can be used to store the remaining part of up to two
10027bbfd9adSNeilBrownsymlinks.  In many cases this will be sufficient.  If it isn't, a
10037bbfd9adSNeilBrownseparate stack is allocated with room for 40 symlinks.  Pathname
10047bbfd9adSNeilBrownlookup will never exceed that stack as, once the 40th symlink is
10057bbfd9adSNeilBrowndetected, an error is returned.
10067bbfd9adSNeilBrown
10077bbfd9adSNeilBrownIt might seem that the name remnants are all that needs to be stored on
10087bbfd9adSNeilBrownthis stack, but we need a bit more.  To see that, we need to move on to
10097bbfd9adSNeilBrowncache lifetimes.
10107bbfd9adSNeilBrown
10117bbfd9adSNeilBrownStorage and lifetime of cached symlinks
10127bbfd9adSNeilBrown---------------------------------------
10137bbfd9adSNeilBrown
10147bbfd9adSNeilBrownLike other filesystem resources, such as inodes and directory
10157bbfd9adSNeilBrownentries, symlinks are cached by Linux to avoid repeated costly access
10167bbfd9adSNeilBrownto external storage.  It is particularly important for RCU-walk to be
10177bbfd9adSNeilBrownable to find and temporarily hold onto these cached entries, so that
10187bbfd9adSNeilBrownit doesn't need to drop down into REF-walk.
10197bbfd9adSNeilBrown
10207bbfd9adSNeilBrown.. _object-oriented design pattern: https://lwn.net/Articles/446317/
10217bbfd9adSNeilBrown
10227bbfd9adSNeilBrownWhile each filesystem is free to make its own choice, symlinks are
10237bbfd9adSNeilBrowntypically stored in one of two places.  Short symlinks are often
10247bbfd9adSNeilBrownstored directly in the inode.  When a filesystem allocates a ``struct
10257bbfd9adSNeilBrowninode`` it typically allocates extra space to store private data (a
10267bbfd9adSNeilBrowncommon `object-oriented design pattern`_ in the kernel).  This will
10277bbfd9adSNeilBrownsometimes include space for a symlink.  The other common location is
10287bbfd9adSNeilBrownin the page cache, which normally stores the content of files.  The
10297bbfd9adSNeilBrownpathname in a symlink can be seen as the content of that symlink and
10307bbfd9adSNeilBrowncan easily be stored in the page cache just like file content.
10317bbfd9adSNeilBrown
10327bbfd9adSNeilBrownWhen neither of these is suitable, the next most likely scenario is
10337bbfd9adSNeilBrownthat the filesystem will allocate some temporary memory and copy or
10347bbfd9adSNeilBrownconstruct the symlink content into that memory whenever it is needed.
10357bbfd9adSNeilBrown
10367bbfd9adSNeilBrownWhen the symlink is stored in the inode, it has the same lifetime as
10377bbfd9adSNeilBrownthe inode which, itself, is protected by RCU or by a counted reference
10387bbfd9adSNeilBrownon the dentry.  This means that the mechanisms that pathname lookup
10397bbfd9adSNeilBrownuses to access the dcache and icache (inode cache) safely are quite
10407bbfd9adSNeilBrownsufficient for accessing some cached symlinks safely.  In these cases,
10417bbfd9adSNeilBrownthe ``i_link`` pointer in the inode is set to point to wherever the
10427bbfd9adSNeilBrownsymlink is stored and it can be accessed directly whenever needed.
10437bbfd9adSNeilBrown
10447bbfd9adSNeilBrownWhen the symlink is stored in the page cache or elsewhere, the
10457bbfd9adSNeilBrownsituation is not so straightforward.  A reference on a dentry or even
10467bbfd9adSNeilBrownon an inode does not imply any reference on cached pages of that
10477bbfd9adSNeilBrowninode, and even an ``rcu_read_lock()`` is not sufficient to ensure that
10487bbfd9adSNeilBrowna page will not disappear.  So for these symlinks the pathname lookup
10497bbfd9adSNeilBrowncode needs to ask the filesystem to provide a stable reference and,
10507bbfd9adSNeilBrownsignificantly, needs to release that reference when it is finished
10517bbfd9adSNeilBrownwith it.
10527bbfd9adSNeilBrown
10537bbfd9adSNeilBrownTaking a reference to a cache page is often possible even in RCU-walk
10547bbfd9adSNeilBrownmode.  It does require making changes to memory, which is best avoided,
10557bbfd9adSNeilBrownbut that isn't necessarily a big cost and it is better than dropping
10567bbfd9adSNeilBrownout of RCU-walk mode completely.  Even filesystems that allocate
10577bbfd9adSNeilBrownspace to copy the symlink into can use ``GFP_ATOMIC`` to often successfully
10587bbfd9adSNeilBrownallocate memory without the need to drop out of RCU-walk.  If a
10597bbfd9adSNeilBrownfilesystem cannot successfully get a reference in RCU-walk mode, it
10607bbfd9adSNeilBrownmust return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to
10617bbfd9adSNeilBrownREF-walk mode in which the filesystem is allowed to sleep.
10627bbfd9adSNeilBrown
10634a00e4bdSFox ChenThe place for all this to happen is the ``i_op->get_link()`` inode
10644a00e4bdSFox Chenmethod. This is called both in RCU-walk and REF-walk. In RCU-walk the
10654a00e4bdSFox Chen``dentry*`` argument is NULL, ``->get_link()`` can return -ECHILD to drop out of
10664a00e4bdSFox ChenRCU-walk.  Much like the ``i_op->permission()`` method we
10674a00e4bdSFox Chenlooked at previously, ``->get_link()`` would need to be careful that
10687bbfd9adSNeilBrownall the data structures it references are safe to be accessed while
1069671f7335SFox Chenholding no counted reference, only the RCU lock. A callback
1070671f7335SFox Chen``struct delayed_called`` will be passed to ``->get_link()``:
1071671f7335SFox Chenfile systems can set their own put_link function and argument through
1072*8943474aSFox Chenset_delayed_call(). Later on, when VFS wants to put link, it will call
1073*8943474aSFox Chendo_delayed_call() to invoke that callback function with the argument.
10747bbfd9adSNeilBrown
10757bbfd9adSNeilBrownIn order for the reference to each symlink to be dropped when the walk completes,
10767bbfd9adSNeilBrownwhether in RCU-walk or REF-walk, the symlink stack needs to contain,
10777bbfd9adSNeilBrownalong with the path remnants:
10787bbfd9adSNeilBrown
1079671f7335SFox Chen- the ``struct path`` to provide a reference to the previous path
1080671f7335SFox Chen- the ``const char *`` to provide a reference to the to previous name
10817bbfd9adSNeilBrown- the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk
1082671f7335SFox Chen- the ``struct delayed_call`` for later invocation.
10837bbfd9adSNeilBrown
10847bbfd9adSNeilBrownThis means that each entry in the symlink stack needs to hold five
10857bbfd9adSNeilBrownpointers and an integer instead of just one pointer (the path
10867bbfd9adSNeilBrownremnant).  On a 64-bit system, this is about 40 bytes per entry;
10877bbfd9adSNeilBrownwith 40 entries it adds up to 1600 bytes total, which is less than
10887bbfd9adSNeilBrownhalf a page.  So it might seem like a lot, but is by no means
10897bbfd9adSNeilBrownexcessive.
10907bbfd9adSNeilBrown
10917bbfd9adSNeilBrownNote that, in a given stack frame, the path remnant (``name``) is not
10927bbfd9adSNeilBrownpart of the symlink that the other fields refer to.  It is the remnant
10937bbfd9adSNeilBrownto be followed once that symlink has been fully parsed.
10947bbfd9adSNeilBrown
10957bbfd9adSNeilBrownFollowing the symlink
10967bbfd9adSNeilBrown---------------------
10977bbfd9adSNeilBrown
10987bbfd9adSNeilBrownThe main loop in ``link_path_walk()`` iterates seamlessly over all
10997bbfd9adSNeilBrowncomponents in the path and all of the non-final symlinks.  As symlinks
11007bbfd9adSNeilBrownare processed, the ``name`` pointer is adjusted to point to a new
11017bbfd9adSNeilBrownsymlink, or is restored from the stack, so that much of the loop
11027bbfd9adSNeilBrowndoesn't need to notice.  Getting this ``name`` variable on and off the
11037bbfd9adSNeilBrownstack is very straightforward; pushing and popping the references is
11047bbfd9adSNeilBrowna little more complex.
11057bbfd9adSNeilBrown
1106*8943474aSFox ChenWhen a symlink is found, walk_component() calls pick_link() via step_into()
110718edb95aSFox Chenwhich returns the link from the filesystem.
110818edb95aSFox ChenProviding that operation is successful, the old path ``name`` is placed on the
110918edb95aSFox Chenstack, and the new value is used as the ``name`` for a while.  When the end of
11107bbfd9adSNeilBrownthe path is found (i.e. ``*name`` is ``'\0'``) the old ``name`` is restored
11117bbfd9adSNeilBrownoff the stack and path walking continues.
11127bbfd9adSNeilBrown
11137bbfd9adSNeilBrownPushing and popping the reference pointers (inode, cookie, etc.) is more
11147bbfd9adSNeilBrowncomplex in part because of the desire to handle tail recursion.  When
11157bbfd9adSNeilBrownthe last component of a symlink itself points to a symlink, we
11167bbfd9adSNeilBrownwant to pop the symlink-just-completed off the stack before pushing
11177bbfd9adSNeilBrownthe symlink-just-found to avoid leaving empty path remnants that would
11187bbfd9adSNeilBrownjust get in the way.
11197bbfd9adSNeilBrown
11207bbfd9adSNeilBrownIt is most convenient to push the new symlink references onto the
11217bbfd9adSNeilBrownstack in ``walk_component()`` immediately when the symlink is found;
11227bbfd9adSNeilBrown``walk_component()`` is also the last piece of code that needs to look at the
11237bbfd9adSNeilBrownold symlink as it walks that last component.  So it is quite
11247bbfd9adSNeilBrownconvenient for ``walk_component()`` to release the old symlink and pop
11257bbfd9adSNeilBrownthe references just before pushing the reference information for the
1126de9414adSFox Chennew symlink.  It is guided in this by three flags: ``WALK_NOFOLLOW`` which
1127de9414adSFox Chenforbids it from following a symlink if it finds one, ``WALK_MORE``
1128de9414adSFox Chenwhich indicates that it is yet too early to release the
1129de9414adSFox Chencurrent symlink, and ``WALK_TRAILING`` which indicates that it is on the final
1130de9414adSFox Chencomponent of the lookup, so we will check userspace flag ``LOOKUP_FOLLOW`` to
1131de9414adSFox Chendecide whether follow it when it is a symlink and call ``may_follow_link()`` to
1132de9414adSFox Chencheck if we have privilege to follow it.
11337bbfd9adSNeilBrown
11347bbfd9adSNeilBrownSymlinks with no final component
11357bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11367bbfd9adSNeilBrown
11377bbfd9adSNeilBrownA pair of special-case symlinks deserve a little further explanation.
11387bbfd9adSNeilBrownBoth result in a new ``struct path`` (with mount and dentry) being set
1139*8943474aSFox Chenup in the ``nameidata``, and result in pick_link() returning ``NULL``.
11407bbfd9adSNeilBrown
11417bbfd9adSNeilBrownThe more obvious case is a symlink to "``/``".  All symlinks starting
1142*8943474aSFox Chenwith "``/``" are detected in pick_link() which resets the ``nameidata``
11437bbfd9adSNeilBrownto point to the effective filesystem root.  If the symlink only
11447bbfd9adSNeilBrowncontains "``/``" then there is nothing more to do, no components at all,
11457bbfd9adSNeilBrownso ``NULL`` is returned to indicate that the symlink can be released and
11467bbfd9adSNeilBrownthe stack frame discarded.
11477bbfd9adSNeilBrown
11487bbfd9adSNeilBrownThe other case involves things in ``/proc`` that look like symlinks but
1149b55eef87SAleksa Saraiaren't really (and are therefore commonly referred to as "magic-links")::
11507bbfd9adSNeilBrown
11517bbfd9adSNeilBrown     $ ls -l /proc/self/fd/1
11527bbfd9adSNeilBrown     lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4
11537bbfd9adSNeilBrown
11547bbfd9adSNeilBrownEvery open file descriptor in any process is represented in ``/proc`` by
11557bbfd9adSNeilBrownsomething that looks like a symlink.  It is really a reference to the
11567bbfd9adSNeilBrowntarget file, not just the name of it.  When you ``readlink`` these
11577bbfd9adSNeilBrownobjects you get a name that might refer to the same file - unless it
11587bbfd9adSNeilBrownhas been unlinked or mounted over.  When ``walk_component()`` follows
11593c1be84bSFox Chenone of these, the ``->get_link()`` method in "procfs" doesn't return
1160*8943474aSFox Chena string name, but instead calls nd_jump_link() which updates the
11613c1be84bSFox Chen``nameidata`` in place to point to that target.  ``->get_link()`` then
1162*8943474aSFox Chenreturns ``NULL``.  Again there is no final component and pick_link()
11633c1be84bSFox Chenreturns ``NULL``.
11647bbfd9adSNeilBrown
11657bbfd9adSNeilBrownFollowing the symlink in the final component
11667bbfd9adSNeilBrown--------------------------------------------
11677bbfd9adSNeilBrown
11687bbfd9adSNeilBrownAll this leads to ``link_path_walk()`` walking down every component, and
11697bbfd9adSNeilBrownfollowing all symbolic links it finds, until it reaches the final
11707bbfd9adSNeilBrowncomponent.  This is just returned in the ``last`` field of ``nameidata``.
11717bbfd9adSNeilBrownFor some callers, this is all they need; they want to create that
11727bbfd9adSNeilBrown``last`` name if it doesn't exist or give an error if it does.  Other
11737bbfd9adSNeilBrowncallers will want to follow a symlink if one is found, and possibly
11747bbfd9adSNeilBrownapply special handling to the last component of that symlink, rather
11757bbfd9adSNeilBrownthan just the last component of the original file name.  These callers
11767bbfd9adSNeilBrownpotentially need to call ``link_path_walk()`` again and again on
11777bbfd9adSNeilBrownsuccessive symlinks until one is found that doesn't point to another
11787bbfd9adSNeilBrownsymlink.
11797bbfd9adSNeilBrown
1180*8943474aSFox ChenThis case is handled by relevant callers of link_path_walk(), such as
1181*8943474aSFox Chenpath_lookupat(), path_openat() using a loop that calls link_path_walk(),
1182*8943474aSFox Chenand then handles the final component by calling open_last_lookups() or
1183*8943474aSFox Chenlookup_last(). If it is a symlink that needs to be followed,
1184*8943474aSFox Chenopen_last_lookups() or lookup_last() will set things up properly and
118571e0a67dSFox Chenreturn the path so that the loop repeats, calling
1186*8943474aSFox Chenlink_path_walk() again.  This could loop as many as 40 times if the last
118771e0a67dSFox Chencomponent of each symlink is another symlink.
11887bbfd9adSNeilBrown
118971e0a67dSFox ChenOf the various functions that examine the final component,
1190*8943474aSFox Chenopen_last_lookups() is the most interesting as it works in tandem
1191*8943474aSFox Chenwith do_open() for opening a file.  Part of open_last_lookups() runs
1192*8943474aSFox Chenwith ``i_rwsem`` held and this part is in a separate function: lookup_open().
11937bbfd9adSNeilBrown
1194*8943474aSFox ChenExplaining open_last_lookups() and do_open() completely is beyond the scope
119571e0a67dSFox Chenof this article, but a few highlights should help those interested in exploring
119671e0a67dSFox Chenthe code.
11977bbfd9adSNeilBrown
1198*8943474aSFox Chen1. Rather than just finding the target file, do_open() is used after
1199*8943474aSFox Chen   open_last_lookup() to open
12007bbfd9adSNeilBrown   it.  If the file was found in the dcache, then ``vfs_open()`` is used for
12017bbfd9adSNeilBrown   this.  If not, then ``lookup_open()`` will either call ``atomic_open()`` (if
12027bbfd9adSNeilBrown   the filesystem provides it) to combine the final lookup with the open, or
1203ef4aa53fSFox Chen   will perform the separate ``i_op->lookup()`` and ``i_op->create()`` steps
12047bbfd9adSNeilBrown   directly.  In the later case the actual "open" of this newly found or
1205*8943474aSFox Chen   created file will be performed by vfs_open(), just as if the name
12067bbfd9adSNeilBrown   were found in the dcache.
12077bbfd9adSNeilBrown
1208*8943474aSFox Chen2. vfs_open() can fail with ``-EOPENSTALE`` if the cached information
1209ef4aa53fSFox Chen   wasn't quite current enough.  If it's in RCU-walk ``-ECHILD`` will be returned
1210ef4aa53fSFox Chen   otherwise ``-ESTALE`` is returned.  When ``-ESTALE`` is returned, the caller may
1211ef4aa53fSFox Chen   retry with ``LOOKUP_REVAL`` flag set.
12127bbfd9adSNeilBrown
12137bbfd9adSNeilBrown3. An open with O_CREAT **does** follow a symlink in the final component,
12147bbfd9adSNeilBrown   unlike other creation system calls (like ``mkdir``).  So the sequence::
12157bbfd9adSNeilBrown
12167bbfd9adSNeilBrown          ln -s bar /tmp/foo
12177bbfd9adSNeilBrown          echo hello > /tmp/foo
12187bbfd9adSNeilBrown
12197bbfd9adSNeilBrown   will create a file called ``/tmp/bar``.  This is not permitted if
12207bbfd9adSNeilBrown   ``O_EXCL`` is set but otherwise is handled for an O_CREAT open much
1221*8943474aSFox Chen   like for a non-creating open: lookup_last() or open_last_lookup()
1222*8943474aSFox Chen   returns a non ``NULL`` value, and link_path_walk() gets called and the
12237bbfd9adSNeilBrown   open process continues on the symlink that was found.
12247bbfd9adSNeilBrown
12257bbfd9adSNeilBrownUpdating the access time
12267bbfd9adSNeilBrown------------------------
12277bbfd9adSNeilBrown
12287bbfd9adSNeilBrownWe previously said of RCU-walk that it would "take no locks, increment
12297bbfd9adSNeilBrownno counts, leave no footprints."  We have since seen that some
12307bbfd9adSNeilBrown"footprints" can be needed when handling symlinks as a counted
12317bbfd9adSNeilBrownreference (or even a memory allocation) may be needed.  But these
12327bbfd9adSNeilBrownfootprints are best kept to a minimum.
12337bbfd9adSNeilBrown
12347bbfd9adSNeilBrownOne other place where walking down a symlink can involve leaving
12357bbfd9adSNeilBrownfootprints in a way that doesn't affect directories is in updating access times.
12367bbfd9adSNeilBrownIn Unix (and Linux) every filesystem object has a "last accessed
12377bbfd9adSNeilBrowntime", or "``atime``".  Passing through a directory to access a file
12387bbfd9adSNeilBrownwithin is not considered to be an access for the purposes of
12397bbfd9adSNeilBrown``atime``; only listing the contents of a directory can update its ``atime``.
12407bbfd9adSNeilBrownSymlinks are different it seems.  Both reading a symlink (with ``readlink()``)
12417bbfd9adSNeilBrownand looking up a symlink on the way to some other destination can
12427bbfd9adSNeilBrownupdate the atime on that symlink.
12437bbfd9adSNeilBrown
1244c69f22f2SAlexander A. Klimov.. _clearest statement: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08
12457bbfd9adSNeilBrown
12467bbfd9adSNeilBrownIt is not clear why this is the case; POSIX has little to say on the
12477bbfd9adSNeilBrownsubject.  The `clearest statement`_ is that, if a particular implementation
12487bbfd9adSNeilBrownupdates a timestamp in a place not specified by POSIX, this must be
12497bbfd9adSNeilBrowndocumented "except that any changes caused by pathname resolution need
12507bbfd9adSNeilBrownnot be documented".  This seems to imply that POSIX doesn't really
12517bbfd9adSNeilBrowncare about access-time updates during pathname lookup.
12527bbfd9adSNeilBrown
12537bbfd9adSNeilBrown.. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8
12547bbfd9adSNeilBrown
12557bbfd9adSNeilBrownAn examination of history shows that prior to `Linux 1.3.87`_, the ext2
12567bbfd9adSNeilBrownfilesystem, at least, didn't update atime when following a link.
12577bbfd9adSNeilBrownUnfortunately we have no record of why that behavior was changed.
12587bbfd9adSNeilBrown
12597bbfd9adSNeilBrownIn any case, access time must now be updated and that operation can be
12607bbfd9adSNeilBrownquite complex.  Trying to stay in RCU-walk while doing it is best
12617bbfd9adSNeilBrownavoided.  Fortunately it is often permitted to skip the ``atime``
12627bbfd9adSNeilBrownupdate.  Because ``atime`` updates cause performance problems in various
12637bbfd9adSNeilBrownareas, Linux supports the ``relatime`` mount option, which generally
12647bbfd9adSNeilBrownlimits the updates of ``atime`` to once per day on files that aren't
12657bbfd9adSNeilBrownbeing changed (and symlinks never change once created).  Even without
12667bbfd9adSNeilBrown``relatime``, many filesystems record ``atime`` with a one-second
12677bbfd9adSNeilBrowngranularity, so only one update per second is required.
12687bbfd9adSNeilBrown
12697bbfd9adSNeilBrownIt is easy to test if an ``atime`` update is needed while in RCU-walk
12707bbfd9adSNeilBrownmode and, if it isn't, the update can be skipped and RCU-walk mode
12717bbfd9adSNeilBrowncontinues.  Only when an ``atime`` update is actually required does the
12727bbfd9adSNeilBrownpath walk drop down to REF-walk.  All of this is handled in the
12737bbfd9adSNeilBrown``get_link()`` function.
12747bbfd9adSNeilBrown
12757bbfd9adSNeilBrownA few flags
12767bbfd9adSNeilBrown-----------
12777bbfd9adSNeilBrown
12787bbfd9adSNeilBrownA suitable way to wrap up this tour of pathname walking is to list
12797bbfd9adSNeilBrownthe various flags that can be stored in the ``nameidata`` to guide the
12807bbfd9adSNeilBrownlookup process.  Many of these are only meaningful on the final
1281b55eef87SAleksa Saraicomponent, others reflect the current state of the pathname lookup, and some
1282b55eef87SAleksa Saraiapply restrictions to all path components encountered in the path lookup.
1283b55eef87SAleksa Sarai
12847bbfd9adSNeilBrownAnd then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with
12857bbfd9adSNeilBrownthe others.  If this is not set, an empty pathname causes an error
12867bbfd9adSNeilBrownvery early on.  If it is set, empty pathnames are not considered to be
12877bbfd9adSNeilBrownan error.
12887bbfd9adSNeilBrown
12897bbfd9adSNeilBrownGlobal state flags
12907bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~~
12917bbfd9adSNeilBrown
12927bbfd9adSNeilBrownWe have already met two global state flags: ``LOOKUP_RCU`` and
12937bbfd9adSNeilBrown``LOOKUP_REVAL``.  These select between one of three overall approaches
12947bbfd9adSNeilBrownto lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.
12957bbfd9adSNeilBrown
12967bbfd9adSNeilBrown``LOOKUP_PARENT`` indicates that the final component hasn't been reached
12977bbfd9adSNeilBrownyet.  This is primarily used to tell the audit subsystem the full
12987bbfd9adSNeilBrowncontext of a particular access being audited.
12997bbfd9adSNeilBrown
1300bcba1e7dSAl Viro``ND_ROOT_PRESET`` indicates that the ``root`` field in the ``nameidata`` was
13017bbfd9adSNeilBrownprovided by the caller, so it shouldn't be released when it is no
13027bbfd9adSNeilBrownlonger needed.
13037bbfd9adSNeilBrown
1304bcba1e7dSAl Viro``ND_JUMPED`` means that the current dentry was chosen not because
13057bbfd9adSNeilBrownit had the right name but for some other reason.  This happens when
13067bbfd9adSNeilBrownfollowing "``..``", following a symlink to ``/``, crossing a mount point
1307b55eef87SAleksa Saraior accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic
1308b55eef87SAleksa Sarailink"). In this case the filesystem has not been asked to revalidate the
1309b55eef87SAleksa Sarainame (with ``d_revalidate()``).  In such cases the inode may still need
1310b55eef87SAleksa Saraito be revalidated, so ``d_op->d_weak_revalidate()`` is called if
1311bcba1e7dSAl Viro``ND_JUMPED`` is set when the look completes - which may be at the
13127bbfd9adSNeilBrownfinal component or, when creating, unlinking, or renaming, at the penultimate component.
13137bbfd9adSNeilBrown
1314b55eef87SAleksa SaraiResolution-restriction flags
1315b55eef87SAleksa Sarai~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1316b55eef87SAleksa Sarai
1317b55eef87SAleksa SaraiIn order to allow userspace to protect itself against certain race conditions
1318b55eef87SAleksa Saraiand attack scenarios involving changing path components, a series of flags are
1319b55eef87SAleksa Saraiavailable which apply restrictions to all path components encountered during
1320b55eef87SAleksa Saraipath lookup. These flags are exposed through ``openat2()``'s ``resolve`` field.
1321b55eef87SAleksa Sarai
1322b55eef87SAleksa Sarai``LOOKUP_NO_SYMLINKS`` blocks all symlink traversals (including magic-links).
1323b55eef87SAleksa SaraiThis is distinctly different from ``LOOKUP_FOLLOW``, because the latter only
1324b55eef87SAleksa Sarairelates to restricting the following of trailing symlinks.
1325b55eef87SAleksa Sarai
1326b55eef87SAleksa Sarai``LOOKUP_NO_MAGICLINKS`` blocks all magic-link traversals. Filesystems must
1327b55eef87SAleksa Saraiensure that they return errors from ``nd_jump_link()``, because that is how
1328b55eef87SAleksa Sarai``LOOKUP_NO_MAGICLINKS`` and other magic-link restrictions are implemented.
1329b55eef87SAleksa Sarai
1330b55eef87SAleksa Sarai``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` traversals (this includes both
1331b55eef87SAleksa Saraibind-mounts and ordinary mounts). Note that the ``vfsmount`` which contains the
1332b55eef87SAleksa Sarailookup is determined by the first mountpoint the path lookup reaches --
1333b55eef87SAleksa Saraiabsolute paths start with the ``vfsmount`` of ``/``, and relative paths start
1334b55eef87SAleksa Saraiwith the ``dfd``'s ``vfsmount``. Magic-links are only permitted if the
1335b55eef87SAleksa Sarai``vfsmount`` of the path is unchanged.
1336b55eef87SAleksa Sarai
1337b55eef87SAleksa Sarai``LOOKUP_BENEATH`` blocks any path components which resolve outside the
1338b55eef87SAleksa Saraistarting point of the resolution. This is done by blocking ``nd_jump_root()``
1339b55eef87SAleksa Saraias well as blocking ".." if it would jump outside the starting point.
1340b55eef87SAleksa Sarai``rename_lock`` and ``mount_lock`` are used to detect attacks against the
1341b55eef87SAleksa Sarairesolution of "..". Magic-links are also blocked.
1342b55eef87SAleksa Sarai
1343b55eef87SAleksa Sarai``LOOKUP_IN_ROOT`` resolves all path components as though the starting point
13449b123556SRandy Dunlapwere the filesystem root. ``nd_jump_root()`` brings the resolution back to
1345b55eef87SAleksa Saraithe starting point, and ".." at the starting point will act as a no-op. As with
1346b55eef87SAleksa Sarai``LOOKUP_BENEATH``, ``rename_lock`` and ``mount_lock`` are used to detect
1347b55eef87SAleksa Saraiattacks against ".." resolution. Magic-links are also blocked.
1348b55eef87SAleksa Sarai
13497bbfd9adSNeilBrownFinal-component flags
13507bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~~~~~
13517bbfd9adSNeilBrown
13527bbfd9adSNeilBrownSome of these flags are only set when the final component is being
13537bbfd9adSNeilBrownconsidered.  Others are only checked for when considering that final
13547bbfd9adSNeilBrowncomponent.
13557bbfd9adSNeilBrown
13567bbfd9adSNeilBrown``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount
13577bbfd9adSNeilBrownpoint, then the mount is triggered.  Some operations would trigger it
13587bbfd9adSNeilBrownanyway, but operations like ``stat()`` deliberately don't.  ``statfs()``
13597bbfd9adSNeilBrownneeds to trigger the mount but otherwise behaves a lot like ``stat()``, so
13607bbfd9adSNeilBrownit sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of
13617bbfd9adSNeilBrown"``mount --bind``".
13627bbfd9adSNeilBrown
13637bbfd9adSNeilBrown``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for
13647bbfd9adSNeilBrownsymlinks.  Some system calls set or clear it implicitly, while
13657bbfd9adSNeilBrownothers have API flags such as ``AT_SYMLINK_FOLLOW`` and
13667bbfd9adSNeilBrown``UMOUNT_NOFOLLOW`` to control it.  Its effect is similar to
13677bbfd9adSNeilBrown``WALK_GET`` that we already met, but it is used in a different way.
13687bbfd9adSNeilBrown
13697bbfd9adSNeilBrown``LOOKUP_DIRECTORY`` insists that the final component is a directory.
13707bbfd9adSNeilBrownVarious callers set this and it is also set when the final component
13717bbfd9adSNeilBrownis found to be followed by a slash.
13727bbfd9adSNeilBrown
13737bbfd9adSNeilBrownFinally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and
13747bbfd9adSNeilBrown``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made
13757bbfd9adSNeilBrownavailable to the filesystem and particularly the ``->d_revalidate()``
13767bbfd9adSNeilBrownmethod.  A filesystem can choose not to bother revalidating too hard
13777bbfd9adSNeilBrownif it knows that it will be asked to open or create the file soon.
13787bbfd9adSNeilBrownThese flags were previously useful for ``->lookup()`` too but with the
13797bbfd9adSNeilBrownintroduction of ``->atomic_open()`` they are less relevant there.
13807bbfd9adSNeilBrown
13817bbfd9adSNeilBrownEnd of the road
13827bbfd9adSNeilBrown---------------
13837bbfd9adSNeilBrown
13847bbfd9adSNeilBrownDespite its complexity, all this pathname lookup code appears to be
13857bbfd9adSNeilBrownin good shape - various parts are certainly easier to understand now
13867bbfd9adSNeilBrownthan even a couple of releases ago.  But that doesn't mean it is
13877bbfd9adSNeilBrown"finished".   As already mentioned, RCU-walk currently only follows
13887bbfd9adSNeilBrownsymlinks that are stored in the inode so, while it handles many ext4
13897bbfd9adSNeilBrownsymlinks, it doesn't help with NFS, XFS, or Btrfs.  That support
13907bbfd9adSNeilBrownis not likely to be long delayed.
1391