← Documents Documentation/filesystems/overlayfs.rst GitHub 원문 ↗

Linux 6.18.37 · Filesystems

OverlayFS

OverlayFS 계층 병합, copy-up, metacopy, NFS export, verity와 내구성 의미를 다룬 전문 번역입니다.

Source pathDocumentation/filesystems/overlayfs.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

overlayfs.rst:1-883

OverlayFS는 읽기 중심 lower tree와 쓰기 가능한 upper tree를 병합합니다. Upper가 이름과 metadata를 우선하며 삭제는 whiteout·opaque xattr, 첫 쓰기는 copy_up, metadata 변경은 선택적으로 metacopy로 표현합니다.

신뢰성과 호환성은 `xino`, `index`, `redirect_dir`, `nfs_export`, `verity`, `uuid`, `fsync`의 조합에 좌우됩니다. 특히 비신뢰 metacopy 계층, upper·workdir 공유, mount 중 underlying 변경, volatile mount의 내구성 상실은 명시적으로 피하거나 운영 절차로 통제해야 합니다.

OverlayFS 핵심 경로
Upper·lower 이름 lookupDirectory면 이름 목록 mergeWhiteout·opaque·redirect 적용Write 필요 시 metadata 또는 full copy_upIndex·origin·verity로 identity와 content 검증Fsync 정책에 따라 upper에 영속화Merged namespace로 결과 노출

이름 조회부터 copy-up, 검증과 내구성 보장까지의 전체 흐름입니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 Written by: Neil Brown
4 Please see MAINTAINERS file for where to send questions.
5
6 Overlay Filesystem
7 ==================
8
9 This document describes a prototype for a new approach to providing
10 overlay-filesystem functionality in Linux (sometimes referred to as
11 union-filesystems). An overlay-filesystem tries to present a
12 filesystem which is the result of overlaying one filesystem on top
13 of the other.
14
15
16 Overlay objects
17 ---------------
18
19 The overlay filesystem approach is 'hybrid', because the objects that
20 appear in the filesystem do not always appear to belong to that filesystem.
21 In many cases, an object accessed in the union will be indistinguishable
22 from accessing the corresponding object from the original filesystem.
23 This is most obvious from the 'st_dev' field returned by stat(2).
24
25 While directories will report an st_dev from the overlay-filesystem,
26 non-directory objects may report an st_dev from the lower filesystem or
27 upper filesystem that is providing the object. Similarly st_ino will
28 only be unique when combined with st_dev, and both of these can change
29 over the lifetime of a non-directory object. Many applications and
30 tools ignore these values and will not be affected.
31
32 In the special case of all overlay layers on the same underlying
33 filesystem, all objects will report an st_dev from the overlay
34 filesystem and st_ino from the underlying filesystem. This will
35 make the overlay mount more compliant with filesystem scanners and
36 overlay objects will be distinguishable from the corresponding
37 objects in the original filesystem.
38
39 On 64bit systems, even if all overlay layers are not on the same
40 underlying filesystem, the same compliant behavior could be achieved
41 with the "xino" feature. The "xino" feature composes a unique object
42 identifier from the real object st_ino and an underlying fsid number.
43 The "xino" feature uses the high inode number bits for fsid, because the
44 underlying filesystems rarely use the high inode number bits. In case
45 the underlying inode number does overflow into the high xino bits, overlay
46 filesystem will fall back to the non xino behavior for that inode.
47
48 The "xino" feature can be enabled with the "-o xino=on" overlay mount option.
49 If all underlying filesystems support NFS file handles, the value of st_ino
50 for overlay filesystem objects is not only unique, but also persistent over
51 the lifetime of the filesystem. The "-o xino=auto" overlay mount option
52 enables the "xino" feature only if the persistent st_ino requirement is met.
53
54 The following table summarizes what can be expected in different overlay
55 configurations.
56
57 Inode properties
58 ````````````````
59
60 +--------------+------------+------------+-----------------+----------------+
61 |Configuration | Persistent | Uniform | st_ino == d_ino | d_ino == i_ino |
62 | | st_ino | st_dev | | [*] |
63 +==============+=====+======+=====+======+========+========+========+=======+
64 | | dir | !dir | dir | !dir | dir | !dir | dir | !dir |
65 +--------------+-----+------+-----+------+--------+--------+--------+-------+
66 | All layers | Y | Y | Y | Y | Y | Y | Y | Y |
67 | on same fs | | | | | | | | |
68 +--------------+-----+------+-----+------+--------+--------+--------+-------+
69 | Layers not | N | N | Y | N | N | Y | N | Y |
70 | on same fs, | | | | | | | | |
71 | xino=off | | | | | | | | |
72 +--------------+-----+------+-----+------+--------+--------+--------+-------+
73 | xino=on/auto | Y | Y | Y | Y | Y | Y | Y | Y |
74 +--------------+-----+------+-----+------+--------+--------+--------+-------+
75 | xino=on/auto,| N | N | Y | N | N | Y | N | Y |
76 | ino overflow | | | | | | | | |
77 +--------------+-----+------+-----+------+--------+--------+--------+-------+
78
79 [*] nfsd v3 readdirplus verifies d_ino == i_ino. i_ino is exposed via several
80 /proc files, such as /proc/locks and /proc/self/fdinfo/<fd> of an inotify
81 file descriptor.
82
83 Upper and Lower
84 ---------------
85
86 An overlay filesystem combines two filesystems - an 'upper' filesystem
87 and a 'lower' filesystem. When a name exists in both filesystems, the
88 object in the 'upper' filesystem is visible while the object in the
89 'lower' filesystem is either hidden or, in the case of directories,
90 merged with the 'upper' object.
91
92 It would be more correct to refer to an upper and lower 'directory
93 tree' rather than 'filesystem' as it is quite possible for both
94 directory trees to be in the same filesystem and there is no
95 requirement that the root of a filesystem be given for either upper or
96 lower.
97
98 A wide range of filesystems supported by Linux can be the lower filesystem,
99 but not all filesystems that are mountable by Linux have the features
100 needed for OverlayFS to work. The lower filesystem does not need to be
101 writable. The lower filesystem can even be another overlayfs. The upper
102 filesystem will normally be writable and if it is it must support the
103 creation of trusted.* and/or user.* extended attributes, and must provide
104 valid d_type in readdir responses, so NFS is not suitable.
105
106 A read-only overlay of two read-only filesystems may use any
107 filesystem type.
108
109 Directories
110 -----------
111
112 Overlaying mainly involves directories. If a given name appears in both
113 upper and lower filesystems and refers to a non-directory in either,
114 then the lower object is hidden - the name refers only to the upper
115 object.
116
117 Where both upper and lower objects are directories, a merged directory
118 is formed.
119
120 At mount time, the two directories given as mount options "lowerdir" and
121 "upperdir" are combined into a merged directory::
122
123 mount -t overlay overlay -olowerdir=/lower,upperdir=/upper,\
124 workdir=/work /merged
125
126 The "workdir" needs to be an empty directory on the same filesystem
127 as upperdir.
128
129 Then whenever a lookup is requested in such a merged directory, the
130 lookup is performed in each actual directory and the combined result
131 is cached in the dentry belonging to the overlay filesystem. If both
132 actual lookups find directories, both are stored and a merged
133 directory is created, otherwise only one is stored: the upper if it
134 exists, else the lower.
135
136 Only the lists of names from directories are merged. Other content
137 such as metadata and extended attributes are reported for the upper
138 directory only. These attributes of the lower directory are hidden.
139
140 whiteouts and opaque directories
141 --------------------------------
142
143 In order to support rm and rmdir without changing the lower
144 filesystem, an overlay filesystem needs to record in the upper filesystem
145 that files have been removed. This is done using whiteouts and opaque
146 directories (non-directories are always opaque).
147
148 A whiteout is created as a character device with 0/0 device number or
149 as a zero-size regular file with the xattr "trusted.overlay.whiteout".
150
151 When a whiteout is found in the upper level of a merged directory, any
152 matching name in the lower level is ignored, and the whiteout itself
153 is also hidden.
154
155 A directory is made opaque by setting the xattr "trusted.overlay.opaque"
156 to "y". Where the upper filesystem contains an opaque directory, any
157 directory in the lower filesystem with the same name is ignored.
158
159 An opaque directory should not contain any whiteouts, because they do not
160 serve any purpose. A merge directory containing regular files with the xattr
161 "trusted.overlay.whiteout", should be additionally marked by setting the xattr
162 "trusted.overlay.opaque" to "x" on the merge directory itself.
163 This is needed to avoid the overhead of checking the "trusted.overlay.whiteout"
164 on all entries during readdir in the common case.
165
166 readdir
167 -------
168
169 When a 'readdir' request is made on a merged directory, the upper and
170 lower directories are each read and the name lists merged in the
171 obvious way (upper is read first, then lower - entries that already
172 exist are not re-added). This merged name list is cached in the
173 'struct file' and so remains as long as the file is kept open. If the
174 directory is opened and read by two processes at the same time, they
175 will each have separate caches. A seekdir to the start of the
176 directory (offset 0) followed by a readdir will cause the cache to be
177 discarded and rebuilt.
178
179 This means that changes to the merged directory do not appear while a
180 directory is being read. This is unlikely to be noticed by many
181 programs.
182
183 seek offsets are assigned sequentially when the directories are read.
184 Thus if:
185
186 - read part of a directory
187 - remember an offset, and close the directory
188 - re-open the directory some time later
189 - seek to the remembered offset
190
191 there may be little correlation between the old and new locations in
192 the list of filenames, particularly if anything has changed in the
193 directory.
194
195 Readdir on directories that are not merged is simply handled by the
196 underlying directory (upper or lower).
197
198 renaming directories
199 --------------------
200
201 When renaming a directory that is on the lower layer or merged (i.e. the
202 directory was not created on the upper layer to start with) overlayfs can
203 handle it in two different ways:
204
205 1. return EXDEV error: this error is returned by rename(2) when trying to
206 move a file or directory across filesystem boundaries. Hence
207 applications are usually prepared to handle this error (mv(1) for example
208 recursively copies the directory tree). This is the default behavior.
209
210 2. If the "redirect_dir" feature is enabled, then the directory will be
211 copied up (but not the contents). Then the "trusted.overlay.redirect"
212 extended attribute is set to the path of the original location from the
213 root of the overlay. Finally the directory is moved to the new
214 location.
215
216 There are several ways to tune the "redirect_dir" feature.
217
218 Kernel config options:
219
220 - OVERLAY_FS_REDIRECT_DIR:
221 If this is enabled, then redirect_dir is turned on by default.
222 - OVERLAY_FS_REDIRECT_ALWAYS_FOLLOW:
223 If this is enabled, then redirects are always followed by default. Enabling
224 this results in a less secure configuration. Enable this option only when
225 worried about backward compatibility with kernels that have the redirect_dir
226 feature and follow redirects even if turned off.
227
228 Module options (can also be changed through /sys/module/overlay/parameters/):
229
230 - "redirect_dir=BOOL":
231 See OVERLAY_FS_REDIRECT_DIR kernel config option above.
232 - "redirect_always_follow=BOOL":
233 See OVERLAY_FS_REDIRECT_ALWAYS_FOLLOW kernel config option above.
234 - "redirect_max=NUM":
235 The maximum number of bytes in an absolute redirect (default is 256).
236
237 Mount options:
238
239 - "redirect_dir=on":
240 Redirects are enabled.
241 - "redirect_dir=follow":
242 Redirects are not created, but followed.
243 - "redirect_dir=nofollow":
244 Redirects are not created and not followed.
245 - "redirect_dir=off":
246 If "redirect_always_follow" is enabled in the kernel/module config,
247 this "off" translates to "follow", otherwise it translates to "nofollow".
248
249 When the NFS export feature is enabled, every copied up directory is
250 indexed by the file handle of the lower inode and a file handle of the
251 upper directory is stored in a "trusted.overlay.upper" extended attribute
252 on the index entry. On lookup of a merged directory, if the upper
253 directory does not match the file handle stores in the index, that is an
254 indication that multiple upper directories may be redirected to the same
255 lower directory. In that case, lookup returns an error and warns about
256 a possible inconsistency.
257
258 Because lower layer redirects cannot be verified with the index, enabling
259 NFS export support on an overlay filesystem with no upper layer requires
260 turning off redirect follow (e.g. "redirect_dir=nofollow").
261
262
263 Non-directories
264 ---------------
265
266 Objects that are not directories (files, symlinks, device-special
267 files etc.) are presented either from the upper or lower filesystem as
268 appropriate. When a file in the lower filesystem is accessed in a way
269 that requires write-access, such as opening for write access, changing
270 some metadata etc., the file is first copied from the lower filesystem
271 to the upper filesystem (copy_up). Note that creating a hard-link
272 also requires copy_up, though of course creation of a symlink does
273 not.
274
275 The copy_up may turn out to be unnecessary, for example if the file is
276 opened for read-write but the data is not modified.
277
278 The copy_up process first makes sure that the containing directory
279 exists in the upper filesystem - creating it and any parents as
280 necessary. It then creates the object with the same metadata (owner,
281 mode, mtime, symlink-target etc.) and then if the object is a file, the
282 data is copied from the lower to the upper filesystem. Finally any
283 extended attributes are copied up.
284
285 Once the copy_up is complete, the overlay filesystem simply
286 provides direct access to the newly created file in the upper
287 filesystem - future operations on the file are barely noticed by the
288 overlay filesystem (though an operation on the name of the file such as
289 rename or unlink will of course be noticed and handled).
290
291
292 Permission model
293 ----------------
294
295 An overlay filesystem stashes credentials that will be used when
296 accessing lower or upper filesystems.
297
298 In the old mount api the credentials of the task calling mount(2) are
299 stashed. In the new mount api the credentials of the task creating the
300 superblock through FSCONFIG_CMD_CREATE command of fsconfig(2) are
301 stashed.
302
303 Starting with kernel v6.15 it is possible to use the "override_creds"
304 mount option which will cause the credentials of the calling task to be
305 recorded. Note that "override_creds" is only meaningful when used with
306 the new mount api as the old mount api combines setting options and
307 superblock creation in a single mount(2) syscall.
308
309 Permission checking in the overlay filesystem follows these principles:
310
311 1) permission check SHOULD return the same result before and after copy up
312
313 2) task creating the overlay mount MUST NOT gain additional privileges
314
315 3) task[*] MAY gain additional privileges through the overlay,
316 compared to direct access on underlying lower or upper filesystems
317
318 This is achieved by performing two permission checks on each access:
319
320 a) check if current task is allowed access based on local DAC (owner,
321 group, mode and posix acl), as well as MAC checks
322
323 b) check if stashed credentials would be allowed real operation on lower or
324 upper layer based on underlying filesystem permissions, again including
325 MAC checks
326
327 Check (a) ensures consistency (1) since owner, group, mode and posix acls
328 are copied up. On the other hand it can result in server enforced
329 permissions (used by NFS, for example) being ignored (3).
330
331 Check (b) ensures that no task gains permissions to underlying layers that
332 the stashed credentials do not have (2). This also means that it is possible
333 to create setups where the consistency rule (1) does not hold; normally,
334 however, the stashed credentials will have sufficient privileges to
335 perform all operations.
336
337 Another way to demonstrate this model is drawing parallels between::
338
339 mount -t overlay overlay -olowerdir=/lower,upperdir=/upper,... /merged
340
341 and::
342
343 cp -a /lower /upper
344 mount --bind /upper /merged
345
346 The resulting access permissions should be the same. The difference is in
347 the time of copy (on-demand vs. up-front).
348
349
350 Multiple lower layers
351 ---------------------
352
353 Multiple lower layers can now be given using the colon (":") as a
354 separator character between the directory names. For example::
355
356 mount -t overlay overlay -olowerdir=/lower1:/lower2:/lower3 /merged
357
358 As the example shows, "upperdir=" and "workdir=" may be omitted. In
359 that case the overlay will be read-only.
360
361 The specified lower directories will be stacked beginning from the
362 rightmost one and going left. In the above example lower1 will be the
363 top, lower2 the middle and lower3 the bottom layer.
364
365 Note: directory names containing colons can be provided as lower layer by
366 escaping the colons with a single backslash. For example::
367
368 mount -t overlay overlay -olowerdir=/a\:lower\:\:dir /merged
369
370 Since kernel version v6.8, directory names containing colons can also
371 be configured as lower layer using the "lowerdir+" mount options and the
372 fsconfig syscall from new mount api. For example::
373
374 fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/a:lower::dir", 0);
375
376 In the latter case, colons in lower layer directory names will be escaped
377 as an octal characters (\072) when displayed in /proc/self/mountinfo.
378
379 Metadata only copy up
380 ---------------------
381
382 When the "metacopy" feature is enabled, overlayfs will only copy
383 up metadata (as opposed to whole file), when a metadata specific operation
384 like chown/chmod is performed. An upper file in this state is marked with
385 "trusted.overlayfs.metacopy" xattr which indicates that the upper file
386 contains no data. The data will be copied up later when file is opened for
387 WRITE operation. After the lower file's data is copied up,
388 the "trusted.overlayfs.metacopy" xattr is removed from the upper file.
389
390 In other words, this is delayed data copy up operation and data is copied
391 up when there is a need to actually modify data.
392
393 There are multiple ways to enable/disable this feature. A config option
394 CONFIG_OVERLAY_FS_METACOPY can be set/unset to enable/disable this feature
395 by default. Or one can enable/disable it at module load time with module
396 parameter metacopy=on/off. Lastly, there is also a per mount option
397 metacopy=on/off to enable/disable this feature per mount.
398
399 Do not use metacopy=on with untrusted upper/lower directories. Otherwise
400 it is possible that an attacker can create a handcrafted file with
401 appropriate REDIRECT and METACOPY xattrs, and gain access to file on lower
402 pointed by REDIRECT. This should not be possible on local system as setting
403 "trusted." xattrs will require CAP_SYS_ADMIN. But it should be possible
404 for untrusted layers like from a pen drive.
405
406 Note: redirect_dir={off|nofollow|follow[*]} and nfs_export=on mount options
407 conflict with metacopy=on, and will result in an error.
408
409 [*] redirect_dir=follow only conflicts with metacopy=on if upperdir=... is
410 given.
411
412
413 Data-only lower layers
414 ----------------------
415
416 With "metacopy" feature enabled, an overlayfs regular file may be a composition
417 of information from up to three different layers:
418
419 1) metadata from a file in the upper layer
420
421 2) st_ino and st_dev object identifier from a file in a lower layer
422
423 3) data from a file in another lower layer (further below)
424
425 The "lower data" file can be on any lower layer, except from the top most
426 lower layer.
427
428 Below the topmost lower layer, any number of lowermost layers may be defined
429 as "data-only" lower layers, using double colon ("::") separators.
430 A normal lower layer is not allowed to be below a data-only layer, so single
431 colon separators are not allowed to the right of double colon ("::") separators.
432
433
434 For example::
435
436 mount -t overlay overlay -olowerdir=/l1:/l2:/l3::/do1::/do2 /merged
437
438 The paths of files in the "data-only" lower layers are not visible in the
439 merged overlayfs directories and the metadata and st_ino/st_dev of files
440 in the "data-only" lower layers are not visible in overlayfs inodes.
441
442 Only the data of the files in the "data-only" lower layers may be visible
443 when a "metacopy" file in one of the lower layers above it, has a "redirect"
444 to the absolute path of the "lower data" file in the "data-only" lower layer.
445
446 Instead of explicitly enabling "metacopy=on" it is sufficient to specify at
447 least one data-only layer to enable redirection of data to a data-only layer.
448 In this case other forms of metacopy are rejected. Note: this way, data-only
449 layers may be used together with "userxattr", in which case careful attention
450 must be given to privileges needed to change the "user.overlay.redirect" xattr
451 to prevent misuse.
452
453 Since kernel version v6.8, "data-only" lower layers can also be added using
454 the "datadir+" mount options and the fsconfig syscall from new mount api.
455 For example::
456
457 fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/l1", 0);
458 fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/l2", 0);
459 fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/l3", 0);
460 fsconfig(fs_fd, FSCONFIG_SET_STRING, "datadir+", "/do1", 0);
461 fsconfig(fs_fd, FSCONFIG_SET_STRING, "datadir+", "/do2", 0);
462
463
464 Specifying layers via file descriptors
465 --------------------------------------
466
467 Since kernel v6.13, overlayfs supports specifying layers via file descriptors in
468 addition to specifying them as paths. This feature is available for the
469 "datadir+", "lowerdir+", "upperdir", and "workdir+" mount options with the
470 fsconfig syscall from the new mount api::
471
472 fsconfig(fs_fd, FSCONFIG_SET_FD, "lowerdir+", NULL, fd_lower1);
473 fsconfig(fs_fd, FSCONFIG_SET_FD, "lowerdir+", NULL, fd_lower2);
474 fsconfig(fs_fd, FSCONFIG_SET_FD, "lowerdir+", NULL, fd_lower3);
475 fsconfig(fs_fd, FSCONFIG_SET_FD, "datadir+", NULL, fd_data1);
476 fsconfig(fs_fd, FSCONFIG_SET_FD, "datadir+", NULL, fd_data2);
477 fsconfig(fs_fd, FSCONFIG_SET_FD, "workdir", NULL, fd_work);
478 fsconfig(fs_fd, FSCONFIG_SET_FD, "upperdir", NULL, fd_upper);
479
480
481 fs-verity support
482 -----------------
483
484 During metadata copy up of a lower file, if the source file has
485 fs-verity enabled and overlay verity support is enabled, then the
486 digest of the lower file is added to the "trusted.overlay.metacopy"
487 xattr. This is then used to verify the content of the lower file
488 each the time the metacopy file is opened.
489
490 When a layer containing verity xattrs is used, it means that any such
491 metacopy file in the upper layer is guaranteed to match the content
492 that was in the lower at the time of the copy-up. If at any time
493 (during a mount, after a remount, etc) such a file in the lower is
494 replaced or modified in any way, access to the corresponding file in
495 overlayfs will result in EIO errors (either on open, due to overlayfs
496 digest check, or from a later read due to fs-verity) and a detailed
497 error is printed to the kernel logs. For more details of how fs-verity
498 file access works, see :ref:`Documentation/filesystems/fsverity.rst
499 <accessing_verity_files>`.
500
501 Verity can be used as a general robustness check to detect accidental
502 changes in the overlayfs directories in use. But, with additional care
503 it can also give more powerful guarantees. For example, if the upper
504 layer is fully trusted (by using dm-verity or something similar), then
505 an untrusted lower layer can be used to supply validated file content
506 for all metacopy files. If additionally the untrusted lower
507 directories are specified as "Data-only", then they can only supply
508 such file content, and the entire mount can be trusted to match the
509 upper layer.
510
511 This feature is controlled by the "verity" mount option, which
512 supports these values:
513
514 - "off":
515 The metacopy digest is never generated or used. This is the
516 default if verity option is not specified.
517 - "on":
518 Whenever a metacopy file specifies an expected digest, the
519 corresponding data file must match the specified digest. When
520 generating a metacopy file the verity digest will be set in it
521 based on the source file (if it has one).
522 - "require":
523 Same as "on", but additionally all metacopy files must specify a
524 digest (or EIO is returned on open). This means metadata copy up
525 will only be used if the data file has fs-verity enabled,
526 otherwise a full copy-up is used.
527
528 Sharing and copying layers
529 --------------------------
530
531 Lower layers may be shared among several overlay mounts and that is indeed
532 a very common practice. An overlay mount may use the same lower layer
533 path as another overlay mount and it may use a lower layer path that is
534 beneath or above the path of another overlay lower layer path.
535
536 Using an upper layer path and/or a workdir path that are already used by
537 another overlay mount is not allowed and may fail with EBUSY. Using
538 partially overlapping paths is not allowed and may fail with EBUSY.
539 If files are accessed from two overlayfs mounts which share or overlap the
540 upper layer and/or workdir path, the behavior of the overlay is undefined,
541 though it will not result in a crash or deadlock.
542
543 Mounting an overlay using an upper layer path, where the upper layer path
544 was previously used by another mounted overlay in combination with a
545 different lower layer path, is allowed, unless the "index" or "metacopy"
546 features are enabled.
547
548 With the "index" feature, on the first time mount, an NFS file
549 handle of the lower layer root directory, along with the UUID of the lower
550 filesystem, are encoded and stored in the "trusted.overlay.origin" extended
551 attribute on the upper layer root directory. On subsequent mount attempts,
552 the lower root directory file handle and lower filesystem UUID are compared
553 to the stored origin in upper root directory. On failure to verify the
554 lower root origin, mount will fail with ESTALE. An overlayfs mount with
555 "index" enabled will fail with EOPNOTSUPP if the lower filesystem
556 does not support NFS export, lower filesystem does not have a valid UUID or
557 if the upper filesystem does not support extended attributes.
558
559 For the "metacopy" feature, there is no verification mechanism at
560 mount time. So if same upper is mounted with different set of lower, mount
561 probably will succeed but expect the unexpected later on. So don't do it.
562
563 It is quite a common practice to copy overlay layers to a different
564 directory tree on the same or different underlying filesystem, and even
565 to a different machine. With the "index" feature, trying to mount
566 the copied layers will fail the verification of the lower root file handle.
567
568 Nesting overlayfs mounts
569 ------------------------
570
571 It is possible to use a lower directory that is stored on an overlayfs
572 mount. For regular files this does not need any special care. However, files
573 that have overlayfs attributes, such as whiteouts or "overlay.*" xattrs, will
574 be interpreted by the underlying overlayfs mount and stripped out. In order to
575 allow the second overlayfs mount to see the attributes they must be escaped.
576
577 Overlayfs specific xattrs are escaped by using a special prefix of
578 "overlay.overlay.". So, a file with a "trusted.overlay.overlay.metacopy" xattr
579 in the lower dir will be exposed as a regular file with a
580 "trusted.overlay.metacopy" xattr in the overlayfs mount. This can be nested by
581 repeating the prefix multiple time, as each instance only removes one prefix.
582
583 A lower dir with a regular whiteout will always be handled by the overlayfs
584 mount, so to support storing an effective whiteout file in an overlayfs mount an
585 alternative form of whiteout is supported. This form is a regular, zero-size
586 file with the "overlay.whiteout" xattr set, inside a directory with the
587 "overlay.opaque" xattr set to "x" (see `whiteouts and opaque directories`_).
588 These alternative whiteouts are never created by overlayfs, but can be used by
589 userspace tools (like containers) that generate lower layers.
590 These alternative whiteouts can be escaped using the standard xattr escape
591 mechanism in order to properly nest to any depth.
592
593 Non-standard behavior
594 ---------------------
595
596 Current version of overlayfs can act as a mostly POSIX compliant
597 filesystem.
598
599 This is the list of cases that overlayfs doesn't currently handle:
600
601 a) POSIX mandates updating st_atime for reads. This is currently not
602 done in the case when the file resides on a lower layer.
603
604 b) If a file residing on a lower layer is opened for read-only and then
605 memory mapped with MAP_SHARED, then subsequent changes to the file are not
606 reflected in the memory mapping.
607
608 c) If a file residing on a lower layer is being executed, then opening that
609 file for write or truncating the file will not be denied with ETXTBSY.
610
611 The following options allow overlayfs to act more like a standards
612 compliant filesystem:
613
614 redirect_dir
615 ````````````
616
617 Enabled with the mount option or module option: "redirect_dir=on" or with
618 the kernel config option CONFIG_OVERLAY_FS_REDIRECT_DIR=y.
619
620 If this feature is disabled, then rename(2) on a lower or merged directory
621 will fail with EXDEV ("Invalid cross-device link").
622
623 index
624 `````
625
626 Enabled with the mount option or module option "index=on" or with the
627 kernel config option CONFIG_OVERLAY_FS_INDEX=y.
628
629 If this feature is disabled and a file with multiple hard links is copied
630 up, then this will "break" the link. Changes will not be propagated to
631 other names referring to the same inode.
632
633 xino
634 ````
635
636 Enabled with the mount option "xino=auto" or "xino=on", with the module
637 option "xino_auto=on" or with the kernel config option
638 CONFIG_OVERLAY_FS_XINO_AUTO=y. Also implicitly enabled by using the same
639 underlying filesystem for all layers making up the overlay.
640
641 If this feature is disabled or the underlying filesystem doesn't have
642 enough free bits in the inode number, then overlayfs will not be able to
643 guarantee that the values of st_ino and st_dev returned by stat(2) and the
644 value of d_ino returned by readdir(3) will act like on a normal filesystem.
645 E.g. the value of st_dev may be different for two objects in the same
646 overlay filesystem and the value of st_ino for filesystem objects may not be
647 persistent and could change even while the overlay filesystem is mounted, as
648 summarized in the `Inode properties`_ table above.
649
650
651 Changes to underlying filesystems
652 ---------------------------------
653
654 Changes to the underlying filesystems while part of a mounted overlay
655 filesystem are not allowed. If the underlying filesystem is changed,
656 the behavior of the overlay is undefined, though it will not result in
657 a crash or deadlock.
658
659 Offline changes, when the overlay is not mounted, are allowed to the
660 upper tree. Offline changes to the lower tree are only allowed if the
661 "metacopy", "index", "xino" and "redirect_dir" features
662 have not been used. If the lower tree is modified and any of these
663 features has been used, the behavior of the overlay is undefined,
664 though it will not result in a crash or deadlock.
665
666 When the overlay NFS export feature is enabled, overlay filesystems
667 behavior on offline changes of the underlying lower layer is different
668 than the behavior when NFS export is disabled.
669
670 On every copy_up, an NFS file handle of the lower inode, along with the
671 UUID of the lower filesystem, are encoded and stored in an extended
672 attribute "trusted.overlay.origin" on the upper inode.
673
674 When the NFS export feature is enabled, a lookup of a merged directory,
675 that found a lower directory at the lookup path or at the path pointed
676 to by the "trusted.overlay.redirect" extended attribute, will verify
677 that the found lower directory file handle and lower filesystem UUID
678 match the origin file handle that was stored at copy_up time. If a
679 found lower directory does not match the stored origin, that directory
680 will not be merged with the upper directory.
681
682
683
684 NFS export
685 ----------
686
687 When the underlying filesystems supports NFS export and the "nfs_export"
688 feature is enabled, an overlay filesystem may be exported to NFS.
689
690 With the "nfs_export" feature, on copy_up of any lower object, an index
691 entry is created under the index directory. The index entry name is the
692 hexadecimal representation of the copy up origin file handle. For a
693 non-directory object, the index entry is a hard link to the upper inode.
694 For a directory object, the index entry has an extended attribute
695 "trusted.overlay.upper" with an encoded file handle of the upper
696 directory inode.
697
698 When encoding a file handle from an overlay filesystem object, the
699 following rules apply:
700
701 1. For a non-upper object, encode a lower file handle from lower inode
702 2. For an indexed object, encode a lower file handle from copy_up origin
703 3. For a pure-upper object and for an existing non-indexed upper object,
704 encode an upper file handle from upper inode
705
706 The encoded overlay file handle includes:
707
708 - Header including path type information (e.g. lower/upper)
709 - UUID of the underlying filesystem
710 - Underlying filesystem encoding of underlying inode
711
712 This encoding format is identical to the encoding format file handles that
713 are stored in extended attribute "trusted.overlay.origin".
714
715 When decoding an overlay file handle, the following steps are followed:
716
717 1. Find underlying layer by UUID and path type information.
718 2. Decode the underlying filesystem file handle to underlying dentry.
719 3. For a lower file handle, lookup the handle in index directory by name.
720 4. If a whiteout is found in index, return ESTALE. This represents an
721 overlay object that was deleted after its file handle was encoded.
722 5. For a non-directory, instantiate a disconnected overlay dentry from the
723 decoded underlying dentry, the path type and index inode, if found.
724 6. For a directory, use the connected underlying decoded dentry, path type
725 and index, to lookup a connected overlay dentry.
726
727 Decoding a non-directory file handle may return a disconnected dentry.
728 copy_up of that disconnected dentry will create an upper index entry with
729 no upper alias.
730
731 When overlay filesystem has multiple lower layers, a middle layer
732 directory may have a "redirect" to lower directory. Because middle layer
733 "redirects" are not indexed, a lower file handle that was encoded from the
734 "redirect" origin directory, cannot be used to find the middle or upper
735 layer directory. Similarly, a lower file handle that was encoded from a
736 descendant of the "redirect" origin directory, cannot be used to
737 reconstruct a connected overlay path. To mitigate the cases of
738 directories that cannot be decoded from a lower file handle, these
739 directories are copied up on encode and encoded as an upper file handle.
740 On an overlay filesystem with no upper layer this mitigation cannot be
741 used NFS export in this setup requires turning off redirect follow (e.g.
742 "redirect_dir=nofollow").
743
744 The overlay filesystem does not support non-directory connectable file
745 handles, so exporting with the 'subtree_check' exportfs configuration will
746 cause failures to lookup files over NFS.
747
748 When the NFS export feature is enabled, all directory index entries are
749 verified on mount time to check that upper file handles are not stale.
750 This verification may cause significant overhead in some cases.
751
752 Note: the mount options index=off,nfs_export=on are conflicting for a
753 read-write mount and will result in an error.
754
755 Note: the mount option uuid=off can be used to replace UUID of the underlying
756 filesystem in file handles with null, and effectively disable UUID checks. This
757 can be useful in case the underlying disk is copied and the UUID of this copy
758 is changed. This is only applicable if all lower/upper/work directories are on
759 the same filesystem, otherwise it will fallback to normal behaviour.
760
761
762 UUID and fsid
763 -------------
764
765 The UUID of overlayfs instance itself and the fsid reported by statfs(2) are
766 controlled by the "uuid" mount option, which supports these values:
767
768 - "null":
769 UUID of overlayfs is null. fsid is taken from upper most filesystem.
770 - "off":
771 UUID of overlayfs is null. fsid is taken from upper most filesystem.
772 UUID of underlying layers is ignored.
773 - "on":
774 UUID of overlayfs is generated and used to report a unique fsid.
775 UUID is stored in xattr "trusted.overlay.uuid", making overlayfs fsid
776 unique and persistent. This option requires an overlayfs with upper
777 filesystem that supports xattrs.
778 - "auto": (default)
779 UUID is taken from xattr "trusted.overlay.uuid" if it exists.
780 Upgrade to "uuid=on" on first time mount of new overlay filesystem that
781 meets the prerequisites.
782 Downgrade to "uuid=null" for existing overlay filesystems that were never
783 mounted with "uuid=on".
784
785
786 Durability and copy up
787 ----------------------
788
789 The fsync(2) system call ensures that the data and metadata of a file
790 are safely written to the backing storage, which is expected to
791 guarantee the existence of the information post system crash.
792
793 Without an fsync(2) call, there is no guarantee that the observed
794 data after a system crash will be either the old or the new data, but
795 in practice, the observed data after crash is often the old or new data
796 or a mix of both.
797
798 When an overlayfs file is modified for the first time, copy up will
799 create a copy of the lower file and its parent directories in the upper
800 layer. Since the Linux filesystem API does not enforce any particular
801 ordering on storing changes without explicit fsync(2) calls, in case
802 of a system crash, the upper file could end up with no data at all
803 (i.e. zeros), which would be an unusual outcome. To avoid this
804 experience, overlayfs calls fsync(2) on the upper file before completing
805 data copy up with rename(2) or link(2) to make the copy up "atomic".
806
807 By default, overlayfs does not explicitly call fsync(2) on copied up
808 directories or on metadata-only copy up, so it provides no guarantee to
809 persist the user's modification unless the user calls fsync(2).
810 The fsync during copy up only guarantees that if a copy up is observed
811 after a crash, the observed data is not zeroes or intermediate values
812 from the copy up staging area.
813
814 On traditional local filesystems with a single journal (e.g. ext4, xfs),
815 fsync on a file also persists the parent directory changes, because they
816 are usually modified in the same transaction, so metadata durability during
817 data copy up effectively comes for free. Overlayfs further limits risk by
818 disallowing network filesystems as upper layer.
819
820 Overlayfs can be tuned to prefer performance or durability when storing
821 to the underlying upper layer. This is controlled by the "fsync" mount
822 option, which supports these values:
823
824 - "auto": (default)
825 Call fsync(2) on upper file before completion of data copy up.
826 No explicit fsync(2) on directory or metadata-only copy up.
827 - "strict":
828 Call fsync(2) on upper file and directories before completion of any
829 copy up.
830 - "volatile": [*]
831 Prefer performance over durability (see `Volatile mount`_)
832
833 [*] The mount option "volatile" is an alias to "fsync=volatile".
834
835
836 Volatile mount
837 --------------
838
839 This is enabled with the "volatile" mount option. Volatile mounts are not
840 guaranteed to survive a crash. It is strongly recommended that volatile
841 mounts are only used if data written to the overlay can be recreated
842 without significant effort.
843
844 The advantage of mounting with the "volatile" option is that all forms of
845 sync calls to the upper filesystem are omitted.
846
847 In order to avoid giving a false sense of safety, the syncfs (and fsync)
848 semantics of volatile mounts are slightly different than that of the rest of
849 VFS. If any writeback error occurs on the upperdir's filesystem after a
850 volatile mount takes place, all sync functions will return an error. Once this
851 condition is reached, the filesystem will not recover, and every subsequent sync
852 call will return an error, even if the upperdir has not experienced a new error
853 since the last sync call.
854
855 When overlay is mounted with "volatile" option, the directory
856 "$workdir/work/incompat/volatile" is created. During next mount, overlay
857 checks for this directory and refuses to mount if present. This is a strong
858 indicator that the user should discard upper and work directories and create
859 fresh ones. In very limited cases where the user knows that the system has
860 not crashed and contents of upperdir are intact, the "volatile" directory
861 can be removed.
862
863
864 User xattr
865 ----------
866
867 The "-o userxattr" mount option forces overlayfs to use the
868 "user.overlay." xattr namespace instead of "trusted.overlay.". This is
869 useful for unprivileged mounting of overlayfs.
870
871
872 Testsuite
873 ---------
874
875 There's a testsuite originally developed by David Howells and currently
876 maintained by Amir Goldstein at:
877
878 https://github.com/amir73il/unionmount-testsuite.git
879
880 Run as root::
881
882 # cd unionmount-testsuite
883 # ./run --ov --verify
884

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Overlay 객체와 inode 식별자

1-82

Neil Brown이 작성한 이 문서는 Linux에서 overlay filesystem, 즉 union filesystem 기능을 제공하는 접근 방식을 설명합니다. OverlayFS는 한 파일시스템 위에 다른 파일시스템을 겹쳐서 두 계층의 결과를 하나의 파일시스템처럼 보여 줍니다.

OverlayFS 객체는 항상 overlay 파일시스템 소속처럼 보이지 않는다는 점에서 hybrid입니다. union을 통해 접근한 객체가 원본 파일시스템의 대응 객체와 구별되지 않는 경우가 많으며 `stat(2)`의 `st_dev`에서 가장 분명히 드러납니다. 디렉터리는 overlay의 `st_dev`를 보고하지만 비디렉터리 객체는 실제 객체를 제공하는 lower 또는 upper의 `st_dev`를 보고할 수 있습니다.

`st_ino`는 `st_dev`와 결합할 때만 고유하며 비디렉터리 객체의 생존 기간 중 두 값이 바뀔 수도 있습니다. 많은 프로그램은 이 값을 무시하므로 영향을 받지 않습니다. 모든 계층이 같은 기반 파일시스템에 있으면 모든 객체가 overlay의 `st_dev`와 기반 파일시스템의 `st_ino`를 보고하여 scanner 호환성이 높아지고 원본 객체와 overlay 객체도 구별됩니다.

64비트 시스템에서는 계층이 서로 다른 기반 파일시스템에 있어도 `xino`가 고유 객체 식별자를 구성할 수 있습니다. 실제 `st_ino`와 기반 `fsid`를 결합하고 inode 번호의 상위 비트에 fsid를 넣습니다. 기반 inode가 상위 xino 비트까지 overflow하면 그 inode에 한해 non-xino 동작으로 fallback합니다.

`-o xino=on`은 xino를 켭니다. 모든 기반 파일시스템이 NFS file handle을 지원하면 overlay 객체의 `st_ino`가 파일시스템 수명 동안 고유하고 persistent합니다. `-o xino=auto`는 이 persistent `st_ino` 조건이 충족될 때만 xino를 활성화합니다.

xino 객체 식별자
기반 객체의 실제 `st_ino`기반 파일시스템의 `fsid`inode 상위 비트에 fsid 합성고유 overlay inode 식별자상위 비트 overflow 시 non-xino fallback

실제 inode 번호와 기반 fsid를 결합하고 overflow 시 해당 inode만 fallback합니다.

OverlayFS inode 속성
구성persistent st_ino dir/!diruniform st_dev dir/!dirst_ino=d_ino dir/!dird_ino=i_ino dir/!dir
모든 계층이 같은 fsY / YY / YY / YY / Y
서로 다른 fs, `xino=off`N / NY / NN / YN / Y
`xino=on|auto`Y / YY / YY / YY / Y
`xino=on|auto`, ino overflowN / NY / NN / YN / Y

원문의 ASCII 표를 같은 열과 디렉터리·비디렉터리 구분으로 재구성했습니다.

NFSv3 `readdirplus`의 nfsd는 `d_ino == i_ino`를 검증합니다. `i_ino`는 `/proc/locks`와 inotify file descriptor의 `/proc/self/fdinfo/<fd>` 같은 `/proc` 파일에도 노출됩니다.

.. SPDX-License-Identifier: GPL-2.0

Written by: Neil Brown
Please see MAINTAINERS file for where to send questions.

Overlay Filesystem
==================

This document describes a prototype for a new approach to providing
overlay-filesystem functionality in Linux (sometimes referred to as
union-filesystems).  An overlay-filesystem tries to present a
filesystem which is the result of overlaying one filesystem on top
of the other.


Overlay objects
---------------

The overlay filesystem approach is 'hybrid', because the objects that
appear in the filesystem do not always appear to belong to that filesystem.
In many cases, an object accessed in the union will be indistinguishable
from accessing the corresponding object from the original filesystem.
This is most obvious from the 'st_dev' field returned by stat(2).

While directories will report an st_dev from the overlay-filesystem,
non-directory objects may report an st_dev from the lower filesystem or
upper filesystem that is providing the object.  Similarly st_ino will
only be unique when combined with st_dev, and both of these can change
over the lifetime of a non-directory object.  Many applications and
tools ignore these values and will not be affected.

In the special case of all overlay layers on the same underlying
filesystem, all objects will report an st_dev from the overlay
filesystem and st_ino from the underlying filesystem.  This will
make the overlay mount more compliant with filesystem scanners and
overlay objects will be distinguishable from the corresponding
objects in the original filesystem.

On 64bit systems, even if all overlay layers are not on the same
underlying filesystem, the same compliant behavior could be achieved
with the "xino" feature.  The "xino" feature composes a unique object
identifier from the real object st_ino and an underlying fsid number.
The "xino" feature uses the high inode number bits for fsid, because the
underlying filesystems rarely use the high inode number bits.  In case
the underlying inode number does overflow into the high xino bits, overlay
filesystem will fall back to the non xino behavior for that inode.

The "xino" feature can be enabled with the "-o xino=on" overlay mount option.
If all underlying filesystems support NFS file handles, the value of st_ino
for overlay filesystem objects is not only unique, but also persistent over
the lifetime of the filesystem.  The "-o xino=auto" overlay mount option
enables the "xino" feature only if the persistent st_ino requirement is met.

The following table summarizes what can be expected in different overlay
configurations.

Inode properties
````````````````

+--------------+------------+------------+-----------------+----------------+
|Configuration | Persistent | Uniform    | st_ino == d_ino | d_ino == i_ino |
|              | st_ino     | st_dev     |                 | [*]            |
+==============+=====+======+=====+======+========+========+========+=======+
|              | dir | !dir | dir | !dir |  dir   |  !dir  |  dir   | !dir  |
+--------------+-----+------+-----+------+--------+--------+--------+-------+
| All layers   |  Y  |  Y   |  Y  |  Y   |  Y     |   Y    |  Y     |  Y    |
| on same fs   |     |      |     |      |        |        |        |       |
+--------------+-----+------+-----+------+--------+--------+--------+-------+
| Layers not   |  N  |  N   |  Y  |  N   |  N     |   Y    |  N     |  Y    |
| on same fs,  |     |      |     |      |        |        |        |       |
| xino=off     |     |      |     |      |        |        |        |       |
+--------------+-----+------+-----+------+--------+--------+--------+-------+
| xino=on/auto |  Y  |  Y   |  Y  |  Y   |  Y     |   Y    |  Y     |  Y    |
+--------------+-----+------+-----+------+--------+--------+--------+-------+
| xino=on/auto,|  N  |  N   |  Y  |  N   |  N     |   Y    |  N     |  Y    |
| ino overflow |     |      |     |      |        |        |        |       |
+--------------+-----+------+-----+------+--------+--------+--------+-------+

[*] nfsd v3 readdirplus verifies d_ino == i_ino. i_ino is exposed via several
/proc files, such as /proc/locks and /proc/self/fdinfo/<fd> of an inotify
file descriptor.

Upper·lower 계층과 병합 디렉터리

83-139

OverlayFS는 `upper`와 `lower` 두 directory tree를 결합합니다. 같은 이름이 양쪽에 있으면 upper 객체가 보이고 lower 객체는 숨겨집니다. 단, 둘 다 디렉터리이면 upper와 lower 디렉터리를 병합합니다. 두 tree가 같은 파일시스템에 있을 수 있고 각 tree가 파일시스템 root일 필요도 없으므로 엄밀히는 upper·lower filesystem보다 directory tree라는 표현이 정확합니다.

여러 Linux 파일시스템을 lower로 사용할 수 있고 lower는 쓰기 가능할 필요가 없으며 다른 overlayfs일 수도 있습니다. 쓰기 가능한 upper는 `trusted.*` 및/또는 `user.*` extended attribute 생성과 `readdir`의 유효한 `d_type`을 지원해야 하므로 NFS는 upper로 적합하지 않습니다. 두 읽기 전용 파일시스템을 합친 읽기 전용 overlay는 어떤 파일시스템 형식도 사용할 수 있습니다.

주어진 이름이 upper와 lower 모두에 있고 어느 한쪽이라도 비디렉터리이면 lower 객체는 숨고 이름은 upper 객체만 가리킵니다. 둘 다 디렉터리일 때만 merged directory를 구성합니다.

mount -t overlay overlay -olowerdir=/lower,upperdir=/upper,\
workdir=/work /merged

`workdir`은 `upperdir`과 같은 파일시스템에 있는 빈 디렉터리여야 합니다. merged directory에서 lookup하면 두 실제 디렉터리를 모두 조회하여 결과를 overlay dentry에 cache합니다. 둘 다 디렉터리이면 둘을 저장해 병합하고, 그 외에는 upper가 있으면 upper 하나만, 없으면 lower 하나만 저장합니다.

병합되는 것은 디렉터리의 이름 목록뿐입니다. metadata와 extended attributes 같은 나머지 내용은 upper 디렉터리의 값만 보고하며 lower 디렉터리의 해당 속성은 숨깁니다.

OverlayFS 계층 조회
`lowerdir=/lower``upperdir=/upper` + 같은 fs의 빈 `workdir`양쪽에서 이름 lookup둘 다 directory이면 merged directory아니면 upper 우선, 없을 때 lowermetadata·xattr은 upper만 노출

upper가 우선하고 디렉터리끼리만 이름 목록을 병합합니다.

같은 이름의 객체 선택
UpperLowerOverlay 결과
없음어떤 객체lower 객체
어떤 객체없음upper 객체
directorydirectory이름 목록을 병합한 directory
한쪽 이상 non-directory같은 이름 존재upper만 보이고 lower는 숨김

upper와 lower 객체 형식에 따른 결과입니다.

Upper and Lower
---------------

An overlay filesystem combines two filesystems - an 'upper' filesystem
and a 'lower' filesystem.  When a name exists in both filesystems, the
object in the 'upper' filesystem is visible while the object in the
'lower' filesystem is either hidden or, in the case of directories,
merged with the 'upper' object.

It would be more correct to refer to an upper and lower 'directory
tree' rather than 'filesystem' as it is quite possible for both
directory trees to be in the same filesystem and there is no
requirement that the root of a filesystem be given for either upper or
lower.

A wide range of filesystems supported by Linux can be the lower filesystem,
but not all filesystems that are mountable by Linux have the features
needed for OverlayFS to work.  The lower filesystem does not need to be
writable.  The lower filesystem can even be another overlayfs.  The upper
filesystem will normally be writable and if it is it must support the
creation of trusted.* and/or user.* extended attributes, and must provide
valid d_type in readdir responses, so NFS is not suitable.

A read-only overlay of two read-only filesystems may use any
filesystem type.

Directories
-----------

Overlaying mainly involves directories.  If a given name appears in both
upper and lower filesystems and refers to a non-directory in either,
then the lower object is hidden - the name refers only to the upper
object.

Where both upper and lower objects are directories, a merged directory
is formed.

At mount time, the two directories given as mount options "lowerdir" and
"upperdir" are combined into a merged directory::

  mount -t overlay overlay -olowerdir=/lower,upperdir=/upper,\
  workdir=/work /merged

The "workdir" needs to be an empty directory on the same filesystem
as upperdir.

Then whenever a lookup is requested in such a merged directory, the
lookup is performed in each actual directory and the combined result
is cached in the dentry belonging to the overlay filesystem.  If both
actual lookups find directories, both are stored and a merged
directory is created, otherwise only one is stored: the upper if it
exists, else the lower.

Only the lists of names from directories are merged.  Other content
such as metadata and extended attributes are reported for the upper
directory only.  These attributes of the lower directory are hidden.

Whiteout·opaque 디렉터리와 readdir

140-197

Lower를 변경하지 않고 `rm`과 `rmdir`을 지원하려면 삭제 사실을 upper에 기록해야 합니다. 이를 위해 whiteout과 opaque directory를 사용하며 비디렉터리 객체는 항상 opaque로 취급됩니다.

Whiteout은 device number 0/0인 character device 또는 `trusted.overlay.whiteout` xattr을 가진 크기 0의 regular file입니다. Merged directory의 upper에서 whiteout을 찾으면 같은 이름의 lower 항목과 whiteout 자체를 모두 숨깁니다.

디렉터리에 `trusted.overlay.opaque=y`를 설정하면 opaque가 되며 같은 이름의 lower 디렉터리를 무시합니다. Opaque directory 안의 whiteout은 역할이 없으므로 두지 않아야 합니다. `trusted.overlay.whiteout`을 가진 regular file이 들어 있는 merge directory에는 `trusted.overlay.opaque=x`도 설정해야 일반적인 readdir에서 모든 entry의 whiteout xattr을 검사하는 비용을 피할 수 있습니다.

Whiteout과 opaque 표시
표식형식효과
Whiteoutdevice 0/0 character device같은 lower 이름과 자신을 숨김
Whiteout0-byte regular file + `trusted.overlay.whiteout`같은 lower 이름과 자신을 숨김
Opaque directory`trusted.overlay.opaque=y`같은 lower directory 전체 무시
Whiteout 포함 merge dir`trusted.overlay.opaque=x`entry별 whiteout xattr 검사 생략 가능

삭제·병합 억제와 readdir 최적화에 쓰는 upper 표식입니다.

Merged directory에 `readdir`를 호출하면 upper를 먼저 읽고 lower를 읽되 이미 존재하는 이름은 다시 추가하지 않습니다. 병합한 이름 목록은 `struct file`에 cache되어 file이 열린 동안 유지됩니다. 두 프로세스가 동시에 같은 디렉터리를 열면 각자 별도 cache를 가집니다. offset 0으로 `seekdir`한 뒤 `readdir`하면 cache를 버리고 다시 만듭니다.

따라서 디렉터리를 읽는 동안 발생한 변경은 그 열린 읽기에 나타나지 않습니다. Seek offset은 읽을 때 순차로 할당하므로 일부를 읽고 offset을 기억한 뒤 닫았다가 나중에 다시 열어 그 offset으로 이동하면, 특히 디렉터리가 바뀐 경우 이전 위치와 새 파일 이름 목록의 위치 사이에 상관관계가 거의 없을 수 있습니다. 병합되지 않은 디렉터리의 readdir는 해당 upper 또는 lower 디렉터리가 직접 처리합니다.

Merged readdir cache
Upper directory 이름을 먼저 읽음Lower directory 이름을 읽음이미 있는 이름은 추가하지 않음`struct file`에 병합 목록 cacheoffset 0 `seekdir` + `readdir` 시 cache 재구성close 후 reopen한 offset은 같은 위치를 보장하지 않음

Upper 우선 이름 병합과 open file별 cache 수명입니다.

whiteouts and opaque directories
--------------------------------

In order to support rm and rmdir without changing the lower
filesystem, an overlay filesystem needs to record in the upper filesystem
that files have been removed.  This is done using whiteouts and opaque
directories (non-directories are always opaque).

A whiteout is created as a character device with 0/0 device number or
as a zero-size regular file with the xattr "trusted.overlay.whiteout".

When a whiteout is found in the upper level of a merged directory, any
matching name in the lower level is ignored, and the whiteout itself
is also hidden.

A directory is made opaque by setting the xattr "trusted.overlay.opaque"
to "y".  Where the upper filesystem contains an opaque directory, any
directory in the lower filesystem with the same name is ignored.

An opaque directory should not contain any whiteouts, because they do not
serve any purpose.  A merge directory containing regular files with the xattr
"trusted.overlay.whiteout", should be additionally marked by setting the xattr
"trusted.overlay.opaque" to "x" on the merge directory itself.
This is needed to avoid the overhead of checking the "trusted.overlay.whiteout"
on all entries during readdir in the common case.

readdir
-------

When a 'readdir' request is made on a merged directory, the upper and
lower directories are each read and the name lists merged in the
obvious way (upper is read first, then lower - entries that already
exist are not re-added).  This merged name list is cached in the
'struct file' and so remains as long as the file is kept open.  If the
directory is opened and read by two processes at the same time, they
will each have separate caches.  A seekdir to the start of the
directory (offset 0) followed by a readdir will cause the cache to be
discarded and rebuilt.

This means that changes to the merged directory do not appear while a
directory is being read.  This is unlikely to be noticed by many
programs.

seek offsets are assigned sequentially when the directories are read.
Thus if:

 - read part of a directory
 - remember an offset, and close the directory
 - re-open the directory some time later
 - seek to the remembered offset

there may be little correlation between the old and new locations in
the list of filenames, particularly if anything has changed in the
directory.

Readdir on directories that are not merged is simply handled by the
underlying directory (upper or lower).

Lower 디렉터리 rename과 redirect

198-262

처음부터 upper에서 만든 것이 아닌 lower 또는 merged directory를 rename할 때 OverlayFS는 두 방식 중 하나를 사용합니다. 기본은 filesystem 경계를 넘는 `rename(2)`처럼 `EXDEV`를 반환하는 것입니다. `mv(1)` 같은 프로그램은 이를 예상하고 directory tree를 재귀적으로 복사합니다.

`redirect_dir`을 켜면 directory 자체만 upper로 copy up하고 내용은 복사하지 않습니다. 이어서 overlay root 기준 원래 위치의 경로를 `trusted.overlay.redirect` xattr에 기록한 뒤 디렉터리를 새 위치로 이동합니다.

`redirect_dir` rename
Lower 또는 merged directory rename 요청`redirect_dir` 비활성: `EXDEV` 반환활성: directory metadata만 copy up`trusted.overlay.redirect`에 원래 절대 경로 저장Upper directory를 새 위치로 이동

디렉터리 내용 대신 경로 redirect를 기록해 lower·merged directory를 이동합니다.

커널 설정 `OVERLAY_FS_REDIRECT_DIR`은 redirect_dir의 기본 활성 여부를 정합니다. `OVERLAY_FS_REDIRECT_ALWAYS_FOLLOW`는 redirect를 항상 따라가게 하며 보안성이 낮아지므로, 기능을 꺼도 redirect를 따라가던 구형 커널과의 호환성이 꼭 필요할 때만 켭니다.

Module parameter `redirect_dir=BOOL`, `redirect_always_follow=BOOL`은 위 커널 설정에 대응하고 `/sys/module/overlay/parameters/`에서도 바꿀 수 있습니다. `redirect_max=NUM`은 absolute redirect의 최대 바이트 수이며 기본값은 256입니다.

`redirect_dir` 마운트 값
새 redirect 생성기존 redirect 추적
`redirect_dir=on`
`redirect_dir=follow`아니요
`redirect_dir=nofollow`아니요아니요
`redirect_dir=off`아니요`redirect_always_follow`이면 follow, 아니면 nofollow

Redirect 생성과 추적을 독립적으로 제어합니다.

NFS export를 켜면 copy up된 각 directory를 lower inode의 file handle로 index하고 index entry의 `trusted.overlay.upper` xattr에 upper directory file handle을 저장합니다. Merged directory lookup에서 upper가 index의 file handle과 일치하지 않으면 여러 upper directory가 같은 lower로 redirect되었을 가능성이 있으므로 오류를 반환하고 inconsistency를 경고합니다.

Lower layer redirect는 index로 검증할 수 없습니다. 따라서 upper가 없는 overlay에서 NFS export를 사용하려면 `redirect_dir=nofollow`처럼 redirect 추적을 꺼야 합니다.

renaming directories
--------------------

When renaming a directory that is on the lower layer or merged (i.e. the
directory was not created on the upper layer to start with) overlayfs can
handle it in two different ways:

1. return EXDEV error: this error is returned by rename(2) when trying to
   move a file or directory across filesystem boundaries.  Hence
   applications are usually prepared to handle this error (mv(1) for example
   recursively copies the directory tree).  This is the default behavior.

2. If the "redirect_dir" feature is enabled, then the directory will be
   copied up (but not the contents).  Then the "trusted.overlay.redirect"
   extended attribute is set to the path of the original location from the
   root of the overlay.  Finally the directory is moved to the new
   location.

There are several ways to tune the "redirect_dir" feature.

Kernel config options:

- OVERLAY_FS_REDIRECT_DIR:
    If this is enabled, then redirect_dir is turned on by  default.
- OVERLAY_FS_REDIRECT_ALWAYS_FOLLOW:
    If this is enabled, then redirects are always followed by default. Enabling
    this results in a less secure configuration.  Enable this option only when
    worried about backward compatibility with kernels that have the redirect_dir
    feature and follow redirects even if turned off.

Module options (can also be changed through /sys/module/overlay/parameters/):

- "redirect_dir=BOOL":
    See OVERLAY_FS_REDIRECT_DIR kernel config option above.
- "redirect_always_follow=BOOL":
    See OVERLAY_FS_REDIRECT_ALWAYS_FOLLOW kernel config option above.
- "redirect_max=NUM":
    The maximum number of bytes in an absolute redirect (default is 256).

Mount options:

- "redirect_dir=on":
    Redirects are enabled.
- "redirect_dir=follow":
    Redirects are not created, but followed.
- "redirect_dir=nofollow":
    Redirects are not created and not followed.
- "redirect_dir=off":
    If "redirect_always_follow" is enabled in the kernel/module config,
    this "off" translates to "follow", otherwise it translates to "nofollow".

When the NFS export feature is enabled, every copied up directory is
indexed by the file handle of the lower inode and a file handle of the
upper directory is stored in a "trusted.overlay.upper" extended attribute
on the index entry.  On lookup of a merged directory, if the upper
directory does not match the file handle stores in the index, that is an
indication that multiple upper directories may be redirected to the same
lower directory.  In that case, lookup returns an error and warns about
a possible inconsistency.

Because lower layer redirects cannot be verified with the index, enabling
NFS export support on an overlay filesystem with no upper layer requires
turning off redirect follow (e.g. "redirect_dir=nofollow").

비디렉터리 copy_up과 권한 모델

263-349

File, symlink, device-special file 같은 비디렉터리는 상황에 따라 upper 또는 lower 객체를 직접 보여 줍니다. Lower file을 write로 열거나 metadata를 변경하는 등 쓰기 접근이 필요하면 먼저 lower에서 upper로 `copy_up`합니다. Hard link 생성도 copy_up이 필요하지만 symlink 생성은 그렇지 않습니다. Read-write로 열었어도 실제 data를 수정하지 않으면 copy_up이 결과적으로 불필요할 수 있습니다.

Copy_up은 먼저 포함 directory와 필요한 모든 parent를 upper에 만듭니다. Owner, mode, mtime, symlink target 등 같은 metadata로 객체를 만들고 regular file이면 lower data를 upper로 복사합니다. 마지막으로 extended attributes를 copy up합니다. 완료 뒤에는 새 upper file에 직접 접근하므로 rename·unlink처럼 이름을 다루는 작업 외에는 overlay 개입이 거의 없습니다.

일반 file copy_up
Lower 객체에 write·metadata 변경·hard-link 요청Upper에 parent directory chain 생성owner·mode·mtime·symlink target 복제Regular file이면 data 복사Extended attributes 복사이후 upper 객체에 직접 접근

Lower 객체를 쓰기 가능한 upper 객체로 전환하는 순서입니다.

OverlayFS는 lower와 upper에 접근할 때 사용할 credential을 저장합니다. Old mount API에서는 `mount(2)` 호출 task의 credential을 저장합니다. New mount API에서는 `fsconfig(2)`의 `FSCONFIG_CMD_CREATE`로 superblock을 만드는 task의 credential을 저장합니다.

Kernel v6.15부터 `override_creds` mount option을 사용하면 옵션을 호출한 task의 credential을 기록할 수 있습니다. Old mount API는 옵션 설정과 superblock 생성을 하나의 `mount(2)` syscall로 결합하므로 `override_creds`는 new mount API에서만 의미가 있습니다.

권한 모델은 세 원칙을 따릅니다. 첫째 copy up 전후 권한 검사 결과가 같아야 합니다. 둘째 overlay mount를 만든 task가 추가 권한을 얻어서는 안 됩니다. 셋째 일반 task는 underlying lower·upper에 직접 접근할 때보다 overlay를 통해 추가 권한을 얻을 수 있습니다.

각 접근에서 두 번 검사합니다. 검사 (a)는 current task에 대해 local DAC, 즉 owner·group·mode·POSIX ACL과 MAC을 확인합니다. 검사 (b)는 저장된 credential이 underlying filesystem 권한과 MAC 아래에서 실제 lower·upper 작업을 수행할 수 있는지 확인합니다.

(a)는 owner·group·mode·POSIX ACL이 copy up되므로 전후 일관성을 지키지만 NFS 같은 서버 강제 권한을 무시할 수 있습니다. (b)는 저장된 credential이 없는 lower·upper 권한을 task가 얻지 못하게 하지만 특수한 구성에서는 전후 일관성이 깨질 수 있습니다. 보통 저장 credential은 모든 작업에 충분한 권한을 갖습니다.

OverlayFS 이중 권한 검사
검사Credential대상 정책보장·효과
(a)Current taskLocal DAC + MACcopy_up 전후 표시 권한 일관성
(b)Stashed credentialUnderlying fs 권한 + MACmount creator의 권한 범위 초과 방지

표시되는 overlay 권한과 실제 계층 작업 권한을 별도로 확인합니다.

이 모델은 `mount -t overlay ...`의 결과가 `cp -a /lower /upper` 뒤 `/upper`를 bind mount한 결과와 같은 접근 권한을 갖는다는 비유로 설명할 수 있습니다. 차이는 복사 시점이 요청 시점의 on-demand인지 사전 up-front인지뿐입니다.

Non-directories
---------------

Objects that are not directories (files, symlinks, device-special
files etc.) are presented either from the upper or lower filesystem as
appropriate.  When a file in the lower filesystem is accessed in a way
that requires write-access, such as opening for write access, changing
some metadata etc., the file is first copied from the lower filesystem
to the upper filesystem (copy_up).  Note that creating a hard-link
also requires copy_up, though of course creation of a symlink does
not.

The copy_up may turn out to be unnecessary, for example if the file is
opened for read-write but the data is not modified.

The copy_up process first makes sure that the containing directory
exists in the upper filesystem - creating it and any parents as
necessary.  It then creates the object with the same metadata (owner,
mode, mtime, symlink-target etc.) and then if the object is a file, the
data is copied from the lower to the upper filesystem.  Finally any
extended attributes are copied up.

Once the copy_up is complete, the overlay filesystem simply
provides direct access to the newly created file in the upper
filesystem - future operations on the file are barely noticed by the
overlay filesystem (though an operation on the name of the file such as
rename or unlink will of course be noticed and handled).


Permission model
----------------

An overlay filesystem stashes credentials that will be used when
accessing lower or upper filesystems.

In the old mount api the credentials of the task calling mount(2) are
stashed. In the new mount api the credentials of the task creating the
superblock through FSCONFIG_CMD_CREATE command of fsconfig(2) are
stashed.

Starting with kernel v6.15 it is possible to use the "override_creds"
mount option which will cause the credentials of the calling task to be
recorded. Note that "override_creds" is only meaningful when used with
the new mount api as the old mount api combines setting options and
superblock creation in a single mount(2) syscall.

Permission checking in the overlay filesystem follows these principles:

 1) permission check SHOULD return the same result before and after copy up

 2) task creating the overlay mount MUST NOT gain additional privileges

 3) task[*] MAY gain additional privileges through the overlay,
    compared to direct access on underlying lower or upper filesystems

This is achieved by performing two permission checks on each access:

 a) check if current task is allowed access based on local DAC (owner,
    group, mode and posix acl), as well as MAC checks

 b) check if stashed credentials would be allowed real operation on lower or
    upper layer based on underlying filesystem permissions, again including
    MAC checks

Check (a) ensures consistency (1) since owner, group, mode and posix acls
are copied up.  On the other hand it can result in server enforced
permissions (used by NFS, for example) being ignored (3).

Check (b) ensures that no task gains permissions to underlying layers that
the stashed credentials do not have (2).  This also means that it is possible
to create setups where the consistency rule (1) does not hold; normally,
however, the stashed credentials will have sufficient privileges to
perform all operations.

Another way to demonstrate this model is drawing parallels between::

  mount -t overlay overlay -olowerdir=/lower,upperdir=/upper,... /merged

and::

  cp -a /lower /upper
  mount --bind /upper /merged

The resulting access permissions should be the same.  The difference is in
the time of copy (on-demand vs. up-front).

여러 lower 계층과 새 mount API

350-378

여러 lower directory는 colon `:`으로 구분합니다. `lowerdir=/lower1:/lower2:/lower3`에서 오른쪽부터 쌓아 올리므로 `/lower1`이 top, `/lower2`가 middle, `/lower3`가 bottom입니다. `upperdir`와 `workdir`를 생략하면 overlay는 read-only입니다.

mount -t overlay overlay -olowerdir=/lower1:/lower2:/lower3 /merged

Directory 이름 자체에 colon이 있으면 단일 backslash로 escape할 수 있습니다. 예를 들어 `/a\:lower\:\:dir`을 lower로 지정합니다.

Kernel v6.8부터 new mount API의 `fsconfig`와 반복 가능한 `lowerdir+` option으로 colon이 들어간 경로를 그대로 전달할 수 있습니다. 이 방식의 경로가 `/proc/self/mountinfo`에 표시될 때 colon은 octal `\072`로 escape됩니다.

fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/a:lower::dir", 0);
여러 lower의 우선순위
Top: `/lower1`Middle: `/lower2`Bottom: `/lower3``upperdir`·`workdir` 없음Read-only merged overlay

왼쪽 경로가 위쪽 계층이며 upper가 없으면 읽기 전용입니다.

Multiple lower layers
---------------------

Multiple lower layers can now be given using the colon (":") as a
separator character between the directory names.  For example::

  mount -t overlay overlay -olowerdir=/lower1:/lower2:/lower3 /merged

As the example shows, "upperdir=" and "workdir=" may be omitted.  In
that case the overlay will be read-only.

The specified lower directories will be stacked beginning from the
rightmost one and going left.  In the above example lower1 will be the
top, lower2 the middle and lower3 the bottom layer.

Note: directory names containing colons can be provided as lower layer by
escaping the colons with a single backslash.  For example::

  mount -t overlay overlay -olowerdir=/a\:lower\:\:dir /merged

Since kernel version v6.8, directory names containing colons can also
be configured as lower layer using the "lowerdir+" mount options and the
fsconfig syscall from new mount api.  For example::

  fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/a:lower::dir", 0);

In the latter case, colons in lower layer directory names will be escaped
as an octal characters (\072) when displayed in /proc/self/mountinfo.

Metadata-only copy up

379-412

`metacopy`를 켜면 `chown`이나 `chmod`처럼 metadata만 바꾸는 작업에서 전체 file 대신 metadata만 upper로 copy up합니다. 이 상태의 upper file은 data가 없음을 나타내는 `trusted.overlayfs.metacopy` xattr로 표시됩니다.

나중에 file을 WRITE로 열 때 lower data를 upper로 복사하며 완료 후 upper file에서 `trusted.overlayfs.metacopy` xattr을 제거합니다. 즉 실제 data 변경이 필요할 때까지 data copy up을 지연합니다.

Metacopy 지연 data 복사
`chown`·`chmod` 같은 metadata 작업Upper에 metadata-only file 생성`trusted.overlayfs.metacopy` 표시Data는 lower에서 계속 읽음첫 WRITE에서 lower data copy upmetacopy xattr 제거

Metadata 변경과 실제 WRITE 시점을 분리합니다.

기본 활성 여부는 `CONFIG_OVERLAY_FS_METACOPY`, module load 시 `metacopy=on|off`, mount별 `metacopy=on|off`로 제어합니다.

신뢰할 수 없는 upper 또는 lower와 `metacopy=on`을 사용해서는 안 됩니다. 공격자가 적절한 REDIRECT와 METACOPY xattr을 직접 만들어 REDIRECT가 가리키는 lower file에 접근할 수 있기 때문입니다. 로컬에서는 `trusted.*` 설정에 `CAP_SYS_ADMIN`이 필요하지만 USB 저장장치 같은 비신뢰 계층에서는 가능할 수 있습니다.

`metacopy=on` 충돌과 보안
조건결과
`redirect_dir=off|nofollow``metacopy=on`과 충돌
`redirect_dir=follow` + `upperdir``metacopy=on`과 충돌
`nfs_export=on``metacopy=on`과 충돌
비신뢰 upper/lower조작된 REDIRECT·METACOPY xattr로 접근 우회 위험

동시에 사용할 수 없는 옵션과 비신뢰 계층의 위험입니다.

Metadata only copy up
---------------------

When the "metacopy" feature is enabled, overlayfs will only copy
up metadata (as opposed to whole file), when a metadata specific operation
like chown/chmod is performed. An upper file in this state is marked with
"trusted.overlayfs.metacopy" xattr which indicates that the upper file
contains no data.  The data will be copied up later when file is opened for
WRITE operation.  After the lower file's data is copied up,
the "trusted.overlayfs.metacopy" xattr is removed from the upper file.

In other words, this is delayed data copy up operation and data is copied
up when there is a need to actually modify data.

There are multiple ways to enable/disable this feature. A config option
CONFIG_OVERLAY_FS_METACOPY can be set/unset to enable/disable this feature
by default. Or one can enable/disable it at module load time with module
parameter metacopy=on/off. Lastly, there is also a per mount option
metacopy=on/off to enable/disable this feature per mount.

Do not use metacopy=on with untrusted upper/lower directories. Otherwise
it is possible that an attacker can create a handcrafted file with
appropriate REDIRECT and METACOPY xattrs, and gain access to file on lower
pointed by REDIRECT. This should not be possible on local system as setting
"trusted." xattrs will require CAP_SYS_ADMIN. But it should be possible
for untrusted layers like from a pen drive.

Note: redirect_dir={off|nofollow|follow[*]} and nfs_export=on mount options
conflict with metacopy=on, and will result in an error.

[*] redirect_dir=follow only conflicts with metacopy=on if upperdir=... is
given.

Data-only lower 계층

413-463

Metacopy를 켜면 하나의 overlay regular file이 최대 세 계층의 정보를 조합할 수 있습니다. Metadata는 upper file, `st_ino`와 `st_dev` 객체 식별자는 lower file, 실제 data는 더 아래의 다른 lower file에서 옵니다.

세 부분으로 구성된 metacopy file
Upper layer file: metadataNormal lower file: `st_ino` + `st_dev` identity더 아래 data-only file: data`trusted.overlay.redirect`가 data path 연결하나의 overlay regular file로 표시

한 overlay inode가 서로 다른 계층의 metadata·identity·data를 결합합니다.

Lower data file은 topmost lower를 제외한 어떤 lower에도 있을 수 있습니다. Topmost 아래의 최하위 계층들은 double colon `::` separator로 data-only lower로 지정합니다. Data-only 아래에 normal lower를 둘 수 없으므로 `::` 오른쪽에는 single colon `:`을 사용할 수 없습니다.

mount -t overlay overlay -olowerdir=/l1:/l2:/l3::/do1::/do2 /merged

이 예에서 `/l1`, `/l2`, `/l3`은 normal lower이고 `/do1`, `/do2`는 data-only입니다. Data-only 경로는 merged directory에 나타나지 않으며 해당 파일의 metadata와 `st_ino`·`st_dev`도 overlay inode에 노출되지 않습니다. 위 normal lower의 metacopy file이 data-only file의 절대 경로로 redirect할 때 data만 보입니다.

Data-only 계층을 하나라도 지정하면 `metacopy=on`을 명시하지 않아도 data redirection이 활성화되며 다른 형태의 metacopy는 거부됩니다. Data-only는 `userxattr`과 함께 쓸 수 있지만 `user.overlay.redirect`를 바꿀 권한을 엄격히 관리해야 오용을 막을 수 있습니다.

Kernel v6.8부터 new mount API에서 `lowerdir+`와 `datadir+`를 반복 호출해 normal lower와 data-only layer를 순서대로 추가할 수 있습니다.

Data-only 계층 순서
계층구분자Merged namespace 노출사용 정보
`/l1:/l2:/l3``:`metadata·identity·일반 data
`/do1::/do2``::`아니요redirect가 가리키는 data만
Data-only 아래 normal lower허용 안 됨-`::` 오른쪽에 `:` 금지

Normal lower 뒤에만 data-only를 둘 수 있습니다.

Data-only lower layers
----------------------

With "metacopy" feature enabled, an overlayfs regular file may be a composition
of information from up to three different layers:

 1) metadata from a file in the upper layer

 2) st_ino and st_dev object identifier from a file in a lower layer

 3) data from a file in another lower layer (further below)

The "lower data" file can be on any lower layer, except from the top most
lower layer.

Below the topmost lower layer, any number of lowermost layers may be defined
as "data-only" lower layers, using double colon ("::") separators.
A normal lower layer is not allowed to be below a data-only layer, so single
colon separators are not allowed to the right of double colon ("::") separators.


For example::

  mount -t overlay overlay -olowerdir=/l1:/l2:/l3::/do1::/do2 /merged

The paths of files in the "data-only" lower layers are not visible in the
merged overlayfs directories and the metadata and st_ino/st_dev of files
in the "data-only" lower layers are not visible in overlayfs inodes.

Only the data of the files in the "data-only" lower layers may be visible
when a "metacopy" file in one of the lower layers above it, has a "redirect"
to the absolute path of the "lower data" file in the "data-only" lower layer.

Instead of explicitly enabling "metacopy=on" it is sufficient to specify at
least one data-only layer to enable redirection of data to a data-only layer.
In this case other forms of metacopy are rejected.  Note: this way, data-only
layers may be used together with "userxattr", in which case careful attention
must be given to privileges needed to change the "user.overlay.redirect" xattr
to prevent misuse.

Since kernel version v6.8, "data-only" lower layers can also be added using
the "datadir+" mount options and the fsconfig syscall from new mount api.
For example::

  fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/l1", 0);
  fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/l2", 0);
  fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/l3", 0);
  fsconfig(fs_fd, FSCONFIG_SET_STRING, "datadir+", "/do1", 0);
  fsconfig(fs_fd, FSCONFIG_SET_STRING, "datadir+", "/do2", 0);

File descriptor 계층과 fs-verity

464-527

Kernel v6.13부터 new mount API의 `fsconfig`에서 path뿐 아니라 file descriptor로도 계층을 지정할 수 있습니다. 원문은 이 기능을 `datadir+`, `lowerdir+`, `upperdir`, `workdir+` mount option에 제공한다고 설명하며, 예제 호출에서는 work directory key로 `workdir`을 사용합니다. `FSCONFIG_SET_FD`를 반복 호출해 여러 lower·data-only 계층을 추가할 수 있습니다.

File descriptor 계층 option
Option`fsconfig` command
`lowerdir+``FSCONFIG_SET_FD``fd_lower1` 등 반복
`datadir+``FSCONFIG_SET_FD``fd_data1` 등 반복
`workdir``FSCONFIG_SET_FD``fd_work`
`upperdir``FSCONFIG_SET_FD``fd_upper`

New mount API에서 descriptor로 전달 가능한 계층입니다.

Lower file의 metadata copy up 때 source에 fs-verity가 켜져 있고 overlay verity support도 켜져 있으면 lower file digest를 `trusted.overlay.metacopy` xattr에 넣습니다. 이후 metacopy file을 열 때마다 lower content를 이 digest로 검증합니다.

Verity xattr이 있는 계층에서는 upper metacopy file이 copy-up 시점의 lower content와 일치함을 보장합니다. Mount 중이든 remount 뒤든 lower file이 교체되거나 수정되면 overlay access가 `EIO`를 반환합니다. Open 시 overlay digest 검사 또는 뒤의 read에서 fs-verity가 오류를 내며 자세한 내용이 kernel log에 기록됩니다. 세부 동작은 `Documentation/filesystems/fsverity.rst`의 `accessing_verity_files`를 참조합니다.

Verity는 우발적 변경을 찾는 강건성 검사로 쓸 수 있습니다. Upper를 dm-verity 등으로 완전히 신뢰하면 비신뢰 lower도 모든 metacopy file의 검증된 content 공급자로 쓸 수 있습니다. 비신뢰 lower를 data-only로 지정하면 content만 공급하므로 전체 mount가 upper와 일치한다고 신뢰할 수 있습니다.

Metacopy fs-verity 검증
Lower source에 fs-verity 활성Metadata copy up`trusted.overlay.metacopy`에 digest 저장Metacopy file open마다 lower content 검증불일치 또는 digest 누락 조건`EIO` + kernel log

Copy-up 시 저장한 digest로 이후 lower data의 변경을 검출합니다.

`verity` mount option
동작
`verity=off`Digest를 생성하거나 사용하지 않음, option 생략 시 기본
`verity=on`기대 digest가 있으면 data가 일치해야 하며 source digest가 있으면 저장
`verity=require``on` + 모든 metacopy에 digest 필수, 없으면 open에서 `EIO`
`require` + source에 fs-verity 없음Metadata-only 대신 full copy-up

Digest 생성·사용과 필수 여부를 제어합니다.

Specifying layers via file descriptors
--------------------------------------

Since kernel v6.13, overlayfs supports specifying layers via file descriptors in
addition to specifying them as paths. This feature is available for the
"datadir+", "lowerdir+", "upperdir", and "workdir+" mount options with the
fsconfig syscall from the new mount api::

  fsconfig(fs_fd, FSCONFIG_SET_FD, "lowerdir+", NULL, fd_lower1);
  fsconfig(fs_fd, FSCONFIG_SET_FD, "lowerdir+", NULL, fd_lower2);
  fsconfig(fs_fd, FSCONFIG_SET_FD, "lowerdir+", NULL, fd_lower3);
  fsconfig(fs_fd, FSCONFIG_SET_FD, "datadir+", NULL, fd_data1);
  fsconfig(fs_fd, FSCONFIG_SET_FD, "datadir+", NULL, fd_data2);
  fsconfig(fs_fd, FSCONFIG_SET_FD, "workdir", NULL, fd_work);
  fsconfig(fs_fd, FSCONFIG_SET_FD, "upperdir", NULL, fd_upper);


fs-verity support
-----------------

During metadata copy up of a lower file, if the source file has
fs-verity enabled and overlay verity support is enabled, then the
digest of the lower file is added to the "trusted.overlay.metacopy"
xattr. This is then used to verify the content of the lower file
each the time the metacopy file is opened.

When a layer containing verity xattrs is used, it means that any such
metacopy file in the upper layer is guaranteed to match the content
that was in the lower at the time of the copy-up. If at any time
(during a mount, after a remount, etc) such a file in the lower is
replaced or modified in any way, access to the corresponding file in
overlayfs will result in EIO errors (either on open, due to overlayfs
digest check, or from a later read due to fs-verity) and a detailed
error is printed to the kernel logs. For more details of how fs-verity
file access works, see :ref:`Documentation/filesystems/fsverity.rst
<accessing_verity_files>`.

Verity can be used as a general robustness check to detect accidental
changes in the overlayfs directories in use. But, with additional care
it can also give more powerful guarantees. For example, if the upper
layer is fully trusted (by using dm-verity or something similar), then
an untrusted lower layer can be used to supply validated file content
for all metacopy files.  If additionally the untrusted lower
directories are specified as "Data-only", then they can only supply
such file content, and the entire mount can be trusted to match the
upper layer.

This feature is controlled by the "verity" mount option, which
supports these values:

- "off":
    The metacopy digest is never generated or used. This is the
    default if verity option is not specified.
- "on":
    Whenever a metacopy file specifies an expected digest, the
    corresponding data file must match the specified digest. When
    generating a metacopy file the verity digest will be set in it
    based on the source file (if it has one).
- "require":
    Same as "on", but additionally all metacopy files must specify a
    digest (or EIO is returned on open). This means metadata copy up
    will only be used if the data file has fs-verity enabled,
    otherwise a full copy-up is used.

계층 공유·중첩 경로와 origin 검증

528-567

여러 overlay mount가 같은 lower layer를 공유하는 것은 허용되고 흔합니다. 같은 lower path를 재사용하거나 다른 overlay lower path의 아래 또는 위 경로를 lower로 사용할 수도 있습니다.

이미 다른 overlay가 사용하는 upper 또는 workdir path, 혹은 부분적으로 겹치는 path는 허용되지 않으며 `EBUSY`로 실패할 수 있습니다. Upper/workdir를 공유하거나 겹치는 두 overlay에서 같은 file에 접근하면 crash나 deadlock은 없지만 동작은 undefined입니다.

계층 path 공유 규칙
Path 관계허용결과
같은 lower path 공유일반적인 사용
다른 lower의 상위·하위 path허용
같은 upper 또는 workdir 재사용아니요`EBUSY` 가능
upper/workdir 부분 overlap아니요`EBUSY` 가능
겹친 upper/workdir로 file 접근금지undefined, crash·deadlock은 없음

Lower는 공유할 수 있지만 upper와 workdir는 독점해야 합니다.

이전에 다른 lower와 조합해 사용한 upper path를 다시 쓰는 것은 원칙적으로 허용되지만 `index` 또는 `metacopy`가 켜져 있으면 허용되지 않습니다.

`index`를 켠 첫 mount에서 lower root의 NFS file handle과 lower filesystem UUID를 encode해 upper root의 `trusted.overlay.origin` xattr에 저장합니다. 다음 mount는 현재 lower root handle과 UUID를 저장된 origin과 비교하며 검증 실패 시 `ESTALE`로 mount가 실패합니다.

Lower가 NFS export를 지원하지 않거나 유효한 UUID가 없거나 upper가 extended attribute를 지원하지 않으면 `index` mount는 `EOPNOTSUPP`로 실패합니다. `metacopy`에는 mount-time 검증이 없으므로 같은 upper를 다른 lower set과 쓰면 mount가 성공할 수 있지만 이후 동작은 예측할 수 없으므로 해서는 안 됩니다.

계층을 같은 또는 다른 기반 파일시스템의 다른 directory tree, 심지어 다른 machine으로 복사하는 경우가 흔합니다. 그러나 `index`가 켜져 있으면 복사된 계층의 lower root file handle 검증이 실패합니다.

`index` origin 검증
첫 mount: lower root NFS file handle + UUIDUpper root `trusted.overlay.origin`에 encode다음 mount: 현재 lower root identity 읽기저장 origin과 비교일치하면 mount 계속불일치하면 `ESTALE`

첫 mount에서 저장한 lower root identity를 다음 mount와 비교합니다.

Sharing and copying layers
--------------------------

Lower layers may be shared among several overlay mounts and that is indeed
a very common practice.  An overlay mount may use the same lower layer
path as another overlay mount and it may use a lower layer path that is
beneath or above the path of another overlay lower layer path.

Using an upper layer path and/or a workdir path that are already used by
another overlay mount is not allowed and may fail with EBUSY.  Using
partially overlapping paths is not allowed and may fail with EBUSY.
If files are accessed from two overlayfs mounts which share or overlap the
upper layer and/or workdir path, the behavior of the overlay is undefined,
though it will not result in a crash or deadlock.

Mounting an overlay using an upper layer path, where the upper layer path
was previously used by another mounted overlay in combination with a
different lower layer path, is allowed, unless the "index" or "metacopy"
features are enabled.

With the "index" feature, on the first time mount, an NFS file
handle of the lower layer root directory, along with the UUID of the lower
filesystem, are encoded and stored in the "trusted.overlay.origin" extended
attribute on the upper layer root directory.  On subsequent mount attempts,
the lower root directory file handle and lower filesystem UUID are compared
to the stored origin in upper root directory.  On failure to verify the
lower root origin, mount will fail with ESTALE.  An overlayfs mount with
"index" enabled will fail with EOPNOTSUPP if the lower filesystem
does not support NFS export, lower filesystem does not have a valid UUID or
if the upper filesystem does not support extended attributes.

For the "metacopy" feature, there is no verification mechanism at
mount time. So if same upper is mounted with different set of lower, mount
probably will succeed but expect the unexpected later on. So don't do it.

It is quite a common practice to copy overlay layers to a different
directory tree on the same or different underlying filesystem, and even
to a different machine.  With the "index" feature, trying to mount
the copied layers will fail the verification of the lower root file handle.

OverlayFS mount 중첩과 xattr escape

568-592

다른 overlayfs mount에 저장된 디렉터리를 lower로 사용할 수 있습니다. 일반 file은 특별한 처리가 필요 없지만 whiteout이나 `overlay.*` xattr 같은 OverlayFS attribute는 아래쪽 overlay가 먼저 해석하고 제거합니다. 두 번째 overlay가 이를 보게 하려면 escape해야 합니다.

OverlayFS 전용 xattr은 `overlay.overlay.` prefix를 사용해 escape합니다. Lower의 `trusted.overlay.overlay.metacopy`는 첫 overlay mount에서 일반 file의 `trusted.overlay.metacopy`로 노출됩니다. 각 overlay instance가 prefix 하나만 제거하므로 prefix를 반복하여 원하는 깊이까지 중첩할 수 있습니다.

일반 whiteout은 아래쪽 overlay가 항상 처리합니다. Overlay mount 안에 다음 계층이 사용할 effective whiteout을 저장하려면 대체 표현을 씁니다. `overlay.opaque=x`인 디렉터리 안에 `overlay.whiteout` xattr을 설정한 크기 0 regular file을 둡니다. OverlayFS 자체는 이 대체 whiteout을 만들지 않지만 container 같은 userspace layer 생성 도구가 사용할 수 있습니다.

대체 whiteout도 표준 xattr escape를 적용해 임의 깊이로 올바르게 중첩할 수 있습니다.

중첩 xattr escape
Lower: `trusted.overlay.overlay.metacopy`첫 overlay가 escape prefix 하나 제거노출: `trusted.overlay.metacopy`다음 overlay가 metacopy 의미로 해석더 깊은 중첩은 `overlay.` prefix 반복

각 overlay가 `overlay.` prefix 한 겹을 제거합니다.

중첩용 대체 whiteout
구성
파일크기 0 regular file
파일 xattr`overlay.whiteout`
포함 디렉터리 xattr`overlay.opaque=x`
생성 주체Container 등 userspace 도구, OverlayFS 자체는 생성하지 않음

아래쪽 overlay가 소비하지 않도록 regular file과 xattr로 표현합니다.

Nesting overlayfs mounts
------------------------

It is possible to use a lower directory that is stored on an overlayfs
mount. For regular files this does not need any special care. However, files
that have overlayfs attributes, such as whiteouts or "overlay.*" xattrs, will
be interpreted by the underlying overlayfs mount and stripped out. In order to
allow the second overlayfs mount to see the attributes they must be escaped.

Overlayfs specific xattrs are escaped by using a special prefix of
"overlay.overlay.". So, a file with a "trusted.overlay.overlay.metacopy" xattr
in the lower dir will be exposed as a regular file with a
"trusted.overlay.metacopy" xattr in the overlayfs mount. This can be nested by
repeating the prefix multiple time, as each instance only removes one prefix.

A lower dir with a regular whiteout will always be handled by the overlayfs
mount, so to support storing an effective whiteout file in an overlayfs mount an
alternative form of whiteout is supported. This form is a regular, zero-size
file with the "overlay.whiteout" xattr set, inside a directory with the
"overlay.opaque" xattr set to "x" (see `whiteouts and opaque directories`_).
These alternative whiteouts are never created by overlayfs, but can be used by
userspace tools (like containers) that generate lower layers.
These alternative whiteouts can be escaped using the standard xattr escape
mechanism in order to properly nest to any depth.

비표준 동작과 호환성 기능

593-650

현재 OverlayFS는 대체로 POSIX 호환으로 동작하지만 몇 가지 예외가 있습니다. Lower에 있는 file을 읽어도 POSIX가 요구하는 `st_atime` 갱신을 하지 않습니다. Lower file을 read-only로 열어 `MAP_SHARED`로 mmap한 뒤 file이 바뀌어도 mapping에 반영되지 않습니다. Lower file이 실행 중이어도 write open이나 truncate를 `ETXTBSY`로 거부하지 않습니다.

OverlayFS 비표준 동작
상황현재 동작
Lower file read`st_atime`을 갱신하지 않음
Lower file read-only + `MAP_SHARED`이후 file 변경이 mapping에 반영되지 않음
Lower file 실행 중 write/truncate`ETXTBSY`로 거부하지 않음

현재 완전히 처리하지 않는 POSIX 의미입니다.

표준 동작에 더 가깝게 만드는 기능은 `redirect_dir`, `index`, `xino`입니다. `redirect_dir=on`, module option 또는 `CONFIG_OVERLAY_FS_REDIRECT_DIR=y`로 redirect를 켭니다. 꺼져 있으면 lower 또는 merged directory의 `rename(2)`이 `EXDEV`로 실패합니다.

`index=on`, module option 또는 `CONFIG_OVERLAY_FS_INDEX=y`로 hard-link index를 켭니다. 꺼진 상태에서 여러 hard link가 있는 file을 copy up하면 link 관계가 끊어져 같은 inode를 가리키던 다른 이름에 변경이 전파되지 않습니다.

`xino=auto|on`, module `xino_auto=on`, `CONFIG_OVERLAY_FS_XINO_AUTO=y`로 inode 합성을 켭니다. 모든 계층이 같은 기반 filesystem이면 암시적으로 활성화됩니다. 꺼져 있거나 inode 번호에 충분한 빈 비트가 없으면 `stat(2)`의 `st_ino`·`st_dev`와 `readdir(3)`의 `d_ino`가 일반 파일시스템처럼 동작함을 보장할 수 없습니다.

표준 호환성 기능
기능활성화비활성화 결과
`redirect_dir`mount/module/configLower·merged directory rename이 `EXDEV`
`index`mount/module/configCopy-up 시 multi-hard-link 관계가 끊어질 수 있음
`xino`mount/module/config 또는 같은 underlying fs`st_dev` 불균일·`st_ino` 비영속 가능

기능을 끌 때 드러나는 의미 차이입니다.

Non-standard behavior
---------------------

Current version of overlayfs can act as a mostly POSIX compliant
filesystem.

This is the list of cases that overlayfs doesn't currently handle:

 a) POSIX mandates updating st_atime for reads.  This is currently not
    done in the case when the file resides on a lower layer.

 b) If a file residing on a lower layer is opened for read-only and then
    memory mapped with MAP_SHARED, then subsequent changes to the file are not
    reflected in the memory mapping.

 c) If a file residing on a lower layer is being executed, then opening that
    file for write or truncating the file will not be denied with ETXTBSY.

The following options allow overlayfs to act more like a standards
compliant filesystem:

redirect_dir
````````````

Enabled with the mount option or module option: "redirect_dir=on" or with
the kernel config option CONFIG_OVERLAY_FS_REDIRECT_DIR=y.

If this feature is disabled, then rename(2) on a lower or merged directory
will fail with EXDEV ("Invalid cross-device link").

index
`````

Enabled with the mount option or module option "index=on" or with the
kernel config option CONFIG_OVERLAY_FS_INDEX=y.

If this feature is disabled and a file with multiple hard links is copied
up, then this will "break" the link.  Changes will not be propagated to
other names referring to the same inode.

xino
````

Enabled with the mount option "xino=auto" or "xino=on", with the module
option "xino_auto=on" or with the kernel config option
CONFIG_OVERLAY_FS_XINO_AUTO=y.  Also implicitly enabled by using the same
underlying filesystem for all layers making up the overlay.

If this feature is disabled or the underlying filesystem doesn't have
enough free bits in the inode number, then overlayfs will not be able to
guarantee that the values of st_ino and st_dev returned by stat(2) and the
value of d_ino returned by readdir(3) will act like on a normal filesystem.
E.g. the value of st_dev may be different for two objects in the same
overlay filesystem and the value of st_ino for filesystem objects may not be
persistent and could change even while the overlay filesystem is mounted, as
summarized in the `Inode properties`_ table above.

기반 파일시스템 변경과 origin

651-683

Overlay가 mount된 동안 underlying filesystem을 변경하는 것은 허용되지 않습니다. 변경하면 crash나 deadlock은 없지만 overlay 동작은 undefined입니다.

Overlay를 mount하지 않은 offline 상태에서는 upper tree를 변경할 수 있습니다. Lower tree의 offline 변경은 `metacopy`, `index`, `xino`, `redirect_dir`를 사용한 적이 없을 때만 허용됩니다. 이 기능을 쓴 뒤 lower를 바꾸면 동작은 undefined지만 역시 crash나 deadlock은 발생하지 않습니다.

Underlying tree 변경 규칙
상태Upper 변경Lower 변경
Overlay mounted허용 안 됨허용 안 됨
Offline허용특수 기능 미사용 시에만 허용
Offline + `metacopy|index|xino|redirect_dir` 사용허용Undefined behavior

Mount 상태와 기능 사용 여부에 따른 허용 범위입니다.

NFS export가 켜져 있으면 lower의 offline 변경에 대한 동작이 export를 끈 경우와 다릅니다. 매 copy_up에서 lower inode의 NFS file handle과 lower filesystem UUID를 encode하여 upper inode의 `trusted.overlay.origin` xattr에 저장합니다.

NFS export 상태에서 merged directory lookup이 lookup path 또는 `trusted.overlay.redirect`가 가리킨 path에서 lower directory를 찾으면, 발견한 lower file handle과 UUID를 copy-up 시 저장한 origin과 비교합니다. 일치하지 않으면 그 lower directory를 upper directory와 병합하지 않습니다.

Lower directory origin 검사
Copy-up: lower file handle + UUID encodeUpper inode의 `trusted.overlay.origin`에 저장Merged lookup에서 lower directory 발견현재 handle·UUID와 origin 비교일치하면 upper와 merge불일치하면 merge 제외

Copy-up 때 저장한 lower identity와 lookup 결과를 비교합니다.

Changes to underlying filesystems
---------------------------------

Changes to the underlying filesystems while part of a mounted overlay
filesystem are not allowed.  If the underlying filesystem is changed,
the behavior of the overlay is undefined, though it will not result in
a crash or deadlock.

Offline changes, when the overlay is not mounted, are allowed to the
upper tree.  Offline changes to the lower tree are only allowed if the
"metacopy", "index", "xino" and "redirect_dir" features
have not been used.  If the lower tree is modified and any of these
features has been used, the behavior of the overlay is undefined,
though it will not result in a crash or deadlock.

When the overlay NFS export feature is enabled, overlay filesystems
behavior on offline changes of the underlying lower layer is different
than the behavior when NFS export is disabled.

On every copy_up, an NFS file handle of the lower inode, along with the
UUID of the lower filesystem, are encoded and stored in an extended
attribute "trusted.overlay.origin" on the upper inode.

When the NFS export feature is enabled, a lookup of a merged directory,
that found a lower directory at the lookup path or at the path pointed
to by the "trusted.overlay.redirect" extended attribute, will verify
that the found lower directory file handle and lower filesystem UUID
match the origin file handle that was stored at copy_up time.  If a
found lower directory does not match the stored origin, that directory
will not be merged with the upper directory.


NFS export index와 file handle

684-743

Underlying filesystem이 NFS export를 지원하고 `nfs_export` 기능을 켜면 OverlayFS를 NFS로 export할 수 있습니다. Lower 객체를 copy up할 때마다 index directory 아래에 entry를 만들며 이름은 copy-up origin file handle의 hexadecimal 표현입니다.

비디렉터리 index entry는 upper inode의 hard link입니다. Directory index entry는 upper directory inode의 encoded file handle을 `trusted.overlay.upper` xattr에 저장합니다.

NFS export index entry
객체Index entry
Non-directoryUpper inode를 가리키는 hard link
Directory`trusted.overlay.upper`에 upper directory file handle
Entry 이름Lower copy-up origin file handle의 hexadecimal 표현

Copy-up origin 형식에 따라 index가 upper 객체를 연결하는 방법입니다.

Overlay file handle을 encode할 때 non-upper 객체는 lower inode의 lower handle을, indexed 객체는 copy_up origin의 lower handle을 사용합니다. Pure-upper 객체와 기존 non-indexed upper 객체는 upper inode의 upper handle을 사용합니다.

Encoded handle에는 lower/upper 같은 path type 정보가 있는 header, underlying filesystem UUID, underlying inode에 대한 파일시스템 고유 encoding이 들어갑니다. 이 형식은 `trusted.overlay.origin` xattr에 저장하는 file handle 형식과 같습니다.

Decode는 여섯 단계입니다. UUID와 path type으로 underlying layer를 찾고 underlying filesystem handle을 underlying dentry로 decode합니다. Lower handle이면 이름으로 index directory를 조회합니다. Index에서 whiteout을 찾으면 handle encode 뒤 객체가 삭제된 것이므로 `ESTALE`을 반환합니다.

비디렉터리는 decoded underlying dentry, path type, 발견된 index inode로 disconnected overlay dentry를 instantiate합니다. Directory는 연결된 underlying dentry, path type, index를 사용해 connected overlay dentry를 lookup합니다. Disconnected non-directory dentry를 copy up하면 upper alias가 없는 upper index entry가 생깁니다.

Overlay file handle decode
UUID + path type으로 layer 선택Underlying handle을 dentry로 decodeLower handle이면 index 이름 lookupWhiteout이면 `ESTALE`Non-directory: disconnected overlay dentryDirectory: connected overlay dentry lookup

Handle identity를 underlying 객체와 index에 연결해 overlay dentry를 재구성합니다.

여러 lower가 있을 때 middle layer directory의 redirect는 index되지 않습니다. Redirect origin이나 descendant에서 encode한 lower handle만으로 middle·upper directory 또는 connected overlay path를 복구할 수 없습니다. 이를 완화하기 위해 그런 directory는 encode 시 copy up하고 upper handle로 encode합니다.

Upper가 없는 overlay에서는 이 완화가 불가능하므로 NFS export를 사용하려면 `redirect_dir=nofollow`처럼 redirect follow를 꺼야 합니다.

NFS export
----------

When the underlying filesystems supports NFS export and the "nfs_export"
feature is enabled, an overlay filesystem may be exported to NFS.

With the "nfs_export" feature, on copy_up of any lower object, an index
entry is created under the index directory.  The index entry name is the
hexadecimal representation of the copy up origin file handle.  For a
non-directory object, the index entry is a hard link to the upper inode.
For a directory object, the index entry has an extended attribute
"trusted.overlay.upper" with an encoded file handle of the upper
directory inode.

When encoding a file handle from an overlay filesystem object, the
following rules apply:

 1. For a non-upper object, encode a lower file handle from lower inode
 2. For an indexed object, encode a lower file handle from copy_up origin
 3. For a pure-upper object and for an existing non-indexed upper object,
    encode an upper file handle from upper inode

The encoded overlay file handle includes:

 - Header including path type information (e.g. lower/upper)
 - UUID of the underlying filesystem
 - Underlying filesystem encoding of underlying inode

This encoding format is identical to the encoding format file handles that
are stored in extended attribute "trusted.overlay.origin".

When decoding an overlay file handle, the following steps are followed:

 1. Find underlying layer by UUID and path type information.
 2. Decode the underlying filesystem file handle to underlying dentry.
 3. For a lower file handle, lookup the handle in index directory by name.
 4. If a whiteout is found in index, return ESTALE. This represents an
    overlay object that was deleted after its file handle was encoded.
 5. For a non-directory, instantiate a disconnected overlay dentry from the
    decoded underlying dentry, the path type and index inode, if found.
 6. For a directory, use the connected underlying decoded dentry, path type
    and index, to lookup a connected overlay dentry.

Decoding a non-directory file handle may return a disconnected dentry.
copy_up of that disconnected dentry will create an upper index entry with
no upper alias.

When overlay filesystem has multiple lower layers, a middle layer
directory may have a "redirect" to lower directory.  Because middle layer
"redirects" are not indexed, a lower file handle that was encoded from the
"redirect" origin directory, cannot be used to find the middle or upper
layer directory.  Similarly, a lower file handle that was encoded from a
descendant of the "redirect" origin directory, cannot be used to
reconstruct a connected overlay path.  To mitigate the cases of
directories that cannot be decoded from a lower file handle, these
directories are copied up on encode and encoded as an upper file handle.
On an overlay filesystem with no upper layer this mitigation cannot be
used NFS export in this setup requires turning off redirect follow (e.g.
"redirect_dir=nofollow").

NFS export 제한과 UUID 검사 해제

744-761

OverlayFS는 비디렉터리 connectable file handle을 지원하지 않습니다. 따라서 exportfs를 `subtree_check`로 구성하면 NFS를 통한 file lookup이 실패할 수 있습니다.

NFS export를 켜면 mount 시 모든 directory index entry의 upper file handle이 stale인지 검증합니다. 이 검증은 경우에 따라 상당한 overhead를 만들 수 있습니다.

Read-write mount에서 `index=off,nfs_export=on`은 서로 충돌하므로 오류가 발생합니다.

`uuid=off`를 사용하면 file handle의 underlying filesystem UUID를 null로 바꿔 UUID 검사를 사실상 끌 수 있습니다. 기반 disk를 복사하면서 사본 UUID가 바뀐 경우 유용할 수 있습니다. 단, 모든 lower·upper·work directory가 같은 filesystem에 있을 때만 적용되며 그렇지 않으면 정상 동작으로 fallback합니다.

NFS export 주의 조건
조건결과
`subtree_check`Non-directory lookup 실패 가능
Directory index mount 검증Stale upper handle 검사, 큰 overhead 가능
RW + `index=off,nfs_export=on`Option 충돌로 mount 오류
`uuid=off` + 모든 dir가 같은 fsHandle UUID를 null로 바꾸고 검사 해제
`uuid=off` + 서로 다른 fs정상 UUID 동작으로 fallback

File handle 연결성, mount 검증, option 충돌과 UUID 예외입니다.

The overlay filesystem does not support non-directory connectable file
handles, so exporting with the 'subtree_check' exportfs configuration will
cause failures to lookup files over NFS.

When the NFS export feature is enabled, all directory index entries are
verified on mount time to check that upper file handles are not stale.
This verification may cause significant overhead in some cases.

Note: the mount options index=off,nfs_export=on are conflicting for a
read-write mount and will result in an error.

Note: the mount option uuid=off can be used to replace UUID of the underlying
filesystem in file handles with null, and effectively disable UUID checks. This
can be useful in case the underlying disk is copied and the UUID of this copy
is changed. This is only applicable if all lower/upper/work directories are on
the same filesystem, otherwise it will fallback to normal behaviour.

Overlay UUID와 statfs fsid

762-785

OverlayFS instance UUID와 `statfs(2)`가 보고하는 fsid는 `uuid` mount option으로 제어합니다.

`uuid` mount option
Overlay UUID보고 fsid와 동작
`uuid=null`NullTopmost filesystem에서 fsid 사용
`uuid=off`NullTopmost fsid 사용, underlying layer UUID 무시
`uuid=on`생성 후 `trusted.overlay.uuid`에 저장고유하고 persistent한 fsid, xattr 지원 upper 필요
`uuid=auto`xattr이 있으면 사용기본값, 조건에 따라 on으로 upgrade 또는 null로 downgrade

Overlay 자체 UUID, fsid 출처와 underlying UUID 검사 의미입니다.

`uuid=on`은 생성한 OverlayFS UUID를 `trusted.overlay.uuid` xattr에 저장해 고유하고 persistent한 fsid를 제공합니다. 따라서 extended attribute를 지원하는 upper filesystem이 필요합니다.

기본 `uuid=auto`는 `trusted.overlay.uuid`가 있으면 사용합니다. 조건을 만족하는 새 overlay filesystem을 처음 mount할 때 `uuid=on`으로 upgrade하고, 과거에 `uuid=on`으로 mount된 적 없는 기존 overlay는 `uuid=null`로 downgrade합니다.

UUID and fsid
-------------

The UUID of overlayfs instance itself and the fsid reported by statfs(2) are
controlled by the "uuid" mount option, which supports these values:

- "null":
    UUID of overlayfs is null. fsid is taken from upper most filesystem.
- "off":
    UUID of overlayfs is null. fsid is taken from upper most filesystem.
    UUID of underlying layers is ignored.
- "on":
    UUID of overlayfs is generated and used to report a unique fsid.
    UUID is stored in xattr "trusted.overlay.uuid", making overlayfs fsid
    unique and persistent.  This option requires an overlayfs with upper
    filesystem that supports xattrs.
- "auto": (default)
    UUID is taken from xattr "trusted.overlay.uuid" if it exists.
    Upgrade to "uuid=on" on first time mount of new overlay filesystem that
    meets the prerequisites.
    Downgrade to "uuid=null" for existing overlay filesystems that were never
    mounted with "uuid=on".

Copy-up 내구성과 fsync 정책

786-835

`fsync(2)`는 file data와 metadata를 backing storage에 안전하게 기록해 system crash 뒤에도 정보가 존재하도록 보장합니다. Fsync 없이 crash가 나면 관찰되는 data가 반드시 이전 또는 새 값이라는 보장은 없고 실제로는 이전 값, 새 값, 둘의 혼합일 수 있습니다.

Overlay file을 처음 수정하면 copy up이 lower file과 parent directory를 upper에 만듭니다. Linux filesystem API는 명시적 fsync가 없을 때 저장 순서를 강제하지 않으므로 crash 뒤 upper file data가 전부 zero가 되는 이례적인 결과도 가능합니다.

이를 막기 위해 OverlayFS는 data copy up을 `rename(2)` 또는 `link(2)`로 atomic하게 완료하기 전에 upper file에 `fsync(2)`를 호출합니다. 기본 설정은 copied-up directory나 metadata-only copy up에는 명시적으로 fsync하지 않으므로 사용자가 fsync를 호출하지 않으면 수정의 영속성을 보장하지 않습니다.

Copy-up 중 fsync는 crash 뒤 copy up이 보인다면 그 data가 zero나 staging area의 intermediate 값은 아니라는 것만 보장합니다. Ext4, XFS 같은 단일 journal 로컬 파일시스템에서는 file fsync가 같은 transaction의 parent directory 변경도 보통 영속화하므로 metadata 내구성이 사실상 함께 따라옵니다. OverlayFS는 network filesystem을 upper로 금지해 위험을 더 줄입니다.

Atomic data copy up
Lower file과 parent를 upper staging에 copyUpper file data·metadata 기록Upper file에 `fsync(2)``rename(2)` 또는 `link(2)`Atomic copy-up 완료Crash 후 보이면 zero·intermediate data가 아님

완성되지 않은 upper data가 노출되는 것을 file fsync와 rename·link로 막습니다.

`fsync` mount option
동작
`fsync=auto`기본값, data copy up 완료 전 upper file fsync; directory·metadata-only는 생략
`fsync=strict`모든 copy up 완료 전 upper file과 directory fsync
`fsync=volatile`내구성보다 성능 우선
`volatile``fsync=volatile`의 alias

성능과 copy-up 내구성 범위를 선택합니다.

Durability and copy up
----------------------

The fsync(2) system call ensures that the data and metadata of a file
are safely written to the backing storage, which is expected to
guarantee the existence of the information post system crash.

Without an fsync(2) call, there is no guarantee that the observed
data after a system crash will be either the old or the new data, but
in practice, the observed data after crash is often the old or new data
or a mix of both.

When an overlayfs file is modified for the first time, copy up will
create a copy of the lower file and its parent directories in the upper
layer.  Since the Linux filesystem API does not enforce any particular
ordering on storing changes without explicit fsync(2) calls, in case
of a system crash, the upper file could end up with no data at all
(i.e. zeros), which would be an unusual outcome.  To avoid this
experience, overlayfs calls fsync(2) on the upper file before completing
data copy up with rename(2) or link(2) to make the copy up "atomic".

By default, overlayfs does not explicitly call fsync(2) on copied up
directories or on metadata-only copy up, so it provides no guarantee to
persist the user's modification unless the user calls fsync(2).
The fsync during copy up only guarantees that if a copy up is observed
after a crash, the observed data is not zeroes or intermediate values
from the copy up staging area.

On traditional local filesystems with a single journal (e.g. ext4, xfs),
fsync on a file also persists the parent directory changes, because they
are usually modified in the same transaction, so metadata durability during
data copy up effectively comes for free.  Overlayfs further limits risk by
disallowing network filesystems as upper layer.

Overlayfs can be tuned to prefer performance or durability when storing
to the underlying upper layer.  This is controlled by the "fsync" mount
option, which supports these values:

- "auto": (default)
    Call fsync(2) on upper file before completion of data copy up.
    No explicit fsync(2) on directory or metadata-only copy up.
- "strict":
    Call fsync(2) on upper file and directories before completion of any
    copy up.
- "volatile": [*]
    Prefer performance over durability (see `Volatile mount`_)

[*] The mount option "volatile" is an alias to "fsync=volatile".

Volatile mount의 실패 의미

836-863

`volatile` mount는 crash 생존을 보장하지 않습니다. Overlay에 쓴 data를 큰 노력 없이 다시 만들 수 있는 경우에만 사용해야 합니다. 장점은 upper filesystem에 대한 모든 형태의 sync 호출을 생략한다는 것입니다.

안전하다는 잘못된 인상을 주지 않도록 volatile mount의 `syncfs`와 `fsync` 의미는 일반 VFS와 다릅니다. Mount 뒤 upperdir filesystem에서 writeback error가 하나라도 발생하면 모든 sync 함수가 오류를 반환합니다. 이 상태는 회복되지 않으며 이후 새 upperdir 오류가 없어도 모든 sync가 계속 실패합니다.

Volatile writeback 오류 고착
`volatile` mountUpper sync 호출 생략Upper filesystem writeback error 발생모든 `syncfs`·`fsync`가 오류 반환Mount 수명 동안 상태 회복 안 됨

한 번 관찰된 upper writeback 오류는 이후 모든 sync 호출의 영구 오류가 됩니다.

Volatile로 mount하면 `$workdir/work/incompat/volatile` 디렉터리를 만듭니다. 다음 mount는 이 디렉터리가 있으면 거부합니다. 이는 upper와 work directory를 버리고 새로 만들어야 한다는 강한 신호입니다.

System이 crash하지 않았고 upperdir 내용이 온전함을 사용자가 확실히 아는 매우 제한된 경우에만 `volatile` 디렉터리를 제거할 수 있습니다.

Volatile 재마운트 판단
상태조치
`$workdir/work/incompat/volatile` 존재재마운트 거부
Crash 가능성 있음Upper와 workdir를 폐기하고 새로 생성
Crash 없음·upper 무결성 확실제한적으로 marker 제거 가능

Incompat marker를 안전 신호로 해석합니다.

Volatile mount
--------------

This is enabled with the "volatile" mount option.  Volatile mounts are not
guaranteed to survive a crash.  It is strongly recommended that volatile
mounts are only used if data written to the overlay can be recreated
without significant effort.

The advantage of mounting with the "volatile" option is that all forms of
sync calls to the upper filesystem are omitted.

In order to avoid giving a false sense of safety, the syncfs (and fsync)
semantics of volatile mounts are slightly different than that of the rest of
VFS.  If any writeback error occurs on the upperdir's filesystem after a
volatile mount takes place, all sync functions will return an error.  Once this
condition is reached, the filesystem will not recover, and every subsequent sync
call will return an error, even if the upperdir has not experienced a new error
since the last sync call.

When overlay is mounted with "volatile" option, the directory
"$workdir/work/incompat/volatile" is created.  During next mount, overlay
checks for this directory and refuses to mount if present. This is a strong
indicator that the user should discard upper and work directories and create
fresh ones. In very limited cases where the user knows that the system has
not crashed and contents of upperdir are intact, the "volatile" directory
can be removed.

User xattr namespace와 testsuite

864-883

`-o userxattr` mount option은 OverlayFS가 `trusted.overlay.` 대신 `user.overlay.` xattr namespace를 사용하도록 강제합니다. 특권이 없는 사용자가 OverlayFS를 mount할 때 유용합니다.

OverlayFS xattr namespace
설정Namespace용도
기본`trusted.overlay.`특권 mount와 내부 metadata
`-o userxattr``user.overlay.`Unprivileged OverlayFS mount

Mount 권한 모델에 따라 사용하는 namespace가 달라집니다.

Testsuite는 David Howells가 처음 개발했고 현재 Amir Goldstein이 유지합니다. 원문 저장소는 `https://github.com/amir73il/unionmount-testsuite.git`입니다. Root 권한으로 저장소 디렉터리에 들어가 `./run --ov --verify`를 실행합니다.

# cd unionmount-testsuite
# ./run --ov --verify
User xattr
----------

The "-o userxattr" mount option forces overlayfs to use the
"user.overlay." xattr namespace instead of "trusted.overlay.".  This is
useful for unprivileged mounting of overlayfs.


Testsuite
---------

There's a testsuite originally developed by David Howells and currently
maintained by Amir Goldstein at:

https://github.com/amir73il/unionmount-testsuite.git

Run as root::

  # cd unionmount-testsuite
  # ./run --ov --verify