/*
 * Copyright (c) 2000-2003 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * Copyright (c) 1999-2003 Apple Computer, Inc.  All Rights Reserved.
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*
 * 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 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
 * FreeBSD-Id: nfs_vnops.c,v 1.72 1997/11/07 09:20:48 phk Exp $
 */

/* XXX - copyrights */

#include <string.h>

/*
 * vnode op calls for Sun NFS version 2 and 3
 */
#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/malloc.h>
#include <sys/mbuf.h>
#include <sys/conf.h>
#include <sys/namei.h>
#include <sys/vnode.h>
#include <sys/dirent.h>
#include <sys/fcntl.h>
#include <sys/lockf.h>
#include <sys/ubc.h>
#include <sys/signalvar.h>

#include <vfs/vfs_support.h>

#include <sys/vm.h>
#include <machine/spl.h>
#include <vm/vm_pageout.h>

#include <sys/time.h> 
#include <kern/clock.h>

#include <miscfs/fifofs/fifo.h>
void fifo_printinfo(struct vnode *); /* XXX */
#include <miscfs/specfs/specdev.h>

#include <rpc/rpcclnt.h>	/* XXX */
#include <nfs/rpcv2.h>
#include <nfs/nfsproto.h>
#include <nfs/nfs.h>
#include <nfs/nfsnode.h>
#include <nfs/nfsmount.h>
#include <nfs/nfs_lock.h>	/* XXX */
#include <nfs/xdr_subs.h>
#include <nfs/nfsm_subs.h>
#include <nfs/nqnfs.h>
#include <nfs/nfs_socket.h>

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

#include <kern/task.h>
#include <kern/sched_prim.h>

#include <sys/kdebug.h>

void vpwakeup(struct vnode *);

#define FSDBG(A, B, C, D, E) \
	KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, (A))) | DBG_FUNC_NONE, \
		(int)(B), (int)(C), (int)(D), (int)(E), 0)
#define FSDBG_TOP(A, B, C, D, E) \
	KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, (A))) | DBG_FUNC_START, \
		(int)(B), (int)(C), (int)(D), (int)(E), 0)
#define FSDBG_BOT(A, B, C, D, E) \
	KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, (A))) | DBG_FUNC_END, \
		(int)(B), (int)(C), (int)(D), (int)(E), 0)

#define	TRUE	1
#define	FALSE	0

#define NFS_FREE_PNBUF(CNP) \
	do { \
		char *tmp = (CNP)->cn_pnbuf; \
		(CNP)->cn_pnbuf = NULL; \
		(CNP)->cn_flags &= ~HASBUF; \
		FREE_ZONE(tmp, (CNP)->cn_pnlen, M_NAMEI); \
	} while (0)

/*
 * Global variables
 */
extern u_long nfs_true, nfs_false;

extern nfstype nfsv3_type[9];
/* XXXMARIUS: name collision */
struct proc *nfs_iodwant_nfsx[NFS_MAXASYNCDAEMON];
struct nfsmount *nfs_iodmount_nfsx[NFS_MAXASYNCDAEMON];
int nfs_numasync_nfsx = 0;
extern struct nfsstats nfsstats_nfsx;
#define nfsstats nfsstats_nfsx

int nfs_ioddelwri = 0;
#define	DIRHDSIZ	(sizeof (struct dirent) - (MAXNAMLEN + 1))

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

/* 
 * the following are needed only by nfs_pageout to know how to handle errors
 * see nfs_pageout comments on explanation of actions.
 * the errors here are copied from errno.h and errors returned by servers
 * are expected to match the same numbers here. If not, our actions maybe
 * erroneous.
 */
enum actiontype {NOACTION, DUMP, DUMPANDLOG, RETRY, RETRYWITHSLEEP, SEVER};

static int errorcount[ELAST+1]; /* better be zeros when initialized */

static const short errortooutcome[ELAST+1] = {
	NOACTION,
	DUMP,			/* EPERM	1	Operation not permitted */
	DUMP,			/* ENOENT	2	No such file or directory */
	DUMPANDLOG,		/* ESRCH	3	No such process */
	RETRY,			/* EINTR 	4	Interrupted system call */
	DUMP,			/* EIO		5	Input/output error */
	DUMP,			/* ENXIO	6	Device not configured */
	DUMPANDLOG,		/* E2BIG	7	Argument list too long */
	DUMPANDLOG,		/* ENOEXEC	8	Exec format error */
	DUMPANDLOG,		/* EBADF	9	Bad file descriptor */
	DUMPANDLOG,		/* ECHILD	10	No child processes */
	DUMPANDLOG,		/* EDEADLK	11	Resource deadlock avoided - was EAGAIN */
	RETRY,			/* ENOMEM	12	Cannot allocate memory */
	DUMP,			/* EACCES	13	Permission denied */
	DUMPANDLOG,		/* EFAULT	14	Bad address */
	DUMPANDLOG,		/* ENOTBLK	15	POSIX - Block device required */
	RETRY,			/* EBUSY	16	Device busy */
	DUMP,			/* EEXIST	17	File exists */
	DUMP,			/* EXDEV	18	Cross-device link */
	DUMP,			/* ENODEV	19	Operation not supported by device */
	DUMP,			/* ENOTDIR	20	Not a directory */
	DUMP,			/* EISDIR 	21	Is a directory */
	DUMP,			/* EINVAL	22	Invalid argument */
	DUMPANDLOG,		/* ENFILE	23	Too many open files in system */
	DUMPANDLOG,		/* EMFILE	24	Too many open files */
	DUMPANDLOG,		/* ENOTTY	25	Inappropriate ioctl for device */
	DUMPANDLOG,		/* ETXTBSY	26	Text file busy - POSIX */
	DUMP,			/* EFBIG	27	File too large */
	DUMP,			/* ENOSPC	28	No space left on device */
	DUMPANDLOG,		/* ESPIPE	29	Illegal seek */
	DUMP,			/* EROFS	30	Read-only file system */
	DUMP,			/* EMLINK	31	Too many links */
	RETRY,			/* EPIPE	32	Broken pipe */
	/* math software */
	DUMPANDLOG,		/* EDOM				33	Numerical argument out of domain */
	DUMPANDLOG,		/* ERANGE			34	Result too large */
	RETRY,			/* EAGAIN/EWOULDBLOCK	35	Resource temporarily unavailable */
	DUMPANDLOG,		/* EINPROGRESS		36	Operation now in progress */
	DUMPANDLOG,		/* EALREADY			37	Operation already in progress */
	/* ipc/network software -- argument errors */
	DUMPANDLOG,		/* ENOTSOC			38	Socket operation on non-socket */
	DUMPANDLOG,		/* EDESTADDRREQ		39	Destination address required */
	DUMPANDLOG,		/* EMSGSIZE			40	Message too long */
	DUMPANDLOG,		/* EPROTOTYPE		41	Protocol wrong type for socket */
	DUMPANDLOG,		/* ENOPROTOOPT		42	Protocol not available */
	DUMPANDLOG,		/* EPROTONOSUPPORT	43	Protocol not supported */
	DUMPANDLOG,		/* ESOCKTNOSUPPORT	44	Socket type not supported */
	DUMPANDLOG,		/* ENOTSUP			45	Operation not supported */
	DUMPANDLOG,		/* EPFNOSUPPORT		46	Protocol family not supported */
	DUMPANDLOG,		/* EAFNOSUPPORT		47	Address family not supported by protocol family */
	DUMPANDLOG,		/* EADDRINUSE		48	Address already in use */
	DUMPANDLOG,		/* EADDRNOTAVAIL	49	Can't assign requested address */
	/* ipc/network software -- operational errors */
	RETRY,			/* ENETDOWN			50	Network is down */
	RETRY,			/* ENETUNREACH		51	Network is unreachable */
	RETRY,			/* ENETRESET		52	Network dropped connection on reset */
	RETRY,			/* ECONNABORTED		53	Software caused connection abort */
	RETRY,			/* ECONNRESET		54	Connection reset by peer */
	RETRY,			/* ENOBUFS			55	No buffer space available */
	RETRY,			/* EISCONN			56	Socket is already connected */
	RETRY,			/* ENOTCONN			57	Socket is not connected */
	RETRY,			/* ESHUTDOWN		58	Can't send after socket shutdown */
	RETRY,			/* ETOOMANYREFS		59	Too many references: can't splice */
	RETRY,			/* ETIMEDOUT		60	Operation timed out */
	RETRY,			/* ECONNREFUSED		61	Connection refused */

	DUMPANDLOG,		/* ELOOP			62	Too many levels of symbolic links */
	DUMP,			/* ENAMETOOLONG		63	File name too long */
	RETRY,			/* EHOSTDOWN		64	Host is down */ 
	RETRY,			/* EHOSTUNREACH		65	No route to host */
	DUMP,			/* ENOTEMPTY		66	Directory not empty */
	/* quotas & mush */     
	DUMPANDLOG,		/* PROCLIM			67	Too many processes */
	DUMPANDLOG,		/* EUSERS			68	Too many users */
	DUMPANDLOG,		/* EDQUOT			69	Disc quota exceeded */   
	/* Network File System */
	DUMP,			/* ESTALE			70	Stale NFS file handle */
	DUMP,			/* EREMOTE			71	Too many levels of remote in path */
	DUMPANDLOG,		/* EBADRPC			72	RPC struct is bad */
	DUMPANDLOG,		/* ERPCMISMATCH		73	RPC version wrong */
	DUMPANDLOG,		/* EPROGUNAVAIL		74	RPC prog. not avail */
	DUMPANDLOG,		/* EPROGMISMATCH	75	Program version wrong */
	DUMPANDLOG,		/* EPROCUNAVAIL		76	Bad procedure for program */

	DUMPANDLOG,		/* ENOLCK			77	No locks available */
	DUMPANDLOG,		/* ENOSYS			78	Function not implemented */
	DUMPANDLOG,		/* EFTYPE			79	Inappropriate file type or format */  
	DUMPANDLOG,		/* EAUTH			80	Authentication error */
	DUMPANDLOG,		/* ENEEDAUTH		81	Need authenticator */
	/* Intelligent device errors */
	DUMPANDLOG,		/* EPWROFF			82	Device power is off */
	DUMPANDLOG,		/* EDEVERR			83	Device error, e.g. paper out */
	DUMPANDLOG,		/* EOVERFLOW		84	Value too large to be stored in data type */
	/* Program loading errors */
	DUMPANDLOG,		/* EBADEXEC			85	Bad executable */
	DUMPANDLOG,		/* EBADARCH			86	Bad CPU type in executable */
	DUMPANDLOG,		/* ESHLIBVERS		87	Shared library version mismatch */
	DUMPANDLOG,		/* EBADMACHO		88	Malformed Macho file */
};

static short
nfs_pageouterrorhandler(error)
	int error;
{
	if (error > ELAST) 
		return(DUMP);
	else 
		return(errortooutcome[error]);
}

/* XXX - nfsx_open() */

/*
 * 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.
 * for NQNFS         - do nothing now, since 2 is dealt with via leases and
 *                     1 should be dealt with via an fsync() system call for
 *                     cases where write errors are important.
 */
/* ARGSUSED */
int
nfsx_close(ap)
	struct vop_close_args /* {
		struct vnodeop_desc *a_desc;
		struct vnode *a_vp;
		int  a_fflag;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;
	register struct nfsnode *np = VTONFS(vp);
	struct nfsmount *nmp;
	int error = 0;

	if (NFS_ISV3(vp))
		printf("closing v3node\n");

	nmp = VFSTONFS(vp->v_mount);
	if (nmp == NULL)
		return (ENXIO);

	if (vp->v_type == VREG) {
#if DIAGNOSTIC
	    register struct sillyrename *sp = np->n_sillyrename;
	    if (sp)
                kprintf("nfsx_close: %s, dvp=%x, vp=%x, ap=%x, np=%x, sp=%x\n",
                	&sp->s_name[0], (unsigned)(sp->s_dvp), (unsigned)vp,
                	(unsigned)ap, (unsigned)np, (unsigned)sp);
#endif

	    if ((nmp->nm_flag & NFSMNT_NQNFS) == 0 &&
		(np->n_flag & NMODIFIED)) {
		printf("MARIUS: in close, also flushing...\n");
		int getlock = !VOP_ISLOCKED(vp);
		if (getlock) {
			error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, ap->a_p);
			if (!error && !VFSTONFS(vp->v_mount)) {
				VOP_UNLOCK(vp, 0, ap->a_p);
				error = ENXIO;
			}
			if (error)
				return (error);
		}
		if (NFS_ISV3(vp)) {
		    error = nfs_flush(vp, ap->a_cred, MNT_WAIT, ap->a_p, 1);
                    /*
                     * We cannot clear the NMODIFIED bit in np->n_flag due to
                     * potential races with other processes
		     * NMODIFIED is a hint
                     */
		    /* np->n_flag &= ~NMODIFIED; */
		} else {
		    error = nfs_vinvalbuf(vp, V_SAVE, ap->a_cred, ap->a_p, 1);
		}
		np->n_xid = 0;
		if (getlock)
			VOP_UNLOCK(vp, 0, ap->a_p);
	    }
	} else {
		printf("not regular file\n");
	}

	/* XXXMARIUS lock */
	if (NFSHASOP(nmp, closerpc))
		error = NFSOP(nmp, closerpc)(vp, ap->a_cred,
		    ap->a_p, ap->a_fflag);

	if (np->n_flag & NWRITEERR) {
		np->n_flag &= ~NWRITEERR;
		error = np->n_error;
	}

	/* XXXMARIUS debug. */
	if (VOP_ISLOCKED(vp)) {
		printf("vnode locked, unlocking.\n");
		VOP_UNLOCK(vp, 0, ap->a_p);
	} else
		printf("vnode not locked.\n");

	return (error);
}

/*
 * nfs setattr call.
 */
int
nfsx_setattr(ap)
	struct vop_setattr_args /* {
		struct vnodeop_desc *a_desc;
		struct vnode *a_vp;
		struct vattr *a_vap;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;
	register struct nfsnode *np = VTONFS(vp);
	register 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

#ifdef XXX /* enable this code soon! (but test it first) */
	/*		  
	 * Setting of flags is not supported.
	 */
	if (vap->va_flags != VNOVAL)
		return (EOPNOTSUPP);
#endif

	/*
	 * 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 == (u_short)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);
			FSDBG_TOP(512, np->n_size, vap->va_size,
				  np->n_vattr.va_size, np->n_flag);
			if (np->n_flag & NMODIFIED) {
 				if (vap->va_size == 0)
 					error = nfs_vinvalbuf(vp, 0,
 						ap->a_cred, ap->a_p, 1);
 				else
 					error = nfs_vinvalbuf(vp, V_SAVE,
 						ap->a_cred, ap->a_p, 1);
	 			if (error) {
					printf("nfsx_setattr: nfs_vinvalbuf %d\n", error);
					FSDBG_BOT(512, np->n_size, vap->va_size,
						  np->n_vattr.va_size, -1);
 					return (error);
				}
			} else if (np->n_size > vap->va_size) { /* shrinking? */
				daddr_t obn, bn;
				int biosize;
				struct nfsbuf *bp;

				biosize = vp->v_mount->mnt_stat.f_iosize;
				obn = (np->n_size - 1) / biosize;
				bn = vap->va_size / biosize; 
				for ( ; obn >= bn; obn--)
				    if (nfs_buf_incore(vp, obn)) {
					bp = nfs_buf_get(vp, obn, biosize, 0, BLK_READ);
					if (!bp)
						continue;
					if (obn == bn) {
					    int neweofoff, mustwrite;
					    mustwrite = 0;
					    neweofoff = vap->va_size - NBOFF(bp);
					    /* check for any dirty data before the new EOF */
					    if (bp->nb_dirtyend && bp->nb_dirtyoff < neweofoff) {
						/* clip dirty range to EOF */
						if (bp->nb_dirtyend > neweofoff)
						    bp->nb_dirtyend = neweofoff;
						mustwrite++;
					    }
					    bp->nb_dirty &= (1 << round_page_32(neweofoff)/PAGE_SIZE) - 1;
					    if (bp->nb_dirty)
						mustwrite++;
					    if (mustwrite) {
						/* gotta write out dirty data before invalidating */
						/* (NB_STABLE indicates that data writes should be FILESYNC) */
						/* (NB_NOCACHE indicates buffer should be discarded) */
						CLR(bp->nb_flags, (NB_DONE | NB_ERROR | NB_INVAL | NB_ASYNC | NB_READ));
						SET(bp->nb_flags, NB_STABLE | NB_NOCACHE);
						/*
						 * NFS has embedded ucred so crhold() risks zone corruption
						 */
						if (bp->nb_wcred == NOCRED)
						    bp->nb_wcred = crdup(ap->a_cred);
						error = nfs_buf_write(bp);
						// Note: bp has been released
						if (error) {
						    FSDBG(512, bp, 0xd00dee, 0xbad, error);
						    np->n_error = error;
						    np->n_flag |= NWRITEERR;
						    error = 0;
						}
						bp = NULL;
					    }
					}
					if (bp) {
					    FSDBG(512, bp, bp->nb_flags, 0, obn);
					    SET(bp->nb_flags, NB_INVAL);
					    nfs_buf_release(bp);
					}
				    }
			}
 			tsize = np->n_size;
			np->n_size = np->n_vattr.va_size = vap->va_size;
			ubc_setsize(vp, (off_t)vap->va_size); /* XXX error? */
  		};
  	} else if ((vap->va_mtime.tv_sec != VNOVAL ||
		    vap->va_atime.tv_sec != VNOVAL) &&
		   (np->n_flag & NMODIFIED) && vp->v_type == VREG) {
		error = nfs_vinvalbuf(vp, V_SAVE, ap->a_cred, ap->a_p, 1);
		if (error == EINTR)
			return (error);
	}

	error = NFSOP(nmp, setattrrpc)(vp, vap, ap->a_cred, ap->a_p);
	FSDBG_BOT(512, np->n_size, vap->va_size, np->n_vattr.va_size, error);
	if (error && vap->va_size != VNOVAL) {
		/* make every effort to resync file size w/ server... */
		int err = 0; /* preserve "error" for return */

		printf("nfsx_setattr: nfs_setattrrpc %d\n", error);
		np->n_size = np->n_vattr.va_size = tsize;
		ubc_setsize(vp, (off_t)np->n_size); /* XXX check error */
		vap->va_size = tsize;
		err = NFSOP(nmp, setattrrpc)(vp, vap, ap->a_cred, ap->a_p);
		if (err)
			printf("nfsx_setattr1: nfs_setattrrpc %d\n", err);
	}
	return (error);
}

/*
 * nfs read call.
 * Just call nfsx_bioread() to do the work.
 */
int
nfsx_read(ap)
	struct vop_read_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		int  a_ioflag;
		struct ucred *a_cred;
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;

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


/*
 * nfs readlink call
 */
int
nfsx_readlink(ap)
	struct vop_readlink_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		struct ucred *a_cred;
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;

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

/*
 * nfs mknod vop
 * just call nfs_mknodrpc() to do the work.
 */
/* ARGSUSED */
int
nfsx_mknod(ap)
	struct vop_mknod_args /* {
		struct vnode *a_dvp;
		struct vnode **a_vpp;
		struct componentname *a_cnp;
		struct vattr *a_vap;
	} */ *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);
	if (!error && newvp)
		vput(newvp);
	*ap->a_vpp = 0;
	return (error);
}

static u_long create_verf;


/*
 * 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 nfs_sillyrename() to set it up
 *     else
 *	  do the remove rpc
 */
int
nfsx_remove(ap)
	struct vop_remove_args /* {
		struct vnodeop_desc *a_desc;
		struct vnode * a_dvp;
		struct vnode * a_vp;
		struct componentname * a_cnp;
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;
	register struct vnode *dvp = ap->a_dvp;
	register struct componentname *cnp = ap->a_cnp;
	register struct nfsnode *np = VTONFS(vp);
	int error = 0, gofree = 0;
	struct vattr vattr;
	struct nfsmount *nmp = VFSTONFS(dvp->v_mount);

#if DIAGNOSTIC
	if ((cnp->cn_flags & HASBUF) == 0)
		panic("nfsx_remove: no name");
	if (vp->v_usecount < 1)
		panic("nfsx_remove: bad v_usecount");
#endif

	if (UBCISVALID(vp)) {
		/* regular files */
		if (UBCINFOEXISTS(vp))
			gofree = (ubc_isinuse(vp, 1)) ? 0 : 1;
		else {
			/* dead or dying vnode.With vnode locking panic instead of error */
			vput(dvp);
			vput(vp);
			NFS_FREE_PNBUF(cnp);
			return (EIO);
		}
	} else {
		/* UBC not in play */
		if (vp->v_usecount == 1)
			gofree = 1;
	}
	if ((ap->a_cnp->cn_flags & NODELETEBUSY) && !gofree) {
		/* Caller requested Carbon delete semantics, but file is busy */
		vput(dvp);
		vput(vp);
		NFS_FREE_PNBUF(cnp);
		return (EBUSY);
	}
	if (gofree || (np->n_sillyrename &&
		VOP_GETATTR(vp, &vattr, cnp->cn_cred, cnp->cn_proc) == 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 = nfs_vinvalbuf(vp, 0, cnp->cn_cred, cnp->cn_proc, 1);
		np->n_size = 0;
		ubc_setsize(vp, (off_t)0); /* XXX check error */
		/* Do the rpc */
		if (error != EINTR)
			error = NFSOP(nmp, removerpc)(dvp, cnp->cn_nameptr,
			    cnp->cn_namelen, cnp->cn_cred, cnp->cn_proc);

		/*
		 * 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;
		if (!error) {
			/*
			 * remove nfsnode from hash now so we can't accidentally find it
			 * again if another object gets created with the same filehandle
			 * before this vnode gets reclaimed
			 */
			LIST_REMOVE(np, n_hash);
			np->n_flag &= ~NHASHED;
		}
	} else if (!np->n_sillyrename) {
		error = nfsx_sillyrename(dvp, vp, cnp);
	}
	np->n_xid = 0;
	vput(dvp);

	VOP_UNLOCK(vp, 0, cnp->cn_proc);
	NFS_FREE_PNBUF(cnp);
	ubc_uncache(vp);
	vrele(vp);

	return (error);
}

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

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

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

#if DIAGNOSTIC
	if ((tcnp->cn_flags & HASBUF) == 0 ||
	    (fcnp->cn_flags & HASBUF) == 0)
		panic("nfsx_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;
		if (tvp)
			VOP_UNLOCK(tvp, 0, tcnp->cn_proc);
		goto out;
	}

	/*
	 * 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.
	 * Don't sillyrename if source and target are same vnode (hard
	 * links or case-variants)
	 */
	if (tvp && tvp != fvp) {
		if (UBCISVALID(tvp)) {
			/* regular files */
			if (UBCINFOEXISTS(tvp))
				inuse = (ubc_isinuse(tvp, 1)) ? 1 : 0;
			else {
				/* dead or dying vnode.With vnode locking panic instead of error */
				error = EIO;
				VOP_UNLOCK(tvp, 0, tcnp->cn_proc);
				goto out;  
			}
		} else {
			/* UBC not in play */
			if (tvp->v_usecount > 1)
				inuse = 1;
		}
	}
	if (inuse && !VTONFS(tvp)->n_sillyrename && tvp->v_type != VDIR) {
		if  ((error = nfsx_sillyrename(tdvp, tvp, tcnp))) {
			/* sillyrename failed. Instead of pressing on, return error */
			VOP_UNLOCK(tvp, 0, tcnp->cn_proc);
			goto out; /* should not be ENOENT. */
		} else {
			/* sillyrename succeeded.*/
			VOP_UNLOCK(tvp, 0, tcnp->cn_proc);
			ubc_uncache(tvp); /* get the nfs turd file to disappear */
			vrele(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_proc);

	if (!error && tvp && tvp != fvp && !VTONFS(tvp)->n_sillyrename) {
		/*
		 * remove nfsnode from hash now so we can't accidentally find it
		 * again if another object gets created with the same filehandle
		 * before this vnode gets reclaimed
		 */
		LIST_REMOVE(VTONFS(tvp), n_hash);
		VTONFS(tvp)->n_flag &= ~NHASHED;
	}

	if (fvp->v_type == VDIR) {
		if (tvp != NULL && tvp->v_type == VDIR) {
			cache_purge(tdvp);
			if (tvp == tdvp) 
				purged = 1;
		}
		cache_purge(fdvp);
	}
	
	cache_purge(fvp);
	if (tvp) {
		if (!purged)
			cache_purge(tvp);
		VOP_UNLOCK(tvp, 0, tcnp->cn_proc);
		ubc_uncache(tvp); /* get the nfs turd file to disappear */
	}
	
out:
	if (tdvp == tvp)
		vrele(tdvp);
	else
		vput(tdvp);
	if (tvp)
		vrele(tvp); /* already unlocked */
	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(sdvp, scnp, sp)
	struct vnode *sdvp;
	struct componentname *scnp;
	register 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_proc));

}

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

	printf("READDIR!\n");

	if (vp->v_type != VDIR)
		return (EPERM);

	printf("READDIR!(2)\n");

	/*
	 * 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 (VFSTONFS(vp->v_mount)->nm_flag & NFSMNT_NQNFS) {
			if (NQNFS_CKCACHABLE(vp, ND_READ)) {
				nfsstats.direofcache_hits++;
				return (0);
			}
		} else if (!VOP_GETATTR(vp, &vattr, ap->a_cred, uio->uio_procp)) {
			if (np->n_mtime == vattr.va_mtime.tv_sec) {
				nfsstats.direofcache_hits++;
				return (0);
			}
			/* directory changed, purge any name cache entries */
			cache_purge(vp);
		}
	}

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

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

int				/* static? */
nfsx_lookitup(dvp, name, len, cred, procp, npp)
	register struct vnode *dvp;
	char *name;
	int len;
	struct ucred *cred;
	struct proc *procp;
	struct nfsnode **npp;
{
	struct vnode *newvp = (struct vnode *)0;
	struct nfsnode *np, *dnp = VTONFS(dvp);
	int error = 0, fhlen;
	nfsfh_t *nfhp;
	struct nfsmount *nmp = VFSTONFS(dvp->v_mount);
	u_char stp[NFSX_STATESIZ];	
	struct componentname cn;

	printf("nfsx_lookITup\n");

	if (nmp == NULL)
		return (ENXIO);

	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_ZONE((caddr_t)np->n_fhp,
					np->n_fhsize, M_NFSBIGFH);
			np->n_fhp = &np->n_fh;
		    } else if (np->n_fhsize <= NFS_SMALLFH && fhlen>NFS_SMALLFH)
			MALLOC_ZONE(np->n_fhp, nfsfh_t *,
						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 = nfs_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';
		}


		/* XXX */
		NFSOP(nmp, lookuploadattr)(newvp, dvp, stp);

/* 		if (v3) { */
/* 			nfsm_postop_attr(newvp, attrflag, &xid); */
/* 			if (!attrflag && *npp == NULL) { */
/* 				m_freem(mrep); */
/* 				if (newvp == dvp) */
/* 					vrele(newvp); */
/* 				else */
/* 					vput(newvp); */
/* 				return (ENOENT); */
/* 			} */
/* 		} else */
/* 			nfsm_loadattr(newvp, (struct vattr *)0, &xid); */
	}

	if (npp && *npp == NULL) {
		if (error) {
			if (newvp) {
				if (newvp == dvp)
					vrele(newvp);
				else
					vput(newvp);
			}
		} else
			*npp = np;
	}
	return (error);
}


int
nfsx_lookup(ap)
	struct vop_lookup_args /* {
		struct vnodeop_desc *a_desc;
		struct vnode *a_dvp;
		struct vnode **a_vpp;
		struct componentname *a_cnp;
	} */ *ap;
{
	register struct componentname *cnp = ap->a_cnp;
	register struct vnode *dvp = ap->a_dvp;
	register struct vnode **vpp = ap->a_vpp;
	register int flags = cnp->cn_flags;
	register struct vnode *newvp;
	nfsfh_t *fhp;
	struct nfsnode *np;
	int lockparent, wantparent, error = 0, fhsize;
	struct proc *p = cnp->cn_proc;
	int unlockdvp = 0;
	struct vattr vattr;
	u_char stp[NFSX_STATESIZ];
	struct nfsmount *nmp = VFSTONFS(dvp->v_mount);

	printf("XXXMARIUS: nfsx_lookup\n");

	if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
		return (EROFS);
	*vpp = NULLVP;
	if (dvp->v_type != VDIR)
		return (ENOTDIR);

	lockparent = flags & LOCKPARENT;
	wantparent = flags & (LOCKPARENT|WANTPARENT);
	np = VTONFS(dvp);

	/* if directory has changed, purge any name cache entries */
	if (!VOP_GETATTR(dvp, &vattr, cnp->cn_cred, p) &&
	    (np->n_mtime != vattr.va_mtime.tv_sec))
		cache_purge(dvp);

	if ((error = cache_lookup(dvp, vpp, cnp)) && error != ENOENT) {
		int vpid;

		newvp = *vpp;
		vpid = newvp->v_id;

		/*
		 * See the comment starting `Step through' in ufs/ufs_lookup.c
		 * for an explanation of the locking protocol
		 */

		/*
		 * Note: we need to make sure to get a lock/ref on newvp
		 * before we possibly go off to the server in VOP_ACCESS.
		 */
		if (dvp == newvp) {
			VREF(newvp);
			error = 0;
		} else if (flags & ISDOTDOT) {
			VOP_UNLOCK(dvp, 0, p);
			error = vget(newvp, LK_EXCLUSIVE, p);
			if (!error)
				error = vn_lock(dvp, LK_EXCLUSIVE, p);
		} else {
			error = vget(newvp, LK_EXCLUSIVE, p);
			if (error)
				VOP_UNLOCK(dvp, 0, p);
		}

		if (error)
			goto cache_lookup_out;

		if ((error = VOP_ACCESS(dvp, VEXEC, cnp->cn_cred, p))) {
			if (dvp == newvp)
				vrele(newvp);
			else
				vput(newvp);
			*vpp = NULLVP;
			printf("error return 1\n");
			goto error_return;
		}

		if ((dvp != newvp) && (!lockparent || !(flags & ISLASTCN)))
			VOP_UNLOCK(dvp, 0, p);

		if (vpid == newvp->v_id) {
			if (!VOP_GETATTR(newvp, &vattr, cnp->cn_cred, p)
				&& vattr.va_ctime.tv_sec == VTONFS(newvp)->n_ctime) {
				nfsstats.lookupcache_hits++;
				if (cnp->cn_nameiop != LOOKUP && (flags & ISLASTCN))
					cnp->cn_flags |= SAVENAME;
				error = 0; /* ignore any from VOP_GETATTR  */
			printf("error return 2\n");
				goto error_return;
			}
			cache_purge(newvp);
		}
		vput(newvp);
		if ((dvp != newvp) && lockparent && (flags & ISLASTCN))
			VOP_UNLOCK(dvp, 0, p);
cache_lookup_out:
		error = vn_lock(dvp, LK_EXCLUSIVE, p);
		*vpp = NULLVP;
		if (error) {
			printf("error return 3\n");
			goto error_return;
		}
	}

	error = 0;
	newvp = NULLVP;
	nfsstats.lookupcache_misses++;

	/* XXX - need to keep state across this... */
	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)) {
			error = EISDIR;
			printf("error return 4\n");
			goto error_return;
		}
		if ((error = nfs_nget(dvp->v_mount, fhp, fhsize, &np))) {
			printf("error return 5\n");
			goto error_return;
		}
		newvp = NFSTOV(np);

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

		*vpp = newvp;
		cnp->cn_flags |= SAVENAME;
		if (!lockparent)
			VOP_UNLOCK(dvp, 0, p);
		error = 0;
			printf("error return 6\n");
		goto error_return;
	}

	if (NFS_CMPFH(np, fhp, fhsize)) {
		VREF(dvp);
		newvp = dvp;
	} else if (flags & ISDOTDOT) {
		/* XXX - figure this one out.  first of all, ISDOTDOT, and n_dvp */

		VOP_UNLOCK(dvp, 0, p);
		error = nfs_nget(dvp->v_mount, fhp, fhsize, &np);
		if (error) {
			vn_lock(dvp, LK_EXCLUSIVE + LK_RETRY, p);
			printf("error return 7\n");
			goto error_return;
		}
		newvp = NFSTOV(np);
		if (!lockparent || !(flags & ISLASTCN))
			unlockdvp = 1; /* keep dvp locked until after postops */
		if ((error = vn_lock(dvp, LK_EXCLUSIVE, p))) {
		    	vput(newvp);
			printf("error return 8\n");
			goto error_return;
		}
	} else {
		if ((error = nfs_nget(dvp->v_mount, fhp, fhsize, &np))) {
			printf("error return 9\n");
			goto error_return;
		}
		if (!lockparent || !(flags & ISLASTCN))
			unlockdvp = 1; /* keep dvp locked until after postops */
		newvp = NFSTOV(np);

		/* For v4 */
		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';
		/* Loadattrcache; covered by the NFSOP() later. */
	}

	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 (unlockdvp) {
		printf("unlockdvp\n");
		VOP_UNLOCK(dvp, 0, p);
		unlockdvp = 0;
	} else
		printf("!unlockdvp\n");		
	if (error) {
		if (newvp != NULLVP) {
			if (newvp == dvp)
				vrele(newvp);
			else
				vput(newvp);
			*vpp = NULLVP;
		}
		if ((cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME) &&
		    (flags & ISLASTCN) && error == ENOENT) {
			if (dvp->v_mount && (dvp->v_mount->mnt_flag & MNT_RDONLY))
				error = EROFS;
			else
				error = EJUSTRETURN;
			if (!lockparent)
				VOP_UNLOCK(dvp, 0, p);
		}
		if (cnp->cn_nameiop != LOOKUP && (flags & ISLASTCN))
			cnp->cn_flags |= SAVENAME;
	}
error_return:

	printf("error_return unlockdvp (%d): %d\n", error, unlockdvp);
	if (unlockdvp)
		VOP_UNLOCK(dvp, 0, p);
	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...
 */

/* format of "random" names and next name to try */
/* (note: shouldn't exceed size of sillyrename.s_name) */
static char sillyrename_name[] = ".nfsAAA%04x4.4";

int
nfsx_sillyrename(dvp, vp, cnp)
	struct vnode *dvp, *vp;
	struct componentname *cnp;
{
	register struct sillyrename *sp;
	struct nfsnode *np;
	int error;
	short pid;
	struct ucred *cred;
	int i, j, k;

	cache_purge(dvp);
	np = VTONFS(vp);
#if DIAGNOSTIC
	if (vp->v_type == VDIR)
		panic("nfsx_sillyrename: dir");
#endif
	MALLOC_ZONE(sp, struct sillyrename *,
			sizeof (struct sillyrename), M_NFSREQ, M_WAITOK);
	sp->s_cred = crdup(cnp->cn_cred);
	sp->s_dvp = dvp;
	VREF(dvp);

	/* Fudge together a funny name */
	pid = cnp->cn_proc->p_pid;
	sp->s_namlen = sprintf(sp->s_name, sillyrename_name, pid);

	/* Try lookitups until we get one that isn't there */
	i = j = k = 0;
	while (nfsx_lookitup(dvp, sp->s_name, sp->s_namlen, sp->s_cred,
		cnp->cn_proc, (struct nfsnode **)0) == 0) {
		if (sp->s_name[4]++ >= 'z')
			sp->s_name[4] = 'A';
		if (++i > ('z' - 'A' + 1)) {
			i = 0;
			if (sp->s_name[5]++ >= 'z')
				sp->s_name[5] = 'A';
			if (++j > ('z' - 'A' + 1)) {
				j = 0;
				if (sp->s_name[6]++ >= 'z')
					sp->s_name[6] = 'A';
				if (++k > ('z' - 'A' + 1)) {
					error = EINVAL;
					goto bad;
				}
			}
		}
	}
	/* make note of next "random" name to try */
	if ((sillyrename_name[4] = (sp->s_name[4] + 1)) > 'z') {
		sillyrename_name[4] = 'A';
		if ((sillyrename_name[5] = (sp->s_name[5] + 1)) > 'z') {
			sillyrename_name[5] = 'A';
			if ((sillyrename_name[6] = (sp->s_name[6] + 1)) > 'z')
				sillyrename_name[6] = 'A';
		}
	}
	/* now, do the rename */
	if ((error = nfsx_renameit(dvp, cnp, sp)))
		goto bad;
	error = nfsx_lookitup(dvp, sp->s_name, sp->s_namlen, sp->s_cred,
		cnp->cn_proc, &np);
#if DIAGNOSTIC
	kprintf("sillyrename: %s, vp=%x, np=%x, dvp=%x\n",
		&sp->s_name[0], (unsigned)vp, (unsigned)np, (unsigned)dvp);
#endif
	np->n_sillyrename = sp;
	return (0);
bad:
	vrele(sp->s_dvp);
	cred = sp->s_cred;
	sp->s_cred = NOCRED;
	crfree(cred);
	FREE_ZONE((caddr_t)sp, sizeof (struct sillyrename), M_NFSREQ);
	return (error);
}

int
nfsx_bmap(ap)
        struct vop_bmap_args /* {
                struct vnode *a_vp;
                daddr_t  a_bn;
                struct vnode **a_vpp;
                daddr_t *a_bnp;
                int *a_runp;
                int *a_runb;
        } */ *ap;
{
        register struct vnode *vp = ap->a_vp;
        int devBlockSize = DEV_BSIZE;

        if (ap->a_vpp != NULL)
                *ap->a_vpp = vp;
        if (ap->a_bnp != NULL) {
                if (!vp->v_mount)
                        return (ENXIO);
                *ap->a_bnp = ap->a_bn * btodb(vp->v_mount->mnt_stat.f_iosize,
                                              devBlockSize);
        }
        if (ap->a_runp != NULL)
                *ap->a_runp = 0;
#ifdef notyet
        if (ap->a_runb != NULL)
                *ap->a_runb = 0;
#endif
        return (0);
}


/*
 * Mmap a file
 *
 * NB Currently unsupported.
 */
/* ARGSUSED */
int
nfsx_mmap(ap)
	struct vop_mmap_args /* {
		struct vnode *a_vp;
		int  a_fflags;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{

	return (EINVAL);
}

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

/* XXXMARIUS: name collision */
/* XXXMARIUS: i think this should actually be nfsx_....  it uses NFSOP */
int
nfs_flushcommits_nfsx(struct vnode *vp, struct proc *p)
{
	struct nfsnode *np = VTONFS(vp);
	struct nfsbuf *bp, *nbp;
	int i, s, error = 0, retv, bvecpos, wcred_set;
	u_quad_t off, endoff, toff;
	struct ucred* wcred;
	struct nfsbuf **bvec = NULL;
#define NFS_COMMITBVECSIZ	20
#define NFS_MAXCOMMITBVECSIZ	1024
	struct nfsbuf *bvec_on_stack[NFS_COMMITBVECSIZ];
	int bvecsize = NFS_MAXCOMMITBVECSIZ;
	struct nfsmount *nmp = VFSTONFS(vp->v_mount);

	FSDBG_TOP(557, vp, np, 0, 0);

	/*
	 * A nb_flags == (NB_DELWRI | NB_NEEDCOMMIT) block has been written to the
	 * server, but nas not been committed to stable storage on the server
	 * yet. The byte range is worked out for as many nfsbufs as we can handle
	 * and the commit rpc is done.
	 */
	if (np->n_dirtyblkhd.lh_first)
		np->n_flag |= NMODIFIED;

	off = (u_quad_t)-1;
	endoff = 0;
	bvecpos = 0;
	wcred_set = 0;

	if (!VFSTONFS(vp->v_mount)) {
		error = ENXIO;
		goto done;
	}
	if (!NFS_ISV3(vp)) {
		error = EINVAL;
		goto done;
	}
	s = splbio();

	/*
	 * 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
	 */
	MALLOC(bvec, struct nfsbuf **,
		       bvecsize * sizeof(struct nfsbuf *), M_TEMP,
		       M_NOWAIT);
	if (bvec == NULL) {
		bvec = bvec_on_stack;
		bvecsize = NFS_COMMITBVECSIZ;
	}
	for (bp = np->n_dirtyblkhd.lh_first; bp && bvecpos < bvecsize; bp = nbp) {
		nbp = bp->nb_vnbufs.le_next;

		if (((bp->nb_flags & (NB_BUSY | NB_DELWRI | NB_NEEDCOMMIT))
			!= (NB_DELWRI | NB_NEEDCOMMIT)))
			continue;

		nfs_buf_remfree(bp);
		SET(bp->nb_flags, NB_BUSY);
		/*
		 * we need a upl to see if the page has been
		 * dirtied (think mmap) since the unstable write, and
		 * also to prevent vm from paging it during our commit rpc
		 */
		if (!ISSET(bp->nb_flags, NB_PAGELIST)) {
			retv = nfs_buf_upl_setup(bp);
			if (retv) {
				/* unable to create upl */
				/* vm object must no longer exist */
				/* this could be fatal if we need */
				/* to write the data again, we'll see...  */
				printf("nfs_flushcommits: upl create failed %d\n", retv);
				bp->nb_valid = bp->nb_dirty = 0;
			}
		}
		nfs_buf_upl_check(bp);

		FSDBG(557, bp, bp->nb_flags, bp->nb_valid, bp->nb_dirty);
		FSDBG(557, bp->nb_validoff, bp->nb_validend,
		      bp->nb_dirtyoff, bp->nb_dirtyend);

		/*
		 * We used to check for dirty pages here; if there were any
		 * we'd abort the commit and force the entire buffer to be
		 * written again.
		 *
		 * Instead of doing that, we now go ahead and commit the dirty
		 * range, and then leave the buffer around with dirty pages
		 * that will be written out later.
		 */

		/* in case blocking calls were made, re-evaluate nbp */
		nbp = bp->nb_vnbufs.le_next;

		/*
		 * Work out if all buffers are using the same cred
		 * so we can deal with them all with one commit.
		 */
		if (wcred_set == 0) {
			wcred = bp->nb_wcred;
			if (wcred == NOCRED)
				panic("nfs: needcommit w/out wcred");
			wcred_set = 1;
		} else if ((wcred_set == 1) && crcmp(wcred, bp->nb_wcred)) {
			wcred_set = -1;
		}
		SET(bp->nb_flags, NB_WRITEINPROG);

		/*
		 * 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 = NBOFF(bp) + bp->nb_dirtyoff;
		if (toff < off)
			off = toff;
		toff += (u_quad_t)(bp->nb_dirtyend - bp->nb_dirtyoff);
		if (toff > endoff)
			endoff = toff;
	}
	splx(s);

	if (bvecpos == 0) {
		error = ENOBUFS;
		goto done;
	}

	/*
	 * 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_set == 1)
		retv = NFSOP(nmp, commit)(vp, off,
		    (int)(endoff - off), wcred, p);
	else {
		retv = 0;

		for (i = 0; i < bvecpos; i++) {
			off_t off, size;
			bp = bvec[i];
			off = NBOFF(bp) + bp->nb_dirtyoff;
			size = (u_quad_t)(bp->nb_dirtyend - bp->nb_dirtyoff);
			retv = NFSOP(nmp, commit)(vp, off,
			    (int)size, bp->nb_wcred, p);
			if (retv)
				break;
		}
	}
	if (retv == NFSERR_STALEWRITEVERF)
		nfs_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];
		FSDBG(557, bp, retv, bp->nb_flags, bp->nb_dirty);

		CLR(bp->nb_flags, (NB_NEEDCOMMIT | NB_WRITEINPROG));

		np->n_needcommitcnt--;
		CHECK_NEEDCOMMITCNT(np);

		if (retv) {
			nfs_buf_release(bp);
		} else {
			s = splbio();
			vp->v_numoutput++;

			if (ISSET(bp->nb_flags, NB_DELWRI)) {
				nfs_nbdwrite--;
				NFSBUFCNTCHK();
				wakeup((caddr_t)&nfs_nbdwrite);
			}
			CLR(bp->nb_flags, (NB_READ|NB_DONE|NB_ERROR|NB_DELWRI));
			/* if block still has dirty pages, we don't want it to */
			/* be released in nfs_buf_iodone().  So, don't set NB_ASYNC. */
			if (!bp->nb_dirty)
				SET(bp->nb_flags, NB_ASYNC);

			/* move to clean list */
			if (bp->nb_vnbufs.le_next != NFSNOLIST)
				LIST_REMOVE(bp, nb_vnbufs);
			LIST_INSERT_HEAD(&VTONFS(vp)->n_cleanblkhd, bp, nb_vnbufs);

			bp->nb_dirtyoff = bp->nb_dirtyend = 0;
			splx(s);

			nfs_buf_iodone(bp);
			if (bp->nb_dirty) {
				/* throw it back in as a delayed write buffer */
				CLR(bp->nb_flags, NB_DONE);
				nfs_buf_write_delayed(bp);
			}
		}
	}

done:
	if (bvec != NULL && bvec != bvec_on_stack)
		_FREE(bvec, M_TEMP);
	FSDBG_BOT(557, vp, np, 0, error);
	return (error);
}

/*
 * Flush all the blocks associated with a vnode.
 * 	Walk through the buffer pool and push any dirty pages
 *	associated with the vnode.
 */
int
nfs_flush(vp, cred, waitfor, p, commit)
	register struct vnode *vp;
	struct ucred *cred;
	int waitfor;
	struct proc *p;
	int commit;
{
	struct nfsnode *np = VTONFS(vp);
	struct nfsbuf *bp, *nbp;
	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
	int s, error = 0, error2, slptimeo = 0, slpflag = 0;
	int passone = 1;

	FSDBG_TOP(517, vp, np, waitfor, commit);

	if (!nmp) {
		error = ENXIO;
		goto done;
	}
	if (nmp->nm_flag & NFSMNT_INT)
		slpflag = PCATCH;
	if (!commit)
		passone = 0;

	/*
	 * On the first pass, commit all the bufs that can be.
	 * On the second pass, nfs_buf_write() is called to do the job.
	 */
again:
	FSDBG(518, np->n_dirtyblkhd.lh_first, np->n_flag, 0, 0);
	if (np->n_dirtyblkhd.lh_first)
		np->n_flag |= NMODIFIED;
	if (!VFSTONFS(vp->v_mount)) {
		error = ENXIO;
		goto done;
	}
	if (NFS_ISV3(vp) && commit) {
		/* loop while it looks like there are still buffers to be */
		/* commited and nfs_flushcommits() seems to be handling them. */
		while (np->n_needcommitcnt)
			if (nfs_flushcommits(vp, p))
				break;
	}

	/* Start/do any write(s) that are required. */
loop:
	s = splbio();
	for (bp = np->n_dirtyblkhd.lh_first; bp; bp = nbp) {
		nbp = bp->nb_vnbufs.le_next;
		if (ISSET(bp->nb_flags, NB_BUSY)) {
			FSDBG(524, bp, waitfor, passone, bp->nb_flags);
			if (waitfor != MNT_WAIT || passone)
				continue;
			SET(bp->nb_flags, NB_WANTED);
			error = tsleep((caddr_t)bp, slpflag | (PRIBIO + 1),
				       "nfsfsync", slptimeo);
			splx(s);
			if (error) {
				error2 = nfs_sigintr(VFSTONFS(vp->v_mount),
				    (struct nfsreq *)0, p);
				if (error2) {
					error = error2;
					goto done;
				}
				if (slpflag == PCATCH) {
					slpflag = 0;
					slptimeo = 2 * hz;
				}
			}
			goto loop;
		}
		if (!ISSET(bp->nb_flags, NB_DELWRI))
			panic("nfsx_fsync: not dirty");
		FSDBG(525, bp, passone, commit, bp->nb_flags);
		if ((passone || !commit) && ISSET(bp->nb_flags, NB_NEEDCOMMIT))
			continue;
		nfs_buf_remfree(bp);
		if (ISSET(bp->nb_flags, NB_ERROR)) {
			np->n_error = bp->nb_error ? bp->nb_error : EIO;
			np->n_flag |= NWRITEERR;
			nfs_buf_release(bp);
			continue;
		}
		if (passone || !commit)
			SET(bp->nb_flags, NB_BUSY|NB_ASYNC);
		else {
			/* the NB_STABLE forces this to be written FILESYNC */
			SET(bp->nb_flags, NB_BUSY|NB_ASYNC|NB_STABLE);
		}
		splx(s);
		nfs_buf_write(bp);
		goto loop;
	}
	splx(s);

	if (passone) {
		passone = 0;
		goto again;
	}

	if (waitfor == MNT_WAIT) {
		while (vp->v_numoutput) {
			vp->v_flag |= VBWAIT;
			error = tsleep((caddr_t)&vp->v_numoutput,
				slpflag | (PRIBIO + 1), "nfsfsync", slptimeo);
			if (error) {
				error2 = nfs_sigintr(VFSTONFS(vp->v_mount),
				    (struct nfsreq *)0, p);
			    if (error2) {
				error = error2;
				goto done;
			    }
			    if (slpflag == PCATCH) {
				slpflag = 0;
				slptimeo = 2 * hz;
			    }
			}
		}
		if (np->n_dirtyblkhd.lh_first && commit) {
			goto loop;
		}
	}
	FSDBG(526, np->n_flag, np->n_error, 0, 0);
	if (np->n_flag & NWRITEERR) {
		error = np->n_error;
		np->n_flag &= ~NWRITEERR;
	}
done:
	FSDBG_BOT(517, vp, np, error, 0);
	return (error);
}

/*
 * Return POSIX pathconf information applicable to nfs.
 *
 * The NFS V2 protocol doesn't support this, so just return EINVAL
 * for V2.
 */
/* ARGSUSED */
int
nfsx_pathconf(ap)
	struct vop_pathconf_args /* {
		struct vnode *a_vp;
		int a_name;
		int *a_retval;
	} */ *ap;
{

	return (EINVAL);
}

/*
 * NFS advisory byte-level locks (client)
 */
int
nfsx_advlock(ap)
	struct vop_advlock_args /* {
		struct vnode *a_vp;
		caddr_t  a_id;
		int  a_op;
		struct flock *a_fl;
		int  a_flags;
	} */ *ap;
{
	return (nfsx_dolock(ap));
}

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

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

/*
 * NFS directory offset lookup.
 * Currently unsupported.
 */
int
nfsx_blkatoff(ap)
	struct vop_blkatoff_args /* {
		struct vnode *a_vp;
		off_t a_offset;
		char **a_res;
		struct buf **a_bpp;
	} */ *ap;
{

#if DIAGNOSTIC
	printf("nfsx_blkatoff: unimplemented!!");
#endif
	return (EOPNOTSUPP);
}

/*
 * NFS flat namespace allocation.
 * Currently unsupported.
 */
int
nfsx_valloc(ap)
	struct vop_valloc_args /* {
		struct vnode *a_pvp;
		int a_mode;
		struct ucred *a_cred;
		struct vnode **a_vpp;
	} */ *ap;
{

	return (EOPNOTSUPP);
}

/*
 * NFS flat namespace free.
 * Currently unsupported.
 */
int
nfsx_vfree(ap)
	struct vop_vfree_args /* {
		struct vnode *a_pvp;
		ino_t a_ino;
		int a_mode;
	} */ *ap;
{

#if DIAGNOSTIC
	printf("nfsx_vfree: unimplemented!!");
#endif
	return (EOPNOTSUPP);
}

/*
 * NFS file truncation.
 */
int
nfsx_truncate(ap)
	struct vop_truncate_args /* {
		struct vnode *a_vp;
		off_t a_length;
		int a_flags;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{

	/* Use nfs_setattr */
#if DIAGNOSTIC
	printf("nfsx_truncate: unimplemented!!");
#endif
	return (EOPNOTSUPP);
}

/*
 * NFS update.
 */
int
nfsx_update(ap)
	struct vop_update_args /* {
		struct vnode *a_vp;
		struct timeval *a_ta;
		struct timeval *a_tm;
		int a_waitfor;
	} */ *ap;
{

	/* Use nfs_setattr */
#if DIAGNOSTIC
	printf("nfsx_update: unimplemented!!");
#endif
	return (EOPNOTSUPP);
}

/*
 * write (or commit) the given NFS buffer
 */
int
nfs_buf_write(struct nfsbuf *bp)
{
	int s;
	int oldflags = bp->nb_flags, rv = 0;
	struct vnode *vp = bp->nb_vp;
	struct ucred *cr;
	struct proc *p = current_proc();

	FSDBG_TOP(553, bp, NBOFF(bp), bp->nb_flags, 0);

	if (!ISSET(bp->nb_flags, NB_BUSY))
		panic("nfs_buf_write: buffer is not busy???");

	s = splbio();
	CLR(bp->nb_flags, (NB_READ|NB_DONE|NB_ERROR|NB_DELWRI));
	if (ISSET(oldflags, NB_DELWRI)) {
		nfs_nbdwrite--;
		NFSBUFCNTCHK();
		wakeup((caddr_t)&nfs_nbdwrite);
	}

	/* move to clean list */
	if (ISSET(oldflags, (NB_ASYNC|NB_DELWRI))) {
		if (bp->nb_vnbufs.le_next != NFSNOLIST)
			LIST_REMOVE(bp, nb_vnbufs);
		LIST_INSERT_HEAD(&VTONFS(vp)->n_cleanblkhd, bp, nb_vnbufs);
	}

	vp->v_numoutput++;
	if (p && p->p_stats)
		p->p_stats->p_ru.ru_oublock++;
	splx(s);

	/*
	 * For async requests when nfsiod(s) are running, queue the request by
	 * calling nfs_asyncio(), otherwise just all nfsx_doio() to do the request.
	 */
	if (ISSET(bp->nb_flags, NB_ASYNC))
		p = (struct proc *)0;
	if (ISSET(bp->nb_flags, NB_READ))
		cr = bp->nb_rcred;
	else
		cr = bp->nb_wcred;
	if (!ISSET(bp->nb_flags, NB_ASYNC) || nfs_asyncio(bp, NOCRED))
		rv = nfsx_doio(bp, cr, p);

	if ((oldflags & NB_ASYNC) == 0) {
		rv = nfs_buf_iowait(bp);
		/* move to clean list */
		if (oldflags & NB_DELWRI) {
			s = splbio();
			if (bp->nb_vnbufs.le_next != NFSNOLIST)
				LIST_REMOVE(bp, nb_vnbufs);
			LIST_INSERT_HEAD(&VTONFS(vp)->n_cleanblkhd, bp, nb_vnbufs);
			splx(s);
		}
		FSDBG_BOT(553, bp, NBOFF(bp), bp->nb_flags, rv);
		nfs_buf_release(bp);
		return (rv);
	} 

	FSDBG_BOT(553, bp, NBOFF(bp), bp->nb_flags, rv);
	return (rv);
}

/*
 * nfs special file access vnode op.
 * Essentially just get vattr and then imitate iaccess() since the device is
 * local to the client.
 */
int
nfsxspec_access(ap)
	struct vop_access_args /* {
		struct vnode *a_vp;
		int  a_mode;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{
	register struct vattr *vap;
	register gid_t *gp;
	register struct ucred *cred = ap->a_cred;
	struct vnode *vp = ap->a_vp;
	mode_t mode = ap->a_mode;
	struct vattr vattr;
	register int i;
	int error;

	/*
	 * Disallow write attempts on filesystems mounted read-only;
	 * unless the file is a socket, fifo, or a block or character
	 * device resident on the filesystem.
	 */
	if ((mode & VWRITE) && vp->v_mount && (vp->v_mount->mnt_flag & MNT_RDONLY)) {
		switch (vp->v_type) {
		case VREG: case VDIR: case VLNK:
			return (EROFS);
		default:
			break;
		}
	}
	/*
	 * If you're the super-user,
	 * you always get access.
	 */
	if (cred->cr_uid == 0)
		return (0);
	vap = &vattr;
	error = VOP_GETATTR(vp, vap, cred, ap->a_p);
	if (error)
		return (error);
	/*
	 * Access check is based on only one of owner, group, public.
	 * If not owner, then check group. If not a member of the
	 * group, then check public access.
	 */
	if (cred->cr_uid != vap->va_uid) {
		mode >>= 3;
		gp = cred->cr_groups;
		for (i = 0; i < cred->cr_ngroups; i++, gp++)
			if (vap->va_gid == *gp)
				goto found;
		mode >>= 3;
found:
		;
	}
	error = (vap->va_mode & mode) == mode ? 0 : EACCES;
	return (error);
}

/*
 * Read wrapper for special devices.
 */
int
nfsxspec_read(ap)
	struct vop_read_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		int  a_ioflag;
		struct ucred *a_cred;
	} */ *ap;
{
	register struct nfsnode *np = VTONFS(ap->a_vp);
	struct timeval now;

	/*
	 * Set access flag.
	 */
	np->n_flag |= NACC;
	microtime(&now);
	np->n_atim.tv_sec = now.tv_sec;
	np->n_atim.tv_nsec = now.tv_usec * 1000;
	return (VOCALL(spec_vnodeop_p, VOFFSET(vop_read), ap));
}

/*
 * Write wrapper for special devices.
 */
int
nfsxspec_write(ap)
	struct vop_write_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		int  a_ioflag;
		struct ucred *a_cred;
	} */ *ap;
{
	register struct nfsnode *np = VTONFS(ap->a_vp);
	struct timeval now;

	/*
	 * Set update flag.
	 */
	np->n_flag |= NUPD;
	microtime(&now);
	np->n_mtim.tv_sec = now.tv_sec;
	np->n_mtim.tv_nsec = now.tv_usec * 1000;
	return (VOCALL(spec_vnodeop_p, VOFFSET(vop_write), ap));
}

/*
 * Close wrapper for special devices.
 *
 * Update the times on the nfsnode then do device close.
 */
int
nfsxspec_close(ap)
	struct vop_close_args /* {
		struct vnode *a_vp;
		int  a_fflag;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;
	register struct nfsnode *np = VTONFS(vp);
	struct vattr vattr;

	if (np->n_flag & (NACC | NUPD)) {
		np->n_flag |= NCHG;
		if (vp->v_usecount == 1 && vp->v_mount &&
		    (vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
			VATTR_NULL(&vattr);
			if (np->n_flag & NACC)
				vattr.va_atime = np->n_atim;
			if (np->n_flag & NUPD)
				vattr.va_mtime = np->n_mtim;
			(void)VOP_SETATTR(vp, &vattr, ap->a_cred, ap->a_p);
		}
	}
	return (VOCALL(spec_vnodeop_p, VOFFSET(vop_close), ap));
}

/*
 * Read wrapper for fifos.
 */
int
nfsxfifo_read(ap)
	struct vop_read_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		int  a_ioflag;
		struct ucred *a_cred;
	} */ *ap;
{
        extern vop_t **fifo_vnodeop_p;
	register struct nfsnode *np = VTONFS(ap->a_vp);
	struct timeval now;

	/*
	 * Set access flag.
	 */
	np->n_flag |= NACC;
	microtime(&now);
	np->n_atim.tv_sec = now.tv_sec;
	np->n_atim.tv_nsec = now.tv_usec * 1000;
	return (VOCALL(fifo_vnodeop_p, VOFFSET(vop_read), ap));
}

/*
 * Write wrapper for fifos.
 */
int
nfsxfifo_write(ap)
	struct vop_write_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		int  a_ioflag;
		struct ucred *a_cred;
	} */ *ap;
{
        extern vop_t **fifo_vnodeop_p;
	register struct nfsnode *np = VTONFS(ap->a_vp);
	struct timeval now;

	/*
	 * Set update flag.
	 */
	np->n_flag |= NUPD;
	microtime(&now);
	np->n_mtim.tv_sec = now.tv_sec;
	np->n_mtim.tv_nsec = now.tv_usec * 1000;
	return (VOCALL(fifo_vnodeop_p, VOFFSET(vop_write), ap));
}

/*
 * Close wrapper for fifos.
 *
 * Update the times on the nfsnode then do fifo close.
 */
int
nfsxfifo_close(ap)
	struct vop_close_args /* {
		struct vnode *a_vp;
		int  a_fflag;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;
	register struct nfsnode *np = VTONFS(vp);
	struct vattr vattr;
	struct timeval now;
        extern vop_t **fifo_vnodeop_p;

	if (np->n_flag & (NACC | NUPD)) {
		microtime(&now);
		if (np->n_flag & NACC) {
			np->n_atim.tv_sec = now.tv_sec;
			np->n_atim.tv_nsec = now.tv_usec * 1000;
		}
		if (np->n_flag & NUPD) {
			np->n_mtim.tv_sec = now.tv_sec;
			np->n_mtim.tv_nsec = now.tv_usec * 1000;
		}
		np->n_flag |= NCHG;
		if (vp->v_usecount == 1 && vp->v_mount &&
		    (vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
			VATTR_NULL(&vattr);
			if (np->n_flag & NACC)
				vattr.va_atime = np->n_atim;
			if (np->n_flag & NUPD)
				vattr.va_mtime = np->n_mtim;
			(void)VOP_SETATTR(vp, &vattr, ap->a_cred, ap->a_p);
		}
	}
	return (VOCALL(fifo_vnodeop_p, VOFFSET(vop_close), ap));
}

int
nfsx_ioctl(ap)
	struct vop_ioctl_args *ap;
{

	/*
	 * XXX we were once bogusly enoictl() which returned this (ENOTTY).
	 * Probably we should return ENODEV.
	 */
	return (ENOTTY);
}

int
nfsx_select(ap)
	struct vop_select_args *ap;
{

	/*
	 * We were once bogusly seltrue() which returns 1.  Is this right?
	 */
	return (1);
}

/*
 * Vnode op for pagein using getblk_pages
 * derived from nfsx_bioread()
 * No read aheads are started from pagein operation
 */
int
nfsx_pagein(ap)
	struct vop_pagein_args /* {
	   	struct vnode *a_vp,
	   	upl_t 	a_pl,
		vm_offset_t   a_pl_offset,
		off_t         a_f_offset,
		size_t        a_size,
		struct ucred *a_cred,
		int           a_flags
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;
	upl_t pl = ap->a_pl;
	size_t size= ap->a_size;
	off_t f_offset = ap->a_f_offset;
	vm_offset_t pl_offset = ap->a_pl_offset;
	int flags  = ap->a_flags;
	struct ucred *cred;
	struct nfsnode *np = VTONFS(vp);
	int biosize, xsize, iosize;
/* 	struct vattr vattr; */
	struct proc *p = current_proc();
	struct nfsmount *nmp;
	int error = 0;
	vm_offset_t ioaddr;
	struct uio	auio;
	struct iovec	aiov;
	struct uio * uio = &auio;
	int nofreeupl = flags & UPL_NOCOMMIT;
	upl_page_info_t *plinfo;

	FSDBG(322, vp, f_offset, size, flags);
	if (pl == (upl_t)NULL)
		panic("nfsx_pagein: no upl");

	if (UBCINVALID(vp)) {
		printf("nfsx_pagein: invalid vnode 0x%x", (int)vp);
		if (!nofreeupl)
			(void) ubc_upl_abort(pl, NULL); 
		return (EPERM);
	}
	UBCINFOCHECK("nfsx_pagein", vp);

	if (size <= 0) {
		printf("nfsx_pagein: invalid size %d", size);
		if (!nofreeupl)
			(void) ubc_upl_abort(pl, NULL); 
		return (EINVAL);
	}
	if (f_offset < 0 || f_offset >= np->n_size || (f_offset & PAGE_MASK_64)) {
		if (!nofreeupl)
			ubc_upl_abort_range(pl, pl_offset, size, 
				UPL_ABORT_ERROR | UPL_ABORT_FREE_ON_EMPTY);
		return (EINVAL);
	}
	cred = ubc_getcred(vp);
	if (cred == NOCRED)
		cred = ap->a_cred;

	auio.uio_offset = f_offset;
	auio.uio_segflg = UIO_SYSSPACE;
	auio.uio_rw = UIO_READ;
	auio.uio_procp = NULL;

	nmp = VFSTONFS(vp->v_mount);
	if (!nmp) {
		if (!nofreeupl)
			ubc_upl_abort_range(pl, pl_offset, size, 
				UPL_ABORT_ERROR | UPL_ABORT_FREE_ON_EMPTY);
		return (ENXIO);
	}

	/* XXXMARIUS: fsinfo */
/* 	if ((nmp->nm_flag & NFSMNT_NFSV3) && !(nmp->nm_state & NFSSTA_GOTFSINFO)) */
/* 		(void)nfsx_fsinfo(nmp, vp, cred, p); */
	biosize = vp->v_mount->mnt_stat.f_iosize;

	plinfo = ubc_upl_pageinfo(pl);
	ubc_upl_map(pl, &ioaddr);
	ioaddr += pl_offset;
	xsize = size;

	do {
		/*
		 * It would be nice to be able to issue all these requests
		 * in parallel instead of waiting for each one to complete
		 * before sending the next one.
		 * XXX Should we align these requests to block boundaries?
		 */
	        iosize = min(biosize, xsize);
		uio->uio_resid = iosize;
		aiov.iov_len  = iosize;
		aiov.iov_base = (caddr_t)ioaddr;
		auio.uio_iov = &aiov;
		auio.uio_iovcnt = 1;

		FSDBG(322, uio->uio_offset, uio->uio_resid, ioaddr, xsize);
// XXX #warning our nfsx_pagein does not support NQNFS
		/*
		 * With UBC we get here only when the file data is not in the VM
		 * page cache, so go ahead and read in.
		 */
#ifdef UBC_DEBUG
		upl_ubc_alias_set(pl, current_act(), 2);
#endif /* UBC_DEBUG */
		nfsstats.pageins++;

		error = NFSOP(nmp, readrpc)(vp, uio, cred);

		if (!error) {
			if (uio->uio_resid) {
				/*
				 * If uio_resid > 0, there is a hole in the file
				 * and no writes after the hole have been pushed
				 * to the server yet... or we're at the EOF
				 * Just zero fill the rest of the valid area.
				 */
				int zcnt = uio->uio_resid;
				int zoff = iosize - zcnt;
				bzero((char *)ioaddr + zoff, zcnt);

				FSDBG(324, uio->uio_offset, zoff, zcnt, ioaddr);
				uio->uio_offset += zcnt;
			}
			ioaddr += iosize;	
			xsize  -= iosize;
		} else
			FSDBG(322, uio->uio_offset, uio->uio_resid, error, -1);

		nmp = VFSTONFS(vp->v_mount);
		if (p && (vp->v_flag & VTEXT) && nmp &&
		    ((nmp->nm_flag & NFSMNT_NQNFS &&
		      NQNFS_CKINVALID(vp, np, ND_READ) &&
		      np->n_lrev != np->n_brev) ||
		     (!(nmp->nm_flag & NFSMNT_NQNFS) &&
		      np->n_mtime != np->n_vattr.va_mtime.tv_sec))) {
			uprintf("Process killed due to text file modification\n");
			psignal(p, SIGKILL);
			p->p_flag |= P_NOSWAP;
		}

	} while (error == 0 && xsize > 0);

	ubc_upl_unmap(pl);

	if (!nofreeupl) {
		if (error) 
			ubc_upl_abort_range(pl, pl_offset, size, 
					    UPL_ABORT_ERROR |
					    UPL_ABORT_FREE_ON_EMPTY);
		else
			ubc_upl_commit_range(pl, pl_offset, size,
					     UPL_COMMIT_CLEAR_DIRTY |
					     UPL_COMMIT_FREE_ON_EMPTY);
	}
	return (error);
}


/*
 * Vnode op for pageout using UPL
 * Derived from nfs_write()
 * File size changes are not permitted in pageout.
 */
int
nfsx_pageout(ap)
	struct vop_pageout_args /* {
		struct vnode *a_vp,
		upl_t 	a_pl,
		vm_offset_t   a_pl_offset,
		off_t         a_f_offset,
		size_t        a_size,
		struct ucred *a_cred,
		int           a_flags
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;
	upl_t pl = ap->a_pl;
	size_t size= ap->a_size;
	off_t f_offset = ap->a_f_offset;
	vm_offset_t pl_offset = ap->a_pl_offset;
	int flags  = ap->a_flags;
/* 	struct proc *p = current_proc(); */
	struct nfsnode *np = VTONFS(vp);
	register struct ucred *cred;
	struct nfsbuf *bp;
	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
	daddr_t lbn;
	int error = 0, iomode, must_commit, s;
	off_t off;
	vm_offset_t ioaddr;
	struct uio	auio;
	struct iovec	aiov;
	int nofreeupl = flags & UPL_NOCOMMIT;
	int biosize, iosize, pgsize, xsize;

	FSDBG(323, f_offset, size, pl, pl_offset);

	if (pl == (upl_t)NULL)
		panic("nfs_pageout: no upl");

	if (UBCINVALID(vp)) {
		printf("nfs_pageout: invalid vnode 0x%x", (int)vp);
		if (!nofreeupl)
			ubc_upl_abort(pl, 0); 
		return (EIO);
	}
	UBCINFOCHECK("nfs_pageout", vp);

	if (size <= 0) {
		printf("nfs_pageout: invalid size %d", size);
		if (!nofreeupl)
			ubc_upl_abort(pl, 0); 
		return (EINVAL);
	}

	if (!nmp) {
		if (!nofreeupl)
			ubc_upl_abort(pl, UPL_ABORT_DUMP_PAGES|UPL_ABORT_FREE_ON_EMPTY);
		return (ENXIO);
	}
	biosize = vp->v_mount->mnt_stat.f_iosize;

	/*
	 * Check to see whether the buffer is incore.
	 * If incore and not busy, invalidate it from the cache.
	 */
	for (iosize = 0; iosize < size; iosize += xsize) {
		off = f_offset + iosize;
		/* need make sure we do things on block boundaries */
		xsize = biosize - (off % biosize);
		if (off + xsize > f_offset + size)
			xsize = f_offset + size - off;
		lbn = ubc_offtoblk(vp, off);
		s = splbio();
		if ((bp = nfs_buf_incore(vp, lbn))) {
			FSDBG(323, off, 1, bp, bp->nb_flags);
			if (ISSET(bp->nb_flags, NB_BUSY)) {
				/* no panic. just tell vm we are busy */
				if (!nofreeupl)
					ubc_upl_abort(pl, 0); 
				return (EBUSY);
			}
			if (bp->nb_dirtyend > 0) {
				/*
				 * if there's a dirty range in the buffer, check to
				 * see if it extends beyond the pageout region
				 *
				 * if the dirty region lies completely within the
				 * pageout region, we just invalidate the buffer
				 * because it's all being written out now anyway.
				 *
				 * if any of the dirty region lies outside the
				 * pageout region, we'll try to clip the dirty
				 * region to eliminate the portion that's being
				 * paged out.  If that's not possible, because
				 * the dirty region extends before and after the
				 * pageout region, then we'll just return EBUSY.
				 */
				off_t boff, start, end;
				boff = NBOFF(bp);
				start = off;
				end = off + xsize;
				/* clip end to EOF */
				if (end > np->n_size)
					end = np->n_size;
				start -= boff;
				end -= boff;
				if ((bp->nb_dirtyoff < start) &&
				    (bp->nb_dirtyend > end)) {
				    /* not gonna be able to clip the dirty region */
				    FSDBG(323, vp, bp, 0xd00deebc, EBUSY);
				    if (!nofreeupl)
					ubc_upl_abort(pl, 0); 
				    return (EBUSY);
				}
				if ((bp->nb_dirtyoff < start) ||
				    (bp->nb_dirtyend > end)) {
				    /* clip dirty region, if necessary */
				    if (bp->nb_dirtyoff < start)
					bp->nb_dirtyend = min(bp->nb_dirtyend, start);
				    if (bp->nb_dirtyend > end)
					bp->nb_dirtyoff = max(bp->nb_dirtyoff, end);
				    FSDBG(323, bp, bp->nb_dirtyoff, bp->nb_dirtyend, 0xd00dee00);
				    /* we're leaving this block dirty */
				    continue;
				}
			}
			nfs_buf_remfree(bp);
			SET(bp->nb_flags, (NB_BUSY | NB_INVAL));
			if (ISSET(bp->nb_flags, NB_NEEDCOMMIT)) {
				CLR(bp->nb_flags, NB_NEEDCOMMIT);
				np->n_needcommitcnt--;
				CHECK_NEEDCOMMITCNT(np);
			}
			nfs_buf_release(bp);
		}
		splx(s);
	}

	cred = ubc_getcred(vp);
	if (cred == NOCRED)
		cred = ap->a_cred;

	if (np->n_flag & NWRITEERR) {
		np->n_flag &= ~NWRITEERR;
		if (!nofreeupl)
			ubc_upl_abort_range(pl, pl_offset, size,
					    UPL_ABORT_FREE_ON_EMPTY);
		return (np->n_error);
	}
	/* XXXMARIUS: fsinfo */
/* 	if ((nmp->nm_flag & NFSMNT_NFSV3) && */
/* 		!(nmp->nm_state & NFSSTA_GOTFSINFO)) */
/* 		(void)nfsx_fsinfo(nmp, vp, cred, p); */

	if (f_offset < 0 || f_offset >= np->n_size ||
	    f_offset & PAGE_MASK_64 || size & PAGE_MASK_64) {
		if (!nofreeupl)
			ubc_upl_abort_range(pl, pl_offset, size,
					    UPL_ABORT_FREE_ON_EMPTY);
		return (EINVAL);
	}

	ubc_upl_map(pl, &ioaddr);
	ioaddr += pl_offset;

	if (f_offset + size > np->n_size)
		xsize = np->n_size - f_offset;
	else
		xsize = size;

	pgsize = round_page_64(xsize);
	if (size > pgsize) {
		if (!nofreeupl)
			ubc_upl_abort_range(pl, pl_offset + pgsize,
					    size - pgsize,
					    UPL_ABORT_FREE_ON_EMPTY);
	}

	/* 
	 * check for partial page and clear the
	 * contents past end of the file before
	 * releasing it in the VM page cache
	 */
	if (f_offset < np->n_size && f_offset + size > np->n_size) {
		size_t io = np->n_size - f_offset;
		bzero((caddr_t)(ioaddr + io), size - io);
		FSDBG(321, np->n_size, f_offset, f_offset + io, size - io);
	}

	auio.uio_offset = f_offset;
	auio.uio_segflg = UIO_SYSSPACE;
	auio.uio_rw = UIO_READ;
	auio.uio_procp = NULL;

	do {
		/*
		 * It would be nice to be able to issue all these requests
		 * in parallel instead of waiting for each one to complete
		 * before sending the next one.
		 * XXX Should we align these requests to block boundaries?
		 */
		iosize = min(biosize, xsize);
		auio.uio_resid = iosize;
		aiov.iov_len = iosize;
		aiov.iov_base = (caddr_t)ioaddr;
		auio.uio_iov = &aiov;
		auio.uio_iovcnt = 1;

		FSDBG(323, auio.uio_offset, auio.uio_resid, ioaddr, xsize);
// XXX #warning our nfs_pageout does not support NQNFS
		nfsstats.pageouts++;

		vp->v_numoutput++;
		/* NMODIFIED would be set here if doing unstable writes */
		iomode = NFSV3WRITE_FILESYNC;
		error = NFSOP(nmp, writerpc)(vp, &auio, cred,
		    &iomode, &must_commit);
		if (must_commit)
			nfs_clearcommit(vp->v_mount);
		vpwakeup(vp);
		if (error)
			goto cleanup;
		/* Note: no need to check uio_resid, because */
		/* it'll only be set if there was an error. */
		ioaddr += iosize;
		xsize -= iosize;
	} while (xsize > 0);

cleanup:
	ubc_upl_unmap(pl);
	/*
	 * We've had several different solutions on what to do when the pageout
	 * gets an error. If we don't handle it, and return an error to the 
	 * caller, vm, it will retry . This can end in endless looping 
	 * between vm and here doing retries of the same page. Doing a dump
	 * back to vm, will get it out of vm's knowledge and we lose whatever
	 * data existed. This is risky, but in some cases necessary. For
	 * example, the initial fix here was to do that for ESTALE. In that case
	 * the server is telling us that the file is no longer the same. We 
	 * would not want to keep paging out to that. We also saw some 151 
	 * errors from Auspex server and NFSv3 can return errors higher than
	 * ELAST. Those along with NFS known server errors we will "dump" from
	 * vm.  Errors we don't expect to occur, we dump and log for further
	 * analysis. Errors that could be transient, networking ones,
	 * we let vm "retry". Lastly, errors that we retry, but may have potential
	 * to storm the network, we "retrywithsleep". "sever" will be used in
	 * in the future to dump all pages of object for cases like ESTALE.
	 * All this is the basis for the states returned and first guesses on
	 * error handling. Tweaking expected as more statistics are gathered.
	 * Note, in the long run we may need another more robust solution to
	 * have some kind of persistant store when the vm cannot dump nor keep
	 * retrying as a solution, but this would be a file architectural change
	 */
	  
	if (!nofreeupl) { /* otherwise stacked file system has to handle this */
		if (error) {
			int abortflags; 
			short action = nfs_pageouterrorhandler(error);
			
			switch (action) {
				case DUMP:
					abortflags = UPL_ABORT_DUMP_PAGES|UPL_ABORT_FREE_ON_EMPTY;
					break;
				case DUMPANDLOG:
					abortflags = UPL_ABORT_DUMP_PAGES|UPL_ABORT_FREE_ON_EMPTY;
					if (error <= ELAST &&
					    (errorcount[error] % 100 == 0)) 
						printf("nfsx_pageout: unexpected error %d. dumping vm page\n", error);
					errorcount[error]++;
					break;
				case RETRY:
					abortflags = UPL_ABORT_FREE_ON_EMPTY;
					break;
				case RETRYWITHSLEEP:
					abortflags = UPL_ABORT_FREE_ON_EMPTY;
					/* pri unused. PSOCK for placeholder. */
					(void) tsleep(&lbolt, PSOCK,
						      "nfspageout", 0);
					break;
				case SEVER: /* not implemented */
				default:
					printf("nfsx_pageout: action %d not expected\n", action);
					break;
			}
				
			ubc_upl_abort_range(pl, pl_offset, size, abortflags);
			/* return error in all cases above */
			
		} else 
			ubc_upl_commit_range(pl, pl_offset, pgsize,
					     UPL_COMMIT_CLEAR_DIRTY |
					     UPL_COMMIT_FREE_ON_EMPTY);
	}
	return (error);
}

/* Blktooff derives file offset given a logical block number */
int
nfsx_blktooff(ap)
	struct vop_blktooff_args /* {
		struct vnode *a_vp;
		daddr_t a_lblkno;
		off_t *a_offset;    
	} */ *ap;
{
	int biosize;
	register struct vnode *vp = ap->a_vp;

	if (!vp->v_mount)
		return (ENXIO);

	biosize = vp->v_mount->mnt_stat.f_iosize;

	*ap->a_offset = (off_t)ap->a_lblkno * biosize;

	return (0);
}

int
nfsx_offtoblk(ap)
	struct vop_offtoblk_args /* {
		struct vnode *a_vp;
		off_t a_offset;    
		daddr_t *a_lblkno;
	} */ *ap;
{
	int biosize;
	register struct vnode *vp = ap->a_vp;

	if (!vp->v_mount)
		return (ENXIO);

	biosize = vp->v_mount->mnt_stat.f_iosize;

	*ap->a_lblkno = (daddr_t)(ap->a_offset / biosize);

	return (0);
}

int
nfsx_cmap(ap)
	struct vop_cmap_args /* {
		struct vnode *a_vp;
		off_t a_offset;    
		size_t a_size;
		daddr_t *a_bpn;
		size_t *a_run;
		void *a_poff;
	} */ *ap;
{
	return (EOPNOTSUPP);
}


/*
 * nfs special file access vnode op.
 * Essentially just get vattr and then imitate iaccess() since the device is
 * local to the client.
 */
int
nfsspec_access(ap)
	struct vop_access_args /* {
		struct vnode *a_vp;
		int  a_mode;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{
	register struct vattr *vap;
	register gid_t *gp;
	register struct ucred *cred = ap->a_cred;
	struct vnode *vp = ap->a_vp;
	mode_t mode = ap->a_mode;
	struct vattr vattr;
	register int i;
	int error;

	/*
	 * Disallow write attempts on filesystems mounted read-only;
	 * unless the file is a socket, fifo, or a block or character
	 * device resident on the filesystem.
	 */
	if ((mode & VWRITE) && vp->v_mount && (vp->v_mount->mnt_flag & MNT_RDONLY)) {
		switch (vp->v_type) {
		case VREG: case VDIR: case VLNK:
			return (EROFS);
		default:
			break;
		}
	}
	/*
	 * If you're the super-user,
	 * you always get access.
	 */
	if (cred->cr_uid == 0)
		return (0);
	vap = &vattr;
	error = VOP_GETATTR(vp, vap, cred, ap->a_p);
	if (error)
		return (error);
	/*
	 * Access check is based on only one of owner, group, public.
	 * If not owner, then check group. If not a member of the
	 * group, then check public access.
	 */
	if (cred->cr_uid != vap->va_uid) {
		mode >>= 3;
		gp = cred->cr_groups;
		for (i = 0; i < cred->cr_ngroups; i++, gp++)
			if (vap->va_gid == *gp)
				goto found;
		mode >>= 3;
found:
		;
	}
	error = (vap->va_mode & mode) == mode ? 0 : EACCES;
	return (error);
}

/*
 * Read wrapper for special devices.
 */
int
nfsspec_read(ap)
	struct vop_read_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		int  a_ioflag;
		struct ucred *a_cred;
	} */ *ap;
{
	register struct nfsnode *np = VTONFS(ap->a_vp);
	struct timeval now;

	/*
	 * Set access flag.
	 */
	np->n_flag |= NACC;
	microtime(&now);
	np->n_atim.tv_sec = now.tv_sec;
	np->n_atim.tv_nsec = now.tv_usec * 1000;
	return (VOCALL(spec_vnodeop_p, VOFFSET(vop_read), ap));
}

/*
 * Write wrapper for special devices.
 */
int
nfsspec_write(ap)
	struct vop_write_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		int  a_ioflag;
		struct ucred *a_cred;
	} */ *ap;
{
	register struct nfsnode *np = VTONFS(ap->a_vp);
	struct timeval now;

	/*
	 * Set update flag.
	 */
	np->n_flag |= NUPD;
	microtime(&now);
	np->n_mtim.tv_sec = now.tv_sec;
	np->n_mtim.tv_nsec = now.tv_usec * 1000;
	return (VOCALL(spec_vnodeop_p, VOFFSET(vop_write), ap));
}

/*
 * Close wrapper for special devices.
 *
 * Update the times on the nfsnode then do device close.
 */
int
nfsspec_close(ap)
	struct vop_close_args /* {
		struct vnode *a_vp;
		int  a_fflag;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;
	register struct nfsnode *np = VTONFS(vp);
	struct vattr vattr;

	if (np->n_flag & (NACC | NUPD)) {
		np->n_flag |= NCHG;
		if (vp->v_usecount == 1 && vp->v_mount &&
		    (vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
			VATTR_NULL(&vattr);
			if (np->n_flag & NACC)
				vattr.va_atime = np->n_atim;
			if (np->n_flag & NUPD)
				vattr.va_mtime = np->n_mtim;
			(void)VOP_SETATTR(vp, &vattr, ap->a_cred, ap->a_p);
		}
	}
	return (VOCALL(spec_vnodeop_p, VOFFSET(vop_close), ap));
}

/*
 * Read wrapper for fifos.
 */
int
nfsfifo_read(ap)
	struct vop_read_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		int  a_ioflag;
		struct ucred *a_cred;
	} */ *ap;
{
        extern vop_t **fifo_vnodeop_p;
	register struct nfsnode *np = VTONFS(ap->a_vp);
	struct timeval now;

	/*
	 * Set access flag.
	 */
	np->n_flag |= NACC;
	microtime(&now);
	np->n_atim.tv_sec = now.tv_sec;
	np->n_atim.tv_nsec = now.tv_usec * 1000;
	return (VOCALL(fifo_vnodeop_p, VOFFSET(vop_read), ap));
}

/*
 * Write wrapper for fifos.
 */
int
nfsfifo_write(ap)
	struct vop_write_args /* {
		struct vnode *a_vp;
		struct uio *a_uio;
		int  a_ioflag;
		struct ucred *a_cred;
	} */ *ap;
{
        extern vop_t **fifo_vnodeop_p;
	register struct nfsnode *np = VTONFS(ap->a_vp);
	struct timeval now;

	/*
	 * Set update flag.
	 */
	np->n_flag |= NUPD;
	microtime(&now);
	np->n_mtim.tv_sec = now.tv_sec;
	np->n_mtim.tv_nsec = now.tv_usec * 1000;
	return (VOCALL(fifo_vnodeop_p, VOFFSET(vop_write), ap));
}

/*
 * Close wrapper for fifos.
 *
 * Update the times on the nfsnode then do fifo close.
 */
int
nfsfifo_close(ap)
	struct vop_close_args /* {
		struct vnode *a_vp;
		int  a_fflag;
		struct ucred *a_cred;
		struct proc *a_p;
	} */ *ap;
{
	register struct vnode *vp = ap->a_vp;
	register struct nfsnode *np = VTONFS(vp);
	struct vattr vattr;
	struct timeval now;
        extern vop_t **fifo_vnodeop_p;

	if (np->n_flag & (NACC | NUPD)) {
		microtime(&now);
		if (np->n_flag & NACC) {
			np->n_atim.tv_sec = now.tv_sec;
			np->n_atim.tv_nsec = now.tv_usec * 1000;
		}
		if (np->n_flag & NUPD) {
			np->n_mtim.tv_sec = now.tv_sec;
			np->n_mtim.tv_nsec = now.tv_usec * 1000;
		}
		np->n_flag |= NCHG;
		if (vp->v_usecount == 1 && vp->v_mount &&
		    (vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
			VATTR_NULL(&vattr);
			if (np->n_flag & NACC)
				vattr.va_atime = np->n_atim;
			if (np->n_flag & NUPD)
				vattr.va_mtime = np->n_mtim;
			(void)VOP_SETATTR(vp, &vattr, ap->a_cred, ap->a_p);
		}
	}
	return (VOCALL(fifo_vnodeop_p, VOFFSET(vop_close), ap));
}
