/*
 * Copyright (c) 1989, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Rick Macklem at The University of Guelph.
 *
 * 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.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
 *
 *	@(#)nfs_vnops.c	8.16 (Berkeley) 5/27/95
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD: src/sys/nfsclient/nfs_vnops.c,v 1.218 2004/04/07 04:59:57 imp Exp $");

/*
 * vnode op calls for Sun NFS version 2 and 3
 */

#include "opt_inet.h"

#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/resourcevar.h>
#include <sys/proc.h>
#include <sys/mount.h>
#include <sys/bio.h>
#include <sys/buf.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/namei.h>
#include <sys/socket.h>
#include <sys/vnode.h>
#include <sys/dirent.h>
#include <sys/fcntl.h>
#include <sys/lockf.h>
#include <sys/stat.h>
#include <sys/sysctl.h>

#include <vm/vm.h>
#include <vm/vm_extern.h>

#include <fs/fifofs/fifo.h>

#include <rpcx/rpcclnt.h>

#include <nfsx/rpcv2.h>
#include <nfsx/nfsproto.h>

#include <nfsxclient/nfs.h>
#include <nfsxclient/nfsnode.h>
#include <nfsxclient/nfsmount.h>
#include <nfsxclient/nfs_lock.h>
#include <nfsx/xdr_subs.h>
#include <nfsxclient/nfsm_subs.h>

#include <nfsx/nfs_socket.h>

#include <net/if.h>
#include <netinet/in.h>
#include <netinet/in_var.h>

/* Defs */
#define	TRUE	1
#define	FALSE	0

/*
 * Ifdef for FreeBSD-current merged buffer cache. It is unfortunate that these
 * calls are not in getblk() and brelse() so that they would not be necessary
 * here.
 */
#ifndef B_VMIO
#define vfs_busy_pages(bp, f)
#endif

int	nfsx_fsync(struct vop_fsync_args *);
int	nfsx_close(struct vop_close_args *);
int	nfsx_lookup(struct vop_lookup_args *);
int	nfsx_mknod(struct vop_mknod_args *);
int	nfsx_print(struct vop_print_args *);
int	nfsx_read(struct vop_read_args *);
int	nfsx_readdir(struct vop_readdir_args *);
int	nfsx_readlink(struct vop_readlink_args *);
int	nfsx_rename(struct vop_rename_args *);
int	nfsx_setattr(struct vop_setattr_args *);
int	nfsx_lookitup(struct vnode *, const char *, int,
            struct ucred *, struct thread *, struct nfsnode **);
int	nfsx_sillyrename(struct vnode *, struct vnode *,
            struct componentname *);
int	nfsx_remove(struct vop_remove_args *);
int	nfsx_renameit(struct vnode *sdvp, struct componentname *scnp,
            struct sillyrename *sp);
int	nfsx_strategy(struct vop_strategy_args *);
int	nfsx_advlock(struct vop_advlock_args *);

static int      nfsx_removeit(struct sillyrename *);
static int	nfsx_flush(struct vnode *, struct ucred *, int, struct thread *,
		    int);

/*
 * Global variables
 */
struct proc	*nfsx_iodwant[NFS_MAXASYNCDAEMON];
struct nfsmount *nfsx_iodmount[NFS_MAXASYNCDAEMON];
int		 nfsx_numasync = 0;
#define	DIRHDSIZ	(sizeof (struct dirent) - (MAXNAMLEN + 1))

SYSCTL_DECL(_vfs_nfsx);

static int	nfsaccess_cache_timeout = NFS_MAXATTRTIMO;
SYSCTL_INT(_vfs_nfsx, OID_AUTO, access_cache_timeout, CTLFLAG_RW,
	   &nfsaccess_cache_timeout, 0, "NFS ACCESS cache timeout");

static int	nfsv3_commit_on_close = 0;
SYSCTL_INT(_vfs_nfsx, OID_AUTO, nfsv3_commit_on_close, CTLFLAG_RW,
	   &nfsv3_commit_on_close, 0, "write+commit on close, else only write");
#if 0
SYSCTL_INT(_vfs_nfsx, OID_AUTO, access_cache_hits, CTLFLAG_RD,
	   &nfsstats.accesscache_hits, 0, "NFS ACCESS cache hit count");

SYSCTL_INT(_vfs_nfsx, OID_AUTO, access_cache_misses, CTLFLAG_RD,
	   &nfsstats.accesscache_misses, 0, "NFS ACCESS cache miss count");
#endif

#define	NFSV3ACCESS_ALL (NFSV3ACCESS_READ | NFSV3ACCESS_MODIFY		\
			 | NFSV3ACCESS_EXTEND | NFSV3ACCESS_EXECUTE	\
			 | NFSV3ACCESS_DELETE | NFSV3ACCESS_LOOKUP)
/*
 * nfs close vnode op
 * What an NFS client should do upon close after writing is a debatable issue.
 * Most NFS clients push delayed writes to the server upon close, basically for
 * two reasons:
 * 1 - So that any write errors may be reported back to the client process
 *     doing the close system call. By far the two most likely errors are
 *     NFSERR_NOSPC and NFSERR_DQUOT to indicate space allocation failure.
 * 2 - To put a worst case upper bound on cache inconsistency between
 *     multiple clients for the file.
 * There is also a consistency problem for Version 2 of the protocol w.r.t.
 * not being able to tell if other clients are writing a file concurrently,
 * since there is no way of knowing if the changed modify time in the reply
 * is only due to the write for this client.
 * (NFS Version 3 provides weak cache consistency data in the reply that
 *  should be sufficient to detect and handle this case.)
 *
 * The current code does the following:
 * for NFS Version 2 - play it safe and flush/invalidate all dirty buffers
 * for NFS Version 3 - flush dirty buffers to the server but don't invalidate
 *                     or commit them (this satisfies 1 and 2 except for the
 *                     case where the server crashes after this close but
 *                     before the commit RPC, which is felt to be "good
 *                     enough". Changing the last argument to nfs_flush() to
 *                     a 1 would force a commit operation, if it is felt a
 *                     commit is necessary now.
 */
/* ARGSUSED */
int
nfsx_close(struct vop_close_args *ap)
{
	struct vnode *vp = ap->a_vp;
	struct nfsnode *np = VTONFS(vp);
	int error = 0;

	if (vp->v_type == VREG) {
	    if (np->n_flag & NMODIFIED) {
		if (NFS_ISV3(vp)) {
		    /*
		     * Under NFSv3 we have dirty buffers to dispose of.  We
		     * must flush them to the NFS server.  We have the option
		     * of waiting all the way through the commit rpc or just
		     * waiting for the initial write.  The default is to only
		     * wait through the initial write so the data is in the
		     * server's cache, which is roughly similar to the state
		     * a standard disk subsystem leaves the file in on close().
		     *
		     * We cannot clear the NMODIFIED bit in np->n_flag due to
		     * potential races with other processes, and certainly
		     * cannot clear it if we don't commit.
		     */
		    int cm = nfsv3_commit_on_close ? 1 : 0;
		    error = nfsx_flush(vp, ap->a_cred, MNT_WAIT, ap->a_td, cm);
		    /* np->n_flag &= ~NMODIFIED; */
		} else {
		    vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, ap->a_td);
		    error = nfsx_vinvalbuf(vp, V_SAVE, ap->a_cred, ap->a_td, 1);
		    VOP_UNLOCK(vp, 0, ap->a_td);
		}
		np->n_attrstamp = 0;
	    }
	    if (np->n_flag & NWRITEERR) {
		np->n_flag &= ~NWRITEERR;
		error = np->n_error;
	    }
	}
	return (error);
}

/*
 * nfs setattr call.
 */
int
nfsx_setattr(struct vop_setattr_args *ap)
{
	struct vnode *vp = ap->a_vp;
	struct nfsnode *np = VTONFS(vp);
	struct vattr *vap = ap->a_vap;
	int error = 0;
	u_quad_t tsize;
	struct nfsmount *nmp = VFSTONFS(vp->v_mount);

#ifndef nolint
	tsize = (u_quad_t)0;
#endif

	/*
	 * Setting of flags is not supported.
	 */
	if (vap->va_flags != VNOVAL)
		return (EOPNOTSUPP);

	/*
	 * Disallow write attempts if the filesystem is mounted read-only.
	 */
  	if ((vap->va_flags != VNOVAL || vap->va_uid != (uid_t)VNOVAL ||
	    vap->va_gid != (gid_t)VNOVAL || vap->va_atime.tv_sec != VNOVAL ||
	    vap->va_mtime.tv_sec != VNOVAL || vap->va_mode != (mode_t)VNOVAL) &&
	    (vp->v_mount->mnt_flag & MNT_RDONLY))
		return (EROFS);
	if (vap->va_size != VNOVAL) {
 		switch (vp->v_type) {
 		case VDIR:
 			return (EISDIR);
 		case VCHR:
 		case VBLK:
 		case VSOCK:
 		case VFIFO:
			if (vap->va_mtime.tv_sec == VNOVAL &&
			    vap->va_atime.tv_sec == VNOVAL &&
			    vap->va_mode == (mode_t)VNOVAL &&
			    vap->va_uid == (uid_t)VNOVAL &&
			    vap->va_gid == (gid_t)VNOVAL)
				return (0);
 			vap->va_size = VNOVAL;
 			break;
 		default:
			/*
			 * Disallow write attempts if the filesystem is
			 * mounted read-only.
			 */
			if (vp->v_mount->mnt_flag & MNT_RDONLY)
				return (EROFS);

			/*
			 *  We run vnode_pager_setsize() early (why?),
			 * we must set np->n_size now to avoid vinvalbuf
			 * V_SAVE races that might setsize a lower
			 * value.
			 */

			tsize = np->n_size;
			error = nfsx_meta_setsize(vp, ap->a_cred, 
			    ap->a_td, vap->va_size);

 			if (np->n_flag & NMODIFIED) {
 			    if (vap->va_size == 0)
 				error = nfsx_vinvalbuf(vp, 0,
 					ap->a_cred, ap->a_td, 1);
 			    else
 				error = nfsx_vinvalbuf(vp, V_SAVE,
 					ap->a_cred, ap->a_td, 1);
 			    if (error) {
				vnode_pager_setsize(vp, np->n_size);
 				return (error);
			    }
 			}
			/*
			 * np->n_size has already been set to vap->va_size
			 * in nfsx_meta_setsize(). We must set it again since
			 * nfs_loadattrcache() could be called through
			 * nfsx_meta_setsize() and could modify np->n_size.
			 */
 			np->n_vattr.va_size = np->n_size = vap->va_size;
  		};
  	} else if ((vap->va_mtime.tv_sec != VNOVAL ||
		vap->va_atime.tv_sec != VNOVAL) && (np->n_flag & NMODIFIED) &&
		vp->v_type == VREG &&
  		(error = nfsx_vinvalbuf(vp, V_SAVE, ap->a_cred,
		 ap->a_td, 1)) == EINTR)
		return (error);

	error = NFSOP(nmp, setattrrpc)(vp, vap, ap->a_cred, ap->a_td);
	if (error && vap->va_size != VNOVAL) {
		np->n_size = np->n_vattr.va_size = tsize;
		vnode_pager_setsize(vp, np->n_size);
	}
	return (error);
}

/*
 * nfs lookup call, one step at a time...
 * First look in cache
 * If not found, unlock the directory nfsnode and do the rpc
 */
int
nfsx_lookup(struct vop_lookup_args *ap)
{
	struct componentname *cnp = ap->a_cnp;
	struct vnode *dvp = ap->a_dvp;
	struct vnode **vpp = ap->a_vpp;
	int flags = cnp->cn_flags;
	struct vnode *newvp;
	struct nfsmount *nmp;
	nfsfh_t *fhp;
	struct nfsnode *np;
	int lockparent, wantparent, error = 0, fhsize;
	struct thread *td = cnp->cn_thread;
	u_char stp[NFSX_STATESIZ];	

	*vpp = NULLVP;
	cnp->cn_flags &= ~PDIRUNLOCK;
	if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
		return (EROFS);
	if (dvp->v_type != VDIR)
		return (ENOTDIR);
	lockparent = flags & LOCKPARENT;
	wantparent = flags & (LOCKPARENT|WANTPARENT);
	nmp = VFSTONFS(dvp->v_mount);
	np = VTONFS(dvp);
	if ((error = cache_lookup(dvp, vpp, cnp)) && error != ENOENT) {
		struct vattr vattr;
		int vpid;

		if ((error = VOP_ACCESS(dvp, VEXEC, cnp->cn_cred, td)) != 0) {
			*vpp = NULLVP;
			return (error);
		}

		vhold(*vpp);
		newvp = *vpp;
		vpid = newvp->v_id;
		/*
		 * See the comment starting `Step through' in ufs/ufs_lookup.c
		 * for an explanation of the locking protocol
		 */
		if (dvp == newvp) {
			VREF(newvp);
			error = 0;
		} else if (flags & ISDOTDOT) {
			VOP_UNLOCK(dvp, 0, td);
			cnp->cn_flags |= PDIRUNLOCK;
			error = vget(newvp, LK_EXCLUSIVE, td);
			if (!error && lockparent && (flags & ISLASTCN)) {
				error = vn_lock(dvp, LK_EXCLUSIVE, td);
				if (error == 0)
					cnp->cn_flags &= ~PDIRUNLOCK;
			}
		} else {
			error = vget(newvp, LK_EXCLUSIVE, td);
			if (!lockparent || error || !(flags & ISLASTCN)) {
				VOP_UNLOCK(dvp, 0, td);
				cnp->cn_flags |= PDIRUNLOCK;
			}
		}
		if (!error) {
			if (vpid == newvp->v_id) {
			   if (!VOP_GETATTR(newvp, &vattr, cnp->cn_cred, td)
			    && vattr.va_ctime.tv_sec == VTONFS(newvp)->n_ctime) {
				nfsxstats.lookupcache_hits++;
				if (cnp->cn_nameiop != LOOKUP &&
				    (flags & ISLASTCN))
					cnp->cn_flags |= SAVENAME;
				vdrop(newvp);
				return (0);
			   }
			   cache_purge(newvp);
			}
			vput(newvp);
			if (lockparent && dvp != newvp && (flags & ISLASTCN))
				VOP_UNLOCK(dvp, 0, td);
		}
		vdrop(newvp);
		error = vn_lock(dvp, LK_EXCLUSIVE, td);
		*vpp = NULLVP;
		if (error) {
			cnp->cn_flags |= PDIRUNLOCK;
			return (error);
		}
		cnp->cn_flags &= ~PDIRUNLOCK;
	}

	newvp = NULLVP;
	nfsxstats.lookupcache_misses++;

	error = NFSOP(nmp, lookuprpc)(dvp, cnp,
	    flags & ISDOTDOT, &fhp, &fhsize, stp);
	if (error != 0)
		goto nfsmout;

	/*
	 * Handle RENAME case...
	 */
	if (cnp->cn_nameiop == RENAME && wantparent && (flags & ISLASTCN)) {
		if (NFS_CMPFH(np, fhp, fhsize))
			return (EISDIR);
		error = nfsx_nget(dvp->v_mount, fhp, fhsize, &np);
		if (error)
			return (error);
		newvp = NFSTOV(np);

		NFSOP(nmp, lookuploadattr)(newvp, dvp, stp);

		*vpp = newvp;
		cnp->cn_flags |= SAVENAME;
		if (!lockparent) {
			VOP_UNLOCK(dvp, 0, td);
			cnp->cn_flags |= PDIRUNLOCK;
		}
		return (0);
	}

	if (flags & ISDOTDOT) {
		VOP_UNLOCK(dvp, 0, td);
		error = nfsx_nget(dvp->v_mount, fhp, fhsize, &np);
		if (error) {
			vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY, td);
			return (error);
		}
		newvp = NFSTOV(np);
		if (lockparent && (flags & ISLASTCN)) {
			error = vn_lock(dvp, LK_EXCLUSIVE, td);
			if (error) {
				cnp->cn_flags |= PDIRUNLOCK;
		    		vput(newvp);
				return (error);
			}
		} else
			cnp->cn_flags |= PDIRUNLOCK;
	} else if (NFS_CMPFH(np, fhp, fhsize)) {
		VREF(dvp);
		newvp = dvp;
	} else {
		error = nfsx_nget(dvp->v_mount, fhp, fhsize, &np);
		if (error)
			return (error);
		if (!lockparent || !(flags & ISLASTCN)) {
			cnp->cn_flags |= PDIRUNLOCK;
			VOP_UNLOCK(dvp, 0, td);
		}
		newvp = NFSTOV(np);

		/*
		 * XXXMARIUS: this is v4 specific; should have a
		 * version handler here.
		 */

		/* Copy name for open() */
		np->n_dvp = dvp;
                np->n_namelen = cnp->cn_namelen;
                if (np->n_name != NULL)
                        FREE(np->n_name, M_NFSREQ);
                MALLOC(np->n_name, u_char *, np->n_namelen + 1,
		    M_NFSREQ, M_WAITOK);
                bcopy(cnp->cn_nameptr, np->n_name, np->n_namelen);
                np->n_name[np->n_namelen] = '\0';

		NFSOP(nmp, lookuploadattr)(newvp, dvp, stp);
	}

	if (cnp->cn_nameiop != LOOKUP && (flags & ISLASTCN))
		cnp->cn_flags |= SAVENAME;
	if ((cnp->cn_flags & MAKEENTRY) &&
	    (cnp->cn_nameiop != DELETE || !(flags & ISLASTCN))) {
		np->n_ctime = np->n_vattr.va_ctime.tv_sec;
		cache_enter(dvp, newvp, cnp);
	}
	*vpp = newvp;
nfsmout:
	if (error) {
		if (newvp != NULLVP) {
			vrele(newvp);
			*vpp = NULLVP;
		}
		if ((cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME) &&
		    (flags & ISLASTCN) && error == ENOENT) {
			if (!lockparent) {
				VOP_UNLOCK(dvp, 0, td);
				cnp->cn_flags |= PDIRUNLOCK;
			}
			if (dvp->v_mount->mnt_flag & MNT_RDONLY)
				error = EROFS;
			else
				error = EJUSTRETURN;
		}
		if (cnp->cn_nameiop != LOOKUP && (flags & ISLASTCN))
			cnp->cn_flags |= SAVENAME;
	}
	return (error);
}

/*
 * nfs read call.
 * Just call nfs_bioread() to do the work.
 */
int
nfsx_read(struct vop_read_args *ap)
{
	struct vnode *vp = ap->a_vp;

	if (vp->v_type == VREG)
		return (nfsx_bioread(vp, ap->a_uio, ap->a_ioflag, ap->a_cred));

	return (vp->v_type == VDIR ? EISDIR : EOPNOTSUPP);
}

/*
 * nfs readlink call
 */
int
nfsx_readlink(struct vop_readlink_args *ap)
{
	struct vnode *vp = ap->a_vp;

	if (vp->v_type != VLNK)
		return (EINVAL);
	return (nfsx_bioread(vp, ap->a_uio, 0, ap->a_cred));
}

/*
 * nfs mknod vop
 * just call nfs_mknodrpc() to do the work.
 */
/* ARGSUSED */
int
nfsx_mknod(struct vop_mknod_args *ap)
{
	struct vnode *newvp;
	struct nfsmount *nmp = VFSTONFS(ap->a_dvp->v_mount);
	int error;

	 error = NFSOP(nmp, mknodrpc)(ap->a_dvp, &newvp, ap->a_cnp, ap->a_vap);

        /* XXX - is this actually referenced here? */
        if (error == 0) {
                *ap->a_vpp = newvp;
                vrele(newvp);
        }

        return (error);
}

/*
 * nfs file remove call
 * To try and make nfs semantics closer to ufs semantics, a file that has
 * other processes using the vnode is renamed instead of removed and then
 * removed later on the last close.
 * - If v_usecount > 1
 *	  If a rename is not already in the works
 *	     call nfsx_sillyrename() to set it up
 *     else
 *	  do the remove rpc
 */
int
nfsx_remove(struct vop_remove_args *ap)
{
	struct vnode *vp = ap->a_vp;
	struct vnode *dvp = ap->a_dvp;
	struct componentname *cnp = ap->a_cnp;
	struct nfsnode *np = VTONFS(vp);
	int error = 0;
	struct vattr vattr;
	struct nfsmount *nmp = VFSTONFS(ap->a_vp->v_mount);

#ifndef DIAGNOSTIC
	if ((cnp->cn_flags & HASBUF) == 0)
		panic("nfs_remove: no name");
	if (vrefcnt(vp) < 1)
		panic("nfs_remove: bad v_usecount");
#endif
	if (vp->v_type == VDIR)
		error = EPERM;
	else if (vrefcnt(vp) == 1 || (np->n_sillyrename &&
	    VOP_GETATTR(vp, &vattr, cnp->cn_cred, cnp->cn_thread) == 0 &&
	    vattr.va_nlink > 1)) {
		/*
		 * Purge the name cache so that the chance of a lookup for
		 * the name succeeding while the remove is in progress is
		 * minimized. Without node locking it can still happen, such
		 * that an I/O op returns ESTALE, but since you get this if
		 * another host removes the file..
		 */
		cache_purge(vp);
		/*
		 * throw away biocache buffers, mainly to avoid
		 * unnecessary delayed writes later.
		 */
		error = nfsx_vinvalbuf(vp, 0, cnp->cn_cred, cnp->cn_thread, 1);
		/* Do the rpc */
		if (error != EINTR)
			error = NFSOP(nmp, removerpc)(dvp, cnp->cn_nameptr,
			    cnp->cn_namelen, cnp->cn_cred, cnp->cn_thread);

		/*
		 * Kludge City: If the first reply to the remove rpc is lost..
		 *   the reply to the retransmitted request will be ENOENT
		 *   since the file was in fact removed
		 *   Therefore, we cheat and return success.
		 */
		if (error == ENOENT)
			error = 0;
	} else if (!np->n_sillyrename)
		error = nfsx_sillyrename(dvp, vp, cnp);
	np->n_attrstamp = 0;
	return (error);
}

/*
 * nfs file remove rpc called from nfs_inactive
 */
static int
nfsx_removeit(struct sillyrename *sp)
{
	struct nfsmount *nmp = VFSTONFS(sp->s_dvp->v_mount);

	/*
	 * Make sure that the directory vnode is still valid.
	 * XXX we should lock sp->s_dvp here.
	 */
	if (sp->s_dvp->v_type == VBAD)
		return (0);

	return (NFSOP(nmp, removerpc)(sp->s_dvp, sp->s_name, sp->s_namlen,
		    sp->s_cred, NULL));
}

/*
 * nfs file rename call
 */
int
nfsx_rename(struct vop_rename_args *ap)
{
	struct vnode *fvp = ap->a_fvp;
	struct vnode *tvp = ap->a_tvp;
	struct vnode *fdvp = ap->a_fdvp;
	struct vnode *tdvp = ap->a_tdvp;
	struct componentname *tcnp = ap->a_tcnp;
	struct componentname *fcnp = ap->a_fcnp;
	int error;
	struct nfsmount *nmp = VFSTONFS(ap->a_fvp->v_mount);

#ifndef DIAGNOSTIC
	if ((tcnp->cn_flags & HASBUF) == 0 ||
	    (fcnp->cn_flags & HASBUF) == 0)
		panic("nfs_rename: no name");
#endif
	/* Check for cross-device rename */
	if ((fvp->v_mount != tdvp->v_mount) ||
	    (tvp && (fvp->v_mount != tvp->v_mount))) {
		error = EXDEV;
		goto out;
	}

	if (fvp == tvp) {
		printf("nfs_rename: fvp == tvp (can't happen)\n");
		error = 0;
		goto out;
	}
	if ((error = vn_lock(fvp, LK_EXCLUSIVE, fcnp->cn_thread)) != 0)
		goto out;

	/*
	 * We have to flush B_DELWRI data prior to renaming
	 * the file.  If we don't, the delayed-write buffers
	 * can be flushed out later after the file has gone stale
	 * under NFSV3.  NFSV2 does not have this problem because
	 * ( as far as I can tell ) it flushes dirty buffers more
	 * often.
	 */
	VOP_FSYNC(fvp, fcnp->cn_cred, MNT_WAIT, fcnp->cn_thread);
	VOP_UNLOCK(fvp, 0, fcnp->cn_thread);
	if (tvp)
	    VOP_FSYNC(tvp, tcnp->cn_cred, MNT_WAIT, tcnp->cn_thread);

	/*
	 * If the tvp exists and is in use, sillyrename it before doing the
	 * rename of the new file over it.
	 * XXX Can't sillyrename a directory.
	 */
	if (tvp && vrefcnt(tvp) > 1 && !VTONFS(tvp)->n_sillyrename &&
		tvp->v_type != VDIR && !nfsx_sillyrename(tdvp, tvp, tcnp)) {
		vput(tvp);
		tvp = NULL;
	}

	error = NFSOP(nmp, renamerpc)(fdvp, fcnp->cn_nameptr, fcnp->cn_namelen,
	    tdvp, tcnp->cn_nameptr, tcnp->cn_namelen, tcnp->cn_cred,
	    tcnp->cn_thread);

	if (fvp->v_type == VDIR) {
		if (tvp != NULL && tvp->v_type == VDIR)
			cache_purge(tdvp);
		cache_purge(fdvp);
	}

out:
	if (tdvp == tvp)
		vrele(tdvp);
	else
		vput(tdvp);
	if (tvp)
		vput(tvp);
	vrele(fdvp);
	vrele(fvp);
	/*
	 * Kludge: Map ENOENT => 0 assuming that it is a reply to a retry.
	 */
	if (error == ENOENT)
		error = 0;
	return (error);
}

/*
 * nfs file rename rpc called from nfs_remove() above
 */
int
nfsx_renameit(struct vnode *sdvp, struct componentname *scnp,
    struct sillyrename *sp)
{
	struct nfsmount *nmp = VFSTONFS(sdvp->v_mount);

	return (NFSOP(nmp, renamerpc)(sdvp, scnp->cn_nameptr,
		    scnp->cn_namelen, sdvp, sp->s_name, sp->s_namlen,
		    scnp->cn_cred, scnp->cn_thread));
}

/*
 * nfs readdir call
 */
int
nfsx_readdir(struct vop_readdir_args *ap)
{
	struct vnode *vp = ap->a_vp;
	struct nfsnode *np = VTONFS(vp);
	struct uio *uio = ap->a_uio;
	int tresid, error;
	struct vattr vattr;

	if (vp->v_type != VDIR)
		return (EPERM);
	/*
	 * first, check for hit on the EOF offset cache
	 */
	if (np->n_direofoffset > 0 && uio->uio_offset >= np->n_direofoffset &&
	    (np->n_flag & NMODIFIED) == 0) {
		if (VOP_GETATTR(vp, &vattr, ap->a_cred, uio->uio_td) == 0 &&
			np->n_mtime == vattr.va_mtime.tv_sec) {
			nfsxstats.direofcache_hits++;
			return (0);
		}
	}

	/*
	 * Call nfs_bioread() to do the real work.
	 */
	tresid = uio->uio_resid;
	error = nfsx_bioread(vp, uio, 0, ap->a_cred);

	if (!error && uio->uio_resid == tresid)
		nfsxstats.direofcache_misses++;
	return (error);
}

/*
 * Silly rename. To make the NFS filesystem that is stateless look a little
 * more like the "ufs" a remove of an active vnode is translated to a rename
 * to a funny looking filename that is removed by nfs_inactive on the
 * nfsnode. There is the potential for another process on a different client
 * to create the same funny name between the nfs_lookitup() fails and the
 * nfs_rename() completes, but...
 */
int
nfsx_sillyrename(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
{
	struct sillyrename *sp;
	struct nfsnode *np;
	int error;
	short pid;

	cache_purge(dvp);
	np = VTONFS(vp);
#ifndef DIAGNOSTIC
	if (vp->v_type == VDIR)
		panic("nfs: sillyrename dir");
#endif
	MALLOC(sp, struct sillyrename *, sizeof (struct sillyrename),
		M_NFSREQ, M_WAITOK);
	sp->s_cred = crhold(cnp->cn_cred);
	sp->s_dvp = dvp;
	sp->s_removeit = nfsx_removeit;
	VREF(dvp);

	/* Fudge together a funny name */
	pid = cnp->cn_thread->td_proc->p_pid;
	sp->s_namlen = sprintf(sp->s_name, ".nfsA%04x4.4", pid);

	/* Try lookitups until we get one that isn't there */
	while (nfsx_lookitup(dvp, sp->s_name, sp->s_namlen, sp->s_cred,
		cnp->cn_thread, NULL) == 0) {
		sp->s_name[4]++;
		if (sp->s_name[4] > 'z') {
			error = EINVAL;
			goto bad;
		}
	}
	error = nfsx_renameit(dvp, cnp, sp);
	if (error)
		goto bad;
	error = nfsx_lookitup(dvp, sp->s_name, sp->s_namlen, sp->s_cred,
		cnp->cn_thread, &np);
	np->n_sillyrename = sp;
	return (0);
bad:
	vrele(sp->s_dvp);
	crfree(sp->s_cred);
	free((caddr_t)sp, M_NFSREQ);
	return (error);
}

/*
 * Look up a file name and optionally either update the file handle or
 * allocate an nfsnode, depending on the value of npp.
 * npp == NULL	--> just do the lookup
 * *npp == NULL --> allocate a new nfsnode and make sure attributes are
 *			handled too
 * *npp != NULL --> update the file handle in the vnode
 */
int
nfsx_lookitup(struct vnode *dvp, const char *name, int len, struct ucred *cred,
    struct thread *td, struct nfsnode **npp)
{
	struct vnode *newvp = NULL;
	struct nfsnode *np, *dnp = VTONFS(dvp);
	int error = 0, fhlen;
	nfsfh_t *nfhp;
	struct componentname cn;
	struct nfsmount *nmp = VFSTONFS(dvp->v_mount);
	u_char stp[NFSX_STATESIZ];

	nfsxstats.rpccnt[NFSPROC_LOOKUP]++;

	(const char *)cn.cn_nameptr = name;
	cn.cn_namelen = len;

	error = NFSOP(nmp, lookuprpc)(dvp, &cn, 0, &nfhp, &fhlen, stp);

	if (npp && !error) {
		if (*npp) {
		    np = *npp;
		    if (np->n_fhsize > NFS_SMALLFH && fhlen <= NFS_SMALLFH) {
			free((caddr_t)np->n_fhp, M_NFSBIGFH);
			np->n_fhp = &np->n_fh;
		    } else if (np->n_fhsize <= NFS_SMALLFH && fhlen>NFS_SMALLFH)
			np->n_fhp =(nfsfh_t *)malloc(fhlen, M_NFSBIGFH, M_WAITOK);
		    bcopy((caddr_t)nfhp, (caddr_t)np->n_fhp, fhlen);
		    np->n_fhsize = fhlen;
		    newvp = NFSTOV(np);
		} else if (NFS_CMPFH(dnp, nfhp, fhlen)) {
		    VREF(dvp);
		    newvp = dvp;
		} else {
		    error = nfsx_nget(dvp->v_mount, nfhp, fhlen, &np);
		    if (error)
			return (error);
		    newvp = NFSTOV(np);
		}

                if (newvp != dvp) {
                        np->n_dvp = dvp;
                        np->n_namelen = len;
                        if (np->n_name != NULL)
                                FREE(np->n_name, M_NFSREQ);
                        MALLOC(np->n_name, u_char *,
                            np->n_namelen + 1, M_NFSREQ, M_WAITOK);
                        memcpy(np->n_name, name, len);
                        np->n_name[len] = '\0';
                }

                NFSOP(nmp, lookuploadattr)(newvp, dvp, stp);
	}
/* nfsmout: */
	if (npp && *npp == NULL) {
		if (error) {
			if (newvp) {
				if (newvp == dvp)
					vrele(newvp);
				else
					vput(newvp);
			}
		} else
			*npp = np;
	}
	return (error);
}

/*
 * Strategy routine.
 * For async requests when nfsiod(s) are running, queue the request by
 * calling nfsx_asyncio(), otherwise just all nfsx_doio() to do the
 * request.
 */
int
nfsx_strategy(struct vop_strategy_args *ap)
{
	struct buf *bp = ap->a_bp;
	struct ucred *cr;
	struct thread *td;
	int error = 0;

	KASSERT(ap->a_vp == ap->a_bp->b_vp, ("%s(%p != %p)",
	    __func__, ap->a_vp, ap->a_bp->b_vp));
	KASSERT(!(bp->b_flags & B_DONE), ("nfs_strategy: buffer %p unexpectedly marked B_DONE", bp));
	KASSERT(BUF_REFCNT(bp) > 0, ("nfs_strategy: buffer %p not locked", bp));

	if (bp->b_flags & B_ASYNC)
		td = NULL;
	else
		td = curthread;	/* XXX */

	if (bp->b_iocmd == BIO_READ)
		cr = bp->b_rcred;
	else
		cr = bp->b_wcred;

	/*
	 * If the op is asynchronous and an i/o daemon is waiting
	 * queue the request, wake it up and wait for completion
	 * otherwise just do it ourselves.
	 */
	if ((bp->b_flags & B_ASYNC) == 0 ||
		nfsx_asyncio(bp, NOCRED, td))
		error = nfsx_doio(bp, cr, td);
	return (error);
}

/*
 * fsync vnode op. Just call nfs_flush() with commit == 1.
 */
/* ARGSUSED */
int
nfsx_fsync(struct vop_fsync_args *ap)
{
	return (nfsx_flush(ap->a_vp, ap->a_cred, ap->a_waitfor, ap->a_td, 1));
}

/*
 * Flush all the blocks associated with a vnode.
 * 	Walk through the buffer pool and push any dirty pages
 *	associated with the vnode.
 */
static int
nfsx_flush(struct vnode *vp, struct ucred *cred, int waitfor, struct thread *td,
    int commit)
{
	struct nfsnode *np = VTONFS(vp);
	struct buf *bp;
	int i;
	struct buf *nbp;
	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
	int s, error = 0, slptimeo = 0, slpflag = 0, retv, bvecpos;
	int passone = 1;
	u_quad_t off, endoff, toff;
	struct ucred* wcred = NULL;
	struct buf **bvec = NULL;
#ifndef NFS_COMMITBVECSIZ
#define NFS_COMMITBVECSIZ	20
#endif
	struct buf *bvec_on_stack[NFS_COMMITBVECSIZ];
	int bvecsize = 0, bveccount;

	if (nmp->nm_flag & NFSMNT_INT)
		slpflag = PCATCH;
	if (!commit)
		passone = 0;
	/*
	 * A b_flags == (B_DELWRI | B_NEEDCOMMIT) block has been written to the
	 * server, but nas not been committed to stable storage on the server
	 * yet. On the first pass, the byte range is worked out and the commit
	 * rpc is done. On the second pass, nfs_writebp() is called to do the
	 * job.
	 */
again:
	off = (u_quad_t)-1;
	endoff = 0;
	bvecpos = 0;
	if (NFS_ISV3(vp) && commit) {
		s = splbio();
		if (bvec != NULL && bvec != bvec_on_stack)
			free(bvec, M_TEMP);
		/*
		 * Count up how many buffers waiting for a commit.
		 */
		bveccount = 0;
		VI_LOCK(vp);
		for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
			nbp = TAILQ_NEXT(bp, b_vnbufs);
			if (BUF_REFCNT(bp) == 0 &&
			    (bp->b_flags & (B_DELWRI | B_NEEDCOMMIT))
				== (B_DELWRI | B_NEEDCOMMIT))
				bveccount++;
		}
		/*
		 * Allocate space to remember the list of bufs to commit.  It is
		 * important to use M_NOWAIT here to avoid a race with nfs_write.
		 * If we can't get memory (for whatever reason), we will end up
		 * committing the buffers one-by-one in the loop below.
		 */
		if (bveccount > NFS_COMMITBVECSIZ) {
			/*
			 * Release the vnode interlock to avoid a lock
			 * order reversal.
			 */
			VI_UNLOCK(vp);
			bvec = (struct buf **)
				malloc(bveccount * sizeof(struct buf *),
				       M_TEMP, M_NOWAIT);
			VI_LOCK(vp);
			if (bvec == NULL) {
				bvec = bvec_on_stack;
				bvecsize = NFS_COMMITBVECSIZ;
			} else
				bvecsize = bveccount;
		} else {
			bvec = bvec_on_stack;
			bvecsize = NFS_COMMITBVECSIZ;
		}
		for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
			if (bvecpos >= bvecsize)
				break;
			if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
				nbp = TAILQ_NEXT(bp, b_vnbufs);
				continue;
			}
			if ((bp->b_flags & (B_DELWRI | B_NEEDCOMMIT)) !=
			    (B_DELWRI | B_NEEDCOMMIT)) {
				BUF_UNLOCK(bp);
				nbp = TAILQ_NEXT(bp, b_vnbufs);
				continue;
			}
			VI_UNLOCK(vp);
			bremfree(bp);
			/*
			 * Work out if all buffers are using the same cred
			 * so we can deal with them all with one commit.
			 *
			 * NOTE: we are not clearing B_DONE here, so we have
			 * to do it later on in this routine if we intend to
			 * initiate I/O on the bp.
			 *
			 * Note: to avoid loopback deadlocks, we do not
			 * assign b_runningbufspace.
			 */
			if (wcred == NULL)
				wcred = bp->b_wcred;
			else if (wcred != bp->b_wcred)
				wcred = NOCRED;
			bp->b_flags |= B_WRITEINPROG;
			vfs_busy_pages(bp, 1);

			VI_LOCK(vp);
			/*
			 * bp is protected by being locked, but nbp is not
			 * and vfs_busy_pages() may sleep.  We have to
			 * recalculate nbp.
			 */
			nbp = TAILQ_NEXT(bp, b_vnbufs);

			/*
			 * A list of these buffers is kept so that the
			 * second loop knows which buffers have actually
			 * been committed. This is necessary, since there
			 * may be a race between the commit rpc and new
			 * uncommitted writes on the file.
			 */
			bvec[bvecpos++] = bp;
			toff = ((u_quad_t)bp->b_blkno) * DEV_BSIZE +
				bp->b_dirtyoff;
			if (toff < off)
				off = toff;
			toff += (u_quad_t)(bp->b_dirtyend - bp->b_dirtyoff);
			if (toff > endoff)
				endoff = toff;
		}
		splx(s);
		VI_UNLOCK(vp);
	}
	if (bvecpos > 0) {
		/*
		 * Commit data on the server, as required.
		 * If all bufs are using the same wcred, then use that with
		 * one call for all of them, otherwise commit each one
		 * separately.
		 */
		if (wcred != NOCRED)
			retv = NFSOP(nmp, commit)(vp, off, (int)(endoff - off),
			    wcred, td);
		else {
			retv = 0;
			for (i = 0; i < bvecpos; i++) {
				off_t off, size;
				bp = bvec[i];
				off = ((u_quad_t)bp->b_blkno) * DEV_BSIZE +
					bp->b_dirtyoff;
				size = (u_quad_t)(bp->b_dirtyend
						  - bp->b_dirtyoff);
				retv = NFSOP(nmp, commit)(vp, off, (int)size,
				    bp->b_wcred, td);
				if (retv) break;
			}
		}

		if (retv == NFSERR_STALEWRITEVERF)
			nfsx_clearcommit(vp->v_mount);

		/*
		 * Now, either mark the blocks I/O done or mark the
		 * blocks dirty, depending on whether the commit
		 * succeeded.
		 */
		for (i = 0; i < bvecpos; i++) {
			bp = bvec[i];
			bp->b_flags &= ~(B_NEEDCOMMIT | B_WRITEINPROG | B_CLUSTEROK);
			if (retv) {
				/*
				 * Error, leave B_DELWRI intact
				 */
				vfs_unbusy_pages(bp);
				brelse(bp);
			} else {
				/*
				 * Success, remove B_DELWRI ( bundirty() ).
				 *
				 * b_dirtyoff/b_dirtyend seem to be NFS
				 * specific.  We should probably move that
				 * into bundirty(). XXX
				 */
				s = splbio();
				VI_LOCK(vp);
				vp->v_numoutput++;
				VI_UNLOCK(vp);
				bp->b_flags |= B_ASYNC;
				bundirty(bp);
				bp->b_flags &= ~B_DONE;
				bp->b_ioflags &= ~BIO_ERROR;
				bp->b_dirtyoff = bp->b_dirtyend = 0;
				splx(s);
				bufdone(bp);
			}
		}
	}

	/*
	 * Start/do any write(s) that are required.
	 */
loop:
	s = splbio();
	VI_LOCK(vp);
	for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
		nbp = TAILQ_NEXT(bp, b_vnbufs);
		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
			if (waitfor != MNT_WAIT || passone)
				continue;

			error = BUF_TIMELOCK(bp,
			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
			    VI_MTX(vp), "nfsfsync", slpflag, slptimeo);
			splx(s);
			if (error == 0)
				panic("nfs_fsync: inconsistent lock");
			if (error == ENOLCK)
				goto loop;
			if (nfsx_sigintr(nmp, NULL, td)) {
				error = EINTR;
				goto done;
			}
			if (slpflag == PCATCH) {
				slpflag = 0;
				slptimeo = 2 * hz;
			}
			goto loop;
		}
		if ((bp->b_flags & B_DELWRI) == 0)
			panic("nfs_fsync: not dirty");
		if ((passone || !commit) && (bp->b_flags & B_NEEDCOMMIT)) {
			BUF_UNLOCK(bp);
			continue;
		}
		VI_UNLOCK(vp);
		bremfree(bp);
		if (passone || !commit)
		    bp->b_flags |= B_ASYNC;
		else
		    bp->b_flags |= B_ASYNC | B_WRITEINPROG;
		splx(s);
		bwrite(bp);
		goto loop;
	}
	splx(s);
	if (passone) {
		passone = 0;
		VI_UNLOCK(vp);
		goto again;
	}
	if (waitfor == MNT_WAIT) {
		while (vp->v_numoutput) {
			vp->v_iflag |= VI_BWAIT;
			error = msleep((caddr_t)&vp->v_numoutput, VI_MTX(vp),
				slpflag | (PRIBIO + 1), "nfsfsync", slptimeo);
			if (error) {
			    VI_UNLOCK(vp);
			    if (nfsx_sigintr(nmp, NULL, td)) {
				error = EINTR;
				goto done;
			    }
			    if (slpflag == PCATCH) {
				slpflag = 0;
				slptimeo = 2 * hz;
			    }
			    VI_LOCK(vp);
			}
		}
		if (!TAILQ_EMPTY(&vp->v_dirtyblkhd) && commit) {
			VI_UNLOCK(vp);
			goto loop;
		}
	}
	VI_UNLOCK(vp);
	if (np->n_flag & NWRITEERR) {
		error = np->n_error;
		np->n_flag &= ~NWRITEERR;
	}
done:
	if (bvec != NULL && bvec != bvec_on_stack)
		free(bvec, M_TEMP);
	return (error);
}

/*
 * NFS advisory byte-level locks.
 */
int
nfsx_advlock(struct vop_advlock_args *ap)
{

	if ((VFSTONFS(ap->a_vp->v_mount)->nm_flag & NFSMNT_NOLOCKD) != 0) {
		struct nfsnode *np = VTONFS(ap->a_vp);

		return (lf_advlock(ap, &(np->n_lockf), np->n_size));
	}
	return (nfsx_dolock(ap));
}

/*
 * Print out the contents of an nfsnode.
 */
int
nfsx_print(struct vop_print_args *ap)
{
	struct vnode *vp = ap->a_vp;
	struct nfsnode *np = VTONFS(vp);

	printf("\tfileid %ld fsid 0x%x",
	   np->n_vattr.va_fileid, np->n_vattr.va_fsid);
	if (vp->v_type == VFIFO)
		fifo_printinfo(vp);
	printf("\n");
	return (0);
}

/*
 * This is the "real" nfs::bwrite(struct buf*).
 * B_WRITEINPROG isn't set unless the force flag is one and it
 * handles the B_NEEDCOMMIT flag.
 * We set B_CACHE if this is a VMIO buffer.
 */
int
nfsx_writebp(struct buf *bp, int force, struct thread *td)
{
	int s;
	int oldflags = bp->b_flags;
#if 0
	int retv = 1;
	off_t off;
#endif

	if (BUF_REFCNT(bp) == 0)
		panic("bwrite: buffer is not locked???");

	if (bp->b_flags & B_INVAL) {
		brelse(bp);
		return(0);
	}

	bp->b_flags |= B_CACHE;

	/*
	 * Undirty the bp.  We will redirty it later if the I/O fails.
	 */

	s = splbio();
	bundirty(bp);
	bp->b_flags &= ~B_DONE;
	bp->b_ioflags &= ~BIO_ERROR;
	bp->b_iocmd = BIO_WRITE;

	VI_LOCK(bp->b_vp);
	bp->b_vp->v_numoutput++;
	VI_UNLOCK(bp->b_vp);
	curthread->td_proc->p_stats->p_ru.ru_oublock++;
	splx(s);

	/*
	 * Note: to avoid loopback deadlocks, we do not
	 * assign b_runningbufspace.
	 */
	vfs_busy_pages(bp, 1);

	if (force)
		bp->b_flags |= B_WRITEINPROG;
	BUF_KERNPROC(bp);
	bp->b_iooffset = dbtob(bp->b_blkno);
	VOP_STRATEGY(bp->b_vp, bp);

	if((oldflags & B_ASYNC) == 0) {
		int rtval = bufwait(bp);

		if (oldflags & B_DELWRI) {
			s = splbio();
			reassignbuf(bp, bp->b_vp);
			splx(s);
		}

		brelse(bp);
		return (rtval);
	}

	return (0);
}
