cachefiles.rst 23 KB

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