← Documents Documentation/filesystems/caching/cachefiles.rst GitHub 원문 ↗

Linux 6.18.37 · Filesystems

Cache on Already Mounted Filesystem

CacheFiles 구성, culling, 디스크 이름 구조, SELinux credential 분리와 on-demand read protocol 전문 번역입니다.

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

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

1. 요약·해설

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

요약·해설

cachefiles.rst:1-662

CacheFiles는 이미 마운트된 로컬 파일시스템의 디렉터리를 FS-Cache backing store로 사용합니다. 커널 모듈은 data I/O와 객체 상태를 관리하고 `cachefilesd`는 `/dev/cachefiles`를 통해 구성·scan·LRU culling·graveyard 삭제를 담당합니다. block과 file 수에 run/cull/stop hysteresis를 적용해 활성 데이터와 공간을 공유합니다.

On-demand read 모드에서는 cache miss의 데이터 fetch와 write를 사용자 데몬에 위임합니다. OPEN은 key와 anonymous fd를 전달하고, READ는 offset·length를 요청하며, CLOSE는 object ID의 fd 정리를 지시합니다. 모든 pending 요청은 고유 `msg_id`로 연결됩니다.

CacheFiles 전체 흐름
`cachefilesd`가 `/dev/cachefiles`를 열고 구성 전달커널 CacheFiles가 FS-Cache에 bind객체를 encoded key와 xattr로 backing filesystem에 저장데몬이 LRU culling과 graveyard 삭제 수행On-demand OPEN으로 key·anonymous fd 전달READ miss를 데몬이 채우고 ioctl로 완료CLOSE에서 object ID의 모든 fd 정리

로컬 backing cache의 시작, 공간 관리와 on-demand I/O 경로입니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 ===================================
4 Cache on Already Mounted Filesystem
5 ===================================
6
7 .. Contents:
8
9 (*) Overview.
10
11 (*) Requirements.
12
13 (*) Configuration.
14
15 (*) Starting the cache.
16
17 (*) Things to avoid.
18
19 (*) Cache culling.
20
21 (*) Cache structure.
22
23 (*) Security model and SELinux.
24
25 (*) A note on security.
26
27 (*) Statistical information.
28
29 (*) Debugging.
30
31 (*) On-demand Read.
32
33
34 Overview
35 ========
36
37 CacheFiles is a caching backend that's meant to use as a cache a directory on
38 an already mounted filesystem of a local type (such as Ext3).
39
40 CacheFiles uses a userspace daemon to do some of the cache management - such as
41 reaping stale nodes and culling. This is called cachefilesd and lives in
42 /sbin.
43
44 The filesystem and data integrity of the cache are only as good as those of the
45 filesystem providing the backing services. Note that CacheFiles does not
46 attempt to journal anything since the journalling interfaces of the various
47 filesystems are very specific in nature.
48
49 CacheFiles creates a misc character device - "/dev/cachefiles" - that is used
50 to communication with the daemon. Only one thing may have this open at once,
51 and while it is open, a cache is at least partially in existence. The daemon
52 opens this and sends commands down it to control the cache.
53
54 CacheFiles is currently limited to a single cache.
55
56 CacheFiles attempts to maintain at least a certain percentage of free space on
57 the filesystem, shrinking the cache by culling the objects it contains to make
58 space if necessary - see the "Cache Culling" section. This means it can be
59 placed on the same medium as a live set of data, and will expand to make use of
60 spare space and automatically contract when the set of data requires more
61 space.
62
63
64
65 Requirements
66 ============
67
68 The use of CacheFiles and its daemon requires the following features to be
69 available in the system and in the cache filesystem:
70
71 - dnotify.
72
73 - extended attributes (xattrs).
74
75 - openat() and friends.
76
77 - bmap() support on files in the filesystem (FIBMAP ioctl).
78
79 - The use of bmap() to detect a partial page at the end of the file.
80
81 It is strongly recommended that the "dir_index" option is enabled on Ext3
82 filesystems being used as a cache.
83
84
85 Configuration
86 =============
87
88 The cache is configured by a script in /etc/cachefilesd.conf. These commands
89 set up cache ready for use. The following script commands are available:
90
91 brun <N>%, bcull <N>%, bstop <N>%, frun <N>%, fcull <N>%, fstop <N>%
92 Configure the culling limits. Optional. See the section on culling
93 The defaults are 7% (run), 5% (cull) and 1% (stop) respectively.
94
95 The commands beginning with a 'b' are file space (block) limits, those
96 beginning with an 'f' are file count limits.
97
98 dir <path>
99 Specify the directory containing the root of the cache. Mandatory.
100
101 tag <name>
102 Specify a tag to FS-Cache to use in distinguishing multiple caches.
103 Optional. The default is "CacheFiles".
104
105 debug <mask>
106 Specify a numeric bitmask to control debugging in the kernel module.
107 Optional. The default is zero (all off). The following values can be
108 OR'd into the mask to collect various information:
109
110 == =================================================
111 1 Turn on trace of function entry (_enter() macros)
112 2 Turn on trace of function exit (_leave() macros)
113 4 Turn on trace of internal debug points (_debug())
114 == =================================================
115
116 This mask can also be set through sysfs, eg::
117
118 echo 5 > /sys/module/cachefiles/parameters/debug
119
120
121 Starting the Cache
122 ==================
123
124 The cache is started by running the daemon. The daemon opens the cache device,
125 configures the cache and tells it to begin caching. At that point the cache
126 binds to fscache and the cache becomes live.
127
128 The daemon is run as follows::
129
130 /sbin/cachefilesd [-d]* [-s] [-n] [-f <configfile>]
131
132 The flags are:
133
134 ``-d``
135 Increase the debugging level. This can be specified multiple times and
136 is cumulative with itself.
137
138 ``-s``
139 Send messages to stderr instead of syslog.
140
141 ``-n``
142 Don't daemonise and go into background.
143
144 ``-f <configfile>``
145 Use an alternative configuration file rather than the default one.
146
147
148 Things to Avoid
149 ===============
150
151 Do not mount other things within the cache as this will cause problems. The
152 kernel module contains its own very cut-down path walking facility that ignores
153 mountpoints, but the daemon can't avoid them.
154
155 Do not create, rename or unlink files and directories in the cache while the
156 cache is active, as this may cause the state to become uncertain.
157
158 Renaming files in the cache might make objects appear to be other objects (the
159 filename is part of the lookup key).
160
161 Do not change or remove the extended attributes attached to cache files by the
162 cache as this will cause the cache state management to get confused.
163
164 Do not create files or directories in the cache, lest the cache get confused or
165 serve incorrect data.
166
167 Do not chmod files in the cache. The module creates things with minimal
168 permissions to prevent random users being able to access them directly.
169
170
171 Cache Culling
172 =============
173
174 The cache may need culling occasionally to make space. This involves
175 discarding objects from the cache that have been used less recently than
176 anything else. Culling is based on the access time of data objects. Empty
177 directories are culled if not in use.
178
179 Cache culling is done on the basis of the percentage of blocks and the
180 percentage of files available in the underlying filesystem. There are six
181 "limits":
182
183 brun, frun
184 If the amount of free space and the number of available files in the cache
185 rises above both these limits, then culling is turned off.
186
187 bcull, fcull
188 If the amount of available space or the number of available files in the
189 cache falls below either of these limits, then culling is started.
190
191 bstop, fstop
192 If the amount of available space or the number of available files in the
193 cache falls below either of these limits, then no further allocation of
194 disk space or files is permitted until culling has raised things above
195 these limits again.
196
197 These must be configured thusly::
198
199 0 <= bstop < bcull < brun < 100
200 0 <= fstop < fcull < frun < 100
201
202 Note that these are percentages of available space and available files, and do
203 _not_ appear as 100 minus the percentage displayed by the "df" program.
204
205 The userspace daemon scans the cache to build up a table of cullable objects.
206 These are then culled in least recently used order. A new scan of the cache is
207 started as soon as space is made in the table. Objects will be skipped if
208 their atimes have changed or if the kernel module says it is still using them.
209
210
211 Cache Structure
212 ===============
213
214 The CacheFiles module will create two directories in the directory it was
215 given:
216
217 * cache/
218 * graveyard/
219
220 The active cache objects all reside in the first directory. The CacheFiles
221 kernel module moves any retired or culled objects that it can't simply unlink
222 to the graveyard from which the daemon will actually delete them.
223
224 The daemon uses dnotify to monitor the graveyard directory, and will delete
225 anything that appears therein.
226
227
228 The module represents index objects as directories with the filename "I..." or
229 "J...". Note that the "cache/" directory is itself a special index.
230
231 Data objects are represented as files if they have no children, or directories
232 if they do. Their filenames all begin "D..." or "E...". If represented as a
233 directory, data objects will have a file in the directory called "data" that
234 actually holds the data.
235
236 Special objects are similar to data objects, except their filenames begin
237 "S..." or "T...".
238
239
240 If an object has children, then it will be represented as a directory.
241 Immediately in the representative directory are a collection of directories
242 named for hash values of the child object keys with an '@' prepended. Into
243 this directory, if possible, will be placed the representations of the child
244 objects::
245
246 /INDEX /INDEX /INDEX /DATA FILES
247 /=========/==========/=================================/================
248 cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400
249 cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...DB1ry
250 cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...N22ry
251 cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...FP1ry
252
253
254 If the key is so long that it exceeds NAME_MAX with the decorations added on to
255 it, then it will be cut into pieces, the first few of which will be used to
256 make a nest of directories, and the last one of which will be the objects
257 inside the last directory. The names of the intermediate directories will have
258 '+' prepended::
259
260 J1223/@23/+xy...z/+kl...m/Epqr
261
262
263 Note that keys are raw data, and not only may they exceed NAME_MAX in size,
264 they may also contain things like '/' and NUL characters, and so they may not
265 be suitable for turning directly into a filename.
266
267 To handle this, CacheFiles will use a suitably printable filename directly and
268 "base-64" encode ones that aren't directly suitable. The two versions of
269 object filenames indicate the encoding:
270
271 =============== =============== ===============
272 OBJECT TYPE PRINTABLE ENCODED
273 =============== =============== ===============
274 Index "I..." "J..."
275 Data "D..." "E..."
276 Special "S..." "T..."
277 =============== =============== ===============
278
279 Intermediate directories are always "@" or "+" as appropriate.
280
281
282 Each object in the cache has an extended attribute label that holds the object
283 type ID (required to distinguish special objects) and the auxiliary data from
284 the netfs. The latter is used to detect stale objects in the cache and update
285 or retire them.
286
287
288 Note that CacheFiles will erase from the cache any file it doesn't recognise or
289 any file of an incorrect type (such as a FIFO file or a device file).
290
291
292 Security Model and SELinux
293 ==========================
294
295 CacheFiles is implemented to deal properly with the LSM security features of
296 the Linux kernel and the SELinux facility.
297
298 One of the problems that CacheFiles faces is that it is generally acting on
299 behalf of a process, and running in that process's context, and that includes a
300 security context that is not appropriate for accessing the cache - either
301 because the files in the cache are inaccessible to that process, or because if
302 the process creates a file in the cache, that file may be inaccessible to other
303 processes.
304
305 The way CacheFiles works is to temporarily change the security context (fsuid,
306 fsgid and actor security label) that the process acts as - without changing the
307 security context of the process when it the target of an operation performed by
308 some other process (so signalling and suchlike still work correctly).
309
310
311 When the CacheFiles module is asked to bind to its cache, it:
312
313 (1) Finds the security label attached to the root cache directory and uses
314 that as the security label with which it will create files. By default,
315 this is::
316
317 cachefiles_var_t
318
319 (2) Finds the security label of the process which issued the bind request
320 (presumed to be the cachefilesd daemon), which by default will be::
321
322 cachefilesd_t
323
324 and asks LSM to supply a security ID as which it should act given the
325 daemon's label. By default, this will be::
326
327 cachefiles_kernel_t
328
329 SELinux transitions the daemon's security ID to the module's security ID
330 based on a rule of this form in the policy::
331
332 type_transition <daemon's-ID> kernel_t : process <module's-ID>;
333
334 For instance::
335
336 type_transition cachefilesd_t kernel_t : process cachefiles_kernel_t;
337
338
339 The module's security ID gives it permission to create, move and remove files
340 and directories in the cache, to find and access directories and files in the
341 cache, to set and access extended attributes on cache objects, and to read and
342 write files in the cache.
343
344 The daemon's security ID gives it only a very restricted set of permissions: it
345 may scan directories, stat files and erase files and directories. It may
346 not read or write files in the cache, and so it is precluded from accessing the
347 data cached therein; nor is it permitted to create new files in the cache.
348
349
350 There are policy source files available in:
351
352 https://people.redhat.com/~dhowells/fscache/cachefilesd-0.8.tar.bz2
353
354 and later versions. In that tarball, see the files::
355
356 cachefilesd.te
357 cachefilesd.fc
358 cachefilesd.if
359
360 They are built and installed directly by the RPM.
361
362 If a non-RPM based system is being used, then copy the above files to their own
363 directory and run::
364
365 make -f /usr/share/selinux/devel/Makefile
366 semodule -i cachefilesd.pp
367
368 You will need checkpolicy and selinux-policy-devel installed prior to the
369 build.
370
371
372 By default, the cache is located in /var/fscache, but if it is desirable that
373 it should be elsewhere, than either the above policy files must be altered, or
374 an auxiliary policy must be installed to label the alternate location of the
375 cache.
376
377 For instructions on how to add an auxiliary policy to enable the cache to be
378 located elsewhere when SELinux is in enforcing mode, please see::
379
380 /usr/share/doc/cachefilesd-*/move-cache.txt
381
382 When the cachefilesd rpm is installed; alternatively, the document can be found
383 in the sources.
384
385
386 A Note on Security
387 ==================
388
389 CacheFiles makes use of the split security in the task_struct. It allocates
390 its own task_security structure, and redirects current->cred to point to it
391 when it acts on behalf of another process, in that process's context.
392
393 The reason it does this is that it calls vfs_mkdir() and suchlike rather than
394 bypassing security and calling inode ops directly. Therefore the VFS and LSM
395 may deny the CacheFiles access to the cache data because under some
396 circumstances the caching code is running in the security context of whatever
397 process issued the original syscall on the netfs.
398
399 Furthermore, should CacheFiles create a file or directory, the security
400 parameters with that object is created (UID, GID, security label) would be
401 derived from that process that issued the system call, thus potentially
402 preventing other processes from accessing the cache - including CacheFiles's
403 cache management daemon (cachefilesd).
404
405 What is required is to temporarily override the security of the process that
406 issued the system call. We can't, however, just do an in-place change of the
407 security data as that affects the process as an object, not just as a subject.
408 This means it may lose signals or ptrace events for example, and affects what
409 the process looks like in /proc.
410
411 So CacheFiles makes use of a logical split in the security between the
412 objective security (task->real_cred) and the subjective security (task->cred).
413 The objective security holds the intrinsic security properties of a process and
414 is never overridden. This is what appears in /proc, and is what is used when a
415 process is the target of an operation by some other process (SIGKILL for
416 example).
417
418 The subjective security holds the active security properties of a process, and
419 may be overridden. This is not seen externally, and is used when a process
420 acts upon another object, for example SIGKILLing another process or opening a
421 file.
422
423 LSM hooks exist that allow SELinux (or Smack or whatever) to reject a request
424 for CacheFiles to run in a context of a specific security label, or to create
425 files and directories with another security label.
426
427
428 Statistical Information
429 =======================
430
431 If FS-Cache is compiled with the following option enabled::
432
433 CONFIG_CACHEFILES_HISTOGRAM=y
434
435 then it will gather certain statistics and display them through a proc file.
436
437 /proc/fs/cachefiles/histogram
438
439 ::
440
441 cat /proc/fs/cachefiles/histogram
442 JIFS SECS LOOKUPS MKDIRS CREATES
443 ===== ===== ========= ========= =========
444
445 This shows the breakdown of the number of times each amount of time
446 between 0 jiffies and HZ-1 jiffies a variety of tasks took to run. The
447 columns are as follows:
448
449 ======= =======================================================
450 COLUMN TIME MEASUREMENT
451 ======= =======================================================
452 LOOKUPS Length of time to perform a lookup on the backing fs
453 MKDIRS Length of time to perform a mkdir on the backing fs
454 CREATES Length of time to perform a create on the backing fs
455 ======= =======================================================
456
457 Each row shows the number of events that took a particular range of times.
458 Each step is 1 jiffy in size. The JIFS column indicates the particular
459 jiffy range covered, and the SECS field the equivalent number of seconds.
460
461
462 Debugging
463 =========
464
465 If CONFIG_CACHEFILES_DEBUG is enabled, the CacheFiles facility can have runtime
466 debugging enabled by adjusting the value in::
467
468 /sys/module/cachefiles/parameters/debug
469
470 This is a bitmask of debugging streams to enable:
471
472 ======= ======= =============================== =======================
473 BIT VALUE STREAM POINT
474 ======= ======= =============================== =======================
475 0 1 General Function entry trace
476 1 2 Function exit trace
477 2 4 General
478 ======= ======= =============================== =======================
479
480 The appropriate set of values should be OR'd together and the result written to
481 the control file. For example::
482
483 echo $((1|4|8)) >/sys/module/cachefiles/parameters/debug
484
485 will turn on all function entry debugging.
486
487
488 On-demand Read
489 ==============
490
491 When working in its original mode, CacheFiles serves as a local cache for a
492 remote networking fs - while in on-demand read mode, CacheFiles can boost the
493 scenario where on-demand read semantics are needed, e.g. container image
494 distribution.
495
496 The essential difference between these two modes is seen when a cache miss
497 occurs: In the original mode, the netfs will fetch the data from the remote
498 server and then write it to the cache file; in on-demand read mode, fetching
499 the data and writing it into the cache is delegated to a user daemon.
500
501 ``CONFIG_CACHEFILES_ONDEMAND`` should be enabled to support on-demand read mode.
502
503
504 Protocol Communication
505 ----------------------
506
507 The on-demand read mode uses a simple protocol for communication between kernel
508 and user daemon. The protocol can be modeled as::
509
510 kernel --[request]--> user daemon --[reply]--> kernel
511
512 CacheFiles will send requests to the user daemon when needed. The user daemon
513 should poll the devnode ('/dev/cachefiles') to check if there's a pending
514 request to be processed. A POLLIN event will be returned when there's a pending
515 request.
516
517 The user daemon then reads the devnode to fetch a request to process. It should
518 be noted that each read only gets one request. When it has finished processing
519 the request, the user daemon should write the reply to the devnode.
520
521 Each request starts with a message header of the form::
522
523 struct cachefiles_msg {
524 __u32 msg_id;
525 __u32 opcode;
526 __u32 len;
527 __u32 object_id;
528 __u8 data[];
529 };
530
531 where:
532
533 * ``msg_id`` is a unique ID identifying this request among all pending
534 requests.
535
536 * ``opcode`` indicates the type of this request.
537
538 * ``object_id`` is a unique ID identifying the cache file operated on.
539
540 * ``data`` indicates the payload of this request.
541
542 * ``len`` indicates the whole length of this request, including the
543 header and following type-specific payload.
544
545
546 Turning on On-demand Mode
547 -------------------------
548
549 An optional parameter becomes available to the "bind" command::
550
551 bind [ondemand]
552
553 When the "bind" command is given no argument, it defaults to the original mode.
554 When it is given the "ondemand" argument, i.e. "bind ondemand", on-demand read
555 mode will be enabled.
556
557
558 The OPEN Request
559 ----------------
560
561 When the netfs opens a cache file for the first time, a request with the
562 CACHEFILES_OP_OPEN opcode, a.k.a an OPEN request will be sent to the user
563 daemon. The payload format is of the form::
564
565 struct cachefiles_open {
566 __u32 volume_key_size;
567 __u32 cookie_key_size;
568 __u32 fd;
569 __u32 flags;
570 __u8 data[];
571 };
572
573 where:
574
575 * ``data`` contains the volume_key followed directly by the cookie_key.
576 The volume key is a NUL-terminated string; the cookie key is binary
577 data.
578
579 * ``volume_key_size`` indicates the size of the volume key in bytes.
580
581 * ``cookie_key_size`` indicates the size of the cookie key in bytes.
582
583 * ``fd`` indicates an anonymous fd referring to the cache file, through
584 which the user daemon can perform write/llseek file operations on the
585 cache file.
586
587
588 The user daemon can use the given (volume_key, cookie_key) pair to distinguish
589 the requested cache file. With the given anonymous fd, the user daemon can
590 fetch the data and write it to the cache file in the background, even when
591 kernel has not triggered a cache miss yet.
592
593 Be noted that each cache file has a unique object_id, while it may have multiple
594 anonymous fds. The user daemon may duplicate anonymous fds from the initial
595 anonymous fd indicated by the @fd field through dup(). Thus each object_id can
596 be mapped to multiple anonymous fds, while the usr daemon itself needs to
597 maintain the mapping.
598
599 When implementing a user daemon, please be careful of RLIMIT_NOFILE,
600 ``/proc/sys/fs/nr_open`` and ``/proc/sys/fs/file-max``. Typically these needn't
601 be huge since they're related to the number of open device blobs rather than
602 open files of each individual filesystem.
603
604 The user daemon should reply the OPEN request by issuing a "copen" (complete
605 open) command on the devnode::
606
607 copen <msg_id>,<cache_size>
608
609 where:
610
611 * ``msg_id`` must match the msg_id field of the OPEN request.
612
613 * When >= 0, ``cache_size`` indicates the size of the cache file;
614 when < 0, ``cache_size`` indicates any error code encountered by the
615 user daemon.
616
617
618 The CLOSE Request
619 -----------------
620
621 When a cookie withdrawn, a CLOSE request (opcode CACHEFILES_OP_CLOSE) will be
622 sent to the user daemon. This tells the user daemon to close all anonymous fds
623 associated with the given object_id. The CLOSE request has no extra payload,
624 and shouldn't be replied.
625
626
627 The READ Request
628 ----------------
629
630 When a cache miss is encountered in on-demand read mode, CacheFiles will send a
631 READ request (opcode CACHEFILES_OP_READ) to the user daemon. This tells the user
632 daemon to fetch the contents of the requested file range. The payload is of the
633 form::
634
635 struct cachefiles_read {
636 __u64 off;
637 __u64 len;
638 };
639
640 where:
641
642 * ``off`` indicates the starting offset of the requested file range.
643
644 * ``len`` indicates the length of the requested file range.
645
646
647 When it receives a READ request, the user daemon should fetch the requested data
648 and write it to the cache file identified by object_id.
649
650 When it has finished processing the READ request, the user daemon should reply
651 by using the CACHEFILES_IOC_READ_COMPLETE ioctl on one of the anonymous fds
652 associated with the object_id given in the READ request. The ioctl is of the
653 form::
654
655 ioctl(fd, CACHEFILES_IOC_READ_COMPLETE, msg_id);
656
657 where:
658
659 * ``fd`` is one of the anonymous fds associated with the object_id
660 given.
661
662 * ``msg_id`` must match the msg_id field of the READ request.
663

3. 한국어 전문 번역

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

문서 구성

1-33

이 문서는 이미 마운트된 로컬 파일시스템 위에 CacheFiles 캐시를 구성하는 방법을 설명합니다.

다루는 주제는 개요, 요구 사항, 구성, 캐시 시작, 피해야 할 작업, cache culling, 캐시 구조, 보안 모델과 SELinux, 보안 구현 참고, 통계 정보, 디버깅, on-demand read입니다.

CacheFiles 문서 영역
영역주제
설치·운영요구 사항, 구성, 시작, 금지 작업
공간 관리culling 한계와 디스크 구조
보안·진단SELinux, credential 분리, 통계, debugging
On-demandkernel-daemon protocol과 OPEN/CLOSE/READ

설정부터 운영과 on-demand protocol까지의 구성을 묶었습니다.

.. SPDX-License-Identifier: GPL-2.0

===================================
Cache on Already Mounted Filesystem
===================================

.. Contents:

 (*) Overview.

 (*) Requirements.

 (*) Configuration.

 (*) Starting the cache.

 (*) Things to avoid.

 (*) Cache culling.

 (*) Cache structure.

 (*) Security model and SELinux.

 (*) A note on security.

 (*) Statistical information.

 (*) Debugging.

 (*) On-demand Read.

개요

34-64

CacheFiles는 Ext3 같은 로컬 형식의 이미 마운트된 파일시스템에 있는 디렉터리를 캐시로 사용하는 FS-Cache 백엔드입니다.

오래된 노드 제거와 culling 같은 캐시 관리 일부는 `/sbin`에 있는 사용자 공간 데몬 `cachefilesd`가 수행합니다.

캐시의 파일시스템 무결성과 데이터 무결성은 backing service를 제공하는 파일시스템의 수준을 넘지 못합니다. 파일시스템별 journal interface가 매우 특수하므로 CacheFiles 자체는 아무것도 journal하려 하지 않습니다.

CacheFiles는 데몬과 통신하는 miscellaneous 문자 장치 `/dev/cachefiles`를 만듭니다. 한 번에 하나의 주체만 이 장치를 열 수 있고, 열려 있는 동안 캐시는 최소한 부분적으로 존재합니다. 데몬은 장치를 열고 명령을 보내 캐시를 제어합니다.

현재 CacheFiles는 캐시 하나만 지원합니다.

CacheFiles는 backing 파일시스템에 일정 비율 이상의 여유 공간을 유지하려 합니다. 필요하면 캐시 객체를 cull하여 공간을 만듭니다. 따라서 활성 데이터와 같은 매체에 캐시를 둘 수 있으며, 남는 공간을 사용하도록 확장되었다가 활성 데이터가 더 많은 공간을 필요로 하면 자동으로 축소됩니다.

CacheFiles의 역할 분담
로컬 파일시스템의 캐시 디렉터리커널 CacheFiles가 FS-Cache 데이터 I/O 수행`/dev/cachefiles`로 제어 요청 교환`cachefilesd`가 scan·cull·graveyard 삭제여유 공간 임계치에 따라 캐시 자동 확장·축소

커널 백엔드와 사용자 공간 데몬이 하나의 로컬 캐시를 관리합니다.

Overview
========

CacheFiles is a caching backend that's meant to use as a cache a directory on
an already mounted filesystem of a local type (such as Ext3).

CacheFiles uses a userspace daemon to do some of the cache management - such as
reaping stale nodes and culling.  This is called cachefilesd and lives in
/sbin.

The filesystem and data integrity of the cache are only as good as those of the
filesystem providing the backing services.  Note that CacheFiles does not
attempt to journal anything since the journalling interfaces of the various
filesystems are very specific in nature.

CacheFiles creates a misc character device - "/dev/cachefiles" - that is used
to communication with the daemon.  Only one thing may have this open at once,
and while it is open, a cache is at least partially in existence.  The daemon
opens this and sends commands down it to control the cache.

CacheFiles is currently limited to a single cache.

CacheFiles attempts to maintain at least a certain percentage of free space on
the filesystem, shrinking the cache by culling the objects it contains to make
space if necessary - see the "Cache Culling" section.  This means it can be
placed on the same medium as a live set of data, and will expand to make use of
spare space and automatically contract when the set of data requires more
space.


요구 사항

65-84

CacheFiles와 데몬을 사용하려면 시스템과 캐시 파일시스템에 `dnotify`, extended attribute(xattr), `openat()` 계열 함수, 파일에 대한 `bmap()` 지원인 `FIBMAP` ioctl이 있어야 합니다.

파일 끝의 부분 page를 감지할 때 `bmap()`을 사용할 수 있어야 합니다.

캐시로 사용하는 Ext3 파일시스템에서는 `dir_index` 옵션을 활성화할 것을 강력히 권장합니다.

CacheFiles 기반 기능
기능사용 목적
`dnotify`graveyard 등 디렉터리 변화 감시
xattr객체 형식과 coherency 보조 데이터 저장
`openat()` 계열디렉터리 기준 안전한 경로 작업
`bmap()` / `FIBMAP`블록 매핑과 파일 끝 부분 page 감지
Ext3 `dir_index`큰 캐시 디렉터리 조회 성능

백엔드 파일시스템과 시스템이 제공해야 하는 기능입니다.

Requirements
============

The use of CacheFiles and its daemon requires the following features to be
available in the system and in the cache filesystem:

        - dnotify.

        - extended attributes (xattrs).

        - openat() and friends.

        - bmap() support on files in the filesystem (FIBMAP ioctl).

        - The use of bmap() to detect a partial page at the end of the file.

It is strongly recommended that the "dir_index" option is enabled on Ext3
filesystems being used as a cache.

`/etc/cachefilesd.conf` 구성

85-120

캐시는 `/etc/cachefilesd.conf`의 script 명령으로 구성합니다. 이 명령들이 캐시를 사용할 준비 상태로 만듭니다.

`brun N%`, `bcull N%`, `bstop N%`, `frun N%`, `fcull N%`, `fstop N%`는 선택적인 culling 한계를 설정합니다. 기본값은 각각 run 7%, cull 5%, stop 1%입니다. `b`로 시작하는 명령은 파일 공간인 block 한계이고, `f`로 시작하는 명령은 사용 가능한 파일 수 한계입니다.

필수 `dir <path>`는 캐시 루트를 포함하는 디렉터리를 지정합니다.

선택적 `tag <name>`은 여러 캐시를 구별하도록 FS-Cache에 전달할 tag를 지정합니다. 기본값은 `CacheFiles`입니다.

선택적 `debug <mask>`는 커널 모듈 디버깅을 제어하는 numeric bitmask를 지정하며 기본값은 0입니다. 값 1은 `_enter()` 함수 진입 trace, 2는 `_leave()` 함수 종료 trace, 4는 `_debug()` 내부 지점 trace를 켭니다. 필요한 값을 OR로 결합합니다.

이 mask는 sysfs에서도 설정할 수 있습니다. 예를 들어 `echo 5 > /sys/module/cachefiles/parameters/debug`는 bit 1과 4를 켭니다.

cachefilesd 구성 명령
명령필수 여부기능
`brun/bcull/bstop`선택사용 가능한 block 비율 임계치
`frun/fcull/fstop`선택사용 가능한 file 수 비율 임계치
`dir <path>`필수캐시 루트 디렉터리
`tag <name>`선택FS-Cache 식별 tag, 기본 `CacheFiles`
`debug <mask>`선택1=entry, 2=exit, 4=internal

캐시 위치와 culling·진단 정책을 지정합니다.

Configuration
=============

The cache is configured by a script in /etc/cachefilesd.conf.  These commands
set up cache ready for use.  The following script commands are available:

 brun <N>%, bcull <N>%, bstop <N>%, frun <N>%, fcull <N>%, fstop <N>%
        Configure the culling limits.  Optional.  See the section on culling
        The defaults are 7% (run), 5% (cull) and 1% (stop) respectively.

        The commands beginning with a 'b' are file space (block) limits, those
        beginning with an 'f' are file count limits.

 dir <path>
        Specify the directory containing the root of the cache.  Mandatory.

 tag <name>
        Specify a tag to FS-Cache to use in distinguishing multiple caches.
        Optional.  The default is "CacheFiles".

 debug <mask>
        Specify a numeric bitmask to control debugging in the kernel module.
        Optional.  The default is zero (all off).  The following values can be
        OR'd into the mask to collect various information:

                ==        =================================================
                1        Turn on trace of function entry (_enter() macros)
                2        Turn on trace of function exit (_leave() macros)
                4        Turn on trace of internal debug points (_debug())
                ==        =================================================

        This mask can also be set through sysfs, eg::

                echo 5 > /sys/module/cachefiles/parameters/debug

캐시 시작

121-147

데몬을 실행하면 캐시가 시작됩니다. 데몬은 cache device를 열고 캐시를 구성한 뒤 caching 시작을 명령합니다. 그 시점에 캐시가 FS-Cache에 bind되어 live 상태가 됩니다.

실행 형식은 `/sbin/cachefilesd [-d]* [-s] [-n] [-f <configfile>]`입니다.

`-d`는 debugging level을 높이며 여러 번 지정할 수 있고 누적됩니다. `-s`는 syslog 대신 stderr로 메시지를 보냅니다. `-n`은 daemonize하여 background로 가지 않게 합니다. `-f <configfile>`은 기본 파일 대신 다른 구성 파일을 사용합니다.

캐시 활성화
`cachefilesd` 실행과 구성 파일 읽기`/dev/cachefiles` 단독 open캐시 디렉터리와 임계치 구성커널에 caching 시작 명령CacheFiles가 FS-Cache에 bind캐시 live 상태

데몬 실행에서 FS-Cache bind까지의 순서입니다.

Starting the Cache
==================

The cache is started by running the daemon.  The daemon opens the cache device,
configures the cache and tells it to begin caching.  At that point the cache
binds to fscache and the cache becomes live.

The daemon is run as follows::

        /sbin/cachefilesd [-d]* [-s] [-n] [-f <configfile>]

The flags are:

 ``-d``
        Increase the debugging level.  This can be specified multiple times and
        is cumulative with itself.

 ``-s``
        Send messages to stderr instead of syslog.

 ``-n``
        Don't daemonise and go into background.

 ``-f <configfile>``
        Use an alternative configuration file rather than the default one.

피해야 할 작업

148-170

캐시 내부에 다른 파일시스템을 마운트하지 마십시오. 커널 모듈의 축소된 path walking 기능은 mountpoint를 무시하지만 데몬은 이를 피할 수 없어 문제가 생깁니다.

캐시가 활성 상태일 때 캐시 안의 파일이나 디렉터리를 생성, rename 또는 unlink하지 마십시오. 상태가 불확실해질 수 있습니다.

캐시 파일을 rename하면 파일 이름이 lookup key의 일부이므로 객체가 다른 객체처럼 보일 수 있습니다.

캐시가 파일에 붙인 extended attribute를 바꾸거나 제거하지 마십시오. 캐시 상태 관리가 혼란에 빠집니다.

캐시 안에 파일이나 디렉터리를 임의로 만들지 마십시오. 캐시가 혼동하거나 잘못된 데이터를 제공할 수 있습니다.

캐시 파일에 `chmod`를 실행하지 마십시오. 모듈은 임의 사용자가 캐시 파일에 직접 접근하지 못하도록 최소 권한으로 객체를 만듭니다.

활성 캐시 금지 작업
금지 작업위험
내부 mount데몬 path traversal 불일치
create·rename·unlink객체 상태와 lookup key 불일치
xattr 변경·삭제형식·coherency 상태 손상
임의 파일·디렉터리 생성잘못된 객체 인식과 데이터 제공
`chmod`직접 접근 차단 보안 모델 훼손

CacheFiles가 소유한 namespace와 metadata를 외부에서 바꾸면 안 됩니다.

Things to Avoid
===============

Do not mount other things within the cache as this will cause problems.  The
kernel module contains its own very cut-down path walking facility that ignores
mountpoints, but the daemon can't avoid them.

Do not create, rename or unlink files and directories in the cache while the
cache is active, as this may cause the state to become uncertain.

Renaming files in the cache might make objects appear to be other objects (the
filename is part of the lookup key).

Do not change or remove the extended attributes attached to cache files by the
cache as this will cause the cache state management to get confused.

Do not create files or directories in the cache, lest the cache get confused or
serve incorrect data.

Do not chmod files in the cache.  The module creates things with minimal
permissions to prevent random users being able to access them directly.

Cache culling

171-210

캐시는 공간을 만들기 위해 때때로 culling이 필요합니다. 다른 객체보다 덜 최근에 사용된 객체를 버리며 data object의 access time을 기준으로 합니다. 사용 중이 아닌 빈 디렉터리도 cull합니다.

culling은 backing 파일시스템에서 사용 가능한 block 비율과 사용 가능한 file 수 비율을 기준으로 하며 여섯 한계를 사용합니다.

`brun`과 `frun`은 여유 공간과 사용 가능한 파일 수가 둘 다 각 한계보다 높아지면 culling을 끕니다.

`bcull` 또는 `fcull` 중 어느 하나보다 사용 가능한 공간이나 파일 수가 낮아지면 culling을 시작합니다.

`bstop` 또는 `fstop` 중 어느 하나보다 낮아지면 culling이 다시 임계치 위로 올릴 때까지 디스크 공간이나 파일의 추가 할당을 허용하지 않습니다.

임계치는 `0 <= bstop < bcull < brun < 100`, `0 <= fstop < fcull < frun < 100` 순서를 만족해야 합니다. 이는 사용 가능한 공간과 파일의 비율이며 `df`가 표시하는 사용률을 100에서 뺀 값처럼 단순 해석해서는 안 됩니다.

사용자 공간 데몬은 캐시를 scan해 cull 가능한 객체 table을 만들고 least recently used 순서로 cull합니다. table에 공간이 생기면 즉시 새 scan을 시작합니다. 객체의 atime이 바뀌었거나 커널 모듈이 아직 사용 중이라고 알리면 해당 객체를 건너뜁니다.

Culling 상태 임계치
단계BlockFile동작
Run`brun``frun`둘 다 초과하면 culling 중지
Cull`bcull``fcull`하나라도 미만이면 culling 시작
Stop`bstop``fstop`하나라도 미만이면 새 공간·파일 할당 중지

block과 file 수에 같은 세 단계 hysteresis를 적용합니다.

Cache Culling
=============

The cache may need culling occasionally to make space.  This involves
discarding objects from the cache that have been used less recently than
anything else.  Culling is based on the access time of data objects.  Empty
directories are culled if not in use.

Cache culling is done on the basis of the percentage of blocks and the
percentage of files available in the underlying filesystem.  There are six
"limits":

 brun, frun
     If the amount of free space and the number of available files in the cache
     rises above both these limits, then culling is turned off.

 bcull, fcull
     If the amount of available space or the number of available files in the
     cache falls below either of these limits, then culling is started.

 bstop, fstop
     If the amount of available space or the number of available files in the
     cache falls below either of these limits, then no further allocation of
     disk space or files is permitted until culling has raised things above
     these limits again.

These must be configured thusly::

        0 <= bstop < bcull < brun < 100
        0 <= fstop < fcull < frun < 100

Note that these are percentages of available space and available files, and do
_not_ appear as 100 minus the percentage displayed by the "df" program.

The userspace daemon scans the cache to build up a table of cullable objects.
These are then culled in least recently used order.  A new scan of the cache is
started as soon as space is made in the table.  Objects will be skipped if
their atimes have changed or if the kernel module says it is still using them.

캐시 디스크 구조와 이름 인코딩

211-291

CacheFiles 모듈은 지정된 디렉터리 아래에 `cache/`와 `graveyard/`를 만듭니다. 활성 캐시 객체는 모두 `cache/`에 있습니다. 커널 모듈이 즉시 unlink할 수 없는 retired 또는 culled 객체는 `graveyard/`로 옮기고 데몬이 실제로 삭제합니다.

데몬은 `dnotify`로 `graveyard/`를 감시하고 그 안에 나타나는 모든 항목을 삭제합니다.

모듈은 index object를 `I...` 또는 `J...` 이름의 디렉터리로 표현하며 `cache/` 자체도 특별한 index입니다.

자식이 없는 data object는 파일, 자식이 있으면 디렉터리로 표현합니다. 이름은 `D...` 또는 `E...`로 시작합니다. 디렉터리로 표현되는 경우 실제 데이터는 그 안의 `data` 파일에 저장합니다. special object도 비슷하지만 이름이 `S...` 또는 `T...`로 시작합니다.

자식이 있는 객체의 대표 디렉터리 바로 아래에는 자식 객체 key의 hash 앞에 `@`를 붙인 디렉터리들이 있습니다. 가능하면 그 안에 자식 객체 표현을 배치합니다. 원문의 경로 예시는 `cache/@4a/I03nfs/@30/Ji.../@75/Es...`처럼 cache index, netfs index, volume index, hash bucket, data file로 이어집니다.

key에 decoration을 붙인 길이가 `NAME_MAX`를 넘으면 key를 여러 조각으로 나눕니다. 앞 조각들로 중첩 디렉터리를 만들고 마지막 조각이 최종 객체 이름이 됩니다. 중간 디렉터리 이름에는 `+`를 붙이며 예시는 `J1223/@23/+xy...z/+kl...m/Epqr`입니다.

key는 raw data이므로 `NAME_MAX`를 넘을 뿐 아니라 `/`나 NUL도 포함할 수 있어 직접 파일 이름으로 쓰지 못할 수 있습니다. CacheFiles는 적합한 key는 출력 가능한 파일 이름으로 직접 사용하고, 적합하지 않은 key는 base-64로 encode합니다.

index는 printable `I...`, encoded `J...`; data는 printable `D...`, encoded `E...`; special은 printable `S...`, encoded `T...`를 사용합니다. 중간 디렉터리는 용도에 따라 항상 `@` 또는 `+`입니다.

캐시의 각 객체에는 object type ID와 netfs auxiliary data를 담은 extended attribute label이 있습니다. object type ID는 special object를 구분하는 데 필요하고 auxiliary data는 오래된 객체를 감지하여 update 또는 retire하는 데 사용합니다.

CacheFiles는 인식하지 못하는 파일이나 FIFO·device file처럼 형식이 잘못된 파일을 캐시에서 지웁니다.

CacheFiles 이름 체계
객체PrintableEncoded표현
Index`I...``J...`디렉터리
Data`D...``E...`리프는 파일, 자식이 있으면 디렉터리+`data`
Special`S...``T...`data object와 유사
Hash bucket`@...``@...`자식 key hash별 디렉터리
긴 key 중간 조각`+...``+...``NAME_MAX` 초과 시 중첩 디렉터리

출력 가능한 key와 encoded key를 객체 종류별로 구분합니다.

Cache Structure
===============

The CacheFiles module will create two directories in the directory it was
given:

 * cache/
 * graveyard/

The active cache objects all reside in the first directory.  The CacheFiles
kernel module moves any retired or culled objects that it can't simply unlink
to the graveyard from which the daemon will actually delete them.

The daemon uses dnotify to monitor the graveyard directory, and will delete
anything that appears therein.


The module represents index objects as directories with the filename "I..." or
"J...".  Note that the "cache/" directory is itself a special index.

Data objects are represented as files if they have no children, or directories
if they do.  Their filenames all begin "D..." or "E...".  If represented as a
directory, data objects will have a file in the directory called "data" that
actually holds the data.

Special objects are similar to data objects, except their filenames begin
"S..." or "T...".


If an object has children, then it will be represented as a directory.
Immediately in the representative directory are a collection of directories
named for hash values of the child object keys with an '@' prepended.  Into
this directory, if possible, will be placed the representations of the child
objects::

         /INDEX    /INDEX     /INDEX                            /DATA FILES
        /=========/==========/=================================/================
        cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400
        cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...DB1ry
        cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...N22ry
        cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...FP1ry


If the key is so long that it exceeds NAME_MAX with the decorations added on to
it, then it will be cut into pieces, the first few of which will be used to
make a nest of directories, and the last one of which will be the objects
inside the last directory.  The names of the intermediate directories will have
'+' prepended::

        J1223/@23/+xy...z/+kl...m/Epqr


Note that keys are raw data, and not only may they exceed NAME_MAX in size,
they may also contain things like '/' and NUL characters, and so they may not
be suitable for turning directly into a filename.

To handle this, CacheFiles will use a suitably printable filename directly and
"base-64" encode ones that aren't directly suitable.  The two versions of
object filenames indicate the encoding:

        ===============        ===============        ===============
        OBJECT TYPE        PRINTABLE        ENCODED
        ===============        ===============        ===============
        Index                "I..."                "J..."
        Data                "D..."                "E..."
        Special                "S..."                "T..."
        ===============        ===============        ===============

Intermediate directories are always "@" or "+" as appropriate.


Each object in the cache has an extended attribute label that holds the object
type ID (required to distinguish special objects) and the auxiliary data from
the netfs.  The latter is used to detect stale objects in the cache and update
or retire them.


Note that CacheFiles will erase from the cache any file it doesn't recognise or
any file of an incorrect type (such as a FIFO file or a device file).

보안 모델과 SELinux

292-385

CacheFiles는 Linux 커널의 LSM 보안 기능과 SELinux를 올바르게 다루도록 구현되었습니다.

문제는 CacheFiles가 일반적으로 어떤 프로세스를 대신해 그 프로세스의 context에서 동작한다는 점입니다. 그 security context는 캐시 파일에 접근할 권한이 없거나, 그 context로 만든 캐시 파일을 다른 프로세스가 접근하지 못하게 할 수 있어 캐시 접근에 부적합합니다.

CacheFiles는 다른 프로세스를 대신해 작업하는 동안 그 프로세스가 주체로 사용하는 security context, 즉 fsuid, fsgid, actor security label을 임시로 바꿉니다. 다른 프로세스가 해당 프로세스를 대상으로 연산할 때 사용하는 context는 바꾸지 않으므로 signal 같은 기능은 계속 올바르게 작동합니다.

모듈이 캐시에 bind할 때 먼저 cache root directory의 security label을 찾아 파일 생성 label로 사용합니다. 기본값은 `cachefiles_var_t`입니다.

다음으로 bind 요청을 보낸 프로세스, 보통 cachefilesd 데몬의 security label을 찾습니다. 기본값은 `cachefilesd_t`입니다. LSM에 이 데몬 label을 바탕으로 모듈이 행위할 security ID를 요청하며 기본값은 `cachefiles_kernel_t`입니다.

SELinux는 `type_transition <daemon's-ID> kernel_t : process <module's-ID>;` 형태의 policy rule에 따라 데몬 security ID를 모듈 security ID로 transition합니다. 기본 예시는 `type_transition cachefilesd_t kernel_t : process cachefiles_kernel_t;`입니다.

모듈 security ID에는 캐시의 파일과 디렉터리 생성·이동·삭제, 탐색과 접근, cache object xattr 설정·접근, cache file 읽기·쓰기 권한이 있습니다.

데몬 security ID의 권한은 매우 제한적입니다. 디렉터리 scan, file stat, 파일과 디렉터리 삭제만 할 수 있습니다. 캐시 파일을 읽거나 쓸 수 없어 캐시 데이터에 접근할 수 없고, 새 캐시 파일도 만들 수 없습니다.

policy source는 문서에 나온 cachefilesd tarball 이후 버전의 `cachefilesd.te`, `cachefilesd.fc`, `cachefilesd.if`에 있으며 RPM이 직접 build하고 install합니다.

RPM 기반이 아닌 시스템에서는 세 파일을 별도 디렉터리에 복사한 뒤 `make -f /usr/share/selinux/devel/Makefile`과 `semodule -i cachefilesd.pp`를 실행합니다. build 전에 `checkpolicy`와 `selinux-policy-devel`이 설치되어 있어야 합니다.

기본 캐시 위치는 `/var/fscache`입니다. 다른 위치를 사용하려면 policy source를 수정하거나 대체 위치에 올바른 label을 붙이는 auxiliary policy를 설치해야 합니다. SELinux enforcing mode에서 이동하는 방법은 `/usr/share/doc/cachefilesd-*/move-cache.txt` 또는 source 문서를 참고합니다.

CacheFiles SELinux 역할
Label주체·객체대표 권한
`cachefiles_var_t`cache root와 생성 객체캐시 객체 label
`cachefilesd_t`사용자 공간 데몬scan, stat, erase만 허용
`cachefiles_kernel_t`커널 모듈의 주관적 contextcreate, move, remove, xattr, read, write

파일 생성 주체와 관리 데몬의 권한을 분리합니다.

Security Model and SELinux
==========================

CacheFiles is implemented to deal properly with the LSM security features of
the Linux kernel and the SELinux facility.

One of the problems that CacheFiles faces is that it is generally acting on
behalf of a process, and running in that process's context, and that includes a
security context that is not appropriate for accessing the cache - either
because the files in the cache are inaccessible to that process, or because if
the process creates a file in the cache, that file may be inaccessible to other
processes.

The way CacheFiles works is to temporarily change the security context (fsuid,
fsgid and actor security label) that the process acts as - without changing the
security context of the process when it the target of an operation performed by
some other process (so signalling and suchlike still work correctly).


When the CacheFiles module is asked to bind to its cache, it:

 (1) Finds the security label attached to the root cache directory and uses
     that as the security label with which it will create files.  By default,
     this is::

        cachefiles_var_t

 (2) Finds the security label of the process which issued the bind request
     (presumed to be the cachefilesd daemon), which by default will be::

        cachefilesd_t

     and asks LSM to supply a security ID as which it should act given the
     daemon's label.  By default, this will be::

        cachefiles_kernel_t

     SELinux transitions the daemon's security ID to the module's security ID
     based on a rule of this form in the policy::

        type_transition <daemon's-ID> kernel_t : process <module's-ID>;

     For instance::

        type_transition cachefilesd_t kernel_t : process cachefiles_kernel_t;


The module's security ID gives it permission to create, move and remove files
and directories in the cache, to find and access directories and files in the
cache, to set and access extended attributes on cache objects, and to read and
write files in the cache.

The daemon's security ID gives it only a very restricted set of permissions: it
may scan directories, stat files and erase files and directories.  It may
not read or write files in the cache, and so it is precluded from accessing the
data cached therein; nor is it permitted to create new files in the cache.


There are policy source files available in:

        https://people.redhat.com/~dhowells/fscache/cachefilesd-0.8.tar.bz2

and later versions.  In that tarball, see the files::

        cachefilesd.te
        cachefilesd.fc
        cachefilesd.if

They are built and installed directly by the RPM.

If a non-RPM based system is being used, then copy the above files to their own
directory and run::

        make -f /usr/share/selinux/devel/Makefile
        semodule -i cachefilesd.pp

You will need checkpolicy and selinux-policy-devel installed prior to the
build.


By default, the cache is located in /var/fscache, but if it is desirable that
it should be elsewhere, than either the above policy files must be altered, or
an auxiliary policy must be installed to label the alternate location of the
cache.

For instructions on how to add an auxiliary policy to enable the cache to be
located elsewhere when SELinux is in enforcing mode, please see::

        /usr/share/doc/cachefilesd-*/move-cache.txt

When the cachefilesd rpm is installed; alternatively, the document can be found
in the sources.

Credential 분리에 관한 보안 참고

386-427

CacheFiles는 `task_struct`의 분리된 보안 모델을 사용합니다. 자체 `task_security` 구조를 할당하고 다른 프로세스를 대신해 그 context에서 동작할 때 `current->cred`가 이를 가리키도록 바꿉니다.

이렇게 하는 이유는 보안을 우회해 inode operation을 직접 호출하지 않고 `vfs_mkdir()` 같은 VFS 함수를 호출하기 때문입니다. netfs에서 원래 syscall을 보낸 프로세스의 security context로 caching 코드가 실행되는 상황에서는 VFS와 LSM이 CacheFiles의 캐시 데이터 접근을 거부할 수 있습니다.

또한 원래 프로세스의 context로 파일이나 디렉터리를 만들면 UID, GID, security label도 그 프로세스에서 파생됩니다. 그러면 CacheFiles 관리 데몬을 포함한 다른 프로세스가 캐시에 접근하지 못할 수 있습니다.

따라서 syscall을 보낸 프로세스의 보안을 임시로 override해야 합니다. 하지만 security data를 제자리에서 바꾸면 주체로서뿐 아니라 객체로서의 프로세스에도 영향을 줍니다. signal이나 ptrace event를 잃거나 `/proc`에 보이는 모습이 바뀔 수 있으므로 그렇게 할 수 없습니다.

CacheFiles는 objective security인 `task->real_cred`와 subjective security인 `task->cred` 사이의 논리적 분리를 이용합니다.

objective security는 프로세스 고유의 보안 속성을 보유하며 절대로 override되지 않습니다. `/proc`에 보이는 값이고 `SIGKILL`처럼 다른 프로세스가 이 프로세스를 대상으로 연산할 때 사용됩니다.

subjective security는 프로세스의 현재 능동적 보안 속성이며 override할 수 있습니다. 외부에는 보이지 않고 다른 프로세스에 `SIGKILL`을 보내거나 파일을 여는 것처럼 프로세스가 다른 객체에 작용할 때 사용됩니다.

LSM hook은 SELinux, Smack 등이 CacheFiles가 특정 security label context로 실행하거나 다른 label로 파일·디렉터리를 만들려는 요청을 거부할 수 있게 합니다.

Objective와 subjective credential
Credential필드용도Override
Objective`task->real_cred``/proc`, signal·ptrace의 대상 신원안 함
Subjective`task->cred`파일 생성·접근 등 행위 주체 신원CacheFiles 작업 동안 임시 허용

대상으로 보이는 신원은 유지하고 객체에 작용할 권한만 임시 변경합니다.

A Note on Security
==================

CacheFiles makes use of the split security in the task_struct.  It allocates
its own task_security structure, and redirects current->cred to point to it
when it acts on behalf of another process, in that process's context.

The reason it does this is that it calls vfs_mkdir() and suchlike rather than
bypassing security and calling inode ops directly.  Therefore the VFS and LSM
may deny the CacheFiles access to the cache data because under some
circumstances the caching code is running in the security context of whatever
process issued the original syscall on the netfs.

Furthermore, should CacheFiles create a file or directory, the security
parameters with that object is created (UID, GID, security label) would be
derived from that process that issued the system call, thus potentially
preventing other processes from accessing the cache - including CacheFiles's
cache management daemon (cachefilesd).

What is required is to temporarily override the security of the process that
issued the system call.  We can't, however, just do an in-place change of the
security data as that affects the process as an object, not just as a subject.
This means it may lose signals or ptrace events for example, and affects what
the process looks like in /proc.

So CacheFiles makes use of a logical split in the security between the
objective security (task->real_cred) and the subjective security (task->cred).
The objective security holds the intrinsic security properties of a process and
is never overridden.  This is what appears in /proc, and is what is used when a
process is the target of an operation by some other process (SIGKILL for
example).

The subjective security holds the active security properties of a process, and
may be overridden.  This is not seen externally, and is used when a process
acts upon another object, for example SIGKILLing another process or opening a
file.

LSM hooks exist that allow SELinux (or Smack or whatever) to reject a request
for CacheFiles to run in a context of a specific security label, or to create
files and directories with another security label.

통계 정보

428-461

FS-Cache를 `CONFIG_CACHEFILES_HISTOGRAM=y`로 빌드하면 특정 통계를 모아 `/proc/fs/cachefiles/histogram`에 표시합니다.

출력은 0 jiffy부터 `HZ-1` jiffy까지 각 시간 구간에서 여러 작업이 실행된 횟수를 보여 줍니다. `LOOKUPS`는 backing filesystem lookup 시간, `MKDIRS`는 mkdir 시간, `CREATES`는 create 시간을 나타냅니다.

각 행은 특정 시간 범위가 걸린 사건 수를 보여 주며 한 단계의 크기는 1 jiffy입니다. `JIFS`는 해당 jiffy 범위, `SECS`는 같은 값을 초로 나타냅니다.

CacheFiles histogram 열
측정값
`JIFS`1 jiffy 단위 시간 구간
`SECS`해당 구간의 초 환산
`LOOKUPS`backing fs lookup 시간별 횟수
`MKDIRS`backing fs mkdir 시간별 횟수
`CREATES`backing fs create 시간별 횟수

backing filesystem metadata 작업 지연을 jiffy별로 계수합니다.

Statistical Information
=======================

If FS-Cache is compiled with the following option enabled::

        CONFIG_CACHEFILES_HISTOGRAM=y

then it will gather certain statistics and display them through a proc file.

 /proc/fs/cachefiles/histogram

     ::

        cat /proc/fs/cachefiles/histogram
        JIFS  SECS  LOOKUPS   MKDIRS    CREATES
        ===== ===== ========= ========= =========

     This shows the breakdown of the number of times each amount of time
     between 0 jiffies and HZ-1 jiffies a variety of tasks took to run.  The
     columns are as follows:

        =======                =======================================================
        COLUMN                TIME MEASUREMENT
        =======                =======================================================
        LOOKUPS                Length of time to perform a lookup on the backing fs
        MKDIRS                Length of time to perform a mkdir on the backing fs
        CREATES                Length of time to perform a create on the backing fs
        =======                =======================================================

     Each row shows the number of events that took a particular range of times.
     Each step is 1 jiffy in size.  The JIFS column indicates the particular
     jiffy range covered, and the SECS field the equivalent number of seconds.

Runtime debugging

462-487

`CONFIG_CACHEFILES_DEBUG`를 활성화했다면 `/sys/module/cachefiles/parameters/debug` 값을 조정해 CacheFiles runtime debugging을 켤 수 있습니다.

이 값은 debugging stream bitmask입니다. bit 0, 값 1은 일반 function entry trace; bit 1, 값 2는 function exit trace; bit 2, 값 4는 general debugging을 뜻합니다.

필요한 값을 OR로 결합해 control file에 씁니다. 원문의 예시 `echo $((1|4|8)) > /sys/module/cachefiles/parameters/debug`는 모든 function entry debugging을 켠다고 설명합니다.

Debug bitmask
Bit지점
01Function entry trace
12Function exit trace
24General debug point

kernel module runtime trace stream을 조합합니다.

Debugging
=========

If CONFIG_CACHEFILES_DEBUG is enabled, the CacheFiles facility can have runtime
debugging enabled by adjusting the value in::

        /sys/module/cachefiles/parameters/debug

This is a bitmask of debugging streams to enable:

        =======        =======        ===============================        =======================
        BIT        VALUE        STREAM                                POINT
        =======        =======        ===============================        =======================
        0        1        General                                Function entry trace
        1        2                                        Function exit trace
        2        4                                        General
        =======        =======        ===============================        =======================

The appropriate set of values should be OR'd together and the result written to
the control file.  For example::

        echo $((1|4|8)) >/sys/module/cachefiles/parameters/debug

will turn on all function entry debugging.

On-demand read 개요

488-503

기본 모드에서 CacheFiles는 원격 네트워크 파일시스템을 위한 로컬 캐시입니다. on-demand read 모드에서는 container image 배포처럼 on-demand read semantics가 필요한 작업을 가속할 수 있습니다.

두 모드의 핵심 차이는 cache miss 처리입니다. 기본 모드에서는 netfs가 원격 서버에서 데이터를 가져와 캐시 파일에 씁니다. on-demand read 모드에서는 데이터 fetch와 cache file write를 사용자 데몬에 위임합니다.

on-demand read 모드를 지원하려면 `CONFIG_CACHEFILES_ONDEMAND`를 활성화해야 합니다.

Cache miss 처리 비교
모드Fetch·cache write 주체대표 사용
기본netfs원격 네트워크 파일시스템 로컬 캐시
On-demand사용자 공간 데몬container image 등 요청 기반 데이터 공급

데이터를 원격에서 가져와 캐시에 쓰는 주체가 달라집니다.

On-demand Read
==============

When working in its original mode, CacheFiles serves as a local cache for a
remote networking fs - while in on-demand read mode, CacheFiles can boost the
scenario where on-demand read semantics are needed, e.g. container image
distribution.

The essential difference between these two modes is seen when a cache miss
occurs: In the original mode, the netfs will fetch the data from the remote
server and then write it to the cache file; in on-demand read mode, fetching
the data and writing it into the cache is delegated to a user daemon.

``CONFIG_CACHEFILES_ONDEMAND`` should be enabled to support on-demand read mode.

Kernel-daemon 요청·응답 protocol

504-545

on-demand read 모드는 커널과 사용자 데몬 사이의 단순한 `kernel --[request]--> user daemon --[reply]--> kernel` protocol을 사용합니다.

CacheFiles는 필요할 때 사용자 데몬에 요청을 보냅니다. 데몬은 pending request를 확인하기 위해 `/dev/cachefiles`를 poll해야 하며, 요청이 있으면 `POLLIN` event가 반환됩니다.

데몬은 devnode를 읽어 처리할 요청 하나를 가져옵니다. read 한 번은 요청 하나만 반환합니다. 처리가 끝나면 devnode에 reply를 써야 합니다.

각 요청은 `struct cachefiles_msg` header로 시작합니다. `msg_id`는 모든 pending request 중 이 요청을 식별하는 고유 ID이고, `opcode`는 요청 형식, `object_id`는 작업 대상 cache file의 고유 ID, `data`는 payload입니다. `len`은 header와 형식별 payload를 포함한 전체 요청 길이입니다.

On-demand 요청 왕복
커널 CacheFiles가 request 생성`/dev/cachefiles` poll에 `POLLIN`데몬 read 한 번으로 request 하나 수신`msg_id`, `opcode`, `object_id`, payload 처리데몬이 devnode 또는 지정 ioctl로 reply커널이 같은 `msg_id` 요청 완료

poll, 단일 request read, 처리, reply 순서입니다.

Protocol Communication
----------------------

The on-demand read mode uses a simple protocol for communication between kernel
and user daemon. The protocol can be modeled as::

        kernel --[request]--> user daemon --[reply]--> kernel

CacheFiles will send requests to the user daemon when needed.  The user daemon
should poll the devnode ('/dev/cachefiles') to check if there's a pending
request to be processed.  A POLLIN event will be returned when there's a pending
request.

The user daemon then reads the devnode to fetch a request to process.  It should
be noted that each read only gets one request. When it has finished processing
the request, the user daemon should write the reply to the devnode.

Each request starts with a message header of the form::

        struct cachefiles_msg {
                __u32 msg_id;
                __u32 opcode;
                __u32 len;
                __u32 object_id;
                __u8  data[];
        };

where:

        * ``msg_id`` is a unique ID identifying this request among all pending
          requests.

        * ``opcode`` indicates the type of this request.

        * ``object_id`` is a unique ID identifying the cache file operated on.

        * ``data`` indicates the payload of this request.

        * ``len`` indicates the whole length of this request, including the
          header and following type-specific payload.

On-demand 모드 활성화

546-557

`bind` 명령에는 선택적 매개변수 `bind [ondemand]`가 추가됩니다.

인수 없이 `bind`를 사용하면 기본 모드가 됩니다. `bind ondemand`처럼 `ondemand` 인수를 주면 on-demand read 모드를 활성화합니다.

`bind` 모드 선택
명령모드
`bind`기본 CacheFiles 모드
`bind ondemand`On-demand read 모드

같은 캐시 bind 명령에서 동작 모드를 고릅니다.

Turning on On-demand Mode
-------------------------

An optional parameter becomes available to the "bind" command::

        bind [ondemand]

When the "bind" command is given no argument, it defaults to the original mode.
When it is given the "ondemand" argument, i.e. "bind ondemand", on-demand read
mode will be enabled.

`CACHEFILES_OP_OPEN` 요청

558-617

netfs가 cache file을 처음 열면 `CACHEFILES_OP_OPEN` opcode의 OPEN 요청을 사용자 데몬에 보냅니다. payload는 `struct cachefiles_open`입니다.

`data`에는 volume key 바로 뒤에 cookie key가 이어집니다. volume key는 NUL로 끝나는 문자열이고 cookie key는 binary data입니다. `volume_key_size`와 `cookie_key_size`는 각각의 byte 크기입니다.

`fd`는 cache file을 가리키는 anonymous fd입니다. 사용자 데몬은 이를 통해 cache file에 write와 `llseek` file operation을 수행할 수 있습니다.

데몬은 `(volume_key, cookie_key)` 쌍으로 요청된 cache file을 구별합니다. anonymous fd를 사용하면 커널이 아직 cache miss를 유발하지 않았더라도 background에서 데이터를 fetch하여 cache file에 쓸 수 있습니다.

각 cache file에는 고유한 `object_id`가 있지만 anonymous fd는 여러 개일 수 있습니다. 데몬은 OPEN의 `fd`를 `dup()`하여 anonymous fd를 복제할 수 있습니다. 따라서 하나의 `object_id`가 여러 fd에 매핑될 수 있고 데몬 자체가 이 mapping을 유지해야 합니다.

데몬 구현에서는 `RLIMIT_NOFILE`, `/proc/sys/fs/nr_open`, `/proc/sys/fs/file-max`에 주의해야 합니다. 이 한계는 각 파일시스템의 열린 파일 수가 아니라 열린 device blob 수와 관련되므로 보통 매우 클 필요는 없습니다.

데몬은 devnode에 `copen <msg_id>,<cache_size>` 명령을 보내 OPEN 요청에 reply해야 합니다. `msg_id`는 OPEN 요청의 값과 일치해야 합니다. `cache_size >= 0`이면 cache file 크기이고, 0보다 작으면 데몬이 만난 오류 code를 나타냅니다.

OPEN 요청과 `copen` 응답
필드·명령의미
`volume_key_size` / `cookie_key_size`두 key의 byte 크기
`data[]`NUL 종료 volume key + binary cookie key
`fd`cache file의 anonymous fd
`object_id`cache file별 고유 ID, 여러 fd와 매핑 가능
`copen msg_id,cache_size`OPEN 완료, 크기 또는 음수 오류

키, object ID, anonymous fd와 응답 값의 관계입니다.

The OPEN Request
----------------

When the netfs opens a cache file for the first time, a request with the
CACHEFILES_OP_OPEN opcode, a.k.a an OPEN request will be sent to the user
daemon.  The payload format is of the form::

        struct cachefiles_open {
                __u32 volume_key_size;
                __u32 cookie_key_size;
                __u32 fd;
                __u32 flags;
                __u8  data[];
        };

where:

        * ``data`` contains the volume_key followed directly by the cookie_key.
          The volume key is a NUL-terminated string; the cookie key is binary
          data.

        * ``volume_key_size`` indicates the size of the volume key in bytes.

        * ``cookie_key_size`` indicates the size of the cookie key in bytes.

        * ``fd`` indicates an anonymous fd referring to the cache file, through
          which the user daemon can perform write/llseek file operations on the
          cache file.


The user daemon can use the given (volume_key, cookie_key) pair to distinguish
the requested cache file.  With the given anonymous fd, the user daemon can
fetch the data and write it to the cache file in the background, even when
kernel has not triggered a cache miss yet.

Be noted that each cache file has a unique object_id, while it may have multiple
anonymous fds.  The user daemon may duplicate anonymous fds from the initial
anonymous fd indicated by the @fd field through dup().  Thus each object_id can
be mapped to multiple anonymous fds, while the usr daemon itself needs to
maintain the mapping.

When implementing a user daemon, please be careful of RLIMIT_NOFILE,
``/proc/sys/fs/nr_open`` and ``/proc/sys/fs/file-max``.  Typically these needn't
be huge since they're related to the number of open device blobs rather than
open files of each individual filesystem.

The user daemon should reply the OPEN request by issuing a "copen" (complete
open) command on the devnode::

        copen <msg_id>,<cache_size>

where:

        * ``msg_id`` must match the msg_id field of the OPEN request.

        * When >= 0, ``cache_size`` indicates the size of the cache file;
          when < 0, ``cache_size`` indicates any error code encountered by the
          user daemon.

`CACHEFILES_OP_CLOSE` 요청

618-626

cookie가 withdrawn되면 `CACHEFILES_OP_CLOSE` opcode의 CLOSE 요청을 사용자 데몬에 보냅니다.

이 요청은 데몬에 해당 `object_id`와 연결된 모든 anonymous fd를 닫으라고 알립니다. 추가 payload가 없으며 reply해서는 안 됩니다.

CLOSE 처리
FS-Cache cookie withdrawn커널이 `CACHEFILES_OP_CLOSE` 전송데몬이 `object_id`의 모든 anonymous fd 조회연결된 fd 모두 closereply 없음

cookie 철회가 daemon fd 정리로 이어집니다.

The CLOSE Request
-----------------

When a cookie withdrawn, a CLOSE request (opcode CACHEFILES_OP_CLOSE) will be
sent to the user daemon.  This tells the user daemon to close all anonymous fds
associated with the given object_id.  The CLOSE request has no extra payload,
and shouldn't be replied.

`CACHEFILES_OP_READ` 요청

627-662

on-demand read 모드에서 cache miss가 발생하면 CacheFiles는 `CACHEFILES_OP_READ` opcode의 READ 요청을 사용자 데몬에 보냅니다. 데몬은 요청된 file range의 내용을 가져와야 합니다.

payload는 `struct cachefiles_read`이며 `off`는 요청 file range의 시작 offset, `len`은 길이입니다.

READ 요청을 받으면 데몬은 요청된 데이터를 fetch하여 `object_id`로 식별되는 cache file에 써야 합니다.

처리가 끝나면 데몬은 해당 `object_id`에 연결된 anonymous fd 중 하나에서 `CACHEFILES_IOC_READ_COMPLETE` ioctl을 사용해 reply해야 합니다. 호출 형식은 `ioctl(fd, CACHEFILES_IOC_READ_COMPLETE, msg_id)`입니다.

`fd`는 요청의 `object_id`에 연결된 anonymous fd 중 하나이고, `msg_id`는 READ 요청 header의 값과 일치해야 합니다.

READ miss 처리
netfs cache miss커널이 `CACHEFILES_OP_READ`와 `off`,`len` 전송데몬이 remote 또는 backing source에서 range fetch`object_id`의 anonymous fd로 cache file에 write`CACHEFILES_IOC_READ_COMPLETE`에 같은 `msg_id` 전달커널이 대기 중인 read 재개

요청 range를 채우고 같은 request ID로 완료를 알립니다.

The READ Request
----------------

When a cache miss is encountered in on-demand read mode, CacheFiles will send a
READ request (opcode CACHEFILES_OP_READ) to the user daemon. This tells the user
daemon to fetch the contents of the requested file range.  The payload is of the
form::

        struct cachefiles_read {
                __u64 off;
                __u64 len;
        };

where:

        * ``off`` indicates the starting offset of the requested file range.

        * ``len`` indicates the length of the requested file range.


When it receives a READ request, the user daemon should fetch the requested data
and write it to the cache file identified by object_id.

When it has finished processing the READ request, the user daemon should reply
by using the CACHEFILES_IOC_READ_COMPLETE ioctl on one of the anonymous fds
associated with the object_id given in the READ request.  The ioctl is of the
form::

        ioctl(fd, CACHEFILES_IOC_READ_COMPLETE, msg_id);

where:

        * ``fd`` is one of the anonymous fds associated with the object_id
          given.

        * ``msg_id`` must match the msg_id field of the READ request.