/*	$NetBSD: tmpfs.h,v 1.26 2007/02/22 06:37:00 thorpej Exp $	*/

/*-
 * Copyright (c) 2005, 2006 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Julio M. Merino Vidal, developed as part of Google's Summer of Code
 * 2005 program.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * $FreeBSD: src/sys/fs/tmpfs/tmpfs.h,v 1.18 2009/10/11 07:03:56 delphij Exp $
 */

#ifndef _VFS_TMPFS_TMPFS_H_
#define _VFS_TMPFS_TMPFS_H_

/* ---------------------------------------------------------------------
 * KERNEL-SPECIFIC DEFINITIONS
 * --------------------------------------------------------------------- */
#include <sys/dirent.h>
#include <sys/mount.h>
#include <sys/tree.h>
#include <sys/vnode.h>
#include <sys/file.h>
#include <sys/lock.h>
#include <sys/lockf.h>
#include <sys/mutex.h>

/* --------------------------------------------------------------------- */
#include <sys/malloc.h>
#ifdef _KERNEL
#include <sys/systm.h>
#endif
#include <sys/vmmeter.h>
#include <vm/swap_pager.h>

#ifdef MALLOC_DECLARE
MALLOC_DECLARE(M_TMPFSMNT);
#endif

/* --------------------------------------------------------------------- */

/*
 * Internal representation of a tmpfs directory entry.
 */
struct tmpfs_dirent {
	RB_ENTRY(tmpfs_dirent)	rb_node;
	RB_ENTRY(tmpfs_dirent)	rb_cookienode;

	/* Length of the name stored in this directory entry.  This avoids
	 * the need to recalculate it every time the name is used. */
	uint16_t		td_namelen;

	/* The name of the entry, allocated from a string pool.  This
	* string is not required to be zero-terminated; therefore, the
	* td_namelen field must always be used when accessing its value. */
	char 			*td_name;

	/* Pointer to the node this entry refers to. */
	struct tmpfs_node 	*td_node;
};

struct tmpfs_dirtree;
RB_HEAD(tmpfs_dirtree, tmpfs_dirent);
RB_PROTOTYPE(tmpfs_dirtree, tmpfs_dirent, rb_node,
	tmpfs_dirtree_compare);

RB_HEAD(tmpfs_dirtree_cookie, tmpfs_dirent);
RB_PROTOTYPE(tmpfs_dirtree_cookie, tmpfs_dirent, rb_cookienode,
	tmpfs_dirtree_cookie_compare);


/*
 * A directory in tmpfs holds a set of directory entries, which in
 * turn point to other files (which can be directories themselves).
 *
 * In tmpfs, this set is managed by a red-black tree, whose root is defined
 * by the struct tmpfs_dirtree type.
 *
 * It is important to notice that directories do not have entries for . and
 * .. as other file systems do.  These can be generated when requested
 * based on information available by other means, such as the pointer to
 * the node itself in the former case or the pointer to the parent directory
 * in the latter case.  This is done to simplify tmpfs's code and, more
 * importantly, to remove redundancy.
 *
 * Each entry in a directory has a cookie that identifies it.  Cookies
 * supersede offsets within directories because, given how tmpfs stores
 * directories in memory, there is no such thing as an offset.  (Emulating
 * a real offset could be very difficult.)
 *
 * The '.', '..' and the end of directory markers have fixed cookies which
 * cannot collide with the cookies generated by other entries.  The cookies
 * for the other entries are generated based on the memory address on which
 * stores their information is stored.
 *
 * DragonFly binaries use 64-bit cookies.  We mask-off the signed bit to
 * ensure that cookie 'offsets' are positive.
 */
#ifdef _KERNEL

#define	TMPFS_ROOTINO	((ino_t)2)

#define	TMPFS_DIRCOOKIE_DOT	0
#define	TMPFS_DIRCOOKIE_DOTDOT	1
#define	TMPFS_DIRCOOKIE_EOF	((off_t)0x7FFFFFFFFFFFFFFFLLU)

static __inline
off_t
tmpfs_dircookie(struct tmpfs_dirent *de)
{
	return ((off_t)((uintptr_t)de >> 1) & 0x7FFFFFFFFFFFFFFFLLU);
}

/*
 * WARNING!  Caller should never try to actually access a tmpfs dirent
 *	     structure from a cookiedir() conversion.  It is used strictly
 *	     for RBTREE operations.
 */
static __inline
void *
tmpfs_cookiedir(off_t off)
{
	return ((void *)((uintptr_t)off << 1));
}

#endif  /* _KERNEL */

/* --------------------------------------------------------------------- */

/*
 * Internal representation of a tmpfs file system node.
 *
 * This structure is splitted in two parts: one holds attributes common
 * to all file types and the other holds data that is only applicable to
 * a particular type.  The code must be careful to only access those
 * attributes that are actually allowed by the node's type.
 */
struct tmpfs_node {
	/* Doubly-linked list entry which links all existing nodes for a
	 * single file system.  This is provided to ease the removal of
	 * all nodes during the unmount operation. */
	LIST_ENTRY(tmpfs_node)	tn_entries;

	/* The node's type.  Any of 'VBLK', 'VCHR', 'VDIR', 'VFIFO',
	 * 'VLNK', 'VREG' and 'VSOCK' is allowed.  The usage of vnode
	 * types instead of a custom enumeration is to make things simpler
	 * and faster, as we do not need to convert between two types. */
	enum vtype		tn_type;

	/* Node identifier. */
	ino_t			tn_id;

	/* Node's internal status.  This is used by several file system
	 * operations to do modifications to the node in a delayed
	 * fashion. */
	int			tn_blksize;	/* small file optimization */
	int			tn_status;
#define	TMPFS_NODE_ACCESSED	(1 << 1)
#define	TMPFS_NODE_MODIFIED	(1 << 2)
#define	TMPFS_NODE_CHANGED	(1 << 3)

	/* The node size.  It does not necessarily match the real amount
	 * of memory consumed by it. */
	off_t			tn_size;

	/* Generic node attributes. */
	uid_t			tn_uid;
	gid_t			tn_gid;
	mode_t			tn_mode;
	u_int			tn_flags;
	nlink_t			tn_links;	/* atomic ops req */
	long			tn_atime;
	long			tn_atimensec;
	long			tn_mtime;
	long			tn_mtimensec;
	long			tn_ctime;
	long			tn_ctimensec;
	unsigned long		tn_gen;
	struct lockf		tn_advlock;

	/* As there is a single vnode for each active file within the
	 * system, care has to be taken to avoid allocating more than one
	 * vnode per file.  In order to do this, a bidirectional association
	 * is kept between vnodes and nodes.
	 *
	 * Whenever a vnode is allocated, its v_data field is updated to
	 * point to the node it references.  At the same time, the node's
	 * tn_vnode field is modified to point to the new vnode representing
	 * it.  Further attempts to allocate a vnode for this same node will
	 * result in returning a new reference to the value stored in
	 * tn_vnode.
	 *
	 * May be NULL when the node is unused (that is, no vnode has been
	 * allocated for it or it has been reclaimed). */
	struct vnode *		tn_vnode;

	/* interlock to protect structure */
	struct lock		tn_interlock;

	/*
	 * tmpfs vnode state, may specify an allocation in-progress.
	 */
	int		tn_vpstate;

	/* misc data field for different tn_type node */
	union {
		/* Valid when tn_type == VBLK || tn_type == VCHR. */
		dev_t			tn_rdev; /*int32_t ?*/

		/* Valid when tn_type == VDIR. */
		struct tn_dir {
			/*
			 * Pointer to the parent directory.  The root
			 * directory has a pointer to itself in this field;
			 * this property identifies the root node.
			 */
			struct tmpfs_node *	tn_parent;

			/*
			 * Directory entries are indexed by name and also
			 * indexed by cookie.
			 */
			struct tmpfs_dirtree		tn_dirtree;
			struct tmpfs_dirtree_cookie	tn_cookietree;
		} tn_dir;

		/* Valid when tn_type == VLNK. */
		/* The link's target, allocated from a string pool. */
		char *			tn_link;

		/*
		 * Valid when tn_type == VREG.
		 *
		 * aobj is used as backing store for the vnode object.  It
		 * typically only contains swap assignments, but we also use
		 * it to save the vnode object's vm_page's when the vnode
		 * becomes inactive.
		 */
		struct tn_reg {
			vm_object_t		tn_aobj;
			size_t			tn_aobj_pages;
			int			tn_pages_in_aobj;
		} tn_reg;

		/* Valid when tn_type = VFIFO */
		struct tn_fifo {
			int (*tn_fo_read)  (struct file *fp, struct uio *uio,
			        struct ucred *cred, int flags);
			int (*tn_fo_write) (struct file *fp, struct uio *uio,
			        struct ucred *cred, int flags);
		} tn_fifo;
	} tn_spec;
};

/* Only userspace needs this */
#define VTOI(vp)	((struct tmpfs_node *)(vp)->v_data)

#ifdef _KERNEL
LIST_HEAD(tmpfs_node_list, tmpfs_node);

#define tn_rdev tn_spec.tn_rdev
#define tn_dir tn_spec.tn_dir
#define tn_link tn_spec.tn_link
#define tn_reg tn_spec.tn_reg
#define tn_fifo tn_spec.tn_fifo

#define TMPFS_NODE_LOCK(node) lockmgr(&(node)->tn_interlock, LK_EXCLUSIVE|LK_RETRY)
#define TMPFS_NODE_LOCK_SH(node) lockmgr(&(node)->tn_interlock, LK_SHARED|LK_RETRY)
#define TMPFS_NODE_UNLOCK(node) lockmgr(&(node)->tn_interlock, LK_RELEASE)
#define TMPFS_NODE_MTX(node) (&(node)->tn_interlock)

#ifdef INVARIANTS
#define TMPFS_ASSERT_LOCKED(node) do {					\
		KKASSERT(node != NULL);					\
		KKASSERT(node->tn_vnode != NULL);			\
		if (!vn_islocked(node->tn_vnode) &&			\
		    (lockstatus(TMPFS_NODE_MTX(node), curthread) == LK_EXCLUSIVE ))		\
			panic("tmpfs: node is not locked: %p", node);	\
	} while (0)
#define TMPFS_ASSERT_ELOCKED(node) do {					\
		KKASSERT((node) != NULL);				\
		KKASSERT(lockstatus(TMPFS_NODE_MTX(node), curthread) == LK_EXCLUSIVE);		\
	} while (0)
#else
#define TMPFS_ASSERT_LOCKED(node) (void)0
#define TMPFS_ASSERT_ELOCKED(node) (void)0
#endif  /* INVARIANTS */

#define TMPFS_VNODE_DOOMED	0x0001
/* --------------------------------------------------------------------- */

/*
 * Internal representation of a tmpfs mount point.
 */
struct tmpfs_mount {
	struct mount		*tm_mount;

	/* Maximum number of memory pages available for use by the file
	 * system, set during mount time.  This variable must never be
	 * used directly as it may be bigger than the current amount of
	 * free memory; in the extreme case, it will hold the SIZE_MAX
	 * value.  Instead, use the TMPFS_PAGES_MAX macro. */
	long			tm_pages_max;

	/* Number of pages in use by the file system.  Cannot be bigger
	 * than the value returned by TMPFS_PAGES_MAX in any case. */
	long			tm_pages_used;

	/* Pointer to the node representing the root directory of this
	 * file system. */
	struct tmpfs_node *	tm_root;

	/* Maximum number of possible nodes for this file system; set
	 * during mount time.  We need a hard limit on the maximum number
	 * of nodes to avoid allocating too much of them; their objects
	 * cannot be released until the file system is unmounted.
	 * Otherwise, we could easily run out of memory by creating lots
	 * of empty files and then simply removing them. */
	ino_t			tm_nodes_max;

	/* Number of nodes currently that are in use. */
	ino_t			tm_nodes_inuse;

	/* maximum representable file size */
	u_int64_t		tm_maxfilesize;

	/* Nodes are organized in two different lists.  The used list
	 * contains all nodes that are currently used by the file system;
	 * i.e., they refer to existing files.  The available list contains
	 * all nodes that are currently available for use by new files.
	 * Nodes must be kept in this list (instead of deleting them)
	 * because we need to keep track of their generation number (tn_gen
	 * field).
	 *
	 * Note that nodes are lazily allocated: if the available list is
	 * empty and we have enough space to create more nodes, they will be
	 * created and inserted in the used list.  Once these are released,
	 * they will go into the available list, remaining alive until the
	 * file system is unmounted. */
	struct tmpfs_node_list	tm_nodes_used;

	/* Per-mount malloc zones for tmpfs nodes, names, and dirents */
	struct malloc_type	*tm_node_zone_obj;
	struct malloc_type	*tm_dirent_zone_obj;
	struct malloc_type	*tm_name_zone;

	ino_t			tm_ino;
	int			tm_flags;

	struct netexport	tm_export;

	struct mount		*tm_mnt;
};

#define TMPFS_LOCK(tm) lwkt_gettoken(&(tm)->tm_mount->mnt_token)
#define TMPFS_UNLOCK(tm) lwkt_reltoken(&(tm)->tm_mount->mnt_token)

/* --------------------------------------------------------------------- */

/*
 * This structure maps a file identifier to a tmpfs node.  Used by the
 * NFS code.
 */
struct tmpfs_fid {
	uint16_t		tf_len;
	uint16_t		tf_pad;
	ino_t			tf_id;
	unsigned long		tf_gen;
} __packed;

/* --------------------------------------------------------------------- */

/*
 * Prototypes for tmpfs_subr.c.
 */

int	tmpfs_alloc_node(struct tmpfs_mount *, enum vtype,
	    uid_t uid, gid_t gid, mode_t mode, char *, int, int,
	    struct tmpfs_node **);
void	tmpfs_free_node(struct tmpfs_mount *, struct tmpfs_node *);
int	tmpfs_alloc_dirent(struct tmpfs_mount *, struct tmpfs_node *,
	    const char *, uint16_t, struct tmpfs_dirent **);
void	tmpfs_free_dirent(struct tmpfs_mount *, struct tmpfs_dirent *);
int	tmpfs_alloc_vp(struct mount *, struct tmpfs_node *,
	    struct tmpfs_node *, int, struct vnode **);
int	tmpfs_alloc_file(struct vnode *, struct vnode **, struct vattr *,
	    struct namecache *, struct ucred *, char *);
void	tmpfs_dir_attach_locked(struct tmpfs_node *, struct tmpfs_dirent *);
void	tmpfs_dir_detach_locked(struct tmpfs_node *, struct tmpfs_dirent *);
struct tmpfs_dirent *	tmpfs_dir_lookup(struct tmpfs_node *node,
			    struct tmpfs_node *f,
			    struct namecache *ncp);
int	tmpfs_dir_getdotdent(struct tmpfs_node *, struct uio *);
int	tmpfs_dir_getdotdotdent(struct tmpfs_mount *,
			    struct tmpfs_node *, struct uio *);
struct tmpfs_dirent *	tmpfs_dir_lookupbycookie(struct tmpfs_node *, off_t,
			    int);
int	tmpfs_dir_getdents(struct tmpfs_node *, struct uio *, off_t *);
int	tmpfs_reg_resize(struct vnode *, off_t, int);
int	tmpfs_chflags(struct vnode *, u_long, struct ucred *);
int	tmpfs_chmod(struct vnode *, mode_t, struct ucred *);
int	tmpfs_chown(struct vnode *, uid_t, gid_t, struct ucred *);
int	tmpfs_chsize(struct vnode *, u_quad_t, struct ucred *);
int	tmpfs_chtimes(struct vnode *, struct timespec *, struct timespec *,
	    int, struct ucred *);
void	tmpfs_itimes(struct vnode *, const struct timespec *,
	    const struct timespec *);

void	tmpfs_node_init(struct tmpfs_node *node);
void	tmpfs_node_uninit(struct tmpfs_node *node);
void	tmpfs_update(struct vnode *);
int	tmpfs_truncate(struct vnode *, off_t);
void	tmpfs_lock4(struct tmpfs_node *node1, struct tmpfs_node *node2,
		struct tmpfs_node *node3, struct tmpfs_node *node4);
void	tmpfs_unlock4(struct tmpfs_node *node1, struct tmpfs_node *node2,
		struct tmpfs_node *node3, struct tmpfs_node *node4);

/* --------------------------------------------------------------------- */

/*
 * Convenience macros to simplify some logical expressions.
 */
#define IMPLIES(a, b) (!(a) || (b))
#define IFF(a, b) (IMPLIES(a, b) && IMPLIES(b, a))

/* --------------------------------------------------------------------- */

/*
 * Checks that the directory entry pointed by 'de' matches the name 'name'
 * with a length of 'len'.
 */
#define TMPFS_DIRENT_MATCHES(de, name, len) \
    (de->td_namelen == (uint16_t)len && \
    bcmp((de)->td_name, (name), (de)->td_namelen) == 0)

/* --------------------------------------------------------------------- */

/*
 * Ensures that the node pointed by 'node' is a directory and that its
 * contents are consistent with respect to directories.
 */
#define TMPFS_VALIDATE_DIR(node) do {	\
    KKASSERT((node)->tn_type == VDIR);	\
    KKASSERT((node)->tn_size % sizeof(struct tmpfs_dirent) == 0); \
} while(0)

/* --------------------------------------------------------------------- */

/*
 * Macros/functions to convert from generic data structures to tmpfs
 * specific ones.  Kernel code use VP_TO_TMPFS_NODE() instead of VTOI().
 */

static inline
struct tmpfs_mount *
VFS_TO_TMPFS(struct mount *mp)
{
	struct tmpfs_mount *tmp;

	KKASSERT((mp) != NULL && (mp)->mnt_data != NULL);
	tmp = (struct tmpfs_mount *)(mp)->mnt_data;
	return tmp;
}

static inline
struct tmpfs_node *
VP_TO_TMPFS_NODE(struct vnode *vp)
{
	struct tmpfs_node *node;

	KKASSERT((vp) != NULL && (vp)->v_data != NULL);
	node = (struct tmpfs_node *)vp->v_data;
	return node;
}

static inline
struct tmpfs_node *
VP_TO_TMPFS_DIR(struct vnode *vp)
{
	struct tmpfs_node *node;

	node = VP_TO_TMPFS_NODE(vp);
	TMPFS_VALIDATE_DIR(node);
	return node;
}

/* --------------------------------------------------------------------- */
/*
 * buffer cache size
 */
#define TMPFS_BLKSIZE	16384			/* buffer cache size*/
#define TMPFS_BLKMASK	(TMPFS_BLKSIZE - 1)
#define TMPFS_BLKMASK64	((off_t)(TMPFS_BLKSIZE - 1))
#endif /* _KERNEL */

#endif /* _VFS_TMPFS_TMPFS_H_ */
