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

===========================
Coda Kernel-Venus Interface
===========================

.. Note::

   This is one of the technical documents describing a component of
   Coda -- this document describes the client kernel-Venus interface.

For more information:

  http://www.coda.cs.cmu.edu

For user level software needed to run Coda:

  ftp://ftp.coda.cs.cmu.edu

To run Coda you need to get a user level cache manager for the client,
named Venus, as well as tools to manipulate ACLs, to log in, etc.  The
client needs to have the Coda filesystem selected in the kernel
configuration.

The server needs a user level server and at present does not depend on
kernel support.

  The Venus kernel interface

  Peter J. Braam

  v1.0, Nov 9, 1997

  This document describes the communication between Venus and kernel
  level filesystem code needed for the operation of the Coda file sys-
  tem.  This document version is meant to describe the current interface
  (version 1.0) as well as improvements we envisage.

.. Table of Contents

  1. Introduction

  2. Servicing Coda filesystem calls

  3. The message layer

     3.1 Implementation details

  4. The interface at the call level

     4.1 Data structures shared by the kernel and Venus
     4.2 The pioctl interface
     4.3 root
     4.4 lookup
     4.5 getattr
     4.6 setattr
     4.7 access
     4.8 create
     4.9 mkdir
     4.10 link
     4.11 symlink
     4.12 remove
     4.13 rmdir
     4.14 readlink
     4.15 open
     4.16 close
     4.17 ioctl
     4.18 rename
     4.19 readdir
     4.20 vget
     4.21 fsync
     4.22 inactive
     4.23 rdwr
     4.24 odymount
     4.25 ody_lookup
     4.26 ody_expand
     4.27 prefetch
     4.28 signal

  5. The minicache and downcalls

     5.1 INVALIDATE
     5.2 FLUSH
     5.3 PURGEUSER
     5.4 ZAPFILE
     5.5 ZAPDIR
     5.6 ZAPVNODE
     5.7 PURGEFID
     5.8 REPLACE

  6. Initialization and cleanup

     6.1 Requirements

1. Introduction
===============

  A key component in the Coda Distributed File System is the cache
  manager, Venus.

  When processes on a Coda enabled system access files in the Coda
  filesystem, requests are directed at the filesystem layer in the
  operating system. The operating system will communicate with Venus to
  service the request for the process.  Venus manages a persistent
  client cache and makes remote procedure calls to Coda file servers and
  related servers (such as authentication servers) to service these
  requests it receives from the operating system.  When Venus has
  serviced a request it replies to the operating system with appropriate
  return codes, and other data related to the request.  Optionally the
  kernel support for Coda may maintain a minicache of recently processed
  requests to limit the number of interactions with Venus.  Venus
  possesses the facility to inform the kernel when elements from its
  minicache are no longer valid.

  This document describes precisely this communication between the
  kernel and Venus.  The definitions of so called upcalls and downcalls
  will be given with the format of the data they handle. We shall also
  describe the semantic invariants resulting from the calls.

  Historically Coda was implemented in a BSD file system in Mach 2.6.
  The interface between the kernel and Venus is very similar to the BSD
  VFS interface.  Similar functionality is provided, and the format of
  the parameters and returned data is very similar to the BSD VFS.  This
  leads to an almost natural environment for implementing a kernel-level
  filesystem driver for Coda in a BSD system.  However, other operating
  systems such as Linux and Windows 95 and NT have virtual filesystem
  with different interfaces.

  To implement Coda on these systems some reverse engineering of the
  Venus/Kernel protocol is necessary.  Also it came to light that other
  systems could profit significantly from certain small optimizations
  and modifications to the protocol. To facilitate this work as well as
  to make future ports easier, communication between Venus and the
  kernel should be documented in great detail.  This is the aim of this
  document.

2.  Servicing Coda filesystem calls
===================================

  The service of a request for a Coda file system service originates in
  a process P which accessing a Coda file. It makes a system call which
  traps to the OS kernel. Examples of such calls trapping to the kernel
  are ``read``, ``write``, ``open``, ``close``, ``create``, ``mkdir``,
  ``rmdir``, ``chmod`` in a Unix ontext.  Similar calls exist in the Win32
  environment, and are named ``CreateFile``.

  Generally the operating system handles the request in a virtual
  filesystem (VFS) layer, which is named I/O Manager in NT and IFS
  manager in Windows 95.  The VFS is responsible for partial processing
  of the request and for locating the specific filesystem(s) which will
  service parts of the request.  Usually the information in the path
  assists in locating the correct FS drivers.  Sometimes after extensive
  pre-processing, the VFS starts invoking exported routines in the FS
  driver.  This is the point where the FS specific processing of the
  request starts, and here the Coda specific kernel code comes into
  play.

  The FS layer for Coda must expose and implement several interfaces.
  First and foremost the VFS must be able to make all necessary calls to
  the Coda FS layer, so the Coda FS driver must expose the VFS interface
  as applicable in the operating system. These differ very significantly
  among operating systems, but share features such as facilities to
  read/write and create and remove objects.  The Coda FS layer services
  such VFS requests by invoking one or more well defined services
  offered by the cache manager Venus.  When the replies from Venus have
  come back to the FS driver, servicing of the VFS call continues and
  finishes with a reply to the kernel's VFS. Finally the VFS layer
  returns to the process.

  As a result of this design a basic interface exposed by the FS driver
  must allow Venus to manage message traffic.  In particular Venus must
  be able to retrieve and place messages and to be notified of the
  arrival of a new message. The notification must be through a mechanism
  which does not block Venus since Venus must attend to other tasks even
  when no messages are waiting or being processed.

  **Interfaces of the Coda FS Driver**

  Furthermore the FS layer provides for a special path of communication
  between a user process and Venus, called the pioctl interface. The
  pioctl interface is used for Coda specific services, such as
  requesting detailed information about the persistent cache managed by
  Venus. Here the involvement of the kernel is minimal.  It identifies
  the calling process and passes the information on to Venus.  When
  Venus replies the response is passed back to the caller in unmodified
  form.

  Finally Venus allows the kernel FS driver to cache the results from
  certain services.  This is done to avoid excessive context switches
  and results in an efficient system.  However, Venus may acquire
  information, for example from the network which implies that cached
  information must be flushed or replaced. Venus then makes a downcall
  to the Coda FS layer to request flushes or updates in the cache.  The
  kernel FS driver handles such requests synchronously.

  Among these interfaces the VFS interface and the facility to place,
  receive and be notified of messages are platform specific.  We will
  not go into the calls exported to the VFS layer but we will state the
  requirements of the message exchange mechanism.

3.  The message layer
=====================

  At the lowest level the communication between Venus and the FS driver
  proceeds through messages.  The synchronization between processes
  requesting Coda file service and Venus relies on blocking and waking
  up processes.  The Coda FS driver processes VFS- and pioctl-requests
  on behalf of a process P, creates messages for Venus, awaits replies
  and finally returns to the caller.  The implementation of the exchange
  of messages is platform specific, but the semantics have (so far)
  appeared to be generally applicable.  Data buffers are created by the
  FS Driver in kernel memory on behalf of P and copied to user memory in
  Venus.

  The FS Driver while servicing P makes upcalls to Venus.  Such an
  upcall is dispatched to Venus by creating a message structure.  The
  structure contains the identification of P, the message sequence
  number, the size of the request and a pointer to the data in kernel
  memory for the request.  Since the data buffer is re-used to hold the
  reply from Venus, there is a field for the size of the reply.  A flags
  field is used in the message to precisely record the status of the
  message.  Additional platform dependent structures involve pointers to
  determine the position of the message on queues and pointers to
  synchronization objects.  In the upcall routine the message structure
  is filled in, flags are set to 0, and it is placed on the *pending*
  queue.  The routine calling upcall is responsible for allocating the
  data buffer; its structure will be described in the next section.

  A facility must exist to notify Venus that the message has been
  created, and implemented using available synchronization objects in
  the OS. This notification is done in the upcall context of the process
  P. When the message is on the pending queue, process P cannot proceed
  in upcall.  The (kernel mode) processing of P in the filesystem
  request routine must be suspended until Venus has replied.  Therefore
  the calling thread in P is blocked in upcall.  A pointer in the
  message structure will locate the synchronization object on which P is
  sleeping.

  Venus detects the notification that a message has arrived, and the FS
  driver allow Venus to retrieve the message with a getmsg_from_kernel
  call. This action finishes in the kernel by putting the message on the
  queue of processing messages and setting flags to READ.  Venus is
  passed the contents of the data buffer. The getmsg_from_kernel call
  now returns and Venus processes the request.

  At some later point the FS driver receives a message from Venus,
  namely when Venus calls sendmsg_to_kernel.  At this moment the Coda FS
  driver looks at the contents of the message and decides if:

  *  the message is a reply for a suspended thread P.  If so it removes
     the message from the processing queue and marks the message as
     WRITTEN.  Finally, the FS driver unblocks P (still in the kernel
     mode context of Venus) and the sendmsg_to_kernel call returns to
     Venus.  The process P will be scheduled at some point and continues
     processing its upcall with the data buffer replaced with the reply
     from Venus.

  *  The message is a ``downcall``.  A downcall is a request from Venus to
     the FS Driver. The FS driver processes the request immediately
     (usually a cache eviction or replacement) and when it finishes
     sendmsg_to_kernel returns.

  Now P awakes and continues processing upcall.  There are some
  subtleties to take account of. First P will determine if it was woken
  up in upcall by a signal from some other source (for example an
  attempt to terminate P) or as is normally the case by Venus in its
  sendmsg_to_kernel call.  In the normal case, the upcall routine will
  deallocate the message structure and return.  The FS routine can proceed
  with its processing.

  **Sleeping and IPC arrangements**

  In case P is woken up by a signal and not by Venus, it will first look
  at the flags field.  If the message is not yet READ, the process P can
  handle its signal without notifying Venus.  If Venus has READ, and
  the request should not be processed, P can send Venus a signal message
  to indicate that it should disregard the previous message.  Such
  signals are put in the queue at the head, and read first by Venus.  If
  the message is already marked as WRITTEN it is too late to stop the
  processing.  The VFS routine will now continue.  (-- If a VFS request
  involves more than one upcall, this can lead to complicated state, an
  extra field "handle_signals" could be added in the message structure
  to indicate points of no return have been passed.--)

3.1.  Implementation details
----------------------------

  The Unix implementation of this mechanism has been through the
  implementation of a character device associated with Coda.  Venus
  retrieves messages by doing a read on the device, replies are sent
  with a write and notification is through the select system call on the
  file descriptor for the device.  The process P is kept waiting on an
  interruptible wait queue object.

  In Windows NT and the DPMI Windows 95 implementation a DeviceIoControl
  call is used.  The DeviceIoControl call is designed to copy buffers
  from user memory to kernel memory with OPCODES. The sendmsg_to_kernel
  is issued as a synchronous call, while the getmsg_from_kernel call is
  asynchronous.  Windows EventObjects are used for notification of
  message arrival.  The process P is kept waiting on a KernelEvent
  object in NT and a semaphore in Windows 95.

4.  The interface at the call level
===================================

  This section describes the upcalls a Coda FS driver can make to Venus.
  Each of these upcalls make use of two structures: inputArgs and
  outputArgs.   In pseudo BNF form the structures take the following
  form::

	struct inputArgs {
	    u_long opcode;
	    u_long unique;     /* Keep multiple outstanding msgs distinct */
	    u_short pid;                 /* Common to all */
	    u_short pgid;                /* Common to all */
	    struct CodaCred cred;        /* Common to all */

	    <union "in" of call dependent parts of inputArgs>
	};

	struct outputArgs {
	    u_long opcode;
	    u_long unique;       /* Keep multiple outstanding msgs distinct */
	    u_long result;

	    <union "out" of call dependent parts of inputArgs>
	};

  Before going on let us elucidate the role of the various fields. The
  inputArgs start with the opcode which defines the type of service
  requested from Venus. There are approximately 30 upcalls at present
  which we will discuss.   The unique field labels the inputArg with a
  unique number which will identify the message uniquely.  A process and
  process group id are passed.  Finally the credentials of the caller
  are included.

  Before delving into the specific calls we need to discuss a variety of
  data structures shared by the kernel and Venus.

4.1.  Data structures shared by the kernel and Venus
----------------------------------------------------

  The CodaCred structure defines a variety of user and group ids as
  they are set for the calling process. The vuid_t and vgid_t are 32 bit
  unsigned integers.  It also defines group membership in an array.  On
  Unix the CodaCred has proven sufficient to implement good security
  semantics for Coda but the structure may have to undergo modification
  for the Windows environment when these mature::

	struct CodaCred {
	    vuid_t cr_uid, cr_euid, cr_suid, cr_fsuid; /* Real, effective, set, fs uid */
	    vgid_t cr_gid, cr_egid, cr_sgid, cr_fsgid; /* same for groups */
	    vgid_t cr_groups[NGROUPS];        /* Group membership for caller */
	};

  .. Note::

     It is questionable if we need CodaCreds in Venus. Finally Venus
     doesn't know about groups, although it does create files with the
     default uid/gid.  Perhaps the list of group membership is superfluous.

  The next item is the fundamental identifier used to identify Coda
  files, the ViceFid.  A fid of a file uniquely defines a file or
  directory in the Coda filesystem within a cell [1]_::

	typedef struct ViceFid {
	    VolumeId Volume;
	    VnodeId Vnode;
	    Unique_t Unique;
	} ViceFid;

  .. [1] A cell is agroup of Coda servers acting under the aegis of a single
	 system control machine or SCM. See the Coda Administration manual
	 for a detailed description of the role of the SCM.

  Each of the constituent fields: VolumeId, VnodeId and Unique_t are
  unsigned 32 bit integers.  We envisage that a further field will need
  to be prefixed to identify the Coda cell; this will probably take the
  form of a Ipv6 size IP address naming the Coda cell through DNS.

  The next important structure shared between Venus and the kernel is
  the attributes of the file.  The following structure is used to
  exchange information.  It has room for future extensions such as
  support for device files (currently not present in Coda)::

	struct coda_timespec {
		int64_t         tv_sec;         /* seconds */
		long            tv_nsec;        /* nanoseconds */
	};

	struct coda_vattr {
		enum coda_vtype va_type;        /* vnode type (for create) */
		u_short         va_mode;        /* files access mode and type */
		short           va_nlink;       /* number of references to file */
		vuid_t          va_uid;         /* owner user id */
		vgid_t          va_gid;         /* owner group id */
		long            va_fsid;        /* file system id (dev for now) */
		long            va_fileid;      /* file id */
		u_quad_t        va_size;        /* file size in bytes */
		long            va_blocksize;   /* blocksize preferred for i/o */
		struct coda_timespec va_atime;  /* time of last access */
		struct coda_timespec va_mtime;  /* time of last modification */
		struct coda_timespec va_ctime;  /* time file changed */
		u_long          va_gen;         /* generation number of file */
		u_long          va_flags;       /* flags defined for file */
		dev_t           va_rdev;        /* device special file represents */
		u_quad_t        va_bytes;       /* bytes of disk space held by file */
		u_quad_t        va_filerev;     /* file modification number */
		u_int           va_vaflags;     /* operations flags, see below */
		long            va_spare;       /* remain quad aligned */
	};

4.2.  The pioctl interface
--------------------------

  Coda specific requests can be made by application through the pioctl
  interface. The pioctl is implemented as an ordinary ioctl on a
  fictitious file /coda/.CONTROL.  The pioctl call opens this file, gets
  a file handle and makes the ioctl call. Finally it closes the file.

  The kernel involvement in this is limited to providing the facility to
  open and close and pass the ioctl message and to verify that a path in
  the pioctl data buffers is a file in a Coda filesystem.

  The kernel is handed a data packet of the form::

	struct {
	    const char *path;
	    struct ViceIoctl vidata;
	    int follow;
	} data;

  where::

	struct ViceIoctl {
		caddr_t in, out;        /* Data to be transferred in, or out */
		short in_size;          /* Size of input buffer <= 2K */
		short out_size;         /* Maximum size of output buffer, <= 2K */
	};

  The path must be a Coda file, otherwise the ioctl upcall will not be
  made.

  .. Note:: The data structures and code are a mess.  We need to clean this up.

**We now proceed to document the individual calls**:

4.3.  root
----------

  Arguments
     in

	empty

     out::

		struct cfs_root_out {
		    ViceFid VFid;
		} cfs_root;

  Description
    This call is made to Venus during the initialization of
    the Coda filesystem. If the result is zero, the cfs_root structure
    contains the ViceFid of the root of the Coda filesystem. If a non-zero
    result is generated, its value is a platform dependent error code
    indicating the difficulty Venus encountered in locating the root of
    the Coda filesystem.

4.4.  lookup
------------

  Summary
    Find the ViceFid and type of an object in a directory if it exists.

  Arguments
     in::

		struct  cfs_lookup_in {
		    ViceFid     VFid;
		    char        *name;          /* Place holder for data. */
		} cfs_lookup;

     out::

		struct cfs_lookup_out {
		    ViceFid VFid;
		    int vtype;
		} cfs_lookup;

  Description
    This call is made to determine the ViceFid and filetype of
    a directory entry.  The directory entry requested carries name 'name'
    and Venus will search the directory identified by cfs_lookup_in.VFid.
    The result may indicate that the name does not exist, or that
    difficulty was encountered in finding it (e.g. due to disconnection).
    If the result is zero, the field cfs_lookup_out.VFid contains the
    targets ViceFid and cfs_lookup_out.vtype the coda_vtype giving the
    type of object the name designates.

  The name of the object is an 8 bit character string of maximum length
  CFS_MAXNAMLEN, currently set to 256 (including a 0 terminator.)

  It is extremely important to realize that Venus bitwise ors the field
  cfs_lookup.vtype with CFS_NOCACHE to indicate that the object should
  not be put in the kernel name cache.

  .. Note::

     The type of the vtype is currently wrong.  It should be
     coda_vtype. Linux does not take note of CFS_NOCACHE.  It should.

4.5.  getattr
-------------

  Summary Get the attributes of a file.

  Arguments
     in::

		struct cfs_getattr_in {
		    ViceFid VFid;
		    struct coda_vattr attr; /* XXXXX */
		} cfs_getattr;

     out::

		struct cfs_getattr_out {
		    struct coda_vattr attr;
		} cfs_getattr;

  Description
    This call returns the attributes of the file identified by fid.

  Errors
    Errors can occur if the object with fid does not exist, is
    unaccessible or if the caller does not have permission to fetch
    attributes.

  .. Note::

     Many kernel FS drivers (Linux, NT and Windows 95) need to acquire
     the attributes as well as the Fid for the instantiation of an internal
     "inode" or "FileHandle".  A significant improvement in performance on
     such systems could be made by combining the lookup and getattr calls
     both at the Venus/kernel interaction level and at the RPC level.

  The vattr structure included in the input arguments is superfluous and
  should be removed.

4.6.  setattr
-------------

  Summary
    Set the attributes of a file.

  Arguments
     in::

		struct cfs_setattr_in {
		    ViceFid VFid;
		    struct coda_vattr attr;
		} cfs_setattr;

     out

	empty

  Description
    The structure attr is filled with attributes to be changed
    in BSD style.  Attributes not to be changed are set to -1, apart from
    vtype which is set to VNON. Other are set to the value to be assigned.
    The only attributes which the FS driver may request to change are the
    mode, owner, groupid, atime, mtime and ctime.  The return value
    indicates success or failure.

  Errors
    A variety of errors can occur.  The object may not exist, may
    be inaccessible, or permission may not be granted by Venus.

4.7.  access
------------

  Arguments
     in::

		struct cfs_access_in {
		    ViceFid     VFid;
		    int flags;
		} cfs_access;

     out

	empty

  Description
    Verify if access to the object identified by VFid for
    operations described by flags is permitted.  The result indicates if
    access will be granted.  It is important to remember that Coda uses
    ACLs to enforce protection and that ultimately the servers, not the
    clients enforce the security of the system.  The result of this call
    will depend on whether a token is held by the user.

  Errors
    The object may not exist, or the ACL describing the protection
    may not be accessible.

4.8.  create
------------

  Summary
    Invoked to create a file

  Arguments
     in::

		struct cfs_create_in {
		    ViceFid VFid;
		    struct coda_vattr attr;
		    int excl;
		    int mode;
		    char        *name;          /* Place holder for data. */
		} cfs_create;

     out::

		struct cfs_create_out {
		    ViceFid VFid;
		    struct coda_vattr attr;
		} cfs_create;

  Description
    This upcall is invoked to request creation of a file.
    The file will be created in the directory identified by VFid, its name
    will be name, and the mode will be mode.  If excl is set an error will
    be returned if the file already exists.  If the size field in attr is
    set to zero the file will be truncated.  The uid and gid of the file
    are set by converting the CodaCred to a uid using a macro CRTOUID
    (this macro is platform dependent).  Upon success the VFid and
    attributes of the file are returned.  The Coda FS Driver will normally
    instantiate a vnode, inode or file handle at kernel level for the new
    object.

  Errors
    A variety of errors can occur. Permissions may be insufficient.
    If the object exists and is not a file the error EISDIR is returned
    under Unix.

  .. Note::

     The packing of parameters is very inefficient and appears to
     indicate confusion between the system call creat and the VFS operation
     create. The VFS operation create is only called to create new objects.
     This create call differs from the Unix one in that it is not invoked
     to return a file descriptor. The truncate and exclusive options,
     together with the mode, could simply be part of the mode as it is
     under Unix.  There should be no flags argument; this is used in open
     (2) to return a file descriptor for READ or WRITE mode.

  The attributes of the directory should be returned too, since the size
  and mtime changed.

4.9.  mkdir
-----------

  Summary
    Create a new directory.

  Arguments
     in::

		struct cfs_mkdir_in {
		    ViceFid     VFid;
		    struct coda_vattr attr;
		    char        *name;          /* Place holder for data. */
		} cfs_mkdir;

     out::

		struct cfs_mkdir_out {
		    ViceFid VFid;
		    struct coda_vattr attr;
		} cfs_mkdir;

  Description
    This call is similar to create but creates a directory.
    Only the mode field in the input parameters is used for creation.
    Upon successful creation, the attr returned contains the attributes of
    the new directory.

  Errors
    As for create.

  .. Note::

     The input parameter should be changed to mode instead of
     attributes.

  The attributes of the parent should be returned since the size and
  mtime changes.

4.10.  link
-----------

  Summary
    Create a link to an existing file.

  Arguments
     in::

		struct cfs_link_in {
		    ViceFid sourceFid;          /* cnode to link *to* */
		    ViceFid destFid;            /* Directory in which to place link */
		    char        *tname;         /* Place holder for data. */
		} cfs_link;

     out

	empty

  Description
    This call creates a link to the sourceFid in the directory
    identified by destFid with name tname.  The source must reside in the
    target's parent, i.e. the source must be have parent destFid, i.e. Coda
    does not support cross directory hard links.  Only the return value is
    relevant.  It indicates success or the type of failure.

  Errors
    The usual errors can occur.

4.11.  symlink
--------------

  Summary
    create a symbolic link

  Arguments
     in::

		struct cfs_symlink_in {
		    ViceFid     VFid;          /* Directory to put symlink in */
		    char        *srcname;
		    struct coda_vattr attr;
		    char        *tname;
		} cfs_symlink;

     out

	none

  Description
    Create a symbolic link. The link is to be placed in the
    directory identified by VFid and named tname.  It should point to the
    pathname srcname.  The attributes of the newly created object are to
    be set to attr.

  .. Note::

     The attributes of the target directory should be returned since
     its size changed.

4.12.  remove
-------------

  Summary
    Remove a file

  Arguments
     in::

		struct cfs_remove_in {
		    ViceFid     VFid;
		    char        *name;          /* Place holder for data. */
		} cfs_remove;

     out

	none

  Description
    Remove file named cfs_remove_in.name in directory
    identified by   VFid.

  .. Note::

     The attributes of the directory should be returned since its
     mtime and size may change.

4.13.  rmdir
------------

  Summary
    Remove a directory

  Arguments
     in::

		struct cfs_rmdir_in {
		    ViceFid     VFid;
		    char        *name;          /* Place holder for data. */
		} cfs_rmdir;

     out

	none

  Description
    Remove the directory with name 'name' from the directory
    identified by VFid.

  .. Note:: The attributes of the parent directory should be returned since
	    its mtime and size may change.

4.14.  readlink
---------------

  Summary
    Read the value of a symbolic link.

  Arguments
     in::

		struct cfs_readlink_in {
		    ViceFid VFid;
		} cfs_readlink;

     out::

		struct cfs_readlink_out {
		    int count;
		    caddr_t     data;           /* Place holder for data. */
		} cfs_readlink;

  Description
    This routine reads the contents of symbolic link
    identified by VFid into the buffer data.  The buffer data must be able
    to hold any name up to CFS_MAXNAMLEN (PATH or NAM??).

  Errors
    No unusual errors.

4.15.  open
-----------

  Summary
    Open a file.

  Arguments
     in::

		struct cfs_open_in {
		    ViceFid     VFid;
		    int flags;
		} cfs_open;

     out::

		struct cfs_open_out {
		    dev_t       dev;
		    ino_t       inode;
		} cfs_open;

  Description
    This request asks Venus to place the file identified by
    VFid in its cache and to note that the calling process wishes to open
    it with flags as in open(2).  The return value to the kernel differs
    for Unix and Windows systems.  For Unix systems the Coda FS Driver is
    informed of the device and inode number of the container file in the
    fields dev and inode.  For Windows the path of the container file is
    returned to the kernel.

  .. Note::

     Currently the cfs_open_out structure is not properly adapted to
     deal with the Windows case.  It might be best to implement two
     upcalls, one to open aiming at a container file name, the other at a
     container file inode.

4.16.  close
------------

  Summary
    Close a file, update it on the servers.

  Arguments
     in::

		struct cfs_close_in {
		    ViceFid     VFid;
		    int flags;
		} cfs_close;

     out

	none

  Description
    Close the file identified by VFid.

  .. Note::

     The flags argument is bogus and not used.  However, Venus' code
     has room to deal with an execp input field, probably this field should
     be used to inform Venus that the file was closed but is still memory
     mapped for execution.  There are comments about fetching versus not
     fetching the data in Venus vproc_vfscalls.  This seems silly.  If a
     file is being closed, the data in the container file is to be the new
     data.  Here again the execp flag might be in play to create confusion:
     currently Venus might think a file can be flushed from the cache when
     it is still memory mapped.  This needs to be understood.

4.17.  ioctl
------------

  Summary
    Do an ioctl on a file. This includes the pioctl interface.

  Arguments
     in::

		struct cfs_ioctl_in {
		    ViceFid VFid;
		    int cmd;
		    int len;
		    int rwflag;
		    char *data;                 /* Place holder for data. */
		} cfs_ioctl;

     out::

		struct cfs_ioctl_out {
		    int len;
		    caddr_t     data;           /* Place holder for data. */
		} cfs_ioctl;

  Description
    Do an ioctl operation on a file.  The command, len and
    data arguments are filled as usual.  flags is not used by Venus.

  .. Note::

     Another bogus parameter.  flags is not used.  What is the
     business about PREFETCHING in the Venus code?

4.18.  rename
-------------

  Summary
    Rename a fid.

  Arguments
     in::

		struct cfs_rename_in {
		    ViceFid     sourceFid;
		    char        *srcname;
		    ViceFid destFid;
		    char        *destname;
		} cfs_rename;

     out

	none

  Description
    Rename the object with name srcname in directory
    sourceFid to destname in destFid.   It is important that the names
    srcname and destname are 0 terminated strings.  Strings in Unix
    kernels are not always null terminated.

4.19.  readdir
--------------

  Summary
    Read directory entries.

  Arguments
     in::

		struct cfs_readdir_in {
		    ViceFid     VFid;
		    int count;
		    int offset;
		} cfs_readdir;

     out::

		struct cfs_readdir_out {
		    int size;
		    caddr_t     data;           /* Place holder for data. */
		} cfs_readdir;

  Description
    Read directory entries from VFid starting at offset and
    read at most count bytes.  Returns the data in data and returns
    the size in size.

  .. Note::

     This call is not used.  Readdir operations exploit container
     files.  We will re-evaluate this during the directory revamp which is
     about to take place.

4.20.  vget
-----------

  Summary
    instructs Venus to do an FSDB->Get.

  Arguments
     in::

		struct cfs_vget_in {
		    ViceFid VFid;
		} cfs_vget;

     out::

		struct cfs_vget_out {
		    ViceFid VFid;
		    int vtype;
		} cfs_vget;

  Description
    This upcall asks Venus to do a get operation on an fsobj
    labelled by VFid.

  .. Note::

     This operation is not used.  However, it is extremely useful
     since it can be used to deal with read/write memory mapped files.
     These can be "pinned" in the Venus cache using vget and released with
     inactive.

4.21.  fsync
------------

  Summary
    Tell Venus to update the RVM attributes of a file.

  Arguments
     in::

		struct cfs_fsync_in {
		    ViceFid VFid;
		} cfs_fsync;

     out

	none

  Description
    Ask Venus to update RVM attributes of object VFid. This
    should be called as part of kernel level fsync type calls.  The
    result indicates if the syncing was successful.

  .. Note:: Linux does not implement this call. It should.

4.22.  inactive
---------------

  Summary
    Tell Venus a vnode is no longer in use.

  Arguments
     in::

		struct cfs_inactive_in {
		    ViceFid VFid;
		} cfs_inactive;

     out

	none

  Description
    This operation returns EOPNOTSUPP.

  .. Note:: This should perhaps be removed.

4.23.  rdwr
-----------

  Summary
    Read or write from a file

  Arguments
     in::

		struct cfs_rdwr_in {
		    ViceFid     VFid;
		    int rwflag;
		    int count;
		    int offset;
		    int ioflag;
		    caddr_t     data;           /* Place holder for data. */
		} cfs_rdwr;

     out::

		struct cfs_rdwr_out {
		    int rwflag;
		    int count;
		    caddr_t     data;   /* Place holder for data. */
		} cfs_rdwr;

  Description
    This upcall asks Venus to read or write from a file.

  .. Note::

    It should be removed since it is against the Coda philosophy that
    read/write operations never reach Venus.  I have been told the
    operation does not work.  It is not currently used.

4.24.  odymount
---------------

  Summary
    Allows mounting multiple Coda "filesystems" on one Unix mount point.

  Arguments
     in::

		struct ody_mount_in {
		    char        *name;          /* Place holder for data. */
		} ody_mount;

     out::

		struct ody_mount_out {
		    ViceFid VFid;
		} ody_mount;

  Description
    Asks Venus to return the rootfid of a Coda system named
    name.  The fid is returned in VFid.

  .. Note::

     This call was used by David for dynamic sets.  It should be
     removed since it causes a jungle of pointers in the VFS mounting area.
     It is not used by Coda proper.  Call is not implemented by Venus.

4.25.  ody_lookup
-----------------

  Summary
    Looks up something.

  Arguments
     in

	irrelevant

     out

	irrelevant

  .. Note:: Gut it. Call is not implemented by Venus.

4.26.  ody_expand
-----------------

  Summary
    expands something in a dynamic set.

  Arguments
     in

	irrelevant

     out

	irrelevant

  .. Note:: Gut it. Call is not implemented by Venus.

4.27.  prefetch
---------------

  Summary
    Prefetch a dynamic set.

  Arguments

     in

	Not documented.

     out

	Not documented.

  Description
    Venus worker.cc has support for this call, although it is
    noted that it doesn't work.  Not surprising, since the kernel does not
    have support for it. (ODY_PREFETCH is not a defined operation).

  .. Note:: Gut it. It isn't working and isn't used by Coda.

4.28.  signal
-------------

  Summary
    Send Venus a signal about an upcall.

  Arguments
     in

	none

     out

	not applicable.

  Description
    This is an out-of-band upcall to Venus to inform Venus
    that the calling process received a signal after Venus read the
    message from the input queue.  Venus is supposed to clean up the
    operation.

  Errors
    No reply is given.

  .. Note::

     We need to better understand what Venus needs to clean up and if
     it is doing this correctly.  Also we need to handle multiple upcall
     per system call situations correctly.  It would be important to know
     what state changes in Venus take place after an upcall for which the
     kernel is responsible for notifying Venus to clean up (e.g. open
     definitely is such a state change, but many others are maybe not).

5.  The minicache and downcalls
===============================

  The Coda FS Driver can cache results of lookup and access upcalls, to
  limit the frequency of upcalls.  Upcalls carry a price since a process
  context switch needs to take place.  The counterpart of caching the
  information is that Venus will notify the FS Driver that cached
  entries must be flushed or renamed.

  The kernel code generally has to maintain a structure which links the
  internal file handles (called vnodes in BSD, inodes in Linux and
  FileHandles in Windows) with the ViceFid's which Venus maintains.  The
  reason is that frequent translations back and forth are needed in
  order to make upcalls and use the results of upcalls.  Such linking
  objects are called cnodes.

  The current minicache implementations have cache entries which record
  the following:

  1. the name of the file

  2. the cnode of the directory containing the object

  3. a list of CodaCred's for which the lookup is permitted.

  4. the cnode of the object

  The lookup call in the Coda FS Driver may request the cnode of the
  desired object from the cache, by passing its name, directory and the
  CodaCred's of the caller.  The cache will return the cnode or indicate
  that it cannot be found.  The Coda FS Driver must be careful to
  invalidate cache entries when it modifies or removes objects.

  When Venus obtains information that indicates that cache entries are
  no longer valid, it will make a downcall to the kernel.  Downcalls are
  intercepted by the Coda FS Driver and lead to cache invalidations of
  the kind described below.  The Coda FS Driver does not return an error
  unless the downcall data could not be read into kernel memory.

5.1.  INVALIDATE
----------------

  No information is available on this call.

5.2.  FLUSH
-----------

  Arguments
    None

  Summary
    Flush the name cache entirely.

  Description
    Venus issues this call upon startup and when it dies. This
    is to prevent stale cache information being held.  Some operating
    systems allow the kernel name cache to be switched off dynamically.
    When this is done, this downcall is made.

5.3.  PURGEUSER
---------------

  Arguments
    ::

	  struct cfs_purgeuser_out {/* CFS_PURGEUSER is a venus->kernel call */
	      struct CodaCred cred;
	  } cfs_purgeuser;

  Description
    Remove all entries in the cache carrying the Cred.  This
    call is issued when tokens for a user expire or are flushed.

5.4.  ZAPFILE
-------------

  Arguments
    ::

	  struct cfs_zapfile_out {  /* CFS_ZAPFILE is a venus->kernel call */
	      ViceFid CodaFid;
	  } cfs_zapfile;

  Description
    Remove all entries which have the (dir vnode, name) pair.
    This is issued as a result of an invalidation of cached attributes of
    a vnode.

  .. Note::

     Call is not named correctly in NetBSD and Mach.  The minicache
     zapfile routine takes different arguments. Linux does not implement
     the invalidation of attributes correctly.

5.5.  ZAPDIR
------------

  Arguments
    ::

	  struct cfs_zapdir_out {   /* CFS_ZAPDIR is a venus->kernel call */
	      ViceFid CodaFid;
	  } cfs_zapdir;

  Description
    Remove all entries in the cache lying in a directory
    CodaFid, and all children of this directory. This call is issued when
    Venus receives a callback on the directory.

5.6.  ZAPVNODE
--------------

  Arguments
    ::

	  struct cfs_zapvnode_out { /* CFS_ZAPVNODE is a venus->kernel call */
	      struct CodaCred cred;
	      ViceFid VFid;
	  } cfs_zapvnode;

  Description
    Remove all entries in the cache carrying the cred and VFid
    as in the arguments. This downcall is probably never issued.

5.7.  PURGEFID
--------------

  Arguments
    ::

	  struct cfs_purgefid_out { /* CFS_PURGEFID is a venus->kernel call */
	      ViceFid CodaFid;
	  } cfs_purgefid;

  Description
    Flush the attribute for the file. If it is a dir (odd
    vnode), purge its children from the namecache and remove the file from the
    namecache.

5.8.  REPLACE
-------------

  Summary
    Replace the Fid's for a collection of names.

  Arguments
    ::

	  struct cfs_replace_out { /* cfs_replace is a venus->kernel call */
	      ViceFid NewFid;
	      ViceFid OldFid;
	  } cfs_replace;

  Description
    This routine replaces a ViceFid in the name cache with
    another.  It is added to allow Venus during reintegration to replace
    locally allocated temp fids while disconnected with global fids even
    when the reference counts on those fids are not zero.

6.  Initialization and cleanup
==============================

  This section gives brief hints as to desirable features for the Coda
  FS Driver at startup and upon shutdown or Venus failures.  Before
  entering the discussion it is useful to repeat that the Coda FS Driver
  maintains the following data:

  1. message queues

  2. cnodes

  3. name cache entries

     The name cache entries are entirely private to the driver, so they
     can easily be manipulated.   The message queues will generally have
     clear points of initialization and destruction.  The cnodes are
     much more delicate.  User processes hold reference counts in Coda
     filesystems and it can be difficult to clean up the cnodes.

  It can expect requests through:

  1. the message subsystem

  2. the VFS layer

  3. pioctl interface

     Currently the pioctl passes through the VFS for Coda so we can
     treat these similarly.

6.1.  Requirements
------------------

  The following requirements should be accommodated:

  1. The message queues should have open and close routines.  On Unix
     the opening of the character devices are such routines.

    -  Before opening, no messages can be placed.

    -  Opening will remove any old messages still pending.

    -  Close will notify any sleeping processes that their upcall cannot
       be completed.

    -  Close will free all memory allocated by the message queues.

  2. At open the namecache shall be initialized to empty state.

  3. Before the message queues are open, all VFS operations will fail.
     Fortunately this can be achieved by making sure than mounting the
     Coda filesystem cannot succeed before opening.

  4. After closing of the queues, no VFS operations can succeed.  Here
     one needs to be careful, since a few operations (lookup,
     read/write, readdir) can proceed without upcalls.  These must be
     explicitly blocked.

  5. Upon closing the namecache shall be flushed and disabled.

  6. All memory held by cnodes can be freed without relying on upcalls.

  7. Unmounting the file system can be done without relying on upcalls.

  8. Mounting the Coda filesystem should fail gracefully if Venus cannot
     get the rootfid or the attributes of the rootfid.  The latter is
     best implemented by Venus fetching these objects before attempting
     to mount.

  .. Note::

     NetBSD in particular but also Linux have not implemented the
     above requirements fully.  For smooth operation this needs to be
     corrected.


code:
=======================================================
Configfs - Userspace-driven Kernel Object Configuration
=======================================================

Joel Becker <joel.becker@oracle.com>

Updated: 31 March 2005

Copyright (c) 2005 Oracle Corporation,
	Joel Becker <joel.becker@oracle.com>

What is configfs?
=================

configfs is a ram-based filesystem that provides the converse of
sysfs's functionality.  Where sysfs is a filesystem-based view of
kernel objects, configfs is a filesystem-based manager of kernel
objects, or config_items.

With sysfs, an object is created in kernel (for example, when a device
is discovered) and it is registered with sysfs.  Its attributes then
appear in sysfs, allowing userspace to read the attributes via
readdir(3)/read(2).  It may allow some attributes to be modified via
write(2).  The important point is that the object is created and
destroyed in kernel, the kernel controls the lifecycle of the sysfs
representation, and sysfs is merely a window on all this.

A configfs config_item is created via an explicit userspace operation:
mkdir(2).  It is destroyed via rmdir(2).  The attributes appear at
mkdir(2) time, and can be read or modified via read(2) and write(2).
As with sysfs, readdir(3) queries the list of items and/or attributes.
symlink(2) can be used to group items together.  Unlike sysfs, the
lifetime of the representation is completely driven by userspace.  The
kernel modules backing the items must respond to this.

Both sysfs and configfs can and should exist together on the same
system.  One is not a replacement for the other.

Using configfs
==============

configfs can be compiled as a module or into the kernel.  You can access
it by doing::

	mount -t configfs none /config

The configfs tree will be empty unless client modules are also loaded.
These are modules that register their item types with configfs as
subsystems.  Once a client subsystem is loaded, it will appear as a
subdirectory (or more than one) under /config.  Like sysfs, the
configfs tree is always there, whether mounted on /config or not.

An item is created via mkdir(2).  The item's attributes will also
appear at this time.  readdir(3) can determine what the attributes are,
read(2) can query their default values, and write(2) can store new
values.  Don't mix more than one attribute in one attribute file.

There are two types of configfs attributes:

* Normal attributes, which similar to sysfs attributes, are small ASCII text
  files, with a maximum size of one page (PAGE_SIZE, 4096 on i386).  Preferably
  only one value per file should be used, and the same caveats from sysfs apply.
  Configfs expects write(2) to store the entire buffer at once.  When writing to
  normal configfs attributes, userspace processes should first read the entire
  file, modify the portions they wish to change, and then write the entire
  buffer back.

* Binary attributes, which are somewhat similar to sysfs binary attributes,
  but with a few slight changes to semantics.  The PAGE_SIZE limitation does not
  apply, but the whole binary item must fit in single kernel vmalloc'ed buffer.
  The write(2) calls from user space are buffered, and the attributes'
  write_bin_attribute method will be invoked on the final close, therefore it is
  imperative for user-space to check the return code of close(2) in order to
  verify that the operation finished successfully.
  To avoid a malicious user OOMing the kernel, there's a per-binary attribute
  maximum buffer value.

When an item needs to be destroyed, remove it with rmdir(2).  An
item cannot be destroyed if any other item has a link to it (via
symlink(2)).  Links can be removed via unlink(2).

Configuring FakeNBD: an Example
===============================

Imagine there's a Network Block Device (NBD) driver that allows you to
access remote block devices.  Call it FakeNBD.  FakeNBD uses configfs
for its configuration.  Obviously, there will be a nice program that
sysadmins use to configure FakeNBD, but somehow that program has to tell
the driver about it.  Here's where configfs comes in.

When the FakeNBD driver is loaded, it registers itself with configfs.
readdir(3) sees this just fine::

	# ls /config
	fakenbd

A fakenbd connection can be created with mkdir(2).  The name is
arbitrary, but likely the tool will make some use of the name.  Perhaps
it is a uuid or a disk name::

	# mkdir /config/fakenbd/disk1
	# ls /config/fakenbd/disk1
	target device rw

The target attribute contains the IP address of the server FakeNBD will
connect to.  The device attribute is the device on the server.
Predictably, the rw attribute determines whether the connection is
read-only or read-write::

	# echo 10.0.0.1 > /config/fakenbd/disk1/target
	# echo /dev/sda1 > /config/fakenbd/disk1/device
	# echo 1 > /config/fakenbd/disk1/rw

That's it.  That's all there is.  Now the device is configured, via the
shell no less.

Coding With configfs
====================

Every object in configfs is a config_item.  A config_item reflects an
object in the subsystem.  It has attributes that match values on that
object.  configfs handles the filesystem representation of that object
and its attributes, allowing the subsystem to ignore all but the
basic show/store interaction.

Items are created and destroyed inside a config_group.  A group is a
collection of items that share the same attributes and operations.
Items are created by mkdir(2) and removed by rmdir(2), but configfs
handles that.  The group has a set of operations to perform these tasks

A subsystem is the top level of a client module.  During initialization,
the client module registers the subsystem with configfs, the subsystem
appears as a directory at the top of the configfs filesystem.  A
subsystem is also a config_group, and can do everything a config_group
can.

struct config_item
==================

::

	struct config_item {
		char                    *ci_name;
		char                    ci_namebuf[UOBJ_NAME_LEN];
		struct kref             ci_kref;
		struct list_head        ci_entry;
		struct config_item      *ci_parent;
		struct config_group     *ci_group;
		struct config_item_type *ci_type;
		struct dentry           *ci_dentry;
	};

	void config_item_init(struct config_item *);
	void config_item_init_type_name(struct config_item *,
					const char *name,
					struct config_item_type *type);
	struct config_item *config_item_get(struct config_item *);
	void config_item_put(struct config_item *);

Generally, struct config_item is embedded in a container structure, a
structure that actually represents what the subsystem is doing.  The
config_item portion of that structure is how the object interacts with
configfs.

Whether statically defined in a source file or created by a parent
config_group, a config_item must have one of the _init() functions
called on it.  This initializes the reference count and sets up the
appropriate fields.

All users of a config_item should have a reference on it via
config_item_get(), and drop the reference when they are done via
config_item_put().

By itself, a config_item cannot do much more than appear in configfs.
Usually a subsystem wants the item to display and/or store attributes,
among other things.  For that, it needs a type.

struct config_item_type
=======================

::

	struct configfs_item_operations {
		void (*release)(struct config_item *);
		int (*allow_link)(struct config_item *src,
				  struct config_item *target);
		void (*drop_link)(struct config_item *src,
				 struct config_item *target);
	};

	struct config_item_type {
		struct module                           *ct_owner;
		struct configfs_item_operations         *ct_item_ops;
		struct configfs_group_operations        *ct_group_ops;
		struct configfs_attribute               **ct_attrs;
		struct configfs_bin_attribute		**ct_bin_attrs;
	};

The most basic function of a config_item_type is to define what
operations can be performed on a config_item.  All items that have been
allocated dynamically will need to provide the ct_item_ops->release()
method.  This method is called when the config_item's reference count
reaches zero.

struct configfs_attribute
=========================

::

	struct configfs_attribute {
		char                    *ca_name;
		struct module           *ca_owner;
		umode_t                  ca_mode;
		ssize_t (*show)(struct config_item *, char *);
		ssize_t (*store)(struct config_item *, const char *, size_t);
	};

When a config_item wants an attribute to appear as a file in the item's
configfs directory, it must define a configfs_attribute describing it.
It then adds the attribute to the NULL-terminated array
config_item_type->ct_attrs.  When the item appears in configfs, the
attribute file will appear with the configfs_attribute->ca_name
filename.  configfs_attribute->ca_mode specifies the file permissions.

If an attribute is readable and provides a ->show method, that method will
be called whenever userspace asks for a read(2) on the attribute.  If an
attribute is writable and provides a ->store  method, that method will be
called whenever userspace asks for a write(2) on the attribute.

struct configfs_bin_attribute
=============================

::

	struct configfs_bin_attribute {
		struct configfs_attribute	cb_attr;
		void				*cb_private;
		size_t				cb_max_size;
	};

The binary attribute is used when the one needs to use binary blob to
appear as the contents of a file in the item's configfs directory.
To do so add the binary attribute to the NULL-terminated array
config_item_type->ct_bin_attrs, and the item appears in configfs, the
attribute file will appear with the configfs_bin_attribute->cb_attr.ca_name
filename.  configfs_bin_attribute->cb_attr.ca_mode specifies the file
permissions.
The cb_private member is provided for use by the driver, while the
cb_max_size member specifies the maximum amount of vmalloc buffer
to be used.

If binary attribute is readable and the config_item provides a
ct_item_ops->read_bin_attribute() method, that method will be called
whenever userspace asks for a read(2) on the attribute.  The converse
will happen for write(2). The reads/writes are bufferred so only a
single read/write will occur; the attributes' need not concern itself
with it.

struct config_group
===================

A config_item cannot live in a vacuum.  The only way one can be created
is via mkdir(2) on a config_group.  This will trigger creation of a
child item::

	struct config_group {
		struct config_item		cg_item;
		struct list_head		cg_children;
		struct configfs_subsystem 	*cg_subsys;
		struct list_head		default_groups;
		struct list_head		group_entry;
	};

	void config_group_init(struct config_group *group);
	void config_group_init_type_name(struct config_group *group,
					 const char *name,
					 struct config_item_type *type);

The config_group structure contains a config_item.  Properly configuring
that item means that a group can behave as an item in its own right.
However, it can do more: it can create child items or groups.  This is
accomplished via the group operations specified on the group's
config_item_type::

	struct configfs_group_operations {
		struct config_item *(*make_item)(struct config_group *group,
						 const char *name);
		struct config_group *(*make_group)(struct config_group *group,
						   const char *name);
		void (*disconnect_notify)(struct config_group *group,
					  struct config_item *item);
		void (*drop_item)(struct config_group *group,
				  struct config_item *item);
	};

A group creates child items by providing the
ct_group_ops->make_item() method.  If provided, this method is called from
mkdir(2) in the group's directory.  The subsystem allocates a new
config_item (or more likely, its container structure), initializes it,
and returns it to configfs.  Configfs will then populate the filesystem
tree to reflect the new item.

If the subsystem wants the child to be a group itself, the subsystem
provides ct_group_ops->make_group().  Everything else behaves the same,
using the group _init() functions on the group.

Finally, when userspace calls rmdir(2) on the item or group,
ct_group_ops->drop_item() is called.  As a config_group is also a
config_item, it is not necessary for a separate drop_group() method.
The subsystem must config_item_put() the reference that was initialized
upon item allocation.  If a subsystem has no work to do, it may omit
the ct_group_ops->drop_item() method, and configfs will call
config_item_put() on the item on behalf of the subsystem.

Important:
   drop_item() is void, and as such cannot fail.  When rmdir(2)
   is called, configfs WILL remove the item from the filesystem tree
   (assuming that it has no children to keep it busy).  The subsystem is
   responsible for responding to this.  If the subsystem has references to
   the item in other threads, the memory is safe.  It may take some time
   for the item to actually disappear from the subsystem's usage.  But it
   is gone from configfs.

When drop_item() is called, the item's linkage has already been torn
down.  It no longer has a reference on its parent and has no place in
the item hierarchy.  If a client needs to do some cleanup before this
teardown happens, the subsystem can implement the
ct_group_ops->disconnect_notify() method.  The method is called after
configfs has removed the item from the filesystem view but before the
item is removed from its parent group.  Like drop_item(),
disconnect_notify() is void and cannot fail.  Client subsystems should
not drop any references here, as they still must do it in drop_item().

A config_group cannot be removed while it still has child items.  This
is implemented in the configfs rmdir(2) code.  ->drop_item() will not be
called, as the item has not been dropped.  rmdir(2) will fail, as the
directory is not empty.

struct configfs_subsystem
=========================

A subsystem must register itself, usually at module_init time.  This
tells configfs to make the subsystem appear in the file tree::

	struct configfs_subsystem {
		struct config_group	su_group;
		struct mutex		su_mutex;
	};

	int configfs_register_subsystem(struct configfs_subsystem *subsys);
	void configfs_unregister_subsystem(struct configfs_subsystem *subsys);

A subsystem consists of a toplevel config_group and a mutex.
The group is where child config_items are created.  For a subsystem,
this group is usually defined statically.  Before calling
configfs_register_subsystem(), the subsystem must have initialized the
group via the usual group _init() functions, and it must also have
initialized the mutex.

When the register call returns, the subsystem is live, and it
will be visible via configfs.  At that point, mkdir(2) can be called and
the subsystem must be ready for it.

An Example
==========

The best example of these basic concepts is the simple_children
subsystem/group and the simple_child item in
samples/configfs/configfs_sample.c. It shows a trivial object displaying
and storing an attribute, and a simple group creating and destroying
these children.

Hierarchy Navigation and the Subsystem Mutex
============================================

There is an extra bonus that configfs provides.  The config_groups and
config_items are arranged in a hierarchy due to the fact that they
appear in a filesystem.  A subsystem is NEVER to touch the filesystem
parts, but the subsystem might be interested in this hierarchy.  For
this reason, the hierarchy is mirrored via the config_group->cg_children
and config_item->ci_parent structure members.

A subsystem can navigate the cg_children list and the ci_parent pointer
to see the tree created by the subsystem.  This can race with configfs'
management of the hierarchy, so configfs uses the subsystem mutex to
protect modifications.  Whenever a subsystem wants to navigate the
hierarchy, it must do so under the protection of the subsystem
mutex.

A subsystem will be prevented from acquiring the mutex while a newly
allocated item has not been linked into this hierarchy.   Similarly, it
will not be able to acquire the mutex while a dropping item has not
yet been unlinked.  This means that an item's ci_parent pointer will
never be NULL while the item is in configfs, and that an item will only
be in its parent's cg_children list for the same duration.  This allows
a subsystem to trust ci_parent and cg_children while they hold the
mutex.

Item Aggregation Via symlink(2)
===============================

configfs provides a simple group via the group->item parent/child
relationship.  Often, however, a larger environment requires aggregation
outside of the parent/child connection.  This is implemented via
symlink(2).

A config_item may provide the ct_item_ops->allow_link() and
ct_item_ops->drop_link() methods.  If the ->allow_link() method exists,
symlink(2) may be called with the config_item as the source of the link.
These links are only allowed between configfs config_items.  Any
symlink(2) attempt outside the configfs filesystem will be denied.

When symlink(2) is called, the source config_item's ->allow_link()
method is called with itself and a target item.  If the source item
allows linking to target item, it returns 0.  A source item may wish to
reject a link if it only wants links to a certain type of object (say,
in its own subsystem).

When unlink(2) is called on the symbolic link, the source item is
notified via the ->drop_link() method.  Like the ->drop_item() method,
this is a void function and cannot return failure.  The subsystem is
responsible for responding to the change.

A config_item cannot be removed while it links to any other item, nor
can it be removed while an item links to it.  Dangling symlinks are not
allowed in configfs.

Automatically Created Subgroups
===============================

A new config_group may want to have two types of child config_items.
While this could be codified by magic names in ->make_item(), it is much
more explicit to have a method whereby userspace sees this divergence.

Rather than have a group where some items behave differently than
others, configfs provides a method whereby one or many subgroups are
automatically created inside the parent at its creation.  Thus,
mkdir("parent") results in "parent", "parent/subgroup1", up through
"parent/subgroupN".  Items of type 1 can now be created in
"parent/subgroup1", and items of type N can be created in
"parent/subgroupN".

These automatic subgroups, or default groups, do not preclude other
children of the parent group.  If ct_group_ops->make_group() exists,
other child groups can be created on the parent group directly.

A configfs subsystem specifies default groups by adding them using the
configfs_add_default_group() function to the parent config_group
structure.  Each added group is populated in the configfs tree at the same
time as the parent group.  Similarly, they are removed at the same time
as the parent.  No extra notification is provided.  When a ->drop_item()
method call notifies the subsystem the parent group is going away, it
also means every default group child associated with that parent group.

As a consequence of this, default groups cannot be removed directly via
rmdir(2).  They also are not considered when rmdir(2) on the parent
group is checking for children.

Dependent Subsystems
====================

Sometimes other drivers depend on particular configfs items.  For
example, ocfs2 mounts depend on a heartbeat region item.  If that
region item is removed with rmdir(2), the ocfs2 mount must BUG or go
readonly.  Not happy.

configfs provides two additional API calls: configfs_depend_item() and
configfs_undepend_item().  A client driver can call
configfs_depend_item() on an existing item to tell configfs that it is
depended on.  configfs will then return -EBUSY from rmdir(2) for that
item.  When the item is no longer depended on, the client driver calls
configfs_undepend_item() on it.

These API cannot be called underneath any configfs callbacks, as
they will conflict.  They can block and allocate.  A client driver
probably shouldn't calling them of its own gumption.  Rather it should
be providing an API that external subsystems call.

How does this work?  Imagine the ocfs2 mount process.  When it mounts,
it asks for a heartbeat region item.  This is done via a call into the
heartbeat code.  Inside the heartbeat code, the region item is looked
up.  Here, the heartbeat code calls configfs_depend_item().  If it
succeeds, then heartbeat knows the region is safe to give to ocfs2.
If it fails, it was being torn down anyway, and heartbeat can gracefully
pass up an error.

repo_name: angery/linux


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

===========================================
Cramfs - cram a filesystem onto a small ROM
===========================================

cramfs is designed to be simple and small, and to compress things well.

It uses the zlib routines to compress a file one page at a time, and
allows random page access.  The meta-data is not compressed, but is
expressed in a very terse representation to make it use much less
diskspace than traditional filesystems.

You can't write to a cramfs filesystem (making it compressible and
compact also makes it _very_ hard to update on-the-fly), so you have to
create the disk image with the "mkcramfs" utility.

Usage Notes
-----------

File sizes are limited to less than 16MB.

Maximum filesystem size is a little over 256MB.  (The last file on the
filesystem is allowed to extend past 256MB.)

Only the low 8 bits of gid are stored.  The current version of
mkcramfs simply truncates to 8 bits, which is a potential security
issue.

Hard links are supported, but hard linked files
will still have a link count of 1 in the cramfs image.

Cramfs directories have no ``.`` or ``..`` entries.  Directories (like
every other file on cramfs) always have a link count of 1.  (There's
no need to use -noleaf in ``find``, btw.)

No timestamps are stored in a cramfs, so these default to the epoch
(1970 GMT).  Recently-accessed files may have updated timestamps, but
the update lasts only as long as the inode is cached in memory, after
which the timestamp reverts to 1970, i.e. moves backwards in time.

Currently, cramfs must be written and read with architectures of the
same endianness, and can be read only by kernels with PAGE_SIZE
== 4096.  At least the latter of these is a bug, but it hasn't been
decided what the best fix is.  For the moment if you have larger pages
you can just change the #define in mkcramfs.c, so long as you don't
mind the filesystem becoming unreadable to future kernels.

Memory Mapped cramfs image
--------------------------

The CRAMFS_MTD Kconfig option adds support for loading data directly from
a physical linear memory range (usually non volatile memory like Flash)
instead of going through the block device layer. This saves some memory
since no intermediate buffering is necessary to hold the data before
decompressing.

And when data blocks are kept uncompressed and properly aligned, they will
automatically be mapped directly into user space whenever possible providing
eXecute-In-Place (XIP) from ROM of read-only segments. Data segments mapped
read-write (hence they have to be copied to RAM) may still be compressed in
the cramfs image in the same file along with non compressed read-only
segments. Both MMU and no-MMU systems are supported. This is particularly
handy for tiny embedded systems with very tight memory constraints.

The location of the cramfs image in memory is system dependent. You must
know the proper physical address where the cramfs image is located and
configure an MTD device for it. Also, that MTD device must be supported
by a map driver that implements the "point" method. Examples of such
MTD drivers are cfi_cmdset_0001 (Intel/Sharp CFI flash) or physmap
(Flash device in physical memory map). MTD partitions based on such devices
are fine too. Then that device should be specified with the "mtd:" prefix
as the mount device argument. For example, to mount the MTD device named
"fs_partition" on the /mnt directory::

    $ mount -t cramfs mtd:fs_partition /mnt

To boot a kernel with this as root filesystem, suffice to specify
something like "root=mtd:fs_partition" on the kernel command line.

Tools
-----

A version of mkcramfs that can take advantage of the latest capabilities
described above can be found here:

https://github.com/npitre/cramfs-tools

For /usr/share/magic
--------------------

=====	=======================	=======================
0	ulelong	0x28cd3d45	Linux cramfs offset 0
>4	ulelong	x		size %d
>8	ulelong	x		flags 0x%x
>12	ulelong	x		future 0x%x
>16	string	>\0		signature "%.16s"
>32	ulelong	x		fsid.crc 0x%x
>36	ulelong	x		fsid.edition %d
>40	ulelong	x		fsid.blocks %d
>44	ulelong	x		fsid.files %d
>48	string	>\0		name "%.16s"
512	ulelong	0x28cd3d45	Linux cramfs offset 512
>516	ulelong	x		size %d
>520	ulelong	x		flags 0x%x
>524	ulelong	x		future 0x%x
>528	string	>\0		signature "%.16s"
>544	ulelong	x		fsid.crc 0x%x
>548	ulelong	x		fsid.edition %d
>552	ulelong	x		fsid.blocks %d
>556	ulelong	x		fsid.files %d
>560	string	>\0		name "%.16s"
=====	=======================	=======================

Hacker Notes
------------

See fs/cramfs/README for filesystem layout and implementation notes.


code:
=======================
Direct Access for files
=======================

Motivation
----------

The page cache is usually used to buffer reads and writes to files.
It is also used to provide the pages which are mapped into userspace
by a call to mmap.

For block devices that are memory-like, the page cache pages would be
unnecessary copies of the original storage.  The `DAX` code removes the
extra copy by performing reads and writes directly to the storage device.
For file mappings, the storage device is mapped directly into userspace.

Usage
-----

If you have a block device which supports `DAX`, you can make a filesystem
on it as usual.  The `DAX` code currently only supports files with a block
size equal to your kernel's `PAGE_SIZE`, so you may need to specify a block
size when creating the filesystem.

Currently 5 filesystems support `DAX`: ext2, ext4, xfs, virtiofs and erofs.
Enabling `DAX` on them is different.

Enabling DAX on ext2 and erofs
------------------------------

When mounting the filesystem, use the ``-o dax`` option on the command line or
add 'dax' to the options in ``/etc/fstab``.  This works to enable `DAX` on all files
within the filesystem.  It is equivalent to the ``-o dax=always`` behavior below.

Enabling DAX on xfs and ext4
----------------------------

Summary
-------

 1. There exists an in-kernel file access mode flag `S_DAX` that corresponds to
    the statx flag `STATX_ATTR_DAX`.  See the manpage for statx(2) for details
    about this access mode.

 2. There exists a persistent flag `FS_XFLAG_DAX` that can be applied to regular
    files and directories. This advisory flag can be set or cleared at any
    time, but doing so does not immediately affect the `S_DAX` state.

 3. If the persistent `FS_XFLAG_DAX` flag is set on a directory, this flag will
    be inherited by all regular files and subdirectories that are subsequently
    created in this directory. Files and subdirectories that exist at the time
    this flag is set or cleared on the parent directory are not modified by
    this modification of the parent directory.

 4. There exist dax mount options which can override `FS_XFLAG_DAX` in the
    setting of the `S_DAX` flag.  Given underlying storage which supports `DAX` the
    following hold:

    ``-o dax=inode``  means "follow `FS_XFLAG_DAX`" and is the default.

    ``-o dax=never``  means "never set `S_DAX`, ignore `FS_XFLAG_DAX`."

    ``-o dax=always`` means "always set `S_DAX` ignore `FS_XFLAG_DAX`."

    ``-o dax``      is a legacy option which is an alias for ``dax=always``.

    .. warning::

      The option ``-o dax`` may be removed in the future so ``-o dax=always`` is
      the preferred method for specifying this behavior.

    .. note::

      Modifications to and the inheritance behavior of `FS_XFLAG_DAX` remain
      the same even when the filesystem is mounted with a dax option.  However,
      in-core inode state (`S_DAX`) will be overridden until the filesystem is
      remounted with dax=inode and the inode is evicted from kernel memory.

 5. The `S_DAX` policy can be changed via:

    a) Setting the parent directory `FS_XFLAG_DAX` as needed before files are
       created

    b) Setting the appropriate dax="foo" mount option

    c) Changing the `FS_XFLAG_DAX` flag on existing regular files and
       directories.  This has runtime constraints and limitations that are
       described in 6) below.

 6. When changing the `S_DAX` policy via toggling the persistent `FS_XFLAG_DAX`
    flag, the change to existing regular files won't take effect until the
    files are closed by all processes.

Details
-------

There are 2 per-file dax flags.  One is a persistent inode setting (`FS_XFLAG_DAX`)
and the other is a volatile flag indicating the active state of the feature
(`S_DAX`).

`FS_XFLAG_DAX` is preserved within the filesystem.  This persistent config
setting can be set, cleared and/or queried using the `FS_IOC_FS`[`GS`]`ETXATTR` ioctl
(see ioctl_xfs_fsgetxattr(2)) or an utility such as 'xfs_io'.

New files and directories automatically inherit `FS_XFLAG_DAX` from
their parent directory **when created**.  Therefore, setting `FS_XFLAG_DAX` at
directory creation time can be used to set a default behavior for an entire
sub-tree.

To clarify inheritance, here are 3 examples:

Example A:

.. code-block:: shell

  mkdir -p a/b/c
  xfs_io -c 'chattr +x' a
  mkdir a/b/c/d
  mkdir a/e

  ------[outcome]------

  dax: a,e
  no dax: b,c,d

Example B:

.. code-block:: shell

  mkdir a
  xfs_io -c 'chattr +x' a
  mkdir -p a/b/c/d

  ------[outcome]------

  dax: a,b,c,d
  no dax:

Example C:

.. code-block:: shell

  mkdir -p a/b/c
  xfs_io -c 'chattr +x' c
  mkdir a/b/c/d

  ------[outcome]------

  dax: c,d
  no dax: a,b

The current enabled state (`S_DAX`) is set when a file inode is instantiated in
memory by the kernel.  It is set based on the underlying media support, the
value of `FS_XFLAG_DAX` and the filesystem's dax mount option.

statx can be used to query `S_DAX`.

.. note::

  That only regular files will ever have `S_DAX` set and therefore statx
  will never indicate that `S_DAX` is set on directories.

Setting the `FS_XFLAG_DAX` flag (specifically or through inheritance) occurs even
if the underlying media does not support dax and/or the filesystem is
overridden with a mount option.

Enabling DAX on virtiofs
----------------------------
The semantic of DAX on virtiofs is basically equal to that on ext4 and xfs,
except that when '-o dax=inode' is specified, virtiofs client derives the hint
whether DAX shall be enabled or not from virtiofs server through FUSE protocol,
rather than the persistent `FS_XFLAG_DAX` flag. That is, whether DAX shall be
enabled or not is completely determined by virtiofs server, while virtiofs
server itself may deploy various algorithm making this decision, e.g. depending
on the persistent `FS_XFLAG_DAX` flag on the host.

It is still supported to set or clear persistent `FS_XFLAG_DAX` flag inside
guest, but it is not guaranteed that DAX will be enabled or disabled for
corresponding file then. Users inside guest still need to call statx(2) and
check the statx flag `STATX_ATTR_DAX` to see if DAX is enabled for this file.

Implementation Tips for Block Driver Writers
--------------------------------------------

To support `DAX` in your block driver, implement the 'direct_access'
block device operation.  It is used to translate the sector number
(expressed in units of 512-byte sectors) to a page frame number (pfn)
that identifies the physical page for the memory.  It also returns a
kernel virtual address that can be used to access the memory.

The direct_access method takes a 'size' parameter that indicates the
number of bytes being requested.  The function should return the number
of bytes that can be contiguously accessed at that offset.  It may also
return a negative errno if an error occurs.

In order to support this method, the storage must be byte-accessible by
the CPU at all times.  If your device uses paging techniques to expose
a large amount of memory through a smaller window, then you cannot
implement direct_access.  Equally, if your device can occasionally
stall the CPU for an extended period, you should also not attempt to
implement direct_access.

These block devices may be used for inspiration:
- brd: RAM backed block device driver
- dcssblk: s390 dcss block device driver
- pmem: NVDIMM persistent memory driver

Implementation Tips for Filesystem Writers
------------------------------------------

Filesystem support consists of:

* Adding support to mark inodes as being `DAX` by setting the `S_DAX` flag in
  i_flags
* Implementing ->read_iter and ->write_iter operations which use
  :c:func:`dax_iomap_rw()` when inode has `S_DAX` flag set
* Implementing an mmap file operation for `DAX` files which sets the
  `VM_MIXEDMAP` and `VM_HUGEPAGE` flags on the `VMA`, and setting the vm_ops to
  include handlers for fault, pmd_fault, page_mkwrite, pfn_mkwrite. These
  handlers should probably call :c:func:`dax_iomap_fault()` passing the
  appropriate fault size and iomap operations.
* Calling :c:func:`iomap_zero_range()` passing appropriate iomap operations
  instead of :c:func:`block_truncate_page()` for `DAX` files
* Ensuring that there is sufficient locking between reads, writes,
  truncates and page faults

The iomap handlers for allocating blocks must make sure that allocated blocks
are zeroed out and converted to written extents before being returned to avoid
exposure of uninitialized data through mmap.

These filesystems may be used for inspiration:

.. seealso::

  ext2: see Documentation/filesystems/ext2.rst

.. seealso::

  xfs:  see Documentation/admin-guide/xfs.rst

.. seealso::

  ext4: see Documentation/filesystems/ext4/

Handling Media Errors
---------------------

The libnvdimm subsystem stores a record of known media error locations for
each pmem block device (in gendisk->badblocks). If we fault at such location,
or one with a latent error not yet discovered, the application can expect
to receive a `SIGBUS`. Libnvdimm also allows clearing of these errors by simply
writing the affected sectors (through the pmem driver, and if the underlying
NVDIMM supports the clear_poison DSM defined by ACPI).

Since `DAX` IO normally doesn't go through the ``driver/bio`` path, applications or
sysadmins have an option to restore the lost data from a prior ``backup/inbuilt``
redundancy in the following ways:

1. Delete the affected file, and restore from a backup (sysadmin route):
   This will free the filesystem blocks that were being used by the file,
   and the next time they're allocated, they will be zeroed first, which
   happens through the driver, and will clear bad sectors.

2. Truncate or hole-punch the part of the file that has a bad-block (at least
   an entire aligned sector has to be hole-punched, but not necessarily an
   entire filesystem block).

These are the two basic paths that allow `DAX` filesystems to continue operating
in the presence of media errors. More robust error recovery mechanisms can be
built on top of this in the future, for example, involving redundancy/mirroring
provided at the block layer through DM, or additionally, at the filesystem
level. These would have to rely on the above two tenets, that error clearing
can happen either by sending an IO through the driver, or zeroing (also through
the driver).

Shortcomings
------------

Even if the kernel or its modules are stored on a filesystem that supports
`DAX` on a block device that supports `DAX`, they will still be copied into RAM.

The DAX code does not work correctly on architectures which have virtually
mapped caches such as ARM, MIPS and SPARC.

Calling :c:func:`get_user_pages()` on a range of user memory that has been
mmaped from a `DAX` file will fail when there are no 'struct page' to describe
those pages.  This problem has been addressed in some device drivers
by adding optional struct page support for pages under the control of
the driver (see `CONFIG_NVDIMM_PFN` in ``drivers/nvdimm`` for an example of
how to do this). In the non struct page cases `O_DIRECT` reads/writes to
those memory ranges from a non-`DAX` file will fail

.. note::

  `O_DIRECT` reads/writes _of a `DAX` file do work, it is the memory that
  is being accessed that is key here).  Other things that will not work in
  the non struct page case include RDMA, :c:func:`sendfile()` and
  :c:func:`splice()`.


code:
.. SPDX-License-Identifier: GPL-2.0
.. include:: <isonum.txt>

=======
DebugFS
=======

Copyright |copy| 2009 Jonathan Corbet <corbet@lwn.net>

Debugfs exists as a simple way for kernel developers to make information
available to user space.  Unlike /proc, which is only meant for information
about a process, or sysfs, which has strict one-value-per-file rules,
debugfs has no rules at all.  Developers can put any information they want
there.  The debugfs filesystem is also intended to not serve as a stable
ABI to user space; in theory, there are no stability constraints placed on
files exported there.  The real world is not always so simple, though [1]_;
even debugfs interfaces are best designed with the idea that they will need
to be maintained forever.

Debugfs is typically mounted with a command like::

    mount -t debugfs none /sys/kernel/debug

(Or an equivalent /etc/fstab line).
The debugfs root directory is accessible only to the root user by
default. To change access to the tree the "uid", "gid" and "mode" mount
options can be used.

Note that the debugfs API is exported GPL-only to modules.

Code using debugfs should include <linux/debugfs.h>.  Then, the first order
of business will be to create at least one directory to hold a set of
debugfs files::

    struct dentry *debugfs_create_dir(const char *name, struct dentry *parent);

This call, if successful, will make a directory called name underneath the
indicated parent directory.  If parent is NULL, the directory will be
created in the debugfs root.  On success, the return value is a struct
dentry pointer which can be used to create files in the directory (and to
clean it up at the end).  An ERR_PTR(-ERROR) return value indicates that
something went wrong.  If ERR_PTR(-ENODEV) is returned, that is an
indication that the kernel has been built without debugfs support and none
of the functions described below will work.

The most general way to create a file within a debugfs directory is with::

    struct dentry *debugfs_create_file(const char *name, umode_t mode,
				       struct dentry *parent, void *data,
				       const struct file_operations *fops);

Here, name is the name of the file to create, mode describes the access
permissions the file should have, parent indicates the directory which
should hold the file, data will be stored in the i_private field of the
resulting inode structure, and fops is a set of file operations which
implement the file's behavior.  At a minimum, the read() and/or write()
operations should be provided; others can be included as needed.  Again,
the return value will be a dentry pointer to the created file,
ERR_PTR(-ERROR) on error, or ERR_PTR(-ENODEV) if debugfs support is
missing.

Create a file with an initial size, the following function can be used
instead::

    void debugfs_create_file_size(const char *name, umode_t mode,
				  struct dentry *parent, void *data,
				  const struct file_operations *fops,
				  loff_t file_size);

file_size is the initial file size. The other parameters are the same
as the function debugfs_create_file.

In a number of cases, the creation of a set of file operations is not
actually necessary; the debugfs code provides a number of helper functions
for simple situations.  Files containing a single integer value can be
created with any of::

    void debugfs_create_u8(const char *name, umode_t mode,
			   struct dentry *parent, u8 *value);
    void debugfs_create_u16(const char *name, umode_t mode,
			    struct dentry *parent, u16 *value);
    void debugfs_create_u32(const char *name, umode_t mode,
			    struct dentry *parent, u32 *value);
    void debugfs_create_u64(const char *name, umode_t mode,
			    struct dentry *parent, u64 *value);

These files support both reading and writing the given value; if a specific
file should not be written to, simply set the mode bits accordingly.  The
values in these files are in decimal; if hexadecimal is more appropriate,
the following functions can be used instead::

    void debugfs_create_x8(const char *name, umode_t mode,
			   struct dentry *parent, u8 *value);
    void debugfs_create_x16(const char *name, umode_t mode,
			    struct dentry *parent, u16 *value);
    void debugfs_create_x32(const char *name, umode_t mode,
			    struct dentry *parent, u32 *value);
    void debugfs_create_x64(const char *name, umode_t mode,
			    struct dentry *parent, u64 *value);

These functions are useful as long as the developer knows the size of the
value to be exported.  Some types can have different widths on different
architectures, though, complicating the situation somewhat.  There are
functions meant to help out in such special cases::

    void debugfs_create_size_t(const char *name, umode_t mode,
			       struct dentry *parent, size_t *value);

As might be expected, this function will create a debugfs file to represent
a variable of type size_t.

Similarly, there are helpers for variables of type unsigned long, in decimal
and hexadecimal::

    struct dentry *debugfs_create_ulong(const char *name, umode_t mode,
					struct dentry *parent,
					unsigned long *value);
    void debugfs_create_xul(const char *name, umode_t mode,
			    struct dentry *parent, unsigned long *value);

Boolean values can be placed in debugfs with::

    void debugfs_create_bool(const char *name, umode_t mode,
                             struct dentry *parent, bool *value);

A read on the resulting file will yield either Y (for non-zero values) or
N, followed by a newline.  If written to, it will accept either upper- or
lower-case values, or 1 or 0.  Any other input will be silently ignored.

Also, atomic_t values can be placed in debugfs with::

    void debugfs_create_atomic_t(const char *name, umode_t mode,
				 struct dentry *parent, atomic_t *value)

A read of this file will get atomic_t values, and a write of this file
will set atomic_t values.

Another option is exporting a block of arbitrary binary data, with
this structure and function::

    struct debugfs_blob_wrapper {
	void *data;
	unsigned long size;
    };

    struct dentry *debugfs_create_blob(const char *name, umode_t mode,
				       struct dentry *parent,
				       struct debugfs_blob_wrapper *blob);

A read of this file will return the data pointed to by the
debugfs_blob_wrapper structure.  Some drivers use "blobs" as a simple way
to return several lines of (static) formatted text output.  This function
can be used to export binary information, but there does not appear to be
any code which does so in the mainline.  Note that all files created with
debugfs_create_blob() are read-only.

If you want to dump a block of registers (something that happens quite
often during development, even if little such code reaches mainline),
debugfs offers two functions: one to make a registers-only file, and
another to insert a register block in the middle of another sequential
file::

    struct debugfs_reg32 {
	char *name;
	unsigned long offset;
    };

    struct debugfs_regset32 {
	const struct debugfs_reg32 *regs;
	int nregs;
	void __iomem *base;
	struct device *dev;     /* Optional device for Runtime PM */
    };

    debugfs_create_regset32(const char *name, umode_t mode,
			    struct dentry *parent,
			    struct debugfs_regset32 *regset);

    void debugfs_print_regs32(struct seq_file *s, const struct debugfs_reg32 *regs,
			 int nregs, void __iomem *base, char *prefix);

The "base" argument may be 0, but you may want to build the reg32 array
using __stringify, and a number of register names (macros) are actually
byte offsets over a base for the register block.

If you want to dump a u32 array in debugfs, you can create a file with::

    struct debugfs_u32_array {
	u32 *array;
	u32 n_elements;
    };

    void debugfs_create_u32_array(const char *name, umode_t mode,
			struct dentry *parent,
			struct debugfs_u32_array *array);

The "array" argument wraps a pointer to the array's data and the number
of its elements. Note: Once array is created its size can not be changed.

There is a helper function to create a device-related seq_file::

   void debugfs_create_devm_seqfile(struct device *dev,
				const char *name,
				struct dentry *parent,
				int (*read_fn)(struct seq_file *s,
					void *data));

The "dev" argument is the device related to this debugfs file, and
the "read_fn" is a function pointer which to be called to print the
seq_file content.

There are a couple of other directory-oriented helper functions::

    struct dentry *debugfs_rename(struct dentry *old_dir,
    				  struct dentry *old_dentry,
		                  struct dentry *new_dir,
				  const char *new_name);

    struct dentry *debugfs_create_symlink(const char *name,
                                          struct dentry *parent,
				      	  const char *target);

A call to debugfs_rename() will give a new name to an existing debugfs
file, possibly in a different directory.  The new_name must not exist prior
to the call; the return value is old_dentry with updated information.
Symbolic links can be created with debugfs_create_symlink().

There is one important thing that all debugfs users must take into account:
there is no automatic cleanup of any directories created in debugfs.  If a
module is unloaded without explicitly removing debugfs entries, the result
will be a lot of stale pointers and no end of highly antisocial behavior.
So all debugfs users - at least those which can be built as modules - must
be prepared to remove all files and directories they create there.  A file
can be removed with::

    void debugfs_remove(struct dentry *dentry);

The dentry value can be NULL or an error value, in which case nothing will
be removed.

Once upon a time, debugfs users were required to remember the dentry
pointer for every debugfs file they created so that all files could be
cleaned up.  We live in more civilized times now, though, and debugfs users
can call::

    void debugfs_remove_recursive(struct dentry *dentry);

If this function is passed a pointer for the dentry corresponding to the
top-level directory, the entire hierarchy below that directory will be
removed.

.. [1] http://lwn.net/Articles/309298/


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

=====================
The Devpts Filesystem
=====================

Each mount of the devpts filesystem is now distinct such that ptys
and their indicies allocated in one mount are independent from ptys
and their indicies in all other mounts.

All mounts of the devpts filesystem now create a ``/dev/pts/ptmx`` node
with permissions ``0000``.

To retain backwards compatibility the a ptmx device node (aka any node
created with ``mknod name c 5 2``) when opened will look for an instance
of devpts under the name ``pts`` in the same directory as the ptmx device
node.

As an option instead of placing a ``/dev/ptmx`` device node at ``/dev/ptmx``
it is possible to place a symlink to ``/dev/pts/ptmx`` at ``/dev/ptmx`` or
to bind mount ``/dev/ptx/ptmx`` to ``/dev/ptmx``.  If you opt for using
the devpts filesystem in this manner devpts should be mounted with
the ``ptmxmode=0666``, or ``chmod 0666 /dev/pts/ptmx`` should be called.

Total count of pty pairs in all instances is limited by sysctls::

    kernel.pty.max = 4096	- global limit
    kernel.pty.reserve = 1024	- reserved for filesystems mounted from the initial mount namespace
    kernel.pty.nr		- current count of ptys

Per-instance limit could be set by adding mount option ``max=<count>``.

This feature was added in kernel 3.4 together with
``sysctl kernel.pty.reserve``.

In kernels older than 3.4 sysctl ``kernel.pty.max`` works as per-instance limit.


code:
=================
Directory Locking
=================

Locking scheme used for directory operations is based on two
kinds of locks - per-inode (->i_rwsem) and per-filesystem
(->s_vfs_rename_mutex).

When taking the i_rwsem on multiple non-directory objects, we
always acquire the locks in order by increasing address.  We'll call
that "inode pointer" order in the following.

For our purposes all operations fall in 5 classes:

1) read access.  Locking rules: caller locks directory we are accessing.
The lock is taken shared.

2) object creation.  Locking rules: same as above, but the lock is taken
exclusive.

3) object removal.  Locking rules: caller locks parent, finds victim,
locks victim and calls the method.  Locks are exclusive.

4) rename() that is _not_ cross-directory.  Locking rules: caller locks
the parent and finds source and target.  In case of exchange (with
RENAME_EXCHANGE in flags argument) lock both.  In any case,
if the target already exists, lock it.  If the source is a non-directory,
lock it.  If we need to lock both, lock them in inode pointer order.
Then call the method.  All locks are exclusive.
NB: we might get away with locking the source (and target in exchange
case) shared.

5) link creation.  Locking rules:

	* lock parent
	* check that source is not a directory
	* lock source
	* call the method.

All locks are exclusive.

6) cross-directory rename.  The trickiest in the whole bunch.  Locking
rules:

	* lock the filesystem
	* lock parents in "ancestors first" order.
	* find source and target.
	* if old parent is equal to or is a descendent of target
	  fail with -ENOTEMPTY
	* if new parent is equal to or is a descendent of source
	  fail with -ELOOP
	* If it's an exchange, lock both the source and the target.
	* If the target exists, lock it.  If the source is a non-directory,
	  lock it.  If we need to lock both, do so in inode pointer order.
	* call the method.

All ->i_rwsem are taken exclusive.  Again, we might get away with locking
the source (and target in exchange case) shared.

The rules above obviously guarantee that all directories that are going to be
read, modified or removed by method will be locked by caller.

If no directory is its own ancestor, the scheme above is deadlock-free.

Proof:

	First of all, at any moment we have a partial ordering of the
	objects - A < B iff A is an ancestor of B.

	That ordering can change.  However, the following is true:

(1) if object removal or non-cross-directory rename holds lock on A and
    attempts to acquire lock on B, A will remain the parent of B until we
    acquire the lock on B.  (Proof: only cross-directory rename can change
    the parent of object and it would have to lock the parent).

(2) if cross-directory rename holds the lock on filesystem, order will not
    change until rename acquires all locks.  (Proof: other cross-directory
    renames will be blocked on filesystem lock and we don't start changing
    the order until we had acquired all locks).

(3) locks on non-directory objects are acquired only after locks on
    directory objects, and are acquired in inode pointer order.
    (Proof: all operations but renames take lock on at most one
    non-directory object, except renames, which take locks on source and
    target in inode pointer order in the case they are not directories.)

Now consider the minimal deadlock.  Each process is blocked on
attempt to acquire some lock and already holds at least one lock.  Let's
consider the set of contended locks.  First of all, filesystem lock is
not contended, since any process blocked on it is not holding any locks.
Thus all processes are blocked on ->i_rwsem.

By (3), any process holding a non-directory lock can only be
waiting on another non-directory lock with a larger address.  Therefore
the process holding the "largest" such lock can always make progress, and
non-directory objects are not included in the set of contended locks.

Thus link creation can't be a part of deadlock - it can't be
blocked on source and it means that it doesn't hold any locks.

Any contended object is either held by cross-directory rename or
has a child that is also contended.  Indeed, suppose that it is held by
operation other than cross-directory rename.  Then the lock this operation
is blocked on belongs to child of that object due to (1).

It means that one of the operations is cross-directory rename.
Otherwise the set of contended objects would be infinite - each of them
would have a contended child and we had assumed that no object is its
own descendent.  Moreover, there is exactly one cross-directory rename
(see above).

Consider the object blocking the cross-directory rename.  One
of its descendents is locked by cross-directory rename (otherwise we
would again have an infinite set of contended objects).  But that
means that cross-directory rename is taking locks out of order.  Due
to (2) the order hadn't changed since we had acquired filesystem lock.
But locking rules for cross-directory rename guarantee that we do not
try to acquire lock on descendent before the lock on ancestor.
Contradiction.  I.e.  deadlock is impossible.  Q.E.D.

These operations are guaranteed to avoid loop creation.  Indeed,
the only operation that could introduce loops is cross-directory rename.
Since the only new (parent, child) pair added by rename() is (new parent,
source), such loop would have to contain these objects and the rest of it
would have to exist before rename().  I.e. at the moment of loop creation
rename() responsible for that would be holding filesystem lock and new parent
would have to be equal to or a descendent of source.  But that means that
new parent had been equal to or a descendent of source since the moment when
we had acquired filesystem lock and rename() would fail with -ELOOP in that
case.

While this locking scheme works for arbitrary DAGs, it relies on
ability to check that directory is a descendent of another object.  Current
implementation assumes that directory graph is a tree.  This assumption is
also preserved by all operations (cross-directory rename on a tree that would
not introduce a cycle will leave it a tree and link() fails for directories).

Notice that "directory" in the above == "anything that might have
children", so if we are going to introduce hybrid objects we will need
either to make sure that link(2) doesn't work for them or to make changes
in is_subdir() that would make it work even in presence of such beasts.