Blame view

Documentation/filesystems/path-lookup.rst 71 KB
4064174be   Jonathan Corbet   docs: Bring some ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  ===============
  Pathname lookup
  ===============
  
  This write-up is based on three articles published at lwn.net:
  
  - <https://lwn.net/Articles/649115/> Pathname lookup in Linux
  - <https://lwn.net/Articles/649729/> RCU-walk: faster pathname lookup in Linux
  - <https://lwn.net/Articles/650786/> A walk among the symlinks
  
  Written by Neil Brown with help from Al Viro and Jon Corbet.
  It has subsequently been updated to reflect changes in the kernel
  including:
  
  - per-directory parallel name lookup.
b55eef872   Aleksa Sarai   Documentation: pa...
16
  - ``openat2()`` resolution restriction flags.
3ce96239d   Neil Brown   Documentation: ad...
17

7bbfd9ad8   NeilBrown   Documentation: co...
18
19
  Introduction to pathname lookup
  ===============================
3ce96239d   Neil Brown   Documentation: ad...
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  
  The most obvious aspect of pathname lookup, which very little
  exploration is needed to discover, is that it is complex.  There are
  many rules, special cases, and implementation alternatives that all
  combine to confuse the unwary reader.  Computer science has long been
  acquainted with such complexity and has tools to help manage it.  One
  tool that we will make extensive use of is "divide and conquer".  For
  the early parts of the analysis we will divide off symlinks - leaving
  them until the final part.  Well before we get to symlinks we have
  another major division based on the VFS's approach to locking which
  will allow us to review "REF-walk" and "RCU-walk" separately.  But we
  are getting ahead of ourselves.  There are some important low level
  distinctions we need to clarify first.
  
  There are two sorts of ...
  --------------------------
7bbfd9ad8   NeilBrown   Documentation: co...
36
  .. _openat: http://man7.org/linux/man-pages/man2/openat.2.html
3ce96239d   Neil Brown   Documentation: ad...
37
38
39
  
  Pathnames (sometimes "file names"), used to identify objects in the
  filesystem, will be familiar to most readers.  They contain two sorts
7bbfd9ad8   NeilBrown   Documentation: co...
40
  of elements: "slashes" that are sequences of one or more "``/``"
3ce96239d   Neil Brown   Documentation: ad...
41
  characters, and "components" that are sequences of one or more
7bbfd9ad8   NeilBrown   Documentation: co...
42
  non-"``/``" characters.  These form two kinds of paths.  Those that
3ce96239d   Neil Brown   Documentation: ad...
43
44
  start with slashes are "absolute" and start from the filesystem root.
  The others are "relative" and start from the current directory, or
87b92d4b8   Vegard Nossum   docs: path-lookup...
45
46
  from some other location specified by a file descriptor given to
  "``*at()``" system calls such as `openat() <openat_>`_.
3ce96239d   Neil Brown   Documentation: ad...
47

7bbfd9ad8   NeilBrown   Documentation: co...
48
  .. _execveat: http://man7.org/linux/man-pages/man2/execveat.2.html
3ce96239d   Neil Brown   Documentation: ad...
49
50
51
52
  
  It is tempting to describe the second kind as starting with a
  component, but that isn't always accurate: a pathname can lack both
  slashes and components, it can be empty, in other words.  This is
87b92d4b8   Vegard Nossum   docs: path-lookup...
53
  generally forbidden in POSIX, but some of those "``*at()``" system calls
7bbfd9ad8   NeilBrown   Documentation: co...
54
  in Linux permit it when the ``AT_EMPTY_PATH`` flag is given.  For
3ce96239d   Neil Brown   Documentation: ad...
55
  example, if you have an open file descriptor on an executable file you
7bbfd9ad8   NeilBrown   Documentation: co...
56
57
  can execute it by calling `execveat() <execveat_>`_ passing
  the file descriptor, an empty path, and the ``AT_EMPTY_PATH`` flag.
3ce96239d   Neil Brown   Documentation: ad...
58
59
60
61
  
  These paths can be divided into two sections: the final component and
  everything else.  The "everything else" is the easy bit.  In all cases
  it must identify a directory that already exists, otherwise an error
7bbfd9ad8   NeilBrown   Documentation: co...
62
  such as ``ENOENT`` or ``ENOTDIR`` will be reported.
3ce96239d   Neil Brown   Documentation: ad...
63
64
65
66
67
  
  The final component is not so simple.  Not only do different system
  calls interpret it quite differently (e.g. some create it, some do
  not), but it might not even exist: neither the empty pathname nor the
  pathname that is just slashes have a final component.  If it does
7bbfd9ad8   NeilBrown   Documentation: co...
68
  exist, it could be "``.``" or "``..``" which are handled quite differently
3ce96239d   Neil Brown   Documentation: ad...
69
  from other components.
c69f22f25   Alexander A. Klimov   Replace HTTP link...
70
  .. _POSIX: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
3ce96239d   Neil Brown   Documentation: ad...
71

7bbfd9ad8   NeilBrown   Documentation: co...
72
  If a pathname ends with a slash, such as "``/tmp/foo/``" it might be
3ce96239d   Neil Brown   Documentation: ad...
73
74
  tempting to consider that to have an empty final component.  In many
  ways that would lead to correct results, but not always.  In
7bbfd9ad8   NeilBrown   Documentation: co...
75
  particular, ``mkdir()`` and ``rmdir()`` each create or remove a directory named
3ce96239d   Neil Brown   Documentation: ad...
76
  by the final component, and they are required to work with pathnames
ad551a21c   Vegard Nossum   docs: path-lookup...
77
  ending in "``/``".  According to POSIX_:
3ce96239d   Neil Brown   Documentation: ad...
78

ad551a21c   Vegard Nossum   docs: path-lookup...
79
80
    A pathname that contains at least one non-<slash> character and
    that ends with one or more trailing <slash> characters shall not
7bbfd9ad8   NeilBrown   Documentation: co...
81
82
83
84
    be resolved successfully unless the last pathname component before
    the trailing <slash> characters names an existing directory or a
    directory entry that is to be created for a directory immediately
    after the pathname is resolved.
3ce96239d   Neil Brown   Documentation: ad...
85

7bbfd9ad8   NeilBrown   Documentation: co...
86
  The Linux pathname walking code (mostly in ``fs/namei.c``) deals with
3ce96239d   Neil Brown   Documentation: ad...
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
  all of these issues: breaking the path into components, handling the
  "everything else" quite separately from the final component, and
  checking that the trailing slash is not used where it isn't
  permitted.  It also addresses the important issue of concurrent
  access.
  
  While one process is looking up a pathname, another might be making
  changes that affect that lookup.  One fairly extreme case is that if
  "a/b" were renamed to "a/c/b" while another process were looking up
  "a/b/..", that process might successfully resolve on "a/c".
  Most races are much more subtle, and a big part of the task of
  pathname lookup is to prevent them from having damaging effects.  Many
  of the possible races are seen most clearly in the context of the
  "dcache" and an understanding of that is central to understanding
  pathname lookup.
7bbfd9ad8   NeilBrown   Documentation: co...
102
103
  More than just a cache
  ----------------------
3ce96239d   Neil Brown   Documentation: ad...
104
105
106
107
108
109
  
  The "dcache" caches information about names in each filesystem to
  make them quickly available for lookup.  Each entry (known as a
  "dentry") contains three significant fields: a component name, a
  pointer to a parent dentry, and a pointer to the "inode" which
  contains further information about the object in that parent with
7bbfd9ad8   NeilBrown   Documentation: co...
110
  the given name.  The inode pointer can be ``NULL`` indicating that the
3ce96239d   Neil Brown   Documentation: ad...
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
  name doesn't exist in the parent.  While there can be linkage in the
  dentry of a directory to the dentries of the children, that linkage is
  not used for pathname lookup, and so will not be considered here.
  
  The dcache has a number of uses apart from accelerating lookup.  One
  that will be particularly relevant is that it is closely integrated
  with the mount table that records which filesystem is mounted where.
  What the mount table actually stores is which dentry is mounted on top
  of which other dentry.
  
  When considering the dcache, we have another of our "two types"
  distinctions: there are two types of filesystems.
  
  Some filesystems ensure that the information in the dcache is always
  completely accurate (though not necessarily complete).  This can allow
  the VFS to determine if a particular file does or doesn't exist
  without checking with the filesystem, and means that the VFS can
  protect the filesystem against certain races and other problems.
  These are typically "local" filesystems such as ext3, XFS, and Btrfs.
  
  Other filesystems don't provide that guarantee because they cannot.
  These are typically filesystems that are shared across a network,
  whether remote filesystems like NFS and 9P, or cluster filesystems
  like ocfs2 or cephfs.  These filesystems allow the VFS to revalidate
  cached information, and must provide their own protection against
  awkward races.  The VFS can detect these filesystems by the
7bbfd9ad8   NeilBrown   Documentation: co...
137
  ``DCACHE_OP_REVALIDATE`` flag being set in the dentry.
3ce96239d   Neil Brown   Documentation: ad...
138
139
140
141
142
143
144
145
  
  REF-walk: simple concurrency management with refcounts and spinlocks
  --------------------------------------------------------------------
  
  With all of those divisions carefully classified, we can now start
  looking at the actual process of walking along a path.  In particular
  we will start with the handling of the "everything else" part of a
  pathname, and focus on the "REF-walk" approach to concurrency
7bbfd9ad8   NeilBrown   Documentation: co...
146
147
  management.  This code is found in the ``link_path_walk()`` function, if
  you ignore all the places that only run when "``LOOKUP_RCU``"
3ce96239d   Neil Brown   Documentation: ad...
148
  (indicating the use of RCU-walk) is set.
7bbfd9ad8   NeilBrown   Documentation: co...
149
  .. _Meet the Lockers: https://lwn.net/Articles/453685/
3ce96239d   Neil Brown   Documentation: ad...
150
151
152
153
154
155
  
  REF-walk is fairly heavy-handed with locks and reference counts.  Not
  as heavy-handed as in the old "big kernel lock" days, but certainly not
  afraid of taking a lock when one is needed.  It uses a variety of
  different concurrency controls.  A background understanding of the
  various primitives is assumed, or can be gleaned from elsewhere such
7bbfd9ad8   NeilBrown   Documentation: co...
156
  as in `Meet the Lockers`_.
3ce96239d   Neil Brown   Documentation: ad...
157
158
  
  The locking mechanisms used by REF-walk include:
7bbfd9ad8   NeilBrown   Documentation: co...
159
160
  dentry->d_lockref
  ~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
161
162
163
164
165
166
167
168
  
  This uses the lockref primitive to provide both a spinlock and a
  reference count.  The special-sauce of this primitive is that the
  conceptual sequence "lock; inc_ref; unlock;" can often be performed
  with a single atomic memory operation.
  
  Holding a reference on a dentry ensures that the dentry won't suddenly
  be freed and used for something else, so the values in various fields
7bbfd9ad8   NeilBrown   Documentation: co...
169
  will behave as expected.  It also protects the ``->d_inode`` reference
3ce96239d   Neil Brown   Documentation: ad...
170
171
172
173
174
  to the inode to some extent.
  
  The association between a dentry and its inode is fairly permanent.
  For example, when a file is renamed, the dentry and inode move
  together to the new location.  When a file is created the dentry will
7bbfd9ad8   NeilBrown   Documentation: co...
175
  initially be negative (i.e. ``d_inode`` is ``NULL``), and will be assigned
3ce96239d   Neil Brown   Documentation: ad...
176
177
178
  to the new inode as part of the act of creation.
  
  When a file is deleted, this can be reflected in the cache either by
7bbfd9ad8   NeilBrown   Documentation: co...
179
  setting ``d_inode`` to ``NULL``, or by removing it from the hash table
3ce96239d   Neil Brown   Documentation: ad...
180
181
182
183
  (described shortly) used to look up the name in the parent directory.
  If the dentry is still in use the second option is used as it is
  perfectly legal to keep using an open file after it has been deleted
  and having the dentry around helps.  If the dentry is not otherwise in
7bbfd9ad8   NeilBrown   Documentation: co...
184
185
  use (i.e. if the refcount in ``d_lockref`` is one), only then will
  ``d_inode`` be set to ``NULL``.  Doing it this way is more efficient for a
3ce96239d   Neil Brown   Documentation: ad...
186
  very common case.
7bbfd9ad8   NeilBrown   Documentation: co...
187
  So as long as a counted reference is held to a dentry, a non-``NULL`` ``->d_inode``
3ce96239d   Neil Brown   Documentation: ad...
188
  value will never be changed.
7bbfd9ad8   NeilBrown   Documentation: co...
189
190
  dentry->d_lock
  ~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
191

7bbfd9ad8   NeilBrown   Documentation: co...
192
  ``d_lock`` is a synonym for the spinlock that is part of ``d_lockref`` above.
3ce96239d   Neil Brown   Documentation: ad...
193
  For our purposes, holding this lock protects against the dentry being
7bbfd9ad8   NeilBrown   Documentation: co...
194
195
  renamed or unlinked.  In particular, its parent (``d_parent``), and its
  name (``d_name``) cannot be changed, and it cannot be removed from the
3ce96239d   Neil Brown   Documentation: ad...
196
  dentry hash table.
7bbfd9ad8   NeilBrown   Documentation: co...
197
  When looking for a name in a directory, REF-walk takes ``d_lock`` on
3ce96239d   Neil Brown   Documentation: ad...
198
199
200
  each candidate dentry that it finds in the hash table and then checks
  that the parent and name are correct.  So it doesn't lock the parent
  while searching in the cache; it only locks children.
7bbfd9ad8   NeilBrown   Documentation: co...
201
202
  When looking for the parent for a given name (to handle "``..``"),
  REF-walk can take ``d_lock`` to get a stable reference to ``d_parent``,
3ce96239d   Neil Brown   Documentation: ad...
203
  but it first tries a more lightweight approach.  As seen in
7bbfd9ad8   NeilBrown   Documentation: co...
204
205
  ``dget_parent()``, if a reference can be claimed on the parent, and if
  subsequently ``d_parent`` can be seen to have not changed, then there is
3ce96239d   Neil Brown   Documentation: ad...
206
  no need to actually take the lock on the child.
7bbfd9ad8   NeilBrown   Documentation: co...
207
208
  rename_lock
  ~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
209
210
211
212
213
214
215
216
217
218
219
220
  
  Looking up a given name in a given directory involves computing a hash
  from the two values (the name and the dentry of the directory),
  accessing that slot in a hash table, and searching the linked list
  that is found there.
  
  When a dentry is renamed, the name and the parent dentry can both
  change so the hash will almost certainly change too.  This would move the
  dentry to a different chain in the hash table.  If a filename search
  happened to be looking at a dentry that was moved in this way,
  it might end up continuing the search down the wrong chain,
  and so miss out on part of the correct chain.
286b7e24a   Vegard Nossum   docs: path-lookup...
221
  The name-lookup process (``d_lookup()``) does *not* try to prevent this
3ce96239d   Neil Brown   Documentation: ad...
222
  from happening, but only to detect when it happens.
7bbfd9ad8   NeilBrown   Documentation: co...
223
224
  ``rename_lock`` is a seqlock that is updated whenever any dentry is
  renamed.  If ``d_lookup`` finds that a rename happened while it
3ce96239d   Neil Brown   Documentation: ad...
225
226
  unsuccessfully scanned a chain in the hash table, it simply tries
  again.
b55eef872   Aleksa Sarai   Documentation: pa...
227
228
229
230
231
232
  ``rename_lock`` is also used to detect and defend against potential attacks
  against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
  the parent directory is moved outside the root, bypassing the ``path_equal()``
  check). If ``rename_lock`` is updated during the lookup and the path encounters
  a "..", a potential attack occurred and ``handle_dots()`` will bail out with
  ``-EAGAIN``.
7bbfd9ad8   NeilBrown   Documentation: co...
233
234
  inode->i_rwsem
  ~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
235

7bbfd9ad8   NeilBrown   Documentation: co...
236
237
  ``i_rwsem`` is a read/write semaphore that serializes all changes to a particular
  directory.  This ensures that, for example, an ``unlink()`` and a ``rename()``
3ce96239d   Neil Brown   Documentation: ad...
238
239
  cannot both happen at the same time.  It also keeps the directory
  stable while the filesystem is asked to look up a name that is not
1428cc0e0   NeilBrown   Documentation: up...
240
  currently in the dcache or, optionally, when the list of entries in a
7bbfd9ad8   NeilBrown   Documentation: co...
241
  directory is being retrieved with ``readdir()``.
3ce96239d   Neil Brown   Documentation: ad...
242

7bbfd9ad8   NeilBrown   Documentation: co...
243
244
  This has a complementary role to that of ``d_lock``: ``i_rwsem`` on a
  directory protects all of the names in that directory, while ``d_lock``
3ce96239d   Neil Brown   Documentation: ad...
245
  on a name protects just one name in a directory.  Most changes to the
7bbfd9ad8   NeilBrown   Documentation: co...
246
247
  dcache hold ``i_rwsem`` on the relevant directory inode and briefly take
  ``d_lock`` on one or more the dentries while the change happens.  One
3ce96239d   Neil Brown   Documentation: ad...
248
  exception is when idle dentries are removed from the dcache due to
7bbfd9ad8   NeilBrown   Documentation: co...
249
  memory pressure.  This uses ``d_lock``, but ``i_rwsem`` plays no role.
3ce96239d   Neil Brown   Documentation: ad...
250

1428cc0e0   NeilBrown   Documentation: up...
251
  The semaphore affects pathname lookup in two distinct ways.  Firstly it
7bbfd9ad8   NeilBrown   Documentation: co...
252
253
254
255
  prevents changes during lookup of a name in a directory.  ``walk_component()`` uses
  ``lookup_fast()`` first which, in turn, checks to see if the name is in the cache,
  using only ``d_lock`` locking.  If the name isn't found, then ``walk_component()``
  falls back to ``lookup_slow()`` which takes a shared lock on ``i_rwsem``, checks again that
3ce96239d   Neil Brown   Documentation: ad...
256
257
258
259
260
  the name isn't in the cache, and then calls in to the filesystem to get a
  definitive answer.  A new dentry will be added to the cache regardless of
  the result.
  
  Secondly, when pathname lookup reaches the final component, it will
7bbfd9ad8   NeilBrown   Documentation: co...
261
  sometimes need to take an exclusive lock on ``i_rwsem`` before performing the last lookup so
3ce96239d   Neil Brown   Documentation: ad...
262
  that the required exclusion can be achieved.  How path lookup chooses
7bbfd9ad8   NeilBrown   Documentation: co...
263
  to take, or not take, ``i_rwsem`` is one of the
3ce96239d   Neil Brown   Documentation: ad...
264
  issues addressed in a subsequent section.
1428cc0e0   NeilBrown   Documentation: up...
265
  If two threads attempt to look up the same name at the same time - a
7bbfd9ad8   NeilBrown   Documentation: co...
266
  name that is not yet in the dcache - the shared lock on ``i_rwsem`` will
1428cc0e0   NeilBrown   Documentation: up...
267
268
  not prevent them both adding new dentries with the same name.  As this
  would result in confusion an extra level of interlocking is used,
7bbfd9ad8   NeilBrown   Documentation: co...
269
270
  based around a secondary hash table (``in_lookup_hashtable``) and a
  per-dentry flag bit (``DCACHE_PAR_LOOKUP``).
1428cc0e0   NeilBrown   Documentation: up...
271
272
  
  To add a new dentry to the cache while only holding a shared lock on
7bbfd9ad8   NeilBrown   Documentation: co...
273
  ``i_rwsem``, a thread must call ``d_alloc_parallel()``.  This allocates a
1428cc0e0   NeilBrown   Documentation: up...
274
275
276
  dentry, stores the required name and parent in it, checks if there
  is already a matching dentry in the primary or secondary hash
  tables, and if not, stores the newly allocated dentry in the secondary
7bbfd9ad8   NeilBrown   Documentation: co...
277
  hash table, with ``DCACHE_PAR_LOOKUP`` set.
1428cc0e0   NeilBrown   Documentation: up...
278
279
280
281
282
  
  If a matching dentry was found in the primary hash table then that is
  returned and the caller can know that it lost a race with some other
  thread adding the entry.  If no matching dentry is found in either
  cache, the newly allocated dentry is returned and the caller can
7bbfd9ad8   NeilBrown   Documentation: co...
283
  detect this from the presence of ``DCACHE_PAR_LOOKUP``.  In this case it
1428cc0e0   NeilBrown   Documentation: up...
284
285
  knows that it has won any race and now is responsible for asking the
  filesystem to perform the lookup and find the matching inode.  When
7bbfd9ad8   NeilBrown   Documentation: co...
286
  the lookup is complete, it must call ``d_lookup_done()`` which clears
1428cc0e0   NeilBrown   Documentation: up...
287
288
  the flag and does some other house keeping, including removing the
  dentry from the secondary hash table - it will normally have been
7bbfd9ad8   NeilBrown   Documentation: co...
289
290
291
  added to the primary hash table already.  Note that a ``struct
  waitqueue_head`` is passed to ``d_alloc_parallel()``, and
  ``d_lookup_done()`` must be called while this ``waitqueue_head`` is still
1428cc0e0   NeilBrown   Documentation: up...
292
293
294
  in scope.
  
  If a matching dentry is found in the secondary hash table,
7bbfd9ad8   NeilBrown   Documentation: co...
295
296
297
298
  ``d_alloc_parallel()`` has a little more work to do. It first waits for
  ``DCACHE_PAR_LOOKUP`` to be cleared, using a wait_queue that was passed
  to the instance of ``d_alloc_parallel()`` that won the race and that
  will be woken by the call to ``d_lookup_done()``.  It then checks to see
1428cc0e0   NeilBrown   Documentation: up...
299
300
301
302
  if the dentry has now been added to the primary hash table.  If it
  has, the dentry is returned and the caller just sees that it lost any
  race.  If it hasn't been added to the primary hash table, the most
  likely explanation is that some other dentry was added instead using
7bbfd9ad8   NeilBrown   Documentation: co...
303
  ``d_splice_alias()``.  In any case, ``d_alloc_parallel()`` repeats all the
1428cc0e0   NeilBrown   Documentation: up...
304
305
  look ups from the start and will normally return something from the
  primary hash table.
7bbfd9ad8   NeilBrown   Documentation: co...
306
307
  mnt->mnt_count
  ~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
308

7bbfd9ad8   NeilBrown   Documentation: co...
309
  ``mnt_count`` is a per-CPU reference counter on "``mount``" structures.
3ce96239d   Neil Brown   Documentation: ad...
310
311
  Per-CPU here means that incrementing the count is cheap as it only
  uses CPU-local memory, but checking if the count is zero is expensive as
7bbfd9ad8   NeilBrown   Documentation: co...
312
  it needs to check with every CPU.  Taking a ``mnt_count`` reference
3ce96239d   Neil Brown   Documentation: ad...
313
314
  prevents the mount structure from disappearing as the result of regular
  unmount operations, but does not prevent a "lazy" unmount.  So holding
7bbfd9ad8   NeilBrown   Documentation: co...
315
  ``mnt_count`` doesn't ensure that the mount remains in the namespace and,
3ce96239d   Neil Brown   Documentation: ad...
316
  in particular, doesn't stabilize the link to the mounted-on dentry.  It
7bbfd9ad8   NeilBrown   Documentation: co...
317
  does, however, ensure that the ``mount`` data structure remains coherent,
3ce96239d   Neil Brown   Documentation: ad...
318
  and it provides a reference to the root dentry of the mounted
7bbfd9ad8   NeilBrown   Documentation: co...
319
  filesystem.  So a reference through ``->mnt_count`` provides a stable
3ce96239d   Neil Brown   Documentation: ad...
320
  reference to the mounted dentry, but not the mounted-on dentry.
7bbfd9ad8   NeilBrown   Documentation: co...
321
322
  mount_lock
  ~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
323

7bbfd9ad8   NeilBrown   Documentation: co...
324
  ``mount_lock`` is a global seqlock, a bit like ``rename_lock``.  It can be used to
3ce96239d   Neil Brown   Documentation: ad...
325
326
327
328
329
330
  check if any change has been made to any mount points.
  
  While walking down the tree (away from the root) this lock is used when
  crossing a mount point to check that the crossing was safe.  That is,
  the value in the seqlock is read, then the code finds the mount that
  is mounted on the current directory, if there is one, and increments
7bbfd9ad8   NeilBrown   Documentation: co...
331
  the ``mnt_count``.  Finally the value in ``mount_lock`` is checked against
3ce96239d   Neil Brown   Documentation: ad...
332
  the old value.  If there is no change, then the crossing was safe.  If there
7bbfd9ad8   NeilBrown   Documentation: co...
333
  was a change, the ``mnt_count`` is decremented and the whole process is
3ce96239d   Neil Brown   Documentation: ad...
334
335
336
337
338
339
340
341
  retried.
  
  When walking up the tree (towards the root) by following a ".." link,
  a little more care is needed.  In this case the seqlock (which
  contains both a counter and a spinlock) is fully locked to prevent
  any changes to any mount points while stepping up.  This locking is
  needed to stabilize the link to the mounted-on dentry, which the
  refcount on the mount itself doesn't ensure.
b55eef872   Aleksa Sarai   Documentation: pa...
342
343
344
345
346
347
  ``mount_lock`` is also used to detect and defend against potential attacks
  against ``LOOKUP_BENEATH`` and ``LOOKUP_IN_ROOT`` when resolving ".." (where
  the parent directory is moved outside the root, bypassing the ``path_equal()``
  check). If ``mount_lock`` is updated during the lookup and the path encounters
  a "..", a potential attack occurred and ``handle_dots()`` will bail out with
  ``-EAGAIN``.
7bbfd9ad8   NeilBrown   Documentation: co...
348
349
  RCU
  ~~~
3ce96239d   Neil Brown   Documentation: ad...
350
351
352
353
354
355
356
  
  Finally the global (but extremely lightweight) RCU read lock is held
  from time to time to ensure certain data structures don't get freed
  unexpectedly.
  
  In particular it is held while scanning chains in the dcache hash
  table, and the mount point hash table.
7bbfd9ad8   NeilBrown   Documentation: co...
357
  Bringing it together with ``struct nameidata``
9f63df26b   Randy Dunlap   Documentation/fil...
358
  ----------------------------------------------
3ce96239d   Neil Brown   Documentation: ad...
359

c69f22f25   Alexander A. Klimov   Replace HTTP link...
360
  .. _First edition Unix: https://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/u2.s
3ce96239d   Neil Brown   Documentation: ad...
361
362
  
  Throughout the process of walking a path, the current status is stored
7bbfd9ad8   NeilBrown   Documentation: co...
363
364
365
  in a ``struct nameidata``, "namei" being the traditional name - dating
  all the way back to `First Edition Unix`_ - of the function that
  converts a "name" to an "inode".  ``struct nameidata`` contains (among
3ce96239d   Neil Brown   Documentation: ad...
366
  other fields):
7bbfd9ad8   NeilBrown   Documentation: co...
367
  ``struct path path``
9f63df26b   Randy Dunlap   Documentation/fil...
368
  ~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
369

7bbfd9ad8   NeilBrown   Documentation: co...
370
371
  A ``path`` contains a ``struct vfsmount`` (which is
  embedded in a ``struct mount``) and a ``struct dentry``.  Together these
3ce96239d   Neil Brown   Documentation: ad...
372
373
374
  record the current status of the walk.  They start out referring to the
  starting point (the current working directory, the root directory, or some other
  directory identified by a file descriptor), and are updated on each
7bbfd9ad8   NeilBrown   Documentation: co...
375
  step.  A reference through ``d_lockref`` and ``mnt_count`` is always
3ce96239d   Neil Brown   Documentation: ad...
376
  held.
7bbfd9ad8   NeilBrown   Documentation: co...
377
  ``struct qstr last``
9f63df26b   Randy Dunlap   Documentation/fil...
378
  ~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
379

286b7e24a   Vegard Nossum   docs: path-lookup...
380
  This is a string together with a length (i.e. *not* ``nul`` terminated)
3ce96239d   Neil Brown   Documentation: ad...
381
  that is the "next" component in the pathname.
7bbfd9ad8   NeilBrown   Documentation: co...
382
  ``int last_type``
9f63df26b   Randy Dunlap   Documentation/fil...
383
  ~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
384

b4c035369   Al Viro   sanitize handling...
385
386
  This is one of ``LAST_NORM``, ``LAST_ROOT``, ``LAST_DOT`` or ``LAST_DOTDOT``.
  The ``last`` field is only valid if the type is ``LAST_NORM``.
3ce96239d   Neil Brown   Documentation: ad...
387

7bbfd9ad8   NeilBrown   Documentation: co...
388
  ``struct path root``
9f63df26b   Randy Dunlap   Documentation/fil...
389
  ~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
390
391
392
393
  
  This is used to hold a reference to the effective root of the
  filesystem.  Often that reference won't be needed, so this field is
  only assigned the first time it is used, or when a non-standard root
7bbfd9ad8   NeilBrown   Documentation: co...
394
  is requested.  Keeping a reference in the ``nameidata`` ensures that
3ce96239d   Neil Brown   Documentation: ad...
395
  only one root is in effect for the entire path walk, even if it races
7bbfd9ad8   NeilBrown   Documentation: co...
396
  with a ``chroot()`` system call.
3ce96239d   Neil Brown   Documentation: ad...
397

b55eef872   Aleksa Sarai   Documentation: pa...
398
399
400
  It should be noted that in the case of ``LOOKUP_IN_ROOT`` or
  ``LOOKUP_BENEATH``, the effective root becomes the directory file descriptor
  passed to ``openat2()`` (which exposes these ``LOOKUP_`` flags).
3ce96239d   Neil Brown   Documentation: ad...
401
  The root is needed when either of two conditions holds: (1) either the
7bbfd9ad8   NeilBrown   Documentation: co...
402
403
  pathname or a symbolic link starts with a "'/'", or (2) a "``..``"
  component is being handled, since "``..``" from the root must always stay
3ce96239d   Neil Brown   Documentation: ad...
404
405
  at the root.  The value used is usually the current root directory of
  the calling process.  An alternate root can be provided as when
7bbfd9ad8   NeilBrown   Documentation: co...
406
407
  ``sysctl()`` calls ``file_open_root()``, and when NFSv4 or Btrfs call
  ``mount_subtree()``.  In each case a pathname is being looked up in a very
3ce96239d   Neil Brown   Documentation: ad...
408
  specific part of the filesystem, and the lookup must not be allowed to
7bbfd9ad8   NeilBrown   Documentation: co...
409
  escape that subtree.  It works a bit like a local ``chroot()``.
3ce96239d   Neil Brown   Documentation: ad...
410
411
  
  Ignoring the handling of symbolic links, we can now describe the
7bbfd9ad8   NeilBrown   Documentation: co...
412
  "``link_path_walk()``" function, which handles the lookup of everything
3ce96239d   Neil Brown   Documentation: ad...
413
  except the final component as:
7bbfd9ad8   NeilBrown   Documentation: co...
414
415
416
417
418
     Given a path (``name``) and a nameidata structure (``nd``), check that the
     current directory has execute permission and then advance ``name``
     over one component while updating ``last_type`` and ``last``.  If that
     was the final component, then return, otherwise call
     ``walk_component()`` and repeat from the top.
3ce96239d   Neil Brown   Documentation: ad...
419

7bbfd9ad8   NeilBrown   Documentation: co...
420
421
422
423
  ``walk_component()`` is even easier.  If the component is ``LAST_DOTS``,
  it calls ``handle_dots()`` which does the necessary locking as already
  described.  If it finds a ``LAST_NORM`` component it first calls
  "``lookup_fast()``" which only looks in the dcache, but will ask the
3ce96239d   Neil Brown   Documentation: ad...
424
  filesystem to revalidate the result if it is that sort of filesystem.
7bbfd9ad8   NeilBrown   Documentation: co...
425
426
  If that doesn't get a good result, it calls "``lookup_slow()``" which
  takes ``i_rwsem``, rechecks the cache, and then asks the filesystem
3ce96239d   Neil Brown   Documentation: ad...
427
  to find a definitive answer.  Each of these will call
7bbfd9ad8   NeilBrown   Documentation: co...
428
  ``follow_managed()`` (as described below) to handle any mount points.
3ce96239d   Neil Brown   Documentation: ad...
429

7bbfd9ad8   NeilBrown   Documentation: co...
430
431
432
433
434
435
  In the absence of symbolic links, ``walk_component()`` creates a new
  ``struct path`` containing a counted reference to the new dentry and a
  reference to the new ``vfsmount`` which is only counted if it is
  different from the previous ``vfsmount``.  It then calls
  ``path_to_nameidata()`` to install the new ``struct path`` in the
  ``struct nameidata`` and drop the unneeded references.
3ce96239d   Neil Brown   Documentation: ad...
436
437
438
439
440
  
  This "hand-over-hand" sequencing of getting a reference to the new
  dentry before dropping the reference to the previous dentry may
  seem obvious, but is worth pointing out so that we will recognize its
  analogue in the "RCU-walk" version.
7bbfd9ad8   NeilBrown   Documentation: co...
441
442
  Handling the final component
  ----------------------------
3ce96239d   Neil Brown   Documentation: ad...
443

7bbfd9ad8   NeilBrown   Documentation: co...
444
445
446
  ``link_path_walk()`` only walks as far as setting ``nd->last`` and
  ``nd->last_type`` to refer to the final component of the path.  It does
  not call ``walk_component()`` that last time.  Handling that final
3ce96239d   Neil Brown   Documentation: ad...
447
  component remains for the caller to sort out. Those callers are
7bbfd9ad8   NeilBrown   Documentation: co...
448
449
  ``path_lookupat()``, ``path_parentat()``, ``path_mountpoint()`` and
  ``path_openat()`` each of which handles the differing requirements of
3ce96239d   Neil Brown   Documentation: ad...
450
  different system calls.
7bbfd9ad8   NeilBrown   Documentation: co...
451
452
  ``path_parentat()`` is clearly the simplest - it just wraps a little bit
  of housekeeping around ``link_path_walk()`` and returns the parent
3ce96239d   Neil Brown   Documentation: ad...
453
  directory and final component to the caller.  The caller will be either
7bbfd9ad8   NeilBrown   Documentation: co...
454
455
456
  aiming to create a name (via ``filename_create()``) or remove or rename
  a name (in which case ``user_path_parent()`` is used).  They will use
  ``i_rwsem`` to exclude other changes while they validate and then
3ce96239d   Neil Brown   Documentation: ad...
457
  perform their operation.
7bbfd9ad8   NeilBrown   Documentation: co...
458
459
460
461
  ``path_lookupat()`` is nearly as simple - it is used when an existing
  object is wanted such as by ``stat()`` or ``chmod()``.  It essentially just
  calls ``walk_component()`` on the final component through a call to
  ``lookup_last()``.  ``path_lookupat()`` returns just the final dentry.
3ce96239d   Neil Brown   Documentation: ad...
462

7bbfd9ad8   NeilBrown   Documentation: co...
463
  ``path_mountpoint()`` handles the special case of unmounting which must
3ce96239d   Neil Brown   Documentation: ad...
464
  not try to revalidate the mounted filesystem.  It effectively
7bbfd9ad8   NeilBrown   Documentation: co...
465
466
  contains, through a call to ``mountpoint_last()``, an alternate
  implementation of ``lookup_slow()`` which skips that step.  This is
3ce96239d   Neil Brown   Documentation: ad...
467
468
  important when unmounting a filesystem that is inaccessible, such as
  one provided by a dead NFS server.
7bbfd9ad8   NeilBrown   Documentation: co...
469
470
  Finally ``path_openat()`` is used for the ``open()`` system call; it
  contains, in support functions starting with "``do_last()``", all the
3ce96239d   Neil Brown   Documentation: ad...
471
  complexity needed to handle the different subtleties of O_CREAT (with
7bbfd9ad8   NeilBrown   Documentation: co...
472
  or without O_EXCL), final "``/``" characters, and trailing symbolic
3ce96239d   Neil Brown   Documentation: ad...
473
  links.  We will revisit this in the final part of this series, which
7bbfd9ad8   NeilBrown   Documentation: co...
474
475
  focuses on those symbolic links.  "``do_last()``" will sometimes, but
  not always, take ``i_rwsem``, depending on what it finds.
3ce96239d   Neil Brown   Documentation: ad...
476
477
  
  Each of these, or the functions which call them, need to be alert to
7bbfd9ad8   NeilBrown   Documentation: co...
478
  the possibility that the final component is not ``LAST_NORM``.  If the
3ce96239d   Neil Brown   Documentation: ad...
479
  goal of the lookup is to create something, then any value for
7bbfd9ad8   NeilBrown   Documentation: co...
480
481
  ``last_type`` other than ``LAST_NORM`` will result in an error.  For
  example if ``path_parentat()`` reports ``LAST_DOTDOT``, then the caller
3ce96239d   Neil Brown   Documentation: ad...
482
  won't try to create that name.  They also check for trailing slashes
7bbfd9ad8   NeilBrown   Documentation: co...
483
  by testing ``last.name[last.len]``.  If there is any character beyond
3ce96239d   Neil Brown   Documentation: ad...
484
485
486
487
488
489
490
491
492
493
  the final component, it must be a trailing slash.
  
  Revalidation and automounts
  ---------------------------
  
  Apart from symbolic links, there are only two parts of the "REF-walk"
  process not yet covered.  One is the handling of stale cache entries
  and the other is automounts.
  
  On filesystems that require it, the lookup routines will call the
7bbfd9ad8   NeilBrown   Documentation: co...
494
  ``->d_revalidate()`` dentry method to ensure that the cached information
3ce96239d   Neil Brown   Documentation: ad...
495
496
497
498
  is current.  This will often confirm validity or update a few details
  from a server.  In some cases it may find that there has been change
  further up the path and that something that was thought to be valid
  previously isn't really.  When this happens the lookup of the whole
7bbfd9ad8   NeilBrown   Documentation: co...
499
  path is aborted and retried with the "``LOOKUP_REVAL``" flag set.  This
3ce96239d   Neil Brown   Documentation: ad...
500
501
502
503
504
505
  forces revalidation to be more thorough.  We will see more details of
  this retry process in the next article.
  
  Automount points are locations in the filesystem where an attempt to
  lookup a name can trigger changes to how that lookup should be
  handled, in particular by mounting a filesystem there.  These are
b6bb226a7   Ian Kent   autofs: use autof...
506
  covered in greater detail in autofs.txt in the Linux documentation
3ce96239d   Neil Brown   Documentation: ad...
507
508
509
510
  tree, but a few notes specifically related to path lookup are in order
  here.
  
  The Linux VFS has a concept of "managed" dentries which is reflected
7bbfd9ad8   NeilBrown   Documentation: co...
511
  in function names such as "``follow_managed()``".  There are three
3ce96239d   Neil Brown   Documentation: ad...
512
  potentially interesting things about these dentries corresponding
7bbfd9ad8   NeilBrown   Documentation: co...
513
  to three different flags that might be set in ``dentry->d_flags``:
3ce96239d   Neil Brown   Documentation: ad...
514

7bbfd9ad8   NeilBrown   Documentation: co...
515
  ``DCACHE_MANAGE_TRANSIT``
9f63df26b   Randy Dunlap   Documentation/fil...
516
  ~~~~~~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
517
518
  
  If this flag has been set, then the filesystem has requested that the
7bbfd9ad8   NeilBrown   Documentation: co...
519
  ``d_manage()`` dentry operation be called before handling any possible
3ce96239d   Neil Brown   Documentation: ad...
520
521
522
  mount point.  This can perform two particular services:
  
  It can block to avoid races.  If an automount point is being
7bbfd9ad8   NeilBrown   Documentation: co...
523
  unmounted, the ``d_manage()`` function will usually wait for that
3ce96239d   Neil Brown   Documentation: ad...
524
525
526
527
528
529
  process to complete before letting the new lookup proceed and possibly
  trigger a new automount.
  
  It can selectively allow only some processes to transit through a
  mount point.  When a server process is managing automounts, it may
  need to access a directory without triggering normal automount
7bbfd9ad8   NeilBrown   Documentation: co...
530
  processing.  That server process can identify itself to the ``autofs``
3ce96239d   Neil Brown   Documentation: ad...
531
  filesystem, which will then give it a special pass through
7bbfd9ad8   NeilBrown   Documentation: co...
532
  ``d_manage()`` by returning ``-EISDIR``.
3ce96239d   Neil Brown   Documentation: ad...
533

7bbfd9ad8   NeilBrown   Documentation: co...
534
  ``DCACHE_MOUNTED``
9f63df26b   Randy Dunlap   Documentation/fil...
535
  ~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
536
537
538
539
540
  
  This flag is set on every dentry that is mounted on.  As Linux
  supports multiple filesystem namespaces, it is possible that the
  dentry may not be mounted on in *this* namespace, just in some
  other.  So this flag is seen as a hint, not a promise.
7bbfd9ad8   NeilBrown   Documentation: co...
541
542
543
544
  If this flag is set, and ``d_manage()`` didn't return ``-EISDIR``,
  ``lookup_mnt()`` is called to examine the mount hash table (honoring the
  ``mount_lock`` described earlier) and possibly return a new ``vfsmount``
  and a new ``dentry`` (both with counted references).
3ce96239d   Neil Brown   Documentation: ad...
545

7bbfd9ad8   NeilBrown   Documentation: co...
546
  ``DCACHE_NEED_AUTOMOUNT``
9f63df26b   Randy Dunlap   Documentation/fil...
547
  ~~~~~~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
548

7bbfd9ad8   NeilBrown   Documentation: co...
549
550
  If ``d_manage()`` allowed us to get this far, and ``lookup_mnt()`` didn't
  find a mount point, then this flag causes the ``d_automount()`` dentry
3ce96239d   Neil Brown   Documentation: ad...
551
  operation to be called.
7bbfd9ad8   NeilBrown   Documentation: co...
552
  The ``d_automount()`` operation can be arbitrarily complex and may
3ce96239d   Neil Brown   Documentation: ad...
553
554
  communicate with server processes etc. but it should ultimately either
  report that there was an error, that there was nothing to mount, or
7bbfd9ad8   NeilBrown   Documentation: co...
555
  should provide an updated ``struct path`` with new ``dentry`` and ``vfsmount``.
3ce96239d   Neil Brown   Documentation: ad...
556

7bbfd9ad8   NeilBrown   Documentation: co...
557
  In the latter case, ``finish_automount()`` will be called to safely
3ce96239d   Neil Brown   Documentation: ad...
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
  install the new mount point into the mount table.
  
  There is no new locking of import here and it is important that no
  locks (only counted references) are held over this processing due to
  the very real possibility of extended delays.
  This will become more important next time when we examine RCU-walk
  which is particularly sensitive to delays.
  
  RCU-walk - faster pathname lookup in Linux
  ==========================================
  
  RCU-walk is another algorithm for performing pathname lookup in Linux.
  It is in many ways similar to REF-walk and the two share quite a bit
  of code.  The significant difference in RCU-walk is how it allows for
  the possibility of concurrent access.
  
  We noted that REF-walk is complex because there are numerous details
  and special cases.  RCU-walk reduces this complexity by simply
  refusing to handle a number of cases -- it instead falls back to
  REF-walk.  The difficulty with RCU-walk comes from a different
  direction: unfamiliarity.  The locking rules when depending on RCU are
  quite different from traditional locking, so we will spend a little extra
  time when we come to those.
  
  Clear demarcation of roles
  --------------------------
  
  The easiest way to manage concurrency is to forcibly stop any other
  thread from changing the data structures that a given thread is
  looking at.  In cases where no other thread would even think of
  changing the data and lots of different threads want to read at the
  same time, this can be very costly.  Even when using locks that permit
  multiple concurrent readers, the simple act of updating the count of
  the number of current readers can impose an unwanted cost.  So the
  goal when reading a shared data structure that no other process is
  changing is to avoid writing anything to memory at all.  Take no
  locks, increment no counts, leave no footprints.
  
  The REF-walk mechanism already described certainly doesn't follow this
  principle, but then it is really designed to work when there may well
  be other threads modifying the data.  RCU-walk, in contrast, is
  designed for the common situation where there are lots of frequent
  readers and only occasional writers.  This may not be common in all
  parts of the filesystem tree, but in many parts it will be.  For the
  other parts it is important that RCU-walk can quickly fall back to
  using REF-walk.
  
  Pathname lookup always starts in RCU-walk mode but only remains there
  as long as what it is looking for is in the cache and is stable.  It
  dances lightly down the cached filesystem image, leaving no footprints
  and carefully watching where it is, to be sure it doesn't trip.  If it
  notices that something has changed or is changing, or if something
  isn't in the cache, then it tries to stop gracefully and switch to
  REF-walk.
  
  This stopping requires getting a counted reference on the current
7bbfd9ad8   NeilBrown   Documentation: co...
614
  ``vfsmount`` and ``dentry``, and ensuring that these are still valid -
3ce96239d   Neil Brown   Documentation: ad...
615
616
617
618
619
620
621
622
623
624
  that a path walk with REF-walk would have found the same entries.
  This is an invariant that RCU-walk must guarantee.  It can only make
  decisions, such as selecting the next step, that are decisions which
  REF-walk could also have made if it were walking down the tree at the
  same time.  If the graceful stop succeeds, the rest of the path is
  processed with the reliable, if slightly sluggish, REF-walk.  If
  RCU-walk finds it cannot stop gracefully, it simply gives up and
  restarts from the top with REF-walk.
  
  This pattern of "try RCU-walk, if that fails try REF-walk" can be
7bbfd9ad8   NeilBrown   Documentation: co...
625
626
627
  clearly seen in functions like ``filename_lookup()``,
  ``filename_parentat()``, ``filename_mountpoint()``,
  ``do_filp_open()``, and ``do_file_open_root()``.  These five
87b92d4b8   Vegard Nossum   docs: path-lookup...
628
629
  correspond roughly to the four ``path_*()`` functions we met earlier,
  each of which calls ``link_path_walk()``.  The ``path_*()`` functions are
3ce96239d   Neil Brown   Documentation: ad...
630
  called using different mode flags until a mode is found which works.
7bbfd9ad8   NeilBrown   Documentation: co...
631
632
  They are first called with ``LOOKUP_RCU`` set to request "RCU-walk".  If
  that fails with the error ``ECHILD`` they are called again with no
3ce96239d   Neil Brown   Documentation: ad...
633
  special flag to request "REF-walk".  If either of those report the
7bbfd9ad8   NeilBrown   Documentation: co...
634
635
  error ``ESTALE`` a final attempt is made with ``LOOKUP_REVAL`` set (and no
  ``LOOKUP_RCU``) to ensure that entries found in the cache are forcibly
3ce96239d   Neil Brown   Documentation: ad...
636
637
  revalidated - normally entries are only revalidated if the filesystem
  determines that they are too old to trust.
7bbfd9ad8   NeilBrown   Documentation: co...
638
  The ``LOOKUP_RCU`` attempt may drop that flag internally and switch to
3ce96239d   Neil Brown   Documentation: ad...
639
640
641
642
643
644
645
646
647
  REF-walk, but will never then try to switch back to RCU-walk.  Places
  that trip up RCU-walk are much more likely to be near the leaves and
  so it is very unlikely that there will be much, if any, benefit from
  switching back.
  
  RCU and seqlocks: fast and light
  --------------------------------
  
  RCU is, unsurprisingly, critical to RCU-walk mode.  The
7bbfd9ad8   NeilBrown   Documentation: co...
648
  ``rcu_read_lock()`` is held for the entire time that RCU-walk is walking
3ce96239d   Neil Brown   Documentation: ad...
649
650
651
652
653
654
655
656
657
658
659
  down a path.  The particular guarantee it provides is that the key
  data structures - dentries, inodes, super_blocks, and mounts - will
  not be freed while the lock is held.  They might be unlinked or
  invalidated in one way or another, but the memory will not be
  repurposed so values in various fields will still be meaningful.  This
  is the only guarantee that RCU provides; everything else is done using
  seqlocks.
  
  As we saw above, REF-walk holds a counted reference to the current
  dentry and the current vfsmount, and does not release those references
  before taking references to the "next" dentry or vfsmount.  It also
7bbfd9ad8   NeilBrown   Documentation: co...
660
  sometimes takes the ``d_lock`` spinlock.  These references and locks are
3ce96239d   Neil Brown   Documentation: ad...
661
662
663
664
665
666
667
668
669
  taken to prevent certain changes from happening.  RCU-walk must not
  take those references or locks and so cannot prevent such changes.
  Instead, it checks to see if a change has been made, and aborts or
  retries if it has.
  
  To preserve the invariant mentioned above (that RCU-walk may only make
  decisions that REF-walk could have made), it must make the checks at
  or near the same places that REF-walk holds the references.  So, when
  REF-walk increments a reference count or takes a spinlock, RCU-walk
7bbfd9ad8   NeilBrown   Documentation: co...
670
  samples the status of a seqlock using ``read_seqcount_begin()`` or a
3ce96239d   Neil Brown   Documentation: ad...
671
672
  similar function.  When REF-walk decrements the count or drops the
  lock, RCU-walk checks if the sampled status is still valid using
7bbfd9ad8   NeilBrown   Documentation: co...
673
  ``read_seqcount_retry()`` or similar.
3ce96239d   Neil Brown   Documentation: ad...
674
675
676
677
678
679
  
  However, there is a little bit more to seqlocks than that.  If
  RCU-walk accesses two different fields in a seqlock-protected
  structure, or accesses the same field twice, there is no a priori
  guarantee of any consistency between those accesses.  When consistency
  is needed - which it usually is - RCU-walk must take a copy and then
7bbfd9ad8   NeilBrown   Documentation: co...
680
  use ``read_seqcount_retry()`` to validate that copy.
3ce96239d   Neil Brown   Documentation: ad...
681

7bbfd9ad8   NeilBrown   Documentation: co...
682
  ``read_seqcount_retry()`` not only checks the sequence number, but also
3ce96239d   Neil Brown   Documentation: ad...
683
684
685
  imposes a memory barrier so that no memory-read instruction from
  *before* the call can be delayed until *after* the call, either by the
  CPU or by the compiler.  A simple example of this can be seen in
7bbfd9ad8   NeilBrown   Documentation: co...
686
  ``slow_dentry_cmp()`` which, for filesystems which do not use simple
3ce96239d   Neil Brown   Documentation: ad...
687
688
  byte-wise name equality, calls into the filesystem to compare a name
  against a dentry.  The length and name pointer are copied into local
7bbfd9ad8   NeilBrown   Documentation: co...
689
690
691
  variables, then ``read_seqcount_retry()`` is called to confirm the two
  are consistent, and only then is ``->d_compare()`` called.  When
  standard filename comparison is used, ``dentry_cmp()`` is called
286b7e24a   Vegard Nossum   docs: path-lookup...
692
  instead.  Notably it does *not* use ``read_seqcount_retry()``, but
3ce96239d   Neil Brown   Documentation: ad...
693
  instead has a large comment explaining why the consistency guarantee
7bbfd9ad8   NeilBrown   Documentation: co...
694
  isn't necessary.  A subsequent ``read_seqcount_retry()`` will be
3ce96239d   Neil Brown   Documentation: ad...
695
696
697
698
  sufficient to catch any problem that could occur at this point.
  
  With that little refresher on seqlocks out of the way we can look at
  the bigger picture of how RCU-walk uses seqlocks.
7bbfd9ad8   NeilBrown   Documentation: co...
699
  ``mount_lock`` and ``nd->m_seq``
9f63df26b   Randy Dunlap   Documentation/fil...
700
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
701

7bbfd9ad8   NeilBrown   Documentation: co...
702
  We already met the ``mount_lock`` seqlock when REF-walk used it to
3ce96239d   Neil Brown   Documentation: ad...
703
704
  ensure that crossing a mount point is performed safely.  RCU-walk uses
  it for that too, but for quite a bit more.
7bbfd9ad8   NeilBrown   Documentation: co...
705
706
  Instead of taking a counted reference to each ``vfsmount`` as it
  descends the tree, RCU-walk samples the state of ``mount_lock`` at the
3ce96239d   Neil Brown   Documentation: ad...
707
  start of the walk and stores this initial sequence number in the
7bbfd9ad8   NeilBrown   Documentation: co...
708
709
  ``struct nameidata`` in the ``m_seq`` field.  This one lock and one
  sequence number are used to validate all accesses to all ``vfsmounts``,
3ce96239d   Neil Brown   Documentation: ad...
710
711
712
  and all mount point crossings.  As changes to the mount table are
  relatively rare, it is reasonable to fall back on REF-walk any time
  that any "mount" or "unmount" happens.
7bbfd9ad8   NeilBrown   Documentation: co...
713
  ``m_seq`` is checked (using ``read_seqretry()``) at the end of an RCU-walk
3ce96239d   Neil Brown   Documentation: ad...
714
715
  sequence, whether switching to REF-walk for the rest of the path or
  when the end of the path is reached.  It is also checked when stepping
7bbfd9ad8   NeilBrown   Documentation: co...
716
717
  down over a mount point (in ``__follow_mount_rcu()``) or up (in
  ``follow_dotdot_rcu()``).  If it is ever found to have changed, the
3ce96239d   Neil Brown   Documentation: ad...
718
719
  whole RCU-walk sequence is aborted and the path is processed again by
  REF-walk.
7bbfd9ad8   NeilBrown   Documentation: co...
720
  If RCU-walk finds that ``mount_lock`` hasn't changed then it can be sure
3ce96239d   Neil Brown   Documentation: ad...
721
722
723
  that, had REF-walk taken counted references on each vfsmount, the
  results would have been the same.  This ensures the invariant holds,
  at least for vfsmount structures.
7bbfd9ad8   NeilBrown   Documentation: co...
724
  ``dentry->d_seq`` and ``nd->seq``
9f63df26b   Randy Dunlap   Documentation/fil...
725
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
726

7bbfd9ad8   NeilBrown   Documentation: co...
727
728
729
730
  In place of taking a count or lock on ``d_reflock``, RCU-walk samples
  the per-dentry ``d_seq`` seqlock, and stores the sequence number in the
  ``seq`` field of the nameidata structure, so ``nd->seq`` should always be
  the current sequence number of ``nd->dentry``.  This number needs to be
3ce96239d   Neil Brown   Documentation: ad...
731
732
733
734
  revalidated after copying, and before using, the name, parent, or
  inode of the dentry.
  
  The handling of the name we have already looked at, and the parent is
7bbfd9ad8   NeilBrown   Documentation: co...
735
  only accessed in ``follow_dotdot_rcu()`` which fairly trivially follows
3ce96239d   Neil Brown   Documentation: ad...
736
  the required pattern, though it does so for three different cases.
7bbfd9ad8   NeilBrown   Documentation: co...
737
  When not at a mount point, ``d_parent`` is followed and its ``d_seq`` is
3ce96239d   Neil Brown   Documentation: ad...
738
  collected.  When we are at a mount point, we instead follow the
7bbfd9ad8   NeilBrown   Documentation: co...
739
740
  ``mnt->mnt_mountpoint`` link to get a new dentry and collect its
  ``d_seq``.  Then, after finally finding a ``d_parent`` to follow, we must
3ce96239d   Neil Brown   Documentation: ad...
741
  check if we have landed on a mount point and, if so, must find that
7bbfd9ad8   NeilBrown   Documentation: co...
742
  mount point and follow the ``mnt->mnt_root`` link.  This would imply a
3ce96239d   Neil Brown   Documentation: ad...
743
744
745
  somewhat unusual, but certainly possible, circumstance where the
  starting point of the path lookup was in part of the filesystem that
  was mounted on, and so not visible from the root.
7bbfd9ad8   NeilBrown   Documentation: co...
746
  The inode pointer, stored in ``->d_inode``, is a little more
3ce96239d   Neil Brown   Documentation: ad...
747
748
749
750
  interesting.  The inode will always need to be accessed at least
  twice, once to determine if it is NULL and once to verify access
  permissions.  Symlink handling requires a validated inode pointer too.
  Rather than revalidating on each access, a copy is made on the first
7bbfd9ad8   NeilBrown   Documentation: co...
751
  access and it is stored in the ``inode`` field of ``nameidata`` from where
3ce96239d   Neil Brown   Documentation: ad...
752
  it can be safely accessed without further validation.
7bbfd9ad8   NeilBrown   Documentation: co...
753
754
755
  ``lookup_fast()`` is the only lookup routine that is used in RCU-mode,
  ``lookup_slow()`` being too slow and requiring locks.  It is in
  ``lookup_fast()`` that we find the important "hand over hand" tracking
3ce96239d   Neil Brown   Documentation: ad...
756
  of the current dentry.
7bbfd9ad8   NeilBrown   Documentation: co...
757
758
759
760
761
762
763
  The current ``dentry`` and current ``seq`` number are passed to
  ``__d_lookup_rcu()`` which, on success, returns a new ``dentry`` and a
  new ``seq`` number.  ``lookup_fast()`` then copies the inode pointer and
  revalidates the new ``seq`` number.  It then validates the old ``dentry``
  with the old ``seq`` number one last time and only then continues.  This
  process of getting the ``seq`` number of the new dentry and then
  checking the ``seq`` number of the old exactly mirrors the process of
3ce96239d   Neil Brown   Documentation: ad...
764
765
  getting a counted reference to the new dentry before dropping that for
  the old dentry which we saw in REF-walk.
7bbfd9ad8   NeilBrown   Documentation: co...
766
  No ``inode->i_rwsem`` or even ``rename_lock``
9f63df26b   Randy Dunlap   Documentation/fil...
767
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
768

1428cc0e0   NeilBrown   Documentation: up...
769
  A semaphore is a fairly heavyweight lock that can only be taken when it is
7bbfd9ad8   NeilBrown   Documentation: co...
770
771
772
  permissible to sleep.  As ``rcu_read_lock()`` forbids sleeping,
  ``inode->i_rwsem`` plays no role in RCU-walk.  If some other thread does
  take ``i_rwsem`` and modifies the directory in a way that RCU-walk needs
3ce96239d   Neil Brown   Documentation: ad...
773
774
  to notice, the result will be either that RCU-walk fails to find the
  dentry that it is looking for, or it will find a dentry which
7bbfd9ad8   NeilBrown   Documentation: co...
775
  ``read_seqretry()`` won't validate.  In either case it will drop down to
3ce96239d   Neil Brown   Documentation: ad...
776
  REF-walk mode which can take whatever locks are needed.
7bbfd9ad8   NeilBrown   Documentation: co...
777
778
  Though ``rename_lock`` could be used by RCU-walk as it doesn't require
  any sleeping, RCU-walk doesn't bother.  REF-walk uses ``rename_lock`` to
3ce96239d   Neil Brown   Documentation: ad...
779
780
781
782
783
784
785
  protect against the possibility of hash chains in the dcache changing
  while they are being searched.  This can result in failing to find
  something that actually is there.  When RCU-walk fails to find
  something in the dentry cache, whether it is really there or not, it
  already drops down to REF-walk and tries again with appropriate
  locking.  This neatly handles all cases, so adding extra checks on
  rename_lock would bring no significant value.
7bbfd9ad8   NeilBrown   Documentation: co...
786
  ``unlazy walk()`` and ``complete_walk()``
9f63df26b   Randy Dunlap   Documentation/fil...
787
  -----------------------------------------
3ce96239d   Neil Brown   Documentation: ad...
788
789
  
  That "dropping down to REF-walk" typically involves a call to
7bbfd9ad8   NeilBrown   Documentation: co...
790
791
  ``unlazy_walk()``, so named because "RCU-walk" is also sometimes
  referred to as "lazy walk".  ``unlazy_walk()`` is called when
3ce96239d   Neil Brown   Documentation: ad...
792
793
794
795
  following the path down to the current vfsmount/dentry pair seems to
  have proceeded successfully, but the next step is problematic.  This
  can happen if the next name cannot be found in the dcache, if
  permission checking or name revalidation couldn't be achieved while
7bbfd9ad8   NeilBrown   Documentation: co...
796
  the ``rcu_read_lock()`` is held (which forbids sleeping), if an
3ce96239d   Neil Brown   Documentation: ad...
797
  automount point is found, or in a couple of cases involving symlinks.
7bbfd9ad8   NeilBrown   Documentation: co...
798
  It is also called from ``complete_walk()`` when the lookup has reached
3ce96239d   Neil Brown   Documentation: ad...
799
800
801
802
  the final component, or the very end of the path, depending on which
  particular flavor of lookup is used.
  
  Other reasons for dropping out of RCU-walk that do not trigger a call
7bbfd9ad8   NeilBrown   Documentation: co...
803
804
  to ``unlazy_walk()`` are when some inconsistency is found that cannot be
  handled immediately, such as ``mount_lock`` or one of the ``d_seq``
3ce96239d   Neil Brown   Documentation: ad...
805
  seqlocks reporting a change.  In these cases the relevant function
7bbfd9ad8   NeilBrown   Documentation: co...
806
  will return ``-ECHILD`` which will percolate up until it triggers a new
3ce96239d   Neil Brown   Documentation: ad...
807
  attempt from the top using REF-walk.
7bbfd9ad8   NeilBrown   Documentation: co...
808
  For those cases where ``unlazy_walk()`` is an option, it essentially
3ce96239d   Neil Brown   Documentation: ad...
809
810
811
  takes a reference on each of the pointers that it holds (vfsmount,
  dentry, and possibly some symbolic links) and then verifies that the
  relevant seqlocks have not been changed.  If there have been changes,
7bbfd9ad8   NeilBrown   Documentation: co...
812
  it, too, aborts with ``-ECHILD``, otherwise the transition to REF-walk
3ce96239d   Neil Brown   Documentation: ad...
813
814
815
816
817
818
  has been a success and the lookup process continues.
  
  Taking a reference on those pointers is not quite as simple as just
  incrementing a counter.  That works to take a second reference if you
  already have one (often indirectly through another object), but it
  isn't sufficient if you don't actually have a counted reference at
7bbfd9ad8   NeilBrown   Documentation: co...
819
  all.  For ``dentry->d_lockref``, it is safe to increment the reference
3ce96239d   Neil Brown   Documentation: ad...
820
  counter to get a reference unless it has been explicitly marked as
7bbfd9ad8   NeilBrown   Documentation: co...
821
822
  "dead" which involves setting the counter to ``-128``.
  ``lockref_get_not_dead()`` achieves this.
3ce96239d   Neil Brown   Documentation: ad...
823

7bbfd9ad8   NeilBrown   Documentation: co...
824
825
  For ``mnt->mnt_count`` it is safe to take a reference as long as
  ``mount_lock`` is then used to validate the reference.  If that
3ce96239d   Neil Brown   Documentation: ad...
826
  validation fails, it may *not* be safe to just drop that reference in
7bbfd9ad8   NeilBrown   Documentation: co...
827
828
  the standard way of calling ``mnt_put()`` - an unmount may have
  progressed too far.  So the code in ``legitimize_mnt()``, when it
3ce96239d   Neil Brown   Documentation: ad...
829
  finds that the reference it got might not be safe, checks the
7bbfd9ad8   NeilBrown   Documentation: co...
830
  ``MNT_SYNC_UMOUNT`` flag to determine if a simple ``mnt_put()`` is
3ce96239d   Neil Brown   Documentation: ad...
831
832
833
834
  correct, or if it should just decrement the count and pretend none of
  this ever happened.
  
  Taking care in filesystems
7bbfd9ad8   NeilBrown   Documentation: co...
835
  --------------------------
3ce96239d   Neil Brown   Documentation: ad...
836
837
838
839
840
841
842
843
844
  
  RCU-walk depends almost entirely on cached information and often will
  not call into the filesystem at all.  However there are two places,
  besides the already-mentioned component-name comparison, where the
  file system might be included in RCU-walk, and it must know to be
  careful.
  
  If the filesystem has non-standard permission-checking requirements -
  such as a networked filesystem which may need to check with the server
7bbfd9ad8   NeilBrown   Documentation: co...
845
846
847
848
  - the ``i_op->permission`` interface might be called during RCU-walk.
  In this case an extra "``MAY_NOT_BLOCK``" flag is passed so that it
  knows not to sleep, but to return ``-ECHILD`` if it cannot complete
  promptly.  ``i_op->permission`` is given the inode pointer, not the
3ce96239d   Neil Brown   Documentation: ad...
849
850
  dentry, so it doesn't need to worry about further consistency checks.
  However if it accesses any other filesystem data structures, it must
7bbfd9ad8   NeilBrown   Documentation: co...
851
852
  ensure they are safe to be accessed with only the ``rcu_read_lock()``
  held.  This typically means they must be freed using ``kfree_rcu()`` or
3ce96239d   Neil Brown   Documentation: ad...
853
  similar.
7bbfd9ad8   NeilBrown   Documentation: co...
854
  .. _READ_ONCE: https://lwn.net/Articles/624126/
3ce96239d   Neil Brown   Documentation: ad...
855
856
  
  If the filesystem may need to revalidate dcache entries, then
7bbfd9ad8   NeilBrown   Documentation: co...
857
858
859
  ``d_op->d_revalidate`` may be called in RCU-walk too.  This interface
  *is* passed the dentry but does not have access to the ``inode`` or the
  ``seq`` number from the ``nameidata``, so it needs to be extra careful
3ce96239d   Neil Brown   Documentation: ad...
860
  when accessing fields in the dentry.  This "extra care" typically
7bbfd9ad8   NeilBrown   Documentation: co...
861
  involves using  `READ_ONCE() <READ_ONCE_>`_ to access fields, and verifying the
3587679d9   Paul E. McKenney   locking/atomics, ...
862
  result is not NULL before using it.  This pattern can be seen in
7bbfd9ad8   NeilBrown   Documentation: co...
863
  ``nfs_lookup_revalidate()``.
3ce96239d   Neil Brown   Documentation: ad...
864
865
866
867
868
869
870
871
872
873
  
  A pair of patterns
  ------------------
  
  In various places in the details of REF-walk and RCU-walk, and also in
  the big picture, there are a couple of related patterns that are worth
  being aware of.
  
  The first is "try quickly and check, if that fails try slowly".  We
  can see that in the high-level approach of first trying RCU-walk and
7bbfd9ad8   NeilBrown   Documentation: co...
874
  then trying REF-walk, and in places where ``unlazy_walk()`` is used to
3ce96239d   Neil Brown   Documentation: ad...
875
  switch to REF-walk for the rest of the path.  We also saw it earlier
7bbfd9ad8   NeilBrown   Documentation: co...
876
  in ``dget_parent()`` when following a "``..``" link.  It tries a quick way
3ce96239d   Neil Brown   Documentation: ad...
877
878
879
  to get a reference, then falls back to taking locks if needed.
  
  The second pattern is "try quickly and check, if that fails try
7bbfd9ad8   NeilBrown   Documentation: co...
880
881
  again - repeatedly".  This is seen with the use of ``rename_lock`` and
  ``mount_lock`` in REF-walk.  RCU-walk doesn't make use of this pattern -
3ce96239d   Neil Brown   Documentation: ad...
882
883
884
885
  if anything goes wrong it is much safer to just abort and try a more
  sedate approach.
  
  The emphasis here is "try quickly and check".  It should probably be
286b7e24a   Vegard Nossum   docs: path-lookup...
886
  "try quickly *and carefully*, then check".  The fact that checking is
3ce96239d   Neil Brown   Documentation: ad...
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
  needed is a reminder that the system is dynamic and only a limited
  number of things are safe at all.  The most likely cause of errors in
  this whole process is assuming something is safe when in reality it
  isn't.  Careful consideration of what exactly guarantees the safety of
  each access is sometimes necessary.
  
  A walk among the symlinks
  =========================
  
  There are several basic issues that we will examine to understand the
  handling of symbolic links:  the symlink stack, together with cache
  lifetimes, will help us understand the overall recursive handling of
  symlinks and lead to the special care needed for the final component.
  Then a consideration of access-time updates and summary of the various
  flags controlling lookup will finish the story.
  
  The symlink stack
  -----------------
  
  There are only two sorts of filesystem objects that can usefully
  appear in a path prior to the final component: directories and symlinks.
  Handling directories is quite straightforward: the new directory
  simply becomes the starting point at which to interpret the next
  component on the path.  Handling symbolic links requires a bit more
  work.
  
  Conceptually, symbolic links could be handled by editing the path.  If
  a component name refers to a symbolic link, then that component is
  replaced by the body of the link and, if that body starts with a '/',
  then all preceding parts of the path are discarded.  This is what the
7bbfd9ad8   NeilBrown   Documentation: co...
917
918
  "``readlink -f``" command does, though it also edits out "``.``" and
  "``..``" components.
3ce96239d   Neil Brown   Documentation: ad...
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
  
  Directly editing the path string is not really necessary when looking
  up a path, and discarding early components is pointless as they aren't
  looked at anyway.  Keeping track of all remaining components is
  important, but they can of course be kept separately; there is no need
  to concatenate them.  As one symlink may easily refer to another,
  which in turn can refer to a third, we may need to keep the remaining
  components of several paths, each to be processed when the preceding
  ones are completed.  These path remnants are kept on a stack of
  limited size.
  
  There are two reasons for placing limits on how many symlinks can
  occur in a single path lookup.  The most obvious is to avoid loops.
  If a symlink referred to itself either directly or through
  intermediaries, then following the symlink can never complete
7bbfd9ad8   NeilBrown   Documentation: co...
934
  successfully - the error ``ELOOP`` must be returned.  Loops can be
3ce96239d   Neil Brown   Documentation: ad...
935
936
  detected without imposing limits, but limits are the simplest solution
  and, given the second reason for restriction, quite sufficient.
7bbfd9ad8   NeilBrown   Documentation: co...
937
  .. _outlined recently: http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550
3ce96239d   Neil Brown   Documentation: ad...
938

7bbfd9ad8   NeilBrown   Documentation: co...
939
  The second reason was `outlined recently`_ by Linus:
3ce96239d   Neil Brown   Documentation: ad...
940

7bbfd9ad8   NeilBrown   Documentation: co...
941
942
943
     Because it's a latency and DoS issue too. We need to react well to
     true loops, but also to "very deep" non-loops. It's not about memory
     use, it's about users triggering unreasonable CPU resources.
3ce96239d   Neil Brown   Documentation: ad...
944

7bbfd9ad8   NeilBrown   Documentation: co...
945
  Linux imposes a limit on the length of any pathname: ``PATH_MAX``, which
3ce96239d   Neil Brown   Documentation: ad...
946
947
948
949
950
951
952
953
  is 4096.  There are a number of reasons for this limit; not letting the
  kernel spend too much time on just one path is one of them.  With
  symbolic links you can effectively generate much longer paths so some
  sort of limit is needed for the same reason.  Linux imposes a limit of
  at most 40 symlinks in any one path lookup.  It previously imposed a
  further limit of eight on the maximum depth of recursion, but that was
  raised to 40 when a separate stack was implemented, so there is now
  just the one limit.
7bbfd9ad8   NeilBrown   Documentation: co...
954
  The ``nameidata`` structure that we met in an earlier article contains a
3ce96239d   Neil Brown   Documentation: ad...
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
  small stack that can be used to store the remaining part of up to two
  symlinks.  In many cases this will be sufficient.  If it isn't, a
  separate stack is allocated with room for 40 symlinks.  Pathname
  lookup will never exceed that stack as, once the 40th symlink is
  detected, an error is returned.
  
  It might seem that the name remnants are all that needs to be stored on
  this stack, but we need a bit more.  To see that, we need to move on to
  cache lifetimes.
  
  Storage and lifetime of cached symlinks
  ---------------------------------------
  
  Like other filesystem resources, such as inodes and directory
  entries, symlinks are cached by Linux to avoid repeated costly access
  to external storage.  It is particularly important for RCU-walk to be
  able to find and temporarily hold onto these cached entries, so that
  it doesn't need to drop down into REF-walk.
7bbfd9ad8   NeilBrown   Documentation: co...
973
  .. _object-oriented design pattern: https://lwn.net/Articles/446317/
3ce96239d   Neil Brown   Documentation: ad...
974
975
976
  
  While each filesystem is free to make its own choice, symlinks are
  typically stored in one of two places.  Short symlinks are often
7bbfd9ad8   NeilBrown   Documentation: co...
977
978
979
  stored directly in the inode.  When a filesystem allocates a ``struct
  inode`` it typically allocates extra space to store private data (a
  common `object-oriented design pattern`_ in the kernel).  This will
3ce96239d   Neil Brown   Documentation: ad...
980
981
982
983
984
985
986
987
988
989
990
991
992
993
  sometimes include space for a symlink.  The other common location is
  in the page cache, which normally stores the content of files.  The
  pathname in a symlink can be seen as the content of that symlink and
  can easily be stored in the page cache just like file content.
  
  When neither of these is suitable, the next most likely scenario is
  that the filesystem will allocate some temporary memory and copy or
  construct the symlink content into that memory whenever it is needed.
  
  When the symlink is stored in the inode, it has the same lifetime as
  the inode which, itself, is protected by RCU or by a counted reference
  on the dentry.  This means that the mechanisms that pathname lookup
  uses to access the dcache and icache (inode cache) safely are quite
  sufficient for accessing some cached symlinks safely.  In these cases,
7bbfd9ad8   NeilBrown   Documentation: co...
994
  the ``i_link`` pointer in the inode is set to point to wherever the
3ce96239d   Neil Brown   Documentation: ad...
995
996
997
998
999
  symlink is stored and it can be accessed directly whenever needed.
  
  When the symlink is stored in the page cache or elsewhere, the
  situation is not so straightforward.  A reference on a dentry or even
  on an inode does not imply any reference on cached pages of that
7bbfd9ad8   NeilBrown   Documentation: co...
1000
  inode, and even an ``rcu_read_lock()`` is not sufficient to ensure that
3ce96239d   Neil Brown   Documentation: ad...
1001
1002
1003
1004
1005
1006
1007
1008
1009
  a page will not disappear.  So for these symlinks the pathname lookup
  code needs to ask the filesystem to provide a stable reference and,
  significantly, needs to release that reference when it is finished
  with it.
  
  Taking a reference to a cache page is often possible even in RCU-walk
  mode.  It does require making changes to memory, which is best avoided,
  but that isn't necessarily a big cost and it is better than dropping
  out of RCU-walk mode completely.  Even filesystems that allocate
7bbfd9ad8   NeilBrown   Documentation: co...
1010
  space to copy the symlink into can use ``GFP_ATOMIC`` to often successfully
3ce96239d   Neil Brown   Documentation: ad...
1011
1012
  allocate memory without the need to drop out of RCU-walk.  If a
  filesystem cannot successfully get a reference in RCU-walk mode, it
7bbfd9ad8   NeilBrown   Documentation: co...
1013
  must return ``-ECHILD`` and ``unlazy_walk()`` will be called to return to
3ce96239d   Neil Brown   Documentation: ad...
1014
  REF-walk mode in which the filesystem is allowed to sleep.
7bbfd9ad8   NeilBrown   Documentation: co...
1015
  The place for all this to happen is the ``i_op->follow_link()`` inode
3ce96239d   Neil Brown   Documentation: ad...
1016
1017
  method.  In the present mainline code this is never actually called in
  RCU-walk mode as the rewrite is not quite complete.  It is likely that
7bbfd9ad8   NeilBrown   Documentation: co...
1018
  in a future release this method will be passed an ``inode`` pointer when
3ce96239d   Neil Brown   Documentation: ad...
1019
  called in RCU-walk mode so it both (1) knows to be careful, and (2) has the
7bbfd9ad8   NeilBrown   Documentation: co...
1020
1021
  validated pointer.  Much like the ``i_op->permission()`` method we
  looked at previously, ``->follow_link()`` would need to be careful that
3ce96239d   Neil Brown   Documentation: ad...
1022
1023
  all the data structures it references are safe to be accessed while
  holding no counted reference, only the RCU lock.  Though getting a
7bbfd9ad8   NeilBrown   Documentation: co...
1024
  reference with ``->follow_link()`` is not yet done in RCU-walk mode, the
3ce96239d   Neil Brown   Documentation: ad...
1025
1026
1027
1028
  code is ready to release the reference when that does happen.
  
  This need to drop the reference to a symlink adds significant
  complexity.  It requires a reference to the inode so that the
7bbfd9ad8   NeilBrown   Documentation: co...
1029
  ``i_op->put_link()`` inode operation can be called.  In REF-walk, that
3ce96239d   Neil Brown   Documentation: ad...
1030
  reference is kept implicitly through a reference to the dentry, so
7bbfd9ad8   NeilBrown   Documentation: co...
1031
  keeping the ``struct path`` of the symlink is easiest.  For RCU-walk,
3ce96239d   Neil Brown   Documentation: ad...
1032
1033
1034
1035
1036
1037
  the pointer to the inode is kept separately.  To allow switching from
  RCU-walk back to REF-walk in the middle of processing nested symlinks
  we also need the seq number for the dentry so we can confirm that
  switching back was safe.
  
  Finally, when providing a reference to a symlink, the filesystem also
7bbfd9ad8   NeilBrown   Documentation: co...
1038
  provides an opaque "cookie" that must be passed to ``->put_link()`` so that it
3ce96239d   Neil Brown   Documentation: ad...
1039
  knows what to free.  This might be the allocated memory area, or a
7bbfd9ad8   NeilBrown   Documentation: co...
1040
  pointer to the ``struct page`` in the page cache, or something else
3ce96239d   Neil Brown   Documentation: ad...
1041
1042
1043
1044
1045
  completely.  Only the filesystem knows what it is.
  
  In order for the reference to each symlink to be dropped when the walk completes,
  whether in RCU-walk or REF-walk, the symlink stack needs to contain,
  along with the path remnants:
7bbfd9ad8   NeilBrown   Documentation: co...
1046
1047
1048
1049
  - the ``struct path`` to provide a reference to the inode in REF-walk
  - the ``struct inode *`` to provide a reference to the inode in RCU-walk
  - the ``seq`` to allow the path to be safely switched from RCU-walk to REF-walk
  - the ``cookie`` that tells ``->put_path()`` what to put.
3ce96239d   Neil Brown   Documentation: ad...
1050
1051
1052
1053
1054
1055
1056
  
  This means that each entry in the symlink stack needs to hold five
  pointers and an integer instead of just one pointer (the path
  remnant).  On a 64-bit system, this is about 40 bytes per entry;
  with 40 entries it adds up to 1600 bytes total, which is less than
  half a page.  So it might seem like a lot, but is by no means
  excessive.
7bbfd9ad8   NeilBrown   Documentation: co...
1057
  Note that, in a given stack frame, the path remnant (``name``) is not
3ce96239d   Neil Brown   Documentation: ad...
1058
1059
1060
1061
1062
  part of the symlink that the other fields refer to.  It is the remnant
  to be followed once that symlink has been fully parsed.
  
  Following the symlink
  ---------------------
7bbfd9ad8   NeilBrown   Documentation: co...
1063
  The main loop in ``link_path_walk()`` iterates seamlessly over all
3ce96239d   Neil Brown   Documentation: ad...
1064
  components in the path and all of the non-final symlinks.  As symlinks
7bbfd9ad8   NeilBrown   Documentation: co...
1065
  are processed, the ``name`` pointer is adjusted to point to a new
3ce96239d   Neil Brown   Documentation: ad...
1066
  symlink, or is restored from the stack, so that much of the loop
7bbfd9ad8   NeilBrown   Documentation: co...
1067
  doesn't need to notice.  Getting this ``name`` variable on and off the
3ce96239d   Neil Brown   Documentation: ad...
1068
1069
  stack is very straightforward; pushing and popping the references is
  a little more complex.
7bbfd9ad8   NeilBrown   Documentation: co...
1070
1071
1072
  When a symlink is found, ``walk_component()`` returns the value ``1``
  (``0`` is returned for any other sort of success, and a negative number
  is, as usual, an error indicator).  This causes ``get_link()`` to be
3ce96239d   Neil Brown   Documentation: ad...
1073
  called; it then gets the link from the filesystem.  Providing that
7bbfd9ad8   NeilBrown   Documentation: co...
1074
1075
1076
  operation is successful, the old path ``name`` is placed on the stack,
  and the new value is used as the ``name`` for a while.  When the end of
  the path is found (i.e. ``*name`` is ``'\0'``) the old ``name`` is restored
3ce96239d   Neil Brown   Documentation: ad...
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
  off the stack and path walking continues.
  
  Pushing and popping the reference pointers (inode, cookie, etc.) is more
  complex in part because of the desire to handle tail recursion.  When
  the last component of a symlink itself points to a symlink, we
  want to pop the symlink-just-completed off the stack before pushing
  the symlink-just-found to avoid leaving empty path remnants that would
  just get in the way.
  
  It is most convenient to push the new symlink references onto the
7bbfd9ad8   NeilBrown   Documentation: co...
1087
1088
  stack in ``walk_component()`` immediately when the symlink is found;
  ``walk_component()`` is also the last piece of code that needs to look at the
3ce96239d   Neil Brown   Documentation: ad...
1089
  old symlink as it walks that last component.  So it is quite
7bbfd9ad8   NeilBrown   Documentation: co...
1090
  convenient for ``walk_component()`` to release the old symlink and pop
3ce96239d   Neil Brown   Documentation: ad...
1091
  the references just before pushing the reference information for the
7bbfd9ad8   NeilBrown   Documentation: co...
1092
  new symlink.  It is guided in this by two flags; ``WALK_GET``, which
3ce96239d   Neil Brown   Documentation: ad...
1093
  gives it permission to follow a symlink if it finds one, and
7bbfd9ad8   NeilBrown   Documentation: co...
1094
1095
1096
1097
  ``WALK_PUT``, which tells it to release the current symlink after it has been
  followed.  ``WALK_PUT`` is tested first, leading to a call to
  ``put_link()``.  ``WALK_GET`` is tested subsequently (by
  ``should_follow_link()``) leading to a call to ``pick_link()`` which sets
3ce96239d   Neil Brown   Documentation: ad...
1098
  up the stack frame.
7bbfd9ad8   NeilBrown   Documentation: co...
1099
1100
  Symlinks with no final component
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
1101
1102
  
  A pair of special-case symlinks deserve a little further explanation.
7bbfd9ad8   NeilBrown   Documentation: co...
1103
1104
  Both result in a new ``struct path`` (with mount and dentry) being set
  up in the ``nameidata``, and result in ``get_link()`` returning ``NULL``.
3ce96239d   Neil Brown   Documentation: ad...
1105

7bbfd9ad8   NeilBrown   Documentation: co...
1106
1107
  The more obvious case is a symlink to "``/``".  All symlinks starting
  with "``/``" are detected in ``get_link()`` which resets the ``nameidata``
3ce96239d   Neil Brown   Documentation: ad...
1108
  to point to the effective filesystem root.  If the symlink only
7bbfd9ad8   NeilBrown   Documentation: co...
1109
1110
  contains "``/``" then there is nothing more to do, no components at all,
  so ``NULL`` is returned to indicate that the symlink can be released and
3ce96239d   Neil Brown   Documentation: ad...
1111
  the stack frame discarded.
7bbfd9ad8   NeilBrown   Documentation: co...
1112
  The other case involves things in ``/proc`` that look like symlinks but
b55eef872   Aleksa Sarai   Documentation: pa...
1113
  aren't really (and are therefore commonly referred to as "magic-links")::
3ce96239d   Neil Brown   Documentation: ad...
1114

7bbfd9ad8   NeilBrown   Documentation: co...
1115
1116
       $ ls -l /proc/self/fd/1
       lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4
3ce96239d   Neil Brown   Documentation: ad...
1117

7bbfd9ad8   NeilBrown   Documentation: co...
1118
  Every open file descriptor in any process is represented in ``/proc`` by
3ce96239d   Neil Brown   Documentation: ad...
1119
  something that looks like a symlink.  It is really a reference to the
7bbfd9ad8   NeilBrown   Documentation: co...
1120
  target file, not just the name of it.  When you ``readlink`` these
3ce96239d   Neil Brown   Documentation: ad...
1121
  objects you get a name that might refer to the same file - unless it
7bbfd9ad8   NeilBrown   Documentation: co...
1122
1123
1124
1125
1126
1127
1128
  has been unlinked or mounted over.  When ``walk_component()`` follows
  one of these, the ``->follow_link()`` method in "procfs" doesn't return
  a string name, but instead calls ``nd_jump_link()`` which updates the
  ``nameidata`` in place to point to that target.  ``->follow_link()`` then
  returns ``NULL``.  Again there is no final component and ``get_link()``
  reports this by leaving the ``last_type`` field of ``nameidata`` as
  ``LAST_BIND``.
3ce96239d   Neil Brown   Documentation: ad...
1129
1130
1131
  
  Following the symlink in the final component
  --------------------------------------------
7bbfd9ad8   NeilBrown   Documentation: co...
1132
  All this leads to ``link_path_walk()`` walking down every component, and
3ce96239d   Neil Brown   Documentation: ad...
1133
  following all symbolic links it finds, until it reaches the final
7bbfd9ad8   NeilBrown   Documentation: co...
1134
  component.  This is just returned in the ``last`` field of ``nameidata``.
3ce96239d   Neil Brown   Documentation: ad...
1135
  For some callers, this is all they need; they want to create that
7bbfd9ad8   NeilBrown   Documentation: co...
1136
  ``last`` name if it doesn't exist or give an error if it does.  Other
3ce96239d   Neil Brown   Documentation: ad...
1137
1138
1139
  callers will want to follow a symlink if one is found, and possibly
  apply special handling to the last component of that symlink, rather
  than just the last component of the original file name.  These callers
7bbfd9ad8   NeilBrown   Documentation: co...
1140
  potentially need to call ``link_path_walk()`` again and again on
3ce96239d   Neil Brown   Documentation: ad...
1141
1142
  successive symlinks until one is found that doesn't point to another
  symlink.
7bbfd9ad8   NeilBrown   Documentation: co...
1143
1144
  This case is handled by the relevant caller of ``link_path_walk()``, such as
  ``path_lookupat()`` using a loop that calls ``link_path_walk()``, and then
3ce96239d   Neil Brown   Documentation: ad...
1145
  handles the final component.  If the final component is a symlink
7bbfd9ad8   NeilBrown   Documentation: co...
1146
1147
  that needs to be followed, then ``trailing_symlink()`` is called to set
  things up properly and the loop repeats, calling ``link_path_walk()``
3ce96239d   Neil Brown   Documentation: ad...
1148
1149
1150
1151
  again.  This could loop as many as 40 times if the last component of
  each symlink is another symlink.
  
  The various functions that examine the final component and possibly
7bbfd9ad8   NeilBrown   Documentation: co...
1152
1153
1154
  report that it is a symlink are ``lookup_last()``, ``mountpoint_last()``
  and ``do_last()``, each of which use the same convention as
  ``walk_component()`` of returning ``1`` if a symlink was found that needs
3ce96239d   Neil Brown   Documentation: ad...
1155
  to be followed.
7bbfd9ad8   NeilBrown   Documentation: co...
1156
1157
1158
  Of these, ``do_last()`` is the most interesting as it is used for
  opening a file.  Part of ``do_last()`` runs with ``i_rwsem`` held and this
  part is in a separate function: ``lookup_open()``.
3ce96239d   Neil Brown   Documentation: ad...
1159

7bbfd9ad8   NeilBrown   Documentation: co...
1160
  Explaining ``do_last()`` completely is beyond the scope of this article,
3ce96239d   Neil Brown   Documentation: ad...
1161
1162
  but a few highlights should help those interested in exploring the
  code.
7bbfd9ad8   NeilBrown   Documentation: co...
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
  1. Rather than just finding the target file, ``do_last()`` needs to open
     it.  If the file was found in the dcache, then ``vfs_open()`` is used for
     this.  If not, then ``lookup_open()`` will either call ``atomic_open()`` (if
     the filesystem provides it) to combine the final lookup with the open, or
     will perform the separate ``lookup_real()`` and ``vfs_create()`` steps
     directly.  In the later case the actual "open" of this newly found or
     created file will be performed by ``vfs_open()``, just as if the name
     were found in the dcache.
  
  2. ``vfs_open()`` can fail with ``-EOPENSTALE`` if the cached information
     wasn't quite current enough.  Rather than restarting the lookup from
     the top with ``LOOKUP_REVAL`` set, ``lookup_open()`` is called instead,
     giving the filesystem a chance to resolve small inconsistencies.
     If that doesn't work, only then is the lookup restarted from the top.
3ce96239d   Neil Brown   Documentation: ad...
1177
1178
  
  3. An open with O_CREAT **does** follow a symlink in the final component,
7bbfd9ad8   NeilBrown   Documentation: co...
1179
     unlike other creation system calls (like ``mkdir``).  So the sequence::
3ce96239d   Neil Brown   Documentation: ad...
1180

7bbfd9ad8   NeilBrown   Documentation: co...
1181
1182
            ln -s bar /tmp/foo
            echo hello > /tmp/foo
3ce96239d   Neil Brown   Documentation: ad...
1183

7bbfd9ad8   NeilBrown   Documentation: co...
1184
1185
1186
1187
1188
     will create a file called ``/tmp/bar``.  This is not permitted if
     ``O_EXCL`` is set but otherwise is handled for an O_CREAT open much
     like for a non-creating open: ``should_follow_link()`` returns ``1``, and
     so does ``do_last()`` so that ``trailing_symlink()`` gets called and the
     open process continues on the symlink that was found.
3ce96239d   Neil Brown   Documentation: ad...
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
  
  Updating the access time
  ------------------------
  
  We previously said of RCU-walk that it would "take no locks, increment
  no counts, leave no footprints."  We have since seen that some
  "footprints" can be needed when handling symlinks as a counted
  reference (or even a memory allocation) may be needed.  But these
  footprints are best kept to a minimum.
  
  One other place where walking down a symlink can involve leaving
  footprints in a way that doesn't affect directories is in updating access times.
  In Unix (and Linux) every filesystem object has a "last accessed
7bbfd9ad8   NeilBrown   Documentation: co...
1202
  time", or "``atime``".  Passing through a directory to access a file
3ce96239d   Neil Brown   Documentation: ad...
1203
  within is not considered to be an access for the purposes of
7bbfd9ad8   NeilBrown   Documentation: co...
1204
1205
  ``atime``; only listing the contents of a directory can update its ``atime``.
  Symlinks are different it seems.  Both reading a symlink (with ``readlink()``)
3ce96239d   Neil Brown   Documentation: ad...
1206
1207
  and looking up a symlink on the way to some other destination can
  update the atime on that symlink.
c69f22f25   Alexander A. Klimov   Replace HTTP link...
1208
  .. _clearest statement: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08
3ce96239d   Neil Brown   Documentation: ad...
1209
1210
  
  It is not clear why this is the case; POSIX has little to say on the
7bbfd9ad8   NeilBrown   Documentation: co...
1211
  subject.  The `clearest statement`_ is that, if a particular implementation
3ce96239d   Neil Brown   Documentation: ad...
1212
1213
1214
1215
  updates a timestamp in a place not specified by POSIX, this must be
  documented "except that any changes caused by pathname resolution need
  not be documented".  This seems to imply that POSIX doesn't really
  care about access-time updates during pathname lookup.
7bbfd9ad8   NeilBrown   Documentation: co...
1216
  .. _Linux 1.3.87: https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8
3ce96239d   Neil Brown   Documentation: ad...
1217

7bbfd9ad8   NeilBrown   Documentation: co...
1218
  An examination of history shows that prior to `Linux 1.3.87`_, the ext2
3ce96239d   Neil Brown   Documentation: ad...
1219
1220
1221
1222
1223
  filesystem, at least, didn't update atime when following a link.
  Unfortunately we have no record of why that behavior was changed.
  
  In any case, access time must now be updated and that operation can be
  quite complex.  Trying to stay in RCU-walk while doing it is best
7bbfd9ad8   NeilBrown   Documentation: co...
1224
1225
1226
1227
  avoided.  Fortunately it is often permitted to skip the ``atime``
  update.  Because ``atime`` updates cause performance problems in various
  areas, Linux supports the ``relatime`` mount option, which generally
  limits the updates of ``atime`` to once per day on files that aren't
3ce96239d   Neil Brown   Documentation: ad...
1228
  being changed (and symlinks never change once created).  Even without
7bbfd9ad8   NeilBrown   Documentation: co...
1229
  ``relatime``, many filesystems record ``atime`` with a one-second
3ce96239d   Neil Brown   Documentation: ad...
1230
  granularity, so only one update per second is required.
7bbfd9ad8   NeilBrown   Documentation: co...
1231
  It is easy to test if an ``atime`` update is needed while in RCU-walk
3ce96239d   Neil Brown   Documentation: ad...
1232
  mode and, if it isn't, the update can be skipped and RCU-walk mode
7bbfd9ad8   NeilBrown   Documentation: co...
1233
  continues.  Only when an ``atime`` update is actually required does the
3ce96239d   Neil Brown   Documentation: ad...
1234
  path walk drop down to REF-walk.  All of this is handled in the
7bbfd9ad8   NeilBrown   Documentation: co...
1235
  ``get_link()`` function.
3ce96239d   Neil Brown   Documentation: ad...
1236
1237
1238
1239
1240
  
  A few flags
  -----------
  
  A suitable way to wrap up this tour of pathname walking is to list
7bbfd9ad8   NeilBrown   Documentation: co...
1241
  the various flags that can be stored in the ``nameidata`` to guide the
3ce96239d   Neil Brown   Documentation: ad...
1242
  lookup process.  Many of these are only meaningful on the final
b55eef872   Aleksa Sarai   Documentation: pa...
1243
1244
  component, others reflect the current state of the pathname lookup, and some
  apply restrictions to all path components encountered in the path lookup.
7bbfd9ad8   NeilBrown   Documentation: co...
1245
  And then there is ``LOOKUP_EMPTY``, which doesn't fit conceptually with
3ce96239d   Neil Brown   Documentation: ad...
1246
1247
1248
  the others.  If this is not set, an empty pathname causes an error
  very early on.  If it is set, empty pathnames are not considered to be
  an error.
7bbfd9ad8   NeilBrown   Documentation: co...
1249
1250
  Global state flags
  ~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
1251

7bbfd9ad8   NeilBrown   Documentation: co...
1252
1253
  We have already met two global state flags: ``LOOKUP_RCU`` and
  ``LOOKUP_REVAL``.  These select between one of three overall approaches
3ce96239d   Neil Brown   Documentation: ad...
1254
  to lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.
7bbfd9ad8   NeilBrown   Documentation: co...
1255
  ``LOOKUP_PARENT`` indicates that the final component hasn't been reached
3ce96239d   Neil Brown   Documentation: ad...
1256
1257
  yet.  This is primarily used to tell the audit subsystem the full
  context of a particular access being audited.
7bbfd9ad8   NeilBrown   Documentation: co...
1258
  ``LOOKUP_ROOT`` indicates that the ``root`` field in the ``nameidata`` was
3ce96239d   Neil Brown   Documentation: ad...
1259
1260
  provided by the caller, so it shouldn't be released when it is no
  longer needed.
7bbfd9ad8   NeilBrown   Documentation: co...
1261
  ``LOOKUP_JUMPED`` means that the current dentry was chosen not because
3ce96239d   Neil Brown   Documentation: ad...
1262
  it had the right name but for some other reason.  This happens when
7bbfd9ad8   NeilBrown   Documentation: co...
1263
  following "``..``", following a symlink to ``/``, crossing a mount point
b55eef872   Aleksa Sarai   Documentation: pa...
1264
1265
1266
1267
  or accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic
  link"). In this case the filesystem has not been asked to revalidate the
  name (with ``d_revalidate()``).  In such cases the inode may still need
  to be revalidated, so ``d_op->d_weak_revalidate()`` is called if
7bbfd9ad8   NeilBrown   Documentation: co...
1268
  ``LOOKUP_JUMPED`` is set when the look completes - which may be at the
3ce96239d   Neil Brown   Documentation: ad...
1269
  final component or, when creating, unlinking, or renaming, at the penultimate component.
b55eef872   Aleksa Sarai   Documentation: pa...
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
  Resolution-restriction flags
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
  In order to allow userspace to protect itself against certain race conditions
  and attack scenarios involving changing path components, a series of flags are
  available which apply restrictions to all path components encountered during
  path lookup. These flags are exposed through ``openat2()``'s ``resolve`` field.
  
  ``LOOKUP_NO_SYMLINKS`` blocks all symlink traversals (including magic-links).
  This is distinctly different from ``LOOKUP_FOLLOW``, because the latter only
  relates to restricting the following of trailing symlinks.
  
  ``LOOKUP_NO_MAGICLINKS`` blocks all magic-link traversals. Filesystems must
  ensure that they return errors from ``nd_jump_link()``, because that is how
  ``LOOKUP_NO_MAGICLINKS`` and other magic-link restrictions are implemented.
  
  ``LOOKUP_NO_XDEV`` blocks all ``vfsmount`` traversals (this includes both
  bind-mounts and ordinary mounts). Note that the ``vfsmount`` which contains the
  lookup is determined by the first mountpoint the path lookup reaches --
  absolute paths start with the ``vfsmount`` of ``/``, and relative paths start
  with the ``dfd``'s ``vfsmount``. Magic-links are only permitted if the
  ``vfsmount`` of the path is unchanged.
  
  ``LOOKUP_BENEATH`` blocks any path components which resolve outside the
  starting point of the resolution. This is done by blocking ``nd_jump_root()``
  as well as blocking ".." if it would jump outside the starting point.
  ``rename_lock`` and ``mount_lock`` are used to detect attacks against the
  resolution of "..". Magic-links are also blocked.
  
  ``LOOKUP_IN_ROOT`` resolves all path components as though the starting point
9b123556b   Randy Dunlap   Documentation: fi...
1300
  were the filesystem root. ``nd_jump_root()`` brings the resolution back to
b55eef872   Aleksa Sarai   Documentation: pa...
1301
1302
1303
  the starting point, and ".." at the starting point will act as a no-op. As with
  ``LOOKUP_BENEATH``, ``rename_lock`` and ``mount_lock`` are used to detect
  attacks against ".." resolution. Magic-links are also blocked.
7bbfd9ad8   NeilBrown   Documentation: co...
1304
1305
  Final-component flags
  ~~~~~~~~~~~~~~~~~~~~~
3ce96239d   Neil Brown   Documentation: ad...
1306
1307
1308
1309
  
  Some of these flags are only set when the final component is being
  considered.  Others are only checked for when considering that final
  component.
7bbfd9ad8   NeilBrown   Documentation: co...
1310
  ``LOOKUP_AUTOMOUNT`` ensures that, if the final component is an automount
3ce96239d   Neil Brown   Documentation: ad...
1311
  point, then the mount is triggered.  Some operations would trigger it
7bbfd9ad8   NeilBrown   Documentation: co...
1312
1313
1314
1315
  anyway, but operations like ``stat()`` deliberately don't.  ``statfs()``
  needs to trigger the mount but otherwise behaves a lot like ``stat()``, so
  it sets ``LOOKUP_AUTOMOUNT``, as does "``quotactl()``" and the handling of
  "``mount --bind``".
3ce96239d   Neil Brown   Documentation: ad...
1316

7bbfd9ad8   NeilBrown   Documentation: co...
1317
  ``LOOKUP_FOLLOW`` has a similar function to ``LOOKUP_AUTOMOUNT`` but for
3ce96239d   Neil Brown   Documentation: ad...
1318
  symlinks.  Some system calls set or clear it implicitly, while
7bbfd9ad8   NeilBrown   Documentation: co...
1319
1320
1321
  others have API flags such as ``AT_SYMLINK_FOLLOW`` and
  ``UMOUNT_NOFOLLOW`` to control it.  Its effect is similar to
  ``WALK_GET`` that we already met, but it is used in a different way.
3ce96239d   Neil Brown   Documentation: ad...
1322

7bbfd9ad8   NeilBrown   Documentation: co...
1323
  ``LOOKUP_DIRECTORY`` insists that the final component is a directory.
3ce96239d   Neil Brown   Documentation: ad...
1324
1325
  Various callers set this and it is also set when the final component
  is found to be followed by a slash.
7bbfd9ad8   NeilBrown   Documentation: co...
1326
1327
1328
  Finally ``LOOKUP_OPEN``, ``LOOKUP_CREATE``, ``LOOKUP_EXCL``, and
  ``LOOKUP_RENAME_TARGET`` are not used directly by the VFS but are made
  available to the filesystem and particularly the ``->d_revalidate()``
3ce96239d   Neil Brown   Documentation: ad...
1329
1330
  method.  A filesystem can choose not to bother revalidating too hard
  if it knows that it will be asked to open or create the file soon.
7bbfd9ad8   NeilBrown   Documentation: co...
1331
1332
  These flags were previously useful for ``->lookup()`` too but with the
  introduction of ``->atomic_open()`` they are less relevant there.
3ce96239d   Neil Brown   Documentation: ad...
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
  
  End of the road
  ---------------
  
  Despite its complexity, all this pathname lookup code appears to be
  in good shape - various parts are certainly easier to understand now
  than even a couple of releases ago.  But that doesn't mean it is
  "finished".   As already mentioned, RCU-walk currently only follows
  symlinks that are stored in the inode so, while it handles many ext4
  symlinks, it doesn't help with NFS, XFS, or Btrfs.  That support
  is not likely to be long delayed.