code:
.. SPDX-License-Identifier: GPL-2.0

====================
Filesystem Mount API
====================

.. CONTENTS

 (1) Overview.

 (2) The filesystem context.

 (3) The filesystem context operations.

 (4) Filesystem context security.

 (5) VFS filesystem context API.

 (6) Superblock creation helpers.

 (7) Parameter description.

 (8) Parameter helper functions.

Overview
========

The creation of new mounts is now to be done in a multistep process:

 (1) Create a filesystem context.

 (2) Parse the parameters and attach them to the context.  Parameters are
     expected to be passed individually from userspace, though legacy binary
     parameters can also be handled.

 (3) Validate and pre-process the context.

 (4) Get or create a superblock and mountable root.

 (5) Perform the mount.

 (6) Return an error message attached to the context.

 (7) Destroy the context.

To support this, the file_system_type struct gains two new fields::

	int (*init_fs_context)(struct fs_context *fc);
	const struct fs_parameter_description *parameters;

The first is invoked to set up the filesystem-specific parts of a filesystem
context, including the additional space, and the second points to the
parameter description for validation at registration time and querying by a
future system call.

Note that security initialisation is done *after* the filesystem is called so
that the namespaces may be adjusted first.

The Filesystem context
======================

The creation and reconfiguration of a superblock is governed by a filesystem
context.  This is represented by the fs_context structure::

	struct fs_context {
		const struct fs_context_operations *ops;
		struct file_system_type *fs_type;
		void			*fs_private;
		struct dentry		*root;
		struct user_namespace	*user_ns;
		struct net		*net_ns;
		const struct cred	*cred;
		char			*source;
		char			*subtype;
		void			*security;
		void			*s_fs_info;
		unsigned int		sb_flags;
		unsigned int		sb_flags_mask;
		unsigned int		s_iflags;
		unsigned int		lsm_flags;
		enum fs_context_purpose	purpose:8;
		...
	};

The fs_context fields are as follows:

   * ::

       const struct fs_context_operations *ops

     These are operations that can be done on a filesystem context (see
     below).  This must be set by the ->init_fs_context() file_system_type
     operation.

   * ::

       struct file_system_type *fs_type

     A pointer to the file_system_type of the filesystem that is being
     constructed or reconfigured.  This retains a reference on the type owner.

   * ::

       void *fs_private

     A pointer to the file system's private data.  This is where the filesystem
     will need to store any options it parses.

   * ::

       struct dentry *root

     A pointer to the root of the mountable tree (and indirectly, the
     superblock thereof).  This is filled in by the ->get_tree() op.  If this
     is set, an active reference on root->d_sb must also be held.

   * ::

       struct user_namespace *user_ns
       struct net *net_ns

     There are a subset of the namespaces in use by the invoking process.  They
     retain references on each namespace.  The subscribed namespaces may be
     replaced by the filesystem to reflect other sources, such as the parent
     mount superblock on an automount.

   * ::

       const struct cred *cred

     The mounter's credentials.  This retains a reference on the credentials.

   * ::

       char *source

     This specifies the source.  It may be a block device (e.g. /dev/sda1) or
     something more exotic, such as the "host:/path" that NFS desires.

   * ::

       char *subtype

     This is a string to be added to the type displayed in /proc/mounts to
     qualify it (used by FUSE).  This is available for the filesystem to set if
     desired.

   * ::

       void *security

     A place for the LSMs to hang their security data for the superblock.  The
     relevant security operations are described below.

   * ::

       void *s_fs_info

     The proposed s_fs_info for a new superblock, set in the superblock by
     sget_fc().  This can be used to distinguish superblocks.

   * ::

       unsigned int sb_flags
       unsigned int sb_flags_mask

     Which bits SB_* flags are to be set/cleared in super_block::s_flags.

   * ::

       unsigned int s_iflags

     These will be bitwise-OR'd with s->s_iflags when a superblock is created.

   * ::

       enum fs_context_purpose

     This indicates the purpose for which the context is intended.  The
     available values are:

	==========================	======================================
	FS_CONTEXT_FOR_MOUNT,		New superblock for explicit mount
	FS_CONTEXT_FOR_SUBMOUNT		New automatic submount of extant mount
	FS_CONTEXT_FOR_RECONFIGURE	Change an existing mount
	==========================	======================================

The mount context is created by calling vfs_new_fs_context() or
vfs_dup_fs_context() and is destroyed with put_fs_context().  Note that the
structure is not refcounted.

VFS, security and filesystem mount options are set individually with
vfs_parse_mount_option().  Options provided by the old mount(2) system call as
a page of data can be parsed with generic_parse_monolithic().

When mounting, the filesystem is allowed to take data from any of the pointers
and attach it to the superblock (or whatever), provided it clears the pointer
in the mount context.

The filesystem is also allowed to allocate resources and pin them with the
mount context.  For instance, NFS might pin the appropriate protocol version
module.

The Filesystem Context Operations
=================================

The filesystem context points to a table of operations::

	struct fs_context_operations {
		void (*free)(struct fs_context *fc);
		int (*dup)(struct fs_context *fc, struct fs_context *src_fc);
		int (*parse_param)(struct fs_context *fc,
				   struct fs_parameter *param);
		int (*parse_monolithic)(struct fs_context *fc, void *data);
		int (*get_tree)(struct fs_context *fc);
		int (*reconfigure)(struct fs_context *fc);
	};

These operations are invoked by the various stages of the mount procedure to
manage the filesystem context.  They are as follows:

   * ::

	void (*free)(struct fs_context *fc);

     Called to clean up the filesystem-specific part of the filesystem context
     when the context is destroyed.  It should be aware that parts of the
     context may have been removed and NULL'd out by ->get_tree().

   * ::

	int (*dup)(struct fs_context *fc, struct fs_context *src_fc);

     Called when a filesystem context has been duplicated to duplicate the
     filesystem-private data.  An error may be returned to indicate failure to
     do this.

     .. Warning::

         Note that even if this fails, put_fs_context() will be called
	 immediately thereafter, so ->dup() *must* make the
	 filesystem-private data safe for ->free().

   * ::

	int (*parse_param)(struct fs_context *fc,
			   struct fs_parameter *param);

     Called when a parameter is being added to the filesystem context.  param
     points to the key name and maybe a value object.  VFS-specific options
     will have been weeded out and fc->sb_flags updated in the context.
     Security options will also have been weeded out and fc->security updated.

     The parameter can be parsed with fs_parse() and fs_lookup_param().  Note
     that the source(s) are presented as parameters named "source".

     If successful, 0 should be returned or a negative error code otherwise.

   * ::

	int (*parse_monolithic)(struct fs_context *fc, void *data);

     Called when the mount(2) system call is invoked to pass the entire data
     page in one go.  If this is expected to be just a list of "key[=val]"
     items separated by commas, then this may be set to NULL.

     The return value is as for ->parse_param().

     If the filesystem (e.g. NFS) needs to examine the data first and then
     finds it's the standard key-val list then it may pass it off to
     generic_parse_monolithic().

   * ::

	int (*get_tree)(struct fs_context *fc);

     Called to get or create the mountable root and superblock, using the
     information stored in the filesystem context (reconfiguration goes via a
     different vector).  It may detach any resources it desires from the
     filesystem context and transfer them to the superblock it creates.

     On success it should set fc->root to the mountable root and return 0.  In
     the case of an error, it should return a negative error code.

     The phase on a userspace-driven context will be set to only allow this to
     be called once on any particular context.

   * ::

	int (*reconfigure)(struct fs_context *fc);

     Called to effect reconfiguration of a superblock using information stored
     in the filesystem context.  It may detach any resources it desires from
     the filesystem context and transfer them to the superblock.  The
     superblock can be found from fc->root->d_sb.

     On success it should return 0.  In the case of an error, it should return
     a negative error code.

     .. Note:: reconfigure is intended as a replacement for remount_fs.

Filesystem context Security
===========================

The filesystem context contains a security pointer that the LSMs can use for
building up a security context for the superblock to be mounted.  There are a
number of operations used by the new mount code for this purpose:

   * ::

	int security_fs_context_alloc(struct fs_context *fc,
				      struct dentry *reference);

     Called to initialise fc->security (which is preset to NULL) and allocate
     any resources needed.  It should return 0 on success or a negative error
     code on failure.

     reference will be non-NULL if the context is being created for superblock
     reconfiguration (FS_CONTEXT_FOR_RECONFIGURE) in which case it indicates
     the root dentry of the superblock to be reconfigured.  It will also be
     non-NULL in the case of a submount (FS_CONTEXT_FOR_SUBMOUNT) in which case
     it indicates the automount point.

   * ::

	int security_fs_context_dup(struct fs_context *fc,
				    struct fs_context *src_fc);

     Called to initialise fc->security (which is preset to NULL) and allocate
     any resources needed.  The original filesystem context is pointed to by
     src_fc and may be used for reference.  It should return 0 on success or a
     negative error code on failure.

   * ::

	void security_fs_context_free(struct fs_context *fc);

     Called to clean up anything attached to fc->security.  Note that the
     contents may have been transferred to a superblock and the pointer cleared
     during get_tree.

   * ::

	int security_fs_context_parse_param(struct fs_context *fc,
					    struct fs_parameter *param);

     Called for each mount parameter, including the source.  The arguments are
     as for the ->parse_param() method.  It should return 0 to indicate that
     the parameter should be passed on to the filesystem, 1 to indicate that
     the parameter should be discarded or an error to indicate that the
     parameter should be rejected.

     The value pointed to by param may be modified (if a string) or stolen
     (provided the value pointer is NULL'd out).  If it is stolen, 1 must be
     returned to prevent it being passed to the filesystem.

   * ::

	int security_fs_context_validate(struct fs_context *fc);

     Called after all the options have been parsed to validate the collection
     as a whole and to do any necessary allocation so that
     security_sb_get_tree() and security_sb_reconfigure() are less likely to
     fail.  It should return 0 or a negative error code.

     In the case of reconfiguration, the target superblock will be accessible
     via fc->root.

   * ::

	int security_sb_get_tree(struct fs_context *fc);

     Called during the mount procedure to verify that the specified superblock
     is allowed to be mounted and to transfer the security data there.  It
     should return 0 or a negative error code.

   * ::

	void security_sb_reconfigure(struct fs_context *fc);

     Called to apply any reconfiguration to an LSM's context.  It must not
     fail.  Error checking and resource allocation must be done in advance by
     the parameter parsing and validation hooks.

   * ::

	int security_sb_mountpoint(struct fs_context *fc,
			           struct path *mountpoint,
				   unsigned int mnt_flags);

     Called during the mount procedure to verify that the root dentry attached
     to the context is permitted to be attached to the specified mountpoint.
     It should return 0 on success or a negative error code on failure.

VFS Filesystem context API
==========================

There are four operations for creating a filesystem context and one for
destroying a context:

   * ::

       struct fs_context *fs_context_for_mount(struct file_system_type *fs_type,
					       unsigned int sb_flags);

     Allocate a filesystem context for the purpose of setting up a new mount,
     whether that be with a new superblock or sharing an existing one.  This
     sets the superblock flags, initialises the security and calls
     fs_type->init_fs_context() to initialise the filesystem private data.

     fs_type specifies the filesystem type that will manage the context and
     sb_flags presets the superblock flags stored therein.

   * ::

       struct fs_context *fs_context_for_reconfigure(
		struct dentry *dentry,
		unsigned int sb_flags,
		unsigned int sb_flags_mask);

     Allocate a filesystem context for the purpose of reconfiguring an
     existing superblock.  dentry provides a reference to the superblock to be
     configured.  sb_flags and sb_flags_mask indicate which superblock flags
     need changing and to what.

   * ::

       struct fs_context *fs_context_for_submount(
		struct file_system_type *fs_type,
		struct dentry *reference);

     Allocate a filesystem context for the purpose of creating a new mount for
     an automount point or other derived superblock.  fs_type specifies the
     filesystem type that will manage the context and the reference dentry
     supplies the parameters.  Namespaces are propagated from the reference
     dentry's superblock also.

     Note that it's not a requirement that the reference dentry be of the same
     filesystem type as fs_type.

   * ::

        struct fs_context *vfs_dup_fs_context(struct fs_context *src_fc);

     Duplicate a filesystem context, copying any options noted and duplicating
     or additionally referencing any resources held therein.  This is available
     for use where a filesystem has to get a mount within a mount, such as NFS4
     does by internally mounting the root of the target server and then doing a
     private pathwalk to the target directory.

     The purpose in the new context is inherited from the old one.

   * ::

       void put_fs_context(struct fs_context *fc);

     Destroy a filesystem context, releasing any resources it holds.  This
     calls the ->free() operation.  This is intended to be called by anyone who
     created a filesystem context.

     .. Warning::

        filesystem contexts are not refcounted, so this causes unconditional
	destruction.

In all the above operations, apart from the put op, the return is a mount
context pointer or a negative error code.

For the remaining operations, if an error occurs, a negative error code will be
returned.

   * ::

        int vfs_parse_fs_param(struct fs_context *fc,
			       struct fs_parameter *param);

     Supply a single mount parameter to the filesystem context.  This includes
     the specification of the source/device which is specified as the "source"
     parameter (which may be specified multiple times if the filesystem
     supports that).

     param specifies the parameter key name and the value.  The parameter is
     first checked to see if it corresponds to a standard mount flag (in which
     case it is used to set an SB_xxx flag and consumed) or a security option
     (in which case the LSM consumes it) before it is passed on to the
     filesystem.

     The parameter value is typed and can be one of:

	====================		=============================
	fs_value_is_flag		Parameter not given a value
	fs_value_is_string		Value is a string
	fs_value_is_blob		Value is a binary blob
	fs_value_is_filename		Value is a filename* + dirfd
	fs_value_is_file		Value is an open file (file*)
	====================		=============================

     If there is a value, that value is stored in a union in the struct in one
     of param->{string,blob,name,file}.  Note that the function may steal and
     clear the pointer, but then becomes responsible for disposing of the
     object.

   * ::

       int vfs_parse_fs_string(struct fs_context *fc, const char *key,
			       const char *value, size_t v_size);

     A wrapper around vfs_parse_fs_param() that copies the value string it is
     passed.

   * ::

       int generic_parse_monolithic(struct fs_context *fc, void *data);

     Parse a sys_mount() data page, assuming the form to be a text list
     consisting of key[=val] options separated by commas.  Each item in the
     list is passed to vfs_mount_option().  This is the default when the
     ->parse_monolithic() method is NULL.

   * ::

       int vfs_get_tree(struct fs_context *fc);

     Get or create the mountable root and superblock, using the parameters in
     the filesystem context to select/configure the superblock.  This invokes
     the ->get_tree() method.

   * ::

       struct vfsmount *vfs_create_mount(struct fs_context *fc);

     Create a mount given the parameters in the specified filesystem context.
     Note that this does not attach the mount to anything.

Superblock Creation Helpers
===========================

A number of VFS helpers are available for use by filesystems for the creation
or looking up of superblocks.

   * ::

       struct super_block *
       sget_fc(struct fs_context *fc,
	       int (*test)(struct super_block *sb, struct fs_context *fc),
	       int (*set)(struct super_block *sb, struct fs_context *fc));

     This is the core routine.  If test is non-NULL, it searches for an
     existing superblock matching the criteria held in the fs_context, using
     the test function to match them.  If no match is found, a new superblock
     is created and the set function is called to set it up.

     Prior to the set function being called, fc->s_fs_info will be transferred
     to sb->s_fs_info - and fc->s_fs_info will be cleared if set returns
     success (ie. 0).

The following helpers all wrap sget_fc():

	(1) vfs_get_single_super

	    Only one such superblock may exist in the system.  Any further
	    attempt to get a new superblock gets this one (and any parameter
	    differences are ignored).

	(2) vfs_get_keyed_super

	    Multiple superblocks of this type may exist and they're keyed on
	    their s_fs_info pointer (for example this may refer to a
	    namespace).

	(3) vfs_get_independent_super

	    Multiple independent superblocks of this type may exist.  This
	    function never matches an existing one and always creates a new
	    one.

Parameter Description
=====================

Parameters are described using structures defined in linux/fs_parser.h.
There's a core description struct that links everything together::

	struct fs_parameter_description {
		const struct fs_parameter_spec *specs;
		const struct fs_parameter_enum *enums;
	};

For example::

	enum {
		Opt_autocell,
		Opt_bar,
		Opt_dyn,
		Opt_foo,
		Opt_source,
	};

	static const struct fs_parameter_description afs_fs_parameters = {
		.specs		= afs_param_specs,
		.enums		= afs_param_enums,
	};

The members are as follows:

 (1) ::

       const struct fs_parameter_specification *specs;

     Table of parameter specifications, terminated with a null entry, where the
     entries are of type::

	struct fs_parameter_spec {
		const char		*name;
		u8			opt;
		enum fs_parameter_type	type:8;
		unsigned short		flags;
	};

     The 'name' field is a string to match exactly to the parameter key (no
     wildcards, patterns and no case-independence) and 'opt' is the value that
     will be returned by the fs_parser() function in the case of a successful
     match.

     The 'type' field indicates the desired value type and must be one of:

	=======================	=======================	=====================
	TYPE NAME		EXPECTED VALUE		RESULT IN
	=======================	=======================	=====================
	fs_param_is_flag	No value		n/a
	fs_param_is_bool	Boolean value		result->boolean
	fs_param_is_u32		32-bit unsigned int	result->uint_32
	fs_param_is_u32_octal	32-bit octal int	result->uint_32
	fs_param_is_u32_hex	32-bit hex int		result->uint_32
	fs_param_is_s32		32-bit signed int	result->int_32
	fs_param_is_u64		64-bit unsigned int	result->uint_64
	fs_param_is_enum	Enum value name 	result->uint_32
	fs_param_is_string	Arbitrary string	param->string
	fs_param_is_blob	Binary blob		param->blob
	fs_param_is_blockdev	Blockdev path		* Needs lookup
	fs_param_is_path	Path			* Needs lookup
	fs_param_is_fd		File descriptor		result->int_32
	=======================	=======================	=====================

     Note that if the value is of fs_param_is_bool type, fs_parse() will try
     to match any string value against "0", "1", "no", "yes", "false", "true".

     Each parameter can also be qualified with 'flags':

	=======================	================================================
	fs_param_v_optional	The value is optional
	fs_param_neg_with_no	result->negated set if key is prefixed with "no"
	fs_param_neg_with_empty	result->negated set if value is ""
	fs_param_deprecated	The parameter is deprecated.
	=======================	================================================

     These are wrapped with a number of convenience wrappers:

	=======================	===============================================
	MACRO			SPECIFIES
	=======================	===============================================
	fsparam_flag()		fs_param_is_flag
	fsparam_flag_no()	fs_param_is_flag, fs_param_neg_with_no
	fsparam_bool()		fs_param_is_bool
	fsparam_u32()		fs_param_is_u32
	fsparam_u32oct()	fs_param_is_u32_octal
	fsparam_u32hex()	fs_param_is_u32_hex
	fsparam_s32()		fs_param_is_s32
	fsparam_u64()		fs_param_is_u64
	fsparam_enum()		fs_param_is_enum
	fsparam_string()	fs_param_is_string
	fsparam_blob()		fs_param_is_blob
	fsparam_bdev()		fs_param_is_blockdev
	fsparam_path()		fs_param_is_path
	fsparam_fd()		fs_param_is_fd
	=======================	===============================================

     all of which take two arguments, name string and option number - for
     example::

	static const struct fs_parameter_spec afs_param_specs[] = {
		fsparam_flag	("autocell",	Opt_autocell),
		fsparam_flag	("dyn",		Opt_dyn),
		fsparam_string	("source",	Opt_source),
		fsparam_flag_no	("foo",		Opt_foo),
		{}
	};

     An addition macro, __fsparam() is provided that takes an additional pair
     of arguments to specify the type and the flags for anything that doesn't
     match one of the above macros.

 (2) ::

       const struct fs_parameter_enum *enums;

     Table of enum value names to integer mappings, terminated with a null
     entry.  This is of type::

	struct fs_parameter_enum {
		u8		opt;
		char		name[14];
		u8		value;
	};

     Where the array is an unsorted list of { parameter ID, name }-keyed
     elements that indicate the value to map to, e.g.::

	static const struct fs_parameter_enum afs_param_enums[] = {
		{ Opt_bar,   "x",      1},
		{ Opt_bar,   "y",      23},
		{ Opt_bar,   "z",      42},
	};

     If a parameter of type fs_param_is_enum is encountered, fs_parse() will
     try to look the value up in the enum table and the result will be stored
     in the parse result.

The parser should be pointed to by the parser pointer in the file_system_type
struct as this will provide validation on registration (if
CONFIG_VALIDATE_FS_PARSER=y) and will allow the description to be queried from
userspace using the fsinfo() syscall.

Parameter Helper Functions
==========================

A number of helper functions are provided to help a filesystem or an LSM
process the parameters it is given.

   * ::

       int lookup_constant(const struct constant_table tbl[],
			   const char *name, int not_found);

     Look up a constant by name in a table of name -> integer mappings.  The
     table is an array of elements of the following type::

	struct constant_table {
		const char	*name;
		int		value;
	};

     If a match is found, the corresponding value is returned.  If a match
     isn't found, the not_found value is returned instead.

   * ::

       bool validate_constant_table(const struct constant_table *tbl,
				    size_t tbl_size,
				    int low, int high, int special);

     Validate a constant table.  Checks that all the elements are appropriately
     ordered, that there are no duplicates and that the values are between low
     and high inclusive, though provision is made for one allowable special
     value outside of that range.  If no special value is required, special
     should just be set to lie inside the low-to-high range.

     If all is good, true is returned.  If the table is invalid, errors are
     logged to the kernel log buffer and false is returned.

   * ::

       bool fs_validate_description(const struct fs_parameter_description *desc);

     This performs some validation checks on a parameter description.  It
     returns true if the description is good and false if it is not.  It will
     log errors to the kernel log buffer if validation fails.

   * ::

        int fs_parse(struct fs_context *fc,
		     const struct fs_parameter_description *desc,
		     struct fs_parameter *param,
		     struct fs_parse_result *result);

     This is the main interpreter of parameters.  It uses the parameter
     description to look up a parameter by key name and to convert that to an
     option number (which it returns).

     If successful, and if the parameter type indicates the result is a
     boolean, integer or enum type, the value is converted by this function and
     the result stored in result->{boolean,int_32,uint_32,uint_64}.

     If a match isn't initially made, the key is prefixed with "no" and no
     value is present then an attempt will be made to look up the key with the
     prefix removed.  If this matches a parameter for which the type has flag
     fs_param_neg_with_no set, then a match will be made and result->negated
     will be set to true.

     If the parameter isn't matched, -ENOPARAM will be returned; if the
     parameter is matched, but the value is erroneous, -EINVAL will be
     returned; otherwise the parameter's option number will be returned.

   * ::

       int fs_lookup_param(struct fs_context *fc,
			   struct fs_parameter *value,
			   bool want_bdev,
			   unsigned int flags,
			   struct path *_path);

     This takes a parameter that carries a string or filename type and attempts
     to do a path lookup on it.  If the parameter expects a blockdev, a check
     is made that the inode actually represents one.

     Returns 0 if successful and ``*_path`` will be set; returns a negative
     error code if not.


code:
.. SPDX-License-Identifier: GPL-2.0

=================================
Network Filesystem Helper Library
=================================

.. Contents:

 - Overview.
 - Per-inode context.
   - Inode context helper functions.
 - Buffered read helpers.
   - Read helper functions.
   - Read helper structures.
   - Read helper operations.
   - Read helper procedure.
   - Read helper cache API.

Overview
========

The network filesystem helper library is a set of functions designed to aid a
network filesystem in implementing VM/VFS operations.  For the moment, that
just includes turning various VM buffered read operations into requests to read
from the server.  The helper library, however, can also interpose other
services, such as local caching or local data encryption.

Note that the library module doesn't link against local caching directly, so
access must be provided by the netfs.

Per-Inode Context
=================

The network filesystem helper library needs a place to store a bit of state for
its use on each netfs inode it is helping to manage.  To this end, a context
structure is defined::

	struct netfs_inode {
		struct inode inode;
		const struct netfs_request_ops *ops;
		struct fscache_cookie *cache;
	};

A network filesystem that wants to use netfs lib must place one of these in its
inode wrapper struct instead of the VFS ``struct inode``.  This can be done in
a way similar to the following::

	struct my_inode {
		struct netfs_inode netfs; /* Netfslib context and vfs inode */
		...
	};

This allows netfslib to find its state by using ``container_of()`` from the
inode pointer, thereby allowing the netfslib helper functions to be pointed to
directly by the VFS/VM operation tables.

The structure contains the following fields:

 * ``inode``

   The VFS inode structure.

 * ``ops``

   The set of operations provided by the network filesystem to netfslib.

 * ``cache``

   Local caching cookie, or NULL if no caching is enabled.  This field does not
   exist if fscache is disabled.

Inode Context Helper Functions
------------------------------

To help deal with the per-inode context, a number helper functions are
provided.  Firstly, a function to perform basic initialisation on a context and
set the operations table pointer::

	void netfs_inode_init(struct netfs_inode *ctx,
			      const struct netfs_request_ops *ops);

then a function to cast from the VFS inode structure to the netfs context::

	struct netfs_inode *netfs_node(struct inode *inode);

and finally, a function to get the cache cookie pointer from the context
attached to an inode (or NULL if fscache is disabled)::

	struct fscache_cookie *netfs_i_cookie(struct netfs_inode *ctx);

Buffered Read Helpers
=====================

The library provides a set of read helpers that handle the ->read_folio(),
->readahead() and much of the ->write_begin() VM operations and translate them
into a common call framework.

The following services are provided:

 * Handle folios that span multiple pages.

 * Insulate the netfs from VM interface changes.

 * Allow the netfs to arbitrarily split reads up into pieces, even ones that
   don't match folio sizes or folio alignments and that may cross folios.

 * Allow the netfs to expand a readahead request in both directions to meet its
   needs.

 * Allow the netfs to partially fulfil a read, which will then be resubmitted.

 * Handle local caching, allowing cached data and server-read data to be
   interleaved for a single request.

 * Handle clearing of bufferage that aren't on the server.

 * Handle retrying of reads that failed, switching reads from the cache to the
   server as necessary.

 * In the future, this is a place that other services can be performed, such as
   local encryption of data to be stored remotely or in the cache.

From the network filesystem, the helpers require a table of operations.  This
includes a mandatory method to issue a read operation along with a number of
optional methods.

Read Helper Functions
---------------------

Three read helpers are provided::

	void netfs_readahead(struct readahead_control *ractl);
	int netfs_read_folio(struct file *file,
			     struct folio *folio);
	int netfs_write_begin(struct netfs_inode *ctx,
			      struct file *file,
			      struct address_space *mapping,
			      loff_t pos,
			      unsigned int len,
			      struct folio **_folio,
			      void **_fsdata);

Each corresponds to a VM address space operation.  These operations use the
state in the per-inode context.

For ->readahead() and ->read_folio(), the network filesystem just point directly
at the corresponding read helper; whereas for ->write_begin(), it may be a
little more complicated as the network filesystem might want to flush
conflicting writes or track dirty data and needs to put the acquired folio if
an error occurs after calling the helper.

The helpers manage the read request, calling back into the network filesystem
through the suppplied table of operations.  Waits will be performed as
necessary before returning for helpers that are meant to be synchronous.

If an error occurs, the ->free_request() will be called to clean up the
netfs_io_request struct allocated.  If some parts of the request are in
progress when an error occurs, the request will get partially completed if
sufficient data is read.

Additionally, there is::

  * void netfs_subreq_terminated(struct netfs_io_subrequest *subreq,
				 ssize_t transferred_or_error,
				 bool was_async);

which should be called to complete a read subrequest.  This is given the number
of bytes transferred or a negative error code, plus a flag indicating whether
the operation was asynchronous (ie. whether the follow-on processing can be
done in the current context, given this may involve sleeping).

Read Helper Structures
----------------------

The read helpers make use of a couple of structures to maintain the state of
the read.  The first is a structure that manages a read request as a whole::

	struct netfs_io_request {
		struct inode		*inode;
		struct address_space	*mapping;
		struct netfs_cache_resources cache_resources;
		void			*netfs_priv;
		loff_t			start;
		size_t			len;
		loff_t			i_size;
		const struct netfs_request_ops *netfs_ops;
		unsigned int		debug_id;
		...
	};

The above fields are the ones the netfs can use.  They are:

 * ``inode``
 * ``mapping``

   The inode and the address space of the file being read from.  The mapping
   may or may not point to inode->i_data.

 * ``cache_resources``

   Resources for the local cache to use, if present.

 * ``netfs_priv``

   The network filesystem's private data.  The value for this can be passed in
   to the helper functions or set during the request.

 * ``start``
 * ``len``

   The file position of the start of the read request and the length.  These
   may be altered by the ->expand_readahead() op.

 * ``i_size``

   The size of the file at the start of the request.

 * ``netfs_ops``

   A pointer to the operation table.  The value for this is passed into the
   helper functions.

 * ``debug_id``

   A number allocated to this operation that can be displayed in trace lines
   for reference.

The second structure is used to manage individual slices of the overall read
request::

	struct netfs_io_subrequest {
		struct netfs_io_request *rreq;
		loff_t			start;
		size_t			len;
		size_t			transferred;
		unsigned long		flags;
		unsigned short		debug_index;
		...
	};

Each subrequest is expected to access a single source, though the helpers will
handle falling back from one source type to another.  The members are:

 * ``rreq``

   A pointer to the read request.

 * ``start``
 * ``len``

   The file position of the start of this slice of the read request and the
   length.

 * ``transferred``

   The amount of data transferred so far of the length of this slice.  The
   network filesystem or cache should start the operation this far into the
   slice.  If a short read occurs, the helpers will call again, having updated
   this to reflect the amount read so far.

 * ``flags``

   Flags pertaining to the read.  There are two of interest to the filesystem
   or cache:

   * ``NETFS_SREQ_CLEAR_TAIL``

     This can be set to indicate that the remainder of the slice, from
     transferred to len, should be cleared.

   * ``NETFS_SREQ_SEEK_DATA_READ``

     This is a hint to the cache that it might want to try skipping ahead to
     the next data (ie. using SEEK_DATA).

 * ``debug_index``

   A number allocated to this slice that can be displayed in trace lines for
   reference.

Read Helper Operations
----------------------

The network filesystem must provide the read helpers with a table of operations
through which it can issue requests and negotiate::

	struct netfs_request_ops {
		void (*init_request)(struct netfs_io_request *rreq, struct file *file);
		void (*free_request)(struct netfs_io_request *rreq);
		int (*begin_cache_operation)(struct netfs_io_request *rreq);
		void (*expand_readahead)(struct netfs_io_request *rreq);
		bool (*clamp_length)(struct netfs_io_subrequest *subreq);
		void (*issue_read)(struct netfs_io_subrequest *subreq);
		bool (*is_still_valid)(struct netfs_io_request *rreq);
		int (*check_write_begin)(struct file *file, loff_t pos, unsigned len,
					 struct folio **foliop, void **_fsdata);
		void (*done)(struct netfs_io_request *rreq);
	};

The operations are as follows:

 * ``init_request()``

   [Optional] This is called to initialise the request structure.  It is given
   the file for reference.

 * ``free_request()``

   [Optional] This is called as the request is being deallocated so that the
   filesystem can clean up any state it has attached there.

 * ``begin_cache_operation()``

   [Optional] This is called to ask the network filesystem to call into the
   cache (if present) to initialise the caching state for this read.  The netfs
   library module cannot access the cache directly, so the cache should call
   something like fscache_begin_read_operation() to do this.

   The cache gets to store its state in ->cache_resources and must set a table
   of operations of its own there (though of a different type).

   This should return 0 on success and an error code otherwise.  If an error is
   reported, the operation may proceed anyway, just without local caching (only
   out of memory and interruption errors cause failure here).

 * ``expand_readahead()``

   [Optional] This is called to allow the filesystem to expand the size of a
   readahead read request.  The filesystem gets to expand the request in both
   directions, though it's not permitted to reduce it as the numbers may
   represent an allocation already made.  If local caching is enabled, it gets
   to expand the request first.

   Expansion is communicated by changing ->start and ->len in the request
   structure.  Note that if any change is made, ->len must be increased by at
   least as much as ->start is reduced.

 * ``clamp_length()``

   [Optional] This is called to allow the filesystem to reduce the size of a
   subrequest.  The filesystem can use this, for example, to chop up a request
   that has to be split across multiple servers or to put multiple reads in
   flight.

   This should return 0 on success and an error code on error.

 * ``issue_read()``

   [Required] The helpers use this to dispatch a subrequest to the server for
   reading.  In the subrequest, ->start, ->len and ->transferred indicate what
   data should be read from the server.

   There is no return value; the netfs_subreq_terminated() function should be
   called to indicate whether or not the operation succeeded and how much data
   it transferred.  The filesystem also should not deal with setting folios
   uptodate, unlocking them or dropping their refs - the helpers need to deal
   with this as they have to coordinate with copying to the local cache.

   Note that the helpers have the folios locked, but not pinned.  It is
   possible to use the ITER_XARRAY iov iterator to refer to the range of the
   inode that is being operated upon without the need to allocate large bvec
   tables.

 * ``is_still_valid()``

   [Optional] This is called to find out if the data just read from the local
   cache is still valid.  It should return true if it is still valid and false
   if not.  If it's not still valid, it will be reread from the server.

 * ``check_write_begin()``

   [Optional] This is called from the netfs_write_begin() helper once it has
   allocated/grabbed the folio to be modified to allow the filesystem to flush
   conflicting state before allowing it to be modified.

   It may unlock and discard the folio it was given and set the caller's folio
   pointer to NULL.  It should return 0 if everything is now fine (``*foliop``
   left set) or the op should be retried (``*foliop`` cleared) and any other
   error code to abort the operation.

 * ``done``

   [Optional] This is called after the folios in the request have all been
   unlocked (and marked uptodate if applicable).

Read Helper Procedure
---------------------

The read helpers work by the following general procedure:

 * Set up the request.

 * For readahead, allow the local cache and then the network filesystem to
   propose expansions to the read request.  This is then proposed to the VM.
   If the VM cannot fully perform the expansion, a partially expanded read will
   be performed, though this may not get written to the cache in its entirety.

 * Loop around slicing chunks off of the request to form subrequests:

   * If a local cache is present, it gets to do the slicing, otherwise the
     helpers just try to generate maximal slices.

   * The network filesystem gets to clamp the size of each slice if it is to be
     the source.  This allows rsize and chunking to be implemented.

   * The helpers issue a read from the cache or a read from the server or just
     clears the slice as appropriate.

   * The next slice begins at the end of the last one.

   * As slices finish being read, they terminate.

 * When all the subrequests have terminated, the subrequests are assessed and
   any that are short or have failed are reissued:

   * Failed cache requests are issued against the server instead.

   * Failed server requests just fail.

   * Short reads against either source will be reissued against that source
     provided they have transferred some more data:

     * The cache may need to skip holes that it can't do DIO from.

     * If NETFS_SREQ_CLEAR_TAIL was set, a short read will be cleared to the
       end of the slice instead of reissuing.

 * Once the data is read, the folios that have been fully read/cleared:

   * Will be marked uptodate.

   * If a cache is present, will be marked with PG_fscache.

   * Unlocked

 * Any folios that need writing to the cache will then have DIO writes issued.

 * Synchronous operations will wait for reading to be complete.

 * Writes to the cache will proceed asynchronously and the folios will have the
   PG_fscache mark removed when that completes.

 * The request structures will be cleaned up when everything has completed.

Read Helper Cache API
---------------------

When implementing a local cache to be used by the read helpers, two things are
required: some way for the network filesystem to initialise the caching for a
read request and a table of operations for the helpers to call.

The network filesystem's ->begin_cache_operation() method is called to set up a
cache and this must call into the cache to do the work.  If using fscache, for
example, the cache would call::

	int fscache_begin_read_operation(struct netfs_io_request *rreq,
					 struct fscache_cookie *cookie);

passing in the request pointer and the cookie corresponding to the file.

The netfs_io_request object contains a place for the cache to hang its
state::

	struct netfs_cache_resources {
		const struct netfs_cache_ops	*ops;
		void				*cache_priv;
		void				*cache_priv2;
	};

This contains an operations table pointer and two private pointers.  The
operation table looks like the following::

	struct netfs_cache_ops {
		void (*end_operation)(struct netfs_cache_resources *cres);

		void (*expand_readahead)(struct netfs_cache_resources *cres,
					 loff_t *_start, size_t *_len, loff_t i_size);

		enum netfs_io_source (*prepare_read)(struct netfs_io_subrequest *subreq,
						       loff_t i_size);

		int (*read)(struct netfs_cache_resources *cres,
			    loff_t start_pos,
			    struct iov_iter *iter,
			    bool seek_data,
			    netfs_io_terminated_t term_func,
			    void *term_func_priv);

		int (*prepare_write)(struct netfs_cache_resources *cres,
				     loff_t *_start, size_t *_len, loff_t i_size,
				     bool no_space_allocated_yet);

		int (*write)(struct netfs_cache_resources *cres,
			     loff_t start_pos,
			     struct iov_iter *iter,
			     netfs_io_terminated_t term_func,
			     void *term_func_priv);

		int (*query_occupancy)(struct netfs_cache_resources *cres,
				       loff_t start, size_t len, size_t granularity,
				       loff_t *_data_start, size_t *_data_len);
	};

With a termination handler function pointer::

	typedef void (*netfs_io_terminated_t)(void *priv,
					      ssize_t transferred_or_error,
					      bool was_async);

The methods defined in the table are:

 * ``end_operation()``

   [Required] Called to clean up the resources at the end of the read request.

 * ``expand_readahead()``

   [Optional] Called at the beginning of a netfs_readahead() operation to allow
   the cache to expand a request in either direction.  This allows the cache to
   size the request appropriately for the cache granularity.

   The function is passed poiners to the start and length in its parameters,
   plus the size of the file for reference, and adjusts the start and length
   appropriately.  It should return one of:

   * ``NETFS_FILL_WITH_ZEROES``
   * ``NETFS_DOWNLOAD_FROM_SERVER``
   * ``NETFS_READ_FROM_CACHE``
   * ``NETFS_INVALID_READ``

   to indicate whether the slice should just be cleared or whether it should be
   downloaded from the server or read from the cache - or whether slicing
   should be given up at the current point.

 * ``prepare_read()``

   [Required] Called to configure the next slice of a request.  ->start and
   ->len in the subrequest indicate where and how big the next slice can be;
   the cache gets to reduce the length to match its granularity requirements.

 * ``read()``

   [Required] Called to read from the cache.  The start file offset is given
   along with an iterator to read to, which gives the length also.  It can be
   given a hint requesting that it seek forward from that start position for
   data.

   Also provided is a pointer to a termination handler function and private
   data to pass to that function.  The termination function should be called
   with the number of bytes transferred or an error code, plus a flag
   indicating whether the termination is definitely happening in the caller's
   context.

 * ``prepare_write()``

   [Required] Called to prepare a write to the cache to take place.  This
   involves checking to see whether the cache has sufficient space to honour
   the write.  ``*_start`` and ``*_len`` indicate the region to be written; the
   region can be shrunk or it can be expanded to a page boundary either way as
   necessary to align for direct I/O.  i_size holds the size of the object and
   is provided for reference.  no_space_allocated_yet is set to true if the
   caller is certain that no data has been written to that region - for example
   if it tried to do a read from there already.

 * ``write()``

   [Required] Called to write to the cache.  The start file offset is given
   along with an iterator to write from, which gives the length also.

   Also provided is a pointer to a termination handler function and private
   data to pass to that function.  The termination function should be called
   with the number of bytes transferred or an error code, plus a flag
   indicating whether the termination is definitely happening in the caller's
   context.

 * ``query_occupancy()``

   [Required] Called to find out where the next piece of data is within a
   particular region of the cache.  The start and length of the region to be
   queried are passed in, along with the granularity to which the answer needs
   to be aligned.  The function passes back the start and length of the data,
   if any, available within that region.  Note that there may be a hole at the
   front.

   It returns 0 if some data was found, -ENODATA if there was no usable data
   within the region or -ENOBUFS if there is no caching on this file.

Note that these methods are passed a pointer to the cache resource structure,
not the read request structure as they could be used in other situations where
there isn't a read request structure as well, such as writing dirty data to the
cache.

API Function Reference
======================

.. kernel-doc:: include/linux/netfs.h
.. kernel-doc:: fs/netfs/buffered_read.c
.. kernel-doc:: fs/netfs/io.c

repo_name: angery/linux


code:
.. SPDX-License-Identifier: GPL-2.0

=======================
NFSv4 client identifier
=======================

This document explains how the NFSv4 protocol identifies client
instances in order to maintain file open and lock state during
system restarts. A special identifier and principal are maintained
on each client. These can be set by administrators, scripts
provided by site administrators, or tools provided by Linux
distributors.

There are risks if a client's NFSv4 identifier and its principal
are not chosen carefully.

Introduction
------------

The NFSv4 protocol uses "lease-based file locking". Leases help
NFSv4 servers provide file lock guarantees and manage their
resources.

Simply put, an NFSv4 server creates a lease for each NFSv4 client.
The server collects each client's file open and lock state under
the lease for that client.

The client is responsible for periodically renewing its leases.
While a lease remains valid, the server holding that lease
guarantees the file locks the client has created remain in place.

If a client stops renewing its lease (for example, if it crashes),
the NFSv4 protocol allows the server to remove the client's open
and lock state after a certain period of time. When a client
restarts, it indicates to servers that open and lock state
associated with its previous leases is no longer valid and can be
destroyed immediately.

In addition, each NFSv4 server manages a persistent list of client
leases. When the server restarts and clients attempt to recover
their state, the server uses this list to distinguish amongst
clients that held state before the server restarted and clients
sending fresh OPEN and LOCK requests. This enables file locks to
persist safely across server restarts.

NFSv4 client identifiers
------------------------

Each NFSv4 client presents an identifier to NFSv4 servers so that
they can associate the client with its lease. Each client's
identifier consists of two elements:

  - co_ownerid: An arbitrary but fixed string.

  - boot verifier: A 64-bit incarnation verifier that enables a
    server to distinguish successive boot epochs of the same client.

The NFSv4.0 specification refers to these two items as an
"nfs_client_id4". The NFSv4.1 specification refers to these two
items as a "client_owner4".

NFSv4 servers tie this identifier to the principal and security
flavor that the client used when presenting it. Servers use this
principal to authorize subsequent lease modification operations
sent by the client. Effectively this principal is a third element of
the identifier.

As part of the identity presented to servers, a good
"co_ownerid" string has several important properties:

  - The "co_ownerid" string identifies the client during reboot
    recovery, therefore the string is persistent across client
    reboots.
  - The "co_ownerid" string helps servers distinguish the client
    from others, therefore the string is globally unique. Note
    that there is no central authority that assigns "co_ownerid"
    strings.
  - Because it often appears on the network in the clear, the
    "co_ownerid" string does not reveal private information about
    the client itself.
  - The content of the "co_ownerid" string is set and unchanging
    before the client attempts NFSv4 mounts after a restart.
  - The NFSv4 protocol places a 1024-byte limit on the size of the
    "co_ownerid" string.

Protecting NFSv4 lease state
----------------------------

NFSv4 servers utilize the "client_owner4" as described above to
assign a unique lease to each client. Under this scheme, there are
circumstances where clients can interfere with each other. This is
referred to as "lease stealing".

If distinct clients present the same "co_ownerid" string and use
the same principal (for example, AUTH_SYS and UID 0), a server is
unable to tell that the clients are not the same. Each distinct
client presents a different boot verifier, so it appears to the
server as if there is one client that is rebooting frequently.
Neither client can maintain open or lock state in this scenario.

If distinct clients present the same "co_ownerid" string and use
distinct principals, the server is likely to allow the first client
to operate normally but reject subsequent clients with the same
"co_ownerid" string.

If a client's "co_ownerid" string or principal are not stable,
state recovery after a server or client reboot is not guaranteed.
If a client unexpectedly restarts but presents a different
"co_ownerid" string or principal to the server, the server orphans
the client's previous open and lock state. This blocks access to
locked files until the server removes the orphaned state.

If the server restarts and a client presents a changed "co_ownerid"
string or principal to the server, the server will not allow the
client to reclaim its open and lock state, and may give those locks
to other clients in the meantime. This is referred to as "lock
stealing".

Lease stealing and lock stealing increase the potential for denial
of service and in rare cases even data corruption.

Selecting an appropriate client identifier
------------------------------------------

By default, the Linux NFSv4 client implementation constructs its
"co_ownerid" string starting with the words "Linux NFS" followed by
the client's UTS node name (the same node name, incidentally, that
is used as the "machine name" in an AUTH_SYS credential). In small
deployments, this construction is usually adequate. Often, however,
the node name by itself is not adequately unique, and can change
unexpectedly. Problematic situations include:

  - NFS-root (diskless) clients, where the local DCHP server (or
    equivalent) does not provide a unique host name.

  - "Containers" within a single Linux host.  If each container has
    a separate network namespace, but does not use the UTS namespace
    to provide a unique host name, then there can be multiple NFS
    client instances with the same host name.

  - Clients across multiple administrative domains that access a
    common NFS server. If hostnames are not assigned centrally
    then uniqueness cannot be guaranteed unless a domain name is
    included in the hostname.

Linux provides two mechanisms to add uniqueness to its "co_ownerid"
string:

    nfs.nfs4_unique_id
      This module parameter can set an arbitrary uniquifier string
      via the kernel command line, or when the "nfs" module is
      loaded.

    /sys/fs/nfs/client/net/identifier
      This virtual file, available since Linux 5.3, is local to the
      network namespace in which it is accessed and so can provide
      distinction between network namespaces (containers) when the
      hostname remains uniform.

Note that this file is empty on name-space creation. If the
container system has access to some sort of per-container identity
then that uniquifier can be used. For example, a uniquifier might
be formed at boot using the container's internal identifier:

    sha256sum /etc/machine-id | awk '{print $1}' \\
        > /sys/fs/nfs/client/net/identifier

Security considerations
-----------------------

The use of cryptographic security for lease management operations
is strongly encouraged.

If NFS with Kerberos is not configured, a Linux NFSv4 client uses
AUTH_SYS and UID 0 as the principal part of its client identity.
This configuration is not only insecure, it increases the risk of
lease and lock stealing. However, it might be the only choice for
client configurations that have no local persistent storage.
"co_ownerid" string uniqueness and persistence is critical in this
case.

When a Kerberos keytab is present on a Linux NFS client, the client
attempts to use one of the principals in that keytab when
identifying itself to servers. The "sec=" mount option does not
control this behavior. Alternately, a single-user client with a
Kerberos principal can use that principal in place of the client's
host principal.

Using Kerberos for this purpose enables the client and server to
use the same lease for operations covered by all "sec=" settings.
Additionally, the Linux NFS client uses the RPCSEC_GSS security
flavor with Kerberos and the integrity QOS to prevent in-transit
modification of lease modification requests.

Additional notes
----------------
The Linux NFSv4 client establishes a single lease on each NFSv4
server it accesses. NFSv4 mounts from a Linux NFSv4 client of a
particular server then share that lease.

Once a client establishes open and lock state, the NFSv4 protocol
enables lease state to transition to other servers, following data
that has been migrated. This hides data migration completely from
running applications. The Linux NFSv4 client facilitates state
migration by presenting the same "client_owner4" to all servers it
encounters.

========
See Also
========

  - nfs(5)
  - kerberos(7)
  - RFC 7530 for the NFSv4.0 specification
  - RFC 8881 for the NFSv4.1 specification.


code:
:orphan:

Making Filesystems Exportable
=============================

Overview
--------

All filesystem operations require a dentry (or two) as a starting
point.  Local applications have a reference-counted hold on suitable
dentries via open file descriptors or cwd/root.  However remote
applications that access a filesystem via a remote filesystem protocol
such as NFS may not be able to hold such a reference, and so need a
different way to refer to a particular dentry.  As the alternative
form of reference needs to be stable across renames, truncates, and
server-reboot (among other things, though these tend to be the most
problematic), there is no simple answer like 'filename'.

The mechanism discussed here allows each filesystem implementation to
specify how to generate an opaque (outside of the filesystem) byte
string for any dentry, and how to find an appropriate dentry for any
given opaque byte string.
This byte string will be called a "filehandle fragment" as it
corresponds to part of an NFS filehandle.

A filesystem which supports the mapping between filehandle fragments
and dentries will be termed "exportable".

Dcache Issues
-------------

The dcache normally contains a proper prefix of any given filesystem
tree.  This means that if any filesystem object is in the dcache, then
all of the ancestors of that filesystem object are also in the dcache.
As normal access is by filename this prefix is created naturally and
maintained easily (by each object maintaining a reference count on
its parent).

However when objects are included into the dcache by interpreting a
filehandle fragment, there is no automatic creation of a path prefix
for the object.  This leads to two related but distinct features of
the dcache that are not needed for normal filesystem access.

1. The dcache must sometimes contain objects that are not part of the
   proper prefix. i.e that are not connected to the root.
2. The dcache must be prepared for a newly found (via ->lookup) directory
   to already have a (non-connected) dentry, and must be able to move
   that dentry into place (based on the parent and name in the
   ->lookup).   This is particularly needed for directories as
   it is a dcache invariant that directories only have one dentry.

To implement these features, the dcache has:

a. A dentry flag DCACHE_DISCONNECTED which is set on
   any dentry that might not be part of the proper prefix.
   This is set when anonymous dentries are created, and cleared when a
   dentry is noticed to be a child of a dentry which is in the proper
   prefix.  If the refcount on a dentry with this flag set
   becomes zero, the dentry is immediately discarded, rather than being
   kept in the dcache.  If a dentry that is not already in the dcache
   is repeatedly accessed by filehandle (as NFSD might do), an new dentry
   will be a allocated for each access, and discarded at the end of
   the access.

   Note that such a dentry can acquire children, name, ancestors, etc.
   without losing DCACHE_DISCONNECTED - that flag is only cleared when
   subtree is successfully reconnected to root.  Until then dentries
   in such subtree are retained only as long as there are references;
   refcount reaching zero means immediate eviction, same as for unhashed
   dentries.  That guarantees that we won't need to hunt them down upon
   umount.

b. A primitive for creation of secondary roots - d_obtain_root(inode).
   Those do _not_ bear DCACHE_DISCONNECTED.  They are placed on the
   per-superblock list (->s_roots), so they can be located at umount
   time for eviction purposes.

c. Helper routines to allocate anonymous dentries, and to help attach
   loose directory dentries at lookup time. They are:

    d_obtain_alias(inode) will return a dentry for the given inode.
      If the inode already has a dentry, one of those is returned.

      If it doesn't, a new anonymous (IS_ROOT and
      DCACHE_DISCONNECTED) dentry is allocated and attached.

      In the case of a directory, care is taken that only one dentry
      can ever be attached.

    d_splice_alias(inode, dentry) will introduce a new dentry into the tree;
      either the passed-in dentry or a preexisting alias for the given inode
      (such as an anonymous one created by d_obtain_alias), if appropriate.
      It returns NULL when the passed-in dentry is used, following the calling
      convention of ->lookup.

Filesystem Issues
-----------------

For a filesystem to be exportable it must:

   1. provide the filehandle fragment routines described below.
   2. make sure that d_splice_alias is used rather than d_add
      when ->lookup finds an inode for a given parent and name.

      If inode is NULL, d_splice_alias(inode, dentry) is equivalent to::

		d_add(dentry, inode), NULL

      Similarly, d_splice_alias(ERR_PTR(err), dentry) = ERR_PTR(err)

      Typically the ->lookup routine will simply end with a::

		return d_splice_alias(inode, dentry);
	}

A file system implementation declares that instances of the filesystem
are exportable by setting the s_export_op field in the struct
super_block.  This field must point to a "struct export_operations"
struct which has the following members:

 encode_fh  (optional)
    Takes a dentry and creates a filehandle fragment which can later be used
    to find or create a dentry for the same object.  The default
    implementation creates a filehandle fragment that encodes a 32bit inode
    and generation number for the inode encoded, and if necessary the
    same information for the parent.

  fh_to_dentry (mandatory)
    Given a filehandle fragment, this should find the implied object and
    create a dentry for it (possibly with d_obtain_alias).

  fh_to_parent (optional but strongly recommended)
    Given a filehandle fragment, this should find the parent of the
    implied object and create a dentry for it (possibly with
    d_obtain_alias).  May fail if the filehandle fragment is too small.

  get_parent (optional but strongly recommended)
    When given a dentry for a directory, this should return  a dentry for
    the parent.  Quite possibly the parent dentry will have been allocated
    by d_alloc_anon.  The default get_parent function just returns an error
    so any filehandle lookup that requires finding a parent will fail.
    ->lookup("..") is *not* used as a default as it can leave ".." entries
    in the dcache which are too messy to work with.

  get_name (optional)
    When given a parent dentry and a child dentry, this should find a name
    in the directory identified by the parent dentry, which leads to the
    object identified by the child dentry.  If no get_name function is
    supplied, a default implementation is provided which uses vfs_readdir
    to find potential names, and matches inode numbers to find the correct
    match.

  flags
    Some filesystems may need to be handled differently than others. The
    export_operations struct also includes a flags field that allows the
    filesystem to communicate such information to nfsd. See the Export
    Operations Flags section below for more explanation.

A filehandle fragment consists of an array of 1 or more 4byte words,
together with a one byte "type".
The decode_fh routine should not depend on the stated size that is
passed to it.  This size may be larger than the original filehandle
generated by encode_fh, in which case it will have been padded with
nuls.  Rather, the encode_fh routine should choose a "type" which
indicates the decode_fh how much of the filehandle is valid, and how
it should be interpreted.

Export Operations Flags
-----------------------
In addition to the operation vector pointers, struct export_operations also
contains a "flags" field that allows the filesystem to communicate to nfsd
that it may want to do things differently when dealing with it. The
following flags are defined:

  EXPORT_OP_NOWCC - disable NFSv3 WCC attributes on this filesystem
    RFC 1813 recommends that servers always send weak cache consistency
    (WCC) data to the client after each operation. The server should
    atomically collect attributes about the inode, do an operation on it,
    and then collect the attributes afterward. This allows the client to
    skip issuing GETATTRs in some situations but means that the server
    is calling vfs_getattr for almost all RPCs. On some filesystems
    (particularly those that are clustered or networked) this is expensive
    and atomicity is difficult to guarantee. This flag indicates to nfsd
    that it should skip providing WCC attributes to the client in NFSv3
    replies when doing operations on this filesystem. Consider enabling
    this on filesystems that have an expensive ->getattr inode operation,
    or when atomicity between pre and post operation attribute collection
    is impossible to guarantee.

  EXPORT_OP_NOSUBTREECHK - disallow subtree checking on this fs
    Many NFS operations deal with filehandles, which the server must then
    vet to ensure that they live inside of an exported tree. When the
    export consists of an entire filesystem, this is trivial. nfsd can just
    ensure that the filehandle live on the filesystem. When only part of a
    filesystem is exported however, then nfsd must walk the ancestors of the
    inode to ensure that it's within an exported subtree. This is an
    expensive operation and not all filesystems can support it properly.
    This flag exempts the filesystem from subtree checking and causes
    exportfs to get back an error if it tries to enable subtree checking
    on it.

  EXPORT_OP_CLOSE_BEFORE_UNLINK - always close cached files before unlinking
    On some exportable filesystems (such as NFS) unlinking a file that
    is still open can cause a fair bit of extra work. For instance,
    the NFS client will do a "sillyrename" to ensure that the file
    sticks around while it's still open. When reexporting, that open
    file is held by nfsd so we usually end up doing a sillyrename, and
    then immediately deleting the sillyrenamed file just afterward when
    the link count actually goes to zero. Sometimes this delete can race
    with other operations (for instance an rmdir of the parent directory).
    This flag causes nfsd to close any open files for this inode _before_
    calling into the vfs to do an unlink or a rename that would replace
    an existing file.


code:
===============================
NFS
===============================

.. toctree::
   :maxdepth: 1

   client-identifier
   exporting
   pnfs
   rpc-cache
   rpc-server-gss
   nfs41-server
   knfsd-stats
   reexport


code:
============================
Kernel NFS Server Statistics
============================

:Authors: Greg Banks <gnb@sgi.com> - 26 Mar 2009

This document describes the format and semantics of the statistics
which the kernel NFS server makes available to userspace.  These
statistics are available in several text form pseudo files, each of
which is described separately below.

In most cases you don't need to know these formats, as the nfsstat(8)
program from the nfs-utils distribution provides a helpful command-line
interface for extracting and printing them.

All the files described here are formatted as a sequence of text lines,
separated by newline '\n' characters.  Lines beginning with a hash
'#' character are comments intended for humans and should be ignored
by parsing routines.  All other lines contain a sequence of fields
separated by whitespace.

/proc/fs/nfsd/pool_stats
========================

This file is available in kernels from 2.6.30 onwards, if the
/proc/fs/nfsd filesystem is mounted (it almost always should be).

The first line is a comment which describes the fields present in
all the other lines.  The other lines present the following data as
a sequence of unsigned decimal numeric fields.  One line is shown
for each NFS thread pool.

All counters are 64 bits wide and wrap naturally.  There is no way
to zero these counters, instead applications should do their own
rate conversion.

pool
	The id number of the NFS thread pool to which this line applies.
	This number does not change.

	Thread pool ids are a contiguous set of small integers starting
	at zero.  The maximum value depends on the thread pool mode, but
	currently cannot be larger than the number of CPUs in the system.
	Note that in the default case there will be a single thread pool
	which contains all the nfsd threads and all the CPUs in the system,
	and thus this file will have a single line with a pool id of "0".

packets-arrived
	Counts how many NFS packets have arrived.  More precisely, this
	is the number of times that the network stack has notified the
	sunrpc server layer that new data may be available on a transport
	(e.g. an NFS or UDP socket or an NFS/RDMA endpoint).

	Depending on the NFS workload patterns and various network stack
	effects (such as Large Receive Offload) which can combine packets
	on the wire, this may be either more or less than the number
	of NFS calls received (which statistic is available elsewhere).
	However this is a more accurate and less workload-dependent measure
	of how much CPU load is being placed on the sunrpc server layer
	due to NFS network traffic.

sockets-enqueued
	Counts how many times an NFS transport is enqueued to wait for
	an nfsd thread to service it, i.e. no nfsd thread was considered
	available.

	The circumstance this statistic tracks indicates that there was NFS
	network-facing work to be done but it couldn't be done immediately,
	thus introducing a small delay in servicing NFS calls.  The ideal
	rate of change for this counter is zero; significantly non-zero
	values may indicate a performance limitation.

	This can happen because there are too few nfsd threads in the thread
	pool for the NFS workload (the workload is thread-limited), in which
	case configuring more nfsd threads will probably improve the
	performance of the NFS workload.

threads-woken
	Counts how many times an idle nfsd thread is woken to try to
	receive some data from an NFS transport.

	This statistic tracks the circumstance where incoming
	network-facing NFS work is being handled quickly, which is a good
	thing.  The ideal rate of change for this counter will be close
	to but less than the rate of change of the packets-arrived counter.

threads-timedout
	Counts how many times an nfsd thread triggered an idle timeout,
	i.e. was not woken to handle any incoming network packets for
	some time.

	This statistic counts a circumstance where there are more nfsd
	threads configured than can be used by the NFS workload.  This is
	a clue that the number of nfsd threads can be reduced without
	affecting performance.  Unfortunately, it's only a clue and not
	a strong indication, for a couple of reasons:

	 - Currently the rate at which the counter is incremented is quite
	   slow; the idle timeout is 60 minutes.  Unless the NFS workload
	   remains constant for hours at a time, this counter is unlikely
	   to be providing information that is still useful.

	 - It is usually a wise policy to provide some slack,
	   i.e. configure a few more nfsds than are currently needed,
	   to allow for future spikes in load.

Note that incoming packets on NFS transports will be dealt with in
one of three ways.  An nfsd thread can be woken (threads-woken counts
this case), or the transport can be enqueued for later attention
(sockets-enqueued counts this case), or the packet can be temporarily
deferred because the transport is currently being used by an nfsd
thread.  This last case is not very interesting and is not explicitly
counted, but can be inferred from the other counters thus::

	packets-deferred = packets-arrived - ( sockets-enqueued + threads-woken )

More
====

Descriptions of the other statistics file should go here.


code:
=============================
NFSv4.1 Server Implementation
=============================

Server support for minorversion 1 can be controlled using the
/proc/fs/nfsd/versions control file.  The string output returned
by reading this file will contain either "+4.1" or "-4.1"
correspondingly.

Currently, server support for minorversion 1 is enabled by default.
It can be disabled at run time by writing the string "-4.1" to
the /proc/fs/nfsd/versions control file.  Note that to write this
control file, the nfsd service must be taken down.  You can use rpc.nfsd
for this; see rpc.nfsd(8).

(Warning: older servers will interpret "+4.1" and "-4.1" as "+4" and
"-4", respectively.  Therefore, code meant to work on both new and old
kernels must turn 4.1 on or off *before* turning support for version 4
on or off; rpc.nfsd does this correctly.)

The NFSv4 minorversion 1 (NFSv4.1) implementation in nfsd is based
on RFC 5661.

From the many new features in NFSv4.1 the current implementation
focuses on the mandatory-to-implement NFSv4.1 Sessions, providing
"exactly once" semantics and better control and throttling of the
resources allocated for each client.

The table below, taken from the NFSv4.1 document, lists
the operations that are mandatory to implement (REQ), optional
(OPT), and NFSv4.0 operations that are required not to implement (MNI)
in minor version 1.  The first column indicates the operations that
are not supported yet by the linux server implementation.

The OPTIONAL features identified and their abbreviations are as follows:

- **pNFS**	Parallel NFS
- **FDELG**	File Delegations
- **DDELG**	Directory Delegations

The following abbreviations indicate the linux server implementation status.

- **I**	Implemented NFSv4.1 operations.
- **NS**	Not Supported.
- **NS\***	Unimplemented optional feature.

Operations
==========

+-----------------------+----------------------+---------------------+---------------------------+----------------+
| Implementation status | Operation            | REQ,REC, OPT or NMI | Feature (REQ, REC or OPT) | Definition     |
+=======================+======================+=====================+===========================+================+
|                       | ACCESS               | REQ                 |                           | Section 18.1   |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | BACKCHANNEL_CTL      | REQ                 |                           | Section 18.33  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | BIND_CONN_TO_SESSION | REQ                 |                           | Section 18.34  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | CLOSE                | REQ                 |                           | Section 18.2   |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | COMMIT               | REQ                 |                           | Section 18.3   |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | CREATE               | REQ                 |                           | Section 18.4   |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | CREATE_SESSION       | REQ                 |                           | Section 18.36  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| NS*                   | DELEGPURGE           | OPT                 | FDELG (REQ)               | Section 18.5   |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | DELEGRETURN          | OPT                 | FDELG,                    | Section 18.6   |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       |                      |                     | DDELG, pNFS               |                |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       |                      |                     | (REQ)                     |                |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | DESTROY_CLIENTID     | REQ                 |                           | Section 18.50  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | DESTROY_SESSION      | REQ                 |                           | Section 18.37  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | EXCHANGE_ID          | REQ                 |                           | Section 18.35  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | FREE_STATEID         | REQ                 |                           | Section 18.38  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | GETATTR              | REQ                 |                           | Section 18.7   |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | GETDEVICEINFO        | OPT                 | pNFS (REQ)                | Section 18.40  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| NS*                   | GETDEVICELIST        | OPT                 | pNFS (OPT)                | Section 18.41  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | GETFH                | REQ                 |                           | Section 18.8   |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| NS*                   | GET_DIR_DELEGATION   | OPT                 | DDELG (REQ)               | Section 18.39  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | LAYOUTCOMMIT         | OPT                 | pNFS (REQ)                | Section 18.42  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | LAYOUTGET            | OPT                 | pNFS (REQ)                | Section 18.43  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | LAYOUTRETURN         | OPT                 | pNFS (REQ)                | Section 18.44  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | LINK                 | OPT                 |                           | Section 18.9   |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | LOCK                 | REQ                 |                           | Section 18.10  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | LOCKT                | REQ                 |                           | Section 18.11  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | LOCKU                | REQ                 |                           | Section 18.12  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | LOOKUP               | REQ                 |                           | Section 18.13  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | LOOKUPP              | REQ                 |                           | Section 18.14  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | NVERIFY              | REQ                 |                           | Section 18.15  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | OPEN                 | REQ                 |                           | Section 18.16  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| NS*                   | OPENATTR             | OPT                 |                           | Section 18.17  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | OPEN_CONFIRM         | MNI                 |                           | N/A            |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | OPEN_DOWNGRADE       | REQ                 |                           | Section 18.18  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | PUTFH                | REQ                 |                           | Section 18.19  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | PUTPUBFH             | REQ                 |                           | Section 18.20  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | PUTROOTFH            | REQ                 |                           | Section 18.21  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | READ                 | REQ                 |                           | Section 18.22  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | READDIR              | REQ                 |                           | Section 18.23  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | READLINK             | OPT                 |                           | Section 18.24  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | RECLAIM_COMPLETE     | REQ                 |                           | Section 18.51  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | RELEASE_LOCKOWNER    | MNI                 |                           | N/A            |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | REMOVE               | REQ                 |                           | Section 18.25  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | RENAME               | REQ                 |                           | Section 18.26  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | RENEW                | MNI                 |                           | N/A            |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | RESTOREFH            | REQ                 |                           | Section 18.27  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | SAVEFH               | REQ                 |                           | Section 18.28  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | SECINFO              | REQ                 |                           | Section 18.29  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | SECINFO_NO_NAME      | REC                 | pNFS files                | Section 18.45, |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       |                      |                     | layout (REQ)              | Section 13.12  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | SEQUENCE             | REQ                 |                           | Section 18.46  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | SETATTR              | REQ                 |                           | Section 18.30  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | SETCLIENTID          | MNI                 |                           | N/A            |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | SETCLIENTID_CONFIRM  | MNI                 |                           | N/A            |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| NS                    | SET_SSV              | REQ                 |                           | Section 18.47  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| I                     | TEST_STATEID         | REQ                 |                           | Section 18.48  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | VERIFY               | REQ                 |                           | Section 18.31  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
| NS*                   | WANT_DELEGATION      | OPT                 | FDELG (OPT)               | Section 18.49  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+
|                       | WRITE                | REQ                 |                           | Section 18.32  |
+-----------------------+----------------------+---------------------+---------------------------+----------------+

Callback Operations
===================
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| Implementation status | Operation               | REQ,REC, OPT or NMI | Feature (REQ, REC or OPT) | Definition    |
+=======================+=========================+=====================+===========================+===============+
|                       | CB_GETATTR              | OPT                 | FDELG (REQ)               | Section 20.1  |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| I                     | CB_LAYOUTRECALL         | OPT                 | pNFS (REQ)                | Section 20.3  |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| NS*                   | CB_NOTIFY               | OPT                 | DDELG (REQ)               | Section 20.4  |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| NS*                   | CB_NOTIFY_DEVICEID      | OPT                 | pNFS (OPT)                | Section 20.12 |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| NS*                   | CB_NOTIFY_LOCK          | OPT                 |                           | Section 20.11 |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| NS*                   | CB_PUSH_DELEG           | OPT                 | FDELG (OPT)               | Section 20.5  |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       | CB_RECALL               | OPT                 | FDELG,                    | Section 20.2  |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       |                         |                     | DDELG, pNFS               |               |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       |                         |                     | (REQ)                     |               |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| NS*                   | CB_RECALL_ANY           | OPT                 | FDELG,                    | Section 20.6  |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       |                         |                     | DDELG, pNFS               |               |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       |                         |                     | (REQ)                     |               |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| NS                    | CB_RECALL_SLOT          | REQ                 |                           | Section 20.8  |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| NS*                   | CB_RECALLABLE_OBJ_AVAIL | OPT                 | DDELG, pNFS               | Section 20.7  |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       |                         |                     | (REQ)                     |               |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| I                     | CB_SEQUENCE             | OPT                 | FDELG,                    | Section 20.9  |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       |                         |                     | DDELG, pNFS               |               |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       |                         |                     | (REQ)                     |               |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
| NS*                   | CB_WANTS_CANCELLED      | OPT                 | FDELG,                    | Section 20.10 |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       |                         |                     | DDELG, pNFS               |               |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+
|                       |                         |                     | (REQ)                     |               |
+-----------------------+-------------------------+---------------------+---------------------------+---------------+

Implementation notes:
=====================

SSV:
  The spec claims this is mandatory, but we don't actually know of any
  implementations, so we're ignoring it for now.  The server returns
  NFS4ERR_ENCR_ALG_UNSUPP on EXCHANGE_ID, which should be future-proof.

GSS on the backchannel:
  Again, theoretically required but not widely implemented (in
  particular, the current Linux client doesn't request it).  We return
  NFS4ERR_ENCR_ALG_UNSUPP on CREATE_SESSION.

DELEGPURGE:
  mandatory only for servers that support CLAIM_DELEGATE_PREV and/or
  CLAIM_DELEG_PREV_FH (which allows clients to keep delegations that
  persist across client reboots).  Thus we need not implement this for
  now.

EXCHANGE_ID:
  implementation ids are ignored

CREATE_SESSION:
  backchannel attributes are ignored

SEQUENCE:
  no support for dynamic slot table renegotiation (optional)

Nonstandard compound limitations:
  No support for a sessions fore channel RPC compound that requires both a
  ca_maxrequestsize request and a ca_maxresponsesize reply, so we may
  fail to live up to the promise we made in CREATE_SESSION fore channel
  negotiation.

See also http://wiki.linux-nfs.org/wiki/index.php/Server_4.0_and_4.1_issues.


code:
==========================
Reference counting in pnfs
==========================

The are several inter-related caches.  We have layouts which can
reference multiple devices, each of which can reference multiple data servers.
Each data server can be referenced by multiple devices.  Each device
can be referenced by multiple layouts. To keep all of this straight,
we need to reference count.

struct pnfs_layout_hdr
======================

The on-the-wire command LAYOUTGET corresponds to struct
pnfs_layout_segment, usually referred to by the variable name lseg.
Each nfs_inode may hold a pointer to a cache of these layout
segments in nfsi->layout, of type struct pnfs_layout_hdr.

We reference the header for the inode pointing to it, across each
outstanding RPC call that references it (LAYOUTGET, LAYOUTRETURN,
LAYOUTCOMMIT), and for each lseg held within.

Each header is also (when non-empty) put on a list associated with
struct nfs_client (cl_layouts).  Being put on this list does not bump
the reference count, as the layout is kept around by the lseg that
keeps it in the list.

deviceid_cache
==============

lsegs reference device ids, which are resolved per nfs_client and
layout driver type.  The device ids are held in a RCU cache (struct
nfs4_deviceid_cache).  The cache itself is referenced across each
mount.  The entries (struct nfs4_deviceid) themselves are held across
the lifetime of each lseg referencing them.

RCU is used because the deviceid is basically a write once, read many
data structure.  The hlist size of 32 buckets needs better
justification, but seems reasonable given that we can have multiple
deviceid's per filesystem, and multiple filesystems per nfs_client.

The hash code is copied from the nfsd code base.  A discussion of
hashing and variations of this algorithm can be found `here.
<http://groups.google.com/group/comp.lang.c/browse_thread/thread/9522965e2b8d3809>`_

data server cache
=================

file driver devices refer to data servers, which are kept in a module
level cache.  Its reference is held over the lifetime of the deviceid
pointing to it.

lseg
====

lseg maintains an extra reference corresponding to the NFS_LSEG_VALID
bit which holds it in the pnfs_layout_hdr's list.  When the final lseg
is removed from the pnfs_layout_hdr's list, the NFS_LAYOUT_DESTROYED
bit is set, preventing any new lsegs from being added.

layout drivers
==============

PNFS utilizes what is called layout drivers. The STD defines 4 basic
layout types: "files", "objects", "blocks", and "flexfiles". For each
of these types there is a layout-driver with a common function-vectors
table which are called by the nfs-client pnfs-core to implement the
different layout types.

Files-layout-driver code is in: fs/nfs/filelayout/.. directory
Blocks-layout-driver code is in: fs/nfs/blocklayout/.. directory
Flexfiles-layout-driver code is in: fs/nfs/flexfilelayout/.. directory

blocks-layout setup
===================

TODO: Document the setup needs of the blocks layout driver