Back to home page

OSCL-LXR

 
 

    


0001 .. SPDX-License-Identifier: GPL-2.0
0002 
0003 ===================================
0004 Cache on Already Mounted Filesystem
0005 ===================================
0006 
0007 .. Contents:
0008 
0009  (*) Overview.
0010 
0011  (*) Requirements.
0012 
0013  (*) Configuration.
0014 
0015  (*) Starting the cache.
0016 
0017  (*) Things to avoid.
0018 
0019  (*) Cache culling.
0020 
0021  (*) Cache structure.
0022 
0023  (*) Security model and SELinux.
0024 
0025  (*) A note on security.
0026 
0027  (*) Statistical information.
0028 
0029  (*) Debugging.
0030 
0031  (*) On-demand Read.
0032 
0033 
0034 Overview
0035 ========
0036 
0037 CacheFiles is a caching backend that's meant to use as a cache a directory on
0038 an already mounted filesystem of a local type (such as Ext3).
0039 
0040 CacheFiles uses a userspace daemon to do some of the cache management - such as
0041 reaping stale nodes and culling.  This is called cachefilesd and lives in
0042 /sbin.
0043 
0044 The filesystem and data integrity of the cache are only as good as those of the
0045 filesystem providing the backing services.  Note that CacheFiles does not
0046 attempt to journal anything since the journalling interfaces of the various
0047 filesystems are very specific in nature.
0048 
0049 CacheFiles creates a misc character device - "/dev/cachefiles" - that is used
0050 to communication with the daemon.  Only one thing may have this open at once,
0051 and while it is open, a cache is at least partially in existence.  The daemon
0052 opens this and sends commands down it to control the cache.
0053 
0054 CacheFiles is currently limited to a single cache.
0055 
0056 CacheFiles attempts to maintain at least a certain percentage of free space on
0057 the filesystem, shrinking the cache by culling the objects it contains to make
0058 space if necessary - see the "Cache Culling" section.  This means it can be
0059 placed on the same medium as a live set of data, and will expand to make use of
0060 spare space and automatically contract when the set of data requires more
0061 space.
0062 
0063 
0064 
0065 Requirements
0066 ============
0067 
0068 The use of CacheFiles and its daemon requires the following features to be
0069 available in the system and in the cache filesystem:
0070 
0071         - dnotify.
0072 
0073         - extended attributes (xattrs).
0074 
0075         - openat() and friends.
0076 
0077         - bmap() support on files in the filesystem (FIBMAP ioctl).
0078 
0079         - The use of bmap() to detect a partial page at the end of the file.
0080 
0081 It is strongly recommended that the "dir_index" option is enabled on Ext3
0082 filesystems being used as a cache.
0083 
0084 
0085 Configuration
0086 =============
0087 
0088 The cache is configured by a script in /etc/cachefilesd.conf.  These commands
0089 set up cache ready for use.  The following script commands are available:
0090 
0091  brun <N>%, bcull <N>%, bstop <N>%, frun <N>%, fcull <N>%, fstop <N>%
0092         Configure the culling limits.  Optional.  See the section on culling
0093         The defaults are 7% (run), 5% (cull) and 1% (stop) respectively.
0094 
0095         The commands beginning with a 'b' are file space (block) limits, those
0096         beginning with an 'f' are file count limits.
0097 
0098  dir <path>
0099         Specify the directory containing the root of the cache.  Mandatory.
0100 
0101  tag <name>
0102         Specify a tag to FS-Cache to use in distinguishing multiple caches.
0103         Optional.  The default is "CacheFiles".
0104 
0105  debug <mask>
0106         Specify a numeric bitmask to control debugging in the kernel module.
0107         Optional.  The default is zero (all off).  The following values can be
0108         OR'd into the mask to collect various information:
0109 
0110                 ==      =================================================
0111                 1       Turn on trace of function entry (_enter() macros)
0112                 2       Turn on trace of function exit (_leave() macros)
0113                 4       Turn on trace of internal debug points (_debug())
0114                 ==      =================================================
0115 
0116         This mask can also be set through sysfs, eg::
0117 
0118                 echo 5 >/sys/modules/cachefiles/parameters/debug
0119 
0120 
0121 Starting the Cache
0122 ==================
0123 
0124 The cache is started by running the daemon.  The daemon opens the cache device,
0125 configures the cache and tells it to begin caching.  At that point the cache
0126 binds to fscache and the cache becomes live.
0127 
0128 The daemon is run as follows::
0129 
0130         /sbin/cachefilesd [-d]* [-s] [-n] [-f <configfile>]
0131 
0132 The flags are:
0133 
0134  ``-d``
0135         Increase the debugging level.  This can be specified multiple times and
0136         is cumulative with itself.
0137 
0138  ``-s``
0139         Send messages to stderr instead of syslog.
0140 
0141  ``-n``
0142         Don't daemonise and go into background.
0143 
0144  ``-f <configfile>``
0145         Use an alternative configuration file rather than the default one.
0146 
0147 
0148 Things to Avoid
0149 ===============
0150 
0151 Do not mount other things within the cache as this will cause problems.  The
0152 kernel module contains its own very cut-down path walking facility that ignores
0153 mountpoints, but the daemon can't avoid them.
0154 
0155 Do not create, rename or unlink files and directories in the cache while the
0156 cache is active, as this may cause the state to become uncertain.
0157 
0158 Renaming files in the cache might make objects appear to be other objects (the
0159 filename is part of the lookup key).
0160 
0161 Do not change or remove the extended attributes attached to cache files by the
0162 cache as this will cause the cache state management to get confused.
0163 
0164 Do not create files or directories in the cache, lest the cache get confused or
0165 serve incorrect data.
0166 
0167 Do not chmod files in the cache.  The module creates things with minimal
0168 permissions to prevent random users being able to access them directly.
0169 
0170 
0171 Cache Culling
0172 =============
0173 
0174 The cache may need culling occasionally to make space.  This involves
0175 discarding objects from the cache that have been used less recently than
0176 anything else.  Culling is based on the access time of data objects.  Empty
0177 directories are culled if not in use.
0178 
0179 Cache culling is done on the basis of the percentage of blocks and the
0180 percentage of files available in the underlying filesystem.  There are six
0181 "limits":
0182 
0183  brun, frun
0184      If the amount of free space and the number of available files in the cache
0185      rises above both these limits, then culling is turned off.
0186 
0187  bcull, fcull
0188      If the amount of available space or the number of available files in the
0189      cache falls below either of these limits, then culling is started.
0190 
0191  bstop, fstop
0192      If the amount of available space or the number of available files in the
0193      cache falls below either of these limits, then no further allocation of
0194      disk space or files is permitted until culling has raised things above
0195      these limits again.
0196 
0197 These must be configured thusly::
0198 
0199         0 <= bstop < bcull < brun < 100
0200         0 <= fstop < fcull < frun < 100
0201 
0202 Note that these are percentages of available space and available files, and do
0203 _not_ appear as 100 minus the percentage displayed by the "df" program.
0204 
0205 The userspace daemon scans the cache to build up a table of cullable objects.
0206 These are then culled in least recently used order.  A new scan of the cache is
0207 started as soon as space is made in the table.  Objects will be skipped if
0208 their atimes have changed or if the kernel module says it is still using them.
0209 
0210 
0211 Cache Structure
0212 ===============
0213 
0214 The CacheFiles module will create two directories in the directory it was
0215 given:
0216 
0217  * cache/
0218  * graveyard/
0219 
0220 The active cache objects all reside in the first directory.  The CacheFiles
0221 kernel module moves any retired or culled objects that it can't simply unlink
0222 to the graveyard from which the daemon will actually delete them.
0223 
0224 The daemon uses dnotify to monitor the graveyard directory, and will delete
0225 anything that appears therein.
0226 
0227 
0228 The module represents index objects as directories with the filename "I..." or
0229 "J...".  Note that the "cache/" directory is itself a special index.
0230 
0231 Data objects are represented as files if they have no children, or directories
0232 if they do.  Their filenames all begin "D..." or "E...".  If represented as a
0233 directory, data objects will have a file in the directory called "data" that
0234 actually holds the data.
0235 
0236 Special objects are similar to data objects, except their filenames begin
0237 "S..." or "T...".
0238 
0239 
0240 If an object has children, then it will be represented as a directory.
0241 Immediately in the representative directory are a collection of directories
0242 named for hash values of the child object keys with an '@' prepended.  Into
0243 this directory, if possible, will be placed the representations of the child
0244 objects::
0245 
0246          /INDEX    /INDEX     /INDEX                            /DATA FILES
0247         /=========/==========/=================================/================
0248         cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400
0249         cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...DB1ry
0250         cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...N22ry
0251         cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...FP1ry
0252 
0253 
0254 If the key is so long that it exceeds NAME_MAX with the decorations added on to
0255 it, then it will be cut into pieces, the first few of which will be used to
0256 make a nest of directories, and the last one of which will be the objects
0257 inside the last directory.  The names of the intermediate directories will have
0258 '+' prepended::
0259 
0260         J1223/@23/+xy...z/+kl...m/Epqr
0261 
0262 
0263 Note that keys are raw data, and not only may they exceed NAME_MAX in size,
0264 they may also contain things like '/' and NUL characters, and so they may not
0265 be suitable for turning directly into a filename.
0266 
0267 To handle this, CacheFiles will use a suitably printable filename directly and
0268 "base-64" encode ones that aren't directly suitable.  The two versions of
0269 object filenames indicate the encoding:
0270 
0271         =============== =============== ===============
0272         OBJECT TYPE     PRINTABLE       ENCODED
0273         =============== =============== ===============
0274         Index           "I..."          "J..."
0275         Data            "D..."          "E..."
0276         Special         "S..."          "T..."
0277         =============== =============== ===============
0278 
0279 Intermediate directories are always "@" or "+" as appropriate.
0280 
0281 
0282 Each object in the cache has an extended attribute label that holds the object
0283 type ID (required to distinguish special objects) and the auxiliary data from
0284 the netfs.  The latter is used to detect stale objects in the cache and update
0285 or retire them.
0286 
0287 
0288 Note that CacheFiles will erase from the cache any file it doesn't recognise or
0289 any file of an incorrect type (such as a FIFO file or a device file).
0290 
0291 
0292 Security Model and SELinux
0293 ==========================
0294 
0295 CacheFiles is implemented to deal properly with the LSM security features of
0296 the Linux kernel and the SELinux facility.
0297 
0298 One of the problems that CacheFiles faces is that it is generally acting on
0299 behalf of a process, and running in that process's context, and that includes a
0300 security context that is not appropriate for accessing the cache - either
0301 because the files in the cache are inaccessible to that process, or because if
0302 the process creates a file in the cache, that file may be inaccessible to other
0303 processes.
0304 
0305 The way CacheFiles works is to temporarily change the security context (fsuid,
0306 fsgid and actor security label) that the process acts as - without changing the
0307 security context of the process when it the target of an operation performed by
0308 some other process (so signalling and suchlike still work correctly).
0309 
0310 
0311 When the CacheFiles module is asked to bind to its cache, it:
0312 
0313  (1) Finds the security label attached to the root cache directory and uses
0314      that as the security label with which it will create files.  By default,
0315      this is::
0316 
0317         cachefiles_var_t
0318 
0319  (2) Finds the security label of the process which issued the bind request
0320      (presumed to be the cachefilesd daemon), which by default will be::
0321 
0322         cachefilesd_t
0323 
0324      and asks LSM to supply a security ID as which it should act given the
0325      daemon's label.  By default, this will be::
0326 
0327         cachefiles_kernel_t
0328 
0329      SELinux transitions the daemon's security ID to the module's security ID
0330      based on a rule of this form in the policy::
0331 
0332         type_transition <daemon's-ID> kernel_t : process <module's-ID>;
0333 
0334      For instance::
0335 
0336         type_transition cachefilesd_t kernel_t : process cachefiles_kernel_t;
0337 
0338 
0339 The module's security ID gives it permission to create, move and remove files
0340 and directories in the cache, to find and access directories and files in the
0341 cache, to set and access extended attributes on cache objects, and to read and
0342 write files in the cache.
0343 
0344 The daemon's security ID gives it only a very restricted set of permissions: it
0345 may scan directories, stat files and erase files and directories.  It may
0346 not read or write files in the cache, and so it is precluded from accessing the
0347 data cached therein; nor is it permitted to create new files in the cache.
0348 
0349 
0350 There are policy source files available in:
0351 
0352         https://people.redhat.com/~dhowells/fscache/cachefilesd-0.8.tar.bz2
0353 
0354 and later versions.  In that tarball, see the files::
0355 
0356         cachefilesd.te
0357         cachefilesd.fc
0358         cachefilesd.if
0359 
0360 They are built and installed directly by the RPM.
0361 
0362 If a non-RPM based system is being used, then copy the above files to their own
0363 directory and run::
0364 
0365         make -f /usr/share/selinux/devel/Makefile
0366         semodule -i cachefilesd.pp
0367 
0368 You will need checkpolicy and selinux-policy-devel installed prior to the
0369 build.
0370 
0371 
0372 By default, the cache is located in /var/fscache, but if it is desirable that
0373 it should be elsewhere, than either the above policy files must be altered, or
0374 an auxiliary policy must be installed to label the alternate location of the
0375 cache.
0376 
0377 For instructions on how to add an auxiliary policy to enable the cache to be
0378 located elsewhere when SELinux is in enforcing mode, please see::
0379 
0380         /usr/share/doc/cachefilesd-*/move-cache.txt
0381 
0382 When the cachefilesd rpm is installed; alternatively, the document can be found
0383 in the sources.
0384 
0385 
0386 A Note on Security
0387 ==================
0388 
0389 CacheFiles makes use of the split security in the task_struct.  It allocates
0390 its own task_security structure, and redirects current->cred to point to it
0391 when it acts on behalf of another process, in that process's context.
0392 
0393 The reason it does this is that it calls vfs_mkdir() and suchlike rather than
0394 bypassing security and calling inode ops directly.  Therefore the VFS and LSM
0395 may deny the CacheFiles access to the cache data because under some
0396 circumstances the caching code is running in the security context of whatever
0397 process issued the original syscall on the netfs.
0398 
0399 Furthermore, should CacheFiles create a file or directory, the security
0400 parameters with that object is created (UID, GID, security label) would be
0401 derived from that process that issued the system call, thus potentially
0402 preventing other processes from accessing the cache - including CacheFiles's
0403 cache management daemon (cachefilesd).
0404 
0405 What is required is to temporarily override the security of the process that
0406 issued the system call.  We can't, however, just do an in-place change of the
0407 security data as that affects the process as an object, not just as a subject.
0408 This means it may lose signals or ptrace events for example, and affects what
0409 the process looks like in /proc.
0410 
0411 So CacheFiles makes use of a logical split in the security between the
0412 objective security (task->real_cred) and the subjective security (task->cred).
0413 The objective security holds the intrinsic security properties of a process and
0414 is never overridden.  This is what appears in /proc, and is what is used when a
0415 process is the target of an operation by some other process (SIGKILL for
0416 example).
0417 
0418 The subjective security holds the active security properties of a process, and
0419 may be overridden.  This is not seen externally, and is used whan a process
0420 acts upon another object, for example SIGKILLing another process or opening a
0421 file.
0422 
0423 LSM hooks exist that allow SELinux (or Smack or whatever) to reject a request
0424 for CacheFiles to run in a context of a specific security label, or to create
0425 files and directories with another security label.
0426 
0427 
0428 Statistical Information
0429 =======================
0430 
0431 If FS-Cache is compiled with the following option enabled::
0432 
0433         CONFIG_CACHEFILES_HISTOGRAM=y
0434 
0435 then it will gather certain statistics and display them through a proc file.
0436 
0437  /proc/fs/cachefiles/histogram
0438 
0439      ::
0440 
0441         cat /proc/fs/cachefiles/histogram
0442         JIFS  SECS  LOOKUPS   MKDIRS    CREATES
0443         ===== ===== ========= ========= =========
0444 
0445      This shows the breakdown of the number of times each amount of time
0446      between 0 jiffies and HZ-1 jiffies a variety of tasks took to run.  The
0447      columns are as follows:
0448 
0449         =======         =======================================================
0450         COLUMN          TIME MEASUREMENT
0451         =======         =======================================================
0452         LOOKUPS         Length of time to perform a lookup on the backing fs
0453         MKDIRS          Length of time to perform a mkdir on the backing fs
0454         CREATES         Length of time to perform a create on the backing fs
0455         =======         =======================================================
0456 
0457      Each row shows the number of events that took a particular range of times.
0458      Each step is 1 jiffy in size.  The JIFS column indicates the particular
0459      jiffy range covered, and the SECS field the equivalent number of seconds.
0460 
0461 
0462 Debugging
0463 =========
0464 
0465 If CONFIG_CACHEFILES_DEBUG is enabled, the CacheFiles facility can have runtime
0466 debugging enabled by adjusting the value in::
0467 
0468         /sys/module/cachefiles/parameters/debug
0469 
0470 This is a bitmask of debugging streams to enable:
0471 
0472         ======= ======= =============================== =======================
0473         BIT     VALUE   STREAM                          POINT
0474         ======= ======= =============================== =======================
0475         0       1       General                         Function entry trace
0476         1       2                                       Function exit trace
0477         2       4                                       General
0478         ======= ======= =============================== =======================
0479 
0480 The appropriate set of values should be OR'd together and the result written to
0481 the control file.  For example::
0482 
0483         echo $((1|4|8)) >/sys/module/cachefiles/parameters/debug
0484 
0485 will turn on all function entry debugging.
0486 
0487 
0488 On-demand Read
0489 ==============
0490 
0491 When working in its original mode, CacheFiles serves as a local cache for a
0492 remote networking fs - while in on-demand read mode, CacheFiles can boost the
0493 scenario where on-demand read semantics are needed, e.g. container image
0494 distribution.
0495 
0496 The essential difference between these two modes is seen when a cache miss
0497 occurs: In the original mode, the netfs will fetch the data from the remote
0498 server and then write it to the cache file; in on-demand read mode, fetching
0499 the data and writing it into the cache is delegated to a user daemon.
0500 
0501 ``CONFIG_CACHEFILES_ONDEMAND`` should be enabled to support on-demand read mode.
0502 
0503 
0504 Protocol Communication
0505 ----------------------
0506 
0507 The on-demand read mode uses a simple protocol for communication between kernel
0508 and user daemon. The protocol can be modeled as::
0509 
0510         kernel --[request]--> user daemon --[reply]--> kernel
0511 
0512 CacheFiles will send requests to the user daemon when needed.  The user daemon
0513 should poll the devnode ('/dev/cachefiles') to check if there's a pending
0514 request to be processed.  A POLLIN event will be returned when there's a pending
0515 request.
0516 
0517 The user daemon then reads the devnode to fetch a request to process.  It should
0518 be noted that each read only gets one request. When it has finished processing
0519 the request, the user daemon should write the reply to the devnode.
0520 
0521 Each request starts with a message header of the form::
0522 
0523         struct cachefiles_msg {
0524                 __u32 msg_id;
0525                 __u32 opcode;
0526                 __u32 len;
0527                 __u32 object_id;
0528                 __u8  data[];
0529         };
0530 
0531 where:
0532 
0533         * ``msg_id`` is a unique ID identifying this request among all pending
0534           requests.
0535 
0536         * ``opcode`` indicates the type of this request.
0537 
0538         * ``object_id`` is a unique ID identifying the cache file operated on.
0539 
0540         * ``data`` indicates the payload of this request.
0541 
0542         * ``len`` indicates the whole length of this request, including the
0543           header and following type-specific payload.
0544 
0545 
0546 Turning on On-demand Mode
0547 -------------------------
0548 
0549 An optional parameter becomes available to the "bind" command::
0550 
0551         bind [ondemand]
0552 
0553 When the "bind" command is given no argument, it defaults to the original mode.
0554 When it is given the "ondemand" argument, i.e. "bind ondemand", on-demand read
0555 mode will be enabled.
0556 
0557 
0558 The OPEN Request
0559 ----------------
0560 
0561 When the netfs opens a cache file for the first time, a request with the
0562 CACHEFILES_OP_OPEN opcode, a.k.a an OPEN request will be sent to the user
0563 daemon.  The payload format is of the form::
0564 
0565         struct cachefiles_open {
0566                 __u32 volume_key_size;
0567                 __u32 cookie_key_size;
0568                 __u32 fd;
0569                 __u32 flags;
0570                 __u8  data[];
0571         };
0572 
0573 where:
0574 
0575         * ``data`` contains the volume_key followed directly by the cookie_key.
0576           The volume key is a NUL-terminated string; the cookie key is binary
0577           data.
0578 
0579         * ``volume_key_size`` indicates the size of the volume key in bytes.
0580 
0581         * ``cookie_key_size`` indicates the size of the cookie key in bytes.
0582 
0583         * ``fd`` indicates an anonymous fd referring to the cache file, through
0584           which the user daemon can perform write/llseek file operations on the
0585           cache file.
0586 
0587 
0588 The user daemon can use the given (volume_key, cookie_key) pair to distinguish
0589 the requested cache file.  With the given anonymous fd, the user daemon can
0590 fetch the data and write it to the cache file in the background, even when
0591 kernel has not triggered a cache miss yet.
0592 
0593 Be noted that each cache file has a unique object_id, while it may have multiple
0594 anonymous fds.  The user daemon may duplicate anonymous fds from the initial
0595 anonymous fd indicated by the @fd field through dup().  Thus each object_id can
0596 be mapped to multiple anonymous fds, while the usr daemon itself needs to
0597 maintain the mapping.
0598 
0599 When implementing a user daemon, please be careful of RLIMIT_NOFILE,
0600 ``/proc/sys/fs/nr_open`` and ``/proc/sys/fs/file-max``.  Typically these needn't
0601 be huge since they're related to the number of open device blobs rather than
0602 open files of each individual filesystem.
0603 
0604 The user daemon should reply the OPEN request by issuing a "copen" (complete
0605 open) command on the devnode::
0606 
0607         copen <msg_id>,<cache_size>
0608 
0609 where:
0610 
0611         * ``msg_id`` must match the msg_id field of the OPEN request.
0612 
0613         * When >= 0, ``cache_size`` indicates the size of the cache file;
0614           when < 0, ``cache_size`` indicates any error code encountered by the
0615           user daemon.
0616 
0617 
0618 The CLOSE Request
0619 -----------------
0620 
0621 When a cookie withdrawn, a CLOSE request (opcode CACHEFILES_OP_CLOSE) will be
0622 sent to the user daemon.  This tells the user daemon to close all anonymous fds
0623 associated with the given object_id.  The CLOSE request has no extra payload,
0624 and shouldn't be replied.
0625 
0626 
0627 The READ Request
0628 ----------------
0629 
0630 When a cache miss is encountered in on-demand read mode, CacheFiles will send a
0631 READ request (opcode CACHEFILES_OP_READ) to the user daemon. This tells the user
0632 daemon to fetch the contents of the requested file range.  The payload is of the
0633 form::
0634 
0635         struct cachefiles_read {
0636                 __u64 off;
0637                 __u64 len;
0638         };
0639 
0640 where:
0641 
0642         * ``off`` indicates the starting offset of the requested file range.
0643 
0644         * ``len`` indicates the length of the requested file range.
0645 
0646 
0647 When it receives a READ request, the user daemon should fetch the requested data
0648 and write it to the cache file identified by object_id.
0649 
0650 When it has finished processing the READ request, the user daemon should reply
0651 by using the CACHEFILES_IOC_READ_COMPLETE ioctl on one of the anonymous fds
0652 associated with the object_id given in the READ request.  The ioctl is of the
0653 form::
0654 
0655         ioctl(fd, CACHEFILES_IOC_READ_COMPLETE, msg_id);
0656 
0657 where:
0658 
0659         * ``fd`` is one of the anonymous fds associated with the object_id
0660           given.
0661 
0662         * ``msg_id`` must match the msg_id field of the READ request.