Skip to contentSkip to conversation

Permit filesystem local caching [try #3]

PATCH In review David Howells 3 participants 41 messages Aug 10, 2007 – Aug 15, 2007

Subsystems (18)
lore
Share & tools
lore

David Howells

author maintainer
#0 lore raw

cover Permit filesystem local caching [try #3]

These patches add local caching for network filesystems such as NFS and AFS.

FS-Cache now runs fully asynchronously as required by Trond Myklebust for NFS.

--
Changes:
[try #3]:

(*) Added missing file to CacheFiles patch.

(*) Made new security functions return errors and pass actual return data via
argument pointer.

(*) Cleaned up NFS patch.

(*) The 'fsc' flag must now be passed to NFS mount by the string options.

(*) Split the NFS patch into three as requested by Trond.

[try #2]:

(*) The CacheFiles module no longer accepts directory fds in its cull and
inuse commands from cachefilesd. Instead it uses the current working directory of the calling process as the basis for looking up the object. Corollary to this, fget_light() no longer needs to be exported.

--
A tarball of the patches is available at:

http://people.redhat.com/~dhowells/fscache/patches/nfs+fscache-22.tar.bz2

To use this version of CacheFiles, the cachefilesd-0.9 is also required. It is available as an SRPM:

	http://people.redhat.com/~dhowells/fscache/cachefilesd-0.9-1.fc7.src.rpm

Or as individual bits:

http://people.redhat.com/~dhowells/fscache/cachefilesd-0.9.tar.bz2
http://people.redhat.com/~dhowells/fscache/cachefilesd.fc
http://people.redhat.com/~dhowells/fscache/cachefilesd.if
http://people.redhat.com/~dhowells/fscache/cachefilesd.te
http://people.redhat.com/~dhowells/fscache/cachefilesd.spec

The .fc, .if and .te files are for manipulating SELinux.

David

author maintainer
#1 lore raw

PATCH 1/16 FS-Cache: Release page->private after failed readahead [try #3]

The attached patch causes read_cache_pages() to release page-private data on a page for which add_to_page_cache() fails or the filler function fails. This permits pages with caching references associated with them to be cleaned up.

The invalidatepage() address space op is called (indirectly) to do the honours.

---

 mm/readahead.c |   40 ++++++++++++++++++++++++++++++++++++++--
 1 files changed, 38 insertions(+), 2 deletions(-)
mm/readahead.c +38 -2
index 39bf45d..12d1378 100644
@@ -15,6 +15,7 @@
 #include <linux/backing-dev.h>
 #include <linux/task_io_accounting_ops.h>
 #include <linux/pagevec.h>
+#include <linux/buffer_head.h>
 
 void default_unplug_io_fn(struct backing_dev_info *bdi, struct page *page)
 {
@@ -51,6 +52,41 @@ EXPORT_SYMBOL_GPL(file_ra_state_init);
 
 #define list_to_page(head) (list_entry((head)->prev, struct page, lru))
 
+/*
+ * see if a page needs releasing upon read_cache_pages() failure
+ * - the caller of read_cache_pages() may have set PG_private before calling,
+ *   such as the NFS fs marking pages that are cached locally on disk, thus we
+ *   need to give the fs a chance to clean up in the event of an error
+ */
+static void read_cache_pages_invalidate_page(struct address_space *mapping,
+					     struct page *page)
+{
+	if (PagePrivate(page)) {
+		if (TestSetPageLocked(page))
+			BUG();
+		page->mapping = mapping;
+		do_invalidatepage(page, 0);
+		page->mapping = NULL;
+		unlock_page(page);
+	}
+	page_cache_release(page);
+}
+
+/*
+ * release a list of pages, invalidating them first if need be
+ */
+static void read_cache_pages_invalidate_pages(struct address_space *mapping,
+					      struct list_head *pages)
+{
+	struct page *victim;
+
+	while (!list_empty(pages)) {
+		victim = list_to_page(pages);
+		list_del(&victim->lru);
+		read_cache_pages_invalidate_page(mapping, victim);
+	}
+}
+
 /**
  * read_cache_pages - populate an address space with some pages & start reads against them
  * @mapping: the address_space
@@ -74,14 +110,14 @@ int read_cache_pages(struct address_space *mapping, struct list_head *pages,
 		page = list_to_page(pages);
 		list_del(&page->lru);
 		if (add_to_page_cache(page, mapping, page->index, GFP_KERNEL)) {
-			page_cache_release(page);
+			read_cache_pages_invalidate_page(mapping, page);
 			continue;
 		}
 		ret = filler(data, page);
 		if (!pagevec_add(&lru_pvec, page))
 			__pagevec_lru_add(&lru_pvec);
 		if (ret) {
-			put_pages_list(pages);
+			read_cache_pages_invalidate_pages(mapping, pages);
 			break;
 		}
 		task_io_account_read(PAGE_CACHE_SIZE);
author maintainer
#3 lore raw

PATCH 3/16 FS-Cache: Provide an add_wait_queue_tail() function [try #3]

In reply to David Howells

Provide an add_wait_queue_tail() function to add a waiter to the back of a wait queue instead of the front.

---

 include/linux/wait.h |    1 +
 kernel/wait.c        |   18 ++++++++++++++++++
 2 files changed, 19 insertions(+), 0 deletions(-)
include/linux/wait.h +1 -0
index 0e68628..4cae7db 100644
@@ -118,6 +118,7 @@ static inline int waitqueue_active(wait_queue_head_t *q)
 #define is_sync_wait(wait)	(!(wait) || ((wait)->private))
 
 extern void FASTCALL(add_wait_queue(wait_queue_head_t *q, wait_queue_t * wait));
+extern void FASTCALL(add_wait_queue_tail(wait_queue_head_t *q, wait_queue_t * wait));
 extern void FASTCALL(add_wait_queue_exclusive(wait_queue_head_t *q, wait_queue_t * wait));
 extern void FASTCALL(remove_wait_queue(wait_queue_head_t *q, wait_queue_t * wait));
 
kernel/wait.c +18 -0
index 444ddbf..7acc9cc 100644
@@ -29,6 +29,24 @@ void fastcall add_wait_queue(wait_queue_head_t *q, wait_queue_t *wait)
 }
 EXPORT_SYMBOL(add_wait_queue);
 
+/**
+ * add_wait_queue_tail - Add a waiter to the back of a waitqueue
+ * @q: the wait queue to append the waiter to
+ * @wait: the waiter to be queued
+ *
+ * Add a waiter to the back of a waitqueue so that it gets woken up last.
+ */
+void fastcall add_wait_queue_tail(wait_queue_head_t *q, wait_queue_t *wait)
+{
+	unsigned long flags;
+
+	wait->flags &= ~WQ_FLAG_EXCLUSIVE;
+	spin_lock_irqsave(&q->lock, flags);
+	__add_wait_queue_tail(q, wait);
+	spin_unlock_irqrestore(&q->lock, flags);
+}
+EXPORT_SYMBOL(add_wait_queue_tail);
+
 void fastcall add_wait_queue_exclusive(wait_queue_head_t *q, wait_queue_t *wait)
 {
 	unsigned long flags;
author maintainer
#4 lore raw

PATCH 4/16 FS-Cache: Generic filesystem caching facility [try #3]

In reply to David Howells

The attached patch adds a generic intermediary (FS-Cache) by which filesystems may call on local caching capabilities, and by which local caching backends may make caches available:

	+---------+
	|         |                        +--------------+
	|   NFS   |--+                     |              |
	|         |  |                 +-->|   CacheFS    |
	+---------+  |   +----------+  |   |  /dev/hda5   |
	             |   |          |  |   +--------------+
	+---------+  +-->|          |  |
	|         |      |          |--+
	|   AFS   |----->| FS-Cache |
	|         |      |          |--+
	+---------+  +-->|          |  |
	             |   |          |  |   +--------------+
	+---------+  |   +----------+  |   |              |
	|         |  |                 +-->|  CacheFiles  |
	|  ISOFS  |--+                     |  /var/cache  |
	|         |                        +--------------+
	+---------+

The patch also documents the netfs interface and the cache backend interface provided by the facility.

There are a number of reasons why I'm not using i_mapping to do this. These have been discussed a lot on the LKML and CacheFS mailing lists, but to summarise the basics:

(1) Most filesystems don't do hole reportage. Holes in files are treated as blocks of zeros and can't be distinguished otherwise, making it difficult to distinguish blocks that have been read from the network and cached from those that haven't.

(2) The backing inode must be fully populated before being exposed to userspace through the main inode because the VM/VFS goes directly to the backing inode and does not interrogate the front inode on VM ops.

Therefore:

(a) The backing inode must fit entirely within the cache.

(b) All backed files currently open must fit entirely within the cache at the same time.

(c) A working set of files in total larger than the cache may not be cached.

(d) A file may not grow larger than the available space in the cache.

(e) A file that's open and cached, and remotely grows larger than the cache is potentially stuffed.

(3) Writes go to the backing filesystem, and can only be transferred to the network when the file is closed.

(4) There's no record of what changes have been made, so the whole file must be written back.

(5) The pages belong to the backing filesystem, and all metadata associated with that page are relevant only to the backing filesystem, and not anything stacked atop it.

The attached patch adds a generic core to which both networking filesystems and caches may bind. It transfers requests from networking filesystems to appropriate caches if possible, or else gracefully denies them.

If this facility is disabled in the kernel configuration, then all its operations will be trivially reducible to nothing by the compiler.

FS-Cache provides the following facilities:

(1) Caches can be added / removed at any time, even whilst in use.

(2) Adds a facility by which tags can be used to refer to caches, even if they're not mounted yet.

(3) More than one cache can be used at once. Caches can be selected explicitly by use of tags.

(4) The netfs is provided with an interface that allows either party to withdraw caching facilities from a file (required for (1)).

(5) A netfs may annotate cache objects that belongs to it.

(6) Cache objects can be pinned and reservations made.

(7) The interface to the netfs returns as few errors as possible, preferring rather to let the netfs remain oblivious.

(8) Cookies are used to represent indices, files and other objects to the netfs. The simplest cookie is just a NULL pointer - indicating nothing cached there.

(9) The netfs is allowed to propose - dynamically - any index hierarchy it desires, though it must be aware that the index search function is recursive, stack space is limited, and indices can only be children of indices.

(10) Indices can be used to group files together to reduce key size and to make group invalidation easier. The use of indices may make lookup quicker, but that's cache dependent.

(11) Data I/O is effectively done directly to and from the netfs's pages. The netfs indicates that page A is at index B of the data-file represented by cookie C, and that it should be read or written. The cache backend may or may not start I/O on that page, but if it does, a netfs callback will be invoked to indicate completion. The I/O may be either synchronous or asynchronous.

(12) Cookies can be "retired" upon release. At this point FS-Cache will mark them as obsolete and the index hierarchy rooted at that point will get recycled.

(13) The netfs provides a "match" function for index searches. In addition to saying whether a match was made or not, this can also specify that an entry should be updated or deleted.

FS-Cache maintains a virtual indexing tree in which all indices, files, objects and pages are kept. Bits of this tree may actually reside in one or more caches.

FSDEF
|
+------------------------------------+
| |
NFS AFS
| |
+--------------------------+ +-----------+
| | | |
homedir mirror afs.org redhat.com
| | |
+------------+ +---------------+ +----------+
| | | | | |
00001 00002 00007 00125 vol00001 vol00002

     |            |           |               |                         |
 +---+---+     +-----+      +---+      +------+------+            +-----+----+
 |   |   |     |     |      |   |      |      |      |            |     |    |
PG0 PG1 PG2   PG0  XATTR   PG0 PG1   DIRENT DIRENT DIRENT        R/W   R/O  Bak
                     |                                            |
                    PG0                                       +-------+
                                                              |       |
                                                            00001   00003
                                                              |
                                                          +---+---+
                                                          |   |   |
                                                         PG0 PG1 PG2

In the example above, you can see two netfs's being backed: NFS and AFS. These have different index hierarchies:

(*) The NFS primary index will probably contain per-server indices. Each
server index is indexed by NFS file handles to get data file objects. Each data file objects can have an array of pages, but may also have further child objects, such as extended attributes and directory entries. Extended attribute objects themselves have page-array contents.

(*) The AFS primary index contains per-cell indices. Each cell index contains
per-logical-volume indices. Each of volume index contains up to three indices for the read-write, read-only and backup mirrors of those volumes. Each of these contains vnode data file objects, each of which contains an array of pages.

The very top index is the FS-Cache master index in which individual netfs's have entries.

Any index object may reside in more than one cache, provided it only has index children. Any index with non-index object children will be assumed to only reside in one cache.

The FS-Cache overview can be found in:

Documentation/filesystems/caching/fscache.txt

The netfs API to FS-Cache can be found in:

Documentation/filesystems/caching/netfs-api.txt

The cache backend API to FS-Cache can be found in:

Documentation/filesystems/caching/backend-api.txt

---

 Documentation/filesystems/caching/backend-api.txt |  625 +++++++++++++++
 Documentation/filesystems/caching/fscache.txt     |  295 +++++++
 Documentation/filesystems/caching/netfs-api.txt   |  741 ++++++++++++++++++
 fs/Kconfig                                        |    6 
 fs/Makefile                                       |    1 
 fs/fscache/Kconfig                                |   49 +
 fs/fscache/Makefile                               |   19 
 fs/fscache/fsc-cache.c                            |  512 ++++++++++++
 fs/fscache/fsc-cookie.c                           |  494 ++++++++++++
 fs/fscache/fsc-fsdef.c                            |  111 +++
 fs/fscache/fsc-internal.h                         |  376 +++++++++
 fs/fscache/fsc-main.c                             |  127 +++
 fs/fscache/fsc-manage.c                           |  260 ++++++
 fs/fscache/fsc-object.c                           |  586 ++++++++++++++
 fs/fscache/fsc-page.c                             |  863 +++++++++++++++++++++
 fs/fscache/fsc-proc.c                             |  399 ++++++++++
 fs/fscache/fsc-stats.c                            |  103 +++
 fs/fscache/fsc-threads.c                          |  590 ++++++++++++++
 include/linux/fscache-cache.h                     |  433 +++++++++++
 include/linux/fscache.h                           |  593 ++++++++++++++
 20 files changed, 7183 insertions(+), 0 deletions(-)
Documentation/filesystems/caching/backend-api.txt new file +625 -0
new file mode 100644
index 0000000..a7e58eb
@@ -0,0 +1,625 @@
+			  ==========================
+			  FS-CACHE CACHE BACKEND API
+			  ==========================
+
+The FS-Cache system provides an API by which actual caches can be supplied to
+FS-Cache for it to then serve out to network filesystems and other interested
+parties.
+
+This API is declared in <linux/fscache-cache.h>.
+
+
+====================================
+INITIALISING AND REGISTERING A CACHE
+====================================
+
+To start off, a cache definition must be initialised and registered for each
+cache the backend wants to make available.  For instance, CacheFS does this in
+the fill_super() operation on mounting.
+
+The cache definition (struct fscache_cache) should be initialised by calling:
+
+	void fscache_init_cache(struct fscache_cache *cache,
+				struct fscache_cache_ops *ops,
+				const char *idfmt,
+				...);
+
+Where:
+
+ (*) "cache" is a pointer to the cache definition;
+
+ (*) "ops" is a pointer to the table of operations that the backend supports on
+     this cache; and
+
+ (*) "idfmt" is a format and printf-style arguments for constructing a label
+     for the cache.
+
+
+The cache should then be registered with FS-Cache by passing a pointer to the
+previously initialised cache definition to:
+
+	int fscache_add_cache(struct fscache_cache *cache,
+			      struct fscache_object *fsdef,
+			      const char *tagname);
+
+Two extra arguments should also be supplied:
+
+ (*) "fsdef" which should point to the object representation for the FS-Cache
+     master index in this cache.  Netfs primary index entries will be created
+     here.
+
+ (*) "tagname" which, if given, should be a text string naming this cache.  If
+     this is NULL, the identifier will be used instead.  For CacheFS, the
+     identifier is set to name the underlying block device and the tag can be
+     supplied by mount.
+
+This function may return -ENOMEM if it ran out of memory or -EEXIST if the tag
+is already in use.  0 will be returned on success.
+
+
+=====================
+UNREGISTERING A CACHE
+=====================
+
+A cache can be withdrawn from the system by calling this function with a
+pointer to the cache definition:
+
+	void fscache_withdraw_cache(struct fscache_cache *cache);
+
+In CacheFS's case, this is called by put_super().
+
+
+========
+SECURITY
+========
+
+The cache methods are executed one of two contexts:
+
+ (1) that of the userspace process that issued the netfs operation that caused
+     the cache method to be invoked, or
+
+ (2) that of one of the processes in the FS-Cache thread pool.
+
+In either case, this may not be an appropriate context in which to access the
+cache.
+
+The calling process's fsuid, fsgid and SELinux security identities may need to
+be masqueraded for the duration of the cache driver's access to the cache.
+This is left to the cache to handle; FS-Cache makes no effort in this regard.
+
+
+===================================
+CONTROL AND STATISTICS PRESENTATION
+===================================
+
+The cache may present data to the outside world through FS-Cache's interfaces
+in sysfs and procfs - the former for control and the latter for statistics.
+
+A sysfs directory called /sys/fs/fscache/<cachetag>/ is created if CONFIG_SYSFS
+is enabled.  This is accessible through the kobject struct fscache_cache::kobj
+and is for use by the cache as it sees fit.
+
+The cache driver may create itself a directory named for the cache type in the
+/proc/fs/fscache/ directory.  This is available if CONFIG_FSCACHE_PROC is
+enabled and is accessible through:
+
+	struct proc_dir_entry *proc_fscache;
+
+
+========================
+RELEVANT DATA STRUCTURES
+========================
+
+ (*) Index/Data file FS-Cache representation cookie:
+
+	struct fscache_cookie {
+		struct fscache_object_def	*def;
+		struct fscache_netfs		*netfs;
+		void				*netfs_data;
+		...
+	};
+
+     The fields that might be of use to the backend describe the object
+     definition, the netfs definition and the netfs's data for this cookie.
+     The object definition contain functions supplied by the netfs for loading
+     and matching index entries; these are required to provide some of the
+     cache operations.
+
+
+ (*) In-cache object representation:
+
+	struct fscache_object {
+		int				debug_id;
+		enum {
+			FSCACHE_OBJECT_RECYCLING,
+			...
+		}				state;
+		spinlock_t			lock
+		struct fscache_cache		*cache;
+		struct fscache_cookie		*cookie;
+		...
+	};
+
+     Structures of this type should be allocated by the cache backend and
+     passed to FS-Cache when requested by the appropriate cache operation.  In
+     the case of CacheFS, they're embedded in CacheFS's internal object
+     structures.
+
+     The debug_id is a simple integer that can be used in debugging messages
+     that refer to a particular object.  In such a case it should be printed
+     using "OBJ%x" to be consistent with FS-Cache.
+
+     Each object contains a pointer to the cookie that represents the object it
+     is backing.  An object should retired when put_object() is called if it is
+     in state FSCACHE_OBJECT_RECYCLING.  The fscache_object struct should be
+     initialised by calling fscache_object_init(object).
+
+
+ (*) FS-Cache operation record:
+
+	struct fscache_operation {
+		atomic_t		usage;
+		struct fscache_object	*object;
+		unsigned long		flags;
+	#define FSCACHE_OP_EXCLUSIVE
+		void (*processor)(struct fscache_operation *op);
+		void (*release)(struct fscache_operation *op);
+		...
+	};
+
+     FS-Cache has a pool of threads that it uses to give CPU time to the
+     various asynchronous operations that need to be done as part of driving
+     the cache.  These are represented by the above structure.  The processor
+     method is called to give the op CPU time, and the release method to get
+     rid of it when its usage count reaches 0.
+
+     An operation can be made exclusive upon an object by setting the
+     appropriate flag before enqueuing it with fscache_enqueue_operation().  If
+     an operation needs more processing time, it should be enqueued again.
+
+
+ (*) FS-Cache retrieval operation record:
+
+	struct fscache_retrieval {
+		struct fscache_operation op;
+		struct address_space	*mapping;
+		struct list_head	*to_do;
+		...
+	};
+
+     A structure of this type is allocated by FS-Cache to record retrieval and
+     allocation requests made by the netfs.  This struct is then passed to the
+     backend to do the operation.  The backend may get extra refs to it by
+     calling fscache_get_retrieval() and refs may be discarded by calling
+     fscache_put_retrieval().
+
+     A retrieval operation can be used by the backend to do retrieval work.  To
+     do this, the retrieval->op.processor method pointer should be set
+     appropriately by the backend and fscache_enqueue_retrieval() called to
+     submit it to the thread pool.  CacheFiles, for example, uses this to queue
+     page examination when it detects PG_lock being cleared.
+
+     The to_do field is an empty list available for the cache backend to use as
+     it sees fit.
+
+
+ (*) FS-Cache storage operation record:
+
+	struct fscache_storage {
+		struct fscache_operation op;
+		pgoff_t			store_limit;
+		...
+	};
+
+     A structure of this type is allocated by FS-Cache to record outstanding
+     writes to be made.  FS-Cache itself enqueues this operation and invokes
+     the write_page() method on the object at appropriate times to effect
+     storage.
+
+
+================
+CACHE OPERATIONS
+================
+
+The cache backend provides FS-Cache with a table of operations that can be
+performed on the denizens of the cache.  These are held in a structure of type:
+
+	struct fscache_cache_ops
+
+ (*) Name of cache provider [mandatory]:
+
+	const char *name
+
+     This isn't strictly an operation, but should be pointed at a string naming
+     the backend.
+
+
+ (*) Allocate a new object [mandatory]:
+
+	struct fscache_object *(*alloc_object)(struct fscache_cache *cache,
+					       struct fscache_cookie *cookie)
+
+     This method is used to allocate a cache object representation to back a
+     cookie in a particular cache.  fscache_object_init() should be called on
+     the object to initialise it prior to returning.
+
+     This function may also be used to parse the index key to be used for
+     multiple lookup calls to turn it into a more convenient form.  FS-Cache
+     will call the lookup_complete() method to allow the cache to release the
+     form once lookup is complete or aborted.
+
+
+ (*) Look up and create object [mandatory]:
+
+	void (*lookup_object)(struct fscache_object *object)
+
+     This method is used to look up an object, given that the object is already
+     allocated and attached to the cookie.  This should instantiate that object
+     in the cache if it can.
+
+     The method should call fscache_object_lookup_negative() as soon as
+     possible if it determines the object doesn't exist in the cache.  If the
+     object is found to exist and the netfs indicates that it is valid then
+     fscache_obtained_object() should be called once the object is in a
+     position to have data stored in it.  Similarly, fscache_obtained_object()
+     should also be called once a non-present object has been created.
+
+     If a lookup error occurs, fscache_object_lookup_error() should be called
+     to abort the lookup of that object.
+
+
+ (*) Release lookup data [mandatory]:
+
+	void (*lookup_complete)(struct fscache_object *object)
+
+     This method is called to ask the cache to release any resources it was
+     using to perform a lookup.
+
+
+ (*) Increment object refcount [mandatory]:
+
+	struct fscache_object *(*grab_object)(struct fscache_object *object)
+
+     This method is called to increment the reference count on an object.  It
+     may fail (for instance if the cache is being withdrawn) by returning NULL.
+     It should return the object pointer if successful.
+
+
+ (*) Lock/Unlock object [mandatory]:
+
+	void (*lock_object)(struct fscache_object *object)
+	void (*unlock_object)(struct fscache_object *object)
+
+     These methods are used to exclusively lock an object.  It must be possible
+     to schedule with the lock held, so a spinlock isn't sufficient.
+
+
+ (*) Pin/Unpin object [optional]:
+
+	int (*pin_object)(struct fscache_object *object)
+	void (*unpin_object)(struct fscache_object *object)
+
+     These methods are used to pin an object into the cache.  Once pinned an
+     object cannot be reclaimed to make space.  Return -ENOSPC if there's not
+     enough space in the cache to permit this.
+
+
+ (*) Update object [mandatory]:
+
+	int (*update_object)(struct fscache_object *object)
+
+     This is called to update the index entry for the specified object.  The
+     new information should be in object->cookie->netfs_data.  This can be
+     obtained by calling object->cookie->def->get_aux()/get_attr().
+
+
+ (*) Discard object [mandatory]:
+
+	void (*drop_object)(struct fscache_object *object)
+
+     This method is called to indicate that an object has been unbound from its
+     cookie, and that the cache should release the object's resources and
+     retire it if it's in state FSCACHE_OBJECT_RECYCLING.
+
+     This method should not attempt to release any references held by the
+     caller.  The caller will invoke the put_object() method as appropriate.
+
+
+ (*) Release object reference [mandatory]:
+
+	void (*put_object)(struct fscache_object *object)
+
+     This method is used to discard a reference to an object.  The object may
+     be freed when all the references to it are released.
+
+
+ (*) Synchronise a cache [mandatory]:
+
+	void (*sync)(struct fscache_cache *cache)
+
+     This is called to ask the backend to synchronise a cache with its backing
+     device.
+
+
+ (*) Dissociate a cache [mandatory]:
+
+	void (*dissociate_pages)(struct fscache_cache *cache)
+
+     This is called to ask a cache to perform any page dissociations as part of
+     cache withdrawal.
+
+
+ (*) Notification that the attributes on a netfs file changed [mandatory]:
+
+	int (*attr_changed)(struct fscache_object *object);
+
+     This is called to indicate to the cache that certain attributes on a netfs
+     file have changed (for example the maximum size a file may reach).  The
+     cache can read these from the netfs by calling the cookie's get_attr()
+     method.
+
+     The cache may use the file size information to reserve space on the cache.
+     It should also call fscache_set_store_limit() to indicate to FS-Cache the
+     highest byte it's willing to store for an object.
+
+     This method may return -ve if an error occurred or the cache object cannot
+     be expanded.  In such a case, the object will be withdrawn from service.
+
+     This operation is run asynchronously from FS-Cache's thread pool, and
+     storage and retrieval operations from the netfs are excluded during the
+     execution of this operation.
+
+
+ (*) Reserve cache space for an object's data [optional]:
+
+	int (*reserve_space)(struct fscache_object *object, loff_t size);
+
+     This is called to request that cache space be reserved to hold the data
+     for an object and the metadata used to track it.  Zero size should be
+     taken as request to cancel a reservation.
+
+     This should return 0 if successful, -ENOSPC if there isn't enough space
+     available, or -ENOMEM or -EIO on other errors.
+
+     The reservation may exceed the current size of the object, thus permitting
+     future expansion.  If the amount of space consumed by an object would
+     exceed the reservation, it's permitted to refuse requests to allocate
+     pages, but not required.  An object may be pruned down to its reservation
+     size if larger than that already.
+
+
+ (*) Request page be read from cache [mandatory]:
+
+	int (*read_or_alloc_page)(struct fscache_retrieval *op,
+				  struct page *page,
+				  gfp_t gfp)
+
+     This is called to attempt to read a netfs page from the cache, or to
+     reserve a backing block if not.  FS-Cache will have done as much checking
+     as it can before calling, but most of the work belongs to the backend.
+
+     If there's no page in the cache, then -ENODATA should be returned if the
+     backend managed to reserve a backing block; -ENOBUFS or -ENOMEM if it
+     didn't.
+
+     If there is suitable data in the cache, then a read operation should be
+     queued and 0 returned.  When the read finishes, fscache_end_io() should be
+     called.
+
+     The fscache_mark_pages_cached() should be called for the page if any cache
+     metadata is retained.  This will indicate to the netfs that the page needs
+     explicit uncaching.  This operation takes a pagevec, thus allowing several
+     pages to be marked at once.
+
+     The retrieval record pointed to by op should be retained for each page
+     queued and released when I/O on the page has been formally ended.
+     fscache_get/put_retrieval() are available for this purpose.
+
+     The retrieval record may be used to get CPU time via the FS-Cache thread
+     pool.  If this is desired, the op->op.processor should be set to point to
+     the appropriate processing routine, and fscache_enqueue_retrieval() should
+     be called at an appropriate point to request CPU time.  For instance, the
+     retrieval routine could be enqueued upon the completion of a disk read.
+     The to_do field in the retrieval record is provided to aid in this.
+
+     If an I/O error occurs, fscache_io_error() should be called and -ENOBUFS
+     returned if possible or fscache_end_io() called with a suitable error
+     code..
+
+
+ (*) Request pages be read from cache [mandatory]:
+
+	int (*read_or_alloc_pages)(struct fscache_retrieval *op,
+				   struct list_head *pages,
+				   unsigned *nr_pages,
+				   gfp_t gfp)
+
+     This is like the read_or_alloc_page() method, except it is handed a list
+     of pages instead of one page.  Any pages on which a read operation is
+     started must be added to the page cache for the specified mapping and also
+     to the LRU.  Such pages must also be removed from the pages list and
+     *nr_pages decremented per page.
+
+     If there was an error such as -ENOMEM, then that should be returned; else
+     if one or more pages couldn't be read or allocated, then -ENOBUFS should
+     be returned; else if one or more pages couldn't be read, then -ENODATA
+     should be returned.  If all the pages are dispatched then 0 should be
+     returned.
+
+
+ (*) Request page be allocated in the cache [mandatory]:
+
+	int (*allocate_page)(struct fscache_retrieval *op,
+			     struct page *page,
+			     gfp_t gfp)
+
+     This is like the read_or_alloc_page() method, except that it shouldn't
+     read from the cache, even if there's data there that could be retrieved.
+     It should, however, set up any internal metadata required such that
+     the write_page() method can write to the cache.
+
+     If there's no backing block available, then -ENOBUFS should be returned
+     (or -ENOMEM if there were other problems).  If a block is successfully
+     allocated, then the netfs page should be marked and 0 returned.
+
+
+ (*) Request pages be allocated in the cache [mandatory]:
+
+	int (*allocate_pages)(struct fscache_retrieval *op,
+			      struct list_head *pages,
+			      unsigned *nr_pages,
+			      gfp_t gfp)
+
+     This is an multiple page version of the allocate_page() method.  pages and
+     nr_pages should be treated as for the read_or_alloc_pages() method.
+
+
+ (*) Request page be written to cache [mandatory]:
+
+	int (*write_page)(struct fscache_storage *op,
+			  struct page *page);
+
+     This is called to write from a page on which there was a previously
+     successful read_or_alloc_page() call or similar.  FS-Cache filters out
+     pages that don't have mappings.
+
+     This method is called asynchronously from the FS-Cache thread pool.  It is
+     not required to actually store anything, provided -ENODATA is then
+     returned to the next read of this page.
+
+     If an error occurred, then a negative error code should be returned,
+     otherwise zero should be returned.  FS-Cache will take appropriate action
+     in response to an error, such as withdrawing this object.
+
+     If this method returns success then FS-Cache will inform the netfs
+     appropriately.
+
+
+ (*) Discard retained per-page metadata [mandatory]:
+
+	void (*uncache_page)(struct fscache_object *object, struct page *page)
+
+     This is called when a netfs page is being evicted from the pagecache.  The
+     cache backend should tear down any internal representation or tracking it
+     maintains for this page.
+
+
+==================
+FS-CACHE UTILITIES
+==================
+
+FS-Cache provides some utilities that a cache backend may make use of:
+
+ (*) Note occurrence of an I/O error in a cache:
+
+	void fscache_io_error(struct fscache_cache *cache)
+
+     This tells FS-Cache that an I/O error occurred in the cache.  After this
+     has been called, only resource dissociation operations (object and page
+     release) will be passed from the netfs to the cache backend for the
+     specified cache.
+
+     This does not actually withdraw the cache.  That must be done separately.
+
+
+ (*) Invoke the retrieval I/O completion function:
+
+	void fscache_end_io(struct fscache_retrieval *op, struct page *page,
+			    int error);
+
+     This is called to note the end of an attempt to retrieve a page.  The
+     error value should be 0 if successful and an error otherwise.
+
+
+ (*) Set highest store limit:
+
+	void fscache_set_store_limit(struct fscache_object *object,
+				     loff_t i_size);
+
+     This sets the limit FS-Cache imposes on the highest byte it's willing to
+     try and store for a netfs.  Any page over this limit is automatically
+     rejected by fscache_read_alloc_page() and co with -ENOBUFS.
+
+
+ (*) Mark pages as being cached:
+
+	void fscache_mark_pages_cached(struct fscache_retrieval *op,
+				       struct pagevec *pagevec);
+
+     This marks a set of pages as being cached.  After this has been called,
+     the netfs must call fscache_uncache_page() to unmark the pages.
+
+
+ (*) Initialise a freshly allocated object:
+
+	void fscache_object_init(struct fscache_object *object);
+
+     This initialises all the fields in an object representation.
+
+
+ (*) Indicate negative lookup on an object:
+
+	void fscache_object_lookup_negative(struct fscache_object *object);
+
+     This is called to indicate to FS-Cache that a lookup process for an object
+     found a negative result.
+
+     This changes the state of an object to permit reads pending on lookup
+     completion to go off and start fetching data from the netfs server as it's
+     known at this point that there can't be any data in the cache.
+
+     This may be called multiple times on an object.  Only the first call is
+     significant - all subsequent calls are ignored.
+
+
+ (*) Indicate an object has been obtained:
+
+	void fscache_obtained_object(struct fscache_object *object);
+
+     This is called to indicate to FS-Cache that a lookup process for an object
+     produced a positive result, or that an object was created.  This should
+     only be called once for any particular object.
+
+     This changes the state of an object to indicate:
+
+	(1) if no call to fscache_object_lookup_negative() has been made on
+	    this object, that there may be data available, and that reads can
+	    now go and look for it; and
+
+        (2) that writes may now proceed against this object.
+
+
+ (*) Indicate that object lookup failed:
+
+	void fscache_object_lookup_error(struct fscache_object *object);
+
+     This marks an object as having encountered a fatal error (usually EIO)
+     and causes it to move into a state whereby it will be withdrawn as soon
+     as possible.
+
+
+ (*) Get and release references on a retrieval record:
+
+	void fscache_get_retrieval(struct fscache_retrieval *op);
+	void fscache_put_retrieval(struct fscache_retrieval *op);
+
+     These two functions are used to retain a retrieval record whilst doing
+     asynchronous data retrieval and block allocation.
+
+
+ (*) Enqueue a retrieval record for processing.
+
+	void fscache_enqueue_retrieval(struct fscache_retrieval *op);
+
+     This enqueues a retrieval record for processing by the FS-Cache thread
+     pool.  One of the threads in the pool will invoke the retrieval record's
+     op->op.processor callback function.  This function may be called from
+     within the callback function.
+
+
+ (*) List of object state names:
+
+	const char *fscache_object_states[];
+
+     For debugging purposes, this may be used to turn the state that an object
+     is in into a text string for display purposes.
Documentation/filesystems/caching/fscache.txt new file +295 -0

295 lines not on this page · raw message

Documentation/filesystems/caching/netfs-api.txt new file +741 -0

741 lines not on this page · raw message

fs/Kconfig +6 -0
index 58a0650..3e1c276 100644
@@ -631,6 +631,12 @@ config GENERIC_ACL
 	bool
 	select FS_POSIX_ACL
 
+menu "Caches"
+
+source "fs/fscache/Kconfig"
+
+endmenu
+
 if BLOCK
 menu "CD-ROM/DVD Filesystems"
 
fs/Makefile +1 -0
index 720c29d..4eecc9a 100644
@@ -65,6 +65,7 @@ obj-$(CONFIG_PROFILING)		+= dcookies.o
 obj-$(CONFIG_DLM)		+= dlm/
  
 # Do not add any filesystems before this line
+obj-$(CONFIG_FSCACHE)		+= fscache/
 obj-$(CONFIG_REISERFS_FS)	+= reiserfs/
 obj-$(CONFIG_EXT3_FS)		+= ext3/ # Before ext2 so root fs can be ext3
 obj-$(CONFIG_EXT4DEV_FS)	+= ext4/ # Before ext2 so root fs can be ext4dev
fs/fscache/Kconfig new file +49 -0

49 lines not on this page · raw message

fs/fscache/Makefile new file +19 -0
new file mode 100644
index 0000000..e60dad3
@@ -0,0 +1,19 @@
+#
+# Makefile for general filesystem caching code
+#
+
+fscache-y := \
+	fsc-cache.o \
+	fsc-cookie.o \
+	fsc-fsdef.o \
+	fsc-main.o \
+	fsc-manage.o \
+	fsc-object.o \
+	fsc-page.o \
+	fsc-threads.o
+
+fscache-$(CONFIG_FSCACHE_PROC) += \
+	fsc-proc.o \
+	fsc-stats.o
+
+obj-$(CONFIG_FSCACHE) := fscache.o
fs/fscache/fsc-cache.c new file +512 -0

512 lines not on this page · raw message

fs/fscache/fsc-cookie.c new file +494 -0

494 lines not on this page · raw message

fs/fscache/fsc-fsdef.c new file +111 -0

111 lines not on this page · raw message

fs/fscache/fsc-internal.h new file +376 -0

135 lines not on this page · raw message

fs/fscache/fsc-main.c new file +127 -0

127 lines not on this page · raw message

fs/fscache/fsc-manage.c new file +260 -0

260 lines not on this page · raw message

fs/fscache/fsc-object.c new file +586 -0

586 lines not on this page · raw message

fs/fscache/fsc-page.c new file +863 -0

863 lines not on this page · raw message

fs/fscache/fsc-proc.c new file +399 -0

399 lines not on this page · raw message

fs/fscache/fsc-stats.c new file +103 -0

103 lines not on this page · raw message

fs/fscache/fsc-threads.c new file +590 -0

590 lines not on this page · raw message

include/linux/fscache-cache.h new file +433 -0

433 lines not on this page · raw message

include/linux/fscache.h new file +593 -0

593 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Part of the diff is not shown here. View the raw message.

author maintainer
#5 lore raw

PATCH 5/16 CacheFiles: Add missing copy_page export for ia64 [try #3]

In reply to David Howells

This one-line patch fixes the missing export of copy_page introduced by the cachefile patches. This patch is not yet upstream, but is required for cachefile on ia64. It will be pushed upstream when cachefile goes upstream.

---

 arch/ia64/kernel/ia64_ksyms.c |    1 +
 1 files changed, 1 insertions(+), 0 deletions(-)
arch/ia64/kernel/ia64_ksyms.c +1 -0
index bd17190..20c3546 100644
@@ -43,6 +43,7 @@ EXPORT_SYMBOL(__do_clear_user);
 EXPORT_SYMBOL(__strlen_user);
 EXPORT_SYMBOL(__strncpy_from_user);
 EXPORT_SYMBOL(__strnlen_user);
+EXPORT_SYMBOL(copy_page);
 
 /* from arch/ia64/lib */
 extern void __divsi3(void);
author maintainer
#2 lore raw

PATCH 2/16 FS-Cache: Recruit a couple of page flags for cache management [try #3]

In reply to David Howells

Recruit a couple of page flags to aid in cache management. The following extra flags are defined:

(1) PG_fscache (PG_owner_priv_2)

The marked page is backed by a local cache and is pinning resources in the cache driver.

(2) PG_fscache_write (PG_owner_priv_3)

The marked page is being written to the local cache. The page may not be modified whilst this is in progress.

If PG_fscache is set, then things that checked for PG_private will now also check for that. This includes things like truncation and page invalidation. The function page_has_private() had been added to detect this.

---

 fs/splice.c                |    2 +-
 include/linux/page-flags.h |   30 +++++++++++++++++++++++++++++-
 include/linux/pagemap.h    |   11 +++++++++++
 mm/filemap.c               |   16 ++++++++++++++++
 mm/migrate.c               |    2 +-
 mm/page_alloc.c            |    3 +++
 mm/readahead.c             |    9 +++++----
 mm/swap.c                  |    4 ++--
 mm/swap_state.c            |    4 ++--
 mm/truncate.c              |   10 +++++-----
 mm/vmscan.c                |    2 +-
 11 files changed, 76 insertions(+), 17 deletions(-)
fs/splice.c +1 -1
index c010a72..ae4f5b7 100644
@@ -58,7 +58,7 @@ static int page_cache_pipe_buf_steal(struct pipe_inode_info *pipe,
 		 */
 		wait_on_page_writeback(page);
 
-		if (PagePrivate(page))
+		if (page_has_private(page))
 			try_to_release_page(page, GFP_KERNEL);
 
 		/*
include/linux/page-flags.h +29 -1
index 209d3a4..eaf9854 100644
@@ -83,19 +83,24 @@
 #define PG_private		11	/* If pagecache, has fs-private data */
 
 #define PG_writeback		12	/* Page is under writeback */
+#define PG_owner_priv_2		13	/* Owner use. If pagecache, fs may use */
 #define PG_compound		14	/* Part of a compound page */
 #define PG_swapcache		15	/* Swap page: swp_entry_t in private */
 
 #define PG_mappedtodisk		16	/* Has blocks allocated on-disk */
 #define PG_reclaim		17	/* To be reclaimed asap */
+#define PG_owner_priv_3		18	/* Owner use. If pagecache, fs may use */
 #define PG_buddy		19	/* Page is free, on buddy lists */
 
 /* PG_readahead is only used for file reads; PG_reclaim is only for writes */
 #define PG_readahead		PG_reclaim /* Reminder to do async read-ahead */
 
-/* PG_owner_priv_1 users should have descriptive aliases */
+/* PG_owner_priv_1/2/3 users should have descriptive aliases */
 #define PG_checked		PG_owner_priv_1 /* Used by some filesystems */
 #define PG_pinned		PG_owner_priv_1	/* Xen pinned pagetable */
+#define PG_fscache		PG_owner_priv_2	/* Backed by local cache */
+#define PG_fscache_write	PG_owner_priv_3	/* Writing to local cache */
+
 
 #if (BITS_PER_LONG > 32)
 /*
@@ -199,6 +204,18 @@ static inline void SetPageUptodate(struct page *page)
 #define TestClearPageWriteback(page) test_and_clear_bit(PG_writeback,	\
 							&(page)->flags)
 
+#define PageFsCache(page)	test_bit(PG_fscache, &(page)->flags)
+#define SetPageFsCache(page)	set_bit(PG_fscache, &(page)->flags)
+#define ClearPageFsCache(page)	clear_bit(PG_fscache, &(page)->flags)
+#define TestSetPageFsCache(page) test_and_set_bit(PG_fscache, &(page)->flags)
+#define TestClearPageFsCache(page) test_and_clear_bit(PG_fscache, &(page)->flags)
+
+#define PageFsCacheWrite(page)		test_bit(PG_fscache_write, &(page)->flags)
+#define SetPageFsCacheWrite(page)	set_bit(PG_fscache_write, &(page)->flags)
+#define ClearPageFsCacheWrite(page)	clear_bit(PG_fscache_write, &(page)->flags)
+#define TestSetPageFsCacheWrite(page)	test_and_set_bit(PG_fscache_write, &(page)->flags)
+#define TestClearPageFsCacheWrite(page)	test_and_clear_bit(PG_fscache_write, &(page)->flags)
+
 #define PageBuddy(page)		test_bit(PG_buddy, &(page)->flags)
 #define __SetPageBuddy(page)	__set_bit(PG_buddy, &(page)->flags)
 #define __ClearPageBuddy(page)	__clear_bit(PG_buddy, &(page)->flags)
@@ -272,4 +289,15 @@ static inline void set_page_writeback(struct page *page)
 	test_set_page_writeback(page);
 }
 
+/**
+ * page_has_private - Determine if page has private stuff
+ * @page: The page to be checked
+ *
+ * Determine if a page has private stuff, indicating that release routines
+ * should be invoked upon it.
+ */
+#define page_has_private(page)			\
+	((page)->flags & ((1 << PG_private) |	\
+			  (1 << PG_fscache)))
+
 #endif	/* PAGE_FLAGS_H */
include/linux/pagemap.h +11 -0
index 8a83537..d1049b6 100644
@@ -208,6 +208,17 @@ static inline void wait_on_page_writeback(struct page *page)
 
 extern void end_page_writeback(struct page *page);
 
+/* 
+ * Wait for a page to finish being written to a local cache
+ */
+static inline void wait_on_page_fscache_write(struct page *page)
+{
+	if (PageFsCacheWrite(page))
+		wait_on_page_bit(page, PG_fscache_write);
+}
+
+extern void end_page_fscache_write(struct page *page);
+
 /*
  * Fault a userspace page into pagetables.  Return non-zero on a fault.
  *
mm/filemap.c +16 -0
index 6cf700d..7b96487 100644
@@ -557,6 +557,19 @@ void end_page_writeback(struct page *page)
 EXPORT_SYMBOL(end_page_writeback);
 
 /**
+ * end_page_fscache_write - End writing page to cache
+ * @page: the page
+ */
+void end_page_fscache_write(struct page *page)
+{
+	if (!TestClearPageFsCacheWrite(page))
+		BUG();
+	smp_mb__after_clear_bit();
+	wake_up_page(page, PG_fscache_write);
+}
+EXPORT_SYMBOL(end_page_fscache_write);
+
+/**
  * __lock_page - get a lock on the page, assuming we need to sleep to get it
  * @page: the page to lock
  *
@@ -2243,6 +2256,9 @@ out:
  * (presumably at page->private).  If the release was successful, return `1'.
  * Otherwise return zero.
  *
+ * This may also be called if PG_fscache is set on a page, indicating that the
+ * page is known to the local caching routines.
+ *
  * The @gfp_mask argument specifies whether I/O may be performed to release
  * this page (__GFP_IO), and whether the call may block (__GFP_WAIT).
  *
mm/migrate.c +1 -1
index 37c73b9..828cacf 100644
@@ -544,7 +544,7 @@ static int fallback_migrate_page(struct address_space *mapping,
 	 * Buffers may be managed in a filesystem specific way.
 	 * We must have no buffers or drop them.
 	 */
-	if (PagePrivate(page) &&
+	if (page_has_private(page) &&
 	    !try_to_release_page(page, GFP_KERNEL))
 		return -EAGAIN;
 
mm/page_alloc.c +3 -0
index 3da85b8..96a42d1 100644
@@ -208,6 +208,7 @@ static void bad_page(struct page *page)
 	dump_stack();
 	page->flags &= ~(1 << PG_lru	|
 			1 << PG_private |
+			1 << PG_fscache	|
 			1 << PG_locked	|
 			1 << PG_active	|
 			1 << PG_dirty	|
@@ -445,6 +446,7 @@ static inline int free_pages_check(struct page *page)
 		(page->flags & (
 			1 << PG_lru	|
 			1 << PG_private |
+			1 << PG_fscache	|
 			1 << PG_locked	|
 			1 << PG_active	|
 			1 << PG_slab	|
@@ -593,6 +595,7 @@ static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
 		(page->flags & (
 			1 << PG_lru	|
 			1 << PG_private	|
+			1 << PG_fscache	|
 			1 << PG_locked	|
 			1 << PG_active	|
 			1 << PG_dirty	|
mm/readahead.c +5 -4
index 12d1378..8b5e017 100644
@@ -54,14 +54,15 @@ EXPORT_SYMBOL_GPL(file_ra_state_init);
 
 /*
  * see if a page needs releasing upon read_cache_pages() failure
- * - the caller of read_cache_pages() may have set PG_private before calling,
- *   such as the NFS fs marking pages that are cached locally on disk, thus we
- *   need to give the fs a chance to clean up in the event of an error
+ * - the caller of read_cache_pages() may have set PG_private or PG_fscache
+ *   before calling, such as the NFS fs marking pages that are cached locally
+ *   on disk, thus we need to give the fs a chance to clean up in the event of
+ *   an error
  */
 static void read_cache_pages_invalidate_page(struct address_space *mapping,
 					     struct page *page)
 {
-	if (PagePrivate(page)) {
+	if (page_has_private(page)) {
 		if (TestSetPageLocked(page))
 			BUG();
 		page->mapping = mapping;
mm/swap.c +2 -2
index d3cb966..498d0c1 100644
@@ -412,8 +412,8 @@ void pagevec_strip(struct pagevec *pvec)
 	for (i = 0; i < pagevec_count(pvec); i++) {
 		struct page *page = pvec->pages[i];
 
-		if (PagePrivate(page) && !TestSetPageLocked(page)) {
-			if (PagePrivate(page))
+		if (page_has_private(page) && !TestSetPageLocked(page)) {
+			if (page_has_private(page))
 				try_to_release_page(page, 0);
 			unlock_page(page);
 		}
mm/swap_state.c +2 -2
index 67daecb..93667ef 100644
@@ -75,7 +75,7 @@ static int __add_to_swap_cache(struct page *page, swp_entry_t entry,
 	int error;
 
 	BUG_ON(PageSwapCache(page));
-	BUG_ON(PagePrivate(page));
+	BUG_ON(page_has_private(page));
 	error = radix_tree_preload(gfp_mask);
 	if (!error) {
 		write_lock_irq(&swapper_space.tree_lock);
@@ -126,7 +126,7 @@ void __delete_from_swap_cache(struct page *page)
 	BUG_ON(!PageLocked(page));
 	BUG_ON(!PageSwapCache(page));
 	BUG_ON(PageWriteback(page));
-	BUG_ON(PagePrivate(page));
+	BUG_ON(page_has_private(page));
 
 	radix_tree_delete(&swapper_space.page_tree, page_private(page));
 	set_page_private(page, 0);
mm/truncate.c +5 -5
index 5cdfbc1..5555cb0 100644
@@ -48,7 +48,7 @@ void do_invalidatepage(struct page *page, unsigned long offset)
 static inline void truncate_partial_page(struct page *page, unsigned partial)
 {
 	zero_user_page(page, partial, PAGE_CACHE_SIZE - partial, KM_USER0);
-	if (PagePrivate(page))
+	if (page_has_private(page))
 		do_invalidatepage(page, partial);
 }
 
@@ -97,7 +97,7 @@ truncate_complete_page(struct address_space *mapping, struct page *page)
 
 	cancel_dirty_page(page, PAGE_CACHE_SIZE);
 
-	if (PagePrivate(page))
+	if (page_has_private(page))
 		do_invalidatepage(page, 0);
 
 	remove_from_page_cache(page);
@@ -122,7 +122,7 @@ invalidate_complete_page(struct address_space *mapping, struct page *page)
 	if (page->mapping != mapping)
 		return 0;
 
-	if (PagePrivate(page) && !try_to_release_page(page, 0))
+	if (page_has_private(page) && !try_to_release_page(page, 0))
 		return 0;
 
 	ret = remove_mapping(mapping, page);
@@ -344,14 +344,14 @@ invalidate_complete_page2(struct address_space *mapping, struct page *page)
 	if (page->mapping != mapping)
 		return 0;
 
-	if (PagePrivate(page) && !try_to_release_page(page, GFP_KERNEL))
+	if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL))
 		return 0;
 
 	write_lock_irq(&mapping->tree_lock);
 	if (PageDirty(page))
 		goto failed;
 
-	BUG_ON(PagePrivate(page));
+	BUG_ON(page_has_private(page));
 	__remove_from_page_cache(page);
 	write_unlock_irq(&mapping->tree_lock);
 	ClearPageUptodate(page);
mm/vmscan.c +1 -1
index d419e10..de851f4 100644
@@ -548,7 +548,7 @@ static unsigned long shrink_page_list(struct list_head *page_list,
 		 * process address space (page_count == 1) it can be freed.
 		 * Otherwise, leave the page on the LRU so it is swappable.
 		 */
-		if (PagePrivate(page)) {
+		if (page_has_private(page)) {
 			if (!try_to_release_page(page, sc->gfp_mask))
 				goto activate_locked;
 			if (!mapping && page_count(page) == 1)
author maintainer
#6 lore raw

PATCH 6/16 CacheFiles: Add a hook to write a single page of data to an inode [try #3]

In reply to David Howells

Add an address space operation to write one single page of data to an inode at a page-aligned location (thus permitting the implementation to be highly optimised).

This is used by CacheFiles to store the contents of netfs pages into their backing file pages.

Supply a generic implementation for this that uses the prepare_write() and commit_write() address_space operations to bound a copy directly into the page cache.

Hook the Ext2 and Ext3 operations to the generic implementation.

---

 fs/ext2/inode.c    |    2 +
 fs/ext3/inode.c    |    3 ++
 include/linux/fs.h |    7 ++++
 mm/filemap.c       |   95 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 107 insertions(+), 0 deletions(-)
fs/ext2/inode.c +2 -0
index 0079b2c..b3e4b50 100644
@@ -695,6 +695,7 @@ const struct address_space_operations ext2_aops = {
 	.direct_IO		= ext2_direct_IO,
 	.writepages		= ext2_writepages,
 	.migratepage		= buffer_migrate_page,
+	.write_one_page		= generic_file_buffered_write_one_page,
 };
 
 const struct address_space_operations ext2_aops_xip = {
@@ -713,6 +714,7 @@ const struct address_space_operations ext2_nobh_aops = {
 	.direct_IO		= ext2_direct_IO,
 	.writepages		= ext2_writepages,
 	.migratepage		= buffer_migrate_page,
+	.write_one_page		= generic_file_buffered_write_one_page,
 };
 
 /*
fs/ext3/inode.c +3 -0
index de4e316..93809eb 100644
@@ -1713,6 +1713,7 @@ static const struct address_space_operations ext3_ordered_aops = {
 	.releasepage	= ext3_releasepage,
 	.direct_IO	= ext3_direct_IO,
 	.migratepage	= buffer_migrate_page,
+	.write_one_page	= generic_file_buffered_write_one_page,
 };
 
 static const struct address_space_operations ext3_writeback_aops = {
@@ -1727,6 +1728,7 @@ static const struct address_space_operations ext3_writeback_aops = {
 	.releasepage	= ext3_releasepage,
 	.direct_IO	= ext3_direct_IO,
 	.migratepage	= buffer_migrate_page,
+	.write_one_page	= generic_file_buffered_write_one_page,
 };
 
 static const struct address_space_operations ext3_journalled_aops = {
@@ -1740,6 +1742,7 @@ static const struct address_space_operations ext3_journalled_aops = {
 	.bmap		= ext3_bmap,
 	.invalidatepage	= ext3_invalidatepage,
 	.releasepage	= ext3_releasepage,
+	.write_one_page	= generic_file_buffered_write_one_page,
 };
 
 void ext3_set_aops(struct inode *inode)
include/linux/fs.h +7 -0
index 6bf1395..1b1f288 100644
@@ -433,6 +433,11 @@ struct address_space_operations {
 	int (*migratepage) (struct address_space *,
 			struct page *, struct page *);
 	int (*launder_page) (struct page *);
+	/* write the contents of the source page over the page at the specified
+	 * index in the target address space (the source page does not need to
+	 * be related to the target address space) */
+	int (*write_one_page)(struct address_space *, pgoff_t, struct page *);
+
 };
 
 struct backing_dev_info;
@@ -1669,6 +1674,8 @@ extern ssize_t generic_file_direct_write(struct kiocb *, const struct iovec *,
 		unsigned long *, loff_t, loff_t *, size_t, size_t);
 extern ssize_t generic_file_buffered_write(struct kiocb *, const struct iovec *,
 		unsigned long, loff_t, loff_t *, size_t, ssize_t);
+extern int generic_file_buffered_write_one_page(struct address_space *,
+						pgoff_t, struct page *);
 extern ssize_t do_sync_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos);
 extern ssize_t do_sync_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos);
 extern void do_generic_mapping_read(struct address_space *mapping,
mm/filemap.c +95 -0

101 lines not on this page · raw message

author maintainer
#7 lore raw

PATCH 7/16 CacheFiles: Permit the page lock state to be monitored [try #3]

In reply to David Howells

Add a function to install a monitor on the page lock waitqueue for a particular page, thus allowing the page being unlocked to be detected.

This is used by CacheFiles to detect read completion on a page in the backing filesystem so that it can then copy the data to the waiting netfs page.

---

 include/linux/pagemap.h |    5 +++++
 mm/filemap.c            |   19 +++++++++++++++++++
 2 files changed, 24 insertions(+), 0 deletions(-)
include/linux/pagemap.h +5 -0
index d1049b6..452fdcf 100644
@@ -220,6 +220,11 @@ static inline void wait_on_page_fscache_write(struct page *page)
 extern void end_page_fscache_write(struct page *page);
 
 /*
+ * Add an arbitrary waiter to a page's wait queue
+ */
+extern void add_page_wait_queue(struct page *page, wait_queue_t *waiter);
+
+/*
  * Fault a userspace page into pagetables.  Return non-zero on a fault.
  *
  * This assumes that two userspace pages are always sufficient.  That's
mm/filemap.c +19 -0
index 5e419a2..c60c24e 100644
@@ -518,6 +518,25 @@ void fastcall wait_on_page_bit(struct page *page, int bit_nr)
 EXPORT_SYMBOL(wait_on_page_bit);
 
 /**
+ * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
+ * @page - Page defining the wait queue of interest
+ * @waiter - Waiter to add to the queue
+ *
+ * Add an arbitrary @waiter to the wait queue for the nominated @page.
+ */
+void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
+{
+	wait_queue_head_t *q = page_waitqueue(page);
+	unsigned long flags;
+
+	spin_lock_irqsave(&q->lock, flags);
+	__add_wait_queue(q, waiter);
+	spin_unlock_irqrestore(&q->lock, flags);
+}
+
+EXPORT_SYMBOL_GPL(add_page_wait_queue);
+
+/**
  * unlock_page - unlock a locked page
  * @page: the page
  *
author maintainer
#8 lore raw

PATCH 8/16 CacheFiles: Export things for CacheFiles [try #3]

In reply to David Howells

Export a number of functions for CacheFiles's use.

---

 fs/super.c       |    2 ++
 kernel/auditsc.c |    2 ++
 2 files changed, 4 insertions(+), 0 deletions(-)
fs/super.c +2 -0
index fc8ebed..c0d99dd 100644
@@ -270,6 +270,8 @@ int fsync_super(struct super_block *sb)
 	return sync_blockdev(sb->s_bdev);
 }
 
+EXPORT_SYMBOL_GPL(fsync_super);
+
 /**
  *	generic_shutdown_super	-	common helper for ->kill_sb()
  *	@sb: superblock to kill
kernel/auditsc.c +2 -0
index 3401293..0112179 100644
@@ -1526,6 +1526,8 @@ add_names:
 	}
 }
 
+EXPORT_SYMBOL_GPL(__audit_inode_child);
+
 /**
  * auditsc_get_stamp - get local copies of audit_context values
  * @ctx: audit_context for the task
author maintainer
#9 lore raw

PATCH 9/16 CacheFiles: Permit a process's create SID to be overridden [try #3]

In reply to David Howells

Make it possible for a process's file creation SID to be temporarily overridden by CacheFiles so that files created in the cache have the right label attached.

Without this facility, files created in the cache will be given the current file creation SID of whatever process happens to have invoked CacheFiles indirectly by means of opening a netfs file at the time the cache file is created.

---

 include/linux/security.h |   39 +++++++++++++++++++++++++++++++++++++++
 security/dummy.c         |   14 ++++++++++++++
 security/selinux/hooks.c |   20 ++++++++++++++++++++
 3 files changed, 73 insertions(+), 0 deletions(-)
include/linux/security.h +39 -0
index c11dc8a..edd1677 100644
@@ -1147,6 +1147,15 @@ struct request_sock;
  *	@secdata contains the security context.
  *	@seclen contains the length of the security context.
  *
+ * @get_fscreate_secid:
+ *	Get the current FS security ID.
+ *	@secid points the location in which to return the security ID.
+ *
+ * @set_fscreate_secid:
+ *	Set the current FS security ID.
+ *	@secid contains the security ID to set.
+ *	@oldsecid points the location in which to return the old security ID.
+ *
  * This is the main security structure.
  */
 struct security_operations {
@@ -1330,6 +1339,8 @@ struct security_operations {
  	int (*setprocattr)(struct task_struct *p, char *name, void *value, size_t size);
 	int (*secid_to_secctx)(u32 secid, char **secdata, u32 *seclen);
 	void (*release_secctx)(char *secdata, u32 seclen);
+	int (*get_fscreate_secid)(u32 *secid);
+	int (*set_fscreate_secid)(u32 secid, u32 *oldsecid);
 
 #ifdef CONFIG_SECURITY_NETWORK
 	int (*unix_stream_connect) (struct socket * sock,
@@ -2127,6 +2138,16 @@ static inline void security_release_secctx(char *secdata, u32 seclen)
 	return security_ops->release_secctx(secdata, seclen);
 }
 
+static inline int security_get_fscreate_secid(u32 *secid)
+{
+	return security_ops->get_fscreate_secid(secid);
+}
+
+static inline int security_set_fscreate_secid(u32 secid, u32 *oldsecid)
+{
+	return security_ops->set_fscreate_secid(secid, oldsecid);
+}
+
 /* prototypes */
 extern int security_init	(void);
 extern int register_security	(struct security_operations *ops);
@@ -2795,6 +2816,11 @@ static inline void securityfs_remove(struct dentry *dentry)
 {
 }
 
+static inline int security_to_secctx_secid(char *secdata, u32 seclen, u32 *secid)
+{
+	return -EOPNOTSUPP;
+}
+
 static inline int security_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
 {
 	return -EOPNOTSUPP;
@@ -2803,6 +2829,19 @@ static inline int security_secid_to_secctx(u32 secid, char **secdata, u32 *secle
 static inline void security_release_secctx(char *secdata, u32 seclen)
 {
 }
+
+static inline int security_get_fscreate_secid(u32 *secid)
+{
+	*secid = 0;
+	return 0;
+}
+
+static inline int security_set_fscreate_secid(u32 secid, u32 *oldsecid)
+{
+	*oldsecid = 0;
+	return 0;
+}
+
 #endif	/* CONFIG_SECURITY */
 
 #ifdef CONFIG_SECURITY_NETWORK
security/dummy.c +14 -0
index 19d813d..9e81edb 100644
@@ -930,6 +930,18 @@ static void dummy_release_secctx(char *secdata, u32 seclen)
 {
 }
 
+static int dummy_get_fscreate_secid(u32 *secid)
+{
+	*secid = 0;
+	return 0;
+}
+
+static int dummy_set_fscreate_secid(u32 secid, u32 *oldsecid)
+{
+	*oldsecid = 0;
+	return 0;
+}
+
 #ifdef CONFIG_KEYS
 static inline int dummy_key_alloc(struct key *key, struct task_struct *ctx,
 				  unsigned long flags)
@@ -1084,6 +1096,8 @@ void security_fixup_ops (struct security_operations *ops)
  	set_to_dummy_if_null(ops, setprocattr);
  	set_to_dummy_if_null(ops, secid_to_secctx);
  	set_to_dummy_if_null(ops, release_secctx);
+ 	set_to_dummy_if_null(ops, get_fscreate_secid);
+ 	set_to_dummy_if_null(ops, set_fscreate_secid);
 #ifdef CONFIG_SECURITY_NETWORK
 	set_to_dummy_if_null(ops, unix_stream_connect);
 	set_to_dummy_if_null(ops, unix_may_send);
security/selinux/hooks.c +20 -0
index 6237933..f82a03d 100644
@@ -4661,6 +4661,24 @@ static void selinux_release_secctx(char *secdata, u32 seclen)
 	kfree(secdata);
 }
 
+static int selinux_get_fscreate_secid(u32 *secid)
+{
+	struct task_security_struct *tsec = current->security;
+
+	*secid = tsec->create_sid;
+	return 0;
+}
+
+static int selinux_set_fscreate_secid(u32 secid, u32 *oldsecid)
+{
+	struct task_security_struct *tsec = current->security;
+	u32 oldsid = tsec->create_sid;
+
+	tsec->create_sid = secid;
+	*oldsecid = oldsid;
+	return 0;
+}
+
 #ifdef CONFIG_KEYS
 
 static int selinux_key_alloc(struct key *k, struct task_struct *tsk,
@@ -4843,6 +4861,8 @@ static struct security_operations selinux_ops = {
 
 	.secid_to_secctx =		selinux_secid_to_secctx,
 	.release_secctx =		selinux_release_secctx,
+	.get_fscreate_secid =		selinux_get_fscreate_secid,
+	.set_fscreate_secid =		selinux_set_fscreate_secid,
 
         .unix_stream_connect =		selinux_socket_unix_stream_connect,
 	.unix_may_send =		selinux_socket_unix_may_send,
author maintainer
#11 lore raw

PATCH 10/16 CacheFiles: Add an act-as SID override in task_security_struct [try #3]

In reply to David Howells

Add an act-as SID to task_security_struct that is equivalent to fsuid/fsgid in task_struct. This permits a task to perform operations as if it is the overriding SID, without changing its own SID as that might be needed to control access to the process by ptrace, signals, /proc, etc.

This is useful for CacheFiles in that it allows CacheFiles to access the cache files and directories using the cache's security context rather than the security context of the process on whose behalf it is working, and in the context of which it is running.

---

 include/linux/security.h          |   36 ++++++++
 security/dummy.c                  |   14 +++
 security/selinux/exports.c        |    2 
 security/selinux/hooks.c          |  162 +++++++++++++++++++++++--------------
 security/selinux/include/objsec.h |    1 
 security/selinux/selinuxfs.c      |    2 
 security/selinux/xfrm.c           |    6 +
 7 files changed, 156 insertions(+), 67 deletions(-)
include/linux/security.h +36 -0
index edd1677..194ef49 100644
@@ -1156,6 +1156,18 @@ struct request_sock;
  *	@secid contains the security ID to set.
  *	@oldsecid points the location in which to return the old security ID.
  *
+ * @act_as_secid:
+ *	Set the security ID as which to act, returning the security ID as which
+ *      the process was previously acting.
+ *	@secid contains the security ID to act as.
+ *	@oldsecid points the location in which to return the displaced security ID.
+ *
+ * @act_as_self:
+ *	Reset the security ID as which to act to be the same as the process's
+ *      owning security ID, and return the security ID as which the process was
+ *      previously acting.
+ *	@oldsecid points the location in which to return the displaced security ID.
+ *
  * This is the main security structure.
  */
 struct security_operations {
@@ -1341,6 +1353,8 @@ struct security_operations {
 	void (*release_secctx)(char *secdata, u32 seclen);
 	int (*get_fscreate_secid)(u32 *secid);
 	int (*set_fscreate_secid)(u32 secid, u32 *oldsecid);
+	int (*act_as_secid)(u32 secid, u32 *oldsecid);
+	int (*act_as_self)(u32 *oldsecid);
 
 #ifdef CONFIG_SECURITY_NETWORK
 	int (*unix_stream_connect) (struct socket * sock,
@@ -2148,6 +2162,16 @@ static inline int security_set_fscreate_secid(u32 secid, u32 *oldsecid)
 	return security_ops->set_fscreate_secid(secid, oldsecid);
 }
 
+static inline int security_act_as_secid(u32 secid, u32 *oldsecid)
+{
+	return security_ops->act_as_secid(secid, oldsecid);
+}
+
+static inline int security_act_as_self(u32 *oldsecid)
+{
+	return security_ops->act_as_self(oldsecid);
+}
+
 /* prototypes */
 extern int security_init	(void);
 extern int register_security	(struct security_operations *ops);
@@ -2842,6 +2866,18 @@ static inline int security_set_fscreate_secid(u32 secid, u32 *oldsecid)
 	return 0;
 }
 
+static inline int security_act_as_secid(u32 secid, u32 *oldsecid)
+{
+	*oldsecid = 0;
+	return 0;
+}
+
+static inline u32 security_act_as_self(u32 *oldsecid)
+{
+	*oldsecid = 0;
+	return 0;
+}
+
 #endif	/* CONFIG_SECURITY */
 
 #ifdef CONFIG_SECURITY_NETWORK
security/dummy.c +14 -0
index 9e81edb..1a0be85 100644
@@ -942,6 +942,18 @@ static int dummy_set_fscreate_secid(u32 secid, u32 *oldsecid)
 	return 0;
 }
 
+static int dummy_act_as_secid(u32 secid, u32 *oldsecid)
+{
+	*oldsecid = 0;
+	return 0;
+}
+
+static int dummy_act_as_self(u32 *oldsecid)
+{
+	*oldsecid = 0;
+	return 0;
+}
+
 #ifdef CONFIG_KEYS
 static inline int dummy_key_alloc(struct key *key, struct task_struct *ctx,
 				  unsigned long flags)
@@ -1098,6 +1110,8 @@ void security_fixup_ops (struct security_operations *ops)
  	set_to_dummy_if_null(ops, release_secctx);
  	set_to_dummy_if_null(ops, get_fscreate_secid);
  	set_to_dummy_if_null(ops, set_fscreate_secid);
+ 	set_to_dummy_if_null(ops, act_as_secid);
+ 	set_to_dummy_if_null(ops, act_as_self);
 #ifdef CONFIG_SECURITY_NETWORK
 	set_to_dummy_if_null(ops, unix_stream_connect);
 	set_to_dummy_if_null(ops, unix_may_send);
security/selinux/exports.c +1 -1
index b6f9694..b559699 100644
@@ -79,7 +79,7 @@ int selinux_relabel_packet_permission(u32 sid)
 	if (selinux_enabled) {
 		struct task_security_struct *tsec = current->security;
 
-		return avc_has_perm(tsec->sid, sid, SECCLASS_PACKET,
+		return avc_has_perm(tsec->actor_sid, sid, SECCLASS_PACKET,
 				    PACKET__RELABELTO, NULL);
 	}
 	return 0;
security/selinux/hooks.c +100 -62

505 lines not on this page · raw message

security/selinux/include/objsec.h +1 -0
index 91b88f0..884df98 100644
@@ -31,6 +31,7 @@ struct task_security_struct {
 	struct task_struct *task;      /* back pointer to task object */
 	u32 osid;            /* SID prior to last execve */
 	u32 sid;             /* current SID */
+	u32 actor_sid;       /* act-as SID (normally == sid) */
 	u32 exec_sid;        /* exec SID */
 	u32 create_sid;      /* fscreate SID */
 	u32 keycreate_sid;   /* keycreate SID */
security/selinux/selinuxfs.c +1 -1
index c9e92da..8df8e6a 100644
@@ -83,7 +83,7 @@ static int task_has_security(struct task_struct *tsk,
 	if (!tsec)
 		return -EACCES;
 
-	return avc_has_perm(tsec->sid, SECINITSID_SECURITY,
+	return avc_has_perm(tsec->actor_sid, SECINITSID_SECURITY,
 			    SECCLASS_SECURITY, perms, NULL);
 }
 
security/selinux/xfrm.c +3 -3
index ba715f4..873b6ba 100644
@@ -240,7 +240,7 @@ static int selinux_xfrm_sec_ctx_alloc(struct xfrm_sec_ctx **ctxp,
 	/*
 	 * Does the subject have permission to set security context?
 	 */
-	rc = avc_has_perm(tsec->sid, ctx->ctx_sid,
+	rc = avc_has_perm(tsec->actor_sid, ctx->ctx_sid,
 			  SECCLASS_ASSOCIATION,
 			  ASSOCIATION__SETCONTEXT, NULL);
 	if (rc)
@@ -341,7 +341,7 @@ int selinux_xfrm_policy_delete(struct xfrm_policy *xp)
 	int rc = 0;
 
 	if (ctx)
-		rc = avc_has_perm(tsec->sid, ctx->ctx_sid,
+		rc = avc_has_perm(tsec->actor_sid, ctx->ctx_sid,
 				  SECCLASS_ASSOCIATION,
 				  ASSOCIATION__SETCONTEXT, NULL);
 
@@ -383,7 +383,7 @@ int selinux_xfrm_state_delete(struct xfrm_state *x)
 	int rc = 0;
 
 	if (ctx)
-		rc = avc_has_perm(tsec->sid, ctx->ctx_sid,
+		rc = avc_has_perm(tsec->actor_sid, ctx->ctx_sid,
 				  SECCLASS_ASSOCIATION,
 				  ASSOCIATION__SETCONTEXT, NULL);
 
author maintainer
#12 lore raw

PATCH 11/16 CacheFiles: Permit an inode's security ID to be obtained [try #3]

In reply to David Howells

Permit an inode's security ID to be obtained by the CacheFiles module. This is then used as the SID with which files and directories will be created in the cache.

---

 include/linux/security.h |   19 +++++++++++++++++++
 security/dummy.c         |    7 +++++++
 security/selinux/hooks.c |    9 +++++++++
 3 files changed, 35 insertions(+), 0 deletions(-)
include/linux/security.h +19 -0
index 194ef49..a54958a 100644
@@ -414,6 +414,11 @@ struct request_sock;
  *	the size of the buffer required.
  *	Returns number of bytes used/required on success.
  *
+ * @inode_get_secid:
+ *	Retrieve the security ID from an inode.
+ *	@inode refers to the inode to get the security ID from.
+ *	@secid points the location in which to return the security ID.
+ *
  * Security hooks for file operations
  *
  * @file_permission:
@@ -1256,6 +1261,7 @@ struct security_operations {
   	int (*inode_getsecurity)(const struct inode *inode, const char *name, void *buffer, size_t size, int err);
   	int (*inode_setsecurity)(struct inode *inode, const char *name, const void *value, size_t size, int flags);
   	int (*inode_listsecurity)(struct inode *inode, char *buffer, size_t buffer_size);
+	int (*inode_get_secid)(struct inode *inode, u32 *secid);
 
 	int (*file_permission) (struct file * file, int mask);
 	int (*file_alloc_security) (struct file * file);
@@ -1818,6 +1824,13 @@ static inline int security_inode_listsecurity(struct inode *inode, char *buffer,
 	return security_ops->inode_listsecurity(inode, buffer, buffer_size);
 }
 
+static inline int security_inode_get_secid(struct inode *inode, u32 *secid)
+{
+	if (unlikely(IS_PRIVATE(inode)))
+		return 0;
+	return security_ops->inode_get_secid(inode, secid);
+}
+
 static inline int security_file_permission (struct file *file, int mask)
 {
 	return security_ops->file_permission (file, mask);
@@ -2518,6 +2531,12 @@ static inline int security_inode_listsecurity(struct inode *inode, char *buffer,
 	return 0;
 }
 
+static inline int security_inode_get_secid(struct inode *inode, u32 *secid)
+{
+	*secid = 0;
+	return 0;
+}
+
 static inline int security_file_permission (struct file *file, int mask)
 {
 	return 0;
security/dummy.c +7 -0
index 1a0be85..6be18fe 100644
@@ -392,6 +392,12 @@ static int dummy_inode_listsecurity(struct inode *inode, char *buffer, size_t bu
 	return 0;
 }
 
+static int dummy_inode_get_secid(struct inode *inode, u32 *secid)
+{
+	*secid = 0;
+	return 0;
+}
+
 static const char *dummy_inode_xattr_getsuffix(void)
 {
 	return NULL;
@@ -1046,6 +1052,7 @@ void security_fixup_ops (struct security_operations *ops)
 	set_to_dummy_if_null(ops, inode_getsecurity);
 	set_to_dummy_if_null(ops, inode_setsecurity);
 	set_to_dummy_if_null(ops, inode_listsecurity);
+	set_to_dummy_if_null(ops, inode_get_secid);
 	set_to_dummy_if_null(ops, file_permission);
 	set_to_dummy_if_null(ops, file_alloc_security);
 	set_to_dummy_if_null(ops, file_free_security);
security/selinux/hooks.c +9 -0
index 2c64ec8..34646f8 100644
@@ -2464,6 +2464,14 @@ static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t
 	return len;
 }
 
+static int selinux_inode_get_secid(struct inode *inode, u32 *secid)
+{
+	struct inode_security_struct *isec = inode->i_security;
+
+	*secid = isec->sid;
+	return 0;
+}
+
 /* file security operations */
 
 static int selinux_file_permission(struct file *file, int mask)
@@ -4826,6 +4834,7 @@ static struct security_operations selinux_ops = {
 	.inode_getsecurity =            selinux_inode_getsecurity,
 	.inode_setsecurity =            selinux_inode_setsecurity,
 	.inode_listsecurity =           selinux_inode_listsecurity,
+	.inode_get_secid =		selinux_inode_get_secid,
 
 	.file_permission =		selinux_file_permission,
 	.file_alloc_security =		selinux_file_alloc_security,
author maintainer
#13 lore raw

PATCH 12/16 CacheFiles: Get the SID under which the CacheFiles module should operate [try #3]

In reply to David Howells

Get the SID under which the CacheFiles module should operate so that the SELinux security system can control the accesses it makes.

---

 include/linux/security.h |   20 ++++++++++++++++++++
 security/dummy.c         |    7 +++++++
 security/selinux/hooks.c |    7 +++++++
 3 files changed, 34 insertions(+), 0 deletions(-)
include/linux/security.h +20 -0
index a54958a..593a4d0 100644
@@ -1173,6 +1173,14 @@ struct request_sock;
  *      previously acting.
  *	@oldsecid points the location in which to return the displaced security ID.
  *
+ * @cachefiles_get_secid:
+ *	Determine the security ID for the CacheFiles module to use when
+ *	accessing the filesystem containing the cache.
+ *	@secid contains the security ID under which cachefiles daemon is
+ *      running.
+ *	@modsecid contains the pointer to where the security ID for the module
+ *	is to be stored.
+ *
  * This is the main security structure.
  */
 struct security_operations {
@@ -1361,6 +1369,7 @@ struct security_operations {
 	int (*set_fscreate_secid)(u32 secid, u32 *oldsecid);
 	int (*act_as_secid)(u32 secid, u32 *oldsecid);
 	int (*act_as_self)(u32 *oldsecid);
+	int (*cachefiles_get_secid)(u32 secid, u32 *modsecid);
 
 #ifdef CONFIG_SECURITY_NETWORK
 	int (*unix_stream_connect) (struct socket * sock,
@@ -2185,6 +2194,11 @@ static inline int security_act_as_self(u32 *oldsecid)
 	return security_ops->act_as_self(oldsecid);
 }
 
+static inline int security_cachefiles_get_secid(u32 secid, u32 *modsecid)
+{
+	return security_ops->cachefiles_get_secid(secid, modsecid);
+}
+
 /* prototypes */
 extern int security_init	(void);
 extern int register_security	(struct security_operations *ops);
@@ -2897,6 +2911,12 @@ static inline u32 security_act_as_self(u32 *oldsecid)
 	return 0;
 }
 
+static inline int security_cachefiles_get_secid(u32 secid, u32 *modsecid)
+{
+	*modsecid = 0;
+	return 0;
+}
+
 #endif	/* CONFIG_SECURITY */
 
 #ifdef CONFIG_SECURITY_NETWORK
security/dummy.c +7 -0
index 6be18fe..6e79dd4 100644
@@ -960,6 +960,12 @@ static int dummy_act_as_self(u32 *oldsecid)
 	return 0;
 }
 
+static int dummy_cachefiles_get_secid(u32 secid, u32 *modsecid)
+{
+	*modsecid = 0;
+	return 0;
+}
+
 #ifdef CONFIG_KEYS
 static inline int dummy_key_alloc(struct key *key, struct task_struct *ctx,
 				  unsigned long flags)
@@ -1119,6 +1125,7 @@ void security_fixup_ops (struct security_operations *ops)
  	set_to_dummy_if_null(ops, set_fscreate_secid);
  	set_to_dummy_if_null(ops, act_as_secid);
  	set_to_dummy_if_null(ops, act_as_self);
+ 	set_to_dummy_if_null(ops, cachefiles_get_secid);
 #ifdef CONFIG_SECURITY_NETWORK
 	set_to_dummy_if_null(ops, unix_stream_connect);
 	set_to_dummy_if_null(ops, unix_may_send);
security/selinux/hooks.c +7 -0
index 34646f8..54542b4 100644
@@ -4723,6 +4723,12 @@ static int selinux_act_as_self(u32 *oldsecid)
 	return 0;
 }
 
+static int selinux_cachefiles_get_secid(u32 secid, u32 *modsecid)
+{
+	return security_transition_sid(secid, SECINITSID_KERNEL,
+				       SECCLASS_PROCESS, modsecid);
+}
+
 #ifdef CONFIG_KEYS
 
 static int selinux_key_alloc(struct key *k, struct task_struct *tsk,
@@ -4910,6 +4916,7 @@ static struct security_operations selinux_ops = {
 	.set_fscreate_secid =		selinux_set_fscreate_secid,
 	.act_as_secid =			selinux_act_as_secid,
 	.act_as_self =			selinux_act_as_self,
+	.cachefiles_get_secid =		selinux_cachefiles_get_secid,
 
         .unix_stream_connect =		selinux_socket_unix_stream_connect,
 	.unix_may_send =		selinux_socket_unix_may_send,
author maintainer
#14 lore raw

PATCH 13/16 CacheFiles: A cache that backs onto a mounted filesystem [try #3]

In reply to David Howells

Add an FS-Cache cache-backend that permits a mounted filesystem to be used as a backing store for the cache.

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 source for the daemon can be downloaded from:

http://people.redhat.com/~dhowells/cachefs/cachefilesd.c

And an example configuration from:

http://people.redhat.com/~dhowells/cachefs/cachefilesd.conf

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 proc-file - "/proc/fs/cachefiles" - that is used for communication with the daemon. Only one thing may have this open at once, and whilst 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.

============
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.

=============
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>%

Configure the culling limits. Optional. See the section on culling The defaults are 7%, 5% and 1% respectively.

(*) 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).

==================
STARTING THE CACHE
==================

The cache is started by running the daemon. The daemon opens the cache proc file, 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.

===============
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 whilst 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
=============

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 available in the underlying filesystem. There are three "limits":

(*) brun

If the amount of available space in the cache rises above this limit, then culling is turned off.

(*) bcull

If the amount of available space in the cache falls below this limit, then culling is started.

(*) bstop

If the amount of available space in the cache falls below this limit, then no further allocation of disk space is permitted until culling has raised the amount above this limit again.

These must be configured thusly:

	0 <= bstop < bcull < brun < 100

Note that these are percentages of available space, 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.

===============
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).

This documentation is added by the patch to:

Documentation/filesystems/caching/cachefiles.txt

---

 Documentation/filesystems/caching/cachefiles.txt |  395 ++++++++++
 fs/Kconfig                                       |    1 
 fs/Makefile                                      |    1 
 fs/cachefiles/Kconfig                            |   33 +
 fs/cachefiles/Makefile                           |   18 
 fs/cachefiles/cf-bind.c                          |  288 +++++++
 fs/cachefiles/cf-daemon.c                        |  720 +++++++++++++++++++
 fs/cachefiles/cf-interface.c                     |  442 +++++++++++
 fs/cachefiles/cf-internal.h                      |  420 +++++++++++
 fs/cachefiles/cf-key.c                           |  159 ++++
 fs/cachefiles/cf-main.c                          |  109 +++
 fs/cachefiles/cf-namei.c                         |  743 +++++++++++++++++++
 fs/cachefiles/cf-proc.c                          |  166 ++++
 fs/cachefiles/cf-rdwr.c                          |  849 ++++++++++++++++++++++
 fs/cachefiles/cf-security.c                      |  114 +++
 fs/cachefiles/cf-xattr.c                         |  292 ++++++++
 16 files changed, 4750 insertions(+), 0 deletions(-)
Documentation/filesystems/caching/cachefiles.txt new file +395 -0
new file mode 100644
index 0000000..b502cff
@@ -0,0 +1,395 @@
+	       ===============================================
+	       CacheFiles: CACHE ON ALREADY MOUNTED FILESYSTEM
+	       ===============================================
+
+Contents:
+
+ (*) Overview.
+
+ (*) Requirements.
+
+ (*) Configuration.
+
+ (*) Starting the cache.
+
+ (*) Things to avoid.
+
+ (*) Cache culling.
+
+ (*) Cache structure.
+
+ (*) Security model and SELinux.
+
+========
+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 whilst 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.
+
+
+============
+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.
+
+
+=============
+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/modules/cachefiles/parameters/debug
+
+
+==================
+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.
+
+
+===============
+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 whilst 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
+=============
+
+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.
+
+
+===============
+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).
+
+
+==========================
+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:
+
+	http://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.
fs/Kconfig +1 -0
index 3e1c276..7feb4cb 100644
@@ -634,6 +634,7 @@ config GENERIC_ACL
 menu "Caches"
 
 source "fs/fscache/Kconfig"
+source "fs/cachefiles/Kconfig"
 
 endmenu
 
fs/Makefile +1 -0
index 4eecc9a..becdb4f 100644
@@ -116,6 +116,7 @@ obj-$(CONFIG_AFS_FS)		+= afs/
 obj-$(CONFIG_BEFS_FS)		+= befs/
 obj-$(CONFIG_HOSTFS)		+= hostfs/
 obj-$(CONFIG_HPPFS)		+= hppfs/
+obj-$(CONFIG_CACHEFILES)	+= cachefiles/
 obj-$(CONFIG_DEBUG_FS)		+= debugfs/
 obj-$(CONFIG_OCFS2_FS)		+= ocfs2/
 obj-$(CONFIG_GFS2_FS)           += gfs2/
fs/cachefiles/Kconfig new file +33 -0
new file mode 100644
index 0000000..ddbdd85
@@ -0,0 +1,33 @@
+
+config CACHEFILES
+	tristate "Filesystem caching on files"
+	depends on FSCACHE
+	help
+	  This permits use of a mounted filesystem as a cache for other
+	  filesystems - primarily networking filesystems - thus allowing fast
+	  local disk to enhance the speed of slower devices.
+
+	  See Documentation/filesystems/caching/cachefiles.txt for more
+	  information.
+
+config CACHEFILES_DEBUG
+	bool "Debug CacheFiles"
+	depends on CACHEFILES
+	help
+	  This permits debugging to be dynamically enabled in the filesystem
+	  caching on files module.  If this is set, the debugging output may be
+	  enabled by setting bits in /sys/modules/cachefiles/parameter/debug or
+	  by including a debugging specifier in /etc/cachefilesd.conf.
+
+config CACHEFILES_HISTOGRAM
+	bool "Gather latency information on CacheFiles"
+	depends on CACHEFILES && FSCACHE_PROC
+	help
+
+	  This option causes latency information to be gathered on CacheFiles
+	  operation and exported through file:
+
+		/proc/fs/fscache/cachefiles/histogram
+
+	  See Documentation/filesystems/caching/cachefiles.txt for more
+	  information.
fs/cachefiles/Makefile new file +18 -0
new file mode 100644
index 0000000..31186a4
@@ -0,0 +1,18 @@
+#
+# Makefile for caching in a mounted filesystem
+#
+
+cachefiles-y := \
+	cf-bind.o \
+	cf-daemon.o \
+	cf-interface.o \
+	cf-key.o \
+	cf-main.o \
+	cf-namei.o \
+	cf-rdwr.o \
+	cf-xattr.o
+
+cachefiles-$(CONFIG_SECURITY) += cf-security.o
+cachefiles-$(CONFIG_CACHEFILES_HISTOGRAM) += cf-proc.o
+
+obj-$(CONFIG_CACHEFILES) := cachefiles.o
fs/cachefiles/cf-bind.c new file +288 -0

288 lines not on this page · raw message

fs/cachefiles/cf-daemon.c new file +720 -0

720 lines not on this page · raw message

fs/cachefiles/cf-interface.c new file +442 -0

442 lines not on this page · raw message

fs/cachefiles/cf-internal.h new file +420 -0

420 lines not on this page · raw message

fs/cachefiles/cf-key.c new file +159 -0

159 lines not on this page · raw message

fs/cachefiles/cf-main.c new file +109 -0

109 lines not on this page · raw message

fs/cachefiles/cf-namei.c new file +743 -0

402 lines not on this page · raw message

fs/cachefiles/cf-proc.c new file +166 -0

166 lines not on this page · raw message

fs/cachefiles/cf-rdwr.c new file +849 -0

849 lines not on this page · raw message

fs/cachefiles/cf-security.c new file +114 -0

114 lines not on this page · raw message

fs/cachefiles/cf-xattr.c new file +292 -0

292 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Part of the diff is not shown here. View the raw message.

author maintainer
#15 lore raw

PATCH 14/16 NFS: Use local caching [try #3]

In reply to David Howells

The attached patch makes it possible for the NFS filesystem to make use of the network filesystem local caching service (FS-Cache).

To be able to use this, an updated mount program is required. This can be obtained from:

http://people.redhat.com/steved/fscache/util-linux/

To mount an NFS filesystem to use caching, add an "fsc" option to the mount:

mount warthog:/ /a -o fsc

---

 fs/nfs/Makefile           |    1 
 fs/nfs/client.c           |    5 +
 fs/nfs/file.c             |   51 ++++++
 fs/nfs/fscache-def.c      |  288 +++++++++++++++++++++++++++++++++++
 fs/nfs/fscache.c          |  374 +++++++++++++++++++++++++++++++++++++++++++++
 fs/nfs/fscache.h          |  144 +++++++++++++++++
 fs/nfs/inode.c            |   48 +++++-
 fs/nfs/read.c             |   28 +++
 fs/nfs/sysctl.c           |   44 +++++
 include/linux/nfs_fs.h    |    8 +
 include/linux/nfs_fs_sb.h |    7 +
 11 files changed, 988 insertions(+), 10 deletions(-)
fs/nfs/Makefile +1 -0
index b55cb23..07c9345 100644
@@ -16,4 +16,5 @@ nfs-$(CONFIG_NFS_V4)	+= nfs4proc.o nfs4xdr.o nfs4state.o nfs4renewd.o \
 			   nfs4namespace.o
 nfs-$(CONFIG_NFS_DIRECTIO) += direct.o
 nfs-$(CONFIG_SYSCTL) += sysctl.o
+nfs-$(CONFIG_NFS_FSCACHE) += fscache.o fscache-def.o
 nfs-objs		:= $(nfs-y)
fs/nfs/client.c +5 -0
index a49f9fe..f1783b2 100644
@@ -41,6 +41,7 @@
 #include "delegation.h"
 #include "iostat.h"
 #include "internal.h"
+#include "fscache.h"
 
 #define NFSDBG_FACILITY		NFSDBG_CLIENT
 
@@ -137,6 +138,8 @@ static struct nfs_client *nfs_alloc_client(const char *hostname,
 	clp->cl_state = 1 << NFS4CLNT_LEASE_EXPIRED;
 #endif
 
+	nfs_fscache_get_client_cookie(clp);
+
 	return clp;
 
 error_3:
@@ -168,6 +171,8 @@ static void nfs_free_client(struct nfs_client *clp)
 
 	nfs4_shutdown_client(clp);
 
+	nfs_fscache_release_client_cookie(clp);
+
 	/* -EIO all pending I/O */
 	if (!IS_ERR(clp->cl_rpcclient))
 		rpc_shutdown_client(clp->cl_rpcclient);
fs/nfs/file.c +50 -1

93 lines not on this page · raw message

fs/nfs/fscache-def.c new file +288 -0

288 lines not on this page · raw message

fs/nfs/fscache.c new file +374 -0

374 lines not on this page · raw message

fs/nfs/fscache.h new file +144 -0

144 lines not on this page · raw message

fs/nfs/inode.c +41 -7

136 lines not on this page · raw message

fs/nfs/read.c +26 -2
index 19e0563..4dfd6dc 100644
@@ -18,12 +18,14 @@
 #include <linux/sunrpc/clnt.h>
 #include <linux/nfs_fs.h>
 #include <linux/nfs_page.h>
+#include <linux/nfs_mount.h>
 #include <linux/smp_lock.h>
 
 #include <asm/system.h>
 
 #include "internal.h"
 #include "iostat.h"
+#include "fscache.h"
 
 #define NFSDBG_FACILITY		NFSDBG_PAGECACHE
 
@@ -114,8 +116,8 @@ static void nfs_readpage_truncate_uninitialised_page(struct nfs_read_data *data)
 	}
 }
 
-static int nfs_readpage_async(struct nfs_open_context *ctx, struct inode *inode,
-		struct page *page)
+int nfs_readpage_async(struct nfs_open_context *ctx, struct inode *inode,
+		       struct page *page)
 {
 	LIST_HEAD(one_request);
 	struct nfs_page	*new;
@@ -142,6 +144,11 @@ static int nfs_readpage_async(struct nfs_open_context *ctx, struct inode *inode,
 
 static void nfs_readpage_release(struct nfs_page *req)
 {
+	struct inode *d_inode = req->wb_context->path.dentry->d_inode;
+
+	if (PageUptodate(req->wb_page))
+		nfs_readpage_to_fscache(d_inode, req->wb_page, 0);
+
 	unlock_page(req->wb_page);
 
 	dprintk("NFS: read done (%s/%Ld %d@%Ld)\n",
@@ -500,8 +507,15 @@ int nfs_readpage(struct file *file, struct page *page)
 		ctx = get_nfs_open_context((struct nfs_open_context *)
 				file->private_data);
 
+	if (!IS_SYNC(inode)) {
+		error = nfs_readpage_from_fscache(ctx, inode, page);
+		if (error == 0)
+			goto out;
+	}
+
 	error = nfs_readpage_async(ctx, inode, page);
 
+out:
 	put_nfs_open_context(ctx);
 	return error;
 out_unlock:
@@ -578,6 +592,15 @@ int nfs_readpages(struct file *filp, struct address_space *mapping,
 	} else
 		desc.ctx = get_nfs_open_context((struct nfs_open_context *)
 				filp->private_data);
+
+	/* attempt to read as many of the pages as possible from the cache
+	 * - this returns -ENOBUFS immediately if the cookie is negative
+	 */
+	ret = nfs_readpages_from_fscache(desc.ctx, inode, mapping,
+					 pages, &nr_pages);
+	if (ret == 0)
+		goto read_complete; /* all pages were read */
+
 	if (rsize < PAGE_CACHE_SIZE)
 		nfs_pageio_init(&pgio, inode, nfs_pagein_multi, rsize, 0);
 	else
@@ -588,6 +611,7 @@ int nfs_readpages(struct file *filp, struct address_space *mapping,
 	nfs_pageio_complete(&pgio);
 	npages = (pgio.pg_bytes_written + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
 	nfs_add_stats(inode, NFSIOS_READPAGES, npages);
+read_complete:
 	put_nfs_open_context(desc.ctx);
 out:
 	return ret;
fs/nfs/sysctl.c +44 -0

56 lines not on this page · raw message

include/linux/nfs_fs.h +8 -0
index 157dcb0..e335076 100644
@@ -172,6 +172,9 @@ struct nfs_inode {
 	int			 delegation_state;
 	struct rw_semaphore	rwsem;
 #endif /* CONFIG_NFS_V4*/
+#ifdef CONFIG_NFS_FSCACHE
+	struct fscache_cookie	*fscache;
+#endif
 	struct inode		vfs_inode;
 };
 
@@ -185,6 +188,7 @@ struct nfs_inode {
 #define NFS_INO_INVALID_ACL	0x0010		/* cached acls are invalid */
 #define NFS_INO_REVAL_PAGECACHE	0x0020		/* must revalidate pagecache */
 #define NFS_INO_REVAL_FORCED	0x0040		/* force revalidation ignoring a delegation */
+#define NFS_INO_INVALID_FSCACHE_ATTR	0x0080	/* local cache attributes are invalid */
 
 /*
  * Bit offsets in flags field
@@ -193,6 +197,7 @@ struct nfs_inode {
 #define NFS_INO_ADVISE_RDPLUS	(1)		/* advise readdirplus */
 #define NFS_INO_STALE		(2)		/* possible stale inode */
 #define NFS_INO_ACL_LRU_SET	(3)		/* Inode is on the LRU list */
+#define NFS_INO_FSCACHE		(4)		/* inode can be cached by FS-Cache */
 
 static inline struct nfs_inode *NFS_I(struct inode *inode)
 {
@@ -218,6 +223,7 @@ static inline struct nfs_inode *NFS_I(struct inode *inode)
 
 #define NFS_FLAGS(inode)		(NFS_I(inode)->flags)
 #define NFS_STALE(inode)		(test_bit(NFS_INO_STALE, &NFS_FLAGS(inode)))
+#define NFS_FSCACHE(inode)		(test_bit(NFS_INO_FSCACHE, &NFS_FLAGS(inode)))
 
 #define NFS_FILEID(inode)		(NFS_I(inode)->fileid)
 
@@ -463,6 +469,7 @@ extern int  nfs_readpages(struct file *, struct address_space *,
 		struct list_head *, unsigned);
 extern int  nfs_readpage_result(struct rpc_task *, struct nfs_read_data *);
 extern void nfs_readdata_release(void *data);
+extern int  nfs_readpage_async(struct nfs_open_context *, struct inode *, struct page *);
 
 /*
  * Allocate nfs_read_data structures
@@ -553,6 +560,7 @@ extern void * nfs_root_data(void);
 #define NFSDBG_CALLBACK		0x0100
 #define NFSDBG_CLIENT		0x0200
 #define NFSDBG_MOUNT		0x0400
+#define NFSDBG_FSCACHE		0x0800
 #define NFSDBG_ALL		0xFFFF
 
 #ifdef __KERNEL__
include/linux/nfs_fs_sb.h +7 -0
index 0cac49b..95d0617 100644
@@ -3,6 +3,7 @@
 
 #include <linux/list.h>
 #include <linux/backing-dev.h>
+#include <linux/fscache.h>
 
 struct nfs_iostats;
 
@@ -65,6 +66,10 @@ struct nfs_client {
 	char			cl_ipaddr[16];
 	unsigned char		cl_id_uniquifier;
 #endif
+
+#ifdef CONFIG_NFS_FSCACHE
+	struct fscache_cookie	*fscache;	/* client index cache cookie */
+#endif
 };
 
 /*
@@ -95,6 +100,8 @@ struct nfs_server {
 	unsigned int		acdirmin;
 	unsigned int		acdirmax;
 	unsigned int		namelen;
+	unsigned int		options;	/* extra options enabled by mount */
+#define NFS_OPTION_FSCACHE	0x00000001	/* - local caching enabled */
 
 	struct nfs_fsid		fsid;
 	__u64			maxfilesize;	/* maximum file size */
author maintainer
#16 lore raw

PATCH 15/16 NFS: Configuration and mount option changes to enable local caching on NFS [try #3]

In reply to David Howells

Changes to the kernel configuration defintions and to the NFS mount options to allow the local caching support added by the previous patch to be enabled.

---

 fs/Kconfig        |    8 ++++++++
 fs/nfs/client.c   |   14 ++++++++++----
 fs/nfs/internal.h |    2 ++
 fs/nfs/super.c    |   40 ++++++++++++++++++++++++++++++++++------
 4 files changed, 54 insertions(+), 10 deletions(-)
fs/Kconfig +8 -0
index 7feb4cb..76d5d16 100644
@@ -1600,6 +1600,14 @@ config NFS_V4
 
 	  If unsure, say N.
 
+config NFS_FSCACHE
+	bool "Provide NFS client caching support (EXPERIMENTAL)"
+	depends on EXPERIMENTAL
+	depends on NFS_FS=m && FSCACHE || NFS_FS=y && FSCACHE=y
+	help
+	  Say Y here if you want NFS data to be cached locally on disc through
+	  the general filesystem cache manager
+
 config NFS_DIRECTIO
 	bool "Allow direct I/O on NFS files"
 	depends on NFS_FS
fs/nfs/client.c +10 -4
index f1783b2..0de4db4 100644
@@ -543,7 +543,8 @@ error:
 /*
  * Create a version 2 or 3 client
  */
-static int nfs_init_server(struct nfs_server *server, const struct nfs_mount_data *data)
+static int nfs_init_server(struct nfs_server *server, const struct nfs_mount_data *data,
+			   unsigned int extra_options)
 {
 	struct nfs_client *clp;
 	int error, nfsvers = 2;
@@ -580,6 +581,7 @@ static int nfs_init_server(struct nfs_server *server, const struct nfs_mount_dat
 	server->acregmax = data->acregmax * HZ;
 	server->acdirmin = data->acdirmin * HZ;
 	server->acdirmax = data->acdirmax * HZ;
+	server->options = extra_options;
 
 	/* Start lockd here, before we might error out */
 	error = nfs_start_lockd(server);
@@ -776,6 +778,7 @@ void nfs_free_server(struct nfs_server *server)
  * - keyed on server and FSID
  */
 struct nfs_server *nfs_create_server(const struct nfs_mount_data *data,
+				     unsigned extra_options,
 				     struct nfs_fh *mntfh)
 {
 	struct nfs_server *server;
@@ -787,7 +790,7 @@ struct nfs_server *nfs_create_server(const struct nfs_mount_data *data,
 		return ERR_PTR(-ENOMEM);
 
 	/* Get a client representation */
-	error = nfs_init_server(server, data);
+	error = nfs_init_server(server, data, extra_options);
 	if (error < 0)
 		goto error;
 
@@ -911,7 +914,8 @@ error:
  * Create a version 4 volume record
  */
 static int nfs4_init_server(struct nfs_server *server,
-		const struct nfs4_mount_data *data, rpc_authflavor_t authflavour)
+		const struct nfs4_mount_data *data, rpc_authflavor_t authflavour,
+		unsigned int extra_options)
 {
 	int error;
 
@@ -930,6 +934,7 @@ static int nfs4_init_server(struct nfs_server *server,
 	server->acregmax = data->acregmax * HZ;
 	server->acdirmin = data->acdirmin * HZ;
 	server->acdirmax = data->acdirmax * HZ;
+	server->options = extra_options;
 
 	error = nfs_init_server_rpcclient(server, authflavour);
 
@@ -948,6 +953,7 @@ struct nfs_server *nfs4_create_server(const struct nfs4_mount_data *data,
 				      const char *mntpath,
 				      const char *ip_addr,
 				      rpc_authflavor_t authflavour,
+				      unsigned int extra_options,
 				      struct nfs_fh *mntfh)
 {
 	struct nfs_fattr fattr;
@@ -967,7 +973,7 @@ struct nfs_server *nfs4_create_server(const struct nfs4_mount_data *data,
 		goto error;
 
 	/* set up the general RPC client */
-	error = nfs4_init_server(server, data, authflavour);
+	error = nfs4_init_server(server, data, authflavour, extra_options);
 	if (error < 0)
 		goto error;
 
fs/nfs/internal.h +2 -0
index 76cf55d..34ef000 100644
@@ -33,6 +33,7 @@ extern struct rpc_program nfs_program;
 extern void nfs_put_client(struct nfs_client *);
 extern struct nfs_client *nfs_find_client(const struct sockaddr_in *, int);
 extern struct nfs_server *nfs_create_server(const struct nfs_mount_data *,
+					    unsigned int,
 					    struct nfs_fh *);
 extern struct nfs_server *nfs4_create_server(const struct nfs4_mount_data *,
 					     const char *,
@@ -40,6 +41,7 @@ extern struct nfs_server *nfs4_create_server(const struct nfs4_mount_data *,
 					     const char *,
 					     const char *,
 					     rpc_authflavor_t,
+					     unsigned int,
 					     struct nfs_fh *);
 extern struct nfs_server *nfs4_create_referral_server(struct nfs_clone_mount *,
 						      struct nfs_fh *);
fs/nfs/super.c +34 -6
index b2a851c..17473f6 100644
@@ -67,6 +67,7 @@ struct nfs_parsed_mount_data {
 				acdirmin, acdirmax;
 	int			namlen;
 	unsigned int		bsize;
+	unsigned int		options;
 	unsigned int		auth_flavor_len;
 	rpc_authflavor_t	auth_flavors[1];
 	char			*client_address;
@@ -101,6 +102,7 @@ enum {
 	Opt_acl, Opt_noacl,
 	Opt_rdirplus, Opt_nordirplus,
 	Opt_sharecache, Opt_nosharecache,
+	Opt_fscache, Opt_nofscache,
 
 	/* Mount options that take integer arguments */
 	Opt_port,
@@ -149,6 +151,8 @@ static match_table_t nfs_mount_option_tokens = {
 	{ Opt_nordirplus, "nordirplus" },
 	{ Opt_sharecache, "sharecache" },
 	{ Opt_nosharecache, "nosharecache" },
+	{ Opt_fscache, "fsc" },
+	{ Opt_nofscache, "nofsc" },
 
 	{ Opt_port, "port=%u" },
 	{ Opt_rsize, "rsize=%u" },
@@ -495,6 +499,8 @@ static void nfs_show_mount_options(struct seq_file *m, struct nfs_server *nfss,
 	seq_printf(m, ",timeo=%lu", 10U * clp->retrans_timeo / HZ);
 	seq_printf(m, ",retrans=%u", clp->retrans_count);
 	seq_printf(m, ",sec=%s", nfs_pseudoflavour_to_name(nfss->client->cl_auth->au_flavor));
+	if (nfss->options & NFS_OPTION_FSCACHE)
+		seq_printf(m, ",fsc");
 }
 
 /*
@@ -725,6 +731,15 @@ static int nfs_parse_mount_options(char *raw,
 			break;
 		case Opt_nosharecache:
 			mnt->flags |= NFS_MOUNT_UNSHARED;
+			mnt->options &= ~NFS_OPTION_FSCACHE;
+			break;
+		case Opt_fscache:
+			/* sharing is mandatory with fscache */
+			mnt->options |= NFS_OPTION_FSCACHE;
+			mnt->flags &= ~NFS_MOUNT_UNSHARED;
+			break;
+		case Opt_nofscache:
+			mnt->options &= ~NFS_OPTION_FSCACHE;
 			break;
 
 		case Opt_port:
@@ -1081,10 +1096,13 @@ out_err:
  */
 static int nfs_validate_mount_data(struct nfs_mount_data **options,
 				   struct nfs_fh *mntfh,
-				   const char *dev_name)
+				   const char *dev_name,
+				   unsigned int *_extra_options)
 {
 	struct nfs_mount_data *data = *options;
 
+	*_extra_options = 0;
+
 	if (data == NULL)
 		goto out_no_data;
 
@@ -1131,6 +1149,7 @@ static int nfs_validate_mount_data(struct nfs_mount_data **options,
 			.acregmax	= 60,
 			.acdirmin	= 30,
 			.acdirmax	= 60,
+			.options	= 0,
 			.mount_server.protocol = IPPROTO_UDP,
 			.mount_server.program = NFS_MNT_PROGRAM,
 			.nfs_server.protocol = IPPROTO_TCP,
@@ -1139,6 +1158,7 @@ static int nfs_validate_mount_data(struct nfs_mount_data **options,
 
 		if (nfs_parse_mount_options((char *) *options, &args) == 0)
 			return -EINVAL;
+		*_extra_options = args.options;
 
 		data = kzalloc(sizeof(*data), GFP_KERNEL);
 		if (data == NULL)
@@ -1372,16 +1392,17 @@ static int nfs_get_sb(struct file_system_type *fs_type,
 	struct nfs_fh mntfh;
 	struct nfs_mount_data *data = raw_data;
 	struct dentry *mntroot;
+	unsigned int extra_options;
 	int (*compare_super)(struct super_block *, void *) = nfs_compare_super;
 	int error;
 
 	/* Validate the mount data */
-	error = nfs_validate_mount_data(&data, &mntfh, dev_name);
+	error = nfs_validate_mount_data(&data, &mntfh, dev_name, &extra_options);
 	if (error < 0)
 		goto out;
 
 	/* Get a volume representation */
-	server = nfs_create_server(data, &mntfh);
+	server = nfs_create_server(data, extra_options, &mntfh);
 	if (IS_ERR(server)) {
 		error = PTR_ERR(server);
 		goto out;
@@ -1556,11 +1577,14 @@ static int nfs4_validate_mount_data(struct nfs4_mount_data **options,
 				    rpc_authflavor_t *authflavour,
 				    char **hostname,
 				    char **mntpath,
-				    char **ip_addr)
+				    char **ip_addr,
+				    unsigned int *_extra_options)
 {
 	struct nfs4_mount_data *data = *options;
 	char *c;
 
+	*_extra_options = 0;
+
 	if (data == NULL)
 		goto out_no_data;
 
@@ -1616,11 +1640,13 @@ static int nfs4_validate_mount_data(struct nfs4_mount_data **options,
 			.acregmax	= 60,
 			.acdirmin	= 30,
 			.acdirmax	= 60,
+			.options	= 0,
 			.nfs_server.protocol = IPPROTO_TCP,
 		};
 
 		if (nfs_parse_mount_options((char *) *options, &args) == 0)
 			return -EINVAL;
+		*_extra_options = args.options;
 
 		if (!nfs_verify_server_address((struct sockaddr *)
 						&args.nfs_server.address))
@@ -1727,19 +1753,21 @@ static int nfs4_get_sb(struct file_system_type *fs_type,
 	rpc_authflavor_t authflavour;
 	struct nfs_fh mntfh;
 	struct dentry *mntroot;
+	unsigned extra_options;
 	char *mntpath = NULL, *hostname = NULL, *ip_addr = NULL;
 	int (*compare_super)(struct super_block *, void *) = nfs_compare_super;
 	int error;
 
 	/* Validate the mount data */
 	error = nfs4_validate_mount_data(&data, dev_name, &addr, &authflavour,
-					 &hostname, &mntpath, &ip_addr);
+					 &hostname, &mntpath, &ip_addr,
+					 &extra_options);
 	if (error < 0)
 		goto out;
 
 	/* Get a volume representation */
 	server = nfs4_create_server(data, hostname, &addr, mntpath, ip_addr,
-				    authflavour, &mntfh);
+				    authflavour, extra_options, &mntfh);
 	if (IS_ERR(server)) {
 		error = PTR_ERR(server);
 		goto out;
author maintainer
#17 lore raw

PATCH 16/16 NFS: Display local caching state [try #3]

In reply to David Howells

Display the local caching state in /proc/fs/nfsfs/volumes.

---

 fs/nfs/client.c  |    7 ++++---
 fs/nfs/fscache.h |   12 ++++++++++++
 2 files changed, 16 insertions(+), 3 deletions(-)
fs/nfs/client.c +4 -3
index 0de4db4..d350668 100644
@@ -1319,7 +1319,7 @@ static int nfs_volume_list_show(struct seq_file *m, void *v)
 
 	/* display header on line 1 */
 	if (v == &nfs_volume_list) {
-		seq_puts(m, "NV SERVER   PORT DEV     FSID\n");
+		seq_puts(m, "NV SERVER   PORT DEV     FSID              FSC\n");
 		return 0;
 	}
 	/* display one transport per line on subsequent lines */
@@ -1333,12 +1333,13 @@ static int nfs_volume_list_show(struct seq_file *m, void *v)
 		 (unsigned long long) server->fsid.major,
 		 (unsigned long long) server->fsid.minor);
 
-	seq_printf(m, "v%d %02x%02x%02x%02x %4hx %-7s %-17s\n",
+	seq_printf(m, "v%d %02x%02x%02x%02x %4hx %-7s %-17s %s\n",
 		   clp->cl_nfsversion,
 		   NIPQUAD(clp->cl_addr.sin_addr),
 		   ntohs(clp->cl_addr.sin_port),
 		   dev,
-		   fsid);
+		   fsid,
+		   nfs_server_fscache_state(server));
 
 	return 0;
 }
fs/nfs/fscache.h +12 -0
index 44bb0d1..77f3450 100644
@@ -56,6 +56,17 @@ extern void __nfs_fscache_invalidate_page(struct page *, struct inode *);
 extern int nfs_fscache_release_page(struct page *, gfp_t);
 
 /*
+ * indicate the client caching state as readable text
+ */
+static inline const char *nfs_server_fscache_state(struct nfs_server *server)
+{
+	if (server->nfs_client->fscache &&
+	    (server->options & NFS_OPTION_FSCACHE))
+		return "yes";
+	return "no ";
+}
+
+/*
  * release the caching state associated with a page if undergoing complete page
  * invalidation
  */
@@ -110,6 +121,7 @@ static inline void nfs_fscache_unregister(void) {}
 static inline void nfs_fscache_get_client_cookie(struct nfs_client *clp) {}
 static inline void nfs4_fscache_get_client_cookie(struct nfs_client *clp) {}
 static inline void nfs_fscache_release_client_cookie(struct nfs_client *clp) {}
+static inline const char *nfs_server_fscache_state(struct nfs_server *server) { return "no "; }
 
 static inline void nfs_fscache_init_fh_cookie(struct inode *inode) {}
 static inline void nfs_fscache_enable_fh_cookie(struct inode *inode) {}
#10 lore raw

Re: [PATCH 09/16] CacheFiles: Permit a process's create SID to be overridden [try #3]

In reply to David Howells
Quoted 4 lines · --- David Howells

Make it possible for a process's file creation SID to be temporarily overridden
by CacheFiles so that files created in the cache have the right label attached.

I still object to the use of sids in LSM interfaces. I still owe you a viable alternative.

Casey Schaufler
[email protected]

#18 lore raw
In reply to David Howells
Quoted 19 lines · --- David Howells

These patches add local caching for network filesystems such as NFS and AFS.

FS-Cache now runs fully asynchronously as required by Trond Myklebust for NFS.

--
Changes:
[try #3]:

(*) Added missing file to CacheFiles patch.

(*) Made new security functions return errors and pass actual return data
via
argument pointer.

(*) Cleaned up NFS patch.

(*) The 'fsc' flag must now be passed to NFS mount by the string options.

Quoted 9 lines

(*) Split the NFS patch into three as requested by Trond.

[try #2]:

(*) The CacheFiles module no longer accepts directory fds in its cull and
inuse commands from cachefilesd. Instead it uses the current working directory of the calling process as the basis for looking up the object. Corollary to this, fget_light() no longer needs to be exported.

How would you expect an LSM that is not SELinux to interface with CacheFiles? You have gone to a great deal of effort to support the requirements of an SELinux system, and that's good, but you have extended the LSM interface to expose SELinux data structures (secids) and require them for the operation of CacheFiles, and that's bad. The data used within an LSM is private to the LSM, and this applies to SELinux as well as to any other LSM that may come along, such as the Smack LSM I'm working on. This applies to task data as well as file data. Further, the behavior of the system in the presence of an LSM should be controlled by the LSM, it is more than a little scary that CacheFiles is enforcing SELinux policy based on secids that may be coming from a different LSM.

I applaud the integration of CacheFiles with SELinux. Unfortunately, you've done so using the LSM interface in such a way that an LSM other than SELinux is likely to demonstrate inappropriate behaviors in the presence of CacheFiles because you have so carefully integrated the SELinux requirements.

If the integration with SELinux is important to you, and I would expect that it is given the work you've put into it, I suggest that the SELinux specific behaviors be identified so that another LSM can provide the behavior appropriate to the policy it chooses to enforce and put that into SELinux with an LSM interface. I know that you're looking at a significant effort to do that, but I wouldn't think that you'd want CacheFiles to behave badly in the presence of an LSM that doesn't happen to be SELinux.

I also know it's tempting to point out the SELinux is the only upstream LSM. I hope to change that before too long, and I know there are others with ambitions as well. I would not like to see CacheFiles have to get excluded in the presence of other LSMs and I doubt you would either.

Casey Schaufler
[email protected]

author maintainer
#19 lore raw
Quoted 2 lines · Casey Schaufler

How would you expect an LSM that is not SELinux to interface with CacheFiles?

You have to understand that I didn't know that much about the LSM interface, so I asked advice of the Red Hat security people, who, naturally, pointed me at the SELinux mailing list. I knew my stuff would have to work with SELinux to be used with RH stuff.

Furthermore, as you pointed out, there aren't any other LSM modules upstream yet for me to work against. I would like CacheFiles to work with all LSM modules in general, but I don't know how to do that yet.

I'm open to suggestion as to how to modify things to support any LSM.

Btw, do you understand the problems that CacheFiles has to deal with? If I set this down clearly, this may help you or someone else suggest a better way to do things.

(1) Some random process tries to access a file on a network filesystem (NFS example).

(2) NFS goes to the cache to attempt to read the data from there prior to going to the network.

(3) The cache driver wants to access the files in the cache, but it's running in the security context of either the aforementioned random process, or one of FS-Cache's thread pool.

This security context, however, doesn't necessarily give it the rights to access what's in the cache, so the driver has to be permitted to act as a context appropriate to accessing the cache, without changing the overall security context of the random process (which would impact things trying to act on that process - kill() for example).

(4) Assuming the data is found in the cache, all well and good, but if it isn't, the cache driver will have to create some files in the cache.

Now, if the cache driver just went ahead and created the files, they could end up with their own security contexts being derived from the random process's security context, thus potentially making it impossible for other processes to access the cache.

So the file-creation part of the security context must also be overridden temporarily, assuming that whatever LSM is in force has such a concept.

Part of the problem is that the VFS does not pass around the security context as which the VFS routines act, but rather gets them from the task_struct. For the most part, this is entirely sufficient, but in the cache driver case, it's a problem.

David

#20 lore raw
Quoted 9 lines · --- David Howells
Quoted 2 lines · Casey Schaufler

How would you expect an LSM that is not SELinux to interface with CacheFiles?

You have to understand that I didn't know that much about the LSM interface, so I asked advice of the Red Hat security people, who, naturally, pointed me at the SELinux mailing list. I knew my stuff would have to work with SELinux to be used with RH stuff.

Sigh. So it's not only SELinux specific, but RedHat specific as well.

Quoted 3 lines

Furthermore, as you pointed out, there aren't any other LSM modules upstream yet for me to work against. I would like CacheFiles to work with all LSM modules in general, but I don't know how to do that yet.

While neither is upstream you can certainly look at AppArmor and Smack, both of which have nefarious plans for getting upstream.

Quoted 1 line

I'm open to suggestion as to how to modify things to support any LSM.

It's been a long time since I dealt with file system cacheing, and that was under Unix, and I don't claim to have a working understanding of the internals of CacheFiles, but ...

Quoted 7 lines

Btw, do you understand the problems that CacheFiles has to deal with? If I set this down clearly, this may help you or someone else suggest a better way to do things.

(1) Some random process tries to access a file on a network filesystem (NFS example).

Quoted 6 lines

(2) NFS goes to the cache to attempt to read the data from there prior to going to the network.

(3) The cache driver wants to access the files in the cache, but it's running in the security context of either the aforementioned random process, or one of FS-Cache's thread pool.

I think that this is the point you should attack. Control the security characteristics of the cache driver properly and you shouldn't need the complexity that you're asking to introduce.

Quoted 5 lines

This security context, however, doesn't necessarily give it the rights to access what's in the cache, so the driver has to be permitted to act as a context appropriate to accessing the cache, without changing the overall security context of the random process (which would impact things trying to act on that process - kill() for example).

Can you run the cache as an independent thread and send it messages rather than trying to do things in the context of the calling process? I know that that involves extra bookkeeppingg, but it's lots safer.

Quoted 8 lines

(4) Assuming the data is found in the cache, all well and good, but if it isn't, the cache driver will have to create some files in the cache.

Now, if the cache driver just went ahead and created the files, they could end up with their own security contexts being derived from the random process's security context, thus potentially making it
impossible
for other processes to access the cache.

Yes, and the SELinux semantics for what label to give a file don't help much, either. The problem with the "act_as" interfaces is that I wouldn't expect them to be any more reliable than the old access() system call, which never really gave you a helpful answer.

Quoted 3 lines

So the file-creation part of the security context must also be overridden temporarily, assuming that whatever LSM is in force has such a concept.

Ideally you want to be running in the right context to create the new file so that no one can use it and then label it "correctly" and make it available.

Quoted 2 lines

Part of the problem is that the VFS does not pass around the security context as which the VFS routines act, but rather gets them from the task_struct.

That's by design.

Quoted 4 lines

For
the most part, this is entirely sufficient, but in the cache driver case, it's
a problem.

The cache driver is a unique case with an unusual function. It's pretty obvious that the kernel architecture, the VFS architecture, LSM, SELinux, NFS and pretty much everyone else has given no thought whatever to the implications of their designs on file system cacheing. For all concerned, I'll say "sorry 'bout that".

Casey Schaufler
[email protected]

author maintainer
#21 lore raw
Quoted 1 line · Casey Schaufler

Sigh. So it's not only SELinux specific, but RedHat specific as well.

*Blink*. How did you come to that conclusion?

Quoted 7 lines
Quoted 3 lines

(3) The cache driver wants to access the files in the cache, but it's running in the security context of either the aforementioned random process, or one of FS-Cache's thread pool.

I think that this is the point you should attack. Control the security characteristics of the cache driver properly and you shouldn't need the complexity that you're asking to introduce.

How? The cache driver acts on behalf of someone else. That someone else has one security context, but the cache itself has to have a different context so that the cache can be shared.

Furthermore, the cache driver doesn't have a security context per se.

Quoted 10 lines
Quoted 6 lines

This security context, however, doesn't necessarily give it the rights to access what's in the cache, so the driver has to be permitted to act as a context appropriate to accessing the cache, without changing the overall security context of the random process (which would impact things trying to act on that process - kill() for example).

Can you run the cache as an independent thread and send it messages rather than trying to do things in the context of the calling process? I know that that involves extra bookkeeppingg, but it's lots safer.

It introduces more complexity, which I believe you were just arguing against above... It also incurs more kernel threads - which I really really want to avoid.

I would rank the complexity and resource overhead of the act-as stuff in LSM (or at least in SELinux) as much less than what you're suggesting.

As it stands, the FS-Cache layer has a pool of threads that CacheFiles makes use of, but this can't be bound to the security of a specific cache because there may be more than one cache of more than one cache driver type.

Quoted 4 lines

Yes, and the SELinux semantics for what label to give a file don't help much, either. The problem with the "act_as" interfaces is that I wouldn't expect them to be any more reliable than the old access() system call, which never really gave you a helpful answer.

I don't see how act_as compares to access().

Quoted 3 lines

Ideally you want to be running in the right context to create the new file so that no one can use it and then label it "correctly" and make it available.

That sounds like it'd be the complexity thing again...

Quoted 5 lines
Quoted 3 lines

Part of the problem is that the VFS does not pass around the security context as which the VFS routines act, but rather gets them from the task_struct.

That's by design.

I suspect that's more by the fact that security wasn't particularly thought about when these interfaces were first written. As with everything in the kernel, it might be negotiable.

Quoted 5 lines

The cache driver is a unique case with an unusual function. It's pretty obvious that the kernel architecture, the VFS architecture, LSM, SELinux, NFS and pretty much everyone else has given no thought whatever to the implications of their designs on file system cacheing. For all concerned, I'll say "sorry 'bout that".

Meaning you think I should just give up on this?

How about I reduce the interface I'm proposing to two functions:

(1) int security_act_as(struct task_struct *context)

Temporarily make the current process act as the given task, including, for example, for SELinux, the security ID with which this task acts on things, and the security ID with which this task creates files.

  (2) int security_act_as_self(void);

Restore the context as which we're asking.

This would mean that the task's security context would have to be able to store acting security IDs for everything, but I don't think that's too much of a stretch resourcewise.

David

#40 lore raw
In reply to Casey Schaufler
Quoted 87 lines · Casey Schaufler
Quoted 9 lines · --- David Howells
Quoted 2 lines · Casey Schaufler

How would you expect an LSM that is not SELinux to interface with CacheFiles?

You have to understand that I didn't know that much about the LSM interface, so I asked advice of the Red Hat security people, who, naturally, pointed me at the SELinux mailing list. I knew my stuff would have to work with SELinux to be used with RH stuff.

Sigh. So it's not only SELinux specific, but RedHat specific as well.

Quoted 3 lines

Furthermore, as you pointed out, there aren't any other LSM modules upstream yet for me to work against. I would like CacheFiles to work with all LSM modules in general, but I don't know how to do that yet.

While neither is upstream you can certainly look at AppArmor and Smack, both of which have nefarious plans for getting upstream.

Quoted 1 line

I'm open to suggestion as to how to modify things to support any LSM.

It's been a long time since I dealt with file system cacheing, and that was under Unix, and I don't claim to have a working understanding of the internals of CacheFiles, but ...

Quoted 7 lines

Btw, do you understand the problems that CacheFiles has to deal with? If I set this down clearly, this may help you or someone else suggest a better way to do things.

(1) Some random process tries to access a file on a network filesystem (NFS example).

Quoted 6 lines

(2) NFS goes to the cache to attempt to read the data from there prior to going to the network.

(3) The cache driver wants to access the files in the cache, but it's running in the security context of either the aforementioned random process, or one of FS-Cache's thread pool.

I think that this is the point you should attack. Control the security characteristics of the cache driver properly and you shouldn't need the complexity that you're asking to introduce.

Quoted 5 lines

This security context, however, doesn't necessarily give it the rights to access what's in the cache, so the driver has to be permitted to act as a context appropriate to accessing the cache, without changing the overall security context of the random process (which would impact things trying to act on that process - kill() for example).

Can you run the cache as an independent thread and send it messages rather than trying to do things in the context of the calling process? I know that that involves extra bookkeeppingg, but it's lots safer.

Quoted 8 lines

(4) Assuming the data is found in the cache, all well and good, but if it isn't, the cache driver will have to create some files in the cache.

Now, if the cache driver just went ahead and created the files, they could end up with their own security contexts being derived from the random process's security context, thus potentially making it
impossible
for other processes to access the cache.

Yes, and the SELinux semantics for what label to give a file don't help much, either. The problem with the "act_as" interfaces is that I wouldn't expect them to be any more reliable than the old access() system call, which never really gave you a helpful answer.

Quoted 3 lines

So the file-creation part of the security context must also be overridden temporarily, assuming that whatever LSM is in force has such a concept.

Ideally you want to be running in the right context to create the new file so that no one can use it and then label it "correctly" and make it available.

Quoted 2 lines

Part of the problem is that the VFS does not pass around the security context as which the VFS routines act, but rather gets them from the task_struct.

That's by design.

Quoted 4 lines

For
the most part, this is entirely sufficient, but in the cache driver case, it's
a problem.

Quoted 5 lines

The cache driver is a unique case with an unusual function. It's pretty obvious that the kernel architecture, the VFS architecture, LSM, SELinux, NFS and pretty much everyone else has given no thought whatever to the implications of their designs on file system cacheing. For all concerned, I'll say "sorry 'bout that".

Parts of it are unique, but some of the same issues crop up in nfs - we will need a way there as well for nfsd to assume the client process' label for permission checking and new file labeling purposes, and the act_as hook is not fundamentally different than what nfsd does today with the fsuid/fsguid, just applied to the security label.

Signature · 2 lines
Stephen Smalley
National Security Agency
#22 lore raw
In reply to David Howells
Quoted 65 lines · --- David Howells
Quoted 1 line · Casey Schaufler

Sigh. So it's not only SELinux specific, but RedHat specific as well.

*Blink*. How did you come to that conclusion?

Quoted 7 lines
Quoted 3 lines

(3) The cache driver wants to access the files in the cache, but it's running in the security context of either the aforementioned random process, or one of FS-Cache's thread pool.

I think that this is the point you should attack. Control the security characteristics of the cache driver properly and you shouldn't need the complexity that you're asking to introduce.

How? The cache driver acts on behalf of someone else. That someone else has one security context, but the cache itself has to have a different context so that the cache can be shared.

Furthermore, the cache driver doesn't have a security context per se.

Quoted 10 lines
Quoted 6 lines

This security context, however, doesn't necessarily give it the rights to access what's in the cache, so the driver has to be permitted to act as a context appropriate to accessing the cache, without changing the overall security context of the random process (which would impact things trying to act on that process - kill() for example).

Can you run the cache as an independent thread and send it messages rather than trying to do things in the context of the calling process? I know that that involves extra bookkeeppingg, but it's lots safer.

It introduces more complexity, which I believe you were just arguing against above... It also incurs more kernel threads - which I really really want to avoid.

I would rank the complexity and resource overhead of the act-as stuff in LSM (or at least in SELinux) as much less than what you're suggesting.

As it stands, the FS-Cache layer has a pool of threads that CacheFiles makes use of, but this can't be bound to the security of a specific cache because there may be more than one cache of more than one cache driver type.

Quoted 4 lines

Yes, and the SELinux semantics for what label to give a file don't help much, either. The problem with the "act_as" interfaces is that I wouldn't expect them to be any more reliable than the old access() system call, which never really gave you a helpful answer.

I don't see how act_as compares to access().

Quoted 3 lines

Ideally you want to be running in the right context to create the new file so that no one can use it and then label it "correctly" and make it available.

That sounds like it'd be the complexity thing again...

Quoted 5 lines
Quoted 3 lines

Part of the problem is that the VFS does not pass around the security context as which the VFS routines act, but rather gets them from the task_struct.

That's by design.

I suspect that's more by the fact that security wasn't particularly thought about when these interfaces were first written. As with everything in the kernel, it might be negotiable.

Quoted 7 lines
Quoted 5 lines

The cache driver is a unique case with an unusual function. It's pretty obvious that the kernel architecture, the VFS architecture, LSM, SELinux, NFS and pretty much everyone else has given no thought whatever to the implications of their designs on file system cacheing. For all concerned, I'll say "sorry 'bout that".

Meaning you think I should just give up on this?

No, sorry, sometimes I sound meaner than I really am. I meant that sympathetically, honest. I don't think you should give up.

Quoted 8 lines

How about I reduce the interface I'm proposing to two functions:

(1) int security_act_as(struct task_struct *context)

Temporarily make the current process act as the given task, including, for example, for SELinux, the security ID with which this task acts on things, and the security ID with which this task creates files.

Quoted 8 lines
  (2) int security_act_as_self(void);

Restore the context as which we're asking.

This would mean that the task's security context would have to be able to store
acting security IDs for everything, but I don't think that's too much of a stretch resourcewise.

I haven't looked into the issues at all and I bet there are plenty, maybe in audit and places outside of the security realm, but this looks like a clean approach from the LSM interface standpoint. Do you want the entire task or just task->security? I could see it either way, but I suspect the task is your best bet. If you call security_act_as() twice, then security_act_as_self() do you pop a stack, or return to the initial state? How about security_act_as(NULL) returning you to the initial state, and dropping security_act_as_self()?

Thank you for taking the effort to address the issues I raised. I appreciate your willingness to accommodate my concerns even after I'd flamed you.

Casey Schaufler
[email protected]

#38 lore raw
In reply to David Howells
Quoted 73 lines · David Howells
Quoted 1 line · Casey Schaufler

Sigh. So it's not only SELinux specific, but RedHat specific as well.

*Blink*. How did you come to that conclusion?

Quoted 7 lines
Quoted 3 lines

(3) The cache driver wants to access the files in the cache, but it's running in the security context of either the aforementioned random process, or one of FS-Cache's thread pool.

I think that this is the point you should attack. Control the security characteristics of the cache driver properly and you shouldn't need the complexity that you're asking to introduce.

How? The cache driver acts on behalf of someone else. That someone else has one security context, but the cache itself has to have a different context so that the cache can be shared.

Furthermore, the cache driver doesn't have a security context per se.

Quoted 10 lines
Quoted 6 lines

This security context, however, doesn't necessarily give it the rights to access what's in the cache, so the driver has to be permitted to act as a context appropriate to accessing the cache, without changing the overall security context of the random process (which would impact things trying to act on that process - kill() for example).

Can you run the cache as an independent thread and send it messages rather than trying to do things in the context of the calling process? I know that that involves extra bookkeeppingg, but it's lots safer.

It introduces more complexity, which I believe you were just arguing against above... It also incurs more kernel threads - which I really really want to avoid.

I would rank the complexity and resource overhead of the act-as stuff in LSM (or at least in SELinux) as much less than what you're suggesting.

As it stands, the FS-Cache layer has a pool of threads that CacheFiles makes use of, but this can't be bound to the security of a specific cache because there may be more than one cache of more than one cache driver type.

Quoted 4 lines

Yes, and the SELinux semantics for what label to give a file don't help much, either. The problem with the "act_as" interfaces is that I wouldn't expect them to be any more reliable than the old access() system call, which never really gave you a helpful answer.

I don't see how act_as compares to access().

Quoted 3 lines

Ideally you want to be running in the right context to create the new file so that no one can use it and then label it "correctly" and make it available.

That sounds like it'd be the complexity thing again...

Quoted 5 lines
Quoted 3 lines

Part of the problem is that the VFS does not pass around the security context as which the VFS routines act, but rather gets them from the task_struct.

That's by design.

I suspect that's more by the fact that security wasn't particularly thought about when these interfaces were first written. As with everything in the kernel, it might be negotiable.

Quoted 5 lines

The cache driver is a unique case with an unusual function. It's pretty obvious that the kernel architecture, the VFS architecture, LSM, SELinux, NFS and pretty much everyone else has given no thought whatever to the implications of their designs on file system cacheing. For all concerned, I'll say "sorry 'bout that".

Meaning you think I should just give up on this?

Quoted 7 lines

How about I reduce the interface I'm proposing to two functions:

(1) int security_act_as(struct task_struct *context)

Temporarily make the current process act as the given task, including, for example, for SELinux, the security ID with which this task acts on things, and the security ID with which this task creates files.

I don't see how that helps with nfsd assuming the label of a remote client process.

Quoted 8 lines
  (2) int security_act_as_self(void);

Restore the context as which we're asking.

This would mean that the task's security context would have to be able to store acting security IDs for everything, but I don't think that's too much of a stretch resourcewise.

Signature · 2 lines
Stephen Smalley
National Security Agency
author maintainer
#23 lore raw
In reply to Casey Schaufler
Quoted 4 lines · Casey Schaufler

I haven't looked into the issues at all and I bet there are plenty, maybe in audit and places outside of the security realm, but this looks like a clean approach from the LSM interface standpoint. Do you want the entire task or just task->security?

It would probably have to be the task struct, lest the security information (for which I've no refcount held) went away whilst I was trying to access it.

Quoted 3 lines

I could see it either way, but I suspect the task is your best bet. If you call security_act_as() twice, then security_act_as_self() do you pop a stack, or return to the initial state?

Good point. I've pondered that. What I have at the moment partly acts like a stack in that I store some of the shifted-out context on the machine stack (in struct cachefiles_secctx). The act-as context should probably be shifted too, in addition to the old file-creation SID and the fsuid/fsgid.

Quoted 2 lines

How about security_act_as(NULL) returning you to the initial state, and dropping security_act_as_self()?

That would be fine.

Actually, to address Stephen Smalley's requirements also, how about making things a bit more complex. Have the following suite of functions:

(1) int security_get_context(struct sec **_context);

This allocates and gives the caller a blob that describes the current context of all the LSM module states attached to the current task and stores a pointer to it in *_context.

(2) int security_push(struct sec *context, struct sec **_old_context)

This causes all the LSM modules on the current task to switch to a new acting state, passing back the old state. It does not change how other tasks do things to this one.

(3) int security_pop(struct sec *context)

This causes all the LSM modules on the current task to switch to a new acting state, deleting the old state. It does not change how other tasks do things to this one.

(4) int security_delete_context(struct sec *context)

This deletes a context blob.

The context blob could then be structured very simply. Give each loaded LSM module an integer index as it is registered. Having a limit to the number of LSM modules would make things simpler. The blob would then be an array of void pointers, one per LSM module, indexed by the integer index for each one. It you don't have a limit on the number of LSM modules, you'd also need a count of slots in the blob.

Any LSM module that wanted to implement the above three functions would fill in or otherwise use the slot that belongs to it. Otherwise the slot would just be left NULL.

For example:

	context --->+--------+                                    +---------+
	            | SLOT 0 |----------------------------------->| SELINUX |
	            +--------+                      +--------+    +---------+
	            | SLOT 1 |--------------------->| THINGY |
	            +--------+                      +--------+
	            | ...    |
	            +--------+         +-------+
	            | SLOT N |-------->| AUDIT |
	            +--------+         +-------+

For Stephen and NFS, he could then generate a context from NFS which nfsd could then put in place. Perhaps any unfilled slot would be ignored by the LSM module to which it belonged.

David

#24 lore raw
Quoted 72 lines · David Howells
Quoted 4 lines · Casey Schaufler

I haven't looked into the issues at all and I bet there are plenty, maybe in audit and places outside of the security realm, but this looks like a clean approach from the LSM interface standpoint. Do you want the entire task or just task->security?

It would probably have to be the task struct, lest the security information (for which I've no refcount held) went away whilst I was trying to access it.

Quoted 3 lines

I could see it either way, but I suspect the task is your best bet. If you call security_act_as() twice, then security_act_as_self() do you pop a stack, or return to the initial state?

Good point. I've pondered that. What I have at the moment partly acts like a stack in that I store some of the shifted-out context on the machine stack (in struct cachefiles_secctx). The act-as context should probably be shifted too, in addition to the old file-creation SID and the fsuid/fsgid.

Quoted 2 lines

How about security_act_as(NULL) returning you to the initial state, and dropping security_act_as_self()?

That would be fine.

Actually, to address Stephen Smalley's requirements also, how about making things a bit more complex. Have the following suite of functions:

(1) int security_get_context(struct sec **_context);

This allocates and gives the caller a blob that describes the current context of all the LSM module states attached to the current task and stores a pointer to it in *_context.

(2) int security_push(struct sec *context, struct sec **_old_context)

This causes all the LSM modules on the current task to switch to a new acting state, passing back the old state. It does not change how other tasks do things to this one.

(3) int security_pop(struct sec *context)

This causes all the LSM modules on the current task to switch to a new acting state, deleting the old state. It does not change how other tasks do things to this one.

(4) int security_delete_context(struct sec *context)

This deletes a context blob.

The context blob could then be structured very simply. Give each loaded LSM module an integer index as it is registered. Having a limit to the number of LSM modules would make things simpler. The blob would then be an array of void pointers, one per LSM module, indexed by the integer index for each one. It you don't have a limit on the number of LSM modules, you'd also need a count of slots in the blob.

Any LSM module that wanted to implement the above three functions would fill in or otherwise use the slot that belongs to it. Otherwise the slot would just be left NULL.

For example:

	context --->+--------+                                    +---------+
	            | SLOT 0 |----------------------------------->| SELINUX |
	            +--------+                      +--------+    +---------+
	            | SLOT 1 |--------------------->| THINGY |
	            +--------+                      +--------+
	            | ...    |
	            +--------+         +-------+
	            | SLOT N |-------->| AUDIT |
	            +--------+         +-------+
Quoted 3 lines

For Stephen and NFS, he could then generate a context from NFS which nfsd could then put in place. Perhaps any unfilled slot would be ignored by the LSM module to which it belonged.

Seems like over-design - we don't need to support LSM stacking, and we don't need to support pushing/popping more than one level of context.

What was the objection again to the original interface, aside from replacing "u32 secids" with "void* security blobs"?

Signature · 2 lines
Stephen Smalley
National Security Agency
#39 lore raw
In reply to Stephen Smalley
Quoted 84 lines · --- Stephen Smalley
Quoted 8 lines · David Howells
Quoted 1 line · Casey Schaufler

Sigh. So it's not only SELinux specific, but RedHat specific as well.

*Blink*. How did you come to that conclusion?

Quoted 2 lines
Quoted 2 lines

(3) The cache driver wants to access the files in the cache, but it's running in the security context of either the aforementioned

random

Quoted 7 lines
Quoted 5 lines
Quoted 1 line

process, or one of FS-Cache's thread pool.

I think that this is the point you should attack. Control the security characteristics of the cache driver properly and you shouldn't need the complexity that you're asking to introduce.

How? The cache driver acts on behalf of someone else. That someone else

has

Quoted 1 line

one security context, but the cache itself has to have a different context

so

Quoted 8 lines

that the cache can be shared.

Furthermore, the cache driver doesn't have a security context per se.

Quoted 4 lines
Quoted 4 lines

This security context, however, doesn't necessarily give it the rights to access what's in the cache, so the driver has to be permitted to act as a context appropriate to accessing the cache, without changing the overall security context of the random

process

Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

(which would impact things trying to act on that process - kill() for example).

Can you run the cache as an independent thread and send it messages rather than trying to do things in the context of the calling process? I know that that involves extra bookkeeppingg, but it's lots safer.

It introduces more complexity, which I believe you were just arguing

against

Quoted 1 line

above... It also incurs more kernel threads - which I really really want

to

Quoted 3 lines

avoid.

I would rank the complexity and resource overhead of the act-as stuff in

LSM

Quoted 3 lines

(or at least in SELinux) as much less than what you're suggesting.

As it stands, the FS-Cache layer has a pool of threads that CacheFiles

makes

Quoted 36 lines

use of, but this can't be bound to the security of a specific cache because there may be more than one cache of more than one cache driver type.

Quoted 4 lines

Yes, and the SELinux semantics for what label to give a file don't help much, either. The problem with the "act_as" interfaces is that I wouldn't expect them to be any more reliable than the old access() system call, which never really gave you a helpful answer.

I don't see how act_as compares to access().

Quoted 3 lines

Ideally you want to be running in the right context to create the new file so that no one can use it and then label it "correctly" and make it available.

That sounds like it'd be the complexity thing again...

Quoted 5 lines
Quoted 3 lines

Part of the problem is that the VFS does not pass around the security context as which the VFS routines act, but rather gets them from the task_struct.

That's by design.

I suspect that's more by the fact that security wasn't particularly thought about when these interfaces were first written. As with everything in the kernel, it might be negotiable.

Quoted 5 lines

The cache driver is a unique case with an unusual function. It's pretty obvious that the kernel architecture, the VFS architecture, LSM, SELinux, NFS and pretty much everyone else has given no thought whatever to the implications of their designs on file system cacheing. For all concerned, I'll say "sorry 'bout that".

Meaning you think I should just give up on this?

How about I reduce the interface I'm proposing to two functions:

Quoted 8 lines
Quoted 5 lines

(1) int security_act_as(struct task_struct *context)

Temporarily make the current process act as the given task, including, for example, for SELinux, the security ID with which this task acts on things, and the security ID with which this task creates files.

I don't see how that helps with nfsd assuming the label of a remote client process.

Well, assuming that nfsd assuming the label of a remote client is a good idea ...

    newtask = taskstructdup(current);
    newtask->security = security_of_client;
    security_act_as(newtask);
    ... do interesting things ...
    security_act_as_self(); /* security_act_as(NULL); ? */
    cleanup_newtask(...)

... would be the basic flow. For what it's worth, and the whole issue is being debated with gusto elsewhere, there are enough problems with nfsd using this approach that it may not be worth holding anything up for.

Quoted 22 lines
Quoted 6 lines
  (2) int security_act_as_self(void);

Restore the context as which we're asking.

This would mean that the task's security context would have to be able to

store

Quoted 2 lines

acting security IDs for everything, but I don't think that's too much of a stretch resourcewise.

Signature · 8 lines
Stephen Smalley
National Security Agency


--
This message was distributed to subscribers of the selinux mailing list.
If you no longer wish to subscribe, send mail to [email protected] with
the words "unsubscribe selinux" without quotes as the message.

Casey Schaufler
[email protected]

author maintainer
#25 lore raw
In reply to Stephen Smalley
Quoted 2 lines · Stephen Smalley

Seems like over-design - we don't need to support LSM stacking, and we don't need to support pushing/popping more than one level of context.

It will, at some point hopefully, be possible for someone to try, say, NFS exporting a cached ISO9660 mount (CDROM) - in which case, we'd should allow for two levels of stack. If we can pass the displaced context to the caller to restore later then that allows for more or less unlimited depth.

It occurs to me that the following is almost good enough, but not quite:

  (1) int security_get_context(void **_context);

This allocates and gives the caller a blob that describes the current context of all the LSM module states attached to the current task and stores a pointer to it in *_context.

(2) int security_push(void *context, struct sec **_old_context)

This causes all the LSM modules on the current task to switch to a new acting state, passing back the old state. It does not change how other tasks do things to this one.

(3) int security_pop(void *context)

This causes all the LSM modules on the current task to switch to a new acting state, deleting the old state. It does not change how other tasks do things to this one.

(4) int security_delete_context(void *context)

I still need a way to transform the cachefilesd context into the kernel's context. See patch:

Subject: [Linux-cachefs] [PATCH 12/16] CacheFiles: Get the SID under which
the CacheFiles module should operate [try #3]

However, this seems to add a fairly generic tranformation, so that could be generalised:

  (5) int security_xfrm_to_kernel_context(void *from, void **_to);
Quoted 2 lines

What was the objection again to the original interface, aside from replacing "u32 secids" with "void* security blobs"?

I got the impression that Casey thought much of this was tied to SELinux, but rereading his/her emails, I'm not so certain. Maybe that's sufficient. Casey?

However, I've realised a problem (as outlined above) with what I've got. Namely its stack isn't necessarily deep enough. Alternatively, nfsd perhaps should suppress caching on what it reads.

David

#37 lore raw
In reply to Stephen Smalley
Quoted 56 lines · --- Stephen Smalley

On Mon, 2007-08-13 at 15:51 +0100, David Howells wrote:

...

Quoted 21 lines

Actually, to address Stephen Smalley's requirements also, how about making things a bit more complex. Have the following suite of functions:

(1) int security_get_context(struct sec **_context);

This allocates and gives the caller a blob that describes the current context of all the LSM module states attached to the current task and stores a pointer to it in *_context.

(2) int security_push(struct sec *context, struct sec **_old_context)

This causes all the LSM modules on the current task to switch to a new acting state, passing back the old state. It does not change how other tasks do things to this one.

(3) int security_pop(struct sec *context)

This causes all the LSM modules on the current task to switch to a new acting state, deleting the old state. It does not change how other tasks do things to this one.

Quoted 5 lines

(4) int security_delete_context(struct sec *context)

This deletes a context blob.

The context blob could then be structured very simply. Give each loaded

LSM

Quoted 1 line

module an integer index as it is registered. Having a limit to the number

of

Quoted 2 lines

LSM modules would make things simpler. The blob would then be an array of void pointers, one per LSM module, indexed by the integer index for each

one.

Quoted 4 lines

It you don't have a limit on the number of LSM modules, you'd also need a count of slots in the blob.

Any LSM module that wanted to implement the above three functions would

fill

Quoted 15 lines

in or otherwise use the slot that belongs to it. Otherwise the slot would just be left NULL.

For example:

	context --->+--------+                                    +---------+
	            | SLOT 0 |----------------------------------->| SELINUX |
	            +--------+                      +--------+    +---------+
	            | SLOT 1 |--------------------->| THINGY |
	            +--------+                      +--------+
	            | ...    |
	            +--------+         +-------+
	            | SLOT N |-------->| AUDIT |
	            +--------+         +-------+
Quoted 6 lines
Quoted 3 lines

For Stephen and NFS, he could then generate a context from NFS which nfsd could then put in place. Perhaps any unfilled slot would be ignored by the LSM module to which it belonged.

Seems like over-design - we don't need to support LSM stacking, and we don't need to support pushing/popping more than one level of context.

LSM stacking has always been contentious and I don't see that it addresses the issue, which is changing the data used by an LSM, not the LSM itself.

Quoted 2 lines

What was the objection again to the original interface, aside from replacing "u32 secids" with "void* security blobs"?

The objection centers around exposing LSM specific data outside the LSM, and it applies to either secids or blobs, really. If you need this information outside the LSM odds are good that what you're using it for is going to be LSM specific, and hence should be inside the LSM. I admit to two gray areas, audit and system service tasks such as the two cited here. I like simplicity and find the single security_act_as() interface attractive for the latter case.

Casey Schaufler
[email protected]

#26 lore raw
In reply to David Howells
Quoted 10 lines · --- David Howells
Quoted 2 lines · Stephen Smalley

Seems like over-design - we don't need to support LSM stacking, and we don't need to support pushing/popping more than one level of context.

It will, at some point hopefully, be possible for someone to try, say, NFS exporting a cached ISO9660 mount (CDROM) - in which case, we'd should allow for two levels of stack. If we can pass the displaced context to the caller to restore later then that allows for more or less unlimited depth.

Quoted 7 lines

It occurs to me that the following is almost good enough, but not quite:

  (1) int security_get_context(void **_context);

This allocates and gives the caller a blob that describes the current context of all the LSM module states attached to the current task and stores a pointer to it in *_context.

Is this intended to be anything more than a copy of current->security?

Quoted 5 lines

(2) int security_push(void *context, struct sec **_old_context)

This causes all the LSM modules on the current task to switch to a new acting state, passing back the old state. It does not change how other tasks do things to this one.

I assume that you're talking about the LSM specific data changing, not the LSM itself.

If you change the task->security information you are definitly going to change what other tasks can do to the calling task. This is part of the dark side of label swapping. This is what I was trying to suggest when I said that if you're going to switch labels you switch to a system-daemon label, do your work, then change the file label explicitly. Stephen may have a trick up his sleeve for SELinux, but I don't expect it to be pleasent.

Quoted 5 lines

(3) int security_pop(void *context)

This causes all the LSM modules on the current task to switch to a new acting state, deleting the old state. It does not change how other tasks do things to this one.

Same issues.

Quoted 5 lines

(4) int security_delete_context(void *context)

I still need a way to transform the cachefilesd context into the kernel's context. See patch:

Quoted 7 lines

Subject: [Linux-cachefs] [PATCH 12/16] CacheFiles: Get the SID under which
the CacheFiles module should operate [try #3]

However, this seems to add a fairly generic tranformation, so that could be generalised:

  (5) int security_xfrm_to_kernel_context(void *from, void **_to);

Woof. What are you transforming from?

Quoted 5 lines
Quoted 2 lines

What was the objection again to the original interface, aside from replacing "u32 secids" with "void* security blobs"?

I got the impression that Casey thought much of this was tied to SELinux, but rereading his/her

"His" is preferred.

Quoted 2 lines

emails, I'm not so certain. Maybe that's sufficient. Casey?

I did get the impression that your initial design was focused on SELinux, and that the implications of alternative LSM modules had not been very high on your priority list. It's clear from your responses that you are taking the issue seriously. Thank you.

Quoted 3 lines

However, I've realised a problem (as outlined above) with what I've got. Namely its stack isn't necessarily deep enough. Alternatively, nfsd perhaps should suppress caching on what it reads.

That's the really nice thing about cans of worms.
They come in six-packs.

Casey Schaufler
[email protected]

author maintainer
#27 lore raw
Quoted 7 lines · Casey Schaufler
Quoted 5 lines
  (1) int security_get_context(void **_context);

This allocates and gives the caller a blob that describes the current context of all the LSM module states attached to the current task and stores a pointer to it in *_context.

Is this intended to be anything more than a copy of current->security?

It has to be sufficient to fully effect security_push().

Quoted 2 lines

I assume that you're talking about the LSM specific data changing, not the LSM itself.

Yes.

Quoted 2 lines

If you change the task->security information you are definitly going to change what other tasks can do to the calling task.

I dealt with that in my current act-as patch. Under SELinux a task has two primary labels. One with which it is labelled and is used to govern effects upon it, and one that is used to act upon things and follows changes to the former.

Quoted 3 lines
Quoted 1 line
  (5) int security_xfrm_to_kernel_context(void *from, void **_to);

Woof. What are you transforming from?

In CacheFiles case, the cachefilesd daemon's security label into the label the cache driver acts as on behalf of other processes.

Quoted 2 lines

That's the really nice thing about cans of worms.
They come in six-packs.

Yeah...

David

#28 lore raw
Quoted 11 lines · --- David Howells
Quoted 7 lines · Casey Schaufler
Quoted 5 lines
  (1) int security_get_context(void **_context);

This allocates and gives the caller a blob that describes the current context of all the LSM module states attached to the current task and stores a pointer to it in *_context.

Is this intended to be anything more than a copy of current->security?

It has to be sufficient to fully effect security_push().

Which is why it requires an LSM interface. Just checking.

Quoted 5 lines
Quoted 2 lines

I assume that you're talking about the LSM specific data changing, not the LSM itself.

Yes.

Quoted 7 lines
Quoted 2 lines

If you change the task->security information you are definitly going to change what other tasks can do to the calling task.

I dealt with that in my current act-as patch. Under SELinux a task has two primary labels. One with which it is labelled and is used to govern effects upon it, and one that is used to act upon things and follows changes to the former.

The specification of your push interface that the push operation not affect how others access the process is OK for SELinux, but not for any other MAC scheme that I've dealt with, and I think that's most of them. Nuts. Smack, for example, uses exactly one label on the process for all purposes.

Are you concerned about accesses other than signals? Signals could be staitforward to deal with in a pushed situation, but I'd hesitate to say that the solution would generalize without additional thought.

Quoted 7 lines
Quoted 3 lines
Quoted 1 line
  (5) int security_xfrm_to_kernel_context(void *from, void **_to);

Woof. What are you transforming from?

In CacheFiles case, the cachefilesd daemon's security label into the label the
cache driver acts as on behalf of other processes.

I'm not sure I understand what this is doing.

Casey Schaufler
[email protected]

author maintainer
#29 lore raw
Quoted 5 lines · Casey Schaufler

The specification of your push interface that the push operation not affect how others access the process is OK for SELinux, but not for any other MAC scheme that I've dealt with, and I think that's most of them. Nuts. Smack, for example, uses exactly one label on the process for all purposes.

It's a fairly important concept. The victimisation security context on a process must not change, even if the kernel overrides the security context that that process acts as so that it can transparently do work on its behalf.

IMO, the right way to do this is to pass the security context directly to vfs_mkdir() and co.

Quoted 4 lines

Are you concerned about accesses other than signals? Signals could be staitforward to deal with in a pushed situation, but I'd hesitate to say that the solution would generalize without additional thought.

There's also /proc and ptrace() for example. ps -z must not show the overridden state.

Quoted 8 lines
Quoted 6 lines
Quoted 3 lines
Quoted 1 line
  (5) int security_xfrm_to_kernel_context(void *from, void **_to);

Woof. What are you transforming from?

In CacheFiles case, the cachefilesd daemon's security label into the label the cache driver acts as on behalf of other processes.

I'm not sure I understand what this is doing.

CacheFiles consists of two parts: the kernel module which creates things in the cache and does accesses into the cache on behalf of processes that access cached filesystems, and the userspace daemon that builds cull tables and deletes things.

The reason there are two security labels is that the daemon's label gives it just enough rights to be able to do its job. More or less all it can do is lookup, opendir, readdir, stat, rmdir, unlink and open the chardev for talking to the kernel module. This means that the daemon can't, for example, be made to read or modify cache storage objects.

Thus means, however, that the daemon's label isn't sufficient for the kernel module to do its job. But since there's no way for the kernel module to directly get a label (and indeed it doesn't know the label it needs), a transformation has to be applied that turns the process label used by the daemon into a process label that the kernel, and only the kernel, can use.

The kernel's label gives it, amongst other things, the additional rights to do mkdir, creat, open, read, write, setxattr, getxattr, rename - things the daemon isn't allowed to do.

David

#30 lore raw
Quoted 51 lines · --- David Howells
Quoted 5 lines · Casey Schaufler

The specification of your push interface that the push operation not affect how others access the process is OK for SELinux, but not for any other MAC scheme that I've dealt with, and I think that's most of them. Nuts. Smack, for example, uses exactly one label on the process for all purposes.

It's a fairly important concept. The victimisation security context on a process must not change, even if the kernel overrides the security context that that process acts as so that it can transparently do work on its behalf.

IMO, the right way to do this is to pass the security context directly to vfs_mkdir() and co.

Quoted 4 lines

Are you concerned about accesses other than signals? Signals could be staitforward to deal with in a pushed situation, but I'd hesitate to say that the solution would generalize without additional thought.

There's also /proc and ptrace() for example. ps -z must not show the overridden state.

Quoted 5 lines
Quoted 5 lines
Quoted 3 lines
Quoted 1 line
  (5) int security_xfrm_to_kernel_context(void *from, void **_to);

Woof. What are you transforming from?

In CacheFiles case, the cachefilesd daemon's security label into the

label

Quoted 3 lines
Quoted 1 line

the cache driver acts as on behalf of other processes.

I'm not sure I understand what this is doing.

CacheFiles consists of two parts: the kernel module which creates things in the cache and does accesses into the cache on behalf of processes that access cached filesystems, and the userspace daemon that builds cull tables and deletes things.

The reason there are two security labels is that the daemon's label gives it just enough rights to be able to do its job. More or less all it can do is lookup, opendir, readdir, stat, rmdir, unlink and open the chardev for talking
to the kernel module. This means that the daemon can't, for example, be made to read or modify cache storage objects.

Thus means, however, that the daemon's label isn't sufficient for the kernel module to do its job. But since there's no way for the kernel module to directly get a label (and indeed it doesn't know the label it needs), a transformation has to be applied that turns the process label used by the daemon into a process label that the kernel, and only the kernel, can use.

Quoted 4 lines

The kernel's label gives it, amongst other things, the additional rights to do
mkdir, creat, open, read, write, setxattr, getxattr, rename - things the daemon isn't allowed to do.

With Smack you can leave the label alone, raise CAP_MAC_OVERRIDE, do your business of setting the label correctly, and then drop the capability. No new hooks required.

Casey Schaufler
[email protected]

author maintainer
#31 lore raw
Quoted 3 lines · Casey Schaufler

With Smack you can leave the label alone, raise CAP_MAC_OVERRIDE, do your business of setting the label correctly, and then drop the capability. No new hooks required.

That sounds like a contradiction. How can you both leave it alone and set it?

David

#32 lore raw
Quoted 8 lines · --- David Howells
Quoted 3 lines · Casey Schaufler

With Smack you can leave the label alone, raise CAP_MAC_OVERRIDE, do your business of setting the label correctly, and then drop the capability. No new hooks required.

That sounds like a contradiction. How can you both leave it alone and set it?

Whoops, sorry. You leave the process label alone and explicitly set the file label using the xattr interfaces.

Casey Schaufler
[email protected]

#33 lore raw
Quoted 8 lines · Casey Schaufler
Quoted 6 lines · --- David Howells
Quoted 3 lines · Casey Schaufler

With Smack you can leave the label alone, raise CAP_MAC_OVERRIDE, do your business of setting the label correctly, and then drop the capability. No new hooks required.

Quoted 5 lines
Quoted 2 lines

That sounds like a contradiction. How can you both leave it alone and set it?

Whoops, sorry. You leave the process label alone and explicitly set the file label using the xattr interfaces.

xattr interfaces don't help with the initial labeling of the file when it is created.

Signature · 2 lines
Stephen Smalley
National Security Agency
#36 lore raw
In reply to Casey Schaufler
Quoted 53 lines · Casey Schaufler
Quoted 51 lines · --- David Howells
Quoted 5 lines · Casey Schaufler

The specification of your push interface that the push operation not affect how others access the process is OK for SELinux, but not for any other MAC scheme that I've dealt with, and I think that's most of them. Nuts. Smack, for example, uses exactly one label on the process for all purposes.

It's a fairly important concept. The victimisation security context on a process must not change, even if the kernel overrides the security context that that process acts as so that it can transparently do work on its behalf.

IMO, the right way to do this is to pass the security context directly to vfs_mkdir() and co.

Quoted 4 lines

Are you concerned about accesses other than signals? Signals could be staitforward to deal with in a pushed situation, but I'd hesitate to say that the solution would generalize without additional thought.

There's also /proc and ptrace() for example. ps -z must not show the overridden state.

Quoted 5 lines
Quoted 5 lines
Quoted 3 lines
Quoted 1 line
  (5) int security_xfrm_to_kernel_context(void *from, void **_to);

Woof. What are you transforming from?

In CacheFiles case, the cachefilesd daemon's security label into the

label

Quoted 3 lines
Quoted 1 line

the cache driver acts as on behalf of other processes.

I'm not sure I understand what this is doing.

CacheFiles consists of two parts: the kernel module which creates things in the cache and does accesses into the cache on behalf of processes that access cached filesystems, and the userspace daemon that builds cull tables and deletes things.

The reason there are two security labels is that the daemon's label gives it just enough rights to be able to do its job. More or less all it can do is lookup, opendir, readdir, stat, rmdir, unlink and open the chardev for talking
to the kernel module. This means that the daemon can't, for example, be made to read or modify cache storage objects.

Thus means, however, that the daemon's label isn't sufficient for the kernel module to do its job. But since there's no way for the kernel module to directly get a label (and indeed it doesn't know the label it needs), a transformation has to be applied that turns the process label used by the daemon into a process label that the kernel, and only the kernel, can use.

Quoted 8 lines
Quoted 4 lines

The kernel's label gives it, amongst other things, the additional rights to do
mkdir, creat, open, read, write, setxattr, getxattr, rename - things the daemon isn't allowed to do.

With Smack you can leave the label alone, raise CAP_MAC_OVERRIDE, do your business of setting the label correctly, and then drop the capability. No new hooks required.

Except that CAP_MAC_OVERRIDE doesn't exist upstream, and if it did, it would represent Smack-specific logic in the core kernel (when you're complaining about SELinux-specific logic there). So even that would have to be encapsulated within a hook.

Signature · 2 lines
Stephen Smalley
National Security Agency
author maintainer
#35 lore raw
In reply to Casey Schaufler
Quoted 2 lines · Casey Schaufler

Whoops, sorry. You leave the process label alone and explicitly set the file label using the xattr interfaces.

That's the wrong way to do things. There'd then be a window in which cachefilesd (the userspace daemon) could attempt to view the file when the file has the wrong label attached.

David

#34 lore raw
In reply to Stephen Smalley
Quoted 10 lines · --- Stephen Smalley
Quoted 9 lines · Casey Schaufler
Quoted 7 lines · --- David Howells
Quoted 3 lines · Casey Schaufler

With Smack you can leave the label alone, raise CAP_MAC_OVERRIDE, do your business of setting the label correctly, and then drop the capability. No new hooks required.

That sounds like a contradiction. How can you both leave it alone and

Quoted 8 lines

set

Quoted 4 lines
Quoted 1 line

it?

Whoops, sorry. You leave the process label alone and explicitly set the file label using the xattr interfaces.

xattr interfaces don't help with the initial labeling of the file when it is created.

That's true. The deamon needs to run with an appropriate label. I don't believe that this is situation with a really simple solution because the activity being performed is unusual.

Quoted 12 lines
Signature · 8 lines
Stephen Smalley
National Security Agency


--
This message was distributed to subscribers of the selinux mailing list.
If you no longer wish to subscribe, send mail to [email protected] with
the words "unsubscribe selinux" without quotes as the message.

Casey Schaufler
[email protected]