brintos

brintos / linux-shallow public Read only

0
0
Text · 69.6 KiB · 2b2df6a Raw
1391 lines · plain
1===============2Pathname lookup3===============4 5This write-up is based on three articles published at lwn.net:6 7- <https://lwn.net/Articles/649115/> Pathname lookup in Linux8- <https://lwn.net/Articles/649729/> RCU-walk: faster pathname lookup in Linux9- <https://lwn.net/Articles/650786/> A walk among the symlinks10 11Written by Neil Brown with help from Al Viro and Jon Corbet.12It has subsequently been updated to reflect changes in the kernel13including:14 15- per-directory parallel name lookup.16- ``openat2()`` resolution restriction flags.17 18Introduction to pathname lookup19===============================20 21The most obvious aspect of pathname lookup, which very little22exploration is needed to discover, is that it is complex.  There are23many rules, special cases, and implementation alternatives that all24combine to confuse the unwary reader.  Computer science has long been25acquainted with such complexity and has tools to help manage it.  One26tool that we will make extensive use of is "divide and conquer".  For27the early parts of the analysis we will divide off symlinks - leaving28them until the final part.  Well before we get to symlinks we have29another major division based on the VFS's approach to locking which30will allow us to review "REF-walk" and "RCU-walk" separately.  But we31are getting ahead of ourselves.  There are some important low level32distinctions we need to clarify first.33 34There are two sorts of ...35--------------------------36 37.. _openat: http://man7.org/linux/man-pages/man2/openat.2.html38 39Pathnames (sometimes "file names"), used to identify objects in the40filesystem, will be familiar to most readers.  They contain two sorts41of elements: "slashes" that are sequences of one or more "``/``"42characters, and "components" that are sequences of one or more43non-"``/``" characters.  These form two kinds of paths.  Those that44start with slashes are "absolute" and start from the filesystem root.45The others are "relative" and start from the current directory, or46from some other location specified by a file descriptor given to47"``*at()``" system calls such as `openat() <openat_>`_.48 49.. _execveat: http://man7.org/linux/man-pages/man2/execveat.2.html50 51It is tempting to describe the second kind as starting with a52component, but that isn't always accurate: a pathname can lack both53slashes and components, it can be empty, in other words.  This is54generally forbidden in POSIX, but some of those "``*at()``" system calls55in Linux permit it when the ``AT_EMPTY_PATH`` flag is given.  For56example, if you have an open file descriptor on an executable file you57can execute it by calling `execveat() <execveat_>`_ passing58the file descriptor, an empty path, and the ``AT_EMPTY_PATH`` flag.59 60These paths can be divided into two sections: the final component and61everything else.  The "everything else" is the easy bit.  In all cases62it must identify a directory that already exists, otherwise an error63such as ``ENOENT`` or ``ENOTDIR`` will be reported.64 65The final component is not so simple.  Not only do different system66calls interpret it quite differently (e.g. some create it, some do67not), but it might not even exist: neither the empty pathname nor the68pathname that is just slashes have a final component.  If it does69exist, it could be "``.``" or "``..``" which are handled quite differently70from other components.71 72.. _POSIX: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_1273 74If a pathname ends with a slash, such as "``/tmp/foo/``" it might be75tempting to consider that to have an empty final component.  In many76ways that would lead to correct results, but not always.  In77particular, ``mkdir()`` and ``rmdir()`` each create or remove a directory named78by the final component, and they are required to work with pathnames79ending in "``/``".  According to POSIX_:80 81  A pathname that contains at least one non-<slash> character and82  that ends with one or more trailing <slash> characters shall not83  be resolved successfully unless the last pathname component before84  the trailing <slash> characters names an existing directory or a85  directory entry that is to be created for a directory immediately86  after the pathname is resolved.87 88The Linux pathname walking code (mostly in ``fs/namei.c``) deals with89all of these issues: breaking the path into components, handling the90"everything else" quite separately from the final component, and91checking that the trailing slash is not used where it isn't92permitted.  It also addresses the important issue of concurrent93access.94 95While one process is looking up a pathname, another might be making96changes that affect that lookup.  One fairly extreme case is that if97"a/b" were renamed to "a/c/b" while another process were looking up98"a/b/..", that process might successfully resolve on "a/c".99Most races are much more subtle, and a big part of the task of100pathname lookup is to prevent them from having damaging effects.  Many101of the possible races are seen most clearly in the context of the102"dcache" and an understanding of that is central to understanding103pathname lookup.104 105More than just a cache106----------------------107 108The "dcache" caches information about names in each filesystem to109make them quickly available for lookup.  Each entry (known as a110"dentry") contains three significant fields: a component name, a111pointer to a parent dentry, and a pointer to the "inode" which112contains further information about the object in that parent with113the given name.  The inode pointer can be ``NULL`` indicating that the114name doesn't exist in the parent.  While there can be linkage in the115dentry of a directory to the dentries of the children, that linkage is116not used for pathname lookup, and so will not be considered here.117 118The dcache has a number of uses apart from accelerating lookup.  One119that will be particularly relevant is that it is closely integrated120with the mount table that records which filesystem is mounted where.121What the mount table actually stores is which dentry is mounted on top122of which other dentry.123 124When considering the dcache, we have another of our "two types"125distinctions: there are two types of filesystems.126 127Some filesystems ensure that the information in the dcache is always128completely accurate (though not necessarily complete).  This can allow129the VFS to determine if a particular file does or doesn't exist130without checking with the filesystem, and means that the VFS can131protect the filesystem against certain races and other problems.132These are typically "local" filesystems such as ext3, XFS, and Btrfs.133 134Other filesystems don't provide that guarantee because they cannot.135These are typically filesystems that are shared across a network,136whether remote filesystems like NFS and 9P, or cluster filesystems137like ocfs2 or cephfs.  These filesystems allow the VFS to revalidate138cached information, and must provide their own protection against139awkward races.  The VFS can detect these filesystems by the140``DCACHE_OP_REVALIDATE`` flag being set in the dentry.141 142REF-walk: simple concurrency management with refcounts and spinlocks143--------------------------------------------------------------------144 145With all of those divisions carefully classified, we can now start146looking at the actual process of walking along a path.  In particular147we will start with the handling of the "everything else" part of a148pathname, and focus on the "REF-walk" approach to concurrency149management.  This code is found in the ``link_path_walk()`` function, if150you ignore all the places that only run when "``LOOKUP_RCU``"151(indicating the use of RCU-walk) is set.152 153.. _Meet the Lockers: https://lwn.net/Articles/453685/154 155REF-walk is fairly heavy-handed with locks and reference counts.  Not156as heavy-handed as in the old "big kernel lock" days, but certainly not157afraid of taking a lock when one is needed.  It uses a variety of158different concurrency controls.  A background understanding of the159various primitives is assumed, or can be gleaned from elsewhere such160as in `Meet the Lockers`_.161 162The locking mechanisms used by REF-walk include:163 164dentry->d_lockref165~~~~~~~~~~~~~~~~~166 167This uses the lockref primitive to provide both a spinlock and a168reference count.  The special-sauce of this primitive is that the169conceptual sequence "lock; inc_ref; unlock;" can often be performed170with a single atomic memory operation.171 172Holding a reference on a dentry ensures that the dentry won't suddenly173be freed and used for something else, so the values in various fields174will behave as expected.  It also protects the ``->d_inode`` reference175to the inode to some extent.176 177The association between a dentry and its inode is fairly permanent.178For example, when a file is renamed, the dentry and inode move179together to the new location.  When a file is created the dentry will180initially be negative (i.e. ``d_inode`` is ``NULL``), and will be assigned181to the new inode as part of the act of creation.182 183When a file is deleted, this can be reflected in the cache either by184setting ``d_inode`` to ``NULL``, or by removing it from the hash table185(described shortly) used to look up the name in the parent directory.186If the dentry is still in use the second option is used as it is187perfectly legal to keep using an open file after it has been deleted188and having the dentry around helps.  If the dentry is not otherwise in189use (i.e. if the refcount in ``d_lockref`` is one), only then will190``d_inode`` be set to ``NULL``.  Doing it this way is more efficient for a191very common case.192 193So as long as a counted reference is held to a dentry, a non-``NULL`` ``->d_inode``194value will never be changed.195 196dentry->d_lock197~~~~~~~~~~~~~~198 199``d_lock`` is a synonym for the spinlock that is part of ``d_lockref`` above.200For our purposes, holding this lock protects against the dentry being201renamed or unlinked.  In particular, its parent (``d_parent``), and its202name (``d_name``) cannot be changed, and it cannot be removed from the203dentry hash table.204 205When looking for a name in a directory, REF-walk takes ``d_lock`` on206each candidate dentry that it finds in the hash table and then checks207that the parent and name are correct.  So it doesn't lock the parent208while searching in the cache; it only locks children.209 210When looking for the parent for a given name (to handle "``..``"),211REF-walk can take ``d_lock`` to get a stable reference to ``d_parent``,212but it first tries a more lightweight approach.  As seen in213``dget_parent()``, if a reference can be claimed on the parent, and if214subsequently ``d_parent`` can be seen to have not changed, then there is215no need to actually take the lock on the child.216 217rename_lock218~~~~~~~~~~~219 220Looking up a given name in a given directory involves computing a hash221from the two values (the name and the dentry of the directory),222accessing that slot in a hash table, and searching the linked list223that is found there.224 225When a dentry is renamed, the name and the parent dentry can both226change so the hash will almost certainly change too.  This would move the227dentry to a different chain in the hash table.  If a filename search228happened to be looking at a dentry that was moved in this way,229it might end up continuing the search down the wrong chain,230and so miss out on part of the correct chain.231 232The name-lookup process (``d_lookup()``) does *not* try to prevent this233from happening, but only to detect when it happens.234``rename_lock`` is a seqlock that is updated whenever any dentry is235renamed.  If ``d_lookup`` finds that a rename happened while it236unsuccessfully scanned a chain in the hash table, it simply tries237again.238 239``rename_lock`` is also used to detect and defend against potential attacks240against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where241the parent directory is moved outside the root, bypassing the ``path_equal()``242check). If ``rename_lock`` is updated during the lookup and the path encounters243a "..", a potential attack occurred and ``handle_dots()`` will bail out with244``-EAGAIN``.245 246inode->i_rwsem247~~~~~~~~~~~~~~248 249``i_rwsem`` is a read/write semaphore that serializes all changes to a particular250directory.  This ensures that, for example, an ``unlink()`` and a ``rename()``251cannot both happen at the same time.  It also keeps the directory252stable while the filesystem is asked to look up a name that is not253currently in the dcache or, optionally, when the list of entries in a254directory is being retrieved with ``readdir()``.255 256This has a complementary role to that of ``d_lock``: ``i_rwsem`` on a257directory protects all of the names in that directory, while ``d_lock``258on a name protects just one name in a directory.  Most changes to the259dcache hold ``i_rwsem`` on the relevant directory inode and briefly take260``d_lock`` on one or more the dentries while the change happens.  One261exception is when idle dentries are removed from the dcache due to262memory pressure.  This uses ``d_lock``, but ``i_rwsem`` plays no role.263 264The semaphore affects pathname lookup in two distinct ways.  Firstly it265prevents changes during lookup of a name in a directory.  ``walk_component()`` uses266``lookup_fast()`` first which, in turn, checks to see if the name is in the cache,267using only ``d_lock`` locking.  If the name isn't found, then ``walk_component()``268falls back to ``lookup_slow()`` which takes a shared lock on ``i_rwsem``, checks again that269the name isn't in the cache, and then calls in to the filesystem to get a270definitive answer.  A new dentry will be added to the cache regardless of271the result.272 273Secondly, when pathname lookup reaches the final component, it will274sometimes need to take an exclusive lock on ``i_rwsem`` before performing the last lookup so275that the required exclusion can be achieved.  How path lookup chooses276to take, or not take, ``i_rwsem`` is one of the277issues addressed in a subsequent section.278 279If two threads attempt to look up the same name at the same time - a280name that is not yet in the dcache - the shared lock on ``i_rwsem`` will281not prevent them both adding new dentries with the same name.  As this282would result in confusion an extra level of interlocking is used,283based around a secondary hash table (``in_lookup_hashtable``) and a284per-dentry flag bit (``DCACHE_PAR_LOOKUP``).285 286To add a new dentry to the cache while only holding a shared lock on287``i_rwsem``, a thread must call ``d_alloc_parallel()``.  This allocates a288dentry, stores the required name and parent in it, checks if there289is already a matching dentry in the primary or secondary hash290tables, and if not, stores the newly allocated dentry in the secondary291hash table, with ``DCACHE_PAR_LOOKUP`` set.292 293If a matching dentry was found in the primary hash table then that is294returned and the caller can know that it lost a race with some other295thread adding the entry.  If no matching dentry is found in either296cache, the newly allocated dentry is returned and the caller can297detect this from the presence of ``DCACHE_PAR_LOOKUP``.  In this case it298knows that it has won any race and now is responsible for asking the299filesystem to perform the lookup and find the matching inode.  When300the lookup is complete, it must call ``d_lookup_done()`` which clears301the flag and does some other house keeping, including removing the302dentry from the secondary hash table - it will normally have been303added to the primary hash table already.  Note that a ``struct304waitqueue_head`` is passed to ``d_alloc_parallel()``, and305``d_lookup_done()`` must be called while this ``waitqueue_head`` is still306in scope.307 308If a matching dentry is found in the secondary hash table,309``d_alloc_parallel()`` has a little more work to do. It first waits for310``DCACHE_PAR_LOOKUP`` to be cleared, using a wait_queue that was passed311to the instance of ``d_alloc_parallel()`` that won the race and that312will be woken by the call to ``d_lookup_done()``.  It then checks to see313if the dentry has now been added to the primary hash table.  If it314has, the dentry is returned and the caller just sees that it lost any315race.  If it hasn't been added to the primary hash table, the most316likely explanation is that some other dentry was added instead using317``d_splice_alias()``.  In any case, ``d_alloc_parallel()`` repeats all the318look ups from the start and will normally return something from the319primary hash table.320 321mnt->mnt_count322~~~~~~~~~~~~~~323 324``mnt_count`` is a per-CPU reference counter on "``mount``" structures.325Per-CPU here means that incrementing the count is cheap as it only326uses CPU-local memory, but checking if the count is zero is expensive as327it needs to check with every CPU.  Taking a ``mnt_count`` reference328prevents the mount structure from disappearing as the result of regular329unmount operations, but does not prevent a "lazy" unmount.  So holding330``mnt_count`` doesn't ensure that the mount remains in the namespace and,331in particular, doesn't stabilize the link to the mounted-on dentry.  It332does, however, ensure that the ``mount`` data structure remains coherent,333and it provides a reference to the root dentry of the mounted334filesystem.  So a reference through ``->mnt_count`` provides a stable335reference to the mounted dentry, but not the mounted-on dentry.336 337mount_lock338~~~~~~~~~~339 340``mount_lock`` is a global seqlock, a bit like ``rename_lock``.  It can be used to341check if any change has been made to any mount points.342 343While walking down the tree (away from the root) this lock is used when344crossing a mount point to check that the crossing was safe.  That is,345the value in the seqlock is read, then the code finds the mount that346is mounted on the current directory, if there is one, and increments347the ``mnt_count``.  Finally the value in ``mount_lock`` is checked against348the old value.  If there is no change, then the crossing was safe.  If there349was a change, the ``mnt_count`` is decremented and the whole process is350retried.351 352When walking up the tree (towards the root) by following a ".." link,353a little more care is needed.  In this case the seqlock (which354contains both a counter and a spinlock) is fully locked to prevent355any changes to any mount points while stepping up.  This locking is356needed to stabilize the link to the mounted-on dentry, which the357refcount on the mount itself doesn't ensure.358 359``mount_lock`` is also used to detect and defend against potential attacks360against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where361the parent directory is moved outside the root, bypassing the ``path_equal()``362check). If ``mount_lock`` is updated during the lookup and the path encounters363a "..", a potential attack occurred and ``handle_dots()`` will bail out with364``-EAGAIN``.365 366RCU367~~~368 369Finally the global (but extremely lightweight) RCU read lock is held370from time to time to ensure certain data structures don't get freed371unexpectedly.372 373In particular it is held while scanning chains in the dcache hash374table, and the mount point hash table.375 376Bringing it together with ``struct nameidata``377----------------------------------------------378 379.. _First edition Unix: https://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/u2.s380 381Throughout the process of walking a path, the current status is stored382in a ``struct nameidata``, "namei" being the traditional name - dating383all the way back to `First Edition Unix`_ - of the function that384converts a "name" to an "inode".  ``struct nameidata`` contains (among385other fields):386 387``struct path path``388~~~~~~~~~~~~~~~~~~~~389 390A ``path`` contains a ``struct vfsmount`` (which is391embedded in a ``struct mount``) and a ``struct dentry``.  Together these392record the current status of the walk.  They start out referring to the393starting point (the current working directory, the root directory, or some other394directory identified by a file descriptor), and are updated on each395step.  A reference through ``d_lockref`` and ``mnt_count`` is always396held.397 398``struct qstr last``399~~~~~~~~~~~~~~~~~~~~400 401This is a string together with a length (i.e. *not* ``nul`` terminated)402that is the "next" component in the pathname.403 404``int last_type``405~~~~~~~~~~~~~~~~~406 407This is one of ``LAST_NORM``, ``LAST_ROOT``, ``LAST_DOT`` or ``LAST_DOTDOT``.408The ``last`` field is only valid if the type is ``LAST_NORM``.409 410``struct path root``411~~~~~~~~~~~~~~~~~~~~412 413This is used to hold a reference to the effective root of the414filesystem.  Often that reference won't be needed, so this field is415only assigned the first time it is used, or when a non-standard root416is requested.  Keeping a reference in the ``nameidata`` ensures that417only one root is in effect for the entire path walk, even if it races418with a ``chroot()`` system call.419 420It should be noted that in the case of ``LOOKUP_IN_ROOT`` or421``LOOKUP_BENEATH``, the effective root becomes the directory file descriptor422passed to ``openat2()`` (which exposes these ``LOOKUP_`` flags).423 424The root is needed when either of two conditions holds: (1) either the425pathname or a symbolic link starts with a "'/'", or (2) a "``..``"426component is being handled, since "``..``" from the root must always stay427at the root.  The value used is usually the current root directory of428the calling process.  An alternate root can be provided as when429``sysctl()`` calls ``file_open_root()``, and when NFSv4 or Btrfs call430``mount_subtree()``.  In each case a pathname is being looked up in a very431specific part of the filesystem, and the lookup must not be allowed to432escape that subtree.  It works a bit like a local ``chroot()``.433 434Ignoring the handling of symbolic links, we can now describe the435"``link_path_walk()``" function, which handles the lookup of everything436except the final component as:437 438   Given a path (``name``) and a nameidata structure (``nd``), check that the439   current directory has execute permission and then advance ``name``440   over one component while updating ``last_type`` and ``last``.  If that441   was the final component, then return, otherwise call442   ``walk_component()`` and repeat from the top.443 444``walk_component()`` is even easier.  If the component is ``LAST_DOTS``,445it calls ``handle_dots()`` which does the necessary locking as already446described.  If it finds a ``LAST_NORM`` component it first calls447"``lookup_fast()``" which only looks in the dcache, but will ask the448filesystem to revalidate the result if it is that sort of filesystem.449If that doesn't get a good result, it calls "``lookup_slow()``" which450takes ``i_rwsem``, rechecks the cache, and then asks the filesystem451to find a definitive answer.452 453As the last step of walk_component(), step_into() will be called either454directly from walk_component() or from handle_dots().  It calls455handle_mounts(), to check and handle mount points, in which a new456``struct path`` is created containing a counted reference to the new dentry and457a reference to the new ``vfsmount`` which is only counted if it is458different from the previous ``vfsmount``. Then if there is459a symbolic link, step_into() calls pick_link() to deal with it,460otherwise it installs the new ``struct path`` in the ``struct nameidata``, and461drops the unneeded references.462 463This "hand-over-hand" sequencing of getting a reference to the new464dentry before dropping the reference to the previous dentry may465seem obvious, but is worth pointing out so that we will recognize its466analogue in the "RCU-walk" version.467 468Handling the final component469----------------------------470 471``link_path_walk()`` only walks as far as setting ``nd->last`` and472``nd->last_type`` to refer to the final component of the path.  It does473not call ``walk_component()`` that last time.  Handling that final474component remains for the caller to sort out. Those callers are475path_lookupat(), path_parentat() and476path_openat() each of which handles the differing requirements of477different system calls.478 479``path_parentat()`` is clearly the simplest - it just wraps a little bit480of housekeeping around ``link_path_walk()`` and returns the parent481directory and final component to the caller.  The caller will be either482aiming to create a name (via ``filename_create()``) or remove or rename483a name (in which case ``user_path_parent()`` is used).  They will use484``i_rwsem`` to exclude other changes while they validate and then485perform their operation.486 487``path_lookupat()`` is nearly as simple - it is used when an existing488object is wanted such as by ``stat()`` or ``chmod()``.  It essentially just489calls ``walk_component()`` on the final component through a call to490``lookup_last()``.  ``path_lookupat()`` returns just the final dentry.491It is worth noting that when flag ``LOOKUP_MOUNTPOINT`` is set,492path_lookupat() will unset LOOKUP_JUMPED in nameidata so that in the493subsequent path traversal d_weak_revalidate() won't be called.494This is important when unmounting a filesystem that is inaccessible, such as495one provided by a dead NFS server.496 497Finally ``path_openat()`` is used for the ``open()`` system call; it498contains, in support functions starting with "open_last_lookups()", all the499complexity needed to handle the different subtleties of O_CREAT (with500or without O_EXCL), final "``/``" characters, and trailing symbolic501links.  We will revisit this in the final part of this series, which502focuses on those symbolic links.  "open_last_lookups()" will sometimes, but503not always, take ``i_rwsem``, depending on what it finds.504 505Each of these, or the functions which call them, need to be alert to506the possibility that the final component is not ``LAST_NORM``.  If the507goal of the lookup is to create something, then any value for508``last_type`` other than ``LAST_NORM`` will result in an error.  For509example if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller510won't try to create that name.  They also check for trailing slashes511by testing ``last.name[last.len]``.  If there is any character beyond512the final component, it must be a trailing slash.513 514Revalidation and automounts515---------------------------516 517Apart from symbolic links, there are only two parts of the "REF-walk"518process not yet covered.  One is the handling of stale cache entries519and the other is automounts.520 521On filesystems that require it, the lookup routines will call the522``->d_revalidate()`` dentry method to ensure that the cached information523is current.  This will often confirm validity or update a few details524from a server.  In some cases it may find that there has been change525further up the path and that something that was thought to be valid526previously isn't really.  When this happens the lookup of the whole527path is aborted and retried with the "``LOOKUP_REVAL``" flag set.  This528forces revalidation to be more thorough.  We will see more details of529this retry process in the next article.530 531Automount points are locations in the filesystem where an attempt to532lookup a name can trigger changes to how that lookup should be533handled, in particular by mounting a filesystem there.  These are534covered in greater detail in autofs.txt in the Linux documentation535tree, but a few notes specifically related to path lookup are in order536here.537 538The Linux VFS has a concept of "managed" dentries.  There are three539potentially interesting things about these dentries corresponding540to three different flags that might be set in ``dentry->d_flags``:541 542``DCACHE_MANAGE_TRANSIT``543~~~~~~~~~~~~~~~~~~~~~~~~~544 545If this flag has been set, then the filesystem has requested that the546``d_manage()`` dentry operation be called before handling any possible547mount point.  This can perform two particular services:548 549It can block to avoid races.  If an automount point is being550unmounted, the ``d_manage()`` function will usually wait for that551process to complete before letting the new lookup proceed and possibly552trigger a new automount.553 554It can selectively allow only some processes to transit through a555mount point.  When a server process is managing automounts, it may556need to access a directory without triggering normal automount557processing.  That server process can identify itself to the ``autofs``558filesystem, which will then give it a special pass through559``d_manage()`` by returning ``-EISDIR``.560 561``DCACHE_MOUNTED``562~~~~~~~~~~~~~~~~~~563 564This flag is set on every dentry that is mounted on.  As Linux565supports multiple filesystem namespaces, it is possible that the566dentry may not be mounted on in *this* namespace, just in some567other.  So this flag is seen as a hint, not a promise.568 569If this flag is set, and ``d_manage()`` didn't return ``-EISDIR``,570``lookup_mnt()`` is called to examine the mount hash table (honoring the571``mount_lock`` described earlier) and possibly return a new ``vfsmount``572and a new ``dentry`` (both with counted references).573 574``DCACHE_NEED_AUTOMOUNT``575~~~~~~~~~~~~~~~~~~~~~~~~~576 577If ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't578find a mount point, then this flag causes the ``d_automount()`` dentry579operation to be called.580 581The ``d_automount()`` operation can be arbitrarily complex and may582communicate with server processes etc. but it should ultimately either583report that there was an error, that there was nothing to mount, or584should provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``.585 586In the latter case, ``finish_automount()`` will be called to safely587install the new mount point into the mount table.588 589There is no new locking of import here and it is important that no590locks (only counted references) are held over this processing due to591the very real possibility of extended delays.592This will become more important next time when we examine RCU-walk593which is particularly sensitive to delays.594 595RCU-walk - faster pathname lookup in Linux596==========================================597 598RCU-walk is another algorithm for performing pathname lookup in Linux.599It is in many ways similar to REF-walk and the two share quite a bit600of code.  The significant difference in RCU-walk is how it allows for601the possibility of concurrent access.602 603We noted that REF-walk is complex because there are numerous details604and special cases.  RCU-walk reduces this complexity by simply605refusing to handle a number of cases -- it instead falls back to606REF-walk.  The difficulty with RCU-walk comes from a different607direction: unfamiliarity.  The locking rules when depending on RCU are608quite different from traditional locking, so we will spend a little extra609time when we come to those.610 611Clear demarcation of roles612--------------------------613 614The easiest way to manage concurrency is to forcibly stop any other615thread from changing the data structures that a given thread is616looking at.  In cases where no other thread would even think of617changing the data and lots of different threads want to read at the618same time, this can be very costly.  Even when using locks that permit619multiple concurrent readers, the simple act of updating the count of620the number of current readers can impose an unwanted cost.  So the621goal when reading a shared data structure that no other process is622changing is to avoid writing anything to memory at all.  Take no623locks, increment no counts, leave no footprints.624 625The REF-walk mechanism already described certainly doesn't follow this626principle, but then it is really designed to work when there may well627be other threads modifying the data.  RCU-walk, in contrast, is628designed for the common situation where there are lots of frequent629readers and only occasional writers.  This may not be common in all630parts of the filesystem tree, but in many parts it will be.  For the631other parts it is important that RCU-walk can quickly fall back to632using REF-walk.633 634Pathname lookup always starts in RCU-walk mode but only remains there635as long as what it is looking for is in the cache and is stable.  It636dances lightly down the cached filesystem image, leaving no footprints637and carefully watching where it is, to be sure it doesn't trip.  If it638notices that something has changed or is changing, or if something639isn't in the cache, then it tries to stop gracefully and switch to640REF-walk.641 642This stopping requires getting a counted reference on the current643``vfsmount`` and ``dentry``, and ensuring that these are still valid -644that a path walk with REF-walk would have found the same entries.645This is an invariant that RCU-walk must guarantee.  It can only make646decisions, such as selecting the next step, that are decisions which647REF-walk could also have made if it were walking down the tree at the648same time.  If the graceful stop succeeds, the rest of the path is649processed with the reliable, if slightly sluggish, REF-walk.  If650RCU-walk finds it cannot stop gracefully, it simply gives up and651restarts from the top with REF-walk.652 653This pattern of "try RCU-walk, if that fails try REF-walk" can be654clearly seen in functions like filename_lookup(),655filename_parentat(),656do_filp_open(), and do_file_open_root().  These four657correspond roughly to the three ``path_*()`` functions we met earlier,658each of which calls ``link_path_walk()``.  The ``path_*()`` functions are659called using different mode flags until a mode is found which works.660They are first called with ``LOOKUP_RCU`` set to request "RCU-walk".  If661that fails with the error ``ECHILD`` they are called again with no662special flag to request "REF-walk".  If either of those report the663error ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no664``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly665revalidated - normally entries are only revalidated if the filesystem666determines that they are too old to trust.667 668The ``LOOKUP_RCU`` attempt may drop that flag internally and switch to669REF-walk, but will never then try to switch back to RCU-walk.  Places670that trip up RCU-walk are much more likely to be near the leaves and671so it is very unlikely that there will be much, if any, benefit from672switching back.673 674RCU and seqlocks: fast and light675--------------------------------676 677RCU is, unsurprisingly, critical to RCU-walk mode.  The678``rcu_read_lock()`` is held for the entire time that RCU-walk is walking679down a path.  The particular guarantee it provides is that the key680data structures - dentries, inodes, super_blocks, and mounts - will681not be freed while the lock is held.  They might be unlinked or682invalidated in one way or another, but the memory will not be683repurposed so values in various fields will still be meaningful.  This684is the only guarantee that RCU provides; everything else is done using685seqlocks.686 687As we saw above, REF-walk holds a counted reference to the current688dentry and the current vfsmount, and does not release those references689before taking references to the "next" dentry or vfsmount.  It also690sometimes takes the ``d_lock`` spinlock.  These references and locks are691taken to prevent certain changes from happening.  RCU-walk must not692take those references or locks and so cannot prevent such changes.693Instead, it checks to see if a change has been made, and aborts or694retries if it has.695 696To preserve the invariant mentioned above (that RCU-walk may only make697decisions that REF-walk could have made), it must make the checks at698or near the same places that REF-walk holds the references.  So, when699REF-walk increments a reference count or takes a spinlock, RCU-walk700samples the status of a seqlock using ``read_seqcount_begin()`` or a701similar function.  When REF-walk decrements the count or drops the702lock, RCU-walk checks if the sampled status is still valid using703``read_seqcount_retry()`` or similar.704 705However, there is a little bit more to seqlocks than that.  If706RCU-walk accesses two different fields in a seqlock-protected707structure, or accesses the same field twice, there is no a priori708guarantee of any consistency between those accesses.  When consistency709is needed - which it usually is - RCU-walk must take a copy and then710use ``read_seqcount_retry()`` to validate that copy.711 712``read_seqcount_retry()`` not only checks the sequence number, but also713imposes a memory barrier so that no memory-read instruction from714*before* the call can be delayed until *after* the call, either by the715CPU or by the compiler.  A simple example of this can be seen in716``slow_dentry_cmp()`` which, for filesystems which do not use simple717byte-wise name equality, calls into the filesystem to compare a name718against a dentry.  The length and name pointer are copied into local719variables, then ``read_seqcount_retry()`` is called to confirm the two720are consistent, and only then is ``->d_compare()`` called.  When721standard filename comparison is used, ``dentry_cmp()`` is called722instead.  Notably it does *not* use ``read_seqcount_retry()``, but723instead has a large comment explaining why the consistency guarantee724isn't necessary.  A subsequent ``read_seqcount_retry()`` will be725sufficient to catch any problem that could occur at this point.726 727With that little refresher on seqlocks out of the way we can look at728the bigger picture of how RCU-walk uses seqlocks.729 730``mount_lock`` and ``nd->m_seq``731~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~732 733We already met the ``mount_lock`` seqlock when REF-walk used it to734ensure that crossing a mount point is performed safely.  RCU-walk uses735it for that too, but for quite a bit more.736 737Instead of taking a counted reference to each ``vfsmount`` as it738descends the tree, RCU-walk samples the state of ``mount_lock`` at the739start of the walk and stores this initial sequence number in the740``struct nameidata`` in the ``m_seq`` field.  This one lock and one741sequence number are used to validate all accesses to all ``vfsmounts``,742and all mount point crossings.  As changes to the mount table are743relatively rare, it is reasonable to fall back on REF-walk any time744that any "mount" or "unmount" happens.745 746``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk747sequence, whether switching to REF-walk for the rest of the path or748when the end of the path is reached.  It is also checked when stepping749down over a mount point (in ``__follow_mount_rcu()``) or up (in750``follow_dotdot_rcu()``).  If it is ever found to have changed, the751whole RCU-walk sequence is aborted and the path is processed again by752REF-walk.753 754If RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure755that, had REF-walk taken counted references on each vfsmount, the756results would have been the same.  This ensures the invariant holds,757at least for vfsmount structures.758 759``dentry->d_seq`` and ``nd->seq``760~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~761 762In place of taking a count or lock on ``d_reflock``, RCU-walk samples763the per-dentry ``d_seq`` seqlock, and stores the sequence number in the764``seq`` field of the nameidata structure, so ``nd->seq`` should always be765the current sequence number of ``nd->dentry``.  This number needs to be766revalidated after copying, and before using, the name, parent, or767inode of the dentry.768 769The handling of the name we have already looked at, and the parent is770only accessed in ``follow_dotdot_rcu()`` which fairly trivially follows771the required pattern, though it does so for three different cases.772 773When not at a mount point, ``d_parent`` is followed and its ``d_seq`` is774collected.  When we are at a mount point, we instead follow the775``mnt->mnt_mountpoint`` link to get a new dentry and collect its776``d_seq``.  Then, after finally finding a ``d_parent`` to follow, we must777check if we have landed on a mount point and, if so, must find that778mount point and follow the ``mnt->mnt_root`` link.  This would imply a779somewhat unusual, but certainly possible, circumstance where the780starting point of the path lookup was in part of the filesystem that781was mounted on, and so not visible from the root.782 783The inode pointer, stored in ``->d_inode``, is a little more784interesting.  The inode will always need to be accessed at least785twice, once to determine if it is NULL and once to verify access786permissions.  Symlink handling requires a validated inode pointer too.787Rather than revalidating on each access, a copy is made on the first788access and it is stored in the ``inode`` field of ``nameidata`` from where789it can be safely accessed without further validation.790 791``lookup_fast()`` is the only lookup routine that is used in RCU-mode,792``lookup_slow()`` being too slow and requiring locks.  It is in793``lookup_fast()`` that we find the important "hand over hand" tracking794of the current dentry.795 796The current ``dentry`` and current ``seq`` number are passed to797``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a798new ``seq`` number.  ``lookup_fast()`` then copies the inode pointer and799revalidates the new ``seq`` number.  It then validates the old ``dentry``800with the old ``seq`` number one last time and only then continues.  This801process of getting the ``seq`` number of the new dentry and then802checking the ``seq`` number of the old exactly mirrors the process of803getting a counted reference to the new dentry before dropping that for804the old dentry which we saw in REF-walk.805 806No ``inode->i_rwsem`` or even ``rename_lock``807~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~808 809A semaphore is a fairly heavyweight lock that can only be taken when it is810permissible to sleep.  As ``rcu_read_lock()`` forbids sleeping,811``inode->i_rwsem`` plays no role in RCU-walk.  If some other thread does812take ``i_rwsem`` and modifies the directory in a way that RCU-walk needs813to notice, the result will be either that RCU-walk fails to find the814dentry that it is looking for, or it will find a dentry which815``read_seqretry()`` won't validate.  In either case it will drop down to816REF-walk mode which can take whatever locks are needed.817 818Though ``rename_lock`` could be used by RCU-walk as it doesn't require819any sleeping, RCU-walk doesn't bother.  REF-walk uses ``rename_lock`` to820protect against the possibility of hash chains in the dcache changing821while they are being searched.  This can result in failing to find822something that actually is there.  When RCU-walk fails to find823something in the dentry cache, whether it is really there or not, it824already drops down to REF-walk and tries again with appropriate825locking.  This neatly handles all cases, so adding extra checks on826rename_lock would bring no significant value.827 828``unlazy walk()`` and ``complete_walk()``829-----------------------------------------830 831That "dropping down to REF-walk" typically involves a call to832``unlazy_walk()``, so named because "RCU-walk" is also sometimes833referred to as "lazy walk".  ``unlazy_walk()`` is called when834following the path down to the current vfsmount/dentry pair seems to835have proceeded successfully, but the next step is problematic.  This836can happen if the next name cannot be found in the dcache, if837permission checking or name revalidation couldn't be achieved while838the ``rcu_read_lock()`` is held (which forbids sleeping), if an839automount point is found, or in a couple of cases involving symlinks.840It is also called from ``complete_walk()`` when the lookup has reached841the final component, or the very end of the path, depending on which842particular flavor of lookup is used.843 844Other reasons for dropping out of RCU-walk that do not trigger a call845to ``unlazy_walk()`` are when some inconsistency is found that cannot be846handled immediately, such as ``mount_lock`` or one of the ``d_seq``847seqlocks reporting a change.  In these cases the relevant function848will return ``-ECHILD`` which will percolate up until it triggers a new849attempt from the top using REF-walk.850 851For those cases where ``unlazy_walk()`` is an option, it essentially852takes a reference on each of the pointers that it holds (vfsmount,853dentry, and possibly some symbolic links) and then verifies that the854relevant seqlocks have not been changed.  If there have been changes,855it, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk856has been a success and the lookup process continues.857 858Taking a reference on those pointers is not quite as simple as just859incrementing a counter.  That works to take a second reference if you860already have one (often indirectly through another object), but it861isn't sufficient if you don't actually have a counted reference at862all.  For ``dentry->d_lockref``, it is safe to increment the reference863counter to get a reference unless it has been explicitly marked as864"dead" which involves setting the counter to ``-128``.865``lockref_get_not_dead()`` achieves this.866 867For ``mnt->mnt_count`` it is safe to take a reference as long as868``mount_lock`` is then used to validate the reference.  If that869validation fails, it may *not* be safe to just drop that reference in870the standard way of calling ``mnt_put()`` - an unmount may have871progressed too far.  So the code in ``legitimize_mnt()``, when it872finds that the reference it got might not be safe, checks the873``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is874correct, or if it should just decrement the count and pretend none of875this ever happened.876 877Taking care in filesystems878--------------------------879 880RCU-walk depends almost entirely on cached information and often will881not call into the filesystem at all.  However there are two places,882besides the already-mentioned component-name comparison, where the883file system might be included in RCU-walk, and it must know to be884careful.885 886If the filesystem has non-standard permission-checking requirements -887such as a networked filesystem which may need to check with the server888- the ``i_op->permission`` interface might be called during RCU-walk.889In this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it890knows not to sleep, but to return ``-ECHILD`` if it cannot complete891promptly.  ``i_op->permission`` is given the inode pointer, not the892dentry, so it doesn't need to worry about further consistency checks.893However if it accesses any other filesystem data structures, it must894ensure they are safe to be accessed with only the ``rcu_read_lock()``895held.  This typically means they must be freed using ``kfree_rcu()`` or896similar.897 898.. _READ_ONCE: https://lwn.net/Articles/624126/899 900If the filesystem may need to revalidate dcache entries, then901``d_op->d_revalidate`` may be called in RCU-walk too.  This interface902*is* passed the dentry but does not have access to the ``inode`` or the903``seq`` number from the ``nameidata``, so it needs to be extra careful904when accessing fields in the dentry.  This "extra care" typically905involves using  `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the906result is not NULL before using it.  This pattern can be seen in907``nfs_lookup_revalidate()``.908 909A pair of patterns910------------------911 912In various places in the details of REF-walk and RCU-walk, and also in913the big picture, there are a couple of related patterns that are worth914being aware of.915 916The first is "try quickly and check, if that fails try slowly".  We917can see that in the high-level approach of first trying RCU-walk and918then trying REF-walk, and in places where ``unlazy_walk()`` is used to919switch to REF-walk for the rest of the path.  We also saw it earlier920in ``dget_parent()`` when following a "``..``" link.  It tries a quick way921to get a reference, then falls back to taking locks if needed.922 923The second pattern is "try quickly and check, if that fails try924again - repeatedly".  This is seen with the use of ``rename_lock`` and925``mount_lock`` in REF-walk.  RCU-walk doesn't make use of this pattern -926if anything goes wrong it is much safer to just abort and try a more927sedate approach.928 929The emphasis here is "try quickly and check".  It should probably be930"try quickly *and carefully*, then check".  The fact that checking is931needed is a reminder that the system is dynamic and only a limited932number of things are safe at all.  The most likely cause of errors in933this whole process is assuming something is safe when in reality it934isn't.  Careful consideration of what exactly guarantees the safety of935each access is sometimes necessary.936 937A walk among the symlinks938=========================939 940There are several basic issues that we will examine to understand the941handling of symbolic links:  the symlink stack, together with cache942lifetimes, will help us understand the overall recursive handling of943symlinks and lead to the special care needed for the final component.944Then a consideration of access-time updates and summary of the various945flags controlling lookup will finish the story.946 947The symlink stack948-----------------949 950There are only two sorts of filesystem objects that can usefully951appear in a path prior to the final component: directories and symlinks.952Handling directories is quite straightforward: the new directory953simply becomes the starting point at which to interpret the next954component on the path.  Handling symbolic links requires a bit more955work.956 957Conceptually, symbolic links could be handled by editing the path.  If958a component name refers to a symbolic link, then that component is959replaced by the body of the link and, if that body starts with a '/',960then all preceding parts of the path are discarded.  This is what the961"``readlink -f``" command does, though it also edits out "``.``" and962"``..``" components.963 964Directly editing the path string is not really necessary when looking965up a path, and discarding early components is pointless as they aren't966looked at anyway.  Keeping track of all remaining components is967important, but they can of course be kept separately; there is no need968to concatenate them.  As one symlink may easily refer to another,969which in turn can refer to a third, we may need to keep the remaining970components of several paths, each to be processed when the preceding971ones are completed.  These path remnants are kept on a stack of972limited size.973 974There are two reasons for placing limits on how many symlinks can975occur in a single path lookup.  The most obvious is to avoid loops.976If a symlink referred to itself either directly or through977intermediaries, then following the symlink can never complete978successfully - the error ``ELOOP`` must be returned.  Loops can be979detected without imposing limits, but limits are the simplest solution980and, given the second reason for restriction, quite sufficient.981 982.. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550983 984The second reason was `outlined recently`_ by Linus:985 986   Because it's a latency and DoS issue too. We need to react well to987   true loops, but also to "very deep" non-loops. It's not about memory988   use, it's about users triggering unreasonable CPU resources.989 990Linux imposes a limit on the length of any pathname: ``PATH_MAX``, which991is 4096.  There are a number of reasons for this limit; not letting the992kernel spend too much time on just one path is one of them.  With993symbolic links you can effectively generate much longer paths so some994sort of limit is needed for the same reason.  Linux imposes a limit of995at most 40 (MAXSYMLINKS) symlinks in any one path lookup.  It previously imposed996a further limit of eight on the maximum depth of recursion, but that was997raised to 40 when a separate stack was implemented, so there is now998just the one limit.999 1000The ``nameidata`` structure that we met in an earlier article contains a1001small stack that can be used to store the remaining part of up to two1002symlinks.  In many cases this will be sufficient.  If it isn't, a1003separate stack is allocated with room for 40 symlinks.  Pathname1004lookup will never exceed that stack as, once the 40th symlink is1005detected, an error is returned.1006 1007It might seem that the name remnants are all that needs to be stored on1008this stack, but we need a bit more.  To see that, we need to move on to1009cache lifetimes.1010 1011Storage and lifetime of cached symlinks1012---------------------------------------1013 1014Like other filesystem resources, such as inodes and directory1015entries, symlinks are cached by Linux to avoid repeated costly access1016to external storage.  It is particularly important for RCU-walk to be1017able to find and temporarily hold onto these cached entries, so that1018it doesn't need to drop down into REF-walk.1019 1020.. _object-oriented design pattern: https://lwn.net/Articles/446317/1021 1022While each filesystem is free to make its own choice, symlinks are1023typically stored in one of two places.  Short symlinks are often1024stored directly in the inode.  When a filesystem allocates a ``struct1025inode`` it typically allocates extra space to store private data (a1026common `object-oriented design pattern`_ in the kernel).  This will1027sometimes include space for a symlink.  The other common location is1028in the page cache, which normally stores the content of files.  The1029pathname in a symlink can be seen as the content of that symlink and1030can easily be stored in the page cache just like file content.1031 1032When neither of these is suitable, the next most likely scenario is1033that the filesystem will allocate some temporary memory and copy or1034construct the symlink content into that memory whenever it is needed.1035 1036When the symlink is stored in the inode, it has the same lifetime as1037the inode which, itself, is protected by RCU or by a counted reference1038on the dentry.  This means that the mechanisms that pathname lookup1039uses to access the dcache and icache (inode cache) safely are quite1040sufficient for accessing some cached symlinks safely.  In these cases,1041the ``i_link`` pointer in the inode is set to point to wherever the1042symlink is stored and it can be accessed directly whenever needed.1043 1044When the symlink is stored in the page cache or elsewhere, the1045situation is not so straightforward.  A reference on a dentry or even1046on an inode does not imply any reference on cached pages of that1047inode, and even an ``rcu_read_lock()`` is not sufficient to ensure that1048a page will not disappear.  So for these symlinks the pathname lookup1049code needs to ask the filesystem to provide a stable reference and,1050significantly, needs to release that reference when it is finished1051with it.1052 1053Taking a reference to a cache page is often possible even in RCU-walk1054mode.  It does require making changes to memory, which is best avoided,1055but that isn't necessarily a big cost and it is better than dropping1056out of RCU-walk mode completely.  Even filesystems that allocate1057space to copy the symlink into can use ``GFP_ATOMIC`` to often successfully1058allocate memory without the need to drop out of RCU-walk.  If a1059filesystem cannot successfully get a reference in RCU-walk mode, it1060must return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to1061REF-walk mode in which the filesystem is allowed to sleep.1062 1063The place for all this to happen is the ``i_op->get_link()`` inode1064method. This is called both in RCU-walk and REF-walk. In RCU-walk the1065``dentry*`` argument is NULL, ``->get_link()`` can return -ECHILD to drop out of1066RCU-walk.  Much like the ``i_op->permission()`` method we1067looked at previously, ``->get_link()`` would need to be careful that1068all the data structures it references are safe to be accessed while1069holding no counted reference, only the RCU lock. A callback1070``struct delayed_called`` will be passed to ``->get_link()``:1071file systems can set their own put_link function and argument through1072set_delayed_call(). Later on, when VFS wants to put link, it will call1073do_delayed_call() to invoke that callback function with the argument.1074 1075In order for the reference to each symlink to be dropped when the walk completes,1076whether in RCU-walk or REF-walk, the symlink stack needs to contain,1077along with the path remnants:1078 1079- the ``struct path`` to provide a reference to the previous path1080- the ``const char *`` to provide a reference to the to previous name1081- the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk1082- the ``struct delayed_call`` for later invocation.1083 1084This means that each entry in the symlink stack needs to hold five1085pointers and an integer instead of just one pointer (the path1086remnant).  On a 64-bit system, this is about 40 bytes per entry;1087with 40 entries it adds up to 1600 bytes total, which is less than1088half a page.  So it might seem like a lot, but is by no means1089excessive.1090 1091Note that, in a given stack frame, the path remnant (``name``) is not1092part of the symlink that the other fields refer to.  It is the remnant1093to be followed once that symlink has been fully parsed.1094 1095Following the symlink1096---------------------1097 1098The main loop in ``link_path_walk()`` iterates seamlessly over all1099components in the path and all of the non-final symlinks.  As symlinks1100are processed, the ``name`` pointer is adjusted to point to a new1101symlink, or is restored from the stack, so that much of the loop1102doesn't need to notice.  Getting this ``name`` variable on and off the1103stack is very straightforward; pushing and popping the references is1104a little more complex.1105 1106When a symlink is found, walk_component() calls pick_link() via step_into()1107which returns the link from the filesystem.1108Providing that operation is successful, the old path ``name`` is placed on the1109stack, and the new value is used as the ``name`` for a while.  When the end of1110the path is found (i.e. ``*name`` is ``'\0'``) the old ``name`` is restored1111off the stack and path walking continues.1112 1113Pushing and popping the reference pointers (inode, cookie, etc.) is more1114complex in part because of the desire to handle tail recursion.  When1115the last component of a symlink itself points to a symlink, we1116want to pop the symlink-just-completed off the stack before pushing1117the symlink-just-found to avoid leaving empty path remnants that would1118just get in the way.1119 1120It is most convenient to push the new symlink references onto the1121stack in ``walk_component()`` immediately when the symlink is found;1122``walk_component()`` is also the last piece of code that needs to look at the1123old symlink as it walks that last component.  So it is quite1124convenient for ``walk_component()`` to release the old symlink and pop1125the references just before pushing the reference information for the1126new symlink.  It is guided in this by three flags: ``WALK_NOFOLLOW`` which1127forbids it from following a symlink if it finds one, ``WALK_MORE``1128which indicates that it is yet too early to release the1129current symlink, and ``WALK_TRAILING`` which indicates that it is on the final1130component of the lookup, so we will check userspace flag ``LOOKUP_FOLLOW`` to1131decide whether follow it when it is a symlink and call ``may_follow_link()`` to1132check if we have privilege to follow it.1133 1134Symlinks with no final component1135~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~1136 1137A pair of special-case symlinks deserve a little further explanation.1138Both result in a new ``struct path`` (with mount and dentry) being set1139up in the ``nameidata``, and result in pick_link() returning ``NULL``.1140 1141The more obvious case is a symlink to "``/``".  All symlinks starting1142with "``/``" are detected in pick_link() which resets the ``nameidata``1143to point to the effective filesystem root.  If the symlink only1144contains "``/``" then there is nothing more to do, no components at all,1145so ``NULL`` is returned to indicate that the symlink can be released and1146the stack frame discarded.1147 1148The other case involves things in ``/proc`` that look like symlinks but1149aren't really (and are therefore commonly referred to as "magic-links")::1150 1151     $ ls -l /proc/self/fd/11152     lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/41153 1154Every open file descriptor in any process is represented in ``/proc`` by1155something that looks like a symlink.  It is really a reference to the1156target file, not just the name of it.  When you ``readlink`` these1157objects you get a name that might refer to the same file - unless it1158has been unlinked or mounted over.  When ``walk_component()`` follows1159one of these, the ``->get_link()`` method in "procfs" doesn't return1160a string name, but instead calls nd_jump_link() which updates the1161``nameidata`` in place to point to that target.  ``->get_link()`` then1162returns ``NULL``.  Again there is no final component and pick_link()1163returns ``NULL``.1164 1165Following the symlink in the final component1166--------------------------------------------1167 1168All this leads to ``link_path_walk()`` walking down every component, and1169following all symbolic links it finds, until it reaches the final1170component.  This is just returned in the ``last`` field of ``nameidata``.1171For some callers, this is all they need; they want to create that1172``last`` name if it doesn't exist or give an error if it does.  Other1173callers will want to follow a symlink if one is found, and possibly1174apply special handling to the last component of that symlink, rather1175than just the last component of the original file name.  These callers1176potentially need to call ``link_path_walk()`` again and again on1177successive symlinks until one is found that doesn't point to another1178symlink.1179 1180This case is handled by relevant callers of link_path_walk(), such as1181path_lookupat(), path_openat() using a loop that calls link_path_walk(),1182and then handles the final component by calling open_last_lookups() or1183lookup_last(). If it is a symlink that needs to be followed,1184open_last_lookups() or lookup_last() will set things up properly and1185return the path so that the loop repeats, calling1186link_path_walk() again.  This could loop as many as 40 times if the last1187component of each symlink is another symlink.1188 1189Of the various functions that examine the final component, 1190open_last_lookups() is the most interesting as it works in tandem1191with do_open() for opening a file.  Part of open_last_lookups() runs1192with ``i_rwsem`` held and this part is in a separate function: lookup_open().1193 1194Explaining open_last_lookups() and do_open() completely is beyond the scope1195of this article, but a few highlights should help those interested in exploring1196the code.1197 11981. Rather than just finding the target file, do_open() is used after1199   open_last_lookup() to open1200   it.  If the file was found in the dcache, then ``vfs_open()`` is used for1201   this.  If not, then ``lookup_open()`` will either call ``atomic_open()`` (if1202   the filesystem provides it) to combine the final lookup with the open, or1203   will perform the separate ``i_op->lookup()`` and ``i_op->create()`` steps1204   directly.  In the later case the actual "open" of this newly found or1205   created file will be performed by vfs_open(), just as if the name1206   were found in the dcache.1207 12082. vfs_open() can fail with ``-EOPENSTALE`` if the cached information1209   wasn't quite current enough.  If it's in RCU-walk ``-ECHILD`` will be returned1210   otherwise ``-ESTALE`` is returned.  When ``-ESTALE`` is returned, the caller may1211   retry with ``LOOKUP_REVAL`` flag set.1212 12133. An open with O_CREAT **does** follow a symlink in the final component,1214   unlike other creation system calls (like ``mkdir``).  So the sequence::1215 1216          ln -s bar /tmp/foo1217          echo hello > /tmp/foo1218 1219   will create a file called ``/tmp/bar``.  This is not permitted if1220   ``O_EXCL`` is set but otherwise is handled for an O_CREAT open much1221   like for a non-creating open: lookup_last() or open_last_lookup()1222   returns a non ``NULL`` value, and link_path_walk() gets called and the1223   open process continues on the symlink that was found.1224 1225Updating the access time1226------------------------1227 1228We previously said of RCU-walk that it would "take no locks, increment1229no counts, leave no footprints."  We have since seen that some1230"footprints" can be needed when handling symlinks as a counted1231reference (or even a memory allocation) may be needed.  But these1232footprints are best kept to a minimum.1233 1234One other place where walking down a symlink can involve leaving1235footprints in a way that doesn't affect directories is in updating access times.1236In Unix (and Linux) every filesystem object has a "last accessed1237time", or "``atime``".  Passing through a directory to access a file1238within is not considered to be an access for the purposes of1239``atime``; only listing the contents of a directory can update its ``atime``.1240Symlinks are different it seems.  Both reading a symlink (with ``readlink()``)1241and looking up a symlink on the way to some other destination can1242update the atime on that symlink.1243 1244.. _clearest statement: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_081245 1246It is not clear why this is the case; POSIX has little to say on the1247subject.  The `clearest statement`_ is that, if a particular implementation1248updates a timestamp in a place not specified by POSIX, this must be1249documented "except that any changes caused by pathname resolution need1250not be documented".  This seems to imply that POSIX doesn't really1251care about access-time updates during pathname lookup.1252 1253.. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb81254 1255An examination of history shows that prior to `Linux 1.3.87`_, the ext21256filesystem, at least, didn't update atime when following a link.1257Unfortunately we have no record of why that behavior was changed.1258 1259In any case, access time must now be updated and that operation can be1260quite complex.  Trying to stay in RCU-walk while doing it is best1261avoided.  Fortunately it is often permitted to skip the ``atime``1262update.  Because ``atime`` updates cause performance problems in various1263areas, Linux supports the ``relatime`` mount option, which generally1264limits the updates of ``atime`` to once per day on files that aren't1265being changed (and symlinks never change once created).  Even without1266``relatime``, many filesystems record ``atime`` with a one-second1267granularity, so only one update per second is required.1268 1269It is easy to test if an ``atime`` update is needed while in RCU-walk1270mode and, if it isn't, the update can be skipped and RCU-walk mode1271continues.  Only when an ``atime`` update is actually required does the1272path walk drop down to REF-walk.  All of this is handled in the1273``get_link()`` function.1274 1275A few flags1276-----------1277 1278A suitable way to wrap up this tour of pathname walking is to list1279the various flags that can be stored in the ``nameidata`` to guide the1280lookup process.  Many of these are only meaningful on the final1281component, others reflect the current state of the pathname lookup, and some1282apply restrictions to all path components encountered in the path lookup.1283 1284And then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with1285the others.  If this is not set, an empty pathname causes an error1286very early on.  If it is set, empty pathnames are not considered to be1287an error.1288 1289Global state flags1290~~~~~~~~~~~~~~~~~~1291 1292We have already met two global state flags: ``LOOKUP_RCU`` and1293``LOOKUP_REVAL``.  These select between one of three overall approaches1294to lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.1295 1296``LOOKUP_PARENT`` indicates that the final component hasn't been reached1297yet.  This is primarily used to tell the audit subsystem the full1298context of a particular access being audited.1299 1300``ND_ROOT_PRESET`` indicates that the ``root`` field in the ``nameidata`` was1301provided by the caller, so it shouldn't be released when it is no1302longer needed.1303 1304``ND_JUMPED`` means that the current dentry was chosen not because1305it had the right name but for some other reason.  This happens when1306following "``..``", following a symlink to ``/``, crossing a mount point1307or accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic1308link"). In this case the filesystem has not been asked to revalidate the1309name (with ``d_revalidate()``).  In such cases the inode may still need1310to be revalidated, so ``d_op->d_weak_revalidate()`` is called if1311``ND_JUMPED`` is set when the look completes - which may be at the1312final component or, when creating, unlinking, or renaming, at the penultimate component.1313 1314Resolution-restriction flags1315~~~~~~~~~~~~~~~~~~~~~~~~~~~~1316 1317In order to allow userspace to protect itself against certain race conditions1318and attack scenarios involving changing path components, a series of flags are1319available which apply restrictions to all path components encountered during1320path lookup. These flags are exposed through ``openat2()``'s ``resolve`` field.1321 1322``LOOKUP_NO_SYMLINKS`` blocks all symlink traversals (including magic-links).1323This is distinctly different from ``LOOKUP_FOLLOW``, because the latter only1324relates to restricting the following of trailing symlinks.1325 1326``LOOKUP_NO_MAGICLINKS`` blocks all magic-link traversals. Filesystems must1327ensure that they return errors from ``nd_jump_link()``, because that is how1328``LOOKUP_NO_MAGICLINKS`` and other magic-link restrictions are implemented.1329 1330``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` traversals (this includes both1331bind-mounts and ordinary mounts). Note that the ``vfsmount`` which contains the1332lookup is determined by the first mountpoint the path lookup reaches --1333absolute paths start with the ``vfsmount`` of ``/``, and relative paths start1334with the ``dfd``'s ``vfsmount``. Magic-links are only permitted if the1335``vfsmount`` of the path is unchanged.1336 1337``LOOKUP_BENEATH`` blocks any path components which resolve outside the1338starting point of the resolution. This is done by blocking ``nd_jump_root()``1339as well as blocking ".." if it would jump outside the starting point.1340``rename_lock`` and ``mount_lock`` are used to detect attacks against the1341resolution of "..". Magic-links are also blocked.1342 1343``LOOKUP_IN_ROOT`` resolves all path components as though the starting point1344were the filesystem root. ``nd_jump_root()`` brings the resolution back to1345the starting point, and ".." at the starting point will act as a no-op. As with1346``LOOKUP_BENEATH``, ``rename_lock`` and ``mount_lock`` are used to detect1347attacks against ".." resolution. Magic-links are also blocked.1348 1349Final-component flags1350~~~~~~~~~~~~~~~~~~~~~1351 1352Some of these flags are only set when the final component is being1353considered.  Others are only checked for when considering that final1354component.1355 1356``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount1357point, then the mount is triggered.  Some operations would trigger it1358anyway, but operations like ``stat()`` deliberately don't.  ``statfs()``1359needs to trigger the mount but otherwise behaves a lot like ``stat()``, so1360it sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of1361"``mount --bind``".1362 1363``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for1364symlinks.  Some system calls set or clear it implicitly, while1365others have API flags such as ``AT_SYMLINK_FOLLOW`` and1366``UMOUNT_NOFOLLOW`` to control it.  Its effect is similar to1367``WALK_GET`` that we already met, but it is used in a different way.1368 1369``LOOKUP_DIRECTORY`` insists that the final component is a directory.1370Various callers set this and it is also set when the final component1371is found to be followed by a slash.1372 1373Finally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and1374``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made1375available to the filesystem and particularly the ``->d_revalidate()``1376method.  A filesystem can choose not to bother revalidating too hard1377if it knows that it will be asked to open or create the file soon.1378These flags were previously useful for ``->lookup()`` too but with the1379introduction of ``->atomic_open()`` they are less relevant there.1380 1381End of the road1382---------------1383 1384Despite its complexity, all this pathname lookup code appears to be1385in good shape - various parts are certainly easier to understand now1386than even a couple of releases ago.  But that doesn't mean it is1387"finished".   As already mentioned, RCU-walk currently only follows1388symlinks that are stored in the inode so, while it handles many ext41389symlinks, it doesn't help with NFS, XFS, or Btrfs.  That support1390is not likely to be long delayed.1391