요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
===============
Pathname lookup
===============
This write-up is based on three articles published at lwn.net:
- <https://lwn.net/Articles/649115/> Pathname lookup in Linux
- <https://lwn.net/Articles/649729/> RCU-walk: faster pathname lookup in Linux
- <https://lwn.net/Articles/650786/> A walk among the symlinks
Written by Neil Brown with help from Al Viro and Jon Corbet.
It has subsequently been updated to reflect changes in the kernel
including:
- per-directory parallel name lookup.
- ``openat2()`` resolution restriction flags.
Introduction to pathname lookup
===============================
The most obvious aspect of pathname lookup, which very little
exploration is needed to discover, is that it is complex. There are
many rules, special cases, and implementation alternatives that all
combine to confuse the unwary reader. Computer science has long been
acquainted with such complexity and has tools to help manage it. One
tool that we will make extensive use of is "divide and conquer". For
the early parts of the analysis we will divide off symlinks - leaving
them until the final part. Well before we get to symlinks we have
another major division based on the VFS's approach to locking which
will allow us to review "REF-walk" and "RCU-walk" separately. But we
are getting ahead of ourselves. There are some important low level
distinctions we need to clarify first.
There are two sorts of ...
--------------------------
.. _openat: http://man7.org/linux/man-pages/man2/openat.2.html
Pathnames (sometimes "file names"), used to identify objects in the
filesystem, will be familiar to most readers. They contain two sorts
of elements: "slashes" that are sequences of one or more "``/``"
characters, and "components" that are sequences of one or more
non-"``/``" characters. These form two kinds of paths. Those that
start with slashes are "absolute" and start from the filesystem root.
The others are "relative" and start from the current directory, or
from some other location specified by a file descriptor given to
"``*at()``" system calls such as `openat() <openat_>`_.
.. _execveat: http://man7.org/linux/man-pages/man2/execveat.2.html
It is tempting to describe the second kind as starting with a
component, but that isn't always accurate: a pathname can lack both
slashes and components, it can be empty, in other words. This is
generally forbidden in POSIX, but some of those "``*at()``" system calls
in Linux permit it when the ``AT_EMPTY_PATH`` flag is given. For
example, if you have an open file descriptor on an executable file you
can execute it by calling `execveat() <execveat_>`_ passing
the file descriptor, an empty path, and the ``AT_EMPTY_PATH`` flag.
These paths can be divided into two sections: the final component and
everything else. The "everything else" is the easy bit. In all cases
it must identify a directory that already exists, otherwise an error
such as ``ENOENT`` or ``ENOTDIR`` will be reported.
The final component is not so simple. Not only do different system
calls interpret it quite differently (e.g. some create it, some do
not), but it might not even exist: neither the empty pathname nor the
pathname that is just slashes have a final component. If it does
exist, it could be "``.``" or "``..``" which are handled quite differently
from other components.
.. _POSIX: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
If a pathname ends with a slash, such as "``/tmp/foo/``" it might be
tempting to consider that to have an empty final component. In many
ways that would lead to correct results, but not always. In
particular, ``mkdir()`` and ``rmdir()`` each create or remove a directory named
by the final component, and they are required to work with pathnames
ending in "``/``". According to POSIX_:
A pathname that contains at least one non-<slash> character and
that ends with one or more trailing <slash> characters shall not
be resolved successfully unless the last pathname component before
the trailing <slash> characters names an existing directory or a
directory entry that is to be created for a directory immediately
after the pathname is resolved.
The Linux pathname walking code (mostly in ``fs/namei.c``) deals with
all of these issues: breaking the path into components, handling the
"everything else" quite separately from the final component, and
checking that the trailing slash is not used where it isn't
permitted. It also addresses the important issue of concurrent
access.
While one process is looking up a pathname, another might be making
changes that affect that lookup. One fairly extreme case is that if
"a/b" were renamed to "a/c/b" while another process were looking up
"a/b/..", that process might successfully resolve on "a/c".
Most races are much more subtle, and a big part of the task of
pathname lookup is to prevent them from having damaging effects. Many
of the possible races are seen most clearly in the context of the
"dcache" and an understanding of that is central to understanding
pathname lookup.
More than just a cache
----------------------
The "dcache" caches information about names in each filesystem to
make them quickly available for lookup. Each entry (known as a
"dentry") contains three significant fields: a component name, a
pointer to a parent dentry, and a pointer to the "inode" which
contains further information about the object in that parent with
the given name. The inode pointer can be ``NULL`` indicating that the
name doesn't exist in the parent. While there can be linkage in the
dentry of a directory to the dentries of the children, that linkage is
not used for pathname lookup, and so will not be considered here.
The dcache has a number of uses apart from accelerating lookup. One
that will be particularly relevant is that it is closely integrated
with the mount table that records which filesystem is mounted where.
What the mount table actually stores is which dentry is mounted on top
of which other dentry.
When considering the dcache, we have another of our "two types"
distinctions: there are two types of filesystems.
Some filesystems ensure that the information in the dcache is always
completely accurate (though not necessarily complete). This can allow
the VFS to determine if a particular file does or doesn't exist
without checking with the filesystem, and means that the VFS can
protect the filesystem against certain races and other problems.
These are typically "local" filesystems such as ext3, XFS, and Btrfs.
Other filesystems don't provide that guarantee because they cannot.
These are typically filesystems that are shared across a network,
whether remote filesystems like NFS and 9P, or cluster filesystems
like ocfs2 or cephfs. These filesystems allow the VFS to revalidate
cached information, and must provide their own protection against
awkward races. The VFS can detect these filesystems by the
``DCACHE_OP_REVALIDATE`` flag being set in the dentry.
REF-walk: simple concurrency management with refcounts and spinlocks
--------------------------------------------------------------------
With all of those divisions carefully classified, we can now start
looking at the actual process of walking along a path. In particular
we will start with the handling of the "everything else" part of a
pathname, and focus on the "REF-walk" approach to concurrency
management. This code is found in the ``link_path_walk()`` function, if
you ignore all the places that only run when "``LOOKUP_RCU``"
(indicating the use of RCU-walk) is set.
.. _Meet the Lockers: https://lwn.net/Articles/453685/
REF-walk is fairly heavy-handed with locks and reference counts. Not
as heavy-handed as in the old "big kernel lock" days, but certainly not
afraid of taking a lock when one is needed. It uses a variety of
different concurrency controls. A background understanding of the
various primitives is assumed, or can be gleaned from elsewhere such
as in `Meet the Lockers`_.
The locking mechanisms used by REF-walk include:
dentry->d_lockref
~~~~~~~~~~~~~~~~~
This uses the lockref primitive to provide both a spinlock and a
reference count. The special-sauce of this primitive is that the
conceptual sequence "lock; inc_ref; unlock;" can often be performed
with a single atomic memory operation.
Holding a reference on a dentry ensures that the dentry won't suddenly
be freed and used for something else, so the values in various fields
will behave as expected. It also protects the ``->d_inode`` reference
to the inode to some extent.
The association between a dentry and its inode is fairly permanent.
For example, when a file is renamed, the dentry and inode move
together to the new location. When a file is created the dentry will
initially be negative (i.e. ``d_inode`` is ``NULL``), and will be assigned
to the new inode as part of the act of creation.
When a file is deleted, this can be reflected in the cache either by
setting ``d_inode`` to ``NULL``, or by removing it from the hash table
(described shortly) used to look up the name in the parent directory.
If the dentry is still in use the second option is used as it is
perfectly legal to keep using an open file after it has been deleted
and having the dentry around helps. If the dentry is not otherwise in
use (i.e. if the refcount in ``d_lockref`` is one), only then will
``d_inode`` be set to ``NULL``. Doing it this way is more efficient for a
very common case.
So as long as a counted reference is held to a dentry, a non-``NULL`` ``->d_inode``
value will never be changed.
dentry->d_lock
~~~~~~~~~~~~~~
``d_lock`` is a synonym for the spinlock that is part of ``d_lockref`` above.
For our purposes, holding this lock protects against the dentry being
renamed or unlinked. In particular, its parent (``d_parent``), and its
name (``d_name``) cannot be changed, and it cannot be removed from the
dentry hash table.
When looking for a name in a directory, REF-walk takes ``d_lock`` on
each candidate dentry that it finds in the hash table and then checks
that the parent and name are correct. So it doesn't lock the parent
while searching in the cache; it only locks children.
When looking for the parent for a given name (to handle "``..``"),
REF-walk can take ``d_lock`` to get a stable reference to ``d_parent``,
but it first tries a more lightweight approach. As seen in
``dget_parent()``, if a reference can be claimed on the parent, and if
subsequently ``d_parent`` can be seen to have not changed, then there is
no need to actually take the lock on the child.
rename_lock
~~~~~~~~~~~
Looking up a given name in a given directory involves computing a hash
from the two values (the name and the dentry of the directory),
accessing that slot in a hash table, and searching the linked list
that is found there.
When a dentry is renamed, the name and the parent dentry can both
change so the hash will almost certainly change too. This would move the
dentry to a different chain in the hash table. If a filename search
happened to be looking at a dentry that was moved in this way,
it might end up continuing the search down the wrong chain,
and so miss out on part of the correct chain.
The name-lookup process (``d_lookup()``) does *not* try to prevent this
from happening, but only to detect when it happens.
``rename_lock`` is a seqlock that is updated whenever any dentry is
renamed. If ``d_lookup`` finds that a rename happened while it
unsuccessfully scanned a chain in the hash table, it simply tries
again.
``rename_lock`` is also used to detect and defend against potential attacks
against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
the parent directory is moved outside the root, bypassing the ``path_equal()``
check). If ``rename_lock`` is updated during the lookup and the path encounters
a "..", a potential attack occurred and ``handle_dots()`` will bail out with
``-EAGAIN``.
inode->i_rwsem
~~~~~~~~~~~~~~
``i_rwsem`` is a read/write semaphore that serializes all changes to a particular
directory. This ensures that, for example, an ``unlink()`` and a ``rename()``
cannot both happen at the same time. It also keeps the directory
stable while the filesystem is asked to look up a name that is not
currently in the dcache or, optionally, when the list of entries in a
directory is being retrieved with ``readdir()``.
This has a complementary role to that of ``d_lock``: ``i_rwsem`` on a
directory protects all of the names in that directory, while ``d_lock``
on a name protects just one name in a directory. Most changes to the
dcache hold ``i_rwsem`` on the relevant directory inode and briefly take
``d_lock`` on one or more the dentries while the change happens. One
exception is when idle dentries are removed from the dcache due to
memory pressure. This uses ``d_lock``, but ``i_rwsem`` plays no role.
The semaphore affects pathname lookup in two distinct ways. Firstly it
prevents changes during lookup of a name in a directory. ``walk_component()`` uses
``lookup_fast()`` first which, in turn, checks to see if the name is in the cache,
using only ``d_lock`` locking. If the name isn't found, then ``walk_component()``
falls back to ``lookup_slow()`` which takes a shared lock on ``i_rwsem``, checks again that
the name isn't in the cache, and then calls in to the filesystem to get a
definitive answer. A new dentry will be added to the cache regardless of
the result.
Secondly, when pathname lookup reaches the final component, it will
sometimes need to take an exclusive lock on ``i_rwsem`` before performing the last lookup so
that the required exclusion can be achieved. How path lookup chooses
to take, or not take, ``i_rwsem`` is one of the
issues addressed in a subsequent section.
If two threads attempt to look up the same name at the same time - a
name that is not yet in the dcache - the shared lock on ``i_rwsem`` will
not prevent them both adding new dentries with the same name. As this
would result in confusion an extra level of interlocking is used,
based around a secondary hash table (``in_lookup_hashtable``) and a
per-dentry flag bit (``DCACHE_PAR_LOOKUP``).
To add a new dentry to the cache while only holding a shared lock on
``i_rwsem``, a thread must call ``d_alloc_parallel()``. This allocates a
dentry, stores the required name and parent in it, checks if there
is already a matching dentry in the primary or secondary hash
tables, and if not, stores the newly allocated dentry in the secondary
hash table, with ``DCACHE_PAR_LOOKUP`` set.
If a matching dentry was found in the primary hash table then that is
returned and the caller can know that it lost a race with some other
thread adding the entry. If no matching dentry is found in either
cache, the newly allocated dentry is returned and the caller can
detect this from the presence of ``DCACHE_PAR_LOOKUP``. In this case it
knows that it has won any race and now is responsible for asking the
filesystem to perform the lookup and find the matching inode. When
the lookup is complete, it must call ``d_lookup_done()`` which clears
the flag and does some other house keeping, including removing the
dentry from the secondary hash table - it will normally have been
added to the primary hash table already. Note that a ``struct
waitqueue_head`` is passed to ``d_alloc_parallel()``, and
``d_lookup_done()`` must be called while this ``waitqueue_head`` is still
in scope.
If a matching dentry is found in the secondary hash table,
``d_alloc_parallel()`` has a little more work to do. It first waits for
``DCACHE_PAR_LOOKUP`` to be cleared, using a wait_queue that was passed
to the instance of ``d_alloc_parallel()`` that won the race and that
will be woken by the call to ``d_lookup_done()``. It then checks to see
if the dentry has now been added to the primary hash table. If it
has, the dentry is returned and the caller just sees that it lost any
race. If it hasn't been added to the primary hash table, the most
likely explanation is that some other dentry was added instead using
``d_splice_alias()``. In any case, ``d_alloc_parallel()`` repeats all the
look ups from the start and will normally return something from the
primary hash table.
mnt->mnt_count
~~~~~~~~~~~~~~
``mnt_count`` is a per-CPU reference counter on "``mount``" structures.
Per-CPU here means that incrementing the count is cheap as it only
uses CPU-local memory, but checking if the count is zero is expensive as
it needs to check with every CPU. Taking a ``mnt_count`` reference
prevents the mount structure from disappearing as the result of regular
unmount operations, but does not prevent a "lazy" unmount. So holding
``mnt_count`` doesn't ensure that the mount remains in the namespace and,
in particular, doesn't stabilize the link to the mounted-on dentry. It
does, however, ensure that the ``mount`` data structure remains coherent,
and it provides a reference to the root dentry of the mounted
filesystem. So a reference through ``->mnt_count`` provides a stable
reference to the mounted dentry, but not the mounted-on dentry.
mount_lock
~~~~~~~~~~
``mount_lock`` is a global seqlock, a bit like ``rename_lock``. It can be used to
check if any change has been made to any mount points.
While walking down the tree (away from the root) this lock is used when
crossing a mount point to check that the crossing was safe. That is,
the value in the seqlock is read, then the code finds the mount that
is mounted on the current directory, if there is one, and increments
the ``mnt_count``. Finally the value in ``mount_lock`` is checked against
the old value. If there is no change, then the crossing was safe. If there
was a change, the ``mnt_count`` is decremented and the whole process is
retried.
When walking up the tree (towards the root) by following a ".." link,
a little more care is needed. In this case the seqlock (which
contains both a counter and a spinlock) is fully locked to prevent
any changes to any mount points while stepping up. This locking is
needed to stabilize the link to the mounted-on dentry, which the
refcount on the mount itself doesn't ensure.
``mount_lock`` is also used to detect and defend against potential attacks
against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
the parent directory is moved outside the root, bypassing the ``path_equal()``
check). If ``mount_lock`` is updated during the lookup and the path encounters
a "..", a potential attack occurred and ``handle_dots()`` will bail out with
``-EAGAIN``.
RCU
~~~
Finally the global (but extremely lightweight) RCU read lock is held
from time to time to ensure certain data structures don't get freed
unexpectedly.
In particular it is held while scanning chains in the dcache hash
table, and the mount point hash table.
Bringing it together with ``struct nameidata``
----------------------------------------------
.. _First edition Unix: https://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/u2.s
Throughout the process of walking a path, the current status is stored
in a ``struct nameidata``, "namei" being the traditional name - dating
all the way back to `First Edition Unix`_ - of the function that
converts a "name" to an "inode". ``struct nameidata`` contains (among
other fields):
``struct path path``
~~~~~~~~~~~~~~~~~~~~
A ``path`` contains a ``struct vfsmount`` (which is
embedded in a ``struct mount``) and a ``struct dentry``. Together these
record the current status of the walk. They start out referring to the
starting point (the current working directory, the root directory, or some other
directory identified by a file descriptor), and are updated on each
step. A reference through ``d_lockref`` and ``mnt_count`` is always
held.
``struct qstr last``
~~~~~~~~~~~~~~~~~~~~
This is a string together with a length (i.e. *not* ``nul`` terminated)
that is the "next" component in the pathname.
``int last_type``
~~~~~~~~~~~~~~~~~
This is one of ``LAST_NORM``, ``LAST_ROOT``, ``LAST_DOT`` or ``LAST_DOTDOT``.
The ``last`` field is only valid if the type is ``LAST_NORM``.
``struct path root``
~~~~~~~~~~~~~~~~~~~~
This is used to hold a reference to the effective root of the
filesystem. Often that reference won't be needed, so this field is
only assigned the first time it is used, or when a non-standard root
is requested. Keeping a reference in the ``nameidata`` ensures that
only one root is in effect for the entire path walk, even if it races
with a ``chroot()`` system call.
It should be noted that in the case of ``LOOKUP_IN_ROOT`` or
``LOOKUP_BENEATH``, the effective root becomes the directory file descriptor
passed to ``openat2()`` (which exposes these ``LOOKUP_`` flags).
The root is needed when either of two conditions holds: (1) either the
pathname or a symbolic link starts with a "'/'", or (2) a "``..``"
component is being handled, since "``..``" from the root must always stay
at the root. The value used is usually the current root directory of
the calling process. An alternate root can be provided as when
``sysctl()`` calls ``file_open_root()``, and when NFSv4 or Btrfs call
``mount_subtree()``. In each case a pathname is being looked up in a very
specific part of the filesystem, and the lookup must not be allowed to
escape that subtree. It works a bit like a local ``chroot()``.
Ignoring the handling of symbolic links, we can now describe the
"``link_path_walk()``" function, which handles the lookup of everything
except the final component as:
Given a path (``name``) and a nameidata structure (``nd``), check that the
current directory has execute permission and then advance ``name``
over one component while updating ``last_type`` and ``last``. If that
was the final component, then return, otherwise call
``walk_component()`` and repeat from the top.
``walk_component()`` is even easier. If the component is ``LAST_DOTS``,
it calls ``handle_dots()`` which does the necessary locking as already
described. If it finds a ``LAST_NORM`` component it first calls
"``lookup_fast()``" which only looks in the dcache, but will ask the
filesystem to revalidate the result if it is that sort of filesystem.
If that doesn't get a good result, it calls "``lookup_slow()``" which
takes ``i_rwsem``, rechecks the cache, and then asks the filesystem
to find a definitive answer.
As the last step of walk_component(), step_into() will be called either
directly from walk_component() or from handle_dots(). It calls
handle_mounts(), to check and handle mount points, in which a new
``struct path`` is created containing a counted reference to the new dentry and
a reference to the new ``vfsmount`` which is only counted if it is
different from the previous ``vfsmount``. Then if there is
a symbolic link, step_into() calls pick_link() to deal with it,
otherwise it installs the new ``struct path`` in the ``struct nameidata``, and
drops the unneeded references.
This "hand-over-hand" sequencing of getting a reference to the new
dentry before dropping the reference to the previous dentry may
seem obvious, but is worth pointing out so that we will recognize its
analogue in the "RCU-walk" version.
Handling the final component
----------------------------
``link_path_walk()`` only walks as far as setting ``nd->last`` and
``nd->last_type`` to refer to the final component of the path. It does
not call ``walk_component()`` that last time. Handling that final
component remains for the caller to sort out. Those callers are
path_lookupat(), path_parentat() and
path_openat() each of which handles the differing requirements of
different system calls.
``path_parentat()`` is clearly the simplest - it just wraps a little bit
of housekeeping around ``link_path_walk()`` and returns the parent
directory and final component to the caller. The caller will be either
aiming to create a name (via ``filename_create()``) or remove or rename
a name (in which case ``user_path_parent()`` is used). They will use
``i_rwsem`` to exclude other changes while they validate and then
perform their operation.
``path_lookupat()`` is nearly as simple - it is used when an existing
object is wanted such as by ``stat()`` or ``chmod()``. It essentially just
calls ``walk_component()`` on the final component through a call to
``lookup_last()``. ``path_lookupat()`` returns just the final dentry.
It is worth noting that when flag ``LOOKUP_MOUNTPOINT`` is set,
path_lookupat() will unset LOOKUP_JUMPED in nameidata so that in the
subsequent path traversal d_weak_revalidate() won't be called.
This is important when unmounting a filesystem that is inaccessible, such as
one provided by a dead NFS server.
Finally ``path_openat()`` is used for the ``open()`` system call; it
contains, in support functions starting with "open_last_lookups()", all the
complexity needed to handle the different subtleties of O_CREAT (with
or without O_EXCL), final "``/``" characters, and trailing symbolic
links. We will revisit this in the final part of this series, which
focuses on those symbolic links. "open_last_lookups()" will sometimes, but
not always, take ``i_rwsem``, depending on what it finds.
Each of these, or the functions which call them, need to be alert to
the possibility that the final component is not ``LAST_NORM``. If the
goal of the lookup is to create something, then any value for
``last_type`` other than ``LAST_NORM`` will result in an error. For
example if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller
won't try to create that name. They also check for trailing slashes
by testing ``last.name[last.len]``. If there is any character beyond
the final component, it must be a trailing slash.
Revalidation and automounts
---------------------------
Apart from symbolic links, there are only two parts of the "REF-walk"
process not yet covered. One is the handling of stale cache entries
and the other is automounts.
On filesystems that require it, the lookup routines will call the
``->d_revalidate()`` dentry method to ensure that the cached information
is current. This will often confirm validity or update a few details
from a server. In some cases it may find that there has been change
further up the path and that something that was thought to be valid
previously isn't really. When this happens the lookup of the whole
path is aborted and retried with the "``LOOKUP_REVAL``" flag set. This
forces revalidation to be more thorough. We will see more details of
this retry process in the next article.
Automount points are locations in the filesystem where an attempt to
lookup a name can trigger changes to how that lookup should be
handled, in particular by mounting a filesystem there. These are
covered in greater detail in autofs.rst in the Linux documentation
tree, but a few notes specifically related to path lookup are in order
here.
The Linux VFS has a concept of "managed" dentries. There are three
potentially interesting things about these dentries corresponding
to three different flags that might be set in ``dentry->d_flags``:
``DCACHE_MANAGE_TRANSIT``
~~~~~~~~~~~~~~~~~~~~~~~~~
If this flag has been set, then the filesystem has requested that the
``d_manage()`` dentry operation be called before handling any possible
mount point. This can perform two particular services:
It can block to avoid races. If an automount point is being
unmounted, the ``d_manage()`` function will usually wait for that
process to complete before letting the new lookup proceed and possibly
trigger a new automount.
It can selectively allow only some processes to transit through a
mount point. When a server process is managing automounts, it may
need to access a directory without triggering normal automount
processing. That server process can identify itself to the ``autofs``
filesystem, which will then give it a special pass through
``d_manage()`` by returning ``-EISDIR``.
``DCACHE_MOUNTED``
~~~~~~~~~~~~~~~~~~
This flag is set on every dentry that is mounted on. As Linux
supports multiple filesystem namespaces, it is possible that the
dentry may not be mounted on in *this* namespace, just in some
other. So this flag is seen as a hint, not a promise.
If this flag is set, and ``d_manage()`` didn't return ``-EISDIR``,
``lookup_mnt()`` is called to examine the mount hash table (honoring the
``mount_lock`` described earlier) and possibly return a new ``vfsmount``
and a new ``dentry`` (both with counted references).
``DCACHE_NEED_AUTOMOUNT``
~~~~~~~~~~~~~~~~~~~~~~~~~
If ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't
find a mount point, then this flag causes the ``d_automount()`` dentry
operation to be called.
The ``d_automount()`` operation can be arbitrarily complex and may
communicate with server processes etc. but it should ultimately either
report that there was an error, that there was nothing to mount, or
should provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``.
In the latter case, ``finish_automount()`` will be called to safely
install the new mount point into the mount table.
There is no new locking of import here and it is important that no
locks (only counted references) are held over this processing due to
the very real possibility of extended delays.
This will become more important next time when we examine RCU-walk
which is particularly sensitive to delays.
RCU-walk - faster pathname lookup in Linux
==========================================
RCU-walk is another algorithm for performing pathname lookup in Linux.
It is in many ways similar to REF-walk and the two share quite a bit
of code. The significant difference in RCU-walk is how it allows for
the possibility of concurrent access.
We noted that REF-walk is complex because there are numerous details
and special cases. RCU-walk reduces this complexity by simply
refusing to handle a number of cases -- it instead falls back to
REF-walk. The difficulty with RCU-walk comes from a different
direction: unfamiliarity. The locking rules when depending on RCU are
quite different from traditional locking, so we will spend a little extra
time when we come to those.
Clear demarcation of roles
--------------------------
The easiest way to manage concurrency is to forcibly stop any other
thread from changing the data structures that a given thread is
looking at. In cases where no other thread would even think of
changing the data and lots of different threads want to read at the
same time, this can be very costly. Even when using locks that permit
multiple concurrent readers, the simple act of updating the count of
the number of current readers can impose an unwanted cost. So the
goal when reading a shared data structure that no other process is
changing is to avoid writing anything to memory at all. Take no
locks, increment no counts, leave no footprints.
The REF-walk mechanism already described certainly doesn't follow this
principle, but then it is really designed to work when there may well
be other threads modifying the data. RCU-walk, in contrast, is
designed for the common situation where there are lots of frequent
readers and only occasional writers. This may not be common in all
parts of the filesystem tree, but in many parts it will be. For the
other parts it is important that RCU-walk can quickly fall back to
using REF-walk.
Pathname lookup always starts in RCU-walk mode but only remains there
as long as what it is looking for is in the cache and is stable. It
dances lightly down the cached filesystem image, leaving no footprints
and carefully watching where it is, to be sure it doesn't trip. If it
notices that something has changed or is changing, or if something
isn't in the cache, then it tries to stop gracefully and switch to
REF-walk.
This stopping requires getting a counted reference on the current
``vfsmount`` and ``dentry``, and ensuring that these are still valid -
that a path walk with REF-walk would have found the same entries.
This is an invariant that RCU-walk must guarantee. It can only make
decisions, such as selecting the next step, that are decisions which
REF-walk could also have made if it were walking down the tree at the
same time. If the graceful stop succeeds, the rest of the path is
processed with the reliable, if slightly sluggish, REF-walk. If
RCU-walk finds it cannot stop gracefully, it simply gives up and
restarts from the top with REF-walk.
This pattern of "try RCU-walk, if that fails try REF-walk" can be
clearly seen in functions like filename_lookup(),
filename_parentat(),
do_filp_open(), and do_file_open_root(). These four
correspond roughly to the three ``path_*()`` functions we met earlier,
each of which calls ``link_path_walk()``. The ``path_*()`` functions are
called using different mode flags until a mode is found which works.
They are first called with ``LOOKUP_RCU`` set to request "RCU-walk". If
that fails with the error ``ECHILD`` they are called again with no
special flag to request "REF-walk". If either of those report the
error ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no
``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly
revalidated - normally entries are only revalidated if the filesystem
determines that they are too old to trust.
The ``LOOKUP_RCU`` attempt may drop that flag internally and switch to
REF-walk, but will never then try to switch back to RCU-walk. Places
that trip up RCU-walk are much more likely to be near the leaves and
so it is very unlikely that there will be much, if any, benefit from
switching back.
RCU and seqlocks: fast and light
--------------------------------
RCU is, unsurprisingly, critical to RCU-walk mode. The
``rcu_read_lock()`` is held for the entire time that RCU-walk is walking
down a path. The particular guarantee it provides is that the key
data structures - dentries, inodes, super_blocks, and mounts - will
not be freed while the lock is held. They might be unlinked or
invalidated in one way or another, but the memory will not be
repurposed so values in various fields will still be meaningful. This
is the only guarantee that RCU provides; everything else is done using
seqlocks.
As we saw above, REF-walk holds a counted reference to the current
dentry and the current vfsmount, and does not release those references
before taking references to the "next" dentry or vfsmount. It also
sometimes takes the ``d_lock`` spinlock. These references and locks are
taken to prevent certain changes from happening. RCU-walk must not
take those references or locks and so cannot prevent such changes.
Instead, it checks to see if a change has been made, and aborts or
retries if it has.
To preserve the invariant mentioned above (that RCU-walk may only make
decisions that REF-walk could have made), it must make the checks at
or near the same places that REF-walk holds the references. So, when
REF-walk increments a reference count or takes a spinlock, RCU-walk
samples the status of a seqlock using ``read_seqcount_begin()`` or a
similar function. When REF-walk decrements the count or drops the
lock, RCU-walk checks if the sampled status is still valid using
``read_seqcount_retry()`` or similar.
However, there is a little bit more to seqlocks than that. If
RCU-walk accesses two different fields in a seqlock-protected
structure, or accesses the same field twice, there is no a priori
guarantee of any consistency between those accesses. When consistency
is needed - which it usually is - RCU-walk must take a copy and then
use ``read_seqcount_retry()`` to validate that copy.
``read_seqcount_retry()`` not only checks the sequence number, but also
imposes a memory barrier so that no memory-read instruction from
*before* the call can be delayed until *after* the call, either by the
CPU or by the compiler. A simple example of this can be seen in
``slow_dentry_cmp()`` which, for filesystems which do not use simple
byte-wise name equality, calls into the filesystem to compare a name
against a dentry. The length and name pointer are copied into local
variables, then ``read_seqcount_retry()`` is called to confirm the two
are consistent, and only then is ``->d_compare()`` called. When
standard filename comparison is used, ``dentry_cmp()`` is called
instead. Notably it does *not* use ``read_seqcount_retry()``, but
instead has a large comment explaining why the consistency guarantee
isn't necessary. A subsequent ``read_seqcount_retry()`` will be
sufficient to catch any problem that could occur at this point.
With that little refresher on seqlocks out of the way we can look at
the bigger picture of how RCU-walk uses seqlocks.
``mount_lock`` and ``nd->m_seq``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We already met the ``mount_lock`` seqlock when REF-walk used it to
ensure that crossing a mount point is performed safely. RCU-walk uses
it for that too, but for quite a bit more.
Instead of taking a counted reference to each ``vfsmount`` as it
descends the tree, RCU-walk samples the state of ``mount_lock`` at the
start of the walk and stores this initial sequence number in the
``struct nameidata`` in the ``m_seq`` field. This one lock and one
sequence number are used to validate all accesses to all ``vfsmounts``,
and all mount point crossings. As changes to the mount table are
relatively rare, it is reasonable to fall back on REF-walk any time
that any "mount" or "unmount" happens.
``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk
sequence, whether switching to REF-walk for the rest of the path or
when the end of the path is reached. It is also checked when stepping
down over a mount point (in ``__follow_mount_rcu()``) or up (in
``follow_dotdot_rcu()``). If it is ever found to have changed, the
whole RCU-walk sequence is aborted and the path is processed again by
REF-walk.
If RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure
that, had REF-walk taken counted references on each vfsmount, the
results would have been the same. This ensures the invariant holds,
at least for vfsmount structures.
``dentry->d_seq`` and ``nd->seq``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In place of taking a count or lock on ``d_reflock``, RCU-walk samples
the per-dentry ``d_seq`` seqlock, and stores the sequence number in the
``seq`` field of the nameidata structure, so ``nd->seq`` should always be
the current sequence number of ``nd->dentry``. This number needs to be
revalidated after copying, and before using, the name, parent, or
inode of the dentry.
The handling of the name we have already looked at, and the parent is
only accessed in ``follow_dotdot_rcu()`` which fairly trivially follows
the required pattern, though it does so for three different cases.
When not at a mount point, ``d_parent`` is followed and its ``d_seq`` is
collected. When we are at a mount point, we instead follow the
``mnt->mnt_mountpoint`` link to get a new dentry and collect its
``d_seq``. Then, after finally finding a ``d_parent`` to follow, we must
check if we have landed on a mount point and, if so, must find that
mount point and follow the ``mnt->mnt_root`` link. This would imply a
somewhat unusual, but certainly possible, circumstance where the
starting point of the path lookup was in part of the filesystem that
was mounted on, and so not visible from the root.
The inode pointer, stored in ``->d_inode``, is a little more
interesting. The inode will always need to be accessed at least
twice, once to determine if it is NULL and once to verify access
permissions. Symlink handling requires a validated inode pointer too.
Rather than revalidating on each access, a copy is made on the first
access and it is stored in the ``inode`` field of ``nameidata`` from where
it can be safely accessed without further validation.
``lookup_fast()`` is the only lookup routine that is used in RCU-mode,
``lookup_slow()`` being too slow and requiring locks. It is in
``lookup_fast()`` that we find the important "hand over hand" tracking
of the current dentry.
The current ``dentry`` and current ``seq`` number are passed to
``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a
new ``seq`` number. ``lookup_fast()`` then copies the inode pointer and
revalidates the new ``seq`` number. It then validates the old ``dentry``
with the old ``seq`` number one last time and only then continues. This
process of getting the ``seq`` number of the new dentry and then
checking the ``seq`` number of the old exactly mirrors the process of
getting a counted reference to the new dentry before dropping that for
the old dentry which we saw in REF-walk.
No ``inode->i_rwsem`` or even ``rename_lock``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A semaphore is a fairly heavyweight lock that can only be taken when it is
permissible to sleep. As ``rcu_read_lock()`` forbids sleeping,
``inode->i_rwsem`` plays no role in RCU-walk. If some other thread does
take ``i_rwsem`` and modifies the directory in a way that RCU-walk needs
to notice, the result will be either that RCU-walk fails to find the
dentry that it is looking for, or it will find a dentry which
``read_seqretry()`` won't validate. In either case it will drop down to
REF-walk mode which can take whatever locks are needed.
Though ``rename_lock`` could be used by RCU-walk as it doesn't require
any sleeping, RCU-walk doesn't bother. REF-walk uses ``rename_lock`` to
protect against the possibility of hash chains in the dcache changing
while they are being searched. This can result in failing to find
something that actually is there. When RCU-walk fails to find
something in the dentry cache, whether it is really there or not, it
already drops down to REF-walk and tries again with appropriate
locking. This neatly handles all cases, so adding extra checks on
rename_lock would bring no significant value.
``unlazy walk()`` and ``complete_walk()``
-----------------------------------------
That "dropping down to REF-walk" typically involves a call to
``unlazy_walk()``, so named because "RCU-walk" is also sometimes
referred to as "lazy walk". ``unlazy_walk()`` is called when
following the path down to the current vfsmount/dentry pair seems to
have proceeded successfully, but the next step is problematic. This
can happen if the next name cannot be found in the dcache, if
permission checking or name revalidation couldn't be achieved while
the ``rcu_read_lock()`` is held (which forbids sleeping), if an
automount point is found, or in a couple of cases involving symlinks.
It is also called from ``complete_walk()`` when the lookup has reached
the final component, or the very end of the path, depending on which
particular flavor of lookup is used.
Other reasons for dropping out of RCU-walk that do not trigger a call
to ``unlazy_walk()`` are when some inconsistency is found that cannot be
handled immediately, such as ``mount_lock`` or one of the ``d_seq``
seqlocks reporting a change. In these cases the relevant function
will return ``-ECHILD`` which will percolate up until it triggers a new
attempt from the top using REF-walk.
For those cases where ``unlazy_walk()`` is an option, it essentially
takes a reference on each of the pointers that it holds (vfsmount,
dentry, and possibly some symbolic links) and then verifies that the
relevant seqlocks have not been changed. If there have been changes,
it, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk
has been a success and the lookup process continues.
Taking a reference on those pointers is not quite as simple as just
incrementing a counter. That works to take a second reference if you
already have one (often indirectly through another object), but it
isn't sufficient if you don't actually have a counted reference at
all. For ``dentry->d_lockref``, it is safe to increment the reference
counter to get a reference unless it has been explicitly marked as
"dead" which involves setting the counter to ``-128``.
``lockref_get_not_dead()`` achieves this.
For ``mnt->mnt_count`` it is safe to take a reference as long as
``mount_lock`` is then used to validate the reference. If that
validation fails, it may *not* be safe to just drop that reference in
the standard way of calling ``mnt_put()`` - an unmount may have
progressed too far. So the code in ``legitimize_mnt()``, when it
finds that the reference it got might not be safe, checks the
``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is
correct, or if it should just decrement the count and pretend none of
this ever happened.
Taking care in filesystems
--------------------------
RCU-walk depends almost entirely on cached information and often will
not call into the filesystem at all. However there are two places,
besides the already-mentioned component-name comparison, where the
file system might be included in RCU-walk, and it must know to be
careful.
If the filesystem has non-standard permission-checking requirements -
such as a networked filesystem which may need to check with the server
- the ``i_op->permission`` interface might be called during RCU-walk.
In this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it
knows not to sleep, but to return ``-ECHILD`` if it cannot complete
promptly. ``i_op->permission`` is given the inode pointer, not the
dentry, so it doesn't need to worry about further consistency checks.
However if it accesses any other filesystem data structures, it must
ensure they are safe to be accessed with only the ``rcu_read_lock()``
held. This typically means they must be freed using ``kfree_rcu()`` or
similar.
.. _READ_ONCE: https://lwn.net/Articles/624126/
If the filesystem may need to revalidate dcache entries, then
``d_op->d_revalidate`` may be called in RCU-walk too. This interface
*is* passed the dentry but does not have access to the ``inode`` or the
``seq`` number from the ``nameidata``, so it needs to be extra careful
when accessing fields in the dentry. This "extra care" typically
involves using `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the
result is not NULL before using it. This pattern can be seen in
``nfs_lookup_revalidate()``.
A pair of patterns
------------------
In various places in the details of REF-walk and RCU-walk, and also in
the big picture, there are a couple of related patterns that are worth
being aware of.
The first is "try quickly and check, if that fails try slowly". We
can see that in the high-level approach of first trying RCU-walk and
then trying REF-walk, and in places where ``unlazy_walk()`` is used to
switch to REF-walk for the rest of the path. We also saw it earlier
in ``dget_parent()`` when following a "``..``" link. It tries a quick way
to get a reference, then falls back to taking locks if needed.
The second pattern is "try quickly and check, if that fails try
again - repeatedly". This is seen with the use of ``rename_lock`` and
``mount_lock`` in REF-walk. RCU-walk doesn't make use of this pattern -
if anything goes wrong it is much safer to just abort and try a more
sedate approach.
The emphasis here is "try quickly and check". It should probably be
"try quickly *and carefully*, then check". The fact that checking is
needed is a reminder that the system is dynamic and only a limited
number of things are safe at all. The most likely cause of errors in
this whole process is assuming something is safe when in reality it
isn't. Careful consideration of what exactly guarantees the safety of
each access is sometimes necessary.
A walk among the symlinks
=========================
There are several basic issues that we will examine to understand the
handling of symbolic links: the symlink stack, together with cache
lifetimes, will help us understand the overall recursive handling of
symlinks and lead to the special care needed for the final component.
Then a consideration of access-time updates and summary of the various
flags controlling lookup will finish the story.
The symlink stack
-----------------
There are only two sorts of filesystem objects that can usefully
appear in a path prior to the final component: directories and symlinks.
Handling directories is quite straightforward: the new directory
simply becomes the starting point at which to interpret the next
component on the path. Handling symbolic links requires a bit more
work.
Conceptually, symbolic links could be handled by editing the path. If
a component name refers to a symbolic link, then that component is
replaced by the body of the link and, if that body starts with a '/',
then all preceding parts of the path are discarded. This is what the
"``readlink -f``" command does, though it also edits out "``.``" and
"``..``" components.
Directly editing the path string is not really necessary when looking
up a path, and discarding early components is pointless as they aren't
looked at anyway. Keeping track of all remaining components is
important, but they can of course be kept separately; there is no need
to concatenate them. As one symlink may easily refer to another,
which in turn can refer to a third, we may need to keep the remaining
components of several paths, each to be processed when the preceding
ones are completed. These path remnants are kept on a stack of
limited size.
There are two reasons for placing limits on how many symlinks can
occur in a single path lookup. The most obvious is to avoid loops.
If a symlink referred to itself either directly or through
intermediaries, then following the symlink can never complete
successfully - the error ``ELOOP`` must be returned. Loops can be
detected without imposing limits, but limits are the simplest solution
and, given the second reason for restriction, quite sufficient.
.. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550
The second reason was `outlined recently`_ by Linus:
Because it's a latency and DoS issue too. We need to react well to
true loops, but also to "very deep" non-loops. It's not about memory
use, it's about users triggering unreasonable CPU resources.
Linux imposes a limit on the length of any pathname: ``PATH_MAX``, which
is 4096. There are a number of reasons for this limit; not letting the
kernel spend too much time on just one path is one of them. With
symbolic links you can effectively generate much longer paths so some
sort of limit is needed for the same reason. Linux imposes a limit of
at most 40 (MAXSYMLINKS) symlinks in any one path lookup. It previously imposed
a further limit of eight on the maximum depth of recursion, but that was
raised to 40 when a separate stack was implemented, so there is now
just the one limit.
The ``nameidata`` structure that we met in an earlier article contains a
small stack that can be used to store the remaining part of up to two
symlinks. In many cases this will be sufficient. If it isn't, a
separate stack is allocated with room for 40 symlinks. Pathname
lookup will never exceed that stack as, once the 40th symlink is
detected, an error is returned.
It might seem that the name remnants are all that needs to be stored on
this stack, but we need a bit more. To see that, we need to move on to
cache lifetimes.
Storage and lifetime of cached symlinks
---------------------------------------
Like other filesystem resources, such as inodes and directory
entries, symlinks are cached by Linux to avoid repeated costly access
to external storage. It is particularly important for RCU-walk to be
able to find and temporarily hold onto these cached entries, so that
it doesn't need to drop down into REF-walk.
.. _object-oriented design pattern: https://lwn.net/Articles/446317/
While each filesystem is free to make its own choice, symlinks are
typically stored in one of two places. Short symlinks are often
stored directly in the inode. When a filesystem allocates a ``struct
inode`` it typically allocates extra space to store private data (a
common `object-oriented design pattern`_ in the kernel). This will
sometimes include space for a symlink. The other common location is
in the page cache, which normally stores the content of files. The
pathname in a symlink can be seen as the content of that symlink and
can easily be stored in the page cache just like file content.
When neither of these is suitable, the next most likely scenario is
that the filesystem will allocate some temporary memory and copy or
construct the symlink content into that memory whenever it is needed.
When the symlink is stored in the inode, it has the same lifetime as
the inode which, itself, is protected by RCU or by a counted reference
on the dentry. This means that the mechanisms that pathname lookup
uses to access the dcache and icache (inode cache) safely are quite
sufficient for accessing some cached symlinks safely. In these cases,
the ``i_link`` pointer in the inode is set to point to wherever the
symlink is stored and it can be accessed directly whenever needed.
When the symlink is stored in the page cache or elsewhere, the
situation is not so straightforward. A reference on a dentry or even
on an inode does not imply any reference on cached pages of that
inode, and even an ``rcu_read_lock()`` is not sufficient to ensure that
a page will not disappear. So for these symlinks the pathname lookup
code needs to ask the filesystem to provide a stable reference and,
significantly, needs to release that reference when it is finished
with it.
Taking a reference to a cache page is often possible even in RCU-walk
mode. It does require making changes to memory, which is best avoided,
but that isn't necessarily a big cost and it is better than dropping
out of RCU-walk mode completely. Even filesystems that allocate
space to copy the symlink into can use ``GFP_ATOMIC`` to often successfully
allocate memory without the need to drop out of RCU-walk. If a
filesystem cannot successfully get a reference in RCU-walk mode, it
must return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to
REF-walk mode in which the filesystem is allowed to sleep.
The place for all this to happen is the ``i_op->get_link()`` inode
method. This is called both in RCU-walk and REF-walk. In RCU-walk the
``dentry*`` argument is NULL, ``->get_link()`` can return -ECHILD to drop out of
RCU-walk. Much like the ``i_op->permission()`` method we
looked at previously, ``->get_link()`` would need to be careful that
all the data structures it references are safe to be accessed while
holding no counted reference, only the RCU lock. A callback
``struct delayed_called`` will be passed to ``->get_link()``:
file systems can set their own put_link function and argument through
set_delayed_call(). Later on, when VFS wants to put link, it will call
do_delayed_call() to invoke that callback function with the argument.
In order for the reference to each symlink to be dropped when the walk completes,
whether in RCU-walk or REF-walk, the symlink stack needs to contain,
along with the path remnants:
- the ``struct path`` to provide a reference to the previous path
- the ``const char *`` to provide a reference to the to previous name
- the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk
- the ``struct delayed_call`` for later invocation.
This means that each entry in the symlink stack needs to hold five
pointers and an integer instead of just one pointer (the path
remnant). On a 64-bit system, this is about 40 bytes per entry;
with 40 entries it adds up to 1600 bytes total, which is less than
half a page. So it might seem like a lot, but is by no means
excessive.
Note that, in a given stack frame, the path remnant (``name``) is not
part of the symlink that the other fields refer to. It is the remnant
to be followed once that symlink has been fully parsed.
Following the symlink
---------------------
The main loop in ``link_path_walk()`` iterates seamlessly over all
components in the path and all of the non-final symlinks. As symlinks
are processed, the ``name`` pointer is adjusted to point to a new
symlink, or is restored from the stack, so that much of the loop
doesn't need to notice. Getting this ``name`` variable on and off the
stack is very straightforward; pushing and popping the references is
a little more complex.
When a symlink is found, walk_component() calls pick_link() via step_into()
which returns the link from the filesystem.
Providing that operation is successful, the old path ``name`` is placed on the
stack, and the new value is used as the ``name`` for a while. When the end of
the path is found (i.e. ``*name`` is ``'\0'``) the old ``name`` is restored
off the stack and path walking continues.
Pushing and popping the reference pointers (inode, cookie, etc.) is more
complex in part because of the desire to handle tail recursion. When
the last component of a symlink itself points to a symlink, we
want to pop the symlink-just-completed off the stack before pushing
the symlink-just-found to avoid leaving empty path remnants that would
just get in the way.
It is most convenient to push the new symlink references onto the
stack in ``walk_component()`` immediately when the symlink is found;
``walk_component()`` is also the last piece of code that needs to look at the
old symlink as it walks that last component. So it is quite
convenient for ``walk_component()`` to release the old symlink and pop
the references just before pushing the reference information for the
new symlink. It is guided in this by three flags: ``WALK_NOFOLLOW`` which
forbids it from following a symlink if it finds one, ``WALK_MORE``
which indicates that it is yet too early to release the
current symlink, and ``WALK_TRAILING`` which indicates that it is on the final
component of the lookup, so we will check userspace flag ``LOOKUP_FOLLOW`` to
decide whether follow it when it is a symlink and call ``may_follow_link()`` to
check if we have privilege to follow it.
Symlinks with no final component
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A pair of special-case symlinks deserve a little further explanation.
Both result in a new ``struct path`` (with mount and dentry) being set
up in the ``nameidata``, and result in pick_link() returning ``NULL``.
The more obvious case is a symlink to "``/``". All symlinks starting
with "``/``" are detected in pick_link() which resets the ``nameidata``
to point to the effective filesystem root. If the symlink only
contains "``/``" then there is nothing more to do, no components at all,
so ``NULL`` is returned to indicate that the symlink can be released and
the stack frame discarded.
The other case involves things in ``/proc`` that look like symlinks but
aren't really (and are therefore commonly referred to as "magic-links")::
$ ls -l /proc/self/fd/1
lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4
Every open file descriptor in any process is represented in ``/proc`` by
something that looks like a symlink. It is really a reference to the
target file, not just the name of it. When you ``readlink`` these
objects you get a name that might refer to the same file - unless it
has been unlinked or mounted over. When ``walk_component()`` follows
one of these, the ``->get_link()`` method in "procfs" doesn't return
a string name, but instead calls nd_jump_link() which updates the
``nameidata`` in place to point to that target. ``->get_link()`` then
returns ``NULL``. Again there is no final component and pick_link()
returns ``NULL``.
Following the symlink in the final component
--------------------------------------------
All this leads to ``link_path_walk()`` walking down every component, and
following all symbolic links it finds, until it reaches the final
component. This is just returned in the ``last`` field of ``nameidata``.
For some callers, this is all they need; they want to create that
``last`` name if it doesn't exist or give an error if it does. Other
callers will want to follow a symlink if one is found, and possibly
apply special handling to the last component of that symlink, rather
than just the last component of the original file name. These callers
potentially need to call ``link_path_walk()`` again and again on
successive symlinks until one is found that doesn't point to another
symlink.
This case is handled by relevant callers of link_path_walk(), such as
path_lookupat(), path_openat() using a loop that calls link_path_walk(),
and then handles the final component by calling open_last_lookups() or
lookup_last(). If it is a symlink that needs to be followed,
open_last_lookups() or lookup_last() will set things up properly and
return the path so that the loop repeats, calling
link_path_walk() again. This could loop as many as 40 times if the last
component of each symlink is another symlink.
Of the various functions that examine the final component,
open_last_lookups() is the most interesting as it works in tandem
with do_open() for opening a file. Part of open_last_lookups() runs
with ``i_rwsem`` held and this part is in a separate function: lookup_open().
Explaining open_last_lookups() and do_open() completely is beyond the scope
of this article, but a few highlights should help those interested in exploring
the code.
1. Rather than just finding the target file, do_open() is used after
open_last_lookup() to open
it. If the file was found in the dcache, then ``vfs_open()`` is used for
this. If not, then ``lookup_open()`` will either call ``atomic_open()`` (if
the filesystem provides it) to combine the final lookup with the open, or
will perform the separate ``i_op->lookup()`` and ``i_op->create()`` steps
directly. In the later case the actual "open" of this newly found or
created file will be performed by vfs_open(), just as if the name
were found in the dcache.
2. vfs_open() can fail with ``-EOPENSTALE`` if the cached information
wasn't quite current enough. If it's in RCU-walk ``-ECHILD`` will be returned
otherwise ``-ESTALE`` is returned. When ``-ESTALE`` is returned, the caller may
retry with ``LOOKUP_REVAL`` flag set.
3. An open with O_CREAT **does** follow a symlink in the final component,
unlike other creation system calls (like ``mkdir``). So the sequence::
ln -s bar /tmp/foo
echo hello > /tmp/foo
will create a file called ``/tmp/bar``. This is not permitted if
``O_EXCL`` is set but otherwise is handled for an O_CREAT open much
like for a non-creating open: lookup_last() or open_last_lookup()
returns a non ``NULL`` value, and link_path_walk() gets called and the
open process continues on the symlink that was found.
Updating the access time
------------------------
We previously said of RCU-walk that it would "take no locks, increment
no counts, leave no footprints." We have since seen that some
"footprints" can be needed when handling symlinks as a counted
reference (or even a memory allocation) may be needed. But these
footprints are best kept to a minimum.
One other place where walking down a symlink can involve leaving
footprints in a way that doesn't affect directories is in updating access times.
In Unix (and Linux) every filesystem object has a "last accessed
time", or "``atime``". Passing through a directory to access a file
within is not considered to be an access for the purposes of
``atime``; only listing the contents of a directory can update its ``atime``.
Symlinks are different it seems. Both reading a symlink (with ``readlink()``)
and looking up a symlink on the way to some other destination can
update the atime on that symlink.
.. _clearest statement: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08
It is not clear why this is the case; POSIX has little to say on the
subject. The `clearest statement`_ is that, if a particular implementation
updates a timestamp in a place not specified by POSIX, this must be
documented "except that any changes caused by pathname resolution need
not be documented". This seems to imply that POSIX doesn't really
care about access-time updates during pathname lookup.
.. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8
An examination of history shows that prior to `Linux 1.3.87`_, the ext2
filesystem, at least, didn't update atime when following a link.
Unfortunately we have no record of why that behavior was changed.
In any case, access time must now be updated and that operation can be
quite complex. Trying to stay in RCU-walk while doing it is best
avoided. Fortunately it is often permitted to skip the ``atime``
update. Because ``atime`` updates cause performance problems in various
areas, Linux supports the ``relatime`` mount option, which generally
limits the updates of ``atime`` to once per day on files that aren't
being changed (and symlinks never change once created). Even without
``relatime``, many filesystems record ``atime`` with a one-second
granularity, so only one update per second is required.
It is easy to test if an ``atime`` update is needed while in RCU-walk
mode and, if it isn't, the update can be skipped and RCU-walk mode
continues. Only when an ``atime`` update is actually required does the
path walk drop down to REF-walk. All of this is handled in the
``get_link()`` function.
A few flags
-----------
A suitable way to wrap up this tour of pathname walking is to list
the various flags that can be stored in the ``nameidata`` to guide the
lookup process. Many of these are only meaningful on the final
component, others reflect the current state of the pathname lookup, and some
apply restrictions to all path components encountered in the path lookup.
And then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with
the others. If this is not set, an empty pathname causes an error
very early on. If it is set, empty pathnames are not considered to be
an error.
Global state flags
~~~~~~~~~~~~~~~~~~
We have already met two global state flags: ``LOOKUP_RCU`` and
``LOOKUP_REVAL``. These select between one of three overall approaches
to lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.
``LOOKUP_PARENT`` indicates that the final component hasn't been reached
yet. This is primarily used to tell the audit subsystem the full
context of a particular access being audited.
``ND_ROOT_PRESET`` indicates that the ``root`` field in the ``nameidata`` was
provided by the caller, so it shouldn't be released when it is no
longer needed.
``ND_JUMPED`` means that the current dentry was chosen not because
it had the right name but for some other reason. This happens when
following "``..``", following a symlink to ``/``, crossing a mount point
or accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic
link"). In this case the filesystem has not been asked to revalidate the
name (with ``d_revalidate()``). In such cases the inode may still need
to be revalidated, so ``d_op->d_weak_revalidate()`` is called if
``ND_JUMPED`` is set when the look completes - which may be at the
final component or, when creating, unlinking, or renaming, at the penultimate component.
Resolution-restriction flags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to allow userspace to protect itself against certain race conditions
and attack scenarios involving changing path components, a series of flags are
available which apply restrictions to all path components encountered during
path lookup. These flags are exposed through ``openat2()``'s ``resolve`` field.
``LOOKUP_NO_SYMLINKS`` blocks all symlink traversals (including magic-links).
This is distinctly different from ``LOOKUP_FOLLOW``, because the latter only
relates to restricting the following of trailing symlinks.
``LOOKUP_NO_MAGICLINKS`` blocks all magic-link traversals. Filesystems must
ensure that they return errors from ``nd_jump_link()``, because that is how
``LOOKUP_NO_MAGICLINKS`` and other magic-link restrictions are implemented.
``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` traversals (this includes both
bind-mounts and ordinary mounts). Note that the ``vfsmount`` which contains the
lookup is determined by the first mountpoint the path lookup reaches --
absolute paths start with the ``vfsmount`` of ``/``, and relative paths start
with the ``dfd``'s ``vfsmount``. Magic-links are only permitted if the
``vfsmount`` of the path is unchanged.
``LOOKUP_BENEATH`` blocks any path components which resolve outside the
starting point of the resolution. This is done by blocking ``nd_jump_root()``
as well as blocking ".." if it would jump outside the starting point.
``rename_lock`` and ``mount_lock`` are used to detect attacks against the
resolution of "..". Magic-links are also blocked.
``LOOKUP_IN_ROOT`` resolves all path components as though the starting point
were the filesystem root. ``nd_jump_root()`` brings the resolution back to
the starting point, and ".." at the starting point will act as a no-op. As with
``LOOKUP_BENEATH``, ``rename_lock`` and ``mount_lock`` are used to detect
attacks against ".." resolution. Magic-links are also blocked.
Final-component flags
~~~~~~~~~~~~~~~~~~~~~
Some of these flags are only set when the final component is being
considered. Others are only checked for when considering that final
component.
``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount
point, then the mount is triggered. Some operations would trigger it
anyway, but operations like ``stat()`` deliberately don't. ``statfs()``
needs to trigger the mount but otherwise behaves a lot like ``stat()``, so
it sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of
"``mount --bind``".
``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for
symlinks. Some system calls set or clear it implicitly, while
others have API flags such as ``AT_SYMLINK_FOLLOW`` and
``UMOUNT_NOFOLLOW`` to control it. Its effect is similar to
``WALK_GET`` that we already met, but it is used in a different way.
``LOOKUP_DIRECTORY`` insists that the final component is a directory.
Various callers set this and it is also set when the final component
is found to be followed by a slash.
Finally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and
``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made
available to the filesystem and particularly the ``->d_revalidate()``
method. A filesystem can choose not to bother revalidating too hard
if it knows that it will be asked to open or create the file soon.
These flags were previously useful for ``->lookup()`` too but with the
introduction of ``->atomic_open()`` they are less relevant there.
End of the road
---------------
Despite its complexity, all this pathname lookup code appears to be
in good shape - various parts are certainly easier to understand now
than even a couple of releases ago. But that doesn't mean it is
"finished". As already mentioned, RCU-walk currently only follows
symlinks that are stored in the inode so, while it handles many ext4
symlinks, it doesn't help with NFS, XFS, or Btrfs. That support
is not likely to be long delayed.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
문서 범위와 분석 방법
1-33이 문서는 LWN의 Linux pathname lookup, RCU-walk, symbolic link 관련 세 글을 바탕으로 Neil Brown이 작성했으며 Al Viro와 Jon Corbet이 도왔습니다. 이후 per-directory parallel name lookup과 `openat2()` resolution restriction flag 같은 커널 변경을 반영했습니다.
Pathname lookup은 규칙, 예외, 구현 선택지가 결합되어 복잡합니다. 문서는 divide and conquer 방식으로 문제를 나눕니다. 먼저 symlink를 마지막까지 분리하고, VFS locking 방식에 따라 counted reference와 lock을 쓰는 REF-walk와 RCU 기반 RCU-walk를 별도로 분석한 뒤 다시 결합합니다.
저수준 path 구분부터 REF-walk·RCU-walk와 symlink로 범위를 확장합니다.
===============
Pathname lookup
===============
This write-up is based on three articles published at lwn.net:
- <https://lwn.net/Articles/649115/> Pathname lookup in Linux
- <https://lwn.net/Articles/649729/> RCU-walk: faster pathname lookup in Linux
- <https://lwn.net/Articles/650786/> A walk among the symlinks
Written by Neil Brown with help from Al Viro and Jon Corbet.
It has subsequently been updated to reflect changes in the kernel
including:
- per-directory parallel name lookup.
- ``openat2()`` resolution restriction flags.
Introduction to pathname lookup
===============================
The most obvious aspect of pathname lookup, which very little
exploration is needed to discover, is that it is complex. There are
many rules, special cases, and implementation alternatives that all
combine to confuse the unwary reader. Computer science has long been
acquainted with such complexity and has tools to help manage it. One
tool that we will make extensive use of is "divide and conquer". For
the early parts of the analysis we will divide off symlinks - leaving
them until the final part. Well before we get to symlinks we have
another major division based on the VFS's approach to locking which
will allow us to review "REF-walk" and "RCU-walk" separately. But we
are getting ahead of ourselves. There are some important low level
distinctions we need to clarify first.
Path의 두 요소와 final component
34-104Pathname은 하나 이상의 `/`로 이루어진 slash와 `/`가 아닌 하나 이상의 문자로 이루어진 component 두 종류의 요소를 가집니다. Slash로 시작하는 absolute path는 filesystem root에서, 나머지 relative path는 current directory 또는 `openat()` 같은 `*at()` system call에 전달한 file descriptor 위치에서 시작합니다.
Relative path가 항상 component로 시작하는 것은 아닙니다. Slash와 component가 모두 없는 empty pathname도 있습니다. POSIX는 일반적으로 이를 금지하지만 Linux의 일부 `*at()` call은 `AT_EMPTY_PATH`를 허용합니다. 예를 들어 executable file descriptor, empty path, `AT_EMPTY_PATH`를 `execveat()`에 전달해 실행할 수 있습니다.
Path는 final component와 그 앞의 everything else로 나뉩니다. 앞부분은 반드시 이미 존재하는 directory를 식별해야 하며 그렇지 않으면 `ENOENT` 또는 `ENOTDIR`입니다. Final component는 system call에 따라 생성할 수도 있고 기존 객체여야 할 수도 있으며, empty path나 slash뿐인 path에는 존재하지 않습니다. `.`과 `..`도 일반 component와 다르게 처리합니다.
`/tmp/foo/`처럼 trailing slash가 있는 path를 empty final component로만 보면 일부는 맞지만 `mkdir()`과 `rmdir()` 규칙을 설명하지 못합니다. POSIX는 slash가 아닌 문자를 포함하고 trailing slash로 끝나는 path가 성공하려면 마지막 component가 기존 directory이거나 resolution 직후 생성할 directory entry여야 한다고 규정합니다.
시작점과 final component의 의미가 lookup 동작을 바꿉니다.
주로 `fs/namei.c`에 있는 Linux pathname walking code는 component 분해, 앞부분과 final component 분리, trailing slash 검사를 모두 처리하고 concurrent access도 방어합니다.
예를 들어 한 process가 `a/b/..`를 lookup하는 동안 다른 process가 `a/b`를 `a/c/b`로 rename하면 첫 process가 `a/c`로 resolve될 수 있습니다. 실제 race는 보통 더 미묘하며 dcache를 이해해야 손상을 막는 lookup 규칙을 이해할 수 있습니다.
앞부분은 directory로 걷고 final component는 호출자가 목적에 맞게 처리합니다.
There are two sorts of ...
--------------------------
.. _openat: http://man7.org/linux/man-pages/man2/openat.2.html
Pathnames (sometimes "file names"), used to identify objects in the
filesystem, will be familiar to most readers. They contain two sorts
of elements: "slashes" that are sequences of one or more "``/``"
characters, and "components" that are sequences of one or more
non-"``/``" characters. These form two kinds of paths. Those that
start with slashes are "absolute" and start from the filesystem root.
The others are "relative" and start from the current directory, or
from some other location specified by a file descriptor given to
"``*at()``" system calls such as `openat() <openat_>`_.
.. _execveat: http://man7.org/linux/man-pages/man2/execveat.2.html
It is tempting to describe the second kind as starting with a
component, but that isn't always accurate: a pathname can lack both
slashes and components, it can be empty, in other words. This is
generally forbidden in POSIX, but some of those "``*at()``" system calls
in Linux permit it when the ``AT_EMPTY_PATH`` flag is given. For
example, if you have an open file descriptor on an executable file you
can execute it by calling `execveat() <execveat_>`_ passing
the file descriptor, an empty path, and the ``AT_EMPTY_PATH`` flag.
These paths can be divided into two sections: the final component and
everything else. The "everything else" is the easy bit. In all cases
it must identify a directory that already exists, otherwise an error
such as ``ENOENT`` or ``ENOTDIR`` will be reported.
The final component is not so simple. Not only do different system
calls interpret it quite differently (e.g. some create it, some do
not), but it might not even exist: neither the empty pathname nor the
pathname that is just slashes have a final component. If it does
exist, it could be "``.``" or "``..``" which are handled quite differently
from other components.
.. _POSIX: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
If a pathname ends with a slash, such as "``/tmp/foo/``" it might be
tempting to consider that to have an empty final component. In many
ways that would lead to correct results, but not always. In
particular, ``mkdir()`` and ``rmdir()`` each create or remove a directory named
by the final component, and they are required to work with pathnames
ending in "``/``". According to POSIX_:
A pathname that contains at least one non-<slash> character and
that ends with one or more trailing <slash> characters shall not
be resolved successfully unless the last pathname component before
the trailing <slash> characters names an existing directory or a
directory entry that is to be created for a directory immediately
after the pathname is resolved.
The Linux pathname walking code (mostly in ``fs/namei.c``) deals with
all of these issues: breaking the path into components, handling the
"everything else" quite separately from the final component, and
checking that the trailing slash is not used where it isn't
permitted. It also addresses the important issue of concurrent
access.
While one process is looking up a pathname, another might be making
changes that affect that lookup. One fairly extreme case is that if
"a/b" were renamed to "a/c/b" while another process were looking up
"a/b/..", that process might successfully resolve on "a/c".
Most races are much more subtle, and a big part of the task of
pathname lookup is to prevent them from having damaging effects. Many
of the possible races are seen most clearly in the context of the
"dcache" and an understanding of that is central to understanding
pathname lookup.
dcache의 구조와 두 파일시스템 유형
105-141dcache는 각 파일시스템의 이름 정보를 cache하여 lookup을 빠르게 합니다. 각 dentry에는 component name, parent dentry pointer, 해당 이름의 객체 정보를 가진 inode pointer가 있습니다. `d_inode == NULL`인 negative dentry는 parent에 그 이름이 없음을 나타냅니다. Directory dentry와 child dentry의 별도 연결은 pathname lookup에 쓰지 않으므로 여기서는 다루지 않습니다.
dcache는 속도 외에도 mount table과 밀접하게 통합됩니다. Mount table은 어떤 dentry 위에 다른 어떤 dentry가 mount되었는지를 기록합니다.
Local filesystem인 ext3, XFS, Btrfs 등은 dcache 정보가 완전하지 않을 수는 있어도 들어 있는 정보는 항상 정확하도록 보장합니다. VFS는 filesystem에 다시 묻지 않고 존재 여부를 판단하고 일부 race를 방어할 수 있습니다.
NFS·9P 같은 remote filesystem과 ocfs2·cephfs 같은 cluster filesystem은 다른 노드의 변경 때문에 정확성을 보장할 수 없습니다. 이들은 VFS가 cache를 revalidate하게 하고 스스로 복잡한 race를 방어해야 합니다. VFS는 dentry의 `DCACHE_OP_REVALIDATE` flag로 이런 filesystem을 식별합니다.
Path component를 parent와 inode에 연결하는 dcache 단위입니다.
파일시스템 유형에 따라 VFS의 cache 신뢰 방식이 다릅니다.
More than just a cache
----------------------
The "dcache" caches information about names in each filesystem to
make them quickly available for lookup. Each entry (known as a
"dentry") contains three significant fields: a component name, a
pointer to a parent dentry, and a pointer to the "inode" which
contains further information about the object in that parent with
the given name. The inode pointer can be ``NULL`` indicating that the
name doesn't exist in the parent. While there can be linkage in the
dentry of a directory to the dentries of the children, that linkage is
not used for pathname lookup, and so will not be considered here.
The dcache has a number of uses apart from accelerating lookup. One
that will be particularly relevant is that it is closely integrated
with the mount table that records which filesystem is mounted where.
What the mount table actually stores is which dentry is mounted on top
of which other dentry.
When considering the dcache, we have another of our "two types"
distinctions: there are two types of filesystems.
Some filesystems ensure that the information in the dcache is always
completely accurate (though not necessarily complete). This can allow
the VFS to determine if a particular file does or doesn't exist
without checking with the filesystem, and means that the VFS can
protect the filesystem against certain races and other problems.
These are typically "local" filesystems such as ext3, XFS, and Btrfs.
Other filesystems don't provide that guarantee because they cannot.
These are typically filesystems that are shared across a network,
whether remote filesystems like NFS and 9P, or cluster filesystems
like ocfs2 or cephfs. These filesystems allow the VFS to revalidate
cached information, and must provide their own protection against
awkward races. The VFS can detect these filesystems by the
``DCACHE_OP_REVALIDATE`` flag being set in the dentry.
REF-walk와 d_lockref
142-195REF-walk는 pathname의 final component 전까지를 걷는 `link_path_walk()`에서 사용하며 `LOOKUP_RCU`가 설정된 RCU 전용 분기를 제외한 경로입니다. Lock과 reference count를 적극적으로 사용해 concurrent modification을 관리합니다.
`dentry->d_lockref`는 lockref primitive로 spinlock과 reference count를 함께 제공합니다. 개념적인 `lock; inc_ref; unlock;` 연속 동작을 흔히 하나의 atomic memory operation으로 처리할 수 있습니다.
Dentry reference를 보유하면 dentry가 갑자기 해제되어 다른 용도로 재사용되지 않으므로 field 값을 안정적으로 읽을 수 있고 `->d_inode` reference도 어느 정도 보호됩니다. Dentry와 inode의 연결은 매우 안정적입니다. Rename 때 둘이 함께 이동하고 create 때 negative dentry의 `d_inode`가 새 inode로 설정됩니다.
Delete는 `d_inode = NULL`로 만들거나 parent의 이름 hash table에서 dentry를 제거하는 방식으로 cache에 반영합니다. Dentry가 사용 중이면 open file은 delete 뒤에도 합법적으로 사용할 수 있으므로 hash에서만 제거합니다. 다른 사용이 없고 `d_lockref` refcount가 1일 때만 `d_inode`를 `NULL`로 만듭니다.
따라서 counted dentry reference를 가진 동안 non-NULL `->d_inode`는 바뀌지 않습니다.
Reference 유무에 따라 delete가 연결을 보존하거나 negative dentry로 바꿉니다.
REF-walk: simple concurrency management with refcounts and spinlocks
--------------------------------------------------------------------
With all of those divisions carefully classified, we can now start
looking at the actual process of walking along a path. In particular
we will start with the handling of the "everything else" part of a
pathname, and focus on the "REF-walk" approach to concurrency
management. This code is found in the ``link_path_walk()`` function, if
you ignore all the places that only run when "``LOOKUP_RCU``"
(indicating the use of RCU-walk) is set.
.. _Meet the Lockers: https://lwn.net/Articles/453685/
REF-walk is fairly heavy-handed with locks and reference counts. Not
as heavy-handed as in the old "big kernel lock" days, but certainly not
afraid of taking a lock when one is needed. It uses a variety of
different concurrency controls. A background understanding of the
various primitives is assumed, or can be gleaned from elsewhere such
as in `Meet the Lockers`_.
The locking mechanisms used by REF-walk include:
dentry->d_lockref
~~~~~~~~~~~~~~~~~
This uses the lockref primitive to provide both a spinlock and a
reference count. The special-sauce of this primitive is that the
conceptual sequence "lock; inc_ref; unlock;" can often be performed
with a single atomic memory operation.
Holding a reference on a dentry ensures that the dentry won't suddenly
be freed and used for something else, so the values in various fields
will behave as expected. It also protects the ``->d_inode`` reference
to the inode to some extent.
The association between a dentry and its inode is fairly permanent.
For example, when a file is renamed, the dentry and inode move
together to the new location. When a file is created the dentry will
initially be negative (i.e. ``d_inode`` is ``NULL``), and will be assigned
to the new inode as part of the act of creation.
When a file is deleted, this can be reflected in the cache either by
setting ``d_inode`` to ``NULL``, or by removing it from the hash table
(described shortly) used to look up the name in the parent directory.
If the dentry is still in use the second option is used as it is
perfectly legal to keep using an open file after it has been deleted
and having the dentry around helps. If the dentry is not otherwise in
use (i.e. if the refcount in ``d_lockref`` is one), only then will
``d_inode`` be set to ``NULL``. Doing it this way is more efficient for a
very common case.
So as long as a counted reference is held to a dentry, a non-``NULL`` ``->d_inode``
value will never be changed.
d_lock과 rename_lock
196-245`d_lock`은 `d_lockref` 안의 spinlock과 같은 lock입니다. 이를 보유하면 dentry가 rename 또는 unlink되지 않으므로 `d_parent`, `d_name`, dentry hash table membership이 안정됩니다.
Directory에서 이름을 찾을 때 REF-walk는 hash table의 각 candidate child dentry에 `d_lock`을 잡고 parent와 name이 맞는지 검사합니다. Parent를 lock한 채 cache를 검색하는 것이 아니라 child만 잠급니다.
`..` 처리를 위해 parent를 찾을 때는 `d_lock`으로 `d_parent`를 안정화할 수 있지만 `dget_parent()`는 먼저 가벼운 방법을 시도합니다. Parent reference를 얻은 뒤 `d_parent`가 변하지 않았음을 확인할 수 있으면 child lock이 필요 없습니다.
이름 lookup은 directory dentry와 name의 hash로 bucket을 고르고 linked list를 검색합니다. Rename은 name과 parent를 바꿔 다른 hash chain으로 dentry를 이동할 수 있습니다. 검색 중인 dentry가 이동하면 잘못된 chain을 계속 따라가 올바른 일부를 놓칠 수 있습니다.
`d_lookup()`은 이동을 막지 않고 감지합니다. 모든 dentry rename 때 갱신되는 seqlock `rename_lock`을 읽고, 실패한 chain scan 중 rename이 있었다면 lookup을 다시 시도합니다.
`rename_lock`은 `LOOKUP_BENEATH`와 `LOOKUP_IN_ROOT` 아래에서 `..` resolution 공격도 방어합니다. Parent를 root 밖으로 옮겨 `path_equal()` 검사를 우회하려는 동안 lock sequence가 변하고 path가 `..`을 만나면 `handle_dots()`가 `-EAGAIN`으로 중단합니다.
한 이름의 안정성과 전체 rename 감지를 서로 다른 lock이 담당합니다.
dentry->d_lock
~~~~~~~~~~~~~~
``d_lock`` is a synonym for the spinlock that is part of ``d_lockref`` above.
For our purposes, holding this lock protects against the dentry being
renamed or unlinked. In particular, its parent (``d_parent``), and its
name (``d_name``) cannot be changed, and it cannot be removed from the
dentry hash table.
When looking for a name in a directory, REF-walk takes ``d_lock`` on
each candidate dentry that it finds in the hash table and then checks
that the parent and name are correct. So it doesn't lock the parent
while searching in the cache; it only locks children.
When looking for the parent for a given name (to handle "``..``"),
REF-walk can take ``d_lock`` to get a stable reference to ``d_parent``,
but it first tries a more lightweight approach. As seen in
``dget_parent()``, if a reference can be claimed on the parent, and if
subsequently ``d_parent`` can be seen to have not changed, then there is
no need to actually take the lock on the child.
rename_lock
~~~~~~~~~~~
Looking up a given name in a given directory involves computing a hash
from the two values (the name and the dentry of the directory),
accessing that slot in a hash table, and searching the linked list
that is found there.
When a dentry is renamed, the name and the parent dentry can both
change so the hash will almost certainly change too. This would move the
dentry to a different chain in the hash table. If a filename search
happened to be looking at a dentry that was moved in this way,
it might end up continuing the search down the wrong chain,
and so miss out on part of the correct chain.
The name-lookup process (``d_lookup()``) does *not* try to prevent this
from happening, but only to detect when it happens.
``rename_lock`` is a seqlock that is updated whenever any dentry is
renamed. If ``d_lookup`` finds that a rename happened while it
unsuccessfully scanned a chain in the hash table, it simply tries
again.
``rename_lock`` is also used to detect and defend against potential attacks
against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
the parent directory is moved outside the root, bypassing the ``path_equal()``
check). If ``rename_lock`` is updated during the lookup and the path encounters
a "..", a potential attack occurred and ``handle_dots()`` will bail out with
``-EAGAIN``.
i_rwsem과 병렬 이름 lookup
246-320`inode->i_rwsem`은 특정 directory의 모든 변경을 직렬화하는 read/write semaphore입니다. `unlink()`와 `rename()`의 동시 수행을 막고, dcache에 없는 이름을 filesystem에 lookup하거나 선택적으로 `readdir()` entry 목록을 읽는 동안 directory를 안정화합니다.
Directory `i_rwsem`은 그 directory의 모든 이름을 보호하고 dentry `d_lock`은 이름 하나만 보호합니다. 대부분의 dcache 변경은 directory inode의 `i_rwsem`을 가진 상태에서 관련 dentry의 `d_lock`을 잠깐 잡습니다. Memory pressure로 idle dentry를 제거할 때는 `d_lock`만 사용합니다.
`walk_component()`는 먼저 `lookup_fast()`로 `d_lock`만 사용해 cache를 검사합니다. 없으면 `lookup_slow()`가 `i_rwsem` shared lock을 잡고 cache를 다시 검사한 뒤 filesystem에 definitive lookup을 요청합니다. 존재 여부와 관계없이 새 dentry가 cache에 추가됩니다. Final component에서는 필요한 배제를 위해 마지막 lookup 전에 exclusive `i_rwsem`을 잡기도 합니다.
dcache hit는 child lock만 쓰고 miss는 directory semaphore 아래 filesystem에 묻습니다.
Shared `i_rwsem`만으로 두 thread가 같은 cache miss 이름의 dentry를 중복 추가하는 것을 막을 수 없습니다. Secondary `in_lookup_hashtable`과 per-dentry `DCACHE_PAR_LOOKUP` flag가 추가 interlock을 제공합니다.
`d_alloc_parallel()`은 dentry를 할당해 name과 parent를 넣고 primary·secondary hash table에 matching dentry가 있는지 검사합니다. 없으면 새 dentry를 secondary table에 `DCACHE_PAR_LOOKUP`과 함께 넣고 반환합니다. 호출자는 flag로 race 승리를 알고 filesystem lookup을 수행한 뒤 `d_lookup_done()`을 호출해 flag를 지우고 secondary table에서 제거합니다. 전달한 `struct waitqueue_head`가 scope 안에 있을 때 완료해야 합니다.
Primary table에서 match를 찾으면 다른 thread가 먼저 추가했음을 뜻합니다. Secondary에서 찾으면 승자 thread의 `d_lookup_done()`이 wait queue를 깨워 `DCACHE_PAR_LOOKUP`을 지울 때까지 기다립니다. 이후 primary에 들어갔으면 반환하고, 없으면 `d_splice_alias()` 등으로 다른 dentry가 추가된 경우일 수 있으므로 처음부터 lookup을 반복합니다.
Secondary hash와 flag로 같은 이름 lookup의 승자 한 명만 filesystem에 질의합니다.
inode->i_rwsem
~~~~~~~~~~~~~~
``i_rwsem`` is a read/write semaphore that serializes all changes to a particular
directory. This ensures that, for example, an ``unlink()`` and a ``rename()``
cannot both happen at the same time. It also keeps the directory
stable while the filesystem is asked to look up a name that is not
currently in the dcache or, optionally, when the list of entries in a
directory is being retrieved with ``readdir()``.
This has a complementary role to that of ``d_lock``: ``i_rwsem`` on a
directory protects all of the names in that directory, while ``d_lock``
on a name protects just one name in a directory. Most changes to the
dcache hold ``i_rwsem`` on the relevant directory inode and briefly take
``d_lock`` on one or more the dentries while the change happens. One
exception is when idle dentries are removed from the dcache due to
memory pressure. This uses ``d_lock``, but ``i_rwsem`` plays no role.
The semaphore affects pathname lookup in two distinct ways. Firstly it
prevents changes during lookup of a name in a directory. ``walk_component()`` uses
``lookup_fast()`` first which, in turn, checks to see if the name is in the cache,
using only ``d_lock`` locking. If the name isn't found, then ``walk_component()``
falls back to ``lookup_slow()`` which takes a shared lock on ``i_rwsem``, checks again that
the name isn't in the cache, and then calls in to the filesystem to get a
definitive answer. A new dentry will be added to the cache regardless of
the result.
Secondly, when pathname lookup reaches the final component, it will
sometimes need to take an exclusive lock on ``i_rwsem`` before performing the last lookup so
that the required exclusion can be achieved. How path lookup chooses
to take, or not take, ``i_rwsem`` is one of the
issues addressed in a subsequent section.
If two threads attempt to look up the same name at the same time - a
name that is not yet in the dcache - the shared lock on ``i_rwsem`` will
not prevent them both adding new dentries with the same name. As this
would result in confusion an extra level of interlocking is used,
based around a secondary hash table (``in_lookup_hashtable``) and a
per-dentry flag bit (``DCACHE_PAR_LOOKUP``).
To add a new dentry to the cache while only holding a shared lock on
``i_rwsem``, a thread must call ``d_alloc_parallel()``. This allocates a
dentry, stores the required name and parent in it, checks if there
is already a matching dentry in the primary or secondary hash
tables, and if not, stores the newly allocated dentry in the secondary
hash table, with ``DCACHE_PAR_LOOKUP`` set.
If a matching dentry was found in the primary hash table then that is
returned and the caller can know that it lost a race with some other
thread adding the entry. If no matching dentry is found in either
cache, the newly allocated dentry is returned and the caller can
detect this from the presence of ``DCACHE_PAR_LOOKUP``. In this case it
knows that it has won any race and now is responsible for asking the
filesystem to perform the lookup and find the matching inode. When
the lookup is complete, it must call ``d_lookup_done()`` which clears
the flag and does some other house keeping, including removing the
dentry from the secondary hash table - it will normally have been
added to the primary hash table already. Note that a ``struct
waitqueue_head`` is passed to ``d_alloc_parallel()``, and
``d_lookup_done()`` must be called while this ``waitqueue_head`` is still
in scope.
If a matching dentry is found in the secondary hash table,
``d_alloc_parallel()`` has a little more work to do. It first waits for
``DCACHE_PAR_LOOKUP`` to be cleared, using a wait_queue that was passed
to the instance of ``d_alloc_parallel()`` that won the race and that
will be woken by the call to ``d_lookup_done()``. It then checks to see
if the dentry has now been added to the primary hash table. If it
has, the dentry is returned and the caller just sees that it lost any
race. If it hasn't been added to the primary hash table, the most
likely explanation is that some other dentry was added instead using
``d_splice_alias()``. In any case, ``d_alloc_parallel()`` repeats all the
look ups from the start and will normally return something from the
primary hash table.
mnt_count, mount_lock과 RCU
321-375`mnt->mnt_count`는 `mount` 구조체의 per-CPU reference counter입니다. 증가에는 CPU-local memory만 써서 싸지만 0인지 확인하려면 모든 CPU를 봐야 해 비쌉니다. Reference는 일반 unmount로 mount 구조체가 사라지는 것을 막지만 lazy unmount는 막지 못합니다.
따라서 `mnt_count`는 mount가 namespace에 남거나 mounted-on dentry 링크가 안정적임을 보장하지 않습니다. 대신 mount 구조체의 coherence와 mounted filesystem root dentry reference를 보장합니다. 즉 mounted dentry는 안정적이지만 mounted-on dentry는 아닙니다.
`mount_lock`은 `rename_lock`과 비슷한 global seqlock으로 어떤 mount point가 바뀌었는지 감지합니다. Root에서 아래로 mount point를 건널 때 sequence를 읽고 해당 mount를 찾아 `mnt_count`를 증가한 뒤 sequence를 다시 확인합니다. 바뀌지 않았으면 안전하고 바뀌었으면 reference를 줄이고 전체 과정을 재시도합니다.
`..`으로 root 쪽으로 올라갈 때는 mounted-on dentry 링크를 안정화해야 하므로 counter와 spinlock을 포함한 seqlock을 완전히 잠가 모든 mount point 변경을 막습니다.
`mount_lock`도 `LOOKUP_BENEATH`·`LOOKUP_IN_ROOT`의 `..` escape 공격을 감지합니다. Lookup 중 mount sequence가 바뀌고 `..`을 만나면 `handle_dots()`가 `-EAGAIN`을 반환합니다.
Global하지만 매우 가벼운 RCU read lock은 dcache hash chain과 mount point hash table을 스캔할 때 구조체가 예기치 않게 해제되는 것을 막습니다.
구조체 수명, namespace 링크와 hash scan을 서로 다른 기구가 보호합니다.
Seqlock 전후 검증 사이에 mount reference를 얻습니다.
mnt->mnt_count
~~~~~~~~~~~~~~
``mnt_count`` is a per-CPU reference counter on "``mount``" structures.
Per-CPU here means that incrementing the count is cheap as it only
uses CPU-local memory, but checking if the count is zero is expensive as
it needs to check with every CPU. Taking a ``mnt_count`` reference
prevents the mount structure from disappearing as the result of regular
unmount operations, but does not prevent a "lazy" unmount. So holding
``mnt_count`` doesn't ensure that the mount remains in the namespace and,
in particular, doesn't stabilize the link to the mounted-on dentry. It
does, however, ensure that the ``mount`` data structure remains coherent,
and it provides a reference to the root dentry of the mounted
filesystem. So a reference through ``->mnt_count`` provides a stable
reference to the mounted dentry, but not the mounted-on dentry.
mount_lock
~~~~~~~~~~
``mount_lock`` is a global seqlock, a bit like ``rename_lock``. It can be used to
check if any change has been made to any mount points.
While walking down the tree (away from the root) this lock is used when
crossing a mount point to check that the crossing was safe. That is,
the value in the seqlock is read, then the code finds the mount that
is mounted on the current directory, if there is one, and increments
the ``mnt_count``. Finally the value in ``mount_lock`` is checked against
the old value. If there is no change, then the crossing was safe. If there
was a change, the ``mnt_count`` is decremented and the whole process is
retried.
When walking up the tree (towards the root) by following a ".." link,
a little more care is needed. In this case the seqlock (which
contains both a counter and a spinlock) is fully locked to prevent
any changes to any mount points while stepping up. This locking is
needed to stabilize the link to the mounted-on dentry, which the
refcount on the mount itself doesn't ensure.
``mount_lock`` is also used to detect and defend against potential attacks
against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
the parent directory is moved outside the root, bypassing the ``path_equal()``
check). If ``mount_lock`` is updated during the lookup and the path encounters
a "..", a potential attack occurred and ``handle_dots()`` will bail out with
``-EAGAIN``.
RCU
~~~
Finally the global (but extremely lightweight) RCU read lock is held
from time to time to ensure certain data structures don't get freed
unexpectedly.
In particular it is held while scanning chains in the dcache hash
table, and the mount point hash table.
struct nameidata와 component walk
376-467Path walk 상태는 `struct nameidata`에 저장됩니다. `namei`는 name을 inode로 바꾸던 First Edition Unix 함수명에서 유래했습니다.
`struct path path`는 `struct mount` 안에 포함된 `struct vfsmount`와 `struct dentry`로 현재 위치를 기록합니다. 시작점은 cwd, root, 또는 file descriptor가 지정한 directory이며 매 step마다 갱신됩니다. `d_lockref`와 `mnt_count` counted reference를 항상 가집니다.
`struct qstr last`는 길이와 문자열을 함께 가진 다음 component이며 NUL-terminated가 아닙니다. `int last_type`은 `LAST_NORM`, `LAST_ROOT`, `LAST_DOT`, `LAST_DOTDOT` 중 하나이고 `last`는 `LAST_NORM`일 때만 유효합니다.
`struct path root`는 effective filesystem root reference입니다. 필요할 때 처음 설정하거나 non-standard root 요청 때 설정하며, nameidata가 reference를 보유해 path walk 중 `chroot()`와 race해도 하나의 root를 유지합니다.
`LOOKUP_IN_ROOT` 또는 `LOOKUP_BENEATH`에서는 `openat2()`에 전달한 directory fd가 effective root입니다. Path 또는 symlink가 `/`로 시작하거나 `..`을 처리할 때 root가 필요합니다. `..`은 root에서 더 올라갈 수 없습니다. 일반적으로 caller의 current root를 쓰지만 `file_open_root()`와 NFSv4·Btrfs의 `mount_subtree()`는 특정 subtree를 local chroot처럼 alternate root로 제공합니다.
현재 위치, 다음 이름과 effective root를 한 walk 동안 유지합니다.
Symlink를 제외한 `link_path_walk()`은 current directory execute permission을 검사하고 `name`을 component 하나만큼 전진시키며 `last_type`과 `last`를 갱신합니다. Final component면 반환하고 아니면 `walk_component()`를 호출해 반복합니다.
`walk_component()`는 `LAST_DOTS`이면 `handle_dots()`를 호출합니다. `LAST_NORM`이면 dcache만 보는 `lookup_fast()`를 먼저 호출하고 필요한 filesystem은 결과를 revalidate합니다. 좋은 결과가 없으면 `lookup_slow()`가 `i_rwsem`을 잡고 cache를 재확인한 뒤 filesystem에 묻습니다.
마지막에는 `step_into()`가 `handle_mounts()`로 mount point를 처리하고 새 dentry와 vfsmount reference의 `struct path`를 만듭니다. Symlink면 `pick_link()`를 호출하고 아니면 새 path를 nameidata에 설치한 뒤 불필요한 이전 reference를 놓습니다. 새 dentry reference를 먼저 얻고 이전 reference를 버리는 hand-over-hand 순서입니다.
Final component 직전까지 이름을 분리하고 lookup·mount·symlink 처리를 반복합니다.
Bringing it together with ``struct nameidata``
----------------------------------------------
.. _First edition Unix: https://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/u2.s
Throughout the process of walking a path, the current status is stored
in a ``struct nameidata``, "namei" being the traditional name - dating
all the way back to `First Edition Unix`_ - of the function that
converts a "name" to an "inode". ``struct nameidata`` contains (among
other fields):
``struct path path``
~~~~~~~~~~~~~~~~~~~~
A ``path`` contains a ``struct vfsmount`` (which is
embedded in a ``struct mount``) and a ``struct dentry``. Together these
record the current status of the walk. They start out referring to the
starting point (the current working directory, the root directory, or some other
directory identified by a file descriptor), and are updated on each
step. A reference through ``d_lockref`` and ``mnt_count`` is always
held.
``struct qstr last``
~~~~~~~~~~~~~~~~~~~~
This is a string together with a length (i.e. *not* ``nul`` terminated)
that is the "next" component in the pathname.
``int last_type``
~~~~~~~~~~~~~~~~~
This is one of ``LAST_NORM``, ``LAST_ROOT``, ``LAST_DOT`` or ``LAST_DOTDOT``.
The ``last`` field is only valid if the type is ``LAST_NORM``.
``struct path root``
~~~~~~~~~~~~~~~~~~~~
This is used to hold a reference to the effective root of the
filesystem. Often that reference won't be needed, so this field is
only assigned the first time it is used, or when a non-standard root
is requested. Keeping a reference in the ``nameidata`` ensures that
only one root is in effect for the entire path walk, even if it races
with a ``chroot()`` system call.
It should be noted that in the case of ``LOOKUP_IN_ROOT`` or
``LOOKUP_BENEATH``, the effective root becomes the directory file descriptor
passed to ``openat2()`` (which exposes these ``LOOKUP_`` flags).
The root is needed when either of two conditions holds: (1) either the
pathname or a symbolic link starts with a "'/'", or (2) a "``..``"
component is being handled, since "``..``" from the root must always stay
at the root. The value used is usually the current root directory of
the calling process. An alternate root can be provided as when
``sysctl()`` calls ``file_open_root()``, and when NFSv4 or Btrfs call
``mount_subtree()``. In each case a pathname is being looked up in a very
specific part of the filesystem, and the lookup must not be allowed to
escape that subtree. It works a bit like a local ``chroot()``.
Ignoring the handling of symbolic links, we can now describe the
"``link_path_walk()``" function, which handles the lookup of everything
except the final component as:
Given a path (``name``) and a nameidata structure (``nd``), check that the
current directory has execute permission and then advance ``name``
over one component while updating ``last_type`` and ``last``. If that
was the final component, then return, otherwise call
``walk_component()`` and repeat from the top.
``walk_component()`` is even easier. If the component is ``LAST_DOTS``,
it calls ``handle_dots()`` which does the necessary locking as already
described. If it finds a ``LAST_NORM`` component it first calls
"``lookup_fast()``" which only looks in the dcache, but will ask the
filesystem to revalidate the result if it is that sort of filesystem.
If that doesn't get a good result, it calls "``lookup_slow()``" which
takes ``i_rwsem``, rechecks the cache, and then asks the filesystem
to find a definitive answer.
As the last step of walk_component(), step_into() will be called either
directly from walk_component() or from handle_dots(). It calls
handle_mounts(), to check and handle mount points, in which a new
``struct path`` is created containing a counted reference to the new dentry and
a reference to the new ``vfsmount`` which is only counted if it is
different from the previous ``vfsmount``. Then if there is
a symbolic link, step_into() calls pick_link() to deal with it,
otherwise it installs the new ``struct path`` in the ``struct nameidata``, and
drops the unneeded references.
This "hand-over-hand" sequencing of getting a reference to the new
dentry before dropping the reference to the previous dentry may
seem obvious, but is worth pointing out so that we will recognize its
analogue in the "RCU-walk" version.
Final component별 caller
468-513`link_path_walk()`은 final component를 `nd->last`와 `nd->last_type`에 설정할 뿐 마지막 `walk_component()`를 호출하지 않습니다. 서로 다른 system call 요구를 처리하는 `path_lookupat()`, `path_parentat()`, `path_openat()`이 이를 마무리합니다.
`path_parentat()`은 housekeeping과 `link_path_walk()` 뒤 parent directory와 final component를 반환합니다. Caller는 `filename_create()`로 이름을 만들거나 `user_path_parent()`를 사용해 remove·rename하며, `i_rwsem`으로 다른 변경을 배제한 채 검증하고 작업합니다.
`path_lookupat()`은 `stat()`·`chmod()`처럼 existing object를 원할 때 `lookup_last()`를 통해 final `walk_component()`를 호출하고 final dentry를 반환합니다. `LOOKUP_MOUNTPOINT`가 있으면 nameidata의 `LOOKUP_JUMPED`를 지워 뒤 path traversal에서 `d_weak_revalidate()`를 호출하지 않습니다. 죽은 NFS server처럼 접근 불가능한 filesystem을 unmount할 때 중요합니다.
`path_openat()`은 `open()`을 위해 `open_last_lookups()` 지원 함수와 함께 `O_CREAT`, `O_EXCL`, trailing `/`, final symlink를 처리합니다. 발견한 상황에 따라 `i_rwsem`을 잡을 수도 있고 잡지 않을 수도 있습니다.
System call 목적에 따라 parent, existing dentry 또는 open 결과를 만듭니다.
Create 목적에서 `last_type != LAST_NORM`이면 오류입니다. 예를 들어 `LAST_DOTDOT` 이름을 생성하지 않습니다. Caller는 `last.name[last.len]` 뒤 문자를 검사해 trailing slash를 찾습니다.
Handling the final component
----------------------------
``link_path_walk()`` only walks as far as setting ``nd->last`` and
``nd->last_type`` to refer to the final component of the path. It does
not call ``walk_component()`` that last time. Handling that final
component remains for the caller to sort out. Those callers are
path_lookupat(), path_parentat() and
path_openat() each of which handles the differing requirements of
different system calls.
``path_parentat()`` is clearly the simplest - it just wraps a little bit
of housekeeping around ``link_path_walk()`` and returns the parent
directory and final component to the caller. The caller will be either
aiming to create a name (via ``filename_create()``) or remove or rename
a name (in which case ``user_path_parent()`` is used). They will use
``i_rwsem`` to exclude other changes while they validate and then
perform their operation.
``path_lookupat()`` is nearly as simple - it is used when an existing
object is wanted such as by ``stat()`` or ``chmod()``. It essentially just
calls ``walk_component()`` on the final component through a call to
``lookup_last()``. ``path_lookupat()`` returns just the final dentry.
It is worth noting that when flag ``LOOKUP_MOUNTPOINT`` is set,
path_lookupat() will unset LOOKUP_JUMPED in nameidata so that in the
subsequent path traversal d_weak_revalidate() won't be called.
This is important when unmounting a filesystem that is inaccessible, such as
one provided by a dead NFS server.
Finally ``path_openat()`` is used for the ``open()`` system call; it
contains, in support functions starting with "open_last_lookups()", all the
complexity needed to handle the different subtleties of O_CREAT (with
or without O_EXCL), final "``/``" characters, and trailing symbolic
links. We will revisit this in the final part of this series, which
focuses on those symbolic links. "open_last_lookups()" will sometimes, but
not always, take ``i_rwsem``, depending on what it finds.
Each of these, or the functions which call them, need to be alert to
the possibility that the final component is not ``LAST_NORM``. If the
goal of the lookup is to create something, then any value for
``last_type`` other than ``LAST_NORM`` will result in an error. For
example if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller
won't try to create that name. They also check for trailing slashes
by testing ``last.name[last.len]``. If there is any character beyond
the final component, it must be a trailing slash.
Cache revalidation과 automount
514-594Revalidation이 필요한 filesystem에서 lookup routine은 `->d_revalidate()`를 호출해 cache가 최신인지 확인합니다. 흔히 유효성을 확인하거나 server에서 일부 정보를 갱신하지만 path 상위의 변경 때문에 이전 결과가 무효임을 찾을 수도 있습니다. 이 경우 전체 lookup을 중단하고 `LOOKUP_REVAL`로 재시도하여 더 철저히 revalidate합니다.
Automount point는 이름 lookup이 그 위치에 filesystem을 mount하는 등 lookup 방법의 변경을 유발하는 곳입니다. VFS는 세 `dentry->d_flags`로 managed dentry를 처리합니다.
`DCACHE_MANAGE_TRANSIT`이면 mount point를 다루기 전에 `d_manage()`를 호출합니다. Automount point가 unmount 중이면 새 lookup이 다시 automount하지 않도록 완료를 기다릴 수 있습니다. Automount server process가 trigger 없이 directory에 접근해야 할 때 autofs에 자신을 식별하고 `d_manage()`가 `-EISDIR`을 반환해 특별 통과를 허용할 수도 있습니다.
`DCACHE_MOUNTED`는 어떤 namespace에서든 dentry 위에 mount가 있음을 나타냅니다. 현재 namespace에는 없을 수 있어 promise가 아니라 hint입니다. Flag가 있고 `d_manage()`가 `-EISDIR`을 반환하지 않았다면 `lookup_mnt()`가 `mount_lock`을 지키며 mount hash를 보고 counted reference를 가진 새 `vfsmount`와 `dentry`를 반환할 수 있습니다.
`DCACHE_NEED_AUTOMOUNT`는 `d_manage()`가 진행을 허용하고 `lookup_mnt()`가 기존 mount를 찾지 못했을 때 `d_automount()`를 호출합니다. 이 callback은 server process와 통신하는 등 복잡할 수 있으며 오류, mount 없음, 또는 새 dentry와 vfsmount의 `struct path`를 반환합니다. 새 path면 `finish_automount()`가 mount table에 안전하게 설치합니다.
Automount 처리에는 장시간 지연 가능성이 있으므로 lock은 보유하지 않고 counted reference만 유지합니다. 지연에 민감한 RCU-walk에서는 특히 중요합니다.
Transit 제어, 기존 mount 탐색과 새 automount trigger의 순서입니다.
Managed dentry callback과 mount table 설치 순서입니다.
Revalidation and automounts
---------------------------
Apart from symbolic links, there are only two parts of the "REF-walk"
process not yet covered. One is the handling of stale cache entries
and the other is automounts.
On filesystems that require it, the lookup routines will call the
``->d_revalidate()`` dentry method to ensure that the cached information
is current. This will often confirm validity or update a few details
from a server. In some cases it may find that there has been change
further up the path and that something that was thought to be valid
previously isn't really. When this happens the lookup of the whole
path is aborted and retried with the "``LOOKUP_REVAL``" flag set. This
forces revalidation to be more thorough. We will see more details of
this retry process in the next article.
Automount points are locations in the filesystem where an attempt to
lookup a name can trigger changes to how that lookup should be
handled, in particular by mounting a filesystem there. These are
covered in greater detail in autofs.rst in the Linux documentation
tree, but a few notes specifically related to path lookup are in order
here.
The Linux VFS has a concept of "managed" dentries. There are three
potentially interesting things about these dentries corresponding
to three different flags that might be set in ``dentry->d_flags``:
``DCACHE_MANAGE_TRANSIT``
~~~~~~~~~~~~~~~~~~~~~~~~~
If this flag has been set, then the filesystem has requested that the
``d_manage()`` dentry operation be called before handling any possible
mount point. This can perform two particular services:
It can block to avoid races. If an automount point is being
unmounted, the ``d_manage()`` function will usually wait for that
process to complete before letting the new lookup proceed and possibly
trigger a new automount.
It can selectively allow only some processes to transit through a
mount point. When a server process is managing automounts, it may
need to access a directory without triggering normal automount
processing. That server process can identify itself to the ``autofs``
filesystem, which will then give it a special pass through
``d_manage()`` by returning ``-EISDIR``.
``DCACHE_MOUNTED``
~~~~~~~~~~~~~~~~~~
This flag is set on every dentry that is mounted on. As Linux
supports multiple filesystem namespaces, it is possible that the
dentry may not be mounted on in *this* namespace, just in some
other. So this flag is seen as a hint, not a promise.
If this flag is set, and ``d_manage()`` didn't return ``-EISDIR``,
``lookup_mnt()`` is called to examine the mount hash table (honoring the
``mount_lock`` described earlier) and possibly return a new ``vfsmount``
and a new ``dentry`` (both with counted references).
``DCACHE_NEED_AUTOMOUNT``
~~~~~~~~~~~~~~~~~~~~~~~~~
If ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't
find a mount point, then this flag causes the ``d_automount()`` dentry
operation to be called.
The ``d_automount()`` operation can be arbitrarily complex and may
communicate with server processes etc. but it should ultimately either
report that there was an error, that there was nothing to mount, or
should provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``.
In the latter case, ``finish_automount()`` will be called to safely
install the new mount point into the mount table.
There is no new locking of import here and it is important that no
locks (only counted references) are held over this processing due to
the very real possibility of extended delays.
This will become more important next time when we examine RCU-walk
which is particularly sensitive to delays.
RCU-walk의 역할과 재시도
595-673RCU-walk는 REF-walk와 코드를 많이 공유하지만 concurrent access를 다루는 방식이 다릅니다. 처리하기 어려운 여러 경우를 직접 맡지 않고 REF-walk로 fallback합니다. RCU locking rule은 전통적 lock과 달라 낯설다는 점이 주된 어려움입니다.
읽는 동안 다른 thread의 변경을 lock으로 막거나 reader count를 갱신하는 것조차 많은 reader가 있는 곳에서는 비용입니다. RCU-walk의 목표는 변경이 드문 shared data를 읽을 때 lock도 count 증가도 없이 memory에 footprint를 남기지 않는 것입니다.
Pathname lookup은 항상 RCU-walk로 시작하며 대상이 cache에 있고 안정된 동안만 유지합니다. 변경, 불안정, cache miss를 발견하면 현재 vfsmount와 dentry에 counted reference를 얻고 REF-walk가 같은 entry를 찾았을지 검증한 뒤 graceful하게 전환합니다. 검증할 수 없으면 처음부터 REF-walk로 재시작합니다.
RCU-walk는 REF-walk도 동시에 선택할 수 있었던 다음 step만 선택해야 한다는 invariant를 지킵니다. 전환에 성공하면 나머지를 REF-walk로 처리하며 한 번 내려간 뒤 RCU-walk로 돌아오지 않습니다.
빠른 cache-only walk에서 안정성 문제가 생기면 reference 기반 REF-walk로 전환합니다.
`filename_lookup()`, `filename_parentat()`, `do_filp_open()`, `do_file_open_root()`에서 이 pattern을 볼 수 있습니다. 먼저 `LOOKUP_RCU`, `-ECHILD`이면 flag 없이 REF-walk, 둘 중 `ESTALE`이면 `LOOKUP_REVAL`과 non-RCU로 마지막 강제 revalidation을 시도합니다.
오류 코드가 다음 mode를 선택합니다.
RCU-walk - faster pathname lookup in Linux
==========================================
RCU-walk is another algorithm for performing pathname lookup in Linux.
It is in many ways similar to REF-walk and the two share quite a bit
of code. The significant difference in RCU-walk is how it allows for
the possibility of concurrent access.
We noted that REF-walk is complex because there are numerous details
and special cases. RCU-walk reduces this complexity by simply
refusing to handle a number of cases -- it instead falls back to
REF-walk. The difficulty with RCU-walk comes from a different
direction: unfamiliarity. The locking rules when depending on RCU are
quite different from traditional locking, so we will spend a little extra
time when we come to those.
Clear demarcation of roles
--------------------------
The easiest way to manage concurrency is to forcibly stop any other
thread from changing the data structures that a given thread is
looking at. In cases where no other thread would even think of
changing the data and lots of different threads want to read at the
same time, this can be very costly. Even when using locks that permit
multiple concurrent readers, the simple act of updating the count of
the number of current readers can impose an unwanted cost. So the
goal when reading a shared data structure that no other process is
changing is to avoid writing anything to memory at all. Take no
locks, increment no counts, leave no footprints.
The REF-walk mechanism already described certainly doesn't follow this
principle, but then it is really designed to work when there may well
be other threads modifying the data. RCU-walk, in contrast, is
designed for the common situation where there are lots of frequent
readers and only occasional writers. This may not be common in all
parts of the filesystem tree, but in many parts it will be. For the
other parts it is important that RCU-walk can quickly fall back to
using REF-walk.
Pathname lookup always starts in RCU-walk mode but only remains there
as long as what it is looking for is in the cache and is stable. It
dances lightly down the cached filesystem image, leaving no footprints
and carefully watching where it is, to be sure it doesn't trip. If it
notices that something has changed or is changing, or if something
isn't in the cache, then it tries to stop gracefully and switch to
REF-walk.
This stopping requires getting a counted reference on the current
``vfsmount`` and ``dentry``, and ensuring that these are still valid -
that a path walk with REF-walk would have found the same entries.
This is an invariant that RCU-walk must guarantee. It can only make
decisions, such as selecting the next step, that are decisions which
REF-walk could also have made if it were walking down the tree at the
same time. If the graceful stop succeeds, the rest of the path is
processed with the reliable, if slightly sluggish, REF-walk. If
RCU-walk finds it cannot stop gracefully, it simply gives up and
restarts from the top with REF-walk.
This pattern of "try RCU-walk, if that fails try REF-walk" can be
clearly seen in functions like filename_lookup(),
filename_parentat(),
do_filp_open(), and do_file_open_root(). These four
correspond roughly to the three ``path_*()`` functions we met earlier,
each of which calls ``link_path_walk()``. The ``path_*()`` functions are
called using different mode flags until a mode is found which works.
They are first called with ``LOOKUP_RCU`` set to request "RCU-walk". If
that fails with the error ``ECHILD`` they are called again with no
special flag to request "REF-walk". If either of those report the
error ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no
``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly
revalidated - normally entries are only revalidated if the filesystem
determines that they are too old to trust.
The ``LOOKUP_RCU`` attempt may drop that flag internally and switch to
REF-walk, but will never then try to switch back to RCU-walk. Places
that trip up RCU-walk are much more likely to be near the leaves and
so it is very unlikely that there will be much, if any, benefit from
switching back.
RCU와 seqlock 검증
674-729RCU-walk 전체 동안 `rcu_read_lock()`을 유지합니다. 이 lock은 dentry, inode, super_block, mount가 해제되어 memory가 재사용되는 것만 막습니다. Unlink나 invalidate 같은 field 변경은 막지 않으므로 나머지는 seqlock으로 검증합니다.
REF-walk가 current dentry·vfsmount reference를 보유하고 next reference를 얻기 전까지 놓지 않으며 필요하면 `d_lock`을 잡는 반면, RCU-walk는 reference와 lock을 얻지 않습니다. 대신 변경이 있었는지 확인해 abort 또는 retry합니다.
REF-walk가 count를 증가하거나 spinlock을 잡는 지점에서 RCU-walk는 `read_seqcount_begin()` 등으로 seqlock 상태를 sample합니다. REF-walk가 count나 lock을 놓는 지점에서 `read_seqcount_retry()`로 sample이 여전히 유효한지 확인하여 두 walk가 같은 결정을 할 수 있다는 invariant를 지킵니다.
Seqlock이 보호하는 두 field 또는 같은 field를 두 번 읽은 값은 자동으로 일관되지 않습니다. 일관성이 필요하면 local copy를 만들고 `read_seqcount_retry()`로 검증해야 합니다. 이 함수는 sequence뿐 아니라 memory barrier를 제공해 앞의 memory read가 CPU나 compiler에 의해 뒤로 지연되지 않게 합니다.
`slow_dentry_cmp()`는 non-standard name equality filesystem에서 name length와 pointer를 local로 복사하고 sequence를 검증한 뒤 `->d_compare()`를 호출합니다. Standard 비교의 `dentry_cmp()`는 이 시점의 consistency가 필수는 아니므로 검증하지 않으며 뒤의 retry 검사가 문제를 잡습니다.
Lock 대신 시작 sequence와 local copy를 종료 sequence로 검증합니다.
RCU and seqlocks: fast and light
--------------------------------
RCU is, unsurprisingly, critical to RCU-walk mode. The
``rcu_read_lock()`` is held for the entire time that RCU-walk is walking
down a path. The particular guarantee it provides is that the key
data structures - dentries, inodes, super_blocks, and mounts - will
not be freed while the lock is held. They might be unlinked or
invalidated in one way or another, but the memory will not be
repurposed so values in various fields will still be meaningful. This
is the only guarantee that RCU provides; everything else is done using
seqlocks.
As we saw above, REF-walk holds a counted reference to the current
dentry and the current vfsmount, and does not release those references
before taking references to the "next" dentry or vfsmount. It also
sometimes takes the ``d_lock`` spinlock. These references and locks are
taken to prevent certain changes from happening. RCU-walk must not
take those references or locks and so cannot prevent such changes.
Instead, it checks to see if a change has been made, and aborts or
retries if it has.
To preserve the invariant mentioned above (that RCU-walk may only make
decisions that REF-walk could have made), it must make the checks at
or near the same places that REF-walk holds the references. So, when
REF-walk increments a reference count or takes a spinlock, RCU-walk
samples the status of a seqlock using ``read_seqcount_begin()`` or a
similar function. When REF-walk decrements the count or drops the
lock, RCU-walk checks if the sampled status is still valid using
``read_seqcount_retry()`` or similar.
However, there is a little bit more to seqlocks than that. If
RCU-walk accesses two different fields in a seqlock-protected
structure, or accesses the same field twice, there is no a priori
guarantee of any consistency between those accesses. When consistency
is needed - which it usually is - RCU-walk must take a copy and then
use ``read_seqcount_retry()`` to validate that copy.
``read_seqcount_retry()`` not only checks the sequence number, but also
imposes a memory barrier so that no memory-read instruction from
*before* the call can be delayed until *after* the call, either by the
CPU or by the compiler. A simple example of this can be seen in
``slow_dentry_cmp()`` which, for filesystems which do not use simple
byte-wise name equality, calls into the filesystem to compare a name
against a dentry. The length and name pointer are copied into local
variables, then ``read_seqcount_retry()`` is called to confirm the two
are consistent, and only then is ``->d_compare()`` called. When
standard filename comparison is used, ``dentry_cmp()`` is called
instead. Notably it does *not* use ``read_seqcount_retry()``, but
instead has a large comment explaining why the consistency guarantee
isn't necessary. A subsequent ``read_seqcount_retry()`` will be
sufficient to catch any problem that could occur at this point.
With that little refresher on seqlocks out of the way we can look at
the bigger picture of how RCU-walk uses seqlocks.
mount_lock m_seq과 dentry d_seq
730-805RCU-walk는 각 vfsmount에 reference를 얻는 대신 walk 시작에서 `mount_lock` sequence를 sample하여 `nameidata.m_seq`에 저장합니다. 하나의 lock과 sequence로 모든 vfsmount access와 mount point crossing을 검증합니다. Mount table 변경은 드물므로 mount·unmount가 하나라도 있으면 REF-walk로 fallback하는 것이 합리적입니다.
RCU sequence 종료, REF-walk 전환, path 끝에서 `read_seqretry()`로 `m_seq`를 검사합니다. `__follow_mount_rcu()`의 하향 crossing과 `follow_dotdot_rcu()`의 상향 crossing에서도 검사하며 변경되었으면 전체 RCU-walk를 중단하고 REF-walk로 다시 처리합니다.
Dentry에서는 `d_lockref` count·lock 대신 per-dentry `dentry->d_seq` seqlock을 sample하여 `nameidata.seq`에 저장합니다. `nd->seq`는 항상 `nd->dentry`의 current sequence여야 하며 name, parent, inode를 복사한 뒤 사용하기 전에 검증합니다.
`follow_dotdot_rcu()`는 일반적으로 `d_parent`와 그 `d_seq`를 얻습니다. Mount point에서는 `mnt->mnt_mountpoint`와 sequence를 얻고, 최종 parent를 따른 뒤 mount point에 도착했는지 확인하여 필요하면 해당 mount의 `mnt->mnt_root`를 따릅니다. 시작점이 root에서 보이지 않는 mounted-over 영역인 드문 경우도 처리합니다.
`d_inode`는 NULL 확인, permission 검사, symlink 처리 등 여러 번 필요합니다. 매번 검증하지 않고 첫 access에서 copy해 `nameidata.inode`에 저장하여 안전하게 재사용합니다.
RCU mode는 lock이 필요한 `lookup_slow()`를 쓰지 않고 `lookup_fast()`만 사용합니다. Current dentry와 old seq를 `__d_lookup_rcu()`에 전달해 new dentry와 new seq를 받고 inode를 복사한 뒤 new seq를 검증합니다. 그 다음 old dentry를 old seq로 마지막 검증합니다. 이는 REF-walk가 new dentry reference를 얻고 old reference를 놓는 hand-over-hand 순서와 같습니다.
Global mount 변경과 per-dentry 변경을 별도 sequence로 검증합니다.
새 dentry의 sequence를 확보한 뒤 이전 dentry를 마지막 검증합니다.
``mount_lock`` and ``nd->m_seq``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We already met the ``mount_lock`` seqlock when REF-walk used it to
ensure that crossing a mount point is performed safely. RCU-walk uses
it for that too, but for quite a bit more.
Instead of taking a counted reference to each ``vfsmount`` as it
descends the tree, RCU-walk samples the state of ``mount_lock`` at the
start of the walk and stores this initial sequence number in the
``struct nameidata`` in the ``m_seq`` field. This one lock and one
sequence number are used to validate all accesses to all ``vfsmounts``,
and all mount point crossings. As changes to the mount table are
relatively rare, it is reasonable to fall back on REF-walk any time
that any "mount" or "unmount" happens.
``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk
sequence, whether switching to REF-walk for the rest of the path or
when the end of the path is reached. It is also checked when stepping
down over a mount point (in ``__follow_mount_rcu()``) or up (in
``follow_dotdot_rcu()``). If it is ever found to have changed, the
whole RCU-walk sequence is aborted and the path is processed again by
REF-walk.
If RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure
that, had REF-walk taken counted references on each vfsmount, the
results would have been the same. This ensures the invariant holds,
at least for vfsmount structures.
``dentry->d_seq`` and ``nd->seq``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In place of taking a count or lock on ``d_reflock``, RCU-walk samples
the per-dentry ``d_seq`` seqlock, and stores the sequence number in the
``seq`` field of the nameidata structure, so ``nd->seq`` should always be
the current sequence number of ``nd->dentry``. This number needs to be
revalidated after copying, and before using, the name, parent, or
inode of the dentry.
The handling of the name we have already looked at, and the parent is
only accessed in ``follow_dotdot_rcu()`` which fairly trivially follows
the required pattern, though it does so for three different cases.
When not at a mount point, ``d_parent`` is followed and its ``d_seq`` is
collected. When we are at a mount point, we instead follow the
``mnt->mnt_mountpoint`` link to get a new dentry and collect its
``d_seq``. Then, after finally finding a ``d_parent`` to follow, we must
check if we have landed on a mount point and, if so, must find that
mount point and follow the ``mnt->mnt_root`` link. This would imply a
somewhat unusual, but certainly possible, circumstance where the
starting point of the path lookup was in part of the filesystem that
was mounted on, and so not visible from the root.
The inode pointer, stored in ``->d_inode``, is a little more
interesting. The inode will always need to be accessed at least
twice, once to determine if it is NULL and once to verify access
permissions. Symlink handling requires a validated inode pointer too.
Rather than revalidating on each access, a copy is made on the first
access and it is stored in the ``inode`` field of ``nameidata`` from where
it can be safely accessed without further validation.
``lookup_fast()`` is the only lookup routine that is used in RCU-mode,
``lookup_slow()`` being too slow and requiring locks. It is in
``lookup_fast()`` that we find the important "hand over hand" tracking
of the current dentry.
The current ``dentry`` and current ``seq`` number are passed to
``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a
new ``seq`` number. ``lookup_fast()`` then copies the inode pointer and
revalidates the new ``seq`` number. It then validates the old ``dentry``
with the old ``seq`` number one last time and only then continues. This
process of getting the ``seq`` number of the new dentry and then
checking the ``seq`` number of the old exactly mirrors the process of
getting a counted reference to the new dentry before dropping that for
the old dentry which we saw in REF-walk.
i_rwsem 없이 걷기와 unlazy_walk
806-876`rcu_read_lock()` 아래에서는 sleep할 수 없으므로 heavyweight semaphore인 `inode->i_rwsem`은 RCU-walk에 쓰지 않습니다. 다른 thread가 i_rwsem을 잡고 directory를 바꾸면 RCU lookup이 dentry를 못 찾거나 `read_seqretry()` 검증에 실패하여 lock을 사용할 수 있는 REF-walk로 내려갑니다.
RCU-walk는 sleep하지 않는 `rename_lock`도 사용하지 않습니다. Hash chain 변경으로 cache hit를 놓쳐도 cache miss 자체가 REF-walk 재시도를 유발하므로 별도 rename sequence 검사가 실익이 없습니다.
RCU-walk에서 REF-walk로 내려갈 때 보통 `unlazy_walk()`을 호출합니다. 현재 mount/dentry까지는 성공했지만 다음 이름이 dcache에 없거나, RCU lock 아래 permission·revalidation을 못 하거나, automount를 만나거나, 특정 symlink 경우에 사용합니다. `complete_walk()`도 final component 또는 path 끝에 도달했을 때 호출할 수 있습니다.
`mount_lock` 또는 `d_seq` 변경처럼 즉시 처리할 수 없는 inconsistency는 `unlazy_walk()` 없이 `-ECHILD`를 반환하여 위 caller가 처음부터 REF-walk로 재시도하게 합니다.
현재 RCU 위치를 counted reference로 합법화한 뒤 나머지를 REF-walk로 처리합니다.
`unlazy_walk()`은 vfsmount, dentry, 선택적 symlink pointer에 reference를 얻고 관련 seqlock이 변하지 않았는지 확인합니다. Counted reference가 전혀 없을 때 단순 증가만으로는 충분하지 않습니다. Dentry는 counter가 dead marker `-128`이 아니면 `lockref_get_not_dead()`로 reference를 얻습니다.
Mount는 reference 후 `mount_lock`으로 검증합니다. 실패한 reference를 무조건 `mnt_put()`하면 unmount가 너무 진행됐을 수 있습니다. `legitimize_mnt()`는 `MNT_SYNC_UMOUNT`를 보고 정상 `mnt_put()`을 할지 count만 줄여 없던 일로 할지 결정합니다.
0-reference 상태에서 객체 종류별로 안전하게 counted reference를 얻습니다.
No ``inode->i_rwsem`` or even ``rename_lock``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A semaphore is a fairly heavyweight lock that can only be taken when it is
permissible to sleep. As ``rcu_read_lock()`` forbids sleeping,
``inode->i_rwsem`` plays no role in RCU-walk. If some other thread does
take ``i_rwsem`` and modifies the directory in a way that RCU-walk needs
to notice, the result will be either that RCU-walk fails to find the
dentry that it is looking for, or it will find a dentry which
``read_seqretry()`` won't validate. In either case it will drop down to
REF-walk mode which can take whatever locks are needed.
Though ``rename_lock`` could be used by RCU-walk as it doesn't require
any sleeping, RCU-walk doesn't bother. REF-walk uses ``rename_lock`` to
protect against the possibility of hash chains in the dcache changing
while they are being searched. This can result in failing to find
something that actually is there. When RCU-walk fails to find
something in the dentry cache, whether it is really there or not, it
already drops down to REF-walk and tries again with appropriate
locking. This neatly handles all cases, so adding extra checks on
rename_lock would bring no significant value.
``unlazy walk()`` and ``complete_walk()``
-----------------------------------------
That "dropping down to REF-walk" typically involves a call to
``unlazy_walk()``, so named because "RCU-walk" is also sometimes
referred to as "lazy walk". ``unlazy_walk()`` is called when
following the path down to the current vfsmount/dentry pair seems to
have proceeded successfully, but the next step is problematic. This
can happen if the next name cannot be found in the dcache, if
permission checking or name revalidation couldn't be achieved while
the ``rcu_read_lock()`` is held (which forbids sleeping), if an
automount point is found, or in a couple of cases involving symlinks.
It is also called from ``complete_walk()`` when the lookup has reached
the final component, or the very end of the path, depending on which
particular flavor of lookup is used.
Other reasons for dropping out of RCU-walk that do not trigger a call
to ``unlazy_walk()`` are when some inconsistency is found that cannot be
handled immediately, such as ``mount_lock`` or one of the ``d_seq``
seqlocks reporting a change. In these cases the relevant function
will return ``-ECHILD`` which will percolate up until it triggers a new
attempt from the top using REF-walk.
For those cases where ``unlazy_walk()`` is an option, it essentially
takes a reference on each of the pointers that it holds (vfsmount,
dentry, and possibly some symbolic links) and then verifies that the
relevant seqlocks have not been changed. If there have been changes,
it, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk
has been a success and the lookup process continues.
Taking a reference on those pointers is not quite as simple as just
incrementing a counter. That works to take a second reference if you
already have one (often indirectly through another object), but it
isn't sufficient if you don't actually have a counted reference at
all. For ``dentry->d_lockref``, it is safe to increment the reference
counter to get a reference unless it has been explicitly marked as
"dead" which involves setting the counter to ``-128``.
``lockref_get_not_dead()`` achieves this.
For ``mnt->mnt_count`` it is safe to take a reference as long as
``mount_lock`` is then used to validate the reference. If that
validation fails, it may *not* be safe to just drop that reference in
the standard way of calling ``mnt_put()`` - an unmount may have
progressed too far. So the code in ``legitimize_mnt()``, when it
finds that the reference it got might not be safe, checks the
``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is
correct, or if it should just decrement the count and pretend none of
this ever happened.
Filesystem callback과 두 반복 pattern
877-936RCU-walk는 대부분 cache 정보만 사용하지만 component name 비교 외에도 filesystem callback 두 곳이 관여할 수 있으며 RCU 제약을 알아야 합니다.
Network filesystem처럼 특수 permission 검사가 필요하면 `i_op->permission`을 RCU-walk에서 호출할 수 있습니다. `MAY_NOT_BLOCK` flag를 추가해 sleep하지 말고 즉시 완료할 수 없으면 `-ECHILD`를 반환하도록 합니다. Callback은 검증된 inode pointer를 받지만 다른 filesystem data structure를 읽으면 RCU lock만으로 안전해야 하며 보통 `kfree_rcu()` 등으로 해제해야 합니다.
Dcache revalidation이 필요하면 `d_op->d_revalidate`도 RCU-walk에서 호출합니다. Dentry는 받지만 nameidata의 inode나 seq는 받지 않으므로 field 접근에 더 조심해야 합니다. `READ_ONCE()`로 field를 읽고 NULL이 아닌지 확인하는 pattern을 `nfs_lookup_revalidate()`에서 볼 수 있습니다.
Sleep 금지와 field 일관성 책임이 filesystem에 전달됩니다.
첫 pattern은 '빠르게 시도하고 검사한 뒤 실패하면 느리게 시도'입니다. 전체 RCU→REF 시도, path 중간 `unlazy_walk()`, `..`에서 `dget_parent()`의 reference 시도 뒤 lock fallback이 예입니다.
둘째는 '빠르게 시도하고 검사한 뒤 실패하면 반복 재시도'입니다. REF-walk의 `rename_lock`, `mount_lock`이 이 방식입니다. RCU-walk는 이상을 만나면 더 안전하게 abort하고 느린 방식으로 바꾸므로 이 반복 pattern을 쓰지 않습니다.
빠른 시도 뒤 실패를 처리하는 방법이 다릅니다.
두 경우 모두 '빠르고 조심스럽게 시도한 뒤 검사'가 핵심입니다. System은 동적이며 각 access의 안전성을 어떤 invariant가 보장하는지 확인해야 합니다.
Taking care in filesystems
--------------------------
RCU-walk depends almost entirely on cached information and often will
not call into the filesystem at all. However there are two places,
besides the already-mentioned component-name comparison, where the
file system might be included in RCU-walk, and it must know to be
careful.
If the filesystem has non-standard permission-checking requirements -
such as a networked filesystem which may need to check with the server
- the ``i_op->permission`` interface might be called during RCU-walk.
In this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it
knows not to sleep, but to return ``-ECHILD`` if it cannot complete
promptly. ``i_op->permission`` is given the inode pointer, not the
dentry, so it doesn't need to worry about further consistency checks.
However if it accesses any other filesystem data structures, it must
ensure they are safe to be accessed with only the ``rcu_read_lock()``
held. This typically means they must be freed using ``kfree_rcu()`` or
similar.
.. _READ_ONCE: https://lwn.net/Articles/624126/
If the filesystem may need to revalidate dcache entries, then
``d_op->d_revalidate`` may be called in RCU-walk too. This interface
*is* passed the dentry but does not have access to the ``inode`` or the
``seq`` number from the ``nameidata``, so it needs to be extra careful
when accessing fields in the dentry. This "extra care" typically
involves using `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the
result is not NULL before using it. This pattern can be seen in
``nfs_lookup_revalidate()``.
A pair of patterns
------------------
In various places in the details of REF-walk and RCU-walk, and also in
the big picture, there are a couple of related patterns that are worth
being aware of.
The first is "try quickly and check, if that fails try slowly". We
can see that in the high-level approach of first trying RCU-walk and
then trying REF-walk, and in places where ``unlazy_walk()`` is used to
switch to REF-walk for the rest of the path. We also saw it earlier
in ``dget_parent()`` when following a "``..``" link. It tries a quick way
to get a reference, then falls back to taking locks if needed.
The second pattern is "try quickly and check, if that fails try
again - repeatedly". This is seen with the use of ``rename_lock`` and
``mount_lock`` in REF-walk. RCU-walk doesn't make use of this pattern -
if anything goes wrong it is much safer to just abort and try a more
sedate approach.
The emphasis here is "try quickly and check". It should probably be
"try quickly *and carefully*, then check". The fact that checking is
needed is a reminder that the system is dynamic and only a limited
number of things are safe at all. The most likely cause of errors in
this whole process is assuming something is safe when in reality it
isn't. Careful consideration of what exactly guarantees the safety of
each access is sometimes necessary.
Symlink stack과 개수 제한
937-1010Final component 앞 path에서 의미 있게 나타날 객체는 directory와 symlink뿐입니다. Directory는 다음 component의 새 시작점이지만 symlink는 남은 path를 별도로 추적해야 합니다.
개념적으로 component가 symlink이면 그 component를 link body로 치환하고 body가 `/`로 시작하면 이전 path를 버릴 수 있습니다. `readlink -f`는 `.`과 `..`도 제거하며 이런 결과를 보여 줍니다. 실제 lookup은 이미 지난 문자열을 편집할 필요 없이 남은 component를 별도로 보관합니다.
Symlink가 또 다른 symlink를 가리킬 수 있으므로 여러 path remnant를 앞선 link 처리가 끝날 때까지 limited stack에 저장합니다.
현재 link body를 먼저 처리하고 이전 path 나머지를 stack에서 복원합니다.
Symlink 수를 제한하는 첫 이유는 self-reference나 간접 loop를 끝내고 `ELOOP`을 반환하기 위해서입니다. 둘째는 매우 깊은 non-loop도 latency와 DoS를 일으켜 과도한 CPU를 쓰기 때문입니다.
Linux pathname 길이 `PATH_MAX`는 4096이고 한 lookup에서 따를 symlink는 최대 `MAXSYMLINKS` 40개입니다. 과거에는 recursion depth 8 제한도 있었지만 별도 stack 구현 뒤 40으로 올라 하나의 제한만 남았습니다.
`nameidata`에는 두 symlink remnant를 담는 작은 내장 stack이 있습니다. 부족하면 40개 공간의 별도 stack을 할당합니다. 40번째 symlink를 감지하면 오류를 반환하므로 이를 넘지 않습니다.
Loop뿐 아니라 CPU 자원 고갈을 막는 상한입니다.
A walk among the symlinks
=========================
There are several basic issues that we will examine to understand the
handling of symbolic links: the symlink stack, together with cache
lifetimes, will help us understand the overall recursive handling of
symlinks and lead to the special care needed for the final component.
Then a consideration of access-time updates and summary of the various
flags controlling lookup will finish the story.
The symlink stack
-----------------
There are only two sorts of filesystem objects that can usefully
appear in a path prior to the final component: directories and symlinks.
Handling directories is quite straightforward: the new directory
simply becomes the starting point at which to interpret the next
component on the path. Handling symbolic links requires a bit more
work.
Conceptually, symbolic links could be handled by editing the path. If
a component name refers to a symbolic link, then that component is
replaced by the body of the link and, if that body starts with a '/',
then all preceding parts of the path are discarded. This is what the
"``readlink -f``" command does, though it also edits out "``.``" and
"``..``" components.
Directly editing the path string is not really necessary when looking
up a path, and discarding early components is pointless as they aren't
looked at anyway. Keeping track of all remaining components is
important, but they can of course be kept separately; there is no need
to concatenate them. As one symlink may easily refer to another,
which in turn can refer to a third, we may need to keep the remaining
components of several paths, each to be processed when the preceding
ones are completed. These path remnants are kept on a stack of
limited size.
There are two reasons for placing limits on how many symlinks can
occur in a single path lookup. The most obvious is to avoid loops.
If a symlink referred to itself either directly or through
intermediaries, then following the symlink can never complete
successfully - the error ``ELOOP`` must be returned. Loops can be
detected without imposing limits, but limits are the simplest solution
and, given the second reason for restriction, quite sufficient.
.. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550
The second reason was `outlined recently`_ by Linus:
Because it's a latency and DoS issue too. We need to react well to
true loops, but also to "very deep" non-loops. It's not about memory
use, it's about users triggering unreasonable CPU resources.
Linux imposes a limit on the length of any pathname: ``PATH_MAX``, which
is 4096. There are a number of reasons for this limit; not letting the
kernel spend too much time on just one path is one of them. With
symbolic links you can effectively generate much longer paths so some
sort of limit is needed for the same reason. Linux imposes a limit of
at most 40 (MAXSYMLINKS) symlinks in any one path lookup. It previously imposed
a further limit of eight on the maximum depth of recursion, but that was
raised to 40 when a separate stack was implemented, so there is now
just the one limit.
The ``nameidata`` structure that we met in an earlier article contains a
small stack that can be used to store the remaining part of up to two
symlinks. In many cases this will be sufficient. If it isn't, a
separate stack is allocated with room for 40 symlinks. Pathname
lookup will never exceed that stack as, once the 40th symlink is
detected, an error is returned.
It might seem that the name remnants are all that needs to be stored on
this stack, but we need a bit more. To see that, we need to move on to
cache lifetimes.
Cached symlink 저장과 수명
1011-1094Linux는 inode와 dentry처럼 symlink도 cache하여 외부 storage 접근을 줄입니다. RCU-walk가 REF-walk로 내려가지 않으려면 cached symlink를 찾고 잠시 안정적으로 보유할 수 있어야 합니다.
짧은 symlink는 흔히 inode private data에 직접 저장합니다. File 내용처럼 page cache에 pathname을 저장하는 방식도 일반적입니다. 둘 다 맞지 않으면 filesystem이 필요할 때 temporary memory를 할당해 symlink 내용을 copy하거나 구성합니다.
Inode 안의 symlink는 RCU 또는 counted dentry reference가 보호하는 inode와 수명이 같으므로 기존 dcache·icache 보호로 충분합니다. 이 경우 inode의 `i_link` pointer가 저장 위치를 가리켜 직접 접근합니다.
Page cache나 다른 곳의 symlink는 dentry·inode reference 또는 `rcu_read_lock()`만으로 page가 사라지지 않음을 보장할 수 없습니다. Path lookup은 filesystem에 stable reference를 요청하고 끝날 때 반드시 놓아야 합니다.
RCU-walk에서도 cache page reference를 얻을 수 있고 memory write 비용이 있더라도 전체 fallback보다 낫습니다. Temporary copy가 필요한 filesystem도 `GFP_ATOMIC`으로 non-sleep allocation을 시도할 수 있습니다. RCU mode에서 reference를 얻지 못하면 `-ECHILD`를 반환하고 `unlazy_walk()`으로 REF-walk에 들어가 sleep할 수 있습니다.
저장 위치마다 stable reference를 얻는 방법이 다릅니다.
이 계약은 `i_op->get_link()` method에 있습니다. RCU-walk에서는 `dentry *` argument가 NULL이고 완료할 수 없으면 `-ECHILD`를 반환합니다. Counted reference 없이 RCU lock만 보유하므로 참조하는 모든 구조체가 RCU-safe여야 합니다.
VFS는 `struct delayed_called`를 `->get_link()`에 전달합니다. Filesystem은 `set_delayed_call()`로 put_link callback과 argument를 설정하고 VFS는 나중에 `do_delayed_call()`로 해제합니다.
각 symlink stack entry는 path remnant 외에도 이전 path reference용 `struct path`, 이전 name용 `const char *`, RCU→REF 전환 검증용 `seq`, 나중 callback용 `struct delayed_call`을 보유합니다. 총 다섯 pointer와 integer이며 64비트에서 entry당 약 40바이트, 40개면 1600바이트로 반 page보다 작습니다. Frame의 `name` remnant는 같은 frame의 다른 field가 참조하는 symlink 본문이 아니라 그 symlink 뒤에 다시 따라갈 path입니다.
Path continuation과 symlink resource 수명 정보를 함께 저장합니다.
Storage and lifetime of cached symlinks
---------------------------------------
Like other filesystem resources, such as inodes and directory
entries, symlinks are cached by Linux to avoid repeated costly access
to external storage. It is particularly important for RCU-walk to be
able to find and temporarily hold onto these cached entries, so that
it doesn't need to drop down into REF-walk.
.. _object-oriented design pattern: https://lwn.net/Articles/446317/
While each filesystem is free to make its own choice, symlinks are
typically stored in one of two places. Short symlinks are often
stored directly in the inode. When a filesystem allocates a ``struct
inode`` it typically allocates extra space to store private data (a
common `object-oriented design pattern`_ in the kernel). This will
sometimes include space for a symlink. The other common location is
in the page cache, which normally stores the content of files. The
pathname in a symlink can be seen as the content of that symlink and
can easily be stored in the page cache just like file content.
When neither of these is suitable, the next most likely scenario is
that the filesystem will allocate some temporary memory and copy or
construct the symlink content into that memory whenever it is needed.
When the symlink is stored in the inode, it has the same lifetime as
the inode which, itself, is protected by RCU or by a counted reference
on the dentry. This means that the mechanisms that pathname lookup
uses to access the dcache and icache (inode cache) safely are quite
sufficient for accessing some cached symlinks safely. In these cases,
the ``i_link`` pointer in the inode is set to point to wherever the
symlink is stored and it can be accessed directly whenever needed.
When the symlink is stored in the page cache or elsewhere, the
situation is not so straightforward. A reference on a dentry or even
on an inode does not imply any reference on cached pages of that
inode, and even an ``rcu_read_lock()`` is not sufficient to ensure that
a page will not disappear. So for these symlinks the pathname lookup
code needs to ask the filesystem to provide a stable reference and,
significantly, needs to release that reference when it is finished
with it.
Taking a reference to a cache page is often possible even in RCU-walk
mode. It does require making changes to memory, which is best avoided,
but that isn't necessarily a big cost and it is better than dropping
out of RCU-walk mode completely. Even filesystems that allocate
space to copy the symlink into can use ``GFP_ATOMIC`` to often successfully
allocate memory without the need to drop out of RCU-walk. If a
filesystem cannot successfully get a reference in RCU-walk mode, it
must return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to
REF-walk mode in which the filesystem is allowed to sleep.
The place for all this to happen is the ``i_op->get_link()`` inode
method. This is called both in RCU-walk and REF-walk. In RCU-walk the
``dentry*`` argument is NULL, ``->get_link()`` can return -ECHILD to drop out of
RCU-walk. Much like the ``i_op->permission()`` method we
looked at previously, ``->get_link()`` would need to be careful that
all the data structures it references are safe to be accessed while
holding no counted reference, only the RCU lock. A callback
``struct delayed_called`` will be passed to ``->get_link()``:
file systems can set their own put_link function and argument through
set_delayed_call(). Later on, when VFS wants to put link, it will call
do_delayed_call() to invoke that callback function with the argument.
In order for the reference to each symlink to be dropped when the walk completes,
whether in RCU-walk or REF-walk, the symlink stack needs to contain,
along with the path remnants:
- the ``struct path`` to provide a reference to the previous path
- the ``const char *`` to provide a reference to the to previous name
- the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk
- the ``struct delayed_call`` for later invocation.
This means that each entry in the symlink stack needs to hold five
pointers and an integer instead of just one pointer (the path
remnant). On a 64-bit system, this is about 40 bytes per entry;
with 40 entries it adds up to 1600 bytes total, which is less than
half a page. So it might seem like a lot, but is by no means
excessive.
Note that, in a given stack frame, the path remnant (``name``) is not
part of the symlink that the other fields refer to. It is the remnant
to be followed once that symlink has been fully parsed.
Symlink push·pop과 WALK flag
1095-1133`link_path_walk()`의 main loop는 원래 path와 모든 non-final symlink component를 같은 방식으로 순회합니다. Symlink를 처리할 때 `name` pointer를 link body로 바꾸거나 stack에서 복원하므로 loop 대부분은 구분할 필요가 없습니다.
Symlink를 찾으면 `walk_component()`가 `step_into()`를 통해 `pick_link()`를 호출해 filesystem에서 link를 얻습니다. 성공하면 old `name`을 stack에 두고 link body를 새 `name`으로 처리합니다. `*name == '\0'`이면 stack에서 old name을 복원해 계속 걷습니다.
Tail recursion을 효율적으로 처리하려면 symlink의 마지막 component가 또 symlink일 때 완료한 frame을 먼저 pop하고 새 frame을 push해야 빈 remnant가 남지 않습니다. `walk_component()`는 old symlink를 마지막으로 보면서 새 symlink를 찾는 곳이므로 old resource release·pop 뒤 new reference push를 수행하기 적합합니다.
Tail symlink에서는 완료 frame을 먼저 제거하여 stack 깊이를 불필요하게 늘리지 않습니다.
`WALK_NOFOLLOW`는 찾은 symlink를 따라가지 못하게 합니다. `WALK_MORE`는 current symlink를 release하기 아직 이르다는 뜻입니다. `WALK_TRAILING`은 lookup의 final component임을 나타내며 userspace `LOOKUP_FOLLOW`로 따라갈지 결정하고 `may_follow_link()`로 권한을 확인합니다.
Follow 금지, frame 수명과 final component 정책을 제어합니다.
Following the symlink
---------------------
The main loop in ``link_path_walk()`` iterates seamlessly over all
components in the path and all of the non-final symlinks. As symlinks
are processed, the ``name`` pointer is adjusted to point to a new
symlink, or is restored from the stack, so that much of the loop
doesn't need to notice. Getting this ``name`` variable on and off the
stack is very straightforward; pushing and popping the references is
a little more complex.
When a symlink is found, walk_component() calls pick_link() via step_into()
which returns the link from the filesystem.
Providing that operation is successful, the old path ``name`` is placed on the
stack, and the new value is used as the ``name`` for a while. When the end of
the path is found (i.e. ``*name`` is ``'\0'``) the old ``name`` is restored
off the stack and path walking continues.
Pushing and popping the reference pointers (inode, cookie, etc.) is more
complex in part because of the desire to handle tail recursion. When
the last component of a symlink itself points to a symlink, we
want to pop the symlink-just-completed off the stack before pushing
the symlink-just-found to avoid leaving empty path remnants that would
just get in the way.
It is most convenient to push the new symlink references onto the
stack in ``walk_component()`` immediately when the symlink is found;
``walk_component()`` is also the last piece of code that needs to look at the
old symlink as it walks that last component. So it is quite
convenient for ``walk_component()`` to release the old symlink and pop
the references just before pushing the reference information for the
new symlink. It is guided in this by three flags: ``WALK_NOFOLLOW`` which
forbids it from following a symlink if it finds one, ``WALK_MORE``
which indicates that it is yet too early to release the
current symlink, and ``WALK_TRAILING`` which indicates that it is on the final
component of the lookup, so we will check userspace flag ``LOOKUP_FOLLOW`` to
decide whether follow it when it is a symlink and call ``may_follow_link()`` to
check if we have privilege to follow it.
Final component가 없는 symlink와 magic-link
1134-1164특별한 두 symlink는 nameidata에 새 mount+dentry `struct path`를 직접 설정하고 `pick_link()`가 NULL을 반환합니다.
첫째는 `/`만 가리키는 symlink입니다. `/`로 시작하는 모든 link는 `pick_link()`가 nameidata를 effective root로 reset합니다. Body가 `/`뿐이면 처리할 component가 없으므로 NULL을 반환하고 symlink resource와 stack frame을 버립니다.
둘째는 `/proc/self/fd/1` 같은 procfs magic-link입니다. Open file descriptor의 target name 문자열이 아니라 target file 자체 reference를 나타냅니다. `readlink` 결과 이름은 unlink되거나 mount-over된 경우 같은 file을 가리키지 않을 수도 있습니다.
`walk_component()`가 magic-link를 따르면 procfs `->get_link()`는 문자열을 반환하지 않고 `nd_jump_link()`로 nameidata를 target path로 직접 바꾼 뒤 NULL을 반환합니다. 따라서 이 경우도 final component가 없습니다.
Path를 직접 바꾸고 `pick_link()`가 NULL을 반환하는 두 경우입니다.
Symlinks with no final component
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A pair of special-case symlinks deserve a little further explanation.
Both result in a new ``struct path`` (with mount and dentry) being set
up in the ``nameidata``, and result in pick_link() returning ``NULL``.
The more obvious case is a symlink to "``/``". All symlinks starting
with "``/``" are detected in pick_link() which resets the ``nameidata``
to point to the effective filesystem root. If the symlink only
contains "``/``" then there is nothing more to do, no components at all,
so ``NULL`` is returned to indicate that the symlink can be released and
the stack frame discarded.
The other case involves things in ``/proc`` that look like symlinks but
aren't really (and are therefore commonly referred to as "magic-links")::
$ ls -l /proc/self/fd/1
lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4
Every open file descriptor in any process is represented in ``/proc`` by
something that looks like a symlink. It is really a reference to the
target file, not just the name of it. When you ``readlink`` these
objects you get a name that might refer to the same file - unless it
has been unlinked or mounted over. When ``walk_component()`` follows
one of these, the ``->get_link()`` method in "procfs" doesn't return
a string name, but instead calls nd_jump_link() which updates the
``nameidata`` in place to point to that target. ``->get_link()`` then
returns ``NULL``. Again there is no final component and pick_link()
returns ``NULL``.
Final symlink와 open 처리
1165-1224`link_path_walk()`은 non-final symlink를 모두 따라간 뒤 final component를 `nameidata.last`에 남깁니다. Create caller는 이 이름만 필요하지만 다른 caller는 final symlink를 따라가 그 link body의 final component에 별도 규칙을 적용해야 합니다.
`path_lookupat()`과 `path_openat()`은 loop에서 `link_path_walk()` 뒤 `lookup_last()` 또는 `open_last_lookups()`로 final component를 처리합니다. 따라갈 symlink이면 다음 path를 준비해 loop를 반복합니다. 각 symlink의 final component가 다시 symlink면 최대 40번 반복할 수 있습니다.
Caller가 final lookup과 path walk를 번갈아 호출합니다.
File open에서는 `open_last_lookups()`와 `do_open()`이 함께 동작하고 `lookup_open()` 구간은 `i_rwsem`을 보유합니다. Dcache에서 file을 찾으면 `vfs_open()`으로 엽니다. 없으면 filesystem이 제공할 때 `atomic_open()`으로 final lookup과 open을 결합하고, 아니면 `i_op->lookup()`과 `i_op->create()`를 따로 수행한 뒤 `vfs_open()`합니다.
`vfs_open()`은 cache 정보가 오래되면 `-EOPENSTALE`로 실패할 수 있습니다. RCU-walk caller에는 `-ECHILD`, 그 외에는 `-ESTALE`로 변환되며 `-ESTALE`이면 caller가 `LOOKUP_REVAL`로 재시도할 수 있습니다.
`O_CREAT` open은 `mkdir` 같은 다른 create call과 달리 final symlink를 따릅니다. `ln -s bar /tmp/foo; echo hello > /tmp/foo`는 `/tmp/bar`를 만듭니다. `O_EXCL`이면 허용되지 않습니다. 그 외에는 normal open처럼 final lookup이 non-NULL symlink path를 반환하고 path walk를 계속합니다.
Dcache hit, atomic open과 분리 lookup/create의 선택입니다.
Following the symlink in the final component
--------------------------------------------
All this leads to ``link_path_walk()`` walking down every component, and
following all symbolic links it finds, until it reaches the final
component. This is just returned in the ``last`` field of ``nameidata``.
For some callers, this is all they need; they want to create that
``last`` name if it doesn't exist or give an error if it does. Other
callers will want to follow a symlink if one is found, and possibly
apply special handling to the last component of that symlink, rather
than just the last component of the original file name. These callers
potentially need to call ``link_path_walk()`` again and again on
successive symlinks until one is found that doesn't point to another
symlink.
This case is handled by relevant callers of link_path_walk(), such as
path_lookupat(), path_openat() using a loop that calls link_path_walk(),
and then handles the final component by calling open_last_lookups() or
lookup_last(). If it is a symlink that needs to be followed,
open_last_lookups() or lookup_last() will set things up properly and
return the path so that the loop repeats, calling
link_path_walk() again. This could loop as many as 40 times if the last
component of each symlink is another symlink.
Of the various functions that examine the final component,
open_last_lookups() is the most interesting as it works in tandem
with do_open() for opening a file. Part of open_last_lookups() runs
with ``i_rwsem`` held and this part is in a separate function: lookup_open().
Explaining open_last_lookups() and do_open() completely is beyond the scope
of this article, but a few highlights should help those interested in exploring
the code.
1. Rather than just finding the target file, do_open() is used after
open_last_lookup() to open
it. If the file was found in the dcache, then ``vfs_open()`` is used for
this. If not, then ``lookup_open()`` will either call ``atomic_open()`` (if
the filesystem provides it) to combine the final lookup with the open, or
will perform the separate ``i_op->lookup()`` and ``i_op->create()`` steps
directly. In the later case the actual "open" of this newly found or
created file will be performed by vfs_open(), just as if the name
were found in the dcache.
2. vfs_open() can fail with ``-EOPENSTALE`` if the cached information
wasn't quite current enough. If it's in RCU-walk ``-ECHILD`` will be returned
otherwise ``-ESTALE`` is returned. When ``-ESTALE`` is returned, the caller may
retry with ``LOOKUP_REVAL`` flag set.
3. An open with O_CREAT **does** follow a symlink in the final component,
unlike other creation system calls (like ``mkdir``). So the sequence::
ln -s bar /tmp/foo
echo hello > /tmp/foo
will create a file called ``/tmp/bar``. This is not permitted if
``O_EXCL`` is set but otherwise is handled for an O_CREAT open much
like for a non-creating open: lookup_last() or open_last_lookup()
returns a non ``NULL`` value, and link_path_walk() gets called and the
open process continues on the symlink that was found.
Symlink access time 갱신
1225-1274RCU-walk는 footprint를 남기지 않는 것이 목표지만 symlink cache reference나 memory allocation이 필요할 수 있고 atime 갱신도 추가 write를 만듭니다.
Directory 안을 통과하는 것만으로는 directory `atime`을 갱신하지 않고 내용 listing만 갱신할 수 있습니다. Symlink는 `readlink()`로 읽거나 다른 목적지로 가는 중 따라가기만 해도 atime을 갱신할 수 있습니다. POSIX는 pathname resolution 중 timestamp 변경을 문서화하지 않아도 된다고 하므로 명확한 이유는 남아 있지 않습니다. ext2는 Linux 1.3.87 전에는 link follow 때 atime을 갱신하지 않았지만 변경 이유 기록은 없습니다.
Atime update는 복잡해 RCU-walk에서 계속 처리하지 않는 것이 좋습니다. `relatime`은 변경되지 않는 file의 atime을 일반적으로 하루 한 번으로 제한하고 symlink는 생성 뒤 바뀌지 않습니다. Relatime이 없어도 많은 filesystem이 1초 granularity를 사용해 초당 한 번만 갱신합니다.
RCU-walk에서 atime update가 필요한지는 쉽게 검사할 수 있습니다. 필요 없으면 건너뛰고 RCU mode를 유지하며 실제 update가 필요할 때만 REF-walk로 내려갑니다. 이 처리는 `get_link()`에 있습니다.
불필요한 write는 건너뛰고 필요한 경우에만 REF-walk로 전환합니다.
Updating the access time
------------------------
We previously said of RCU-walk that it would "take no locks, increment
no counts, leave no footprints." We have since seen that some
"footprints" can be needed when handling symlinks as a counted
reference (or even a memory allocation) may be needed. But these
footprints are best kept to a minimum.
One other place where walking down a symlink can involve leaving
footprints in a way that doesn't affect directories is in updating access times.
In Unix (and Linux) every filesystem object has a "last accessed
time", or "``atime``". Passing through a directory to access a file
within is not considered to be an access for the purposes of
``atime``; only listing the contents of a directory can update its ``atime``.
Symlinks are different it seems. Both reading a symlink (with ``readlink()``)
and looking up a symlink on the way to some other destination can
update the atime on that symlink.
.. _clearest statement: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08
It is not clear why this is the case; POSIX has little to say on the
subject. The `clearest statement`_ is that, if a particular implementation
updates a timestamp in a place not specified by POSIX, this must be
documented "except that any changes caused by pathname resolution need
not be documented". This seems to imply that POSIX doesn't really
care about access-time updates during pathname lookup.
.. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8
An examination of history shows that prior to `Linux 1.3.87`_, the ext2
filesystem, at least, didn't update atime when following a link.
Unfortunately we have no record of why that behavior was changed.
In any case, access time must now be updated and that operation can be
quite complex. Trying to stay in RCU-walk while doing it is best
avoided. Fortunately it is often permitted to skip the ``atime``
update. Because ``atime`` updates cause performance problems in various
areas, Linux supports the ``relatime`` mount option, which generally
limits the updates of ``atime`` to once per day on files that aren't
being changed (and symlinks never change once created). Even without
``relatime``, many filesystems record ``atime`` with a one-second
granularity, so only one update per second is required.
It is easy to test if an ``atime`` update is needed while in RCU-walk
mode and, if it isn't, the update can be skipped and RCU-walk mode
continues. Only when an ``atime`` update is actually required does the
path walk drop down to REF-walk. All of this is handled in the
``get_link()`` function.
Empty path와 global state flag
1275-1313`nameidata` flag는 lookup state, 모든 component에 적용할 restriction, final component 전용 동작으로 나눌 수 있습니다. `LOOKUP_EMPTY`는 별도 범주로, 없으면 empty pathname을 초기에 오류 처리하고 있으면 허용합니다.
`LOOKUP_RCU`와 `LOOKUP_REVAL`은 각각 RCU-walk와 forced revalidation REF-walk를 선택합니다. 둘 다 없으면 일반 REF-walk입니다.
`LOOKUP_PARENT`는 final component에 아직 도달하지 않았음을 나타내며 audit subsystem에 access의 전체 context를 전달하는 데 주로 사용합니다. `ND_ROOT_PRESET`은 caller가 nameidata의 `root`를 제공했으므로 종료 시 임의로 release하지 말아야 함을 뜻합니다.
`ND_JUMPED`는 current dentry가 이름 lookup이 아니라 `..`, `/` symlink, mount crossing, `/proc/$PID/fd/$FD` magic-link 같은 이유로 선택됐음을 뜻합니다. 이때 filesystem이 `d_revalidate()`로 name을 검사하지 않았으므로 완료 시 `d_op->d_weak_revalidate()`로 inode를 검사합니다. 완료 지점은 final component 또는 create·unlink·rename의 penultimate component일 수 있습니다.
전체 walk mode와 special jump 상태를 기록합니다.
A few flags
-----------
A suitable way to wrap up this tour of pathname walking is to list
the various flags that can be stored in the ``nameidata`` to guide the
lookup process. Many of these are only meaningful on the final
component, others reflect the current state of the pathname lookup, and some
apply restrictions to all path components encountered in the path lookup.
And then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with
the others. If this is not set, an empty pathname causes an error
very early on. If it is set, empty pathnames are not considered to be
an error.
Global state flags
~~~~~~~~~~~~~~~~~~
We have already met two global state flags: ``LOOKUP_RCU`` and
``LOOKUP_REVAL``. These select between one of three overall approaches
to lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.
``LOOKUP_PARENT`` indicates that the final component hasn't been reached
yet. This is primarily used to tell the audit subsystem the full
context of a particular access being audited.
``ND_ROOT_PRESET`` indicates that the ``root`` field in the ``nameidata`` was
provided by the caller, so it shouldn't be released when it is no
longer needed.
``ND_JUMPED`` means that the current dentry was chosen not because
it had the right name but for some other reason. This happens when
following "``..``", following a symlink to ``/``, crossing a mount point
or accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic
link"). In this case the filesystem has not been asked to revalidate the
name (with ``d_revalidate()``). In such cases the inode may still need
to be revalidated, so ``d_op->d_weak_revalidate()`` is called if
``ND_JUMPED`` is set when the look completes - which may be at the
final component or, when creating, unlinking, or renaming, at the penultimate component.
openat2 resolution restriction
1314-1348Userspace가 변경되는 path component를 이용한 race와 공격을 막도록 모든 component에 적용하는 restriction flag가 있으며 `openat2()`의 `resolve` field로 노출됩니다.
`LOOKUP_NO_SYMLINKS`는 magic-link를 포함한 모든 symlink traversal을 막습니다. Final trailing symlink만 제어하는 `LOOKUP_FOLLOW`와 다릅니다. `LOOKUP_NO_MAGICLINKS`는 모든 magic-link traversal을 막으며 filesystem의 `nd_jump_link()`가 restriction에 맞춰 오류를 반환해야 합니다.
`LOOKUP_NO_XDEV`는 bind mount와 일반 mount를 포함한 모든 `vfsmount` traversal을 막습니다. Absolute path는 `/`의 vfsmount, relative path는 `dfd`의 vfsmount에서 시작합니다. Magic-link는 path의 vfsmount가 바뀌지 않을 때만 허용됩니다.
`LOOKUP_BENEATH`는 resolution 시작점 밖으로 나가는 component를 막습니다. `nd_jump_root()`를 막고 시작점 밖으로 가는 `..`도 막습니다. `rename_lock`과 `mount_lock`으로 `..` attack을 감지하며 magic-link도 차단합니다.
`LOOKUP_IN_ROOT`는 시작점을 filesystem root처럼 취급합니다. `nd_jump_root()`는 시작점으로 돌아가고 시작점의 `..`은 no-op입니다. BENEATH와 마찬가지로 두 lock으로 공격을 감지하고 magic-link를 막습니다.
Symlink, mount crossing과 시작 subtree 탈출을 제한합니다.
Resolution-restriction flags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to allow userspace to protect itself against certain race conditions
and attack scenarios involving changing path components, a series of flags are
available which apply restrictions to all path components encountered during
path lookup. These flags are exposed through ``openat2()``'s ``resolve`` field.
``LOOKUP_NO_SYMLINKS`` blocks all symlink traversals (including magic-links).
This is distinctly different from ``LOOKUP_FOLLOW``, because the latter only
relates to restricting the following of trailing symlinks.
``LOOKUP_NO_MAGICLINKS`` blocks all magic-link traversals. Filesystems must
ensure that they return errors from ``nd_jump_link()``, because that is how
``LOOKUP_NO_MAGICLINKS`` and other magic-link restrictions are implemented.
``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` traversals (this includes both
bind-mounts and ordinary mounts). Note that the ``vfsmount`` which contains the
lookup is determined by the first mountpoint the path lookup reaches --
absolute paths start with the ``vfsmount`` of ``/``, and relative paths start
with the ``dfd``'s ``vfsmount``. Magic-links are only permitted if the
``vfsmount`` of the path is unchanged.
``LOOKUP_BENEATH`` blocks any path components which resolve outside the
starting point of the resolution. This is done by blocking ``nd_jump_root()``
as well as blocking ".." if it would jump outside the starting point.
``rename_lock`` and ``mount_lock`` are used to detect attacks against the
resolution of "..". Magic-links are also blocked.
``LOOKUP_IN_ROOT`` resolves all path components as though the starting point
were the filesystem root. ``nd_jump_root()`` brings the resolution back to
the starting point, and ".." at the starting point will act as a no-op. As with
``LOOKUP_BENEATH``, ``rename_lock`` and ``mount_lock`` are used to detect
attacks against ".." resolution. Magic-links are also blocked.
Final-component flag와 결론
1349-1390Final component를 고려할 때만 설정하거나 검사하는 flag도 있습니다.
`LOOKUP_AUTOMOUNT`는 final component가 automount point면 mount를 trigger합니다. `stat()`은 의도적으로 trigger하지 않지만 `statfs()`, `quotactl()`, `mount --bind` 처리는 이 flag를 설정합니다.
`LOOKUP_FOLLOW`는 final symlink를 따르는 정책입니다. 일부 system call이 암시적으로 설정·해제하고 다른 API는 `AT_SYMLINK_FOLLOW`, `UMOUNT_NOFOLLOW`로 제어합니다. 앞의 `WALK_GET`과 효과는 비슷하지만 사용 방식이 다릅니다.
`LOOKUP_DIRECTORY`는 final component가 directory여야 한다고 강제하며 여러 caller가 설정하고 final component 뒤에 slash가 있을 때도 설정됩니다.
`LOOKUP_OPEN`, `LOOKUP_CREATE`, `LOOKUP_EXCL`, `LOOKUP_RENAME_TARGET`은 VFS가 직접 사용하지 않고 filesystem, 특히 `->d_revalidate()`에 목적을 알려 줍니다. 곧 open 또는 create할 예정이면 filesystem이 과도한 revalidation을 생략할 수 있습니다. 과거 `->lookup()`에도 유용했지만 `->atomic_open()` 도입 뒤 중요성이 줄었습니다.
Automount, symlink, directory 요구와 다음 작업의 의도를 전달합니다.
Pathname lookup은 복잡하지만 lock·reference와 RCU invariant를 분리하면서 계속 이해하기 쉬워졌습니다. 원문의 마지막 문장은 당시 RCU-walk가 inode에 저장된 symlink만 따라 ext4의 많은 link에는 유효하지만 NFS, XFS, Btrfs에는 아직 도움이 되지 않으며 지원이 오래 지연되지는 않을 것이라고 설명합니다. 이는 문서가 기록한 시점의 구현 상태입니다.
Final-component flags
~~~~~~~~~~~~~~~~~~~~~
Some of these flags are only set when the final component is being
considered. Others are only checked for when considering that final
component.
``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount
point, then the mount is triggered. Some operations would trigger it
anyway, but operations like ``stat()`` deliberately don't. ``statfs()``
needs to trigger the mount but otherwise behaves a lot like ``stat()``, so
it sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of
"``mount --bind``".
``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for
symlinks. Some system calls set or clear it implicitly, while
others have API flags such as ``AT_SYMLINK_FOLLOW`` and
``UMOUNT_NOFOLLOW`` to control it. Its effect is similar to
``WALK_GET`` that we already met, but it is used in a different way.
``LOOKUP_DIRECTORY`` insists that the final component is a directory.
Various callers set this and it is also set when the final component
is found to be followed by a slash.
Finally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and
``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made
available to the filesystem and particularly the ``->d_revalidate()``
method. A filesystem can choose not to bother revalidating too hard
if it knows that it will be asked to open or create the file soon.
These flags were previously useful for ``->lookup()`` too but with the
introduction of ``->atomic_open()`` they are less relevant there.
End of the road
---------------
Despite its complexity, all this pathname lookup code appears to be
in good shape - various parts are certainly easier to understand now
than even a couple of releases ago. But that doesn't mean it is
"finished". As already mentioned, RCU-walk currently only follows
symlinks that are stored in the inode so, while it handles many ext4
symlinks, it doesn't help with NFS, XFS, or Btrfs. That support
is not likely to be long delayed.
요약·해설
path-lookup.rst:1-1390Linux pathname lookup은 dcache와 mount table을 따라 component를 걷고 final component는 system call별 caller가 처리합니다. REF-walk는 `d_lockref`, `i_rwsem`, `mount_lock`과 counted reference로 변경을 막거나 재시도하고, RCU-walk는 memory 수명만 보장한 채 `m_seq`·`d_seq`로 같은 결정을 검증합니다.
Cache miss, sleep이 필요한 callback, automount, symlink resource 또는 sequence 변경이 생기면 RCU-walk는 `unlazy_walk()`으로 REF-walk에 전환하거나 `-ECHILD`로 처음부터 재시작합니다. Symlink는 최대 40개 frame의 stack과 delayed release callback으로 수명을 관리하고, `openat2()` restriction flag가 mount·symlink·root 탈출을 제한합니다.
빠른 RCU cache walk에서 필요한 순간 reference 기반 REF-walk와 final 처리로 이동합니다.