xref: /linux/Documentation/filesystems/path-lookup.rst (revision b55eef872a96738ea9cb35774db5ce9a7d3a648f)
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.
16*b55eef87SAleksa 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
467bbfd9adSNeilBrownfrom some other location specified by a file descriptor given to a
477bbfd9adSNeilBrown"``XXXat``" system call 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
547bbfd9adSNeilBrowngenerally forbidden in POSIX, but some of those "xxx``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
727bbfd9adSNeilBrown.. _POSIX: http://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
797bbfd9adSNeilBrownending in "``/``".  According to POSIX_
807bbfd9adSNeilBrown
817bbfd9adSNeilBrown  A pathname that contains at least one non- &lt;slash> character and
827bbfd9adSNeilBrown  that ends with one or more trailing &lt;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
2327bbfd9adSNeilBrownThe 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
239*b55eef87SAleksa Sarai``rename_lock`` is also used to detect and defend against potential attacks
240*b55eef87SAleksa Saraiagainst ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
241*b55eef87SAleksa Saraithe parent directory is moved outside the root, bypassing the ``path_equal()``
242*b55eef87SAleksa Saraicheck). If ``rename_lock`` is updated during the lookup and the path encounters
243*b55eef87SAleksa Saraia "..", a potential attack occurred and ``handle_dots()`` will bail out with
244*b55eef87SAleksa Sarai``-EAGAIN``.
245*b55eef87SAleksa 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
359*b55eef87SAleksa Sarai``mount_lock`` is also used to detect and defend against potential attacks
360*b55eef87SAleksa Saraiagainst ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
361*b55eef87SAleksa Saraithe parent directory is moved outside the root, bypassing the ``path_equal()``
362*b55eef87SAleksa Saraicheck). If ``mount_lock`` is updated during the lookup and the path encounters
363*b55eef87SAleksa Saraia "..", a potential attack occurred and ``handle_dots()`` will bail out with
364*b55eef87SAleksa Sarai``-EAGAIN``.
365*b55eef87SAleksa 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
3797bbfd9adSNeilBrown.. _First edition Unix: http://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
4017bbfd9adSNeilBrownThis 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
4077bbfd9adSNeilBrownThis is one of ``LAST_NORM``, ``LAST_ROOT``, ``LAST_DOT``, ``LAST_DOTDOT``, or
4087bbfd9adSNeilBrown``LAST_BIND``.  The ``last`` field is only valid if the type is
4097bbfd9adSNeilBrown``LAST_NORM``.  ``LAST_BIND`` is used when following a symlink and no
4107bbfd9adSNeilBrowncomponents of the symlink have been processed yet.  Others should be
4117bbfd9adSNeilBrownfairly self-explanatory.
4127bbfd9adSNeilBrown
4137bbfd9adSNeilBrown``struct path root``
4149f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~
4157bbfd9adSNeilBrown
4167bbfd9adSNeilBrownThis is used to hold a reference to the effective root of the
4177bbfd9adSNeilBrownfilesystem.  Often that reference won't be needed, so this field is
4187bbfd9adSNeilBrownonly assigned the first time it is used, or when a non-standard root
4197bbfd9adSNeilBrownis requested.  Keeping a reference in the ``nameidata`` ensures that
4207bbfd9adSNeilBrownonly one root is in effect for the entire path walk, even if it races
4217bbfd9adSNeilBrownwith a ``chroot()`` system call.
4227bbfd9adSNeilBrown
423*b55eef87SAleksa SaraiIt should be noted that in the case of ``LOOKUP_IN_ROOT`` or
424*b55eef87SAleksa Sarai``LOOKUP_BENEATH``, the effective root becomes the directory file descriptor
425*b55eef87SAleksa Saraipassed to ``openat2()`` (which exposes these ``LOOKUP_`` flags).
426*b55eef87SAleksa Sarai
4277bbfd9adSNeilBrownThe root is needed when either of two conditions holds: (1) either the
4287bbfd9adSNeilBrownpathname or a symbolic link starts with a "'/'", or (2) a "``..``"
4297bbfd9adSNeilBrowncomponent is being handled, since "``..``" from the root must always stay
4307bbfd9adSNeilBrownat the root.  The value used is usually the current root directory of
4317bbfd9adSNeilBrownthe calling process.  An alternate root can be provided as when
4327bbfd9adSNeilBrown``sysctl()`` calls ``file_open_root()``, and when NFSv4 or Btrfs call
4337bbfd9adSNeilBrown``mount_subtree()``.  In each case a pathname is being looked up in a very
4347bbfd9adSNeilBrownspecific part of the filesystem, and the lookup must not be allowed to
4357bbfd9adSNeilBrownescape that subtree.  It works a bit like a local ``chroot()``.
4367bbfd9adSNeilBrown
4377bbfd9adSNeilBrownIgnoring the handling of symbolic links, we can now describe the
4387bbfd9adSNeilBrown"``link_path_walk()``" function, which handles the lookup of everything
4397bbfd9adSNeilBrownexcept the final component as:
4407bbfd9adSNeilBrown
4417bbfd9adSNeilBrown   Given a path (``name``) and a nameidata structure (``nd``), check that the
4427bbfd9adSNeilBrown   current directory has execute permission and then advance ``name``
4437bbfd9adSNeilBrown   over one component while updating ``last_type`` and ``last``.  If that
4447bbfd9adSNeilBrown   was the final component, then return, otherwise call
4457bbfd9adSNeilBrown   ``walk_component()`` and repeat from the top.
4467bbfd9adSNeilBrown
4477bbfd9adSNeilBrown``walk_component()`` is even easier.  If the component is ``LAST_DOTS``,
4487bbfd9adSNeilBrownit calls ``handle_dots()`` which does the necessary locking as already
4497bbfd9adSNeilBrowndescribed.  If it finds a ``LAST_NORM`` component it first calls
4507bbfd9adSNeilBrown"``lookup_fast()``" which only looks in the dcache, but will ask the
4517bbfd9adSNeilBrownfilesystem to revalidate the result if it is that sort of filesystem.
4527bbfd9adSNeilBrownIf that doesn't get a good result, it calls "``lookup_slow()``" which
4537bbfd9adSNeilBrowntakes ``i_rwsem``, rechecks the cache, and then asks the filesystem
4547bbfd9adSNeilBrownto find a definitive answer.  Each of these will call
4557bbfd9adSNeilBrown``follow_managed()`` (as described below) to handle any mount points.
4567bbfd9adSNeilBrown
4577bbfd9adSNeilBrownIn the absence of symbolic links, ``walk_component()`` creates a new
4587bbfd9adSNeilBrown``struct path`` containing a counted reference to the new dentry and a
4597bbfd9adSNeilBrownreference to the new ``vfsmount`` which is only counted if it is
4607bbfd9adSNeilBrowndifferent from the previous ``vfsmount``.  It then calls
4617bbfd9adSNeilBrown``path_to_nameidata()`` to install the new ``struct path`` in the
4627bbfd9adSNeilBrown``struct nameidata`` and drop the unneeded references.
4637bbfd9adSNeilBrown
4647bbfd9adSNeilBrownThis "hand-over-hand" sequencing of getting a reference to the new
4657bbfd9adSNeilBrowndentry before dropping the reference to the previous dentry may
4667bbfd9adSNeilBrownseem obvious, but is worth pointing out so that we will recognize its
4677bbfd9adSNeilBrownanalogue in the "RCU-walk" version.
4687bbfd9adSNeilBrown
4697bbfd9adSNeilBrownHandling the final component
4707bbfd9adSNeilBrown----------------------------
4717bbfd9adSNeilBrown
4727bbfd9adSNeilBrown``link_path_walk()`` only walks as far as setting ``nd->last`` and
4737bbfd9adSNeilBrown``nd->last_type`` to refer to the final component of the path.  It does
4747bbfd9adSNeilBrownnot call ``walk_component()`` that last time.  Handling that final
4757bbfd9adSNeilBrowncomponent remains for the caller to sort out. Those callers are
4767bbfd9adSNeilBrown``path_lookupat()``, ``path_parentat()``, ``path_mountpoint()`` and
4777bbfd9adSNeilBrown``path_openat()`` each of which handles the differing requirements of
4787bbfd9adSNeilBrowndifferent system calls.
4797bbfd9adSNeilBrown
4807bbfd9adSNeilBrown``path_parentat()`` is clearly the simplest - it just wraps a little bit
4817bbfd9adSNeilBrownof housekeeping around ``link_path_walk()`` and returns the parent
4827bbfd9adSNeilBrowndirectory and final component to the caller.  The caller will be either
4837bbfd9adSNeilBrownaiming to create a name (via ``filename_create()``) or remove or rename
4847bbfd9adSNeilBrowna name (in which case ``user_path_parent()`` is used).  They will use
4857bbfd9adSNeilBrown``i_rwsem`` to exclude other changes while they validate and then
4867bbfd9adSNeilBrownperform their operation.
4877bbfd9adSNeilBrown
4887bbfd9adSNeilBrown``path_lookupat()`` is nearly as simple - it is used when an existing
4897bbfd9adSNeilBrownobject is wanted such as by ``stat()`` or ``chmod()``.  It essentially just
4907bbfd9adSNeilBrowncalls ``walk_component()`` on the final component through a call to
4917bbfd9adSNeilBrown``lookup_last()``.  ``path_lookupat()`` returns just the final dentry.
4927bbfd9adSNeilBrown
4937bbfd9adSNeilBrown``path_mountpoint()`` handles the special case of unmounting which must
4947bbfd9adSNeilBrownnot try to revalidate the mounted filesystem.  It effectively
4957bbfd9adSNeilBrowncontains, through a call to ``mountpoint_last()``, an alternate
4967bbfd9adSNeilBrownimplementation of ``lookup_slow()`` which skips that step.  This is
4977bbfd9adSNeilBrownimportant when unmounting a filesystem that is inaccessible, such as
4987bbfd9adSNeilBrownone provided by a dead NFS server.
4997bbfd9adSNeilBrown
5007bbfd9adSNeilBrownFinally ``path_openat()`` is used for the ``open()`` system call; it
5017bbfd9adSNeilBrowncontains, in support functions starting with "``do_last()``", all the
5027bbfd9adSNeilBrowncomplexity needed to handle the different subtleties of O_CREAT (with
5037bbfd9adSNeilBrownor without O_EXCL), final "``/``" characters, and trailing symbolic
5047bbfd9adSNeilBrownlinks.  We will revisit this in the final part of this series, which
5057bbfd9adSNeilBrownfocuses on those symbolic links.  "``do_last()``" will sometimes, but
5067bbfd9adSNeilBrownnot always, take ``i_rwsem``, depending on what it finds.
5077bbfd9adSNeilBrown
5087bbfd9adSNeilBrownEach of these, or the functions which call them, need to be alert to
5097bbfd9adSNeilBrownthe possibility that the final component is not ``LAST_NORM``.  If the
5107bbfd9adSNeilBrowngoal of the lookup is to create something, then any value for
5117bbfd9adSNeilBrown``last_type`` other than ``LAST_NORM`` will result in an error.  For
5127bbfd9adSNeilBrownexample if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller
5137bbfd9adSNeilBrownwon't try to create that name.  They also check for trailing slashes
5147bbfd9adSNeilBrownby testing ``last.name[last.len]``.  If there is any character beyond
5157bbfd9adSNeilBrownthe final component, it must be a trailing slash.
5167bbfd9adSNeilBrown
5177bbfd9adSNeilBrownRevalidation and automounts
5187bbfd9adSNeilBrown---------------------------
5197bbfd9adSNeilBrown
5207bbfd9adSNeilBrownApart from symbolic links, there are only two parts of the "REF-walk"
5217bbfd9adSNeilBrownprocess not yet covered.  One is the handling of stale cache entries
5227bbfd9adSNeilBrownand the other is automounts.
5237bbfd9adSNeilBrown
5247bbfd9adSNeilBrownOn filesystems that require it, the lookup routines will call the
5257bbfd9adSNeilBrown``->d_revalidate()`` dentry method to ensure that the cached information
5267bbfd9adSNeilBrownis current.  This will often confirm validity or update a few details
5277bbfd9adSNeilBrownfrom a server.  In some cases it may find that there has been change
5287bbfd9adSNeilBrownfurther up the path and that something that was thought to be valid
5297bbfd9adSNeilBrownpreviously isn't really.  When this happens the lookup of the whole
5307bbfd9adSNeilBrownpath is aborted and retried with the "``LOOKUP_REVAL``" flag set.  This
5317bbfd9adSNeilBrownforces revalidation to be more thorough.  We will see more details of
5327bbfd9adSNeilBrownthis retry process in the next article.
5337bbfd9adSNeilBrown
5347bbfd9adSNeilBrownAutomount points are locations in the filesystem where an attempt to
5357bbfd9adSNeilBrownlookup a name can trigger changes to how that lookup should be
5367bbfd9adSNeilBrownhandled, in particular by mounting a filesystem there.  These are
5377bbfd9adSNeilBrowncovered in greater detail in autofs.txt in the Linux documentation
5387bbfd9adSNeilBrowntree, but a few notes specifically related to path lookup are in order
5397bbfd9adSNeilBrownhere.
5407bbfd9adSNeilBrown
5417bbfd9adSNeilBrownThe Linux VFS has a concept of "managed" dentries which is reflected
5427bbfd9adSNeilBrownin function names such as "``follow_managed()``".  There are three
5437bbfd9adSNeilBrownpotentially interesting things about these dentries corresponding
5447bbfd9adSNeilBrownto three different flags that might be set in ``dentry->d_flags``:
5457bbfd9adSNeilBrown
5467bbfd9adSNeilBrown``DCACHE_MANAGE_TRANSIT``
5479f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~
5487bbfd9adSNeilBrown
5497bbfd9adSNeilBrownIf this flag has been set, then the filesystem has requested that the
5507bbfd9adSNeilBrown``d_manage()`` dentry operation be called before handling any possible
5517bbfd9adSNeilBrownmount point.  This can perform two particular services:
5527bbfd9adSNeilBrown
5537bbfd9adSNeilBrownIt can block to avoid races.  If an automount point is being
5547bbfd9adSNeilBrownunmounted, the ``d_manage()`` function will usually wait for that
5557bbfd9adSNeilBrownprocess to complete before letting the new lookup proceed and possibly
5567bbfd9adSNeilBrowntrigger a new automount.
5577bbfd9adSNeilBrown
5587bbfd9adSNeilBrownIt can selectively allow only some processes to transit through a
5597bbfd9adSNeilBrownmount point.  When a server process is managing automounts, it may
5607bbfd9adSNeilBrownneed to access a directory without triggering normal automount
5617bbfd9adSNeilBrownprocessing.  That server process can identify itself to the ``autofs``
5627bbfd9adSNeilBrownfilesystem, which will then give it a special pass through
5637bbfd9adSNeilBrown``d_manage()`` by returning ``-EISDIR``.
5647bbfd9adSNeilBrown
5657bbfd9adSNeilBrown``DCACHE_MOUNTED``
5669f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~
5677bbfd9adSNeilBrown
5687bbfd9adSNeilBrownThis flag is set on every dentry that is mounted on.  As Linux
5697bbfd9adSNeilBrownsupports multiple filesystem namespaces, it is possible that the
5707bbfd9adSNeilBrowndentry may not be mounted on in *this* namespace, just in some
5717bbfd9adSNeilBrownother.  So this flag is seen as a hint, not a promise.
5727bbfd9adSNeilBrown
5737bbfd9adSNeilBrownIf this flag is set, and ``d_manage()`` didn't return ``-EISDIR``,
5747bbfd9adSNeilBrown``lookup_mnt()`` is called to examine the mount hash table (honoring the
5757bbfd9adSNeilBrown``mount_lock`` described earlier) and possibly return a new ``vfsmount``
5767bbfd9adSNeilBrownand a new ``dentry`` (both with counted references).
5777bbfd9adSNeilBrown
5787bbfd9adSNeilBrown``DCACHE_NEED_AUTOMOUNT``
5799f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~
5807bbfd9adSNeilBrown
5817bbfd9adSNeilBrownIf ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't
5827bbfd9adSNeilBrownfind a mount point, then this flag causes the ``d_automount()`` dentry
5837bbfd9adSNeilBrownoperation to be called.
5847bbfd9adSNeilBrown
5857bbfd9adSNeilBrownThe ``d_automount()`` operation can be arbitrarily complex and may
5867bbfd9adSNeilBrowncommunicate with server processes etc. but it should ultimately either
5877bbfd9adSNeilBrownreport that there was an error, that there was nothing to mount, or
5887bbfd9adSNeilBrownshould provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``.
5897bbfd9adSNeilBrown
5907bbfd9adSNeilBrownIn the latter case, ``finish_automount()`` will be called to safely
5917bbfd9adSNeilBrowninstall the new mount point into the mount table.
5927bbfd9adSNeilBrown
5937bbfd9adSNeilBrownThere is no new locking of import here and it is important that no
5947bbfd9adSNeilBrownlocks (only counted references) are held over this processing due to
5957bbfd9adSNeilBrownthe very real possibility of extended delays.
5967bbfd9adSNeilBrownThis will become more important next time when we examine RCU-walk
5977bbfd9adSNeilBrownwhich is particularly sensitive to delays.
5987bbfd9adSNeilBrown
5997bbfd9adSNeilBrownRCU-walk - faster pathname lookup in Linux
6007bbfd9adSNeilBrown==========================================
6017bbfd9adSNeilBrown
6027bbfd9adSNeilBrownRCU-walk is another algorithm for performing pathname lookup in Linux.
6037bbfd9adSNeilBrownIt is in many ways similar to REF-walk and the two share quite a bit
6047bbfd9adSNeilBrownof code.  The significant difference in RCU-walk is how it allows for
6057bbfd9adSNeilBrownthe possibility of concurrent access.
6067bbfd9adSNeilBrown
6077bbfd9adSNeilBrownWe noted that REF-walk is complex because there are numerous details
6087bbfd9adSNeilBrownand special cases.  RCU-walk reduces this complexity by simply
6097bbfd9adSNeilBrownrefusing to handle a number of cases -- it instead falls back to
6107bbfd9adSNeilBrownREF-walk.  The difficulty with RCU-walk comes from a different
6117bbfd9adSNeilBrowndirection: unfamiliarity.  The locking rules when depending on RCU are
6127bbfd9adSNeilBrownquite different from traditional locking, so we will spend a little extra
6137bbfd9adSNeilBrowntime when we come to those.
6147bbfd9adSNeilBrown
6157bbfd9adSNeilBrownClear demarcation of roles
6167bbfd9adSNeilBrown--------------------------
6177bbfd9adSNeilBrown
6187bbfd9adSNeilBrownThe easiest way to manage concurrency is to forcibly stop any other
6197bbfd9adSNeilBrownthread from changing the data structures that a given thread is
6207bbfd9adSNeilBrownlooking at.  In cases where no other thread would even think of
6217bbfd9adSNeilBrownchanging the data and lots of different threads want to read at the
6227bbfd9adSNeilBrownsame time, this can be very costly.  Even when using locks that permit
6237bbfd9adSNeilBrownmultiple concurrent readers, the simple act of updating the count of
6247bbfd9adSNeilBrownthe number of current readers can impose an unwanted cost.  So the
6257bbfd9adSNeilBrowngoal when reading a shared data structure that no other process is
6267bbfd9adSNeilBrownchanging is to avoid writing anything to memory at all.  Take no
6277bbfd9adSNeilBrownlocks, increment no counts, leave no footprints.
6287bbfd9adSNeilBrown
6297bbfd9adSNeilBrownThe REF-walk mechanism already described certainly doesn't follow this
6307bbfd9adSNeilBrownprinciple, but then it is really designed to work when there may well
6317bbfd9adSNeilBrownbe other threads modifying the data.  RCU-walk, in contrast, is
6327bbfd9adSNeilBrowndesigned for the common situation where there are lots of frequent
6337bbfd9adSNeilBrownreaders and only occasional writers.  This may not be common in all
6347bbfd9adSNeilBrownparts of the filesystem tree, but in many parts it will be.  For the
6357bbfd9adSNeilBrownother parts it is important that RCU-walk can quickly fall back to
6367bbfd9adSNeilBrownusing REF-walk.
6377bbfd9adSNeilBrown
6387bbfd9adSNeilBrownPathname lookup always starts in RCU-walk mode but only remains there
6397bbfd9adSNeilBrownas long as what it is looking for is in the cache and is stable.  It
6407bbfd9adSNeilBrowndances lightly down the cached filesystem image, leaving no footprints
6417bbfd9adSNeilBrownand carefully watching where it is, to be sure it doesn't trip.  If it
6427bbfd9adSNeilBrownnotices that something has changed or is changing, or if something
6437bbfd9adSNeilBrownisn't in the cache, then it tries to stop gracefully and switch to
6447bbfd9adSNeilBrownREF-walk.
6457bbfd9adSNeilBrown
6467bbfd9adSNeilBrownThis stopping requires getting a counted reference on the current
6477bbfd9adSNeilBrown``vfsmount`` and ``dentry``, and ensuring that these are still valid -
6487bbfd9adSNeilBrownthat a path walk with REF-walk would have found the same entries.
6497bbfd9adSNeilBrownThis is an invariant that RCU-walk must guarantee.  It can only make
6507bbfd9adSNeilBrowndecisions, such as selecting the next step, that are decisions which
6517bbfd9adSNeilBrownREF-walk could also have made if it were walking down the tree at the
6527bbfd9adSNeilBrownsame time.  If the graceful stop succeeds, the rest of the path is
6537bbfd9adSNeilBrownprocessed with the reliable, if slightly sluggish, REF-walk.  If
6547bbfd9adSNeilBrownRCU-walk finds it cannot stop gracefully, it simply gives up and
6557bbfd9adSNeilBrownrestarts from the top with REF-walk.
6567bbfd9adSNeilBrown
6577bbfd9adSNeilBrownThis pattern of "try RCU-walk, if that fails try REF-walk" can be
6587bbfd9adSNeilBrownclearly seen in functions like ``filename_lookup()``,
6597bbfd9adSNeilBrown``filename_parentat()``, ``filename_mountpoint()``,
6607bbfd9adSNeilBrown``do_filp_open()``, and ``do_file_open_root()``.  These five
6617bbfd9adSNeilBrowncorrespond roughly to the four ``path_``* functions we met earlier,
6627bbfd9adSNeilBrowneach of which calls ``link_path_walk()``.  The ``path_*`` functions are
6637bbfd9adSNeilBrowncalled using different mode flags until a mode is found which works.
6647bbfd9adSNeilBrownThey are first called with ``LOOKUP_RCU`` set to request "RCU-walk".  If
6657bbfd9adSNeilBrownthat fails with the error ``ECHILD`` they are called again with no
6667bbfd9adSNeilBrownspecial flag to request "REF-walk".  If either of those report the
6677bbfd9adSNeilBrownerror ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no
6687bbfd9adSNeilBrown``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly
6697bbfd9adSNeilBrownrevalidated - normally entries are only revalidated if the filesystem
6707bbfd9adSNeilBrowndetermines that they are too old to trust.
6717bbfd9adSNeilBrown
6727bbfd9adSNeilBrownThe ``LOOKUP_RCU`` attempt may drop that flag internally and switch to
6737bbfd9adSNeilBrownREF-walk, but will never then try to switch back to RCU-walk.  Places
6747bbfd9adSNeilBrownthat trip up RCU-walk are much more likely to be near the leaves and
6757bbfd9adSNeilBrownso it is very unlikely that there will be much, if any, benefit from
6767bbfd9adSNeilBrownswitching back.
6777bbfd9adSNeilBrown
6787bbfd9adSNeilBrownRCU and seqlocks: fast and light
6797bbfd9adSNeilBrown--------------------------------
6807bbfd9adSNeilBrown
6817bbfd9adSNeilBrownRCU is, unsurprisingly, critical to RCU-walk mode.  The
6827bbfd9adSNeilBrown``rcu_read_lock()`` is held for the entire time that RCU-walk is walking
6837bbfd9adSNeilBrowndown a path.  The particular guarantee it provides is that the key
6847bbfd9adSNeilBrowndata structures - dentries, inodes, super_blocks, and mounts - will
6857bbfd9adSNeilBrownnot be freed while the lock is held.  They might be unlinked or
6867bbfd9adSNeilBrowninvalidated in one way or another, but the memory will not be
6877bbfd9adSNeilBrownrepurposed so values in various fields will still be meaningful.  This
6887bbfd9adSNeilBrownis the only guarantee that RCU provides; everything else is done using
6897bbfd9adSNeilBrownseqlocks.
6907bbfd9adSNeilBrown
6917bbfd9adSNeilBrownAs we saw above, REF-walk holds a counted reference to the current
6927bbfd9adSNeilBrowndentry and the current vfsmount, and does not release those references
6937bbfd9adSNeilBrownbefore taking references to the "next" dentry or vfsmount.  It also
6947bbfd9adSNeilBrownsometimes takes the ``d_lock`` spinlock.  These references and locks are
6957bbfd9adSNeilBrowntaken to prevent certain changes from happening.  RCU-walk must not
6967bbfd9adSNeilBrowntake those references or locks and so cannot prevent such changes.
6977bbfd9adSNeilBrownInstead, it checks to see if a change has been made, and aborts or
6987bbfd9adSNeilBrownretries if it has.
6997bbfd9adSNeilBrown
7007bbfd9adSNeilBrownTo preserve the invariant mentioned above (that RCU-walk may only make
7017bbfd9adSNeilBrowndecisions that REF-walk could have made), it must make the checks at
7027bbfd9adSNeilBrownor near the same places that REF-walk holds the references.  So, when
7037bbfd9adSNeilBrownREF-walk increments a reference count or takes a spinlock, RCU-walk
7047bbfd9adSNeilBrownsamples the status of a seqlock using ``read_seqcount_begin()`` or a
7057bbfd9adSNeilBrownsimilar function.  When REF-walk decrements the count or drops the
7067bbfd9adSNeilBrownlock, RCU-walk checks if the sampled status is still valid using
7077bbfd9adSNeilBrown``read_seqcount_retry()`` or similar.
7087bbfd9adSNeilBrown
7097bbfd9adSNeilBrownHowever, there is a little bit more to seqlocks than that.  If
7107bbfd9adSNeilBrownRCU-walk accesses two different fields in a seqlock-protected
7117bbfd9adSNeilBrownstructure, or accesses the same field twice, there is no a priori
7127bbfd9adSNeilBrownguarantee of any consistency between those accesses.  When consistency
7137bbfd9adSNeilBrownis needed - which it usually is - RCU-walk must take a copy and then
7147bbfd9adSNeilBrownuse ``read_seqcount_retry()`` to validate that copy.
7157bbfd9adSNeilBrown
7167bbfd9adSNeilBrown``read_seqcount_retry()`` not only checks the sequence number, but also
7177bbfd9adSNeilBrownimposes a memory barrier so that no memory-read instruction from
7187bbfd9adSNeilBrown*before* the call can be delayed until *after* the call, either by the
7197bbfd9adSNeilBrownCPU or by the compiler.  A simple example of this can be seen in
7207bbfd9adSNeilBrown``slow_dentry_cmp()`` which, for filesystems which do not use simple
7217bbfd9adSNeilBrownbyte-wise name equality, calls into the filesystem to compare a name
7227bbfd9adSNeilBrownagainst a dentry.  The length and name pointer are copied into local
7237bbfd9adSNeilBrownvariables, then ``read_seqcount_retry()`` is called to confirm the two
7247bbfd9adSNeilBrownare consistent, and only then is ``->d_compare()`` called.  When
7257bbfd9adSNeilBrownstandard filename comparison is used, ``dentry_cmp()`` is called
7267bbfd9adSNeilBrowninstead.  Notably it does _not_ use ``read_seqcount_retry()``, but
7277bbfd9adSNeilBrowninstead has a large comment explaining why the consistency guarantee
7287bbfd9adSNeilBrownisn't necessary.  A subsequent ``read_seqcount_retry()`` will be
7297bbfd9adSNeilBrownsufficient to catch any problem that could occur at this point.
7307bbfd9adSNeilBrown
7317bbfd9adSNeilBrownWith that little refresher on seqlocks out of the way we can look at
7327bbfd9adSNeilBrownthe bigger picture of how RCU-walk uses seqlocks.
7337bbfd9adSNeilBrown
7347bbfd9adSNeilBrown``mount_lock`` and ``nd->m_seq``
7359f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7367bbfd9adSNeilBrown
7377bbfd9adSNeilBrownWe already met the ``mount_lock`` seqlock when REF-walk used it to
7387bbfd9adSNeilBrownensure that crossing a mount point is performed safely.  RCU-walk uses
7397bbfd9adSNeilBrownit for that too, but for quite a bit more.
7407bbfd9adSNeilBrown
7417bbfd9adSNeilBrownInstead of taking a counted reference to each ``vfsmount`` as it
7427bbfd9adSNeilBrowndescends the tree, RCU-walk samples the state of ``mount_lock`` at the
7437bbfd9adSNeilBrownstart of the walk and stores this initial sequence number in the
7447bbfd9adSNeilBrown``struct nameidata`` in the ``m_seq`` field.  This one lock and one
7457bbfd9adSNeilBrownsequence number are used to validate all accesses to all ``vfsmounts``,
7467bbfd9adSNeilBrownand all mount point crossings.  As changes to the mount table are
7477bbfd9adSNeilBrownrelatively rare, it is reasonable to fall back on REF-walk any time
7487bbfd9adSNeilBrownthat any "mount" or "unmount" happens.
7497bbfd9adSNeilBrown
7507bbfd9adSNeilBrown``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk
7517bbfd9adSNeilBrownsequence, whether switching to REF-walk for the rest of the path or
7527bbfd9adSNeilBrownwhen the end of the path is reached.  It is also checked when stepping
7537bbfd9adSNeilBrowndown over a mount point (in ``__follow_mount_rcu()``) or up (in
7547bbfd9adSNeilBrown``follow_dotdot_rcu()``).  If it is ever found to have changed, the
7557bbfd9adSNeilBrownwhole RCU-walk sequence is aborted and the path is processed again by
7567bbfd9adSNeilBrownREF-walk.
7577bbfd9adSNeilBrown
7587bbfd9adSNeilBrownIf RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure
7597bbfd9adSNeilBrownthat, had REF-walk taken counted references on each vfsmount, the
7607bbfd9adSNeilBrownresults would have been the same.  This ensures the invariant holds,
7617bbfd9adSNeilBrownat least for vfsmount structures.
7627bbfd9adSNeilBrown
7637bbfd9adSNeilBrown``dentry->d_seq`` and ``nd->seq``
7649f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7657bbfd9adSNeilBrown
7667bbfd9adSNeilBrownIn place of taking a count or lock on ``d_reflock``, RCU-walk samples
7677bbfd9adSNeilBrownthe per-dentry ``d_seq`` seqlock, and stores the sequence number in the
7687bbfd9adSNeilBrown``seq`` field of the nameidata structure, so ``nd->seq`` should always be
7697bbfd9adSNeilBrownthe current sequence number of ``nd->dentry``.  This number needs to be
7707bbfd9adSNeilBrownrevalidated after copying, and before using, the name, parent, or
7717bbfd9adSNeilBrowninode of the dentry.
7727bbfd9adSNeilBrown
7737bbfd9adSNeilBrownThe handling of the name we have already looked at, and the parent is
7747bbfd9adSNeilBrownonly accessed in ``follow_dotdot_rcu()`` which fairly trivially follows
7757bbfd9adSNeilBrownthe required pattern, though it does so for three different cases.
7767bbfd9adSNeilBrown
7777bbfd9adSNeilBrownWhen not at a mount point, ``d_parent`` is followed and its ``d_seq`` is
7787bbfd9adSNeilBrowncollected.  When we are at a mount point, we instead follow the
7797bbfd9adSNeilBrown``mnt->mnt_mountpoint`` link to get a new dentry and collect its
7807bbfd9adSNeilBrown``d_seq``.  Then, after finally finding a ``d_parent`` to follow, we must
7817bbfd9adSNeilBrowncheck if we have landed on a mount point and, if so, must find that
7827bbfd9adSNeilBrownmount point and follow the ``mnt->mnt_root`` link.  This would imply a
7837bbfd9adSNeilBrownsomewhat unusual, but certainly possible, circumstance where the
7847bbfd9adSNeilBrownstarting point of the path lookup was in part of the filesystem that
7857bbfd9adSNeilBrownwas mounted on, and so not visible from the root.
7867bbfd9adSNeilBrown
7877bbfd9adSNeilBrownThe inode pointer, stored in ``->d_inode``, is a little more
7887bbfd9adSNeilBrowninteresting.  The inode will always need to be accessed at least
7897bbfd9adSNeilBrowntwice, once to determine if it is NULL and once to verify access
7907bbfd9adSNeilBrownpermissions.  Symlink handling requires a validated inode pointer too.
7917bbfd9adSNeilBrownRather than revalidating on each access, a copy is made on the first
7927bbfd9adSNeilBrownaccess and it is stored in the ``inode`` field of ``nameidata`` from where
7937bbfd9adSNeilBrownit can be safely accessed without further validation.
7947bbfd9adSNeilBrown
7957bbfd9adSNeilBrown``lookup_fast()`` is the only lookup routine that is used in RCU-mode,
7967bbfd9adSNeilBrown``lookup_slow()`` being too slow and requiring locks.  It is in
7977bbfd9adSNeilBrown``lookup_fast()`` that we find the important "hand over hand" tracking
7987bbfd9adSNeilBrownof the current dentry.
7997bbfd9adSNeilBrown
8007bbfd9adSNeilBrownThe current ``dentry`` and current ``seq`` number are passed to
8017bbfd9adSNeilBrown``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a
8027bbfd9adSNeilBrownnew ``seq`` number.  ``lookup_fast()`` then copies the inode pointer and
8037bbfd9adSNeilBrownrevalidates the new ``seq`` number.  It then validates the old ``dentry``
8047bbfd9adSNeilBrownwith the old ``seq`` number one last time and only then continues.  This
8057bbfd9adSNeilBrownprocess of getting the ``seq`` number of the new dentry and then
8067bbfd9adSNeilBrownchecking the ``seq`` number of the old exactly mirrors the process of
8077bbfd9adSNeilBrowngetting a counted reference to the new dentry before dropping that for
8087bbfd9adSNeilBrownthe old dentry which we saw in REF-walk.
8097bbfd9adSNeilBrown
8107bbfd9adSNeilBrownNo ``inode->i_rwsem`` or even ``rename_lock``
8119f63df26SRandy Dunlap~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8127bbfd9adSNeilBrown
8137bbfd9adSNeilBrownA semaphore is a fairly heavyweight lock that can only be taken when it is
8147bbfd9adSNeilBrownpermissible to sleep.  As ``rcu_read_lock()`` forbids sleeping,
8157bbfd9adSNeilBrown``inode->i_rwsem`` plays no role in RCU-walk.  If some other thread does
8167bbfd9adSNeilBrowntake ``i_rwsem`` and modifies the directory in a way that RCU-walk needs
8177bbfd9adSNeilBrownto notice, the result will be either that RCU-walk fails to find the
8187bbfd9adSNeilBrowndentry that it is looking for, or it will find a dentry which
8197bbfd9adSNeilBrown``read_seqretry()`` won't validate.  In either case it will drop down to
8207bbfd9adSNeilBrownREF-walk mode which can take whatever locks are needed.
8217bbfd9adSNeilBrown
8227bbfd9adSNeilBrownThough ``rename_lock`` could be used by RCU-walk as it doesn't require
8237bbfd9adSNeilBrownany sleeping, RCU-walk doesn't bother.  REF-walk uses ``rename_lock`` to
8247bbfd9adSNeilBrownprotect against the possibility of hash chains in the dcache changing
8257bbfd9adSNeilBrownwhile they are being searched.  This can result in failing to find
8267bbfd9adSNeilBrownsomething that actually is there.  When RCU-walk fails to find
8277bbfd9adSNeilBrownsomething in the dentry cache, whether it is really there or not, it
8287bbfd9adSNeilBrownalready drops down to REF-walk and tries again with appropriate
8297bbfd9adSNeilBrownlocking.  This neatly handles all cases, so adding extra checks on
8307bbfd9adSNeilBrownrename_lock would bring no significant value.
8317bbfd9adSNeilBrown
8327bbfd9adSNeilBrown``unlazy walk()`` and ``complete_walk()``
8339f63df26SRandy Dunlap-----------------------------------------
8347bbfd9adSNeilBrown
8357bbfd9adSNeilBrownThat "dropping down to REF-walk" typically involves a call to
8367bbfd9adSNeilBrown``unlazy_walk()``, so named because "RCU-walk" is also sometimes
8377bbfd9adSNeilBrownreferred to as "lazy walk".  ``unlazy_walk()`` is called when
8387bbfd9adSNeilBrownfollowing the path down to the current vfsmount/dentry pair seems to
8397bbfd9adSNeilBrownhave proceeded successfully, but the next step is problematic.  This
8407bbfd9adSNeilBrowncan happen if the next name cannot be found in the dcache, if
8417bbfd9adSNeilBrownpermission checking or name revalidation couldn't be achieved while
8427bbfd9adSNeilBrownthe ``rcu_read_lock()`` is held (which forbids sleeping), if an
8437bbfd9adSNeilBrownautomount point is found, or in a couple of cases involving symlinks.
8447bbfd9adSNeilBrownIt is also called from ``complete_walk()`` when the lookup has reached
8457bbfd9adSNeilBrownthe final component, or the very end of the path, depending on which
8467bbfd9adSNeilBrownparticular flavor of lookup is used.
8477bbfd9adSNeilBrown
8487bbfd9adSNeilBrownOther reasons for dropping out of RCU-walk that do not trigger a call
8497bbfd9adSNeilBrownto ``unlazy_walk()`` are when some inconsistency is found that cannot be
8507bbfd9adSNeilBrownhandled immediately, such as ``mount_lock`` or one of the ``d_seq``
8517bbfd9adSNeilBrownseqlocks reporting a change.  In these cases the relevant function
8527bbfd9adSNeilBrownwill return ``-ECHILD`` which will percolate up until it triggers a new
8537bbfd9adSNeilBrownattempt from the top using REF-walk.
8547bbfd9adSNeilBrown
8557bbfd9adSNeilBrownFor those cases where ``unlazy_walk()`` is an option, it essentially
8567bbfd9adSNeilBrowntakes a reference on each of the pointers that it holds (vfsmount,
8577bbfd9adSNeilBrowndentry, and possibly some symbolic links) and then verifies that the
8587bbfd9adSNeilBrownrelevant seqlocks have not been changed.  If there have been changes,
8597bbfd9adSNeilBrownit, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk
8607bbfd9adSNeilBrownhas been a success and the lookup process continues.
8617bbfd9adSNeilBrown
8627bbfd9adSNeilBrownTaking a reference on those pointers is not quite as simple as just
8637bbfd9adSNeilBrownincrementing a counter.  That works to take a second reference if you
8647bbfd9adSNeilBrownalready have one (often indirectly through another object), but it
8657bbfd9adSNeilBrownisn't sufficient if you don't actually have a counted reference at
8667bbfd9adSNeilBrownall.  For ``dentry->d_lockref``, it is safe to increment the reference
8677bbfd9adSNeilBrowncounter to get a reference unless it has been explicitly marked as
8687bbfd9adSNeilBrown"dead" which involves setting the counter to ``-128``.
8697bbfd9adSNeilBrown``lockref_get_not_dead()`` achieves this.
8707bbfd9adSNeilBrown
8717bbfd9adSNeilBrownFor ``mnt->mnt_count`` it is safe to take a reference as long as
8727bbfd9adSNeilBrown``mount_lock`` is then used to validate the reference.  If that
8737bbfd9adSNeilBrownvalidation fails, it may *not* be safe to just drop that reference in
8747bbfd9adSNeilBrownthe standard way of calling ``mnt_put()`` - an unmount may have
8757bbfd9adSNeilBrownprogressed too far.  So the code in ``legitimize_mnt()``, when it
8767bbfd9adSNeilBrownfinds that the reference it got might not be safe, checks the
8777bbfd9adSNeilBrown``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is
8787bbfd9adSNeilBrowncorrect, or if it should just decrement the count and pretend none of
8797bbfd9adSNeilBrownthis ever happened.
8807bbfd9adSNeilBrown
8817bbfd9adSNeilBrownTaking care in filesystems
8827bbfd9adSNeilBrown--------------------------
8837bbfd9adSNeilBrown
8847bbfd9adSNeilBrownRCU-walk depends almost entirely on cached information and often will
8857bbfd9adSNeilBrownnot call into the filesystem at all.  However there are two places,
8867bbfd9adSNeilBrownbesides the already-mentioned component-name comparison, where the
8877bbfd9adSNeilBrownfile system might be included in RCU-walk, and it must know to be
8887bbfd9adSNeilBrowncareful.
8897bbfd9adSNeilBrown
8907bbfd9adSNeilBrownIf the filesystem has non-standard permission-checking requirements -
8917bbfd9adSNeilBrownsuch as a networked filesystem which may need to check with the server
8927bbfd9adSNeilBrown- the ``i_op->permission`` interface might be called during RCU-walk.
8937bbfd9adSNeilBrownIn this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it
8947bbfd9adSNeilBrownknows not to sleep, but to return ``-ECHILD`` if it cannot complete
8957bbfd9adSNeilBrownpromptly.  ``i_op->permission`` is given the inode pointer, not the
8967bbfd9adSNeilBrowndentry, so it doesn't need to worry about further consistency checks.
8977bbfd9adSNeilBrownHowever if it accesses any other filesystem data structures, it must
8987bbfd9adSNeilBrownensure they are safe to be accessed with only the ``rcu_read_lock()``
8997bbfd9adSNeilBrownheld.  This typically means they must be freed using ``kfree_rcu()`` or
9007bbfd9adSNeilBrownsimilar.
9017bbfd9adSNeilBrown
9027bbfd9adSNeilBrown.. _READ_ONCE: https://lwn.net/Articles/624126/
9037bbfd9adSNeilBrown
9047bbfd9adSNeilBrownIf the filesystem may need to revalidate dcache entries, then
9057bbfd9adSNeilBrown``d_op->d_revalidate`` may be called in RCU-walk too.  This interface
9067bbfd9adSNeilBrown*is* passed the dentry but does not have access to the ``inode`` or the
9077bbfd9adSNeilBrown``seq`` number from the ``nameidata``, so it needs to be extra careful
9087bbfd9adSNeilBrownwhen accessing fields in the dentry.  This "extra care" typically
9097bbfd9adSNeilBrowninvolves using  `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the
9107bbfd9adSNeilBrownresult is not NULL before using it.  This pattern can be seen in
9117bbfd9adSNeilBrown``nfs_lookup_revalidate()``.
9127bbfd9adSNeilBrown
9137bbfd9adSNeilBrownA pair of patterns
9147bbfd9adSNeilBrown------------------
9157bbfd9adSNeilBrown
9167bbfd9adSNeilBrownIn various places in the details of REF-walk and RCU-walk, and also in
9177bbfd9adSNeilBrownthe big picture, there are a couple of related patterns that are worth
9187bbfd9adSNeilBrownbeing aware of.
9197bbfd9adSNeilBrown
9207bbfd9adSNeilBrownThe first is "try quickly and check, if that fails try slowly".  We
9217bbfd9adSNeilBrowncan see that in the high-level approach of first trying RCU-walk and
9227bbfd9adSNeilBrownthen trying REF-walk, and in places where ``unlazy_walk()`` is used to
9237bbfd9adSNeilBrownswitch to REF-walk for the rest of the path.  We also saw it earlier
9247bbfd9adSNeilBrownin ``dget_parent()`` when following a "``..``" link.  It tries a quick way
9257bbfd9adSNeilBrownto get a reference, then falls back to taking locks if needed.
9267bbfd9adSNeilBrown
9277bbfd9adSNeilBrownThe second pattern is "try quickly and check, if that fails try
9287bbfd9adSNeilBrownagain - repeatedly".  This is seen with the use of ``rename_lock`` and
9297bbfd9adSNeilBrown``mount_lock`` in REF-walk.  RCU-walk doesn't make use of this pattern -
9307bbfd9adSNeilBrownif anything goes wrong it is much safer to just abort and try a more
9317bbfd9adSNeilBrownsedate approach.
9327bbfd9adSNeilBrown
9337bbfd9adSNeilBrownThe emphasis here is "try quickly and check".  It should probably be
9347bbfd9adSNeilBrown"try quickly _and carefully,_ then check".  The fact that checking is
9357bbfd9adSNeilBrownneeded is a reminder that the system is dynamic and only a limited
9367bbfd9adSNeilBrownnumber of things are safe at all.  The most likely cause of errors in
9377bbfd9adSNeilBrownthis whole process is assuming something is safe when in reality it
9387bbfd9adSNeilBrownisn't.  Careful consideration of what exactly guarantees the safety of
9397bbfd9adSNeilBrowneach access is sometimes necessary.
9407bbfd9adSNeilBrown
9417bbfd9adSNeilBrownA walk among the symlinks
9427bbfd9adSNeilBrown=========================
9437bbfd9adSNeilBrown
9447bbfd9adSNeilBrownThere are several basic issues that we will examine to understand the
9457bbfd9adSNeilBrownhandling of symbolic links:  the symlink stack, together with cache
9467bbfd9adSNeilBrownlifetimes, will help us understand the overall recursive handling of
9477bbfd9adSNeilBrownsymlinks and lead to the special care needed for the final component.
9487bbfd9adSNeilBrownThen a consideration of access-time updates and summary of the various
9497bbfd9adSNeilBrownflags controlling lookup will finish the story.
9507bbfd9adSNeilBrown
9517bbfd9adSNeilBrownThe symlink stack
9527bbfd9adSNeilBrown-----------------
9537bbfd9adSNeilBrown
9547bbfd9adSNeilBrownThere are only two sorts of filesystem objects that can usefully
9557bbfd9adSNeilBrownappear in a path prior to the final component: directories and symlinks.
9567bbfd9adSNeilBrownHandling directories is quite straightforward: the new directory
9577bbfd9adSNeilBrownsimply becomes the starting point at which to interpret the next
9587bbfd9adSNeilBrowncomponent on the path.  Handling symbolic links requires a bit more
9597bbfd9adSNeilBrownwork.
9607bbfd9adSNeilBrown
9617bbfd9adSNeilBrownConceptually, symbolic links could be handled by editing the path.  If
9627bbfd9adSNeilBrowna component name refers to a symbolic link, then that component is
9637bbfd9adSNeilBrownreplaced by the body of the link and, if that body starts with a '/',
9647bbfd9adSNeilBrownthen all preceding parts of the path are discarded.  This is what the
9657bbfd9adSNeilBrown"``readlink -f``" command does, though it also edits out "``.``" and
9667bbfd9adSNeilBrown"``..``" components.
9677bbfd9adSNeilBrown
9687bbfd9adSNeilBrownDirectly editing the path string is not really necessary when looking
9697bbfd9adSNeilBrownup a path, and discarding early components is pointless as they aren't
9707bbfd9adSNeilBrownlooked at anyway.  Keeping track of all remaining components is
9717bbfd9adSNeilBrownimportant, but they can of course be kept separately; there is no need
9727bbfd9adSNeilBrownto concatenate them.  As one symlink may easily refer to another,
9737bbfd9adSNeilBrownwhich in turn can refer to a third, we may need to keep the remaining
9747bbfd9adSNeilBrowncomponents of several paths, each to be processed when the preceding
9757bbfd9adSNeilBrownones are completed.  These path remnants are kept on a stack of
9767bbfd9adSNeilBrownlimited size.
9777bbfd9adSNeilBrown
9787bbfd9adSNeilBrownThere are two reasons for placing limits on how many symlinks can
9797bbfd9adSNeilBrownoccur in a single path lookup.  The most obvious is to avoid loops.
9807bbfd9adSNeilBrownIf a symlink referred to itself either directly or through
9817bbfd9adSNeilBrownintermediaries, then following the symlink can never complete
9827bbfd9adSNeilBrownsuccessfully - the error ``ELOOP`` must be returned.  Loops can be
9837bbfd9adSNeilBrowndetected without imposing limits, but limits are the simplest solution
9847bbfd9adSNeilBrownand, given the second reason for restriction, quite sufficient.
9857bbfd9adSNeilBrown
9867bbfd9adSNeilBrown.. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550
9877bbfd9adSNeilBrown
9887bbfd9adSNeilBrownThe second reason was `outlined recently`_ by Linus:
9897bbfd9adSNeilBrown
9907bbfd9adSNeilBrown   Because it's a latency and DoS issue too. We need to react well to
9917bbfd9adSNeilBrown   true loops, but also to "very deep" non-loops. It's not about memory
9927bbfd9adSNeilBrown   use, it's about users triggering unreasonable CPU resources.
9937bbfd9adSNeilBrown
9947bbfd9adSNeilBrownLinux imposes a limit on the length of any pathname: ``PATH_MAX``, which
9957bbfd9adSNeilBrownis 4096.  There are a number of reasons for this limit; not letting the
9967bbfd9adSNeilBrownkernel spend too much time on just one path is one of them.  With
9977bbfd9adSNeilBrownsymbolic links you can effectively generate much longer paths so some
9987bbfd9adSNeilBrownsort of limit is needed for the same reason.  Linux imposes a limit of
9997bbfd9adSNeilBrownat most 40 symlinks in any one path lookup.  It previously imposed a
10007bbfd9adSNeilBrownfurther limit of eight on the maximum depth of recursion, but that was
10017bbfd9adSNeilBrownraised to 40 when a separate stack was implemented, so there is now
10027bbfd9adSNeilBrownjust the one limit.
10037bbfd9adSNeilBrown
10047bbfd9adSNeilBrownThe ``nameidata`` structure that we met in an earlier article contains a
10057bbfd9adSNeilBrownsmall stack that can be used to store the remaining part of up to two
10067bbfd9adSNeilBrownsymlinks.  In many cases this will be sufficient.  If it isn't, a
10077bbfd9adSNeilBrownseparate stack is allocated with room for 40 symlinks.  Pathname
10087bbfd9adSNeilBrownlookup will never exceed that stack as, once the 40th symlink is
10097bbfd9adSNeilBrowndetected, an error is returned.
10107bbfd9adSNeilBrown
10117bbfd9adSNeilBrownIt might seem that the name remnants are all that needs to be stored on
10127bbfd9adSNeilBrownthis stack, but we need a bit more.  To see that, we need to move on to
10137bbfd9adSNeilBrowncache lifetimes.
10147bbfd9adSNeilBrown
10157bbfd9adSNeilBrownStorage and lifetime of cached symlinks
10167bbfd9adSNeilBrown---------------------------------------
10177bbfd9adSNeilBrown
10187bbfd9adSNeilBrownLike other filesystem resources, such as inodes and directory
10197bbfd9adSNeilBrownentries, symlinks are cached by Linux to avoid repeated costly access
10207bbfd9adSNeilBrownto external storage.  It is particularly important for RCU-walk to be
10217bbfd9adSNeilBrownable to find and temporarily hold onto these cached entries, so that
10227bbfd9adSNeilBrownit doesn't need to drop down into REF-walk.
10237bbfd9adSNeilBrown
10247bbfd9adSNeilBrown.. _object-oriented design pattern: https://lwn.net/Articles/446317/
10257bbfd9adSNeilBrown
10267bbfd9adSNeilBrownWhile each filesystem is free to make its own choice, symlinks are
10277bbfd9adSNeilBrowntypically stored in one of two places.  Short symlinks are often
10287bbfd9adSNeilBrownstored directly in the inode.  When a filesystem allocates a ``struct
10297bbfd9adSNeilBrowninode`` it typically allocates extra space to store private data (a
10307bbfd9adSNeilBrowncommon `object-oriented design pattern`_ in the kernel).  This will
10317bbfd9adSNeilBrownsometimes include space for a symlink.  The other common location is
10327bbfd9adSNeilBrownin the page cache, which normally stores the content of files.  The
10337bbfd9adSNeilBrownpathname in a symlink can be seen as the content of that symlink and
10347bbfd9adSNeilBrowncan easily be stored in the page cache just like file content.
10357bbfd9adSNeilBrown
10367bbfd9adSNeilBrownWhen neither of these is suitable, the next most likely scenario is
10377bbfd9adSNeilBrownthat the filesystem will allocate some temporary memory and copy or
10387bbfd9adSNeilBrownconstruct the symlink content into that memory whenever it is needed.
10397bbfd9adSNeilBrown
10407bbfd9adSNeilBrownWhen the symlink is stored in the inode, it has the same lifetime as
10417bbfd9adSNeilBrownthe inode which, itself, is protected by RCU or by a counted reference
10427bbfd9adSNeilBrownon the dentry.  This means that the mechanisms that pathname lookup
10437bbfd9adSNeilBrownuses to access the dcache and icache (inode cache) safely are quite
10447bbfd9adSNeilBrownsufficient for accessing some cached symlinks safely.  In these cases,
10457bbfd9adSNeilBrownthe ``i_link`` pointer in the inode is set to point to wherever the
10467bbfd9adSNeilBrownsymlink is stored and it can be accessed directly whenever needed.
10477bbfd9adSNeilBrown
10487bbfd9adSNeilBrownWhen the symlink is stored in the page cache or elsewhere, the
10497bbfd9adSNeilBrownsituation is not so straightforward.  A reference on a dentry or even
10507bbfd9adSNeilBrownon an inode does not imply any reference on cached pages of that
10517bbfd9adSNeilBrowninode, and even an ``rcu_read_lock()`` is not sufficient to ensure that
10527bbfd9adSNeilBrowna page will not disappear.  So for these symlinks the pathname lookup
10537bbfd9adSNeilBrowncode needs to ask the filesystem to provide a stable reference and,
10547bbfd9adSNeilBrownsignificantly, needs to release that reference when it is finished
10557bbfd9adSNeilBrownwith it.
10567bbfd9adSNeilBrown
10577bbfd9adSNeilBrownTaking a reference to a cache page is often possible even in RCU-walk
10587bbfd9adSNeilBrownmode.  It does require making changes to memory, which is best avoided,
10597bbfd9adSNeilBrownbut that isn't necessarily a big cost and it is better than dropping
10607bbfd9adSNeilBrownout of RCU-walk mode completely.  Even filesystems that allocate
10617bbfd9adSNeilBrownspace to copy the symlink into can use ``GFP_ATOMIC`` to often successfully
10627bbfd9adSNeilBrownallocate memory without the need to drop out of RCU-walk.  If a
10637bbfd9adSNeilBrownfilesystem cannot successfully get a reference in RCU-walk mode, it
10647bbfd9adSNeilBrownmust return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to
10657bbfd9adSNeilBrownREF-walk mode in which the filesystem is allowed to sleep.
10667bbfd9adSNeilBrown
10677bbfd9adSNeilBrownThe place for all this to happen is the ``i_op->follow_link()`` inode
10687bbfd9adSNeilBrownmethod.  In the present mainline code this is never actually called in
10697bbfd9adSNeilBrownRCU-walk mode as the rewrite is not quite complete.  It is likely that
10707bbfd9adSNeilBrownin a future release this method will be passed an ``inode`` pointer when
10717bbfd9adSNeilBrowncalled in RCU-walk mode so it both (1) knows to be careful, and (2) has the
10727bbfd9adSNeilBrownvalidated pointer.  Much like the ``i_op->permission()`` method we
10737bbfd9adSNeilBrownlooked at previously, ``->follow_link()`` would need to be careful that
10747bbfd9adSNeilBrownall the data structures it references are safe to be accessed while
10757bbfd9adSNeilBrownholding no counted reference, only the RCU lock.  Though getting a
10767bbfd9adSNeilBrownreference with ``->follow_link()`` is not yet done in RCU-walk mode, the
10777bbfd9adSNeilBrowncode is ready to release the reference when that does happen.
10787bbfd9adSNeilBrown
10797bbfd9adSNeilBrownThis need to drop the reference to a symlink adds significant
10807bbfd9adSNeilBrowncomplexity.  It requires a reference to the inode so that the
10817bbfd9adSNeilBrown``i_op->put_link()`` inode operation can be called.  In REF-walk, that
10827bbfd9adSNeilBrownreference is kept implicitly through a reference to the dentry, so
10837bbfd9adSNeilBrownkeeping the ``struct path`` of the symlink is easiest.  For RCU-walk,
10847bbfd9adSNeilBrownthe pointer to the inode is kept separately.  To allow switching from
10857bbfd9adSNeilBrownRCU-walk back to REF-walk in the middle of processing nested symlinks
10867bbfd9adSNeilBrownwe also need the seq number for the dentry so we can confirm that
10877bbfd9adSNeilBrownswitching back was safe.
10887bbfd9adSNeilBrown
10897bbfd9adSNeilBrownFinally, when providing a reference to a symlink, the filesystem also
10907bbfd9adSNeilBrownprovides an opaque "cookie" that must be passed to ``->put_link()`` so that it
10917bbfd9adSNeilBrownknows what to free.  This might be the allocated memory area, or a
10927bbfd9adSNeilBrownpointer to the ``struct page`` in the page cache, or something else
10937bbfd9adSNeilBrowncompletely.  Only the filesystem knows what it is.
10947bbfd9adSNeilBrown
10957bbfd9adSNeilBrownIn order for the reference to each symlink to be dropped when the walk completes,
10967bbfd9adSNeilBrownwhether in RCU-walk or REF-walk, the symlink stack needs to contain,
10977bbfd9adSNeilBrownalong with the path remnants:
10987bbfd9adSNeilBrown
10997bbfd9adSNeilBrown- the ``struct path`` to provide a reference to the inode in REF-walk
11007bbfd9adSNeilBrown- the ``struct inode *`` to provide a reference to the inode in RCU-walk
11017bbfd9adSNeilBrown- the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk
11027bbfd9adSNeilBrown- the ``cookie`` that tells ``->put_path()`` what to put.
11037bbfd9adSNeilBrown
11047bbfd9adSNeilBrownThis means that each entry in the symlink stack needs to hold five
11057bbfd9adSNeilBrownpointers and an integer instead of just one pointer (the path
11067bbfd9adSNeilBrownremnant).  On a 64-bit system, this is about 40 bytes per entry;
11077bbfd9adSNeilBrownwith 40 entries it adds up to 1600 bytes total, which is less than
11087bbfd9adSNeilBrownhalf a page.  So it might seem like a lot, but is by no means
11097bbfd9adSNeilBrownexcessive.
11107bbfd9adSNeilBrown
11117bbfd9adSNeilBrownNote that, in a given stack frame, the path remnant (``name``) is not
11127bbfd9adSNeilBrownpart of the symlink that the other fields refer to.  It is the remnant
11137bbfd9adSNeilBrownto be followed once that symlink has been fully parsed.
11147bbfd9adSNeilBrown
11157bbfd9adSNeilBrownFollowing the symlink
11167bbfd9adSNeilBrown---------------------
11177bbfd9adSNeilBrown
11187bbfd9adSNeilBrownThe main loop in ``link_path_walk()`` iterates seamlessly over all
11197bbfd9adSNeilBrowncomponents in the path and all of the non-final symlinks.  As symlinks
11207bbfd9adSNeilBrownare processed, the ``name`` pointer is adjusted to point to a new
11217bbfd9adSNeilBrownsymlink, or is restored from the stack, so that much of the loop
11227bbfd9adSNeilBrowndoesn't need to notice.  Getting this ``name`` variable on and off the
11237bbfd9adSNeilBrownstack is very straightforward; pushing and popping the references is
11247bbfd9adSNeilBrowna little more complex.
11257bbfd9adSNeilBrown
11267bbfd9adSNeilBrownWhen a symlink is found, ``walk_component()`` returns the value ``1``
11277bbfd9adSNeilBrown(``0`` is returned for any other sort of success, and a negative number
11287bbfd9adSNeilBrownis, as usual, an error indicator).  This causes ``get_link()`` to be
11297bbfd9adSNeilBrowncalled; it then gets the link from the filesystem.  Providing that
11307bbfd9adSNeilBrownoperation is successful, the old path ``name`` is placed on the stack,
11317bbfd9adSNeilBrownand the new value is used as the ``name`` for a while.  When the end of
11327bbfd9adSNeilBrownthe path is found (i.e. ``*name`` is ``'\0'``) the old ``name`` is restored
11337bbfd9adSNeilBrownoff the stack and path walking continues.
11347bbfd9adSNeilBrown
11357bbfd9adSNeilBrownPushing and popping the reference pointers (inode, cookie, etc.) is more
11367bbfd9adSNeilBrowncomplex in part because of the desire to handle tail recursion.  When
11377bbfd9adSNeilBrownthe last component of a symlink itself points to a symlink, we
11387bbfd9adSNeilBrownwant to pop the symlink-just-completed off the stack before pushing
11397bbfd9adSNeilBrownthe symlink-just-found to avoid leaving empty path remnants that would
11407bbfd9adSNeilBrownjust get in the way.
11417bbfd9adSNeilBrown
11427bbfd9adSNeilBrownIt is most convenient to push the new symlink references onto the
11437bbfd9adSNeilBrownstack in ``walk_component()`` immediately when the symlink is found;
11447bbfd9adSNeilBrown``walk_component()`` is also the last piece of code that needs to look at the
11457bbfd9adSNeilBrownold symlink as it walks that last component.  So it is quite
11467bbfd9adSNeilBrownconvenient for ``walk_component()`` to release the old symlink and pop
11477bbfd9adSNeilBrownthe references just before pushing the reference information for the
11487bbfd9adSNeilBrownnew symlink.  It is guided in this by two flags; ``WALK_GET``, which
11497bbfd9adSNeilBrowngives it permission to follow a symlink if it finds one, and
11507bbfd9adSNeilBrown``WALK_PUT``, which tells it to release the current symlink after it has been
11517bbfd9adSNeilBrownfollowed.  ``WALK_PUT`` is tested first, leading to a call to
11527bbfd9adSNeilBrown``put_link()``.  ``WALK_GET`` is tested subsequently (by
11537bbfd9adSNeilBrown``should_follow_link()``) leading to a call to ``pick_link()`` which sets
11547bbfd9adSNeilBrownup the stack frame.
11557bbfd9adSNeilBrown
11567bbfd9adSNeilBrownSymlinks with no final component
11577bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11587bbfd9adSNeilBrown
11597bbfd9adSNeilBrownA pair of special-case symlinks deserve a little further explanation.
11607bbfd9adSNeilBrownBoth result in a new ``struct path`` (with mount and dentry) being set
11617bbfd9adSNeilBrownup in the ``nameidata``, and result in ``get_link()`` returning ``NULL``.
11627bbfd9adSNeilBrown
11637bbfd9adSNeilBrownThe more obvious case is a symlink to "``/``".  All symlinks starting
11647bbfd9adSNeilBrownwith "``/``" are detected in ``get_link()`` which resets the ``nameidata``
11657bbfd9adSNeilBrownto point to the effective filesystem root.  If the symlink only
11667bbfd9adSNeilBrowncontains "``/``" then there is nothing more to do, no components at all,
11677bbfd9adSNeilBrownso ``NULL`` is returned to indicate that the symlink can be released and
11687bbfd9adSNeilBrownthe stack frame discarded.
11697bbfd9adSNeilBrown
11707bbfd9adSNeilBrownThe other case involves things in ``/proc`` that look like symlinks but
1171*b55eef87SAleksa Saraiaren't really (and are therefore commonly referred to as "magic-links")::
11727bbfd9adSNeilBrown
11737bbfd9adSNeilBrown     $ ls -l /proc/self/fd/1
11747bbfd9adSNeilBrown     lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4
11757bbfd9adSNeilBrown
11767bbfd9adSNeilBrownEvery open file descriptor in any process is represented in ``/proc`` by
11777bbfd9adSNeilBrownsomething that looks like a symlink.  It is really a reference to the
11787bbfd9adSNeilBrowntarget file, not just the name of it.  When you ``readlink`` these
11797bbfd9adSNeilBrownobjects you get a name that might refer to the same file - unless it
11807bbfd9adSNeilBrownhas been unlinked or mounted over.  When ``walk_component()`` follows
11817bbfd9adSNeilBrownone of these, the ``->follow_link()`` method in "procfs" doesn't return
11827bbfd9adSNeilBrowna string name, but instead calls ``nd_jump_link()`` which updates the
11837bbfd9adSNeilBrown``nameidata`` in place to point to that target.  ``->follow_link()`` then
11847bbfd9adSNeilBrownreturns ``NULL``.  Again there is no final component and ``get_link()``
11857bbfd9adSNeilBrownreports this by leaving the ``last_type`` field of ``nameidata`` as
11867bbfd9adSNeilBrown``LAST_BIND``.
11877bbfd9adSNeilBrown
11887bbfd9adSNeilBrownFollowing the symlink in the final component
11897bbfd9adSNeilBrown--------------------------------------------
11907bbfd9adSNeilBrown
11917bbfd9adSNeilBrownAll this leads to ``link_path_walk()`` walking down every component, and
11927bbfd9adSNeilBrownfollowing all symbolic links it finds, until it reaches the final
11937bbfd9adSNeilBrowncomponent.  This is just returned in the ``last`` field of ``nameidata``.
11947bbfd9adSNeilBrownFor some callers, this is all they need; they want to create that
11957bbfd9adSNeilBrown``last`` name if it doesn't exist or give an error if it does.  Other
11967bbfd9adSNeilBrowncallers will want to follow a symlink if one is found, and possibly
11977bbfd9adSNeilBrownapply special handling to the last component of that symlink, rather
11987bbfd9adSNeilBrownthan just the last component of the original file name.  These callers
11997bbfd9adSNeilBrownpotentially need to call ``link_path_walk()`` again and again on
12007bbfd9adSNeilBrownsuccessive symlinks until one is found that doesn't point to another
12017bbfd9adSNeilBrownsymlink.
12027bbfd9adSNeilBrown
12037bbfd9adSNeilBrownThis case is handled by the relevant caller of ``link_path_walk()``, such as
12047bbfd9adSNeilBrown``path_lookupat()`` using a loop that calls ``link_path_walk()``, and then
12057bbfd9adSNeilBrownhandles the final component.  If the final component is a symlink
12067bbfd9adSNeilBrownthat needs to be followed, then ``trailing_symlink()`` is called to set
12077bbfd9adSNeilBrownthings up properly and the loop repeats, calling ``link_path_walk()``
12087bbfd9adSNeilBrownagain.  This could loop as many as 40 times if the last component of
12097bbfd9adSNeilBrowneach symlink is another symlink.
12107bbfd9adSNeilBrown
12117bbfd9adSNeilBrownThe various functions that examine the final component and possibly
12127bbfd9adSNeilBrownreport that it is a symlink are ``lookup_last()``, ``mountpoint_last()``
12137bbfd9adSNeilBrownand ``do_last()``, each of which use the same convention as
12147bbfd9adSNeilBrown``walk_component()`` of returning ``1`` if a symlink was found that needs
12157bbfd9adSNeilBrownto be followed.
12167bbfd9adSNeilBrown
12177bbfd9adSNeilBrownOf these, ``do_last()`` is the most interesting as it is used for
12187bbfd9adSNeilBrownopening a file.  Part of ``do_last()`` runs with ``i_rwsem`` held and this
12197bbfd9adSNeilBrownpart is in a separate function: ``lookup_open()``.
12207bbfd9adSNeilBrown
12217bbfd9adSNeilBrownExplaining ``do_last()`` completely is beyond the scope of this article,
12227bbfd9adSNeilBrownbut a few highlights should help those interested in exploring the
12237bbfd9adSNeilBrowncode.
12247bbfd9adSNeilBrown
12257bbfd9adSNeilBrown1. Rather than just finding the target file, ``do_last()`` needs to open
12267bbfd9adSNeilBrown   it.  If the file was found in the dcache, then ``vfs_open()`` is used for
12277bbfd9adSNeilBrown   this.  If not, then ``lookup_open()`` will either call ``atomic_open()`` (if
12287bbfd9adSNeilBrown   the filesystem provides it) to combine the final lookup with the open, or
12297bbfd9adSNeilBrown   will perform the separate ``lookup_real()`` and ``vfs_create()`` steps
12307bbfd9adSNeilBrown   directly.  In the later case the actual "open" of this newly found or
12317bbfd9adSNeilBrown   created file will be performed by ``vfs_open()``, just as if the name
12327bbfd9adSNeilBrown   were found in the dcache.
12337bbfd9adSNeilBrown
12347bbfd9adSNeilBrown2. ``vfs_open()`` can fail with ``-EOPENSTALE`` if the cached information
12357bbfd9adSNeilBrown   wasn't quite current enough.  Rather than restarting the lookup from
12367bbfd9adSNeilBrown   the top with ``LOOKUP_REVAL`` set, ``lookup_open()`` is called instead,
12377bbfd9adSNeilBrown   giving the filesystem a chance to resolve small inconsistencies.
12387bbfd9adSNeilBrown   If that doesn't work, only then is the lookup restarted from the top.
12397bbfd9adSNeilBrown
12407bbfd9adSNeilBrown3. An open with O_CREAT **does** follow a symlink in the final component,
12417bbfd9adSNeilBrown   unlike other creation system calls (like ``mkdir``).  So the sequence::
12427bbfd9adSNeilBrown
12437bbfd9adSNeilBrown          ln -s bar /tmp/foo
12447bbfd9adSNeilBrown          echo hello > /tmp/foo
12457bbfd9adSNeilBrown
12467bbfd9adSNeilBrown   will create a file called ``/tmp/bar``.  This is not permitted if
12477bbfd9adSNeilBrown   ``O_EXCL`` is set but otherwise is handled for an O_CREAT open much
12487bbfd9adSNeilBrown   like for a non-creating open: ``should_follow_link()`` returns ``1``, and
12497bbfd9adSNeilBrown   so does ``do_last()`` so that ``trailing_symlink()`` gets called and the
12507bbfd9adSNeilBrown   open process continues on the symlink that was found.
12517bbfd9adSNeilBrown
12527bbfd9adSNeilBrownUpdating the access time
12537bbfd9adSNeilBrown------------------------
12547bbfd9adSNeilBrown
12557bbfd9adSNeilBrownWe previously said of RCU-walk that it would "take no locks, increment
12567bbfd9adSNeilBrownno counts, leave no footprints."  We have since seen that some
12577bbfd9adSNeilBrown"footprints" can be needed when handling symlinks as a counted
12587bbfd9adSNeilBrownreference (or even a memory allocation) may be needed.  But these
12597bbfd9adSNeilBrownfootprints are best kept to a minimum.
12607bbfd9adSNeilBrown
12617bbfd9adSNeilBrownOne other place where walking down a symlink can involve leaving
12627bbfd9adSNeilBrownfootprints in a way that doesn't affect directories is in updating access times.
12637bbfd9adSNeilBrownIn Unix (and Linux) every filesystem object has a "last accessed
12647bbfd9adSNeilBrowntime", or "``atime``".  Passing through a directory to access a file
12657bbfd9adSNeilBrownwithin is not considered to be an access for the purposes of
12667bbfd9adSNeilBrown``atime``; only listing the contents of a directory can update its ``atime``.
12677bbfd9adSNeilBrownSymlinks are different it seems.  Both reading a symlink (with ``readlink()``)
12687bbfd9adSNeilBrownand looking up a symlink on the way to some other destination can
12697bbfd9adSNeilBrownupdate the atime on that symlink.
12707bbfd9adSNeilBrown
12717bbfd9adSNeilBrown.. _clearest statement: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08
12727bbfd9adSNeilBrown
12737bbfd9adSNeilBrownIt is not clear why this is the case; POSIX has little to say on the
12747bbfd9adSNeilBrownsubject.  The `clearest statement`_ is that, if a particular implementation
12757bbfd9adSNeilBrownupdates a timestamp in a place not specified by POSIX, this must be
12767bbfd9adSNeilBrowndocumented "except that any changes caused by pathname resolution need
12777bbfd9adSNeilBrownnot be documented".  This seems to imply that POSIX doesn't really
12787bbfd9adSNeilBrowncare about access-time updates during pathname lookup.
12797bbfd9adSNeilBrown
12807bbfd9adSNeilBrown.. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8
12817bbfd9adSNeilBrown
12827bbfd9adSNeilBrownAn examination of history shows that prior to `Linux 1.3.87`_, the ext2
12837bbfd9adSNeilBrownfilesystem, at least, didn't update atime when following a link.
12847bbfd9adSNeilBrownUnfortunately we have no record of why that behavior was changed.
12857bbfd9adSNeilBrown
12867bbfd9adSNeilBrownIn any case, access time must now be updated and that operation can be
12877bbfd9adSNeilBrownquite complex.  Trying to stay in RCU-walk while doing it is best
12887bbfd9adSNeilBrownavoided.  Fortunately it is often permitted to skip the ``atime``
12897bbfd9adSNeilBrownupdate.  Because ``atime`` updates cause performance problems in various
12907bbfd9adSNeilBrownareas, Linux supports the ``relatime`` mount option, which generally
12917bbfd9adSNeilBrownlimits the updates of ``atime`` to once per day on files that aren't
12927bbfd9adSNeilBrownbeing changed (and symlinks never change once created).  Even without
12937bbfd9adSNeilBrown``relatime``, many filesystems record ``atime`` with a one-second
12947bbfd9adSNeilBrowngranularity, so only one update per second is required.
12957bbfd9adSNeilBrown
12967bbfd9adSNeilBrownIt is easy to test if an ``atime`` update is needed while in RCU-walk
12977bbfd9adSNeilBrownmode and, if it isn't, the update can be skipped and RCU-walk mode
12987bbfd9adSNeilBrowncontinues.  Only when an ``atime`` update is actually required does the
12997bbfd9adSNeilBrownpath walk drop down to REF-walk.  All of this is handled in the
13007bbfd9adSNeilBrown``get_link()`` function.
13017bbfd9adSNeilBrown
13027bbfd9adSNeilBrownA few flags
13037bbfd9adSNeilBrown-----------
13047bbfd9adSNeilBrown
13057bbfd9adSNeilBrownA suitable way to wrap up this tour of pathname walking is to list
13067bbfd9adSNeilBrownthe various flags that can be stored in the ``nameidata`` to guide the
13077bbfd9adSNeilBrownlookup process.  Many of these are only meaningful on the final
1308*b55eef87SAleksa Saraicomponent, others reflect the current state of the pathname lookup, and some
1309*b55eef87SAleksa Saraiapply restrictions to all path components encountered in the path lookup.
1310*b55eef87SAleksa Sarai
13117bbfd9adSNeilBrownAnd then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with
13127bbfd9adSNeilBrownthe others.  If this is not set, an empty pathname causes an error
13137bbfd9adSNeilBrownvery early on.  If it is set, empty pathnames are not considered to be
13147bbfd9adSNeilBrownan error.
13157bbfd9adSNeilBrown
13167bbfd9adSNeilBrownGlobal state flags
13177bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~~
13187bbfd9adSNeilBrown
13197bbfd9adSNeilBrownWe have already met two global state flags: ``LOOKUP_RCU`` and
13207bbfd9adSNeilBrown``LOOKUP_REVAL``.  These select between one of three overall approaches
13217bbfd9adSNeilBrownto lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.
13227bbfd9adSNeilBrown
13237bbfd9adSNeilBrown``LOOKUP_PARENT`` indicates that the final component hasn't been reached
13247bbfd9adSNeilBrownyet.  This is primarily used to tell the audit subsystem the full
13257bbfd9adSNeilBrowncontext of a particular access being audited.
13267bbfd9adSNeilBrown
13277bbfd9adSNeilBrown``LOOKUP_ROOT`` indicates that the ``root`` field in the ``nameidata`` was
13287bbfd9adSNeilBrownprovided by the caller, so it shouldn't be released when it is no
13297bbfd9adSNeilBrownlonger needed.
13307bbfd9adSNeilBrown
13317bbfd9adSNeilBrown``LOOKUP_JUMPED`` means that the current dentry was chosen not because
13327bbfd9adSNeilBrownit had the right name but for some other reason.  This happens when
13337bbfd9adSNeilBrownfollowing "``..``", following a symlink to ``/``, crossing a mount point
1334*b55eef87SAleksa Saraior accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic
1335*b55eef87SAleksa Sarailink"). In this case the filesystem has not been asked to revalidate the
1336*b55eef87SAleksa Sarainame (with ``d_revalidate()``).  In such cases the inode may still need
1337*b55eef87SAleksa Saraito be revalidated, so ``d_op->d_weak_revalidate()`` is called if
13387bbfd9adSNeilBrown``LOOKUP_JUMPED`` is set when the look completes - which may be at the
13397bbfd9adSNeilBrownfinal component or, when creating, unlinking, or renaming, at the penultimate component.
13407bbfd9adSNeilBrown
1341*b55eef87SAleksa SaraiResolution-restriction flags
1342*b55eef87SAleksa Sarai~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1343*b55eef87SAleksa Sarai
1344*b55eef87SAleksa SaraiIn order to allow userspace to protect itself against certain race conditions
1345*b55eef87SAleksa Saraiand attack scenarios involving changing path components, a series of flags are
1346*b55eef87SAleksa Saraiavailable which apply restrictions to all path components encountered during
1347*b55eef87SAleksa Saraipath lookup. These flags are exposed through ``openat2()``'s ``resolve`` field.
1348*b55eef87SAleksa Sarai
1349*b55eef87SAleksa Sarai``LOOKUP_NO_SYMLINKS`` blocks all symlink traversals (including magic-links).
1350*b55eef87SAleksa SaraiThis is distinctly different from ``LOOKUP_FOLLOW``, because the latter only
1351*b55eef87SAleksa Sarairelates to restricting the following of trailing symlinks.
1352*b55eef87SAleksa Sarai
1353*b55eef87SAleksa Sarai``LOOKUP_NO_MAGICLINKS`` blocks all magic-link traversals. Filesystems must
1354*b55eef87SAleksa Saraiensure that they return errors from ``nd_jump_link()``, because that is how
1355*b55eef87SAleksa Sarai``LOOKUP_NO_MAGICLINKS`` and other magic-link restrictions are implemented.
1356*b55eef87SAleksa Sarai
1357*b55eef87SAleksa Sarai``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` traversals (this includes both
1358*b55eef87SAleksa Saraibind-mounts and ordinary mounts). Note that the ``vfsmount`` which contains the
1359*b55eef87SAleksa Sarailookup is determined by the first mountpoint the path lookup reaches --
1360*b55eef87SAleksa Saraiabsolute paths start with the ``vfsmount`` of ``/``, and relative paths start
1361*b55eef87SAleksa Saraiwith the ``dfd``'s ``vfsmount``. Magic-links are only permitted if the
1362*b55eef87SAleksa Sarai``vfsmount`` of the path is unchanged.
1363*b55eef87SAleksa Sarai
1364*b55eef87SAleksa Sarai``LOOKUP_BENEATH`` blocks any path components which resolve outside the
1365*b55eef87SAleksa Saraistarting point of the resolution. This is done by blocking ``nd_jump_root()``
1366*b55eef87SAleksa Saraias well as blocking ".." if it would jump outside the starting point.
1367*b55eef87SAleksa Sarai``rename_lock`` and ``mount_lock`` are used to detect attacks against the
1368*b55eef87SAleksa Sarairesolution of "..". Magic-links are also blocked.
1369*b55eef87SAleksa Sarai
1370*b55eef87SAleksa Sarai``LOOKUP_IN_ROOT`` resolves all path components as though the starting point
1371*b55eef87SAleksa Saraiwere the filesystem root. ``nd_jump_root()`` brings the resolution back to to
1372*b55eef87SAleksa Saraithe starting point, and ".." at the starting point will act as a no-op. As with
1373*b55eef87SAleksa Sarai``LOOKUP_BENEATH``, ``rename_lock`` and ``mount_lock`` are used to detect
1374*b55eef87SAleksa Saraiattacks against ".." resolution. Magic-links are also blocked.
1375*b55eef87SAleksa Sarai
13767bbfd9adSNeilBrownFinal-component flags
13777bbfd9adSNeilBrown~~~~~~~~~~~~~~~~~~~~~
13787bbfd9adSNeilBrown
13797bbfd9adSNeilBrownSome of these flags are only set when the final component is being
13807bbfd9adSNeilBrownconsidered.  Others are only checked for when considering that final
13817bbfd9adSNeilBrowncomponent.
13827bbfd9adSNeilBrown
13837bbfd9adSNeilBrown``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount
13847bbfd9adSNeilBrownpoint, then the mount is triggered.  Some operations would trigger it
13857bbfd9adSNeilBrownanyway, but operations like ``stat()`` deliberately don't.  ``statfs()``
13867bbfd9adSNeilBrownneeds to trigger the mount but otherwise behaves a lot like ``stat()``, so
13877bbfd9adSNeilBrownit sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of
13887bbfd9adSNeilBrown"``mount --bind``".
13897bbfd9adSNeilBrown
13907bbfd9adSNeilBrown``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for
13917bbfd9adSNeilBrownsymlinks.  Some system calls set or clear it implicitly, while
13927bbfd9adSNeilBrownothers have API flags such as ``AT_SYMLINK_FOLLOW`` and
13937bbfd9adSNeilBrown``UMOUNT_NOFOLLOW`` to control it.  Its effect is similar to
13947bbfd9adSNeilBrown``WALK_GET`` that we already met, but it is used in a different way.
13957bbfd9adSNeilBrown
13967bbfd9adSNeilBrown``LOOKUP_DIRECTORY`` insists that the final component is a directory.
13977bbfd9adSNeilBrownVarious callers set this and it is also set when the final component
13987bbfd9adSNeilBrownis found to be followed by a slash.
13997bbfd9adSNeilBrown
14007bbfd9adSNeilBrownFinally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and
14017bbfd9adSNeilBrown``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made
14027bbfd9adSNeilBrownavailable to the filesystem and particularly the ``->d_revalidate()``
14037bbfd9adSNeilBrownmethod.  A filesystem can choose not to bother revalidating too hard
14047bbfd9adSNeilBrownif it knows that it will be asked to open or create the file soon.
14057bbfd9adSNeilBrownThese flags were previously useful for ``->lookup()`` too but with the
14067bbfd9adSNeilBrownintroduction of ``->atomic_open()`` they are less relevant there.
14077bbfd9adSNeilBrown
14087bbfd9adSNeilBrownEnd of the road
14097bbfd9adSNeilBrown---------------
14107bbfd9adSNeilBrown
14117bbfd9adSNeilBrownDespite its complexity, all this pathname lookup code appears to be
14127bbfd9adSNeilBrownin good shape - various parts are certainly easier to understand now
14137bbfd9adSNeilBrownthan even a couple of releases ago.  But that doesn't mean it is
14147bbfd9adSNeilBrown"finished".   As already mentioned, RCU-walk currently only follows
14157bbfd9adSNeilBrownsymlinks that are stored in the inode so, while it handles many ext4
14167bbfd9adSNeilBrownsymlinks, it doesn't help with NFS, XFS, or Btrfs.  That support
14177bbfd9adSNeilBrownis not likely to be long delayed.
1418