1=============== 2Pathname lookup 3=============== 4 5This write-up is based on three articles published at lwn.net: 6 7- <https://lwn.net/Articles/649115/> Pathname lookup in Linux 8- <https://lwn.net/Articles/649729/> RCU-walk: faster pathname lookup in Linux 9- <https://lwn.net/Articles/650786/> A walk among the symlinks 10 11Written by Neil Brown with help from Al Viro and Jon Corbet. 12It has subsequently been updated to reflect changes in the kernel 13including: 14 15- per-directory parallel name lookup. 16 17Introduction to pathname lookup 18=============================== 19 20The most obvious aspect of pathname lookup, which very little 21exploration is needed to discover, is that it is complex. There are 22many rules, special cases, and implementation alternatives that all 23combine to confuse the unwary reader. Computer science has long been 24acquainted with such complexity and has tools to help manage it. One 25tool that we will make extensive use of is "divide and conquer". For 26the early parts of the analysis we will divide off symlinks - leaving 27them until the final part. Well before we get to symlinks we have 28another major division based on the VFS's approach to locking which 29will allow us to review "REF-walk" and "RCU-walk" separately. But we 30are getting ahead of ourselves. There are some important low level 31distinctions we need to clarify first. 32 33There are two sorts of ... 34-------------------------- 35 36.. _openat: http://man7.org/linux/man-pages/man2/openat.2.html 37 38Pathnames (sometimes "file names"), used to identify objects in the 39filesystem, will be familiar to most readers. They contain two sorts 40of elements: "slashes" that are sequences of one or more "``/``" 41characters, and "components" that are sequences of one or more 42non-"``/``" characters. These form two kinds of paths. Those that 43start with slashes are "absolute" and start from the filesystem root. 44The others are "relative" and start from the current directory, or 45from some other location specified by a file descriptor given to a 46"``XXXat``" system call such as `openat() <openat_>`_. 47 48.. _execveat: http://man7.org/linux/man-pages/man2/execveat.2.html 49 50It is tempting to describe the second kind as starting with a 51component, but that isn't always accurate: a pathname can lack both 52slashes and components, it can be empty, in other words. This is 53generally forbidden in POSIX, but some of those "xxx``at``" system calls 54in Linux permit it when the ``AT_EMPTY_PATH`` flag is given. For 55example, if you have an open file descriptor on an executable file you 56can execute it by calling `execveat() <execveat_>`_ passing 57the file descriptor, an empty path, and the ``AT_EMPTY_PATH`` flag. 58 59These paths can be divided into two sections: the final component and 60everything else. The "everything else" is the easy bit. In all cases 61it must identify a directory that already exists, otherwise an error 62such as ``ENOENT`` or ``ENOTDIR`` will be reported. 63 64The final component is not so simple. Not only do different system 65calls interpret it quite differently (e.g. some create it, some do 66not), but it might not even exist: neither the empty pathname nor the 67pathname that is just slashes have a final component. If it does 68exist, it could be "``.``" or "``..``" which are handled quite differently 69from other components. 70 71.. _POSIX: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12 72 73If a pathname ends with a slash, such as "``/tmp/foo/``" it might be 74tempting to consider that to have an empty final component. In many 75ways that would lead to correct results, but not always. In 76particular, ``mkdir()`` and ``rmdir()`` each create or remove a directory named 77by the final component, and they are required to work with pathnames 78ending in "``/``". According to POSIX_ 79 80 A pathname that contains at least one non- <slash> character and 81 that ends with one or more trailing <slash> characters shall not 82 be resolved successfully unless the last pathname component before 83 the trailing <slash> characters names an existing directory or a 84 directory entry that is to be created for a directory immediately 85 after the pathname is resolved. 86 87The Linux pathname walking code (mostly in ``fs/namei.c``) deals with 88all of these issues: breaking the path into components, handling the 89"everything else" quite separately from the final component, and 90checking that the trailing slash is not used where it isn't 91permitted. It also addresses the important issue of concurrent 92access. 93 94While one process is looking up a pathname, another might be making 95changes that affect that lookup. One fairly extreme case is that if 96"a/b" were renamed to "a/c/b" while another process were looking up 97"a/b/..", that process might successfully resolve on "a/c". 98Most races are much more subtle, and a big part of the task of 99pathname lookup is to prevent them from having damaging effects. Many 100of the possible races are seen most clearly in the context of the 101"dcache" and an understanding of that is central to understanding 102pathname lookup. 103 104More than just a cache 105---------------------- 106 107The "dcache" caches information about names in each filesystem to 108make them quickly available for lookup. Each entry (known as a 109"dentry") contains three significant fields: a component name, a 110pointer to a parent dentry, and a pointer to the "inode" which 111contains further information about the object in that parent with 112the given name. The inode pointer can be ``NULL`` indicating that the 113name doesn't exist in the parent. While there can be linkage in the 114dentry of a directory to the dentries of the children, that linkage is 115not used for pathname lookup, and so will not be considered here. 116 117The dcache has a number of uses apart from accelerating lookup. One 118that will be particularly relevant is that it is closely integrated 119with the mount table that records which filesystem is mounted where. 120What the mount table actually stores is which dentry is mounted on top 121of which other dentry. 122 123When considering the dcache, we have another of our "two types" 124distinctions: there are two types of filesystems. 125 126Some filesystems ensure that the information in the dcache is always 127completely accurate (though not necessarily complete). This can allow 128the VFS to determine if a particular file does or doesn't exist 129without checking with the filesystem, and means that the VFS can 130protect the filesystem against certain races and other problems. 131These are typically "local" filesystems such as ext3, XFS, and Btrfs. 132 133Other filesystems don't provide that guarantee because they cannot. 134These are typically filesystems that are shared across a network, 135whether remote filesystems like NFS and 9P, or cluster filesystems 136like ocfs2 or cephfs. These filesystems allow the VFS to revalidate 137cached information, and must provide their own protection against 138awkward races. The VFS can detect these filesystems by the 139``DCACHE_OP_REVALIDATE`` flag being set in the dentry. 140 141REF-walk: simple concurrency management with refcounts and spinlocks 142-------------------------------------------------------------------- 143 144With all of those divisions carefully classified, we can now start 145looking at the actual process of walking along a path. In particular 146we will start with the handling of the "everything else" part of a 147pathname, and focus on the "REF-walk" approach to concurrency 148management. This code is found in the ``link_path_walk()`` function, if 149you ignore all the places that only run when "``LOOKUP_RCU``" 150(indicating the use of RCU-walk) is set. 151 152.. _Meet the Lockers: https://lwn.net/Articles/453685/ 153 154REF-walk is fairly heavy-handed with locks and reference counts. Not 155as heavy-handed as in the old "big kernel lock" days, but certainly not 156afraid of taking a lock when one is needed. It uses a variety of 157different concurrency controls. A background understanding of the 158various primitives is assumed, or can be gleaned from elsewhere such 159as in `Meet the Lockers`_. 160 161The locking mechanisms used by REF-walk include: 162 163dentry->d_lockref 164~~~~~~~~~~~~~~~~~ 165 166This uses the lockref primitive to provide both a spinlock and a 167reference count. The special-sauce of this primitive is that the 168conceptual sequence "lock; inc_ref; unlock;" can often be performed 169with a single atomic memory operation. 170 171Holding a reference on a dentry ensures that the dentry won't suddenly 172be freed and used for something else, so the values in various fields 173will behave as expected. It also protects the ``->d_inode`` reference 174to the inode to some extent. 175 176The association between a dentry and its inode is fairly permanent. 177For example, when a file is renamed, the dentry and inode move 178together to the new location. When a file is created the dentry will 179initially be negative (i.e. ``d_inode`` is ``NULL``), and will be assigned 180to the new inode as part of the act of creation. 181 182When a file is deleted, this can be reflected in the cache either by 183setting ``d_inode`` to ``NULL``, or by removing it from the hash table 184(described shortly) used to look up the name in the parent directory. 185If the dentry is still in use the second option is used as it is 186perfectly legal to keep using an open file after it has been deleted 187and having the dentry around helps. If the dentry is not otherwise in 188use (i.e. if the refcount in ``d_lockref`` is one), only then will 189``d_inode`` be set to ``NULL``. Doing it this way is more efficient for a 190very common case. 191 192So as long as a counted reference is held to a dentry, a non-``NULL`` ``->d_inode`` 193value will never be changed. 194 195dentry->d_lock 196~~~~~~~~~~~~~~ 197 198``d_lock`` is a synonym for the spinlock that is part of ``d_lockref`` above. 199For our purposes, holding this lock protects against the dentry being 200renamed or unlinked. In particular, its parent (``d_parent``), and its 201name (``d_name``) cannot be changed, and it cannot be removed from the 202dentry hash table. 203 204When looking for a name in a directory, REF-walk takes ``d_lock`` on 205each candidate dentry that it finds in the hash table and then checks 206that the parent and name are correct. So it doesn't lock the parent 207while searching in the cache; it only locks children. 208 209When looking for the parent for a given name (to handle "``..``"), 210REF-walk can take ``d_lock`` to get a stable reference to ``d_parent``, 211but it first tries a more lightweight approach. As seen in 212``dget_parent()``, if a reference can be claimed on the parent, and if 213subsequently ``d_parent`` can be seen to have not changed, then there is 214no need to actually take the lock on the child. 215 216rename_lock 217~~~~~~~~~~~ 218 219Looking up a given name in a given directory involves computing a hash 220from the two values (the name and the dentry of the directory), 221accessing that slot in a hash table, and searching the linked list 222that is found there. 223 224When a dentry is renamed, the name and the parent dentry can both 225change so the hash will almost certainly change too. This would move the 226dentry to a different chain in the hash table. If a filename search 227happened to be looking at a dentry that was moved in this way, 228it might end up continuing the search down the wrong chain, 229and so miss out on part of the correct chain. 230 231The name-lookup process (``d_lookup()``) does _not_ try to prevent this 232from happening, but only to detect when it happens. 233``rename_lock`` is a seqlock that is updated whenever any dentry is 234renamed. If ``d_lookup`` finds that a rename happened while it 235unsuccessfully scanned a chain in the hash table, it simply tries 236again. 237 238inode->i_rwsem 239~~~~~~~~~~~~~~ 240 241``i_rwsem`` is a read/write semaphore that serializes all changes to a particular 242directory. This ensures that, for example, an ``unlink()`` and a ``rename()`` 243cannot both happen at the same time. It also keeps the directory 244stable while the filesystem is asked to look up a name that is not 245currently in the dcache or, optionally, when the list of entries in a 246directory is being retrieved with ``readdir()``. 247 248This has a complementary role to that of ``d_lock``: ``i_rwsem`` on a 249directory protects all of the names in that directory, while ``d_lock`` 250on a name protects just one name in a directory. Most changes to the 251dcache hold ``i_rwsem`` on the relevant directory inode and briefly take 252``d_lock`` on one or more the dentries while the change happens. One 253exception is when idle dentries are removed from the dcache due to 254memory pressure. This uses ``d_lock``, but ``i_rwsem`` plays no role. 255 256The semaphore affects pathname lookup in two distinct ways. Firstly it 257prevents changes during lookup of a name in a directory. ``walk_component()`` uses 258``lookup_fast()`` first which, in turn, checks to see if the name is in the cache, 259using only ``d_lock`` locking. If the name isn't found, then ``walk_component()`` 260falls back to ``lookup_slow()`` which takes a shared lock on ``i_rwsem``, checks again that 261the name isn't in the cache, and then calls in to the filesystem to get a 262definitive answer. A new dentry will be added to the cache regardless of 263the result. 264 265Secondly, when pathname lookup reaches the final component, it will 266sometimes need to take an exclusive lock on ``i_rwsem`` before performing the last lookup so 267that the required exclusion can be achieved. How path lookup chooses 268to take, or not take, ``i_rwsem`` is one of the 269issues addressed in a subsequent section. 270 271If two threads attempt to look up the same name at the same time - a 272name that is not yet in the dcache - the shared lock on ``i_rwsem`` will 273not prevent them both adding new dentries with the same name. As this 274would result in confusion an extra level of interlocking is used, 275based around a secondary hash table (``in_lookup_hashtable``) and a 276per-dentry flag bit (``DCACHE_PAR_LOOKUP``). 277 278To add a new dentry to the cache while only holding a shared lock on 279``i_rwsem``, a thread must call ``d_alloc_parallel()``. This allocates a 280dentry, stores the required name and parent in it, checks if there 281is already a matching dentry in the primary or secondary hash 282tables, and if not, stores the newly allocated dentry in the secondary 283hash table, with ``DCACHE_PAR_LOOKUP`` set. 284 285If a matching dentry was found in the primary hash table then that is 286returned and the caller can know that it lost a race with some other 287thread adding the entry. If no matching dentry is found in either 288cache, the newly allocated dentry is returned and the caller can 289detect this from the presence of ``DCACHE_PAR_LOOKUP``. In this case it 290knows that it has won any race and now is responsible for asking the 291filesystem to perform the lookup and find the matching inode. When 292the lookup is complete, it must call ``d_lookup_done()`` which clears 293the flag and does some other house keeping, including removing the 294dentry from the secondary hash table - it will normally have been 295added to the primary hash table already. Note that a ``struct 296waitqueue_head`` is passed to ``d_alloc_parallel()``, and 297``d_lookup_done()`` must be called while this ``waitqueue_head`` is still 298in scope. 299 300If a matching dentry is found in the secondary hash table, 301``d_alloc_parallel()`` has a little more work to do. It first waits for 302``DCACHE_PAR_LOOKUP`` to be cleared, using a wait_queue that was passed 303to the instance of ``d_alloc_parallel()`` that won the race and that 304will be woken by the call to ``d_lookup_done()``. It then checks to see 305if the dentry has now been added to the primary hash table. If it 306has, the dentry is returned and the caller just sees that it lost any 307race. If it hasn't been added to the primary hash table, the most 308likely explanation is that some other dentry was added instead using 309``d_splice_alias()``. In any case, ``d_alloc_parallel()`` repeats all the 310look ups from the start and will normally return something from the 311primary hash table. 312 313mnt->mnt_count 314~~~~~~~~~~~~~~ 315 316``mnt_count`` is a per-CPU reference counter on "``mount``" structures. 317Per-CPU here means that incrementing the count is cheap as it only 318uses CPU-local memory, but checking if the count is zero is expensive as 319it needs to check with every CPU. Taking a ``mnt_count`` reference 320prevents the mount structure from disappearing as the result of regular 321unmount operations, but does not prevent a "lazy" unmount. So holding 322``mnt_count`` doesn't ensure that the mount remains in the namespace and, 323in particular, doesn't stabilize the link to the mounted-on dentry. It 324does, however, ensure that the ``mount`` data structure remains coherent, 325and it provides a reference to the root dentry of the mounted 326filesystem. So a reference through ``->mnt_count`` provides a stable 327reference to the mounted dentry, but not the mounted-on dentry. 328 329mount_lock 330~~~~~~~~~~ 331 332``mount_lock`` is a global seqlock, a bit like ``rename_lock``. It can be used to 333check if any change has been made to any mount points. 334 335While walking down the tree (away from the root) this lock is used when 336crossing a mount point to check that the crossing was safe. That is, 337the value in the seqlock is read, then the code finds the mount that 338is mounted on the current directory, if there is one, and increments 339the ``mnt_count``. Finally the value in ``mount_lock`` is checked against 340the old value. If there is no change, then the crossing was safe. If there 341was a change, the ``mnt_count`` is decremented and the whole process is 342retried. 343 344When walking up the tree (towards the root) by following a ".." link, 345a little more care is needed. In this case the seqlock (which 346contains both a counter and a spinlock) is fully locked to prevent 347any changes to any mount points while stepping up. This locking is 348needed to stabilize the link to the mounted-on dentry, which the 349refcount on the mount itself doesn't ensure. 350 351RCU 352~~~ 353 354Finally the global (but extremely lightweight) RCU read lock is held 355from time to time to ensure certain data structures don't get freed 356unexpectedly. 357 358In particular it is held while scanning chains in the dcache hash 359table, and the mount point hash table. 360 361Bringing it together with ``struct nameidata`` 362---------------------------------------------- 363 364.. _First edition Unix: http://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/u2.s 365 366Throughout the process of walking a path, the current status is stored 367in a ``struct nameidata``, "namei" being the traditional name - dating 368all the way back to `First Edition Unix`_ - of the function that 369converts a "name" to an "inode". ``struct nameidata`` contains (among 370other fields): 371 372``struct path path`` 373~~~~~~~~~~~~~~~~~~~~ 374 375A ``path`` contains a ``struct vfsmount`` (which is 376embedded in a ``struct mount``) and a ``struct dentry``. Together these 377record the current status of the walk. They start out referring to the 378starting point (the current working directory, the root directory, or some other 379directory identified by a file descriptor), and are updated on each 380step. A reference through ``d_lockref`` and ``mnt_count`` is always 381held. 382 383``struct qstr last`` 384~~~~~~~~~~~~~~~~~~~~ 385 386This is a string together with a length (i.e. _not_ ``nul`` terminated) 387that is the "next" component in the pathname. 388 389``int last_type`` 390~~~~~~~~~~~~~~~~~ 391 392This is one of ``LAST_NORM``, ``LAST_ROOT``, ``LAST_DOT``, ``LAST_DOTDOT``, or 393``LAST_BIND``. The ``last`` field is only valid if the type is 394``LAST_NORM``. ``LAST_BIND`` is used when following a symlink and no 395components of the symlink have been processed yet. Others should be 396fairly self-explanatory. 397 398``struct path root`` 399~~~~~~~~~~~~~~~~~~~~ 400 401This is used to hold a reference to the effective root of the 402filesystem. Often that reference won't be needed, so this field is 403only assigned the first time it is used, or when a non-standard root 404is requested. Keeping a reference in the ``nameidata`` ensures that 405only one root is in effect for the entire path walk, even if it races 406with a ``chroot()`` system call. 407 408The root is needed when either of two conditions holds: (1) either the 409pathname or a symbolic link starts with a "'/'", or (2) a "``..``" 410component is being handled, since "``..``" from the root must always stay 411at the root. The value used is usually the current root directory of 412the calling process. An alternate root can be provided as when 413``sysctl()`` calls ``file_open_root()``, and when NFSv4 or Btrfs call 414``mount_subtree()``. In each case a pathname is being looked up in a very 415specific part of the filesystem, and the lookup must not be allowed to 416escape that subtree. It works a bit like a local ``chroot()``. 417 418Ignoring the handling of symbolic links, we can now describe the 419"``link_path_walk()``" function, which handles the lookup of everything 420except the final component as: 421 422 Given a path (``name``) and a nameidata structure (``nd``), check that the 423 current directory has execute permission and then advance ``name`` 424 over one component while updating ``last_type`` and ``last``. If that 425 was the final component, then return, otherwise call 426 ``walk_component()`` and repeat from the top. 427 428``walk_component()`` is even easier. If the component is ``LAST_DOTS``, 429it calls ``handle_dots()`` which does the necessary locking as already 430described. If it finds a ``LAST_NORM`` component it first calls 431"``lookup_fast()``" which only looks in the dcache, but will ask the 432filesystem to revalidate the result if it is that sort of filesystem. 433If that doesn't get a good result, it calls "``lookup_slow()``" which 434takes ``i_rwsem``, rechecks the cache, and then asks the filesystem 435to find a definitive answer. Each of these will call 436``follow_managed()`` (as described below) to handle any mount points. 437 438In the absence of symbolic links, ``walk_component()`` creates a new 439``struct path`` containing a counted reference to the new dentry and a 440reference to the new ``vfsmount`` which is only counted if it is 441different from the previous ``vfsmount``. It then calls 442``path_to_nameidata()`` to install the new ``struct path`` in the 443``struct nameidata`` and drop the unneeded references. 444 445This "hand-over-hand" sequencing of getting a reference to the new 446dentry before dropping the reference to the previous dentry may 447seem obvious, but is worth pointing out so that we will recognize its 448analogue in the "RCU-walk" version. 449 450Handling the final component 451---------------------------- 452 453``link_path_walk()`` only walks as far as setting ``nd->last`` and 454``nd->last_type`` to refer to the final component of the path. It does 455not call ``walk_component()`` that last time. Handling that final 456component remains for the caller to sort out. Those callers are 457``path_lookupat()``, ``path_parentat()``, ``path_mountpoint()`` and 458``path_openat()`` each of which handles the differing requirements of 459different system calls. 460 461``path_parentat()`` is clearly the simplest - it just wraps a little bit 462of housekeeping around ``link_path_walk()`` and returns the parent 463directory and final component to the caller. The caller will be either 464aiming to create a name (via ``filename_create()``) or remove or rename 465a name (in which case ``user_path_parent()`` is used). They will use 466``i_rwsem`` to exclude other changes while they validate and then 467perform their operation. 468 469``path_lookupat()`` is nearly as simple - it is used when an existing 470object is wanted such as by ``stat()`` or ``chmod()``. It essentially just 471calls ``walk_component()`` on the final component through a call to 472``lookup_last()``. ``path_lookupat()`` returns just the final dentry. 473 474``path_mountpoint()`` handles the special case of unmounting which must 475not try to revalidate the mounted filesystem. It effectively 476contains, through a call to ``mountpoint_last()``, an alternate 477implementation of ``lookup_slow()`` which skips that step. This is 478important when unmounting a filesystem that is inaccessible, such as 479one provided by a dead NFS server. 480 481Finally ``path_openat()`` is used for the ``open()`` system call; it 482contains, in support functions starting with "``do_last()``", all the 483complexity needed to handle the different subtleties of O_CREAT (with 484or without O_EXCL), final "``/``" characters, and trailing symbolic 485links. We will revisit this in the final part of this series, which 486focuses on those symbolic links. "``do_last()``" will sometimes, but 487not always, take ``i_rwsem``, depending on what it finds. 488 489Each of these, or the functions which call them, need to be alert to 490the possibility that the final component is not ``LAST_NORM``. If the 491goal of the lookup is to create something, then any value for 492``last_type`` other than ``LAST_NORM`` will result in an error. For 493example if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller 494won't try to create that name. They also check for trailing slashes 495by testing ``last.name[last.len]``. If there is any character beyond 496the final component, it must be a trailing slash. 497 498Revalidation and automounts 499--------------------------- 500 501Apart from symbolic links, there are only two parts of the "REF-walk" 502process not yet covered. One is the handling of stale cache entries 503and the other is automounts. 504 505On filesystems that require it, the lookup routines will call the 506``->d_revalidate()`` dentry method to ensure that the cached information 507is current. This will often confirm validity or update a few details 508from a server. In some cases it may find that there has been change 509further up the path and that something that was thought to be valid 510previously isn't really. When this happens the lookup of the whole 511path is aborted and retried with the "``LOOKUP_REVAL``" flag set. This 512forces revalidation to be more thorough. We will see more details of 513this retry process in the next article. 514 515Automount points are locations in the filesystem where an attempt to 516lookup a name can trigger changes to how that lookup should be 517handled, in particular by mounting a filesystem there. These are 518covered in greater detail in autofs.txt in the Linux documentation 519tree, but a few notes specifically related to path lookup are in order 520here. 521 522The Linux VFS has a concept of "managed" dentries which is reflected 523in function names such as "``follow_managed()``". There are three 524potentially interesting things about these dentries corresponding 525to three different flags that might be set in ``dentry->d_flags``: 526 527``DCACHE_MANAGE_TRANSIT`` 528~~~~~~~~~~~~~~~~~~~~~~~~~ 529 530If this flag has been set, then the filesystem has requested that the 531``d_manage()`` dentry operation be called before handling any possible 532mount point. This can perform two particular services: 533 534It can block to avoid races. If an automount point is being 535unmounted, the ``d_manage()`` function will usually wait for that 536process to complete before letting the new lookup proceed and possibly 537trigger a new automount. 538 539It can selectively allow only some processes to transit through a 540mount point. When a server process is managing automounts, it may 541need to access a directory without triggering normal automount 542processing. That server process can identify itself to the ``autofs`` 543filesystem, which will then give it a special pass through 544``d_manage()`` by returning ``-EISDIR``. 545 546``DCACHE_MOUNTED`` 547~~~~~~~~~~~~~~~~~~ 548 549This flag is set on every dentry that is mounted on. As Linux 550supports multiple filesystem namespaces, it is possible that the 551dentry may not be mounted on in *this* namespace, just in some 552other. So this flag is seen as a hint, not a promise. 553 554If this flag is set, and ``d_manage()`` didn't return ``-EISDIR``, 555``lookup_mnt()`` is called to examine the mount hash table (honoring the 556``mount_lock`` described earlier) and possibly return a new ``vfsmount`` 557and a new ``dentry`` (both with counted references). 558 559``DCACHE_NEED_AUTOMOUNT`` 560~~~~~~~~~~~~~~~~~~~~~~~~~ 561 562If ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't 563find a mount point, then this flag causes the ``d_automount()`` dentry 564operation to be called. 565 566The ``d_automount()`` operation can be arbitrarily complex and may 567communicate with server processes etc. but it should ultimately either 568report that there was an error, that there was nothing to mount, or 569should provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``. 570 571In the latter case, ``finish_automount()`` will be called to safely 572install the new mount point into the mount table. 573 574There is no new locking of import here and it is important that no 575locks (only counted references) are held over this processing due to 576the very real possibility of extended delays. 577This will become more important next time when we examine RCU-walk 578which is particularly sensitive to delays. 579 580RCU-walk - faster pathname lookup in Linux 581========================================== 582 583RCU-walk is another algorithm for performing pathname lookup in Linux. 584It is in many ways similar to REF-walk and the two share quite a bit 585of code. The significant difference in RCU-walk is how it allows for 586the possibility of concurrent access. 587 588We noted that REF-walk is complex because there are numerous details 589and special cases. RCU-walk reduces this complexity by simply 590refusing to handle a number of cases -- it instead falls back to 591REF-walk. The difficulty with RCU-walk comes from a different 592direction: unfamiliarity. The locking rules when depending on RCU are 593quite different from traditional locking, so we will spend a little extra 594time when we come to those. 595 596Clear demarcation of roles 597-------------------------- 598 599The easiest way to manage concurrency is to forcibly stop any other 600thread from changing the data structures that a given thread is 601looking at. In cases where no other thread would even think of 602changing the data and lots of different threads want to read at the 603same time, this can be very costly. Even when using locks that permit 604multiple concurrent readers, the simple act of updating the count of 605the number of current readers can impose an unwanted cost. So the 606goal when reading a shared data structure that no other process is 607changing is to avoid writing anything to memory at all. Take no 608locks, increment no counts, leave no footprints. 609 610The REF-walk mechanism already described certainly doesn't follow this 611principle, but then it is really designed to work when there may well 612be other threads modifying the data. RCU-walk, in contrast, is 613designed for the common situation where there are lots of frequent 614readers and only occasional writers. This may not be common in all 615parts of the filesystem tree, but in many parts it will be. For the 616other parts it is important that RCU-walk can quickly fall back to 617using REF-walk. 618 619Pathname lookup always starts in RCU-walk mode but only remains there 620as long as what it is looking for is in the cache and is stable. It 621dances lightly down the cached filesystem image, leaving no footprints 622and carefully watching where it is, to be sure it doesn't trip. If it 623notices that something has changed or is changing, or if something 624isn't in the cache, then it tries to stop gracefully and switch to 625REF-walk. 626 627This stopping requires getting a counted reference on the current 628``vfsmount`` and ``dentry``, and ensuring that these are still valid - 629that a path walk with REF-walk would have found the same entries. 630This is an invariant that RCU-walk must guarantee. It can only make 631decisions, such as selecting the next step, that are decisions which 632REF-walk could also have made if it were walking down the tree at the 633same time. If the graceful stop succeeds, the rest of the path is 634processed with the reliable, if slightly sluggish, REF-walk. If 635RCU-walk finds it cannot stop gracefully, it simply gives up and 636restarts from the top with REF-walk. 637 638This pattern of "try RCU-walk, if that fails try REF-walk" can be 639clearly seen in functions like ``filename_lookup()``, 640``filename_parentat()``, ``filename_mountpoint()``, 641``do_filp_open()``, and ``do_file_open_root()``. These five 642correspond roughly to the four ``path_``* functions we met earlier, 643each of which calls ``link_path_walk()``. The ``path_*`` functions are 644called using different mode flags until a mode is found which works. 645They are first called with ``LOOKUP_RCU`` set to request "RCU-walk". If 646that fails with the error ``ECHILD`` they are called again with no 647special flag to request "REF-walk". If either of those report the 648error ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no 649``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly 650revalidated - normally entries are only revalidated if the filesystem 651determines that they are too old to trust. 652 653The ``LOOKUP_RCU`` attempt may drop that flag internally and switch to 654REF-walk, but will never then try to switch back to RCU-walk. Places 655that trip up RCU-walk are much more likely to be near the leaves and 656so it is very unlikely that there will be much, if any, benefit from 657switching back. 658 659RCU and seqlocks: fast and light 660-------------------------------- 661 662RCU is, unsurprisingly, critical to RCU-walk mode. The 663``rcu_read_lock()`` is held for the entire time that RCU-walk is walking 664down a path. The particular guarantee it provides is that the key 665data structures - dentries, inodes, super_blocks, and mounts - will 666not be freed while the lock is held. They might be unlinked or 667invalidated in one way or another, but the memory will not be 668repurposed so values in various fields will still be meaningful. This 669is the only guarantee that RCU provides; everything else is done using 670seqlocks. 671 672As we saw above, REF-walk holds a counted reference to the current 673dentry and the current vfsmount, and does not release those references 674before taking references to the "next" dentry or vfsmount. It also 675sometimes takes the ``d_lock`` spinlock. These references and locks are 676taken to prevent certain changes from happening. RCU-walk must not 677take those references or locks and so cannot prevent such changes. 678Instead, it checks to see if a change has been made, and aborts or 679retries if it has. 680 681To preserve the invariant mentioned above (that RCU-walk may only make 682decisions that REF-walk could have made), it must make the checks at 683or near the same places that REF-walk holds the references. So, when 684REF-walk increments a reference count or takes a spinlock, RCU-walk 685samples the status of a seqlock using ``read_seqcount_begin()`` or a 686similar function. When REF-walk decrements the count or drops the 687lock, RCU-walk checks if the sampled status is still valid using 688``read_seqcount_retry()`` or similar. 689 690However, there is a little bit more to seqlocks than that. If 691RCU-walk accesses two different fields in a seqlock-protected 692structure, or accesses the same field twice, there is no a priori 693guarantee of any consistency between those accesses. When consistency 694is needed - which it usually is - RCU-walk must take a copy and then 695use ``read_seqcount_retry()`` to validate that copy. 696 697``read_seqcount_retry()`` not only checks the sequence number, but also 698imposes a memory barrier so that no memory-read instruction from 699*before* the call can be delayed until *after* the call, either by the 700CPU or by the compiler. A simple example of this can be seen in 701``slow_dentry_cmp()`` which, for filesystems which do not use simple 702byte-wise name equality, calls into the filesystem to compare a name 703against a dentry. The length and name pointer are copied into local 704variables, then ``read_seqcount_retry()`` is called to confirm the two 705are consistent, and only then is ``->d_compare()`` called. When 706standard filename comparison is used, ``dentry_cmp()`` is called 707instead. Notably it does _not_ use ``read_seqcount_retry()``, but 708instead has a large comment explaining why the consistency guarantee 709isn't necessary. A subsequent ``read_seqcount_retry()`` will be 710sufficient to catch any problem that could occur at this point. 711 712With that little refresher on seqlocks out of the way we can look at 713the bigger picture of how RCU-walk uses seqlocks. 714 715``mount_lock`` and ``nd->m_seq`` 716~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 717 718We already met the ``mount_lock`` seqlock when REF-walk used it to 719ensure that crossing a mount point is performed safely. RCU-walk uses 720it for that too, but for quite a bit more. 721 722Instead of taking a counted reference to each ``vfsmount`` as it 723descends the tree, RCU-walk samples the state of ``mount_lock`` at the 724start of the walk and stores this initial sequence number in the 725``struct nameidata`` in the ``m_seq`` field. This one lock and one 726sequence number are used to validate all accesses to all ``vfsmounts``, 727and all mount point crossings. As changes to the mount table are 728relatively rare, it is reasonable to fall back on REF-walk any time 729that any "mount" or "unmount" happens. 730 731``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk 732sequence, whether switching to REF-walk for the rest of the path or 733when the end of the path is reached. It is also checked when stepping 734down over a mount point (in ``__follow_mount_rcu()``) or up (in 735``follow_dotdot_rcu()``). If it is ever found to have changed, the 736whole RCU-walk sequence is aborted and the path is processed again by 737REF-walk. 738 739If RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure 740that, had REF-walk taken counted references on each vfsmount, the 741results would have been the same. This ensures the invariant holds, 742at least for vfsmount structures. 743 744``dentry->d_seq`` and ``nd->seq`` 745~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 746 747In place of taking a count or lock on ``d_reflock``, RCU-walk samples 748the per-dentry ``d_seq`` seqlock, and stores the sequence number in the 749``seq`` field of the nameidata structure, so ``nd->seq`` should always be 750the current sequence number of ``nd->dentry``. This number needs to be 751revalidated after copying, and before using, the name, parent, or 752inode of the dentry. 753 754The handling of the name we have already looked at, and the parent is 755only accessed in ``follow_dotdot_rcu()`` which fairly trivially follows 756the required pattern, though it does so for three different cases. 757 758When not at a mount point, ``d_parent`` is followed and its ``d_seq`` is 759collected. When we are at a mount point, we instead follow the 760``mnt->mnt_mountpoint`` link to get a new dentry and collect its 761``d_seq``. Then, after finally finding a ``d_parent`` to follow, we must 762check if we have landed on a mount point and, if so, must find that 763mount point and follow the ``mnt->mnt_root`` link. This would imply a 764somewhat unusual, but certainly possible, circumstance where the 765starting point of the path lookup was in part of the filesystem that 766was mounted on, and so not visible from the root. 767 768The inode pointer, stored in ``->d_inode``, is a little more 769interesting. The inode will always need to be accessed at least 770twice, once to determine if it is NULL and once to verify access 771permissions. Symlink handling requires a validated inode pointer too. 772Rather than revalidating on each access, a copy is made on the first 773access and it is stored in the ``inode`` field of ``nameidata`` from where 774it can be safely accessed without further validation. 775 776``lookup_fast()`` is the only lookup routine that is used in RCU-mode, 777``lookup_slow()`` being too slow and requiring locks. It is in 778``lookup_fast()`` that we find the important "hand over hand" tracking 779of the current dentry. 780 781The current ``dentry`` and current ``seq`` number are passed to 782``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a 783new ``seq`` number. ``lookup_fast()`` then copies the inode pointer and 784revalidates the new ``seq`` number. It then validates the old ``dentry`` 785with the old ``seq`` number one last time and only then continues. This 786process of getting the ``seq`` number of the new dentry and then 787checking the ``seq`` number of the old exactly mirrors the process of 788getting a counted reference to the new dentry before dropping that for 789the old dentry which we saw in REF-walk. 790 791No ``inode->i_rwsem`` or even ``rename_lock`` 792~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 793 794A semaphore is a fairly heavyweight lock that can only be taken when it is 795permissible to sleep. As ``rcu_read_lock()`` forbids sleeping, 796``inode->i_rwsem`` plays no role in RCU-walk. If some other thread does 797take ``i_rwsem`` and modifies the directory in a way that RCU-walk needs 798to notice, the result will be either that RCU-walk fails to find the 799dentry that it is looking for, or it will find a dentry which 800``read_seqretry()`` won't validate. In either case it will drop down to 801REF-walk mode which can take whatever locks are needed. 802 803Though ``rename_lock`` could be used by RCU-walk as it doesn't require 804any sleeping, RCU-walk doesn't bother. REF-walk uses ``rename_lock`` to 805protect against the possibility of hash chains in the dcache changing 806while they are being searched. This can result in failing to find 807something that actually is there. When RCU-walk fails to find 808something in the dentry cache, whether it is really there or not, it 809already drops down to REF-walk and tries again with appropriate 810locking. This neatly handles all cases, so adding extra checks on 811rename_lock would bring no significant value. 812 813``unlazy walk()`` and ``complete_walk()`` 814----------------------------------------- 815 816That "dropping down to REF-walk" typically involves a call to 817``unlazy_walk()``, so named because "RCU-walk" is also sometimes 818referred to as "lazy walk". ``unlazy_walk()`` is called when 819following the path down to the current vfsmount/dentry pair seems to 820have proceeded successfully, but the next step is problematic. This 821can happen if the next name cannot be found in the dcache, if 822permission checking or name revalidation couldn't be achieved while 823the ``rcu_read_lock()`` is held (which forbids sleeping), if an 824automount point is found, or in a couple of cases involving symlinks. 825It is also called from ``complete_walk()`` when the lookup has reached 826the final component, or the very end of the path, depending on which 827particular flavor of lookup is used. 828 829Other reasons for dropping out of RCU-walk that do not trigger a call 830to ``unlazy_walk()`` are when some inconsistency is found that cannot be 831handled immediately, such as ``mount_lock`` or one of the ``d_seq`` 832seqlocks reporting a change. In these cases the relevant function 833will return ``-ECHILD`` which will percolate up until it triggers a new 834attempt from the top using REF-walk. 835 836For those cases where ``unlazy_walk()`` is an option, it essentially 837takes a reference on each of the pointers that it holds (vfsmount, 838dentry, and possibly some symbolic links) and then verifies that the 839relevant seqlocks have not been changed. If there have been changes, 840it, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk 841has been a success and the lookup process continues. 842 843Taking a reference on those pointers is not quite as simple as just 844incrementing a counter. That works to take a second reference if you 845already have one (often indirectly through another object), but it 846isn't sufficient if you don't actually have a counted reference at 847all. For ``dentry->d_lockref``, it is safe to increment the reference 848counter to get a reference unless it has been explicitly marked as 849"dead" which involves setting the counter to ``-128``. 850``lockref_get_not_dead()`` achieves this. 851 852For ``mnt->mnt_count`` it is safe to take a reference as long as 853``mount_lock`` is then used to validate the reference. If that 854validation fails, it may *not* be safe to just drop that reference in 855the standard way of calling ``mnt_put()`` - an unmount may have 856progressed too far. So the code in ``legitimize_mnt()``, when it 857finds that the reference it got might not be safe, checks the 858``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is 859correct, or if it should just decrement the count and pretend none of 860this ever happened. 861 862Taking care in filesystems 863-------------------------- 864 865RCU-walk depends almost entirely on cached information and often will 866not call into the filesystem at all. However there are two places, 867besides the already-mentioned component-name comparison, where the 868file system might be included in RCU-walk, and it must know to be 869careful. 870 871If the filesystem has non-standard permission-checking requirements - 872such as a networked filesystem which may need to check with the server 873- the ``i_op->permission`` interface might be called during RCU-walk. 874In this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it 875knows not to sleep, but to return ``-ECHILD`` if it cannot complete 876promptly. ``i_op->permission`` is given the inode pointer, not the 877dentry, so it doesn't need to worry about further consistency checks. 878However if it accesses any other filesystem data structures, it must 879ensure they are safe to be accessed with only the ``rcu_read_lock()`` 880held. This typically means they must be freed using ``kfree_rcu()`` or 881similar. 882 883.. _READ_ONCE: https://lwn.net/Articles/624126/ 884 885If the filesystem may need to revalidate dcache entries, then 886``d_op->d_revalidate`` may be called in RCU-walk too. This interface 887*is* passed the dentry but does not have access to the ``inode`` or the 888``seq`` number from the ``nameidata``, so it needs to be extra careful 889when accessing fields in the dentry. This "extra care" typically 890involves using `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the 891result is not NULL before using it. This pattern can be seen in 892``nfs_lookup_revalidate()``. 893 894A pair of patterns 895------------------ 896 897In various places in the details of REF-walk and RCU-walk, and also in 898the big picture, there are a couple of related patterns that are worth 899being aware of. 900 901The first is "try quickly and check, if that fails try slowly". We 902can see that in the high-level approach of first trying RCU-walk and 903then trying REF-walk, and in places where ``unlazy_walk()`` is used to 904switch to REF-walk for the rest of the path. We also saw it earlier 905in ``dget_parent()`` when following a "``..``" link. It tries a quick way 906to get a reference, then falls back to taking locks if needed. 907 908The second pattern is "try quickly and check, if that fails try 909again - repeatedly". This is seen with the use of ``rename_lock`` and 910``mount_lock`` in REF-walk. RCU-walk doesn't make use of this pattern - 911if anything goes wrong it is much safer to just abort and try a more 912sedate approach. 913 914The emphasis here is "try quickly and check". It should probably be 915"try quickly _and carefully,_ then check". The fact that checking is 916needed is a reminder that the system is dynamic and only a limited 917number of things are safe at all. The most likely cause of errors in 918this whole process is assuming something is safe when in reality it 919isn't. Careful consideration of what exactly guarantees the safety of 920each access is sometimes necessary. 921 922A walk among the symlinks 923========================= 924 925There are several basic issues that we will examine to understand the 926handling of symbolic links: the symlink stack, together with cache 927lifetimes, will help us understand the overall recursive handling of 928symlinks and lead to the special care needed for the final component. 929Then a consideration of access-time updates and summary of the various 930flags controlling lookup will finish the story. 931 932The symlink stack 933----------------- 934 935There are only two sorts of filesystem objects that can usefully 936appear in a path prior to the final component: directories and symlinks. 937Handling directories is quite straightforward: the new directory 938simply becomes the starting point at which to interpret the next 939component on the path. Handling symbolic links requires a bit more 940work. 941 942Conceptually, symbolic links could be handled by editing the path. If 943a component name refers to a symbolic link, then that component is 944replaced by the body of the link and, if that body starts with a '/', 945then all preceding parts of the path are discarded. This is what the 946"``readlink -f``" command does, though it also edits out "``.``" and 947"``..``" components. 948 949Directly editing the path string is not really necessary when looking 950up a path, and discarding early components is pointless as they aren't 951looked at anyway. Keeping track of all remaining components is 952important, but they can of course be kept separately; there is no need 953to concatenate them. As one symlink may easily refer to another, 954which in turn can refer to a third, we may need to keep the remaining 955components of several paths, each to be processed when the preceding 956ones are completed. These path remnants are kept on a stack of 957limited size. 958 959There are two reasons for placing limits on how many symlinks can 960occur in a single path lookup. The most obvious is to avoid loops. 961If a symlink referred to itself either directly or through 962intermediaries, then following the symlink can never complete 963successfully - the error ``ELOOP`` must be returned. Loops can be 964detected without imposing limits, but limits are the simplest solution 965and, given the second reason for restriction, quite sufficient. 966 967.. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550 968 969The second reason was `outlined recently`_ by Linus: 970 971 Because it's a latency and DoS issue too. We need to react well to 972 true loops, but also to "very deep" non-loops. It's not about memory 973 use, it's about users triggering unreasonable CPU resources. 974 975Linux imposes a limit on the length of any pathname: ``PATH_MAX``, which 976is 4096. There are a number of reasons for this limit; not letting the 977kernel spend too much time on just one path is one of them. With 978symbolic links you can effectively generate much longer paths so some 979sort of limit is needed for the same reason. Linux imposes a limit of 980at most 40 symlinks in any one path lookup. It previously imposed a 981further limit of eight on the maximum depth of recursion, but that was 982raised to 40 when a separate stack was implemented, so there is now 983just the one limit. 984 985The ``nameidata`` structure that we met in an earlier article contains a 986small stack that can be used to store the remaining part of up to two 987symlinks. In many cases this will be sufficient. If it isn't, a 988separate stack is allocated with room for 40 symlinks. Pathname 989lookup will never exceed that stack as, once the 40th symlink is 990detected, an error is returned. 991 992It might seem that the name remnants are all that needs to be stored on 993this stack, but we need a bit more. To see that, we need to move on to 994cache lifetimes. 995 996Storage and lifetime of cached symlinks 997--------------------------------------- 998 999Like other filesystem resources, such as inodes and directory 1000entries, symlinks are cached by Linux to avoid repeated costly access 1001to external storage. It is particularly important for RCU-walk to be 1002able to find and temporarily hold onto these cached entries, so that 1003it doesn't need to drop down into REF-walk. 1004 1005.. _object-oriented design pattern: https://lwn.net/Articles/446317/ 1006 1007While each filesystem is free to make its own choice, symlinks are 1008typically stored in one of two places. Short symlinks are often 1009stored directly in the inode. When a filesystem allocates a ``struct 1010inode`` it typically allocates extra space to store private data (a 1011common `object-oriented design pattern`_ in the kernel). This will 1012sometimes include space for a symlink. The other common location is 1013in the page cache, which normally stores the content of files. The 1014pathname in a symlink can be seen as the content of that symlink and 1015can easily be stored in the page cache just like file content. 1016 1017When neither of these is suitable, the next most likely scenario is 1018that the filesystem will allocate some temporary memory and copy or 1019construct the symlink content into that memory whenever it is needed. 1020 1021When the symlink is stored in the inode, it has the same lifetime as 1022the inode which, itself, is protected by RCU or by a counted reference 1023on the dentry. This means that the mechanisms that pathname lookup 1024uses to access the dcache and icache (inode cache) safely are quite 1025sufficient for accessing some cached symlinks safely. In these cases, 1026the ``i_link`` pointer in the inode is set to point to wherever the 1027symlink is stored and it can be accessed directly whenever needed. 1028 1029When the symlink is stored in the page cache or elsewhere, the 1030situation is not so straightforward. A reference on a dentry or even 1031on an inode does not imply any reference on cached pages of that 1032inode, and even an ``rcu_read_lock()`` is not sufficient to ensure that 1033a page will not disappear. So for these symlinks the pathname lookup 1034code needs to ask the filesystem to provide a stable reference and, 1035significantly, needs to release that reference when it is finished 1036with it. 1037 1038Taking a reference to a cache page is often possible even in RCU-walk 1039mode. It does require making changes to memory, which is best avoided, 1040but that isn't necessarily a big cost and it is better than dropping 1041out of RCU-walk mode completely. Even filesystems that allocate 1042space to copy the symlink into can use ``GFP_ATOMIC`` to often successfully 1043allocate memory without the need to drop out of RCU-walk. If a 1044filesystem cannot successfully get a reference in RCU-walk mode, it 1045must return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to 1046REF-walk mode in which the filesystem is allowed to sleep. 1047 1048The place for all this to happen is the ``i_op->follow_link()`` inode 1049method. In the present mainline code this is never actually called in 1050RCU-walk mode as the rewrite is not quite complete. It is likely that 1051in a future release this method will be passed an ``inode`` pointer when 1052called in RCU-walk mode so it both (1) knows to be careful, and (2) has the 1053validated pointer. Much like the ``i_op->permission()`` method we 1054looked at previously, ``->follow_link()`` would need to be careful that 1055all the data structures it references are safe to be accessed while 1056holding no counted reference, only the RCU lock. Though getting a 1057reference with ``->follow_link()`` is not yet done in RCU-walk mode, the 1058code is ready to release the reference when that does happen. 1059 1060This need to drop the reference to a symlink adds significant 1061complexity. It requires a reference to the inode so that the 1062``i_op->put_link()`` inode operation can be called. In REF-walk, that 1063reference is kept implicitly through a reference to the dentry, so 1064keeping the ``struct path`` of the symlink is easiest. For RCU-walk, 1065the pointer to the inode is kept separately. To allow switching from 1066RCU-walk back to REF-walk in the middle of processing nested symlinks 1067we also need the seq number for the dentry so we can confirm that 1068switching back was safe. 1069 1070Finally, when providing a reference to a symlink, the filesystem also 1071provides an opaque "cookie" that must be passed to ``->put_link()`` so that it 1072knows what to free. This might be the allocated memory area, or a 1073pointer to the ``struct page`` in the page cache, or something else 1074completely. Only the filesystem knows what it is. 1075 1076In order for the reference to each symlink to be dropped when the walk completes, 1077whether in RCU-walk or REF-walk, the symlink stack needs to contain, 1078along with the path remnants: 1079 1080- the ``struct path`` to provide a reference to the inode in REF-walk 1081- the ``struct inode *`` to provide a reference to the inode in RCU-walk 1082- the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk 1083- the ``cookie`` that tells ``->put_path()`` what to put. 1084 1085This means that each entry in the symlink stack needs to hold five 1086pointers and an integer instead of just one pointer (the path 1087remnant). On a 64-bit system, this is about 40 bytes per entry; 1088with 40 entries it adds up to 1600 bytes total, which is less than 1089half a page. So it might seem like a lot, but is by no means 1090excessive. 1091 1092Note that, in a given stack frame, the path remnant (``name``) is not 1093part of the symlink that the other fields refer to. It is the remnant 1094to be followed once that symlink has been fully parsed. 1095 1096Following the symlink 1097--------------------- 1098 1099The main loop in ``link_path_walk()`` iterates seamlessly over all 1100components in the path and all of the non-final symlinks. As symlinks 1101are processed, the ``name`` pointer is adjusted to point to a new 1102symlink, or is restored from the stack, so that much of the loop 1103doesn't need to notice. Getting this ``name`` variable on and off the 1104stack is very straightforward; pushing and popping the references is 1105a little more complex. 1106 1107When a symlink is found, ``walk_component()`` returns the value ``1`` 1108(``0`` is returned for any other sort of success, and a negative number 1109is, as usual, an error indicator). This causes ``get_link()`` to be 1110called; it then gets the link from the filesystem. Providing that 1111operation is successful, the old path ``name`` is placed on the stack, 1112and the new value is used as the ``name`` for a while. When the end of 1113the path is found (i.e. ``*name`` is ``'\0'``) the old ``name`` is restored 1114off the stack and path walking continues. 1115 1116Pushing and popping the reference pointers (inode, cookie, etc.) is more 1117complex in part because of the desire to handle tail recursion. When 1118the last component of a symlink itself points to a symlink, we 1119want to pop the symlink-just-completed off the stack before pushing 1120the symlink-just-found to avoid leaving empty path remnants that would 1121just get in the way. 1122 1123It is most convenient to push the new symlink references onto the 1124stack in ``walk_component()`` immediately when the symlink is found; 1125``walk_component()`` is also the last piece of code that needs to look at the 1126old symlink as it walks that last component. So it is quite 1127convenient for ``walk_component()`` to release the old symlink and pop 1128the references just before pushing the reference information for the 1129new symlink. It is guided in this by two flags; ``WALK_GET``, which 1130gives it permission to follow a symlink if it finds one, and 1131``WALK_PUT``, which tells it to release the current symlink after it has been 1132followed. ``WALK_PUT`` is tested first, leading to a call to 1133``put_link()``. ``WALK_GET`` is tested subsequently (by 1134``should_follow_link()``) leading to a call to ``pick_link()`` which sets 1135up the stack frame. 1136 1137Symlinks with no final component 1138~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1139 1140A pair of special-case symlinks deserve a little further explanation. 1141Both result in a new ``struct path`` (with mount and dentry) being set 1142up in the ``nameidata``, and result in ``get_link()`` returning ``NULL``. 1143 1144The more obvious case is a symlink to "``/``". All symlinks starting 1145with "``/``" are detected in ``get_link()`` which resets the ``nameidata`` 1146to point to the effective filesystem root. If the symlink only 1147contains "``/``" then there is nothing more to do, no components at all, 1148so ``NULL`` is returned to indicate that the symlink can be released and 1149the stack frame discarded. 1150 1151The other case involves things in ``/proc`` that look like symlinks but 1152aren't really:: 1153 1154 $ ls -l /proc/self/fd/1 1155 lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4 1156 1157Every open file descriptor in any process is represented in ``/proc`` by 1158something that looks like a symlink. It is really a reference to the 1159target file, not just the name of it. When you ``readlink`` these 1160objects you get a name that might refer to the same file - unless it 1161has been unlinked or mounted over. When ``walk_component()`` follows 1162one of these, the ``->follow_link()`` method in "procfs" doesn't return 1163a string name, but instead calls ``nd_jump_link()`` which updates the 1164``nameidata`` in place to point to that target. ``->follow_link()`` then 1165returns ``NULL``. Again there is no final component and ``get_link()`` 1166reports this by leaving the ``last_type`` field of ``nameidata`` as 1167``LAST_BIND``. 1168 1169Following the symlink in the final component 1170-------------------------------------------- 1171 1172All this leads to ``link_path_walk()`` walking down every component, and 1173following all symbolic links it finds, until it reaches the final 1174component. This is just returned in the ``last`` field of ``nameidata``. 1175For some callers, this is all they need; they want to create that 1176``last`` name if it doesn't exist or give an error if it does. Other 1177callers will want to follow a symlink if one is found, and possibly 1178apply special handling to the last component of that symlink, rather 1179than just the last component of the original file name. These callers 1180potentially need to call ``link_path_walk()`` again and again on 1181successive symlinks until one is found that doesn't point to another 1182symlink. 1183 1184This case is handled by the relevant caller of ``link_path_walk()``, such as 1185``path_lookupat()`` using a loop that calls ``link_path_walk()``, and then 1186handles the final component. If the final component is a symlink 1187that needs to be followed, then ``trailing_symlink()`` is called to set 1188things up properly and the loop repeats, calling ``link_path_walk()`` 1189again. This could loop as many as 40 times if the last component of 1190each symlink is another symlink. 1191 1192The various functions that examine the final component and possibly 1193report that it is a symlink are ``lookup_last()``, ``mountpoint_last()`` 1194and ``do_last()``, each of which use the same convention as 1195``walk_component()`` of returning ``1`` if a symlink was found that needs 1196to be followed. 1197 1198Of these, ``do_last()`` is the most interesting as it is used for 1199opening a file. Part of ``do_last()`` runs with ``i_rwsem`` held and this 1200part is in a separate function: ``lookup_open()``. 1201 1202Explaining ``do_last()`` completely is beyond the scope of this article, 1203but a few highlights should help those interested in exploring the 1204code. 1205 12061. Rather than just finding the target file, ``do_last()`` needs to open 1207 it. If the file was found in the dcache, then ``vfs_open()`` is used for 1208 this. If not, then ``lookup_open()`` will either call ``atomic_open()`` (if 1209 the filesystem provides it) to combine the final lookup with the open, or 1210 will perform the separate ``lookup_real()`` and ``vfs_create()`` steps 1211 directly. In the later case the actual "open" of this newly found or 1212 created file will be performed by ``vfs_open()``, just as if the name 1213 were found in the dcache. 1214 12152. ``vfs_open()`` can fail with ``-EOPENSTALE`` if the cached information 1216 wasn't quite current enough. Rather than restarting the lookup from 1217 the top with ``LOOKUP_REVAL`` set, ``lookup_open()`` is called instead, 1218 giving the filesystem a chance to resolve small inconsistencies. 1219 If that doesn't work, only then is the lookup restarted from the top. 1220 12213. An open with O_CREAT **does** follow a symlink in the final component, 1222 unlike other creation system calls (like ``mkdir``). So the sequence:: 1223 1224 ln -s bar /tmp/foo 1225 echo hello > /tmp/foo 1226 1227 will create a file called ``/tmp/bar``. This is not permitted if 1228 ``O_EXCL`` is set but otherwise is handled for an O_CREAT open much 1229 like for a non-creating open: ``should_follow_link()`` returns ``1``, and 1230 so does ``do_last()`` so that ``trailing_symlink()`` gets called and the 1231 open process continues on the symlink that was found. 1232 1233Updating the access time 1234------------------------ 1235 1236We previously said of RCU-walk that it would "take no locks, increment 1237no counts, leave no footprints." We have since seen that some 1238"footprints" can be needed when handling symlinks as a counted 1239reference (or even a memory allocation) may be needed. But these 1240footprints are best kept to a minimum. 1241 1242One other place where walking down a symlink can involve leaving 1243footprints in a way that doesn't affect directories is in updating access times. 1244In Unix (and Linux) every filesystem object has a "last accessed 1245time", or "``atime``". Passing through a directory to access a file 1246within is not considered to be an access for the purposes of 1247``atime``; only listing the contents of a directory can update its ``atime``. 1248Symlinks are different it seems. Both reading a symlink (with ``readlink()``) 1249and looking up a symlink on the way to some other destination can 1250update the atime on that symlink. 1251 1252.. _clearest statement: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08 1253 1254It is not clear why this is the case; POSIX has little to say on the 1255subject. The `clearest statement`_ is that, if a particular implementation 1256updates a timestamp in a place not specified by POSIX, this must be 1257documented "except that any changes caused by pathname resolution need 1258not be documented". This seems to imply that POSIX doesn't really 1259care about access-time updates during pathname lookup. 1260 1261.. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8 1262 1263An examination of history shows that prior to `Linux 1.3.87`_, the ext2 1264filesystem, at least, didn't update atime when following a link. 1265Unfortunately we have no record of why that behavior was changed. 1266 1267In any case, access time must now be updated and that operation can be 1268quite complex. Trying to stay in RCU-walk while doing it is best 1269avoided. Fortunately it is often permitted to skip the ``atime`` 1270update. Because ``atime`` updates cause performance problems in various 1271areas, Linux supports the ``relatime`` mount option, which generally 1272limits the updates of ``atime`` to once per day on files that aren't 1273being changed (and symlinks never change once created). Even without 1274``relatime``, many filesystems record ``atime`` with a one-second 1275granularity, so only one update per second is required. 1276 1277It is easy to test if an ``atime`` update is needed while in RCU-walk 1278mode and, if it isn't, the update can be skipped and RCU-walk mode 1279continues. Only when an ``atime`` update is actually required does the 1280path walk drop down to REF-walk. All of this is handled in the 1281``get_link()`` function. 1282 1283A few flags 1284----------- 1285 1286A suitable way to wrap up this tour of pathname walking is to list 1287the various flags that can be stored in the ``nameidata`` to guide the 1288lookup process. Many of these are only meaningful on the final 1289component, others reflect the current state of the pathname lookup. 1290And then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with 1291the others. If this is not set, an empty pathname causes an error 1292very early on. If it is set, empty pathnames are not considered to be 1293an error. 1294 1295Global state flags 1296~~~~~~~~~~~~~~~~~~ 1297 1298We have already met two global state flags: ``LOOKUP_RCU`` and 1299``LOOKUP_REVAL``. These select between one of three overall approaches 1300to lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation. 1301 1302``LOOKUP_PARENT`` indicates that the final component hasn't been reached 1303yet. This is primarily used to tell the audit subsystem the full 1304context of a particular access being audited. 1305 1306``LOOKUP_ROOT`` indicates that the ``root`` field in the ``nameidata`` was 1307provided by the caller, so it shouldn't be released when it is no 1308longer needed. 1309 1310``LOOKUP_JUMPED`` means that the current dentry was chosen not because 1311it had the right name but for some other reason. This happens when 1312following "``..``", following a symlink to ``/``, crossing a mount point 1313or accessing a "``/proc/$PID/fd/$FD``" symlink. In this case the 1314filesystem has not been asked to revalidate the name (with 1315``d_revalidate()``). In such cases the inode may still need to be 1316revalidated, so ``d_op->d_weak_revalidate()`` is called if 1317``LOOKUP_JUMPED`` is set when the look completes - which may be at the 1318final component or, when creating, unlinking, or renaming, at the penultimate component. 1319 1320Final-component flags 1321~~~~~~~~~~~~~~~~~~~~~ 1322 1323Some of these flags are only set when the final component is being 1324considered. Others are only checked for when considering that final 1325component. 1326 1327``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount 1328point, then the mount is triggered. Some operations would trigger it 1329anyway, but operations like ``stat()`` deliberately don't. ``statfs()`` 1330needs to trigger the mount but otherwise behaves a lot like ``stat()``, so 1331it sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of 1332"``mount --bind``". 1333 1334``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for 1335symlinks. Some system calls set or clear it implicitly, while 1336others have API flags such as ``AT_SYMLINK_FOLLOW`` and 1337``UMOUNT_NOFOLLOW`` to control it. Its effect is similar to 1338``WALK_GET`` that we already met, but it is used in a different way. 1339 1340``LOOKUP_DIRECTORY`` insists that the final component is a directory. 1341Various callers set this and it is also set when the final component 1342is found to be followed by a slash. 1343 1344Finally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and 1345``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made 1346available to the filesystem and particularly the ``->d_revalidate()`` 1347method. A filesystem can choose not to bother revalidating too hard 1348if it knows that it will be asked to open or create the file soon. 1349These flags were previously useful for ``->lookup()`` too but with the 1350introduction of ``->atomic_open()`` they are less relevant there. 1351 1352End of the road 1353--------------- 1354 1355Despite its complexity, all this pathname lookup code appears to be 1356in good shape - various parts are certainly easier to understand now 1357than even a couple of releases ago. But that doesn't mean it is 1358"finished". As already mentioned, RCU-walk currently only follows 1359symlinks that are stored in the inode so, while it handles many ext4 1360symlinks, it doesn't help with NFS, XFS, or Btrfs. That support 1361is not likely to be long delayed. 1362