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