663 lines · plain
1.. SPDX-License-Identifier: GPL-2.02 3===================================4Cache on Already Mounted Filesystem5===================================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 34Overview35========36 37CacheFiles is a caching backend that's meant to use as a cache a directory on38an already mounted filesystem of a local type (such as Ext3).39 40CacheFiles uses a userspace daemon to do some of the cache management - such as41reaping stale nodes and culling. This is called cachefilesd and lives in42/sbin.43 44The filesystem and data integrity of the cache are only as good as those of the45filesystem providing the backing services. Note that CacheFiles does not46attempt to journal anything since the journalling interfaces of the various47filesystems are very specific in nature.48 49CacheFiles creates a misc character device - "/dev/cachefiles" - that is used50to communication with the daemon. Only one thing may have this open at once,51and while it is open, a cache is at least partially in existence. The daemon52opens this and sends commands down it to control the cache.53 54CacheFiles is currently limited to a single cache.55 56CacheFiles attempts to maintain at least a certain percentage of free space on57the filesystem, shrinking the cache by culling the objects it contains to make58space if necessary - see the "Cache Culling" section. This means it can be59placed on the same medium as a live set of data, and will expand to make use of60spare space and automatically contract when the set of data requires more61space.62 63 64 65Requirements66============67 68The use of CacheFiles and its daemon requires the following features to be69available 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 81It is strongly recommended that the "dir_index" option is enabled on Ext382filesystems being used as a cache.83 84 85Configuration86=============87 88The cache is configured by a script in /etc/cachefilesd.conf. These commands89set 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 culling93 The defaults are 7% (run), 5% (cull) and 1% (stop) respectively.94 95 The commands beginning with a 'b' are file space (block) limits, those96 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 be108 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/debug119 120 121Starting the Cache122==================123 124The cache is started by running the daemon. The daemon opens the cache device,125configures the cache and tells it to begin caching. At that point the cache126binds to fscache and the cache becomes live.127 128The daemon is run as follows::129 130 /sbin/cachefilesd [-d]* [-s] [-n] [-f <configfile>]131 132The flags are:133 134 ``-d``135 Increase the debugging level. This can be specified multiple times and136 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 148Things to Avoid149===============150 151Do not mount other things within the cache as this will cause problems. The152kernel module contains its own very cut-down path walking facility that ignores153mountpoints, but the daemon can't avoid them.154 155Do not create, rename or unlink files and directories in the cache while the156cache is active, as this may cause the state to become uncertain.157 158Renaming files in the cache might make objects appear to be other objects (the159filename is part of the lookup key).160 161Do not change or remove the extended attributes attached to cache files by the162cache as this will cause the cache state management to get confused.163 164Do not create files or directories in the cache, lest the cache get confused or165serve incorrect data.166 167Do not chmod files in the cache. The module creates things with minimal168permissions to prevent random users being able to access them directly.169 170 171Cache Culling172=============173 174The cache may need culling occasionally to make space. This involves175discarding objects from the cache that have been used less recently than176anything else. Culling is based on the access time of data objects. Empty177directories are culled if not in use.178 179Cache culling is done on the basis of the percentage of blocks and the180percentage of files available in the underlying filesystem. There are six181"limits":182 183 brun, frun184 If the amount of free space and the number of available files in the cache185 rises above both these limits, then culling is turned off.186 187 bcull, fcull188 If the amount of available space or the number of available files in the189 cache falls below either of these limits, then culling is started.190 191 bstop, fstop192 If the amount of available space or the number of available files in the193 cache falls below either of these limits, then no further allocation of194 disk space or files is permitted until culling has raised things above195 these limits again.196 197These must be configured thusly::198 199 0 <= bstop < bcull < brun < 100200 0 <= fstop < fcull < frun < 100201 202Note that these are percentages of available space and available files, and do203_not_ appear as 100 minus the percentage displayed by the "df" program.204 205The userspace daemon scans the cache to build up a table of cullable objects.206These are then culled in least recently used order. A new scan of the cache is207started as soon as space is made in the table. Objects will be skipped if208their atimes have changed or if the kernel module says it is still using them.209 210 211Cache Structure212===============213 214The CacheFiles module will create two directories in the directory it was215given:216 217 * cache/218 * graveyard/219 220The active cache objects all reside in the first directory. The CacheFiles221kernel module moves any retired or culled objects that it can't simply unlink222to the graveyard from which the daemon will actually delete them.223 224The daemon uses dnotify to monitor the graveyard directory, and will delete225anything that appears therein.226 227 228The module represents index objects as directories with the filename "I..." or229"J...". Note that the "cache/" directory is itself a special index.230 231Data objects are represented as files if they have no children, or directories232if they do. Their filenames all begin "D..." or "E...". If represented as a233directory, data objects will have a file in the directory called "data" that234actually holds the data.235 236Special objects are similar to data objects, except their filenames begin237"S..." or "T...".238 239 240If an object has children, then it will be represented as a directory.241Immediately in the representative directory are a collection of directories242named for hash values of the child object keys with an '@' prepended. Into243this directory, if possible, will be placed the representations of the child244objects::245 246 /INDEX /INDEX /INDEX /DATA FILES247 /=========/==========/=================================/================248 cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400249 cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...DB1ry250 cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...N22ry251 cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...FP1ry252 253 254If the key is so long that it exceeds NAME_MAX with the decorations added on to255it, then it will be cut into pieces, the first few of which will be used to256make a nest of directories, and the last one of which will be the objects257inside the last directory. The names of the intermediate directories will have258'+' prepended::259 260 J1223/@23/+xy...z/+kl...m/Epqr261 262 263Note that keys are raw data, and not only may they exceed NAME_MAX in size,264they may also contain things like '/' and NUL characters, and so they may not265be suitable for turning directly into a filename.266 267To handle this, CacheFiles will use a suitably printable filename directly and268"base-64" encode ones that aren't directly suitable. The two versions of269object filenames indicate the encoding:270 271 =============== =============== ===============272 OBJECT TYPE PRINTABLE ENCODED273 =============== =============== ===============274 Index "I..." "J..."275 Data "D..." "E..."276 Special "S..." "T..."277 =============== =============== ===============278 279Intermediate directories are always "@" or "+" as appropriate.280 281 282Each object in the cache has an extended attribute label that holds the object283type ID (required to distinguish special objects) and the auxiliary data from284the netfs. The latter is used to detect stale objects in the cache and update285or retire them.286 287 288Note that CacheFiles will erase from the cache any file it doesn't recognise or289any file of an incorrect type (such as a FIFO file or a device file).290 291 292Security Model and SELinux293==========================294 295CacheFiles is implemented to deal properly with the LSM security features of296the Linux kernel and the SELinux facility.297 298One of the problems that CacheFiles faces is that it is generally acting on299behalf of a process, and running in that process's context, and that includes a300security context that is not appropriate for accessing the cache - either301because the files in the cache are inaccessible to that process, or because if302the process creates a file in the cache, that file may be inaccessible to other303processes.304 305The way CacheFiles works is to temporarily change the security context (fsuid,306fsgid and actor security label) that the process acts as - without changing the307security context of the process when it the target of an operation performed by308some other process (so signalling and suchlike still work correctly).309 310 311When 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 uses314 that as the security label with which it will create files. By default,315 this is::316 317 cachefiles_var_t318 319 (2) Finds the security label of the process which issued the bind request320 (presumed to be the cachefilesd daemon), which by default will be::321 322 cachefilesd_t323 324 and asks LSM to supply a security ID as which it should act given the325 daemon's label. By default, this will be::326 327 cachefiles_kernel_t328 329 SELinux transitions the daemon's security ID to the module's security ID330 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 339The module's security ID gives it permission to create, move and remove files340and directories in the cache, to find and access directories and files in the341cache, to set and access extended attributes on cache objects, and to read and342write files in the cache.343 344The daemon's security ID gives it only a very restricted set of permissions: it345may scan directories, stat files and erase files and directories. It may346not read or write files in the cache, and so it is precluded from accessing the347data cached therein; nor is it permitted to create new files in the cache.348 349 350There are policy source files available in:351 352 https://people.redhat.com/~dhowells/fscache/cachefilesd-0.8.tar.bz2353 354and later versions. In that tarball, see the files::355 356 cachefilesd.te357 cachefilesd.fc358 cachefilesd.if359 360They are built and installed directly by the RPM.361 362If a non-RPM based system is being used, then copy the above files to their own363directory and run::364 365 make -f /usr/share/selinux/devel/Makefile366 semodule -i cachefilesd.pp367 368You will need checkpolicy and selinux-policy-devel installed prior to the369build.370 371 372By default, the cache is located in /var/fscache, but if it is desirable that373it should be elsewhere, than either the above policy files must be altered, or374an auxiliary policy must be installed to label the alternate location of the375cache.376 377For instructions on how to add an auxiliary policy to enable the cache to be378located elsewhere when SELinux is in enforcing mode, please see::379 380 /usr/share/doc/cachefilesd-*/move-cache.txt381 382When the cachefilesd rpm is installed; alternatively, the document can be found383in the sources.384 385 386A Note on Security387==================388 389CacheFiles makes use of the split security in the task_struct. It allocates390its own task_security structure, and redirects current->cred to point to it391when it acts on behalf of another process, in that process's context.392 393The reason it does this is that it calls vfs_mkdir() and suchlike rather than394bypassing security and calling inode ops directly. Therefore the VFS and LSM395may deny the CacheFiles access to the cache data because under some396circumstances the caching code is running in the security context of whatever397process issued the original syscall on the netfs.398 399Furthermore, should CacheFiles create a file or directory, the security400parameters with that object is created (UID, GID, security label) would be401derived from that process that issued the system call, thus potentially402preventing other processes from accessing the cache - including CacheFiles's403cache management daemon (cachefilesd).404 405What is required is to temporarily override the security of the process that406issued the system call. We can't, however, just do an in-place change of the407security data as that affects the process as an object, not just as a subject.408This means it may lose signals or ptrace events for example, and affects what409the process looks like in /proc.410 411So CacheFiles makes use of a logical split in the security between the412objective security (task->real_cred) and the subjective security (task->cred).413The objective security holds the intrinsic security properties of a process and414is never overridden. This is what appears in /proc, and is what is used when a415process is the target of an operation by some other process (SIGKILL for416example).417 418The subjective security holds the active security properties of a process, and419may be overridden. This is not seen externally, and is used when a process420acts upon another object, for example SIGKILLing another process or opening a421file.422 423LSM hooks exist that allow SELinux (or Smack or whatever) to reject a request424for CacheFiles to run in a context of a specific security label, or to create425files and directories with another security label.426 427 428Statistical Information429=======================430 431If FS-Cache is compiled with the following option enabled::432 433 CONFIG_CACHEFILES_HISTOGRAM=y434 435then it will gather certain statistics and display them through a proc file.436 437 /proc/fs/cachefiles/histogram438 439 ::440 441 cat /proc/fs/cachefiles/histogram442 JIFS SECS LOOKUPS MKDIRS CREATES443 ===== ===== ========= ========= =========444 445 This shows the breakdown of the number of times each amount of time446 between 0 jiffies and HZ-1 jiffies a variety of tasks took to run. The447 columns are as follows:448 449 ======= =======================================================450 COLUMN TIME MEASUREMENT451 ======= =======================================================452 LOOKUPS Length of time to perform a lookup on the backing fs453 MKDIRS Length of time to perform a mkdir on the backing fs454 CREATES Length of time to perform a create on the backing fs455 ======= =======================================================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 particular459 jiffy range covered, and the SECS field the equivalent number of seconds.460 461 462Debugging463=========464 465If CONFIG_CACHEFILES_DEBUG is enabled, the CacheFiles facility can have runtime466debugging enabled by adjusting the value in::467 468 /sys/module/cachefiles/parameters/debug469 470This is a bitmask of debugging streams to enable:471 472 ======= ======= =============================== =======================473 BIT VALUE STREAM POINT474 ======= ======= =============================== =======================475 0 1 General Function entry trace476 1 2 Function exit trace477 2 4 General478 ======= ======= =============================== =======================479 480The appropriate set of values should be OR'd together and the result written to481the control file. For example::482 483 echo $((1|4|8)) >/sys/module/cachefiles/parameters/debug484 485will turn on all function entry debugging.486 487 488On-demand Read489==============490 491When working in its original mode, CacheFiles serves as a local cache for a492remote networking fs - while in on-demand read mode, CacheFiles can boost the493scenario where on-demand read semantics are needed, e.g. container image494distribution.495 496The essential difference between these two modes is seen when a cache miss497occurs: In the original mode, the netfs will fetch the data from the remote498server and then write it to the cache file; in on-demand read mode, fetching499the 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 504Protocol Communication505----------------------506 507The on-demand read mode uses a simple protocol for communication between kernel508and user daemon. The protocol can be modeled as::509 510 kernel --[request]--> user daemon --[reply]--> kernel511 512CacheFiles will send requests to the user daemon when needed. The user daemon513should poll the devnode ('/dev/cachefiles') to check if there's a pending514request to be processed. A POLLIN event will be returned when there's a pending515request.516 517The user daemon then reads the devnode to fetch a request to process. It should518be noted that each read only gets one request. When it has finished processing519the request, the user daemon should write the reply to the devnode.520 521Each 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 531where:532 533 * ``msg_id`` is a unique ID identifying this request among all pending534 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 the543 header and following type-specific payload.544 545 546Turning on On-demand Mode547-------------------------548 549An optional parameter becomes available to the "bind" command::550 551 bind [ondemand]552 553When the "bind" command is given no argument, it defaults to the original mode.554When it is given the "ondemand" argument, i.e. "bind ondemand", on-demand read555mode will be enabled.556 557 558The OPEN Request559----------------560 561When the netfs opens a cache file for the first time, a request with the562CACHEFILES_OP_OPEN opcode, a.k.a an OPEN request will be sent to the user563daemon. 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 573where: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 binary577 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, through584 which the user daemon can perform write/llseek file operations on the585 cache file.586 587 588The user daemon can use the given (volume_key, cookie_key) pair to distinguish589the requested cache file. With the given anonymous fd, the user daemon can590fetch the data and write it to the cache file in the background, even when591kernel has not triggered a cache miss yet.592 593Be noted that each cache file has a unique object_id, while it may have multiple594anonymous fds. The user daemon may duplicate anonymous fds from the initial595anonymous fd indicated by the @fd field through dup(). Thus each object_id can596be mapped to multiple anonymous fds, while the usr daemon itself needs to597maintain the mapping.598 599When 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't601be huge since they're related to the number of open device blobs rather than602open files of each individual filesystem.603 604The user daemon should reply the OPEN request by issuing a "copen" (complete605open) command on the devnode::606 607 copen <msg_id>,<cache_size>608 609where: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 the615 user daemon.616 617 618The CLOSE Request619-----------------620 621When a cookie withdrawn, a CLOSE request (opcode CACHEFILES_OP_CLOSE) will be622sent to the user daemon. This tells the user daemon to close all anonymous fds623associated with the given object_id. The CLOSE request has no extra payload,624and shouldn't be replied.625 626 627The READ Request628----------------629 630When a cache miss is encountered in on-demand read mode, CacheFiles will send a631READ request (opcode CACHEFILES_OP_READ) to the user daemon. This tells the user632daemon to fetch the contents of the requested file range. The payload is of the633form::634 635 struct cachefiles_read {636 __u64 off;637 __u64 len;638 };639 640where: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 647When it receives a READ request, the user daemon should fetch the requested data648and write it to the cache file identified by object_id.649 650When it has finished processing the READ request, the user daemon should reply651by using the CACHEFILES_IOC_READ_COMPLETE ioctl on one of the anonymous fds652associated with the object_id given in the READ request. The ioctl is of the653form::654 655 ioctl(fd, CACHEFILES_IOC_READ_COMPLETE, msg_id);656 657where:658 659 * ``fd`` is one of the anonymous fds associated with the object_id660 given.661 662 * ``msg_id`` must match the msg_id field of the READ request.663