nfs_clvnops.c revision 220764
1/*-
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Rick Macklem at The University of Guelph.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 *
32 *	from nfs_vnops.c	8.16 (Berkeley) 5/27/95
33 */
34
35#include <sys/cdefs.h>
36__FBSDID("$FreeBSD: head/sys/fs/nfsclient/nfs_clvnops.c 220764 2011-04-18 01:02:43Z rmacklem $");
37
38/*
39 * vnode op calls for Sun NFS version 2, 3 and 4
40 */
41
42#include "opt_inet.h"
43
44#include <sys/param.h>
45#include <sys/kernel.h>
46#include <sys/systm.h>
47#include <sys/resourcevar.h>
48#include <sys/proc.h>
49#include <sys/mount.h>
50#include <sys/bio.h>
51#include <sys/buf.h>
52#include <sys/jail.h>
53#include <sys/malloc.h>
54#include <sys/mbuf.h>
55#include <sys/namei.h>
56#include <sys/socket.h>
57#include <sys/vnode.h>
58#include <sys/dirent.h>
59#include <sys/fcntl.h>
60#include <sys/lockf.h>
61#include <sys/stat.h>
62#include <sys/sysctl.h>
63#include <sys/signalvar.h>
64
65#include <vm/vm.h>
66#include <vm/vm_object.h>
67#include <vm/vm_extern.h>
68#include <vm/vm_object.h>
69
70#include <fs/nfs/nfsport.h>
71#include <fs/nfsclient/nfsnode.h>
72#include <fs/nfsclient/nfsmount.h>
73#include <fs/nfsclient/nfs.h>
74
75#include <net/if.h>
76#include <netinet/in.h>
77#include <netinet/in_var.h>
78
79#include <nfs/nfs_lock.h>
80
81/* Defs */
82#define	TRUE	1
83#define	FALSE	0
84
85extern struct nfsstats newnfsstats;
86extern int nfsrv_useacl;
87MALLOC_DECLARE(M_NEWNFSREQ);
88
89/*
90 * Ifdef for FreeBSD-current merged buffer cache. It is unfortunate that these
91 * calls are not in getblk() and brelse() so that they would not be necessary
92 * here.
93 */
94#ifndef B_VMIO
95#define	vfs_busy_pages(bp, f)
96#endif
97
98static vop_read_t	nfsfifo_read;
99static vop_write_t	nfsfifo_write;
100static vop_close_t	nfsfifo_close;
101static int	nfs_setattrrpc(struct vnode *, struct vattr *, struct ucred *,
102		    struct thread *);
103static vop_lookup_t	nfs_lookup;
104static vop_create_t	nfs_create;
105static vop_mknod_t	nfs_mknod;
106static vop_open_t	nfs_open;
107static vop_pathconf_t	nfs_pathconf;
108static vop_close_t	nfs_close;
109static vop_access_t	nfs_access;
110static vop_getattr_t	nfs_getattr;
111static vop_setattr_t	nfs_setattr;
112static vop_read_t	nfs_read;
113static vop_fsync_t	nfs_fsync;
114static vop_remove_t	nfs_remove;
115static vop_link_t	nfs_link;
116static vop_rename_t	nfs_rename;
117static vop_mkdir_t	nfs_mkdir;
118static vop_rmdir_t	nfs_rmdir;
119static vop_symlink_t	nfs_symlink;
120static vop_readdir_t	nfs_readdir;
121static vop_strategy_t	nfs_strategy;
122static vop_lock1_t	nfs_lock1;
123static	int	nfs_lookitup(struct vnode *, char *, int,
124		    struct ucred *, struct thread *, struct nfsnode **);
125static	int	nfs_sillyrename(struct vnode *, struct vnode *,
126		    struct componentname *);
127static vop_access_t	nfsspec_access;
128static vop_readlink_t	nfs_readlink;
129static vop_print_t	nfs_print;
130static vop_advlock_t	nfs_advlock;
131static vop_advlockasync_t nfs_advlockasync;
132static vop_getacl_t nfs_getacl;
133static vop_setacl_t nfs_setacl;
134
135/*
136 * Global vfs data structures for nfs
137 */
138struct vop_vector newnfs_vnodeops = {
139	.vop_default =		&default_vnodeops,
140	.vop_access =		nfs_access,
141	.vop_advlock =		nfs_advlock,
142	.vop_advlockasync =	nfs_advlockasync,
143	.vop_close =		nfs_close,
144	.vop_create =		nfs_create,
145	.vop_fsync =		nfs_fsync,
146	.vop_getattr =		nfs_getattr,
147	.vop_getpages =		ncl_getpages,
148	.vop_putpages =		ncl_putpages,
149	.vop_inactive =		ncl_inactive,
150	.vop_link =		nfs_link,
151	.vop_lock1 = 		nfs_lock1,
152	.vop_lookup =		nfs_lookup,
153	.vop_mkdir =		nfs_mkdir,
154	.vop_mknod =		nfs_mknod,
155	.vop_open =		nfs_open,
156	.vop_pathconf =		nfs_pathconf,
157	.vop_print =		nfs_print,
158	.vop_read =		nfs_read,
159	.vop_readdir =		nfs_readdir,
160	.vop_readlink =		nfs_readlink,
161	.vop_reclaim =		ncl_reclaim,
162	.vop_remove =		nfs_remove,
163	.vop_rename =		nfs_rename,
164	.vop_rmdir =		nfs_rmdir,
165	.vop_setattr =		nfs_setattr,
166	.vop_strategy =		nfs_strategy,
167	.vop_symlink =		nfs_symlink,
168	.vop_write =		ncl_write,
169	.vop_getacl =		nfs_getacl,
170	.vop_setacl =		nfs_setacl,
171};
172
173struct vop_vector newnfs_fifoops = {
174	.vop_default =		&fifo_specops,
175	.vop_access =		nfsspec_access,
176	.vop_close =		nfsfifo_close,
177	.vop_fsync =		nfs_fsync,
178	.vop_getattr =		nfs_getattr,
179	.vop_inactive =		ncl_inactive,
180	.vop_print =		nfs_print,
181	.vop_read =		nfsfifo_read,
182	.vop_reclaim =		ncl_reclaim,
183	.vop_setattr =		nfs_setattr,
184	.vop_write =		nfsfifo_write,
185};
186
187static int nfs_mknodrpc(struct vnode *dvp, struct vnode **vpp,
188    struct componentname *cnp, struct vattr *vap);
189static int nfs_removerpc(struct vnode *dvp, struct vnode *vp, char *name,
190    int namelen, struct ucred *cred, struct thread *td);
191static int nfs_renamerpc(struct vnode *fdvp, struct vnode *fvp,
192    char *fnameptr, int fnamelen, struct vnode *tdvp, struct vnode *tvp,
193    char *tnameptr, int tnamelen, struct ucred *cred, struct thread *td);
194static int nfs_renameit(struct vnode *sdvp, struct vnode *svp,
195    struct componentname *scnp, struct sillyrename *sp);
196
197/*
198 * Global variables
199 */
200#define	DIRHDSIZ	(sizeof (struct dirent) - (MAXNAMLEN + 1))
201
202SYSCTL_DECL(_vfs_newnfs);
203
204static int	nfsaccess_cache_timeout = NFS_MAXATTRTIMO;
205SYSCTL_INT(_vfs_newnfs, OID_AUTO, access_cache_timeout, CTLFLAG_RW,
206	   &nfsaccess_cache_timeout, 0, "NFS ACCESS cache timeout");
207
208static int	nfs_prime_access_cache = 0;
209SYSCTL_INT(_vfs_newnfs, OID_AUTO, prime_access_cache, CTLFLAG_RW,
210	   &nfs_prime_access_cache, 0,
211	   "Prime NFS ACCESS cache when fetching attributes");
212
213static int	newnfs_commit_on_close = 0;
214SYSCTL_INT(_vfs_newnfs, OID_AUTO, commit_on_close, CTLFLAG_RW,
215    &newnfs_commit_on_close, 0, "write+commit on close, else only write");
216
217static int	nfs_clean_pages_on_close = 1;
218SYSCTL_INT(_vfs_newnfs, OID_AUTO, clean_pages_on_close, CTLFLAG_RW,
219	   &nfs_clean_pages_on_close, 0, "NFS clean dirty pages on close");
220
221int newnfs_directio_enable = 0;
222SYSCTL_INT(_vfs_newnfs, OID_AUTO, nfs_directio_enable, CTLFLAG_RW,
223	   &newnfs_directio_enable, 0, "Enable NFS directio");
224
225/*
226 * This sysctl allows other processes to mmap a file that has been opened
227 * O_DIRECT by a process.  In general, having processes mmap the file while
228 * Direct IO is in progress can lead to Data Inconsistencies.  But, we allow
229 * this by default to prevent DoS attacks - to prevent a malicious user from
230 * opening up files O_DIRECT preventing other users from mmap'ing these
231 * files.  "Protected" environments where stricter consistency guarantees are
232 * required can disable this knob.  The process that opened the file O_DIRECT
233 * cannot mmap() the file, because mmap'ed IO on an O_DIRECT open() is not
234 * meaningful.
235 */
236int newnfs_directio_allow_mmap = 1;
237SYSCTL_INT(_vfs_newnfs, OID_AUTO, nfs_directio_allow_mmap, CTLFLAG_RW,
238	   &newnfs_directio_allow_mmap, 0, "Enable mmaped IO on file with O_DIRECT opens");
239
240#if 0
241SYSCTL_INT(_vfs_newnfs, OID_AUTO, access_cache_hits, CTLFLAG_RD,
242	   &newnfsstats.accesscache_hits, 0, "NFS ACCESS cache hit count");
243
244SYSCTL_INT(_vfs_newnfs, OID_AUTO, access_cache_misses, CTLFLAG_RD,
245	   &newnfsstats.accesscache_misses, 0, "NFS ACCESS cache miss count");
246#endif
247
248#define	NFSACCESS_ALL (NFSACCESS_READ | NFSACCESS_MODIFY		\
249			 | NFSACCESS_EXTEND | NFSACCESS_EXECUTE	\
250			 | NFSACCESS_DELETE | NFSACCESS_LOOKUP)
251
252/*
253 * SMP Locking Note :
254 * The list of locks after the description of the lock is the ordering
255 * of other locks acquired with the lock held.
256 * np->n_mtx : Protects the fields in the nfsnode.
257       VM Object Lock
258       VI_MTX (acquired indirectly)
259 * nmp->nm_mtx : Protects the fields in the nfsmount.
260       rep->r_mtx
261 * ncl_iod_mutex : Global lock, protects shared nfsiod state.
262 * nfs_reqq_mtx : Global lock, protects the nfs_reqq list.
263       nmp->nm_mtx
264       rep->r_mtx
265 * rep->r_mtx : Protects the fields in an nfsreq.
266 */
267
268static int
269nfs34_access_otw(struct vnode *vp, int wmode, struct thread *td,
270    struct ucred *cred, u_int32_t *retmode)
271{
272	int error = 0, attrflag, i, lrupos;
273	u_int32_t rmode;
274	struct nfsnode *np = VTONFS(vp);
275	struct nfsvattr nfsva;
276
277	error = nfsrpc_accessrpc(vp, wmode, cred, td, &nfsva, &attrflag,
278	    &rmode, NULL);
279	if (attrflag)
280		(void) nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 0, 1);
281	if (!error) {
282		lrupos = 0;
283		mtx_lock(&np->n_mtx);
284		for (i = 0; i < NFS_ACCESSCACHESIZE; i++) {
285			if (np->n_accesscache[i].uid == cred->cr_uid) {
286				np->n_accesscache[i].mode = rmode;
287				np->n_accesscache[i].stamp = time_second;
288				break;
289			}
290			if (i > 0 && np->n_accesscache[i].stamp <
291			    np->n_accesscache[lrupos].stamp)
292				lrupos = i;
293		}
294		if (i == NFS_ACCESSCACHESIZE) {
295			np->n_accesscache[lrupos].uid = cred->cr_uid;
296			np->n_accesscache[lrupos].mode = rmode;
297			np->n_accesscache[lrupos].stamp = time_second;
298		}
299		mtx_unlock(&np->n_mtx);
300		if (retmode != NULL)
301			*retmode = rmode;
302	} else if (NFS_ISV4(vp)) {
303		error = nfscl_maperr(td, error, (uid_t)0, (gid_t)0);
304	}
305	return (error);
306}
307
308/*
309 * nfs access vnode op.
310 * For nfs version 2, just return ok. File accesses may fail later.
311 * For nfs version 3, use the access rpc to check accessibility. If file modes
312 * are changed on the server, accesses might still fail later.
313 */
314static int
315nfs_access(struct vop_access_args *ap)
316{
317	struct vnode *vp = ap->a_vp;
318	int error = 0, i, gotahit;
319	u_int32_t mode, wmode, rmode;
320	int v34 = NFS_ISV34(vp);
321	struct nfsnode *np = VTONFS(vp);
322
323	/*
324	 * Disallow write attempts on filesystems mounted read-only;
325	 * unless the file is a socket, fifo, or a block or character
326	 * device resident on the filesystem.
327	 */
328	if ((ap->a_accmode & (VWRITE | VAPPEND | VWRITE_NAMED_ATTRS |
329	    VDELETE_CHILD | VWRITE_ATTRIBUTES | VDELETE | VWRITE_ACL |
330	    VWRITE_OWNER)) != 0 && (vp->v_mount->mnt_flag & MNT_RDONLY) != 0) {
331		switch (vp->v_type) {
332		case VREG:
333		case VDIR:
334		case VLNK:
335			return (EROFS);
336		default:
337			break;
338		}
339	}
340	/*
341	 * For nfs v3 or v4, check to see if we have done this recently, and if
342	 * so return our cached result instead of making an ACCESS call.
343	 * If not, do an access rpc, otherwise you are stuck emulating
344	 * ufs_access() locally using the vattr. This may not be correct,
345	 * since the server may apply other access criteria such as
346	 * client uid-->server uid mapping that we do not know about.
347	 */
348	if (v34) {
349		if (ap->a_accmode & VREAD)
350			mode = NFSACCESS_READ;
351		else
352			mode = 0;
353		if (vp->v_type != VDIR) {
354			if (ap->a_accmode & VWRITE)
355				mode |= (NFSACCESS_MODIFY | NFSACCESS_EXTEND);
356			if (ap->a_accmode & VAPPEND)
357				mode |= NFSACCESS_EXTEND;
358			if (ap->a_accmode & VEXEC)
359				mode |= NFSACCESS_EXECUTE;
360			if (ap->a_accmode & VDELETE)
361				mode |= NFSACCESS_DELETE;
362		} else {
363			if (ap->a_accmode & VWRITE)
364				mode |= (NFSACCESS_MODIFY | NFSACCESS_EXTEND);
365			if (ap->a_accmode & VAPPEND)
366				mode |= NFSACCESS_EXTEND;
367			if (ap->a_accmode & VEXEC)
368				mode |= NFSACCESS_LOOKUP;
369			if (ap->a_accmode & VDELETE)
370				mode |= NFSACCESS_DELETE;
371			if (ap->a_accmode & VDELETE_CHILD)
372				mode |= NFSACCESS_MODIFY;
373		}
374		/* XXX safety belt, only make blanket request if caching */
375		if (nfsaccess_cache_timeout > 0) {
376			wmode = NFSACCESS_READ | NFSACCESS_MODIFY |
377				NFSACCESS_EXTEND | NFSACCESS_EXECUTE |
378				NFSACCESS_DELETE | NFSACCESS_LOOKUP;
379		} else {
380			wmode = mode;
381		}
382
383		/*
384		 * Does our cached result allow us to give a definite yes to
385		 * this request?
386		 */
387		gotahit = 0;
388		mtx_lock(&np->n_mtx);
389		for (i = 0; i < NFS_ACCESSCACHESIZE; i++) {
390			if (ap->a_cred->cr_uid == np->n_accesscache[i].uid) {
391			    if (time_second < (np->n_accesscache[i].stamp
392				+ nfsaccess_cache_timeout) &&
393				(np->n_accesscache[i].mode & mode) == mode) {
394				NFSINCRGLOBAL(newnfsstats.accesscache_hits);
395				gotahit = 1;
396			    }
397			    break;
398			}
399		}
400		mtx_unlock(&np->n_mtx);
401		if (gotahit == 0) {
402			/*
403			 * Either a no, or a don't know.  Go to the wire.
404			 */
405			NFSINCRGLOBAL(newnfsstats.accesscache_misses);
406		        error = nfs34_access_otw(vp, wmode, ap->a_td,
407			    ap->a_cred, &rmode);
408			if (!error &&
409			    (rmode & mode) != mode)
410				error = EACCES;
411		}
412		return (error);
413	} else {
414		if ((error = nfsspec_access(ap)) != 0) {
415			return (error);
416		}
417		/*
418		 * Attempt to prevent a mapped root from accessing a file
419		 * which it shouldn't.  We try to read a byte from the file
420		 * if the user is root and the file is not zero length.
421		 * After calling nfsspec_access, we should have the correct
422		 * file size cached.
423		 */
424		mtx_lock(&np->n_mtx);
425		if (ap->a_cred->cr_uid == 0 && (ap->a_accmode & VREAD)
426		    && VTONFS(vp)->n_size > 0) {
427			struct iovec aiov;
428			struct uio auio;
429			char buf[1];
430
431			mtx_unlock(&np->n_mtx);
432			aiov.iov_base = buf;
433			aiov.iov_len = 1;
434			auio.uio_iov = &aiov;
435			auio.uio_iovcnt = 1;
436			auio.uio_offset = 0;
437			auio.uio_resid = 1;
438			auio.uio_segflg = UIO_SYSSPACE;
439			auio.uio_rw = UIO_READ;
440			auio.uio_td = ap->a_td;
441
442			if (vp->v_type == VREG)
443				error = ncl_readrpc(vp, &auio, ap->a_cred);
444			else if (vp->v_type == VDIR) {
445				char* bp;
446				bp = malloc(NFS_DIRBLKSIZ, M_TEMP, M_WAITOK);
447				aiov.iov_base = bp;
448				aiov.iov_len = auio.uio_resid = NFS_DIRBLKSIZ;
449				error = ncl_readdirrpc(vp, &auio, ap->a_cred,
450				    ap->a_td);
451				free(bp, M_TEMP);
452			} else if (vp->v_type == VLNK)
453				error = ncl_readlinkrpc(vp, &auio, ap->a_cred);
454			else
455				error = EACCES;
456		} else
457			mtx_unlock(&np->n_mtx);
458		return (error);
459	}
460}
461
462
463/*
464 * nfs open vnode op
465 * Check to see if the type is ok
466 * and that deletion is not in progress.
467 * For paged in text files, you will need to flush the page cache
468 * if consistency is lost.
469 */
470/* ARGSUSED */
471static int
472nfs_open(struct vop_open_args *ap)
473{
474	struct vnode *vp = ap->a_vp;
475	struct nfsnode *np = VTONFS(vp);
476	struct vattr vattr;
477	int error;
478	int fmode = ap->a_mode;
479
480	if (vp->v_type != VREG && vp->v_type != VDIR && vp->v_type != VLNK)
481		return (EOPNOTSUPP);
482
483	/*
484	 * For NFSv4, we need to do the Open Op before cache validation,
485	 * so that we conform to RFC3530 Sec. 9.3.1.
486	 */
487	if (NFS_ISV4(vp)) {
488		error = nfsrpc_open(vp, fmode, ap->a_cred, ap->a_td);
489		if (error) {
490			error = nfscl_maperr(ap->a_td, error, (uid_t)0,
491			    (gid_t)0);
492			return (error);
493		}
494	}
495
496	/*
497	 * Now, if this Open will be doing reading, re-validate/flush the
498	 * cache, so that Close/Open coherency is maintained.
499	 */
500	mtx_lock(&np->n_mtx);
501	if (np->n_flag & NMODIFIED) {
502		mtx_unlock(&np->n_mtx);
503		error = ncl_vinvalbuf(vp, V_SAVE, ap->a_td, 1);
504		if (error == EINTR || error == EIO) {
505			if (NFS_ISV4(vp))
506				(void) nfsrpc_close(vp, 0, ap->a_td);
507			return (error);
508		}
509		mtx_lock(&np->n_mtx);
510		np->n_attrstamp = 0;
511		if (vp->v_type == VDIR)
512			np->n_direofoffset = 0;
513		mtx_unlock(&np->n_mtx);
514		error = VOP_GETATTR(vp, &vattr, ap->a_cred);
515		if (error) {
516			if (NFS_ISV4(vp))
517				(void) nfsrpc_close(vp, 0, ap->a_td);
518			return (error);
519		}
520		mtx_lock(&np->n_mtx);
521		np->n_mtime = vattr.va_mtime;
522		if (NFS_ISV4(vp))
523			np->n_change = vattr.va_filerev;
524	} else {
525		mtx_unlock(&np->n_mtx);
526		error = VOP_GETATTR(vp, &vattr, ap->a_cred);
527		if (error) {
528			if (NFS_ISV4(vp))
529				(void) nfsrpc_close(vp, 0, ap->a_td);
530			return (error);
531		}
532		mtx_lock(&np->n_mtx);
533		if ((NFS_ISV4(vp) && np->n_change != vattr.va_filerev) ||
534		    NFS_TIMESPEC_COMPARE(&np->n_mtime, &vattr.va_mtime)) {
535			if (vp->v_type == VDIR)
536				np->n_direofoffset = 0;
537			mtx_unlock(&np->n_mtx);
538			error = ncl_vinvalbuf(vp, V_SAVE, ap->a_td, 1);
539			if (error == EINTR || error == EIO) {
540				if (NFS_ISV4(vp))
541					(void) nfsrpc_close(vp, 0, ap->a_td);
542				return (error);
543			}
544			mtx_lock(&np->n_mtx);
545			np->n_mtime = vattr.va_mtime;
546			if (NFS_ISV4(vp))
547				np->n_change = vattr.va_filerev;
548		}
549	}
550
551	/*
552	 * If the object has >= 1 O_DIRECT active opens, we disable caching.
553	 */
554	if (newnfs_directio_enable && (fmode & O_DIRECT) &&
555	    (vp->v_type == VREG)) {
556		if (np->n_directio_opens == 0) {
557			mtx_unlock(&np->n_mtx);
558			error = ncl_vinvalbuf(vp, V_SAVE, ap->a_td, 1);
559			if (error) {
560				if (NFS_ISV4(vp))
561					(void) nfsrpc_close(vp, 0, ap->a_td);
562				return (error);
563			}
564			mtx_lock(&np->n_mtx);
565			np->n_flag |= NNONCACHE;
566		}
567		np->n_directio_opens++;
568	}
569	mtx_unlock(&np->n_mtx);
570	vnode_create_vobject(vp, vattr.va_size, ap->a_td);
571	return (0);
572}
573
574/*
575 * nfs close vnode op
576 * What an NFS client should do upon close after writing is a debatable issue.
577 * Most NFS clients push delayed writes to the server upon close, basically for
578 * two reasons:
579 * 1 - So that any write errors may be reported back to the client process
580 *     doing the close system call. By far the two most likely errors are
581 *     NFSERR_NOSPC and NFSERR_DQUOT to indicate space allocation failure.
582 * 2 - To put a worst case upper bound on cache inconsistency between
583 *     multiple clients for the file.
584 * There is also a consistency problem for Version 2 of the protocol w.r.t.
585 * not being able to tell if other clients are writing a file concurrently,
586 * since there is no way of knowing if the changed modify time in the reply
587 * is only due to the write for this client.
588 * (NFS Version 3 provides weak cache consistency data in the reply that
589 *  should be sufficient to detect and handle this case.)
590 *
591 * The current code does the following:
592 * for NFS Version 2 - play it safe and flush/invalidate all dirty buffers
593 * for NFS Version 3 - flush dirty buffers to the server but don't invalidate
594 *                     or commit them (this satisfies 1 and 2 except for the
595 *                     case where the server crashes after this close but
596 *                     before the commit RPC, which is felt to be "good
597 *                     enough". Changing the last argument to ncl_flush() to
598 *                     a 1 would force a commit operation, if it is felt a
599 *                     commit is necessary now.
600 * for NFS Version 4 - flush the dirty buffers and commit them, if
601 *		       nfscl_mustflush() says this is necessary.
602 *                     It is necessary if there is no write delegation held,
603 *                     in order to satisfy open/close coherency.
604 *                     If the file isn't cached on local stable storage,
605 *                     it may be necessary in order to detect "out of space"
606 *                     errors from the server, if the write delegation
607 *                     issued by the server doesn't allow the file to grow.
608 */
609/* ARGSUSED */
610static int
611nfs_close(struct vop_close_args *ap)
612{
613	struct vnode *vp = ap->a_vp;
614	struct nfsnode *np = VTONFS(vp);
615	struct nfsvattr nfsva;
616	struct ucred *cred;
617	int error = 0, ret, localcred = 0;
618	int fmode = ap->a_fflag;
619
620	if ((vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF))
621		return (0);
622	/*
623	 * During shutdown, a_cred isn't valid, so just use root.
624	 */
625	if (ap->a_cred == NOCRED) {
626		cred = newnfs_getcred();
627		localcred = 1;
628	} else {
629		cred = ap->a_cred;
630	}
631	if (vp->v_type == VREG) {
632	    /*
633	     * Examine and clean dirty pages, regardless of NMODIFIED.
634	     * This closes a major hole in close-to-open consistency.
635	     * We want to push out all dirty pages (and buffers) on
636	     * close, regardless of whether they were dirtied by
637	     * mmap'ed writes or via write().
638	     */
639	    if (nfs_clean_pages_on_close && vp->v_object) {
640		VM_OBJECT_LOCK(vp->v_object);
641		vm_object_page_clean(vp->v_object, 0, 0, 0);
642		VM_OBJECT_UNLOCK(vp->v_object);
643	    }
644	    mtx_lock(&np->n_mtx);
645	    if (np->n_flag & NMODIFIED) {
646		mtx_unlock(&np->n_mtx);
647		if (NFS_ISV3(vp)) {
648		    /*
649		     * Under NFSv3 we have dirty buffers to dispose of.  We
650		     * must flush them to the NFS server.  We have the option
651		     * of waiting all the way through the commit rpc or just
652		     * waiting for the initial write.  The default is to only
653		     * wait through the initial write so the data is in the
654		     * server's cache, which is roughly similar to the state
655		     * a standard disk subsystem leaves the file in on close().
656		     *
657		     * We cannot clear the NMODIFIED bit in np->n_flag due to
658		     * potential races with other processes, and certainly
659		     * cannot clear it if we don't commit.
660		     * These races occur when there is no longer the old
661		     * traditional vnode locking implemented for Vnode Ops.
662		     */
663		    int cm = newnfs_commit_on_close ? 1 : 0;
664		    error = ncl_flush(vp, MNT_WAIT, cred, ap->a_td, cm, 0);
665		    /* np->n_flag &= ~NMODIFIED; */
666		} else if (NFS_ISV4(vp)) {
667			if (nfscl_mustflush(vp) != 0) {
668				int cm = newnfs_commit_on_close ? 1 : 0;
669				error = ncl_flush(vp, MNT_WAIT, cred, ap->a_td,
670				    cm, 0);
671				/*
672				 * as above w.r.t races when clearing
673				 * NMODIFIED.
674				 * np->n_flag &= ~NMODIFIED;
675				 */
676			}
677		} else
678		    error = ncl_vinvalbuf(vp, V_SAVE, ap->a_td, 1);
679		mtx_lock(&np->n_mtx);
680	    }
681 	    /*
682 	     * Invalidate the attribute cache in all cases.
683 	     * An open is going to fetch fresh attrs any way, other procs
684 	     * on this node that have file open will be forced to do an
685 	     * otw attr fetch, but this is safe.
686	     * --> A user found that their RPC count dropped by 20% when
687	     *     this was commented out and I can't see any requirement
688	     *     for it, so I've disabled it when negative lookups are
689	     *     enabled. (What does this have to do with negative lookup
690	     *     caching? Well nothing, except it was reported by the
691	     *     same user that needed negative lookup caching and I wanted
692	     *     there to be a way to disable it to see if it
693	     *     is the cause of some caching/coherency issue that might
694	     *     crop up.)
695 	     */
696	    if (VFSTONFS(vp->v_mount)->nm_negnametimeo == 0)
697		    np->n_attrstamp = 0;
698	    if (np->n_flag & NWRITEERR) {
699		np->n_flag &= ~NWRITEERR;
700		error = np->n_error;
701	    }
702	    mtx_unlock(&np->n_mtx);
703	}
704
705	if (NFS_ISV4(vp)) {
706		/*
707		 * Get attributes so "change" is up to date.
708		 */
709		if (error == 0 && nfscl_mustflush(vp) != 0) {
710			ret = nfsrpc_getattr(vp, cred, ap->a_td, &nfsva,
711			    NULL);
712			if (!ret) {
713				np->n_change = nfsva.na_filerev;
714				(void) nfscl_loadattrcache(&vp, &nfsva, NULL,
715				    NULL, 0, 0);
716			}
717		}
718
719		/*
720		 * and do the close.
721		 */
722		ret = nfsrpc_close(vp, 0, ap->a_td);
723		if (!error && ret)
724			error = ret;
725		if (error)
726			error = nfscl_maperr(ap->a_td, error, (uid_t)0,
727			    (gid_t)0);
728	}
729	if (newnfs_directio_enable)
730		KASSERT((np->n_directio_asyncwr == 0),
731			("nfs_close: dirty unflushed (%d) directio buffers\n",
732			 np->n_directio_asyncwr));
733	if (newnfs_directio_enable && (fmode & O_DIRECT) && (vp->v_type == VREG)) {
734		mtx_lock(&np->n_mtx);
735		KASSERT((np->n_directio_opens > 0),
736			("nfs_close: unexpectedly value (0) of n_directio_opens\n"));
737		np->n_directio_opens--;
738		if (np->n_directio_opens == 0)
739			np->n_flag &= ~NNONCACHE;
740		mtx_unlock(&np->n_mtx);
741	}
742	if (localcred)
743		NFSFREECRED(cred);
744	return (error);
745}
746
747/*
748 * nfs getattr call from vfs.
749 */
750static int
751nfs_getattr(struct vop_getattr_args *ap)
752{
753	struct vnode *vp = ap->a_vp;
754	struct thread *td = curthread;	/* XXX */
755	struct nfsnode *np = VTONFS(vp);
756	int error = 0;
757	struct nfsvattr nfsva;
758	struct vattr *vap = ap->a_vap;
759	struct vattr vattr;
760
761	/*
762	 * Update local times for special files.
763	 */
764	mtx_lock(&np->n_mtx);
765	if (np->n_flag & (NACC | NUPD))
766		np->n_flag |= NCHG;
767	mtx_unlock(&np->n_mtx);
768	/*
769	 * First look in the cache.
770	 */
771	if (ncl_getattrcache(vp, &vattr) == 0) {
772		vap->va_type = vattr.va_type;
773		vap->va_mode = vattr.va_mode;
774		vap->va_nlink = vattr.va_nlink;
775		vap->va_uid = vattr.va_uid;
776		vap->va_gid = vattr.va_gid;
777		vap->va_fsid = vattr.va_fsid;
778		vap->va_fileid = vattr.va_fileid;
779		vap->va_size = vattr.va_size;
780		vap->va_blocksize = vattr.va_blocksize;
781		vap->va_atime = vattr.va_atime;
782		vap->va_mtime = vattr.va_mtime;
783		vap->va_ctime = vattr.va_ctime;
784		vap->va_gen = vattr.va_gen;
785		vap->va_flags = vattr.va_flags;
786		vap->va_rdev = vattr.va_rdev;
787		vap->va_bytes = vattr.va_bytes;
788		vap->va_filerev = vattr.va_filerev;
789		/*
790		 * Get the local modify time for the case of a write
791		 * delegation.
792		 */
793		nfscl_deleggetmodtime(vp, &vap->va_mtime);
794		return (0);
795	}
796
797	if (NFS_ISV34(vp) && nfs_prime_access_cache &&
798	    nfsaccess_cache_timeout > 0) {
799		NFSINCRGLOBAL(newnfsstats.accesscache_misses);
800		nfs34_access_otw(vp, NFSACCESS_ALL, td, ap->a_cred, NULL);
801		if (ncl_getattrcache(vp, ap->a_vap) == 0) {
802			nfscl_deleggetmodtime(vp, &ap->a_vap->va_mtime);
803			return (0);
804		}
805	}
806	error = nfsrpc_getattr(vp, ap->a_cred, td, &nfsva, NULL);
807	if (!error)
808		error = nfscl_loadattrcache(&vp, &nfsva, vap, NULL, 0, 0);
809	if (!error) {
810		/*
811		 * Get the local modify time for the case of a write
812		 * delegation.
813		 */
814		nfscl_deleggetmodtime(vp, &vap->va_mtime);
815	} else if (NFS_ISV4(vp)) {
816		error = nfscl_maperr(td, error, (uid_t)0, (gid_t)0);
817	}
818	return (error);
819}
820
821/*
822 * nfs setattr call.
823 */
824static int
825nfs_setattr(struct vop_setattr_args *ap)
826{
827	struct vnode *vp = ap->a_vp;
828	struct nfsnode *np = VTONFS(vp);
829	struct thread *td = curthread;	/* XXX */
830	struct vattr *vap = ap->a_vap;
831	int error = 0;
832	u_quad_t tsize;
833
834#ifndef nolint
835	tsize = (u_quad_t)0;
836#endif
837
838	/*
839	 * Setting of flags and marking of atimes are not supported.
840	 */
841	if (vap->va_flags != VNOVAL)
842		return (EOPNOTSUPP);
843
844	/*
845	 * Disallow write attempts if the filesystem is mounted read-only.
846	 */
847  	if ((vap->va_flags != VNOVAL || vap->va_uid != (uid_t)VNOVAL ||
848	    vap->va_gid != (gid_t)VNOVAL || vap->va_atime.tv_sec != VNOVAL ||
849	    vap->va_mtime.tv_sec != VNOVAL || vap->va_mode != (mode_t)VNOVAL) &&
850	    (vp->v_mount->mnt_flag & MNT_RDONLY))
851		return (EROFS);
852	if (vap->va_size != VNOVAL) {
853 		switch (vp->v_type) {
854 		case VDIR:
855 			return (EISDIR);
856 		case VCHR:
857 		case VBLK:
858 		case VSOCK:
859 		case VFIFO:
860			if (vap->va_mtime.tv_sec == VNOVAL &&
861			    vap->va_atime.tv_sec == VNOVAL &&
862			    vap->va_mode == (mode_t)VNOVAL &&
863			    vap->va_uid == (uid_t)VNOVAL &&
864			    vap->va_gid == (gid_t)VNOVAL)
865				return (0);
866 			vap->va_size = VNOVAL;
867 			break;
868 		default:
869			/*
870			 * Disallow write attempts if the filesystem is
871			 * mounted read-only.
872			 */
873			if (vp->v_mount->mnt_flag & MNT_RDONLY)
874				return (EROFS);
875			/*
876			 *  We run vnode_pager_setsize() early (why?),
877			 * we must set np->n_size now to avoid vinvalbuf
878			 * V_SAVE races that might setsize a lower
879			 * value.
880			 */
881			mtx_lock(&np->n_mtx);
882			tsize = np->n_size;
883			mtx_unlock(&np->n_mtx);
884			error = ncl_meta_setsize(vp, ap->a_cred, td,
885			    vap->va_size);
886			mtx_lock(&np->n_mtx);
887 			if (np->n_flag & NMODIFIED) {
888			    tsize = np->n_size;
889			    mtx_unlock(&np->n_mtx);
890 			    if (vap->va_size == 0)
891 				error = ncl_vinvalbuf(vp, 0, td, 1);
892 			    else
893 				error = ncl_vinvalbuf(vp, V_SAVE, td, 1);
894 			    if (error) {
895				vnode_pager_setsize(vp, tsize);
896				return (error);
897			    }
898			    /*
899			     * Call nfscl_delegmodtime() to set the modify time
900			     * locally, as required.
901			     */
902			    nfscl_delegmodtime(vp);
903 			} else
904			    mtx_unlock(&np->n_mtx);
905			/*
906			 * np->n_size has already been set to vap->va_size
907			 * in ncl_meta_setsize(). We must set it again since
908			 * nfs_loadattrcache() could be called through
909			 * ncl_meta_setsize() and could modify np->n_size.
910			 */
911			mtx_lock(&np->n_mtx);
912 			np->n_vattr.na_size = np->n_size = vap->va_size;
913			mtx_unlock(&np->n_mtx);
914  		};
915  	} else {
916		mtx_lock(&np->n_mtx);
917		if ((vap->va_mtime.tv_sec != VNOVAL || vap->va_atime.tv_sec != VNOVAL) &&
918		    (np->n_flag & NMODIFIED) && vp->v_type == VREG) {
919			mtx_unlock(&np->n_mtx);
920			if ((error = ncl_vinvalbuf(vp, V_SAVE, td, 1)) != 0 &&
921			    (error == EINTR || error == EIO))
922				return (error);
923		} else
924			mtx_unlock(&np->n_mtx);
925	}
926	error = nfs_setattrrpc(vp, vap, ap->a_cred, td);
927	if (error && vap->va_size != VNOVAL) {
928		mtx_lock(&np->n_mtx);
929		np->n_size = np->n_vattr.na_size = tsize;
930		vnode_pager_setsize(vp, tsize);
931		mtx_unlock(&np->n_mtx);
932	}
933	return (error);
934}
935
936/*
937 * Do an nfs setattr rpc.
938 */
939static int
940nfs_setattrrpc(struct vnode *vp, struct vattr *vap, struct ucred *cred,
941    struct thread *td)
942{
943	struct nfsnode *np = VTONFS(vp);
944	int error, ret, attrflag, i;
945	struct nfsvattr nfsva;
946
947	if (NFS_ISV34(vp)) {
948		mtx_lock(&np->n_mtx);
949		for (i = 0; i < NFS_ACCESSCACHESIZE; i++)
950			np->n_accesscache[i].stamp = 0;
951		np->n_flag |= NDELEGMOD;
952		mtx_unlock(&np->n_mtx);
953	}
954	error = nfsrpc_setattr(vp, vap, NULL, cred, td, &nfsva, &attrflag,
955	    NULL);
956	if (attrflag) {
957		ret = nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 0, 1);
958		if (ret && !error)
959			error = ret;
960	}
961	if (error && NFS_ISV4(vp))
962		error = nfscl_maperr(td, error, vap->va_uid, vap->va_gid);
963	return (error);
964}
965
966/*
967 * nfs lookup call, one step at a time...
968 * First look in cache
969 * If not found, unlock the directory nfsnode and do the rpc
970 */
971static int
972nfs_lookup(struct vop_lookup_args *ap)
973{
974	struct componentname *cnp = ap->a_cnp;
975	struct vnode *dvp = ap->a_dvp;
976	struct vnode **vpp = ap->a_vpp;
977	struct mount *mp = dvp->v_mount;
978	int flags = cnp->cn_flags;
979	struct vnode *newvp;
980	struct nfsmount *nmp;
981	struct nfsnode *np, *newnp;
982	int error = 0, attrflag, dattrflag, ltype;
983	struct thread *td = cnp->cn_thread;
984	struct nfsfh *nfhp;
985	struct nfsvattr dnfsva, nfsva;
986	struct vattr vattr;
987	struct timespec dmtime;
988
989	*vpp = NULLVP;
990	if ((flags & ISLASTCN) && (mp->mnt_flag & MNT_RDONLY) &&
991	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
992		return (EROFS);
993	if (dvp->v_type != VDIR)
994		return (ENOTDIR);
995	nmp = VFSTONFS(mp);
996	np = VTONFS(dvp);
997
998	/* For NFSv4, wait until any remove is done. */
999	mtx_lock(&np->n_mtx);
1000	while (NFSHASNFSV4(nmp) && (np->n_flag & NREMOVEINPROG)) {
1001		np->n_flag |= NREMOVEWANT;
1002		(void) msleep((caddr_t)np, &np->n_mtx, PZERO, "nfslkup", 0);
1003	}
1004	mtx_unlock(&np->n_mtx);
1005
1006	if ((error = VOP_ACCESS(dvp, VEXEC, cnp->cn_cred, td)) != 0)
1007		return (error);
1008	error = cache_lookup(dvp, vpp, cnp);
1009	if (error > 0 && error != ENOENT)
1010		return (error);
1011	if (error == -1) {
1012		/*
1013		 * We only accept a positive hit in the cache if the
1014		 * change time of the file matches our cached copy.
1015		 * Otherwise, we discard the cache entry and fallback
1016		 * to doing a lookup RPC.
1017		 *
1018		 * To better handle stale file handles and attributes,
1019		 * clear the attribute cache of this node if it is a
1020		 * leaf component, part of an open() call, and not
1021		 * locally modified before fetching the attributes.
1022		 * This should allow stale file handles to be detected
1023		 * here where we can fall back to a LOOKUP RPC to
1024		 * recover rather than having nfs_open() detect the
1025		 * stale file handle and failing open(2) with ESTALE.
1026		 */
1027		newvp = *vpp;
1028		newnp = VTONFS(newvp);
1029		if ((flags & (ISLASTCN | ISOPEN)) == (ISLASTCN | ISOPEN) &&
1030		    !(newnp->n_flag & NMODIFIED)) {
1031			mtx_lock(&newnp->n_mtx);
1032			newnp->n_attrstamp = 0;
1033			mtx_unlock(&newnp->n_mtx);
1034		}
1035		if (nfscl_nodeleg(newvp, 0) == 0 ||
1036		    (VOP_GETATTR(newvp, &vattr, cnp->cn_cred) == 0 &&
1037		    timespeccmp(&vattr.va_ctime, &newnp->n_ctime, ==))) {
1038			NFSINCRGLOBAL(newnfsstats.lookupcache_hits);
1039			if (cnp->cn_nameiop != LOOKUP &&
1040			    (flags & ISLASTCN))
1041				cnp->cn_flags |= SAVENAME;
1042			return (0);
1043		}
1044		cache_purge(newvp);
1045		if (dvp != newvp)
1046			vput(newvp);
1047		else
1048			vrele(newvp);
1049		*vpp = NULLVP;
1050	} else if (error == ENOENT) {
1051		if (dvp->v_iflag & VI_DOOMED)
1052			return (ENOENT);
1053		/*
1054		 * We only accept a negative hit in the cache if the
1055		 * modification time of the parent directory matches
1056		 * our cached copy.  Otherwise, we discard all of the
1057		 * negative cache entries for this directory. We also
1058		 * only trust -ve cache entries for less than
1059		 * nm_negative_namecache_timeout seconds.
1060		 */
1061		if ((u_int)(ticks - np->n_dmtime_ticks) <
1062		    (nmp->nm_negnametimeo * hz) &&
1063		    VOP_GETATTR(dvp, &vattr, cnp->cn_cred) == 0 &&
1064		    timespeccmp(&vattr.va_mtime, &np->n_dmtime, ==)) {
1065			NFSINCRGLOBAL(newnfsstats.lookupcache_hits);
1066			return (ENOENT);
1067		}
1068		cache_purge_negative(dvp);
1069		mtx_lock(&np->n_mtx);
1070		timespecclear(&np->n_dmtime);
1071		mtx_unlock(&np->n_mtx);
1072	}
1073
1074	/*
1075	 * Cache the modification time of the parent directory in case
1076	 * the lookup fails and results in adding the first negative
1077	 * name cache entry for the directory.  Since this is reading
1078	 * a single time_t, don't bother with locking.  The
1079	 * modification time may be a bit stale, but it must be read
1080	 * before performing the lookup RPC to prevent a race where
1081	 * another lookup updates the timestamp on the directory after
1082	 * the lookup RPC has been performed on the server but before
1083	 * n_dmtime is set at the end of this function.
1084	 */
1085	dmtime = np->n_vattr.na_mtime;
1086	error = 0;
1087	newvp = NULLVP;
1088	NFSINCRGLOBAL(newnfsstats.lookupcache_misses);
1089	error = nfsrpc_lookup(dvp, cnp->cn_nameptr, cnp->cn_namelen,
1090	    cnp->cn_cred, td, &dnfsva, &nfsva, &nfhp, &attrflag, &dattrflag,
1091	    NULL);
1092	if (dattrflag)
1093		(void) nfscl_loadattrcache(&dvp, &dnfsva, NULL, NULL, 0, 1);
1094	if (error) {
1095		if (newvp != NULLVP) {
1096			vput(newvp);
1097			*vpp = NULLVP;
1098		}
1099
1100		if (error != ENOENT) {
1101			if (NFS_ISV4(dvp))
1102				error = nfscl_maperr(td, error, (uid_t)0,
1103				    (gid_t)0);
1104			return (error);
1105		}
1106
1107		/* The requested file was not found. */
1108		if ((cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME) &&
1109		    (flags & ISLASTCN)) {
1110			/*
1111			 * XXX: UFS does a full VOP_ACCESS(dvp,
1112			 * VWRITE) here instead of just checking
1113			 * MNT_RDONLY.
1114			 */
1115			if (mp->mnt_flag & MNT_RDONLY)
1116				return (EROFS);
1117			cnp->cn_flags |= SAVENAME;
1118			return (EJUSTRETURN);
1119		}
1120
1121		if ((cnp->cn_flags & MAKEENTRY) && cnp->cn_nameiop != CREATE) {
1122			/*
1123			 * Maintain n_dmtime as the modification time
1124			 * of the parent directory when the oldest -ve
1125			 * name cache entry for this directory was
1126			 * added.  If a -ve cache entry has already
1127			 * been added with a newer modification time
1128			 * by a concurrent lookup, then don't bother
1129			 * adding a cache entry.  The modification
1130			 * time of the directory might have changed
1131			 * due to the file this lookup failed to find
1132			 * being created.  In that case a subsequent
1133			 * lookup would incorrectly use the entry
1134			 * added here instead of doing an extra
1135			 * lookup.
1136			 */
1137			mtx_lock(&np->n_mtx);
1138			if (timespeccmp(&np->n_dmtime, &dmtime, <=)) {
1139				if (!timespecisset(&np->n_dmtime)) {
1140					np->n_dmtime = dmtime;
1141					np->n_dmtime_ticks = ticks;
1142				}
1143				mtx_unlock(&np->n_mtx);
1144				cache_enter(dvp, NULL, cnp);
1145			} else
1146				mtx_unlock(&np->n_mtx);
1147		}
1148		return (ENOENT);
1149	}
1150
1151	/*
1152	 * Handle RENAME case...
1153	 */
1154	if (cnp->cn_nameiop == RENAME && (flags & ISLASTCN)) {
1155		if (NFS_CMPFH(np, nfhp->nfh_fh, nfhp->nfh_len)) {
1156			FREE((caddr_t)nfhp, M_NFSFH);
1157			return (EISDIR);
1158		}
1159		error = nfscl_nget(mp, dvp, nfhp, cnp, td, &np, NULL,
1160		    LK_EXCLUSIVE);
1161		if (error)
1162			return (error);
1163		newvp = NFSTOV(np);
1164		if (attrflag)
1165			(void) nfscl_loadattrcache(&newvp, &nfsva, NULL, NULL,
1166			    0, 1);
1167		*vpp = newvp;
1168		cnp->cn_flags |= SAVENAME;
1169		return (0);
1170	}
1171
1172	if (flags & ISDOTDOT) {
1173		ltype = VOP_ISLOCKED(dvp);
1174		error = vfs_busy(mp, MBF_NOWAIT);
1175		if (error != 0) {
1176			vfs_ref(mp);
1177			VOP_UNLOCK(dvp, 0);
1178			error = vfs_busy(mp, 0);
1179			vn_lock(dvp, ltype | LK_RETRY);
1180			vfs_rel(mp);
1181			if (error == 0 && (dvp->v_iflag & VI_DOOMED)) {
1182				vfs_unbusy(mp);
1183				error = ENOENT;
1184			}
1185			if (error != 0)
1186				return (error);
1187		}
1188		VOP_UNLOCK(dvp, 0);
1189		error = nfscl_nget(mp, dvp, nfhp, cnp, td, &np, NULL,
1190		    cnp->cn_lkflags);
1191		if (error == 0)
1192			newvp = NFSTOV(np);
1193		vfs_unbusy(mp);
1194		if (newvp != dvp)
1195			vn_lock(dvp, ltype | LK_RETRY);
1196		if (dvp->v_iflag & VI_DOOMED) {
1197			if (error == 0) {
1198				if (newvp == dvp)
1199					vrele(newvp);
1200				else
1201					vput(newvp);
1202			}
1203			error = ENOENT;
1204		}
1205		if (error != 0)
1206			return (error);
1207		if (attrflag)
1208			(void) nfscl_loadattrcache(&newvp, &nfsva, NULL, NULL,
1209			    0, 1);
1210	} else if (NFS_CMPFH(np, nfhp->nfh_fh, nfhp->nfh_len)) {
1211		FREE((caddr_t)nfhp, M_NFSFH);
1212		VREF(dvp);
1213		newvp = dvp;
1214		if (attrflag)
1215			(void) nfscl_loadattrcache(&newvp, &nfsva, NULL, NULL,
1216			    0, 1);
1217	} else {
1218		error = nfscl_nget(mp, dvp, nfhp, cnp, td, &np, NULL,
1219		    cnp->cn_lkflags);
1220		if (error)
1221			return (error);
1222		newvp = NFSTOV(np);
1223		if (attrflag)
1224			(void) nfscl_loadattrcache(&newvp, &nfsva, NULL, NULL,
1225			    0, 1);
1226		else if ((flags & (ISLASTCN | ISOPEN)) == (ISLASTCN | ISOPEN) &&
1227		    !(np->n_flag & NMODIFIED)) {
1228			/*
1229			 * Flush the attribute cache when opening a
1230			 * leaf node to ensure that fresh attributes
1231			 * are fetched in nfs_open() since we did not
1232			 * fetch attributes from the LOOKUP reply.
1233			 */
1234			mtx_lock(&np->n_mtx);
1235			np->n_attrstamp = 0;
1236			mtx_unlock(&np->n_mtx);
1237		}
1238	}
1239	if (cnp->cn_nameiop != LOOKUP && (flags & ISLASTCN))
1240		cnp->cn_flags |= SAVENAME;
1241	if ((cnp->cn_flags & MAKEENTRY) &&
1242	    (cnp->cn_nameiop != DELETE || !(flags & ISLASTCN))) {
1243		np->n_ctime = np->n_vattr.na_vattr.va_ctime;
1244		cache_enter(dvp, newvp, cnp);
1245	}
1246	*vpp = newvp;
1247	return (0);
1248}
1249
1250/*
1251 * nfs read call.
1252 * Just call ncl_bioread() to do the work.
1253 */
1254static int
1255nfs_read(struct vop_read_args *ap)
1256{
1257	struct vnode *vp = ap->a_vp;
1258
1259	switch (vp->v_type) {
1260	case VREG:
1261		return (ncl_bioread(vp, ap->a_uio, ap->a_ioflag, ap->a_cred));
1262	case VDIR:
1263		return (EISDIR);
1264	default:
1265		return (EOPNOTSUPP);
1266	}
1267}
1268
1269/*
1270 * nfs readlink call
1271 */
1272static int
1273nfs_readlink(struct vop_readlink_args *ap)
1274{
1275	struct vnode *vp = ap->a_vp;
1276
1277	if (vp->v_type != VLNK)
1278		return (EINVAL);
1279	return (ncl_bioread(vp, ap->a_uio, 0, ap->a_cred));
1280}
1281
1282/*
1283 * Do a readlink rpc.
1284 * Called by ncl_doio() from below the buffer cache.
1285 */
1286int
1287ncl_readlinkrpc(struct vnode *vp, struct uio *uiop, struct ucred *cred)
1288{
1289	int error, ret, attrflag;
1290	struct nfsvattr nfsva;
1291
1292	error = nfsrpc_readlink(vp, uiop, cred, uiop->uio_td, &nfsva,
1293	    &attrflag, NULL);
1294	if (attrflag) {
1295		ret = nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 0, 1);
1296		if (ret && !error)
1297			error = ret;
1298	}
1299	if (error && NFS_ISV4(vp))
1300		error = nfscl_maperr(uiop->uio_td, error, (uid_t)0, (gid_t)0);
1301	return (error);
1302}
1303
1304/*
1305 * nfs read rpc call
1306 * Ditto above
1307 */
1308int
1309ncl_readrpc(struct vnode *vp, struct uio *uiop, struct ucred *cred)
1310{
1311	int error, ret, attrflag;
1312	struct nfsvattr nfsva;
1313
1314	error = nfsrpc_read(vp, uiop, cred, uiop->uio_td, &nfsva, &attrflag,
1315	    NULL);
1316	if (attrflag) {
1317		ret = nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 0, 1);
1318		if (ret && !error)
1319			error = ret;
1320	}
1321	if (error && NFS_ISV4(vp))
1322		error = nfscl_maperr(uiop->uio_td, error, (uid_t)0, (gid_t)0);
1323	return (error);
1324}
1325
1326/*
1327 * nfs write call
1328 */
1329int
1330ncl_writerpc(struct vnode *vp, struct uio *uiop, struct ucred *cred,
1331    int *iomode, int *must_commit, int called_from_strategy)
1332{
1333	struct nfsvattr nfsva;
1334	int error = 0, attrflag, ret;
1335	u_char verf[NFSX_VERF];
1336	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1337
1338	*must_commit = 0;
1339	error = nfsrpc_write(vp, uiop, iomode, verf, cred,
1340	    uiop->uio_td, &nfsva, &attrflag, NULL, called_from_strategy);
1341	NFSLOCKMNT(nmp);
1342	if (!error && NFSHASWRITEVERF(nmp) &&
1343	    NFSBCMP(verf, nmp->nm_verf, NFSX_VERF)) {
1344		*must_commit = 1;
1345		NFSBCOPY(verf, nmp->nm_verf, NFSX_VERF);
1346	}
1347	NFSUNLOCKMNT(nmp);
1348	if (attrflag) {
1349		if (VTONFS(vp)->n_flag & ND_NFSV4)
1350			ret = nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 1,
1351			    1);
1352		else
1353			ret = nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 0,
1354			    1);
1355		if (ret && !error)
1356			error = ret;
1357	}
1358	if (vp->v_mount->mnt_kern_flag & MNTK_ASYNC)
1359		*iomode = NFSWRITE_FILESYNC;
1360	if (error && NFS_ISV4(vp))
1361		error = nfscl_maperr(uiop->uio_td, error, (uid_t)0, (gid_t)0);
1362	return (error);
1363}
1364
1365/*
1366 * nfs mknod rpc
1367 * For NFS v2 this is a kludge. Use a create rpc but with the IFMT bits of the
1368 * mode set to specify the file type and the size field for rdev.
1369 */
1370static int
1371nfs_mknodrpc(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1372    struct vattr *vap)
1373{
1374	struct nfsvattr nfsva, dnfsva;
1375	struct vnode *newvp = NULL;
1376	struct nfsnode *np = NULL, *dnp;
1377	struct nfsfh *nfhp;
1378	struct vattr vattr;
1379	int error = 0, attrflag, dattrflag;
1380	u_int32_t rdev;
1381
1382	if (vap->va_type == VCHR || vap->va_type == VBLK)
1383		rdev = vap->va_rdev;
1384	else if (vap->va_type == VFIFO || vap->va_type == VSOCK)
1385		rdev = 0xffffffff;
1386	else
1387		return (EOPNOTSUPP);
1388	if ((error = VOP_GETATTR(dvp, &vattr, cnp->cn_cred)))
1389		return (error);
1390	error = nfsrpc_mknod(dvp, cnp->cn_nameptr, cnp->cn_namelen, vap,
1391	    rdev, vap->va_type, cnp->cn_cred, cnp->cn_thread, &dnfsva,
1392	    &nfsva, &nfhp, &attrflag, &dattrflag, NULL);
1393	if (!error) {
1394		if (!nfhp)
1395			(void) nfsrpc_lookup(dvp, cnp->cn_nameptr,
1396			    cnp->cn_namelen, cnp->cn_cred, cnp->cn_thread,
1397			    &dnfsva, &nfsva, &nfhp, &attrflag, &dattrflag,
1398			    NULL);
1399		if (nfhp)
1400			error = nfscl_nget(dvp->v_mount, dvp, nfhp, cnp,
1401			    cnp->cn_thread, &np, NULL, LK_EXCLUSIVE);
1402	}
1403	if (dattrflag)
1404		(void) nfscl_loadattrcache(&dvp, &dnfsva, NULL, NULL, 0, 1);
1405	if (!error) {
1406		newvp = NFSTOV(np);
1407		if (attrflag != 0) {
1408			error = nfscl_loadattrcache(&newvp, &nfsva, NULL, NULL,
1409			    0, 1);
1410			if (error != 0)
1411				vput(newvp);
1412		}
1413	}
1414	if (!error) {
1415		if ((cnp->cn_flags & MAKEENTRY))
1416			cache_enter(dvp, newvp, cnp);
1417		*vpp = newvp;
1418	} else if (NFS_ISV4(dvp)) {
1419		error = nfscl_maperr(cnp->cn_thread, error, vap->va_uid,
1420		    vap->va_gid);
1421	}
1422	dnp = VTONFS(dvp);
1423	mtx_lock(&dnp->n_mtx);
1424	dnp->n_flag |= NMODIFIED;
1425	if (!dattrflag)
1426		dnp->n_attrstamp = 0;
1427	mtx_unlock(&dnp->n_mtx);
1428	return (error);
1429}
1430
1431/*
1432 * nfs mknod vop
1433 * just call nfs_mknodrpc() to do the work.
1434 */
1435/* ARGSUSED */
1436static int
1437nfs_mknod(struct vop_mknod_args *ap)
1438{
1439	return (nfs_mknodrpc(ap->a_dvp, ap->a_vpp, ap->a_cnp, ap->a_vap));
1440}
1441
1442static struct mtx nfs_cverf_mtx;
1443MTX_SYSINIT(nfs_cverf_mtx, &nfs_cverf_mtx, "NFS create verifier mutex",
1444    MTX_DEF);
1445
1446static nfsquad_t
1447nfs_get_cverf(void)
1448{
1449	static nfsquad_t cverf;
1450	nfsquad_t ret;
1451	static int cverf_initialized = 0;
1452
1453	mtx_lock(&nfs_cverf_mtx);
1454	if (cverf_initialized == 0) {
1455		cverf.lval[0] = arc4random();
1456		cverf.lval[1] = arc4random();
1457		cverf_initialized = 1;
1458	} else
1459		cverf.qval++;
1460	ret = cverf;
1461	mtx_unlock(&nfs_cverf_mtx);
1462
1463	return (ret);
1464}
1465
1466/*
1467 * nfs file create call
1468 */
1469static int
1470nfs_create(struct vop_create_args *ap)
1471{
1472	struct vnode *dvp = ap->a_dvp;
1473	struct vattr *vap = ap->a_vap;
1474	struct componentname *cnp = ap->a_cnp;
1475	struct nfsnode *np = NULL, *dnp;
1476	struct vnode *newvp = NULL;
1477	struct nfsmount *nmp;
1478	struct nfsvattr dnfsva, nfsva;
1479	struct nfsfh *nfhp;
1480	nfsquad_t cverf;
1481	int error = 0, attrflag, dattrflag, fmode = 0;
1482	struct vattr vattr;
1483
1484	/*
1485	 * Oops, not for me..
1486	 */
1487	if (vap->va_type == VSOCK)
1488		return (nfs_mknodrpc(dvp, ap->a_vpp, cnp, vap));
1489
1490	if ((error = VOP_GETATTR(dvp, &vattr, cnp->cn_cred)))
1491		return (error);
1492	if (vap->va_vaflags & VA_EXCLUSIVE)
1493		fmode |= O_EXCL;
1494	dnp = VTONFS(dvp);
1495	nmp = VFSTONFS(vnode_mount(dvp));
1496again:
1497	/* For NFSv4, wait until any remove is done. */
1498	mtx_lock(&dnp->n_mtx);
1499	while (NFSHASNFSV4(nmp) && (dnp->n_flag & NREMOVEINPROG)) {
1500		dnp->n_flag |= NREMOVEWANT;
1501		(void) msleep((caddr_t)dnp, &dnp->n_mtx, PZERO, "nfscrt", 0);
1502	}
1503	mtx_unlock(&dnp->n_mtx);
1504
1505	cverf = nfs_get_cverf();
1506	error = nfsrpc_create(dvp, cnp->cn_nameptr, cnp->cn_namelen,
1507	    vap, cverf, fmode, cnp->cn_cred, cnp->cn_thread, &dnfsva, &nfsva,
1508	    &nfhp, &attrflag, &dattrflag, NULL);
1509	if (!error) {
1510		if (nfhp == NULL)
1511			(void) nfsrpc_lookup(dvp, cnp->cn_nameptr,
1512			    cnp->cn_namelen, cnp->cn_cred, cnp->cn_thread,
1513			    &dnfsva, &nfsva, &nfhp, &attrflag, &dattrflag,
1514			    NULL);
1515		if (nfhp != NULL)
1516			error = nfscl_nget(dvp->v_mount, dvp, nfhp, cnp,
1517			    cnp->cn_thread, &np, NULL, LK_EXCLUSIVE);
1518	}
1519	if (dattrflag)
1520		(void) nfscl_loadattrcache(&dvp, &dnfsva, NULL, NULL, 0, 1);
1521	if (!error) {
1522		newvp = NFSTOV(np);
1523		if (attrflag)
1524			error = nfscl_loadattrcache(&newvp, &nfsva, NULL, NULL,
1525			    0, 1);
1526	}
1527	if (error) {
1528		if (newvp != NULL) {
1529			vput(newvp);
1530			newvp = NULL;
1531		}
1532		if (NFS_ISV34(dvp) && (fmode & O_EXCL) &&
1533		    error == NFSERR_NOTSUPP) {
1534			fmode &= ~O_EXCL;
1535			goto again;
1536		}
1537	} else if (NFS_ISV34(dvp) && (fmode & O_EXCL)) {
1538		if (nfscl_checksattr(vap, &nfsva)) {
1539			/*
1540			 * We are normally called with only a partially
1541			 * initialized VAP. Since the NFSv3 spec says that
1542			 * the server may use the file attributes to
1543			 * store the verifier, the spec requires us to do a
1544			 * SETATTR RPC. FreeBSD servers store the verifier in
1545			 * atime, but we can't really assume that all servers
1546			 * will so we ensure that our SETATTR sets both atime
1547			 * and mtime.
1548			 */
1549			if (vap->va_mtime.tv_sec == VNOVAL)
1550				vfs_timestamp(&vap->va_mtime);
1551			if (vap->va_atime.tv_sec == VNOVAL)
1552				vap->va_atime = vap->va_mtime;
1553			error = nfsrpc_setattr(newvp, vap, NULL, cnp->cn_cred,
1554			    cnp->cn_thread, &nfsva, &attrflag, NULL);
1555			if (error && (vap->va_uid != (uid_t)VNOVAL ||
1556			    vap->va_gid != (gid_t)VNOVAL)) {
1557				/* try again without setting uid/gid */
1558				vap->va_uid = (uid_t)VNOVAL;
1559				vap->va_gid = (uid_t)VNOVAL;
1560				error = nfsrpc_setattr(newvp, vap, NULL,
1561				    cnp->cn_cred, cnp->cn_thread, &nfsva,
1562				    &attrflag, NULL);
1563			}
1564			if (attrflag)
1565				(void) nfscl_loadattrcache(&newvp, &nfsva, NULL,
1566				    NULL, 0, 1);
1567		}
1568	}
1569	if (!error) {
1570		if (cnp->cn_flags & MAKEENTRY)
1571			cache_enter(dvp, newvp, cnp);
1572		*ap->a_vpp = newvp;
1573	} else if (NFS_ISV4(dvp)) {
1574		error = nfscl_maperr(cnp->cn_thread, error, vap->va_uid,
1575		    vap->va_gid);
1576	}
1577	mtx_lock(&dnp->n_mtx);
1578	dnp->n_flag |= NMODIFIED;
1579	if (!dattrflag)
1580		dnp->n_attrstamp = 0;
1581	mtx_unlock(&dnp->n_mtx);
1582	return (error);
1583}
1584
1585/*
1586 * nfs file remove call
1587 * To try and make nfs semantics closer to ufs semantics, a file that has
1588 * other processes using the vnode is renamed instead of removed and then
1589 * removed later on the last close.
1590 * - If v_usecount > 1
1591 *	  If a rename is not already in the works
1592 *	     call nfs_sillyrename() to set it up
1593 *     else
1594 *	  do the remove rpc
1595 */
1596static int
1597nfs_remove(struct vop_remove_args *ap)
1598{
1599	struct vnode *vp = ap->a_vp;
1600	struct vnode *dvp = ap->a_dvp;
1601	struct componentname *cnp = ap->a_cnp;
1602	struct nfsnode *np = VTONFS(vp);
1603	int error = 0;
1604	struct vattr vattr;
1605
1606	KASSERT((cnp->cn_flags & HASBUF) != 0, ("nfs_remove: no name"));
1607	KASSERT(vrefcnt(vp) > 0, ("nfs_remove: bad v_usecount"));
1608	if (vp->v_type == VDIR)
1609		error = EPERM;
1610	else if (vrefcnt(vp) == 1 || (np->n_sillyrename &&
1611	    VOP_GETATTR(vp, &vattr, cnp->cn_cred) == 0 &&
1612	    vattr.va_nlink > 1)) {
1613		/*
1614		 * Purge the name cache so that the chance of a lookup for
1615		 * the name succeeding while the remove is in progress is
1616		 * minimized. Without node locking it can still happen, such
1617		 * that an I/O op returns ESTALE, but since you get this if
1618		 * another host removes the file..
1619		 */
1620		cache_purge(vp);
1621		/*
1622		 * throw away biocache buffers, mainly to avoid
1623		 * unnecessary delayed writes later.
1624		 */
1625		error = ncl_vinvalbuf(vp, 0, cnp->cn_thread, 1);
1626		/* Do the rpc */
1627		if (error != EINTR && error != EIO)
1628			error = nfs_removerpc(dvp, vp, cnp->cn_nameptr,
1629			    cnp->cn_namelen, cnp->cn_cred, cnp->cn_thread);
1630		/*
1631		 * Kludge City: If the first reply to the remove rpc is lost..
1632		 *   the reply to the retransmitted request will be ENOENT
1633		 *   since the file was in fact removed
1634		 *   Therefore, we cheat and return success.
1635		 */
1636		if (error == ENOENT)
1637			error = 0;
1638	} else if (!np->n_sillyrename)
1639		error = nfs_sillyrename(dvp, vp, cnp);
1640	mtx_lock(&np->n_mtx);
1641	np->n_attrstamp = 0;
1642	mtx_unlock(&np->n_mtx);
1643	return (error);
1644}
1645
1646/*
1647 * nfs file remove rpc called from nfs_inactive
1648 */
1649int
1650ncl_removeit(struct sillyrename *sp, struct vnode *vp)
1651{
1652	/*
1653	 * Make sure that the directory vnode is still valid.
1654	 * XXX we should lock sp->s_dvp here.
1655	 */
1656	if (sp->s_dvp->v_type == VBAD)
1657		return (0);
1658	return (nfs_removerpc(sp->s_dvp, vp, sp->s_name, sp->s_namlen,
1659	    sp->s_cred, NULL));
1660}
1661
1662/*
1663 * Nfs remove rpc, called from nfs_remove() and ncl_removeit().
1664 */
1665static int
1666nfs_removerpc(struct vnode *dvp, struct vnode *vp, char *name,
1667    int namelen, struct ucred *cred, struct thread *td)
1668{
1669	struct nfsvattr dnfsva;
1670	struct nfsnode *dnp = VTONFS(dvp);
1671	int error = 0, dattrflag;
1672
1673	mtx_lock(&dnp->n_mtx);
1674	dnp->n_flag |= NREMOVEINPROG;
1675	mtx_unlock(&dnp->n_mtx);
1676	error = nfsrpc_remove(dvp, name, namelen, vp, cred, td, &dnfsva,
1677	    &dattrflag, NULL);
1678	mtx_lock(&dnp->n_mtx);
1679	if ((dnp->n_flag & NREMOVEWANT)) {
1680		dnp->n_flag &= ~(NREMOVEWANT | NREMOVEINPROG);
1681		mtx_unlock(&dnp->n_mtx);
1682		wakeup((caddr_t)dnp);
1683	} else {
1684		dnp->n_flag &= ~NREMOVEINPROG;
1685		mtx_unlock(&dnp->n_mtx);
1686	}
1687	if (dattrflag)
1688		(void) nfscl_loadattrcache(&dvp, &dnfsva, NULL, NULL, 0, 1);
1689	mtx_lock(&dnp->n_mtx);
1690	dnp->n_flag |= NMODIFIED;
1691	if (!dattrflag)
1692		dnp->n_attrstamp = 0;
1693	mtx_unlock(&dnp->n_mtx);
1694	if (error && NFS_ISV4(dvp))
1695		error = nfscl_maperr(td, error, (uid_t)0, (gid_t)0);
1696	return (error);
1697}
1698
1699/*
1700 * nfs file rename call
1701 */
1702static int
1703nfs_rename(struct vop_rename_args *ap)
1704{
1705	struct vnode *fvp = ap->a_fvp;
1706	struct vnode *tvp = ap->a_tvp;
1707	struct vnode *fdvp = ap->a_fdvp;
1708	struct vnode *tdvp = ap->a_tdvp;
1709	struct componentname *tcnp = ap->a_tcnp;
1710	struct componentname *fcnp = ap->a_fcnp;
1711	struct nfsnode *fnp = VTONFS(ap->a_fvp);
1712	struct nfsnode *tdnp = VTONFS(ap->a_tdvp);
1713	struct nfsv4node *newv4 = NULL;
1714	int error;
1715
1716	KASSERT((tcnp->cn_flags & HASBUF) != 0 &&
1717	    (fcnp->cn_flags & HASBUF) != 0, ("nfs_rename: no name"));
1718	/* Check for cross-device rename */
1719	if ((fvp->v_mount != tdvp->v_mount) ||
1720	    (tvp && (fvp->v_mount != tvp->v_mount))) {
1721		error = EXDEV;
1722		goto out;
1723	}
1724
1725	if (fvp == tvp) {
1726		ncl_printf("nfs_rename: fvp == tvp (can't happen)\n");
1727		error = 0;
1728		goto out;
1729	}
1730	if ((error = vn_lock(fvp, LK_EXCLUSIVE)) != 0)
1731		goto out;
1732
1733	/*
1734	 * We have to flush B_DELWRI data prior to renaming
1735	 * the file.  If we don't, the delayed-write buffers
1736	 * can be flushed out later after the file has gone stale
1737	 * under NFSV3.  NFSV2 does not have this problem because
1738	 * ( as far as I can tell ) it flushes dirty buffers more
1739	 * often.
1740	 *
1741	 * Skip the rename operation if the fsync fails, this can happen
1742	 * due to the server's volume being full, when we pushed out data
1743	 * that was written back to our cache earlier. Not checking for
1744	 * this condition can result in potential (silent) data loss.
1745	 */
1746	error = VOP_FSYNC(fvp, MNT_WAIT, fcnp->cn_thread);
1747	VOP_UNLOCK(fvp, 0);
1748	if (!error && tvp)
1749		error = VOP_FSYNC(tvp, MNT_WAIT, tcnp->cn_thread);
1750	if (error)
1751		goto out;
1752
1753	/*
1754	 * If the tvp exists and is in use, sillyrename it before doing the
1755	 * rename of the new file over it.
1756	 * XXX Can't sillyrename a directory.
1757	 */
1758	if (tvp && vrefcnt(tvp) > 1 && !VTONFS(tvp)->n_sillyrename &&
1759		tvp->v_type != VDIR && !nfs_sillyrename(tdvp, tvp, tcnp)) {
1760		vput(tvp);
1761		tvp = NULL;
1762	}
1763
1764	error = nfs_renamerpc(fdvp, fvp, fcnp->cn_nameptr, fcnp->cn_namelen,
1765	    tdvp, tvp, tcnp->cn_nameptr, tcnp->cn_namelen, tcnp->cn_cred,
1766	    tcnp->cn_thread);
1767
1768	if (error == 0 && NFS_ISV4(tdvp)) {
1769		/*
1770		 * For NFSv4, check to see if it is the same name and
1771		 * replace the name, if it is different.
1772		 */
1773		MALLOC(newv4, struct nfsv4node *,
1774		    sizeof (struct nfsv4node) +
1775		    tdnp->n_fhp->nfh_len + tcnp->cn_namelen - 1,
1776		    M_NFSV4NODE, M_WAITOK);
1777		mtx_lock(&tdnp->n_mtx);
1778		mtx_lock(&fnp->n_mtx);
1779		if (fnp->n_v4 != NULL && fvp->v_type == VREG &&
1780		    (fnp->n_v4->n4_namelen != tcnp->cn_namelen ||
1781		      NFSBCMP(tcnp->cn_nameptr, NFS4NODENAME(fnp->n_v4),
1782		      tcnp->cn_namelen) ||
1783		      tdnp->n_fhp->nfh_len != fnp->n_v4->n4_fhlen ||
1784		      NFSBCMP(tdnp->n_fhp->nfh_fh, fnp->n_v4->n4_data,
1785			tdnp->n_fhp->nfh_len))) {
1786#ifdef notdef
1787{ char nnn[100]; int nnnl;
1788nnnl = (tcnp->cn_namelen < 100) ? tcnp->cn_namelen : 99;
1789bcopy(tcnp->cn_nameptr, nnn, nnnl);
1790nnn[nnnl] = '\0';
1791printf("ren replace=%s\n",nnn);
1792}
1793#endif
1794			FREE((caddr_t)fnp->n_v4, M_NFSV4NODE);
1795			fnp->n_v4 = newv4;
1796			newv4 = NULL;
1797			fnp->n_v4->n4_fhlen = tdnp->n_fhp->nfh_len;
1798			fnp->n_v4->n4_namelen = tcnp->cn_namelen;
1799			NFSBCOPY(tdnp->n_fhp->nfh_fh, fnp->n_v4->n4_data,
1800			    tdnp->n_fhp->nfh_len);
1801			NFSBCOPY(tcnp->cn_nameptr,
1802			    NFS4NODENAME(fnp->n_v4), tcnp->cn_namelen);
1803		}
1804		mtx_unlock(&tdnp->n_mtx);
1805		mtx_unlock(&fnp->n_mtx);
1806		if (newv4 != NULL)
1807			FREE((caddr_t)newv4, M_NFSV4NODE);
1808	}
1809
1810	if (fvp->v_type == VDIR) {
1811		if (tvp != NULL && tvp->v_type == VDIR)
1812			cache_purge(tdvp);
1813		cache_purge(fdvp);
1814	}
1815
1816out:
1817	if (tdvp == tvp)
1818		vrele(tdvp);
1819	else
1820		vput(tdvp);
1821	if (tvp)
1822		vput(tvp);
1823	vrele(fdvp);
1824	vrele(fvp);
1825	/*
1826	 * Kludge: Map ENOENT => 0 assuming that it is a reply to a retry.
1827	 */
1828	if (error == ENOENT)
1829		error = 0;
1830	return (error);
1831}
1832
1833/*
1834 * nfs file rename rpc called from nfs_remove() above
1835 */
1836static int
1837nfs_renameit(struct vnode *sdvp, struct vnode *svp, struct componentname *scnp,
1838    struct sillyrename *sp)
1839{
1840
1841	return (nfs_renamerpc(sdvp, svp, scnp->cn_nameptr, scnp->cn_namelen,
1842	    sdvp, NULL, sp->s_name, sp->s_namlen, scnp->cn_cred,
1843	    scnp->cn_thread));
1844}
1845
1846/*
1847 * Do an nfs rename rpc. Called from nfs_rename() and nfs_renameit().
1848 */
1849static int
1850nfs_renamerpc(struct vnode *fdvp, struct vnode *fvp, char *fnameptr,
1851    int fnamelen, struct vnode *tdvp, struct vnode *tvp, char *tnameptr,
1852    int tnamelen, struct ucred *cred, struct thread *td)
1853{
1854	struct nfsvattr fnfsva, tnfsva;
1855	struct nfsnode *fdnp = VTONFS(fdvp);
1856	struct nfsnode *tdnp = VTONFS(tdvp);
1857	int error = 0, fattrflag, tattrflag;
1858
1859	error = nfsrpc_rename(fdvp, fvp, fnameptr, fnamelen, tdvp, tvp,
1860	    tnameptr, tnamelen, cred, td, &fnfsva, &tnfsva, &fattrflag,
1861	    &tattrflag, NULL, NULL);
1862	mtx_lock(&fdnp->n_mtx);
1863	fdnp->n_flag |= NMODIFIED;
1864	if (fattrflag != 0) {
1865		mtx_unlock(&fdnp->n_mtx);
1866		(void) nfscl_loadattrcache(&fdvp, &fnfsva, NULL, NULL, 0, 1);
1867	} else {
1868		fdnp->n_attrstamp = 0;
1869		mtx_unlock(&fdnp->n_mtx);
1870	}
1871	mtx_lock(&tdnp->n_mtx);
1872	tdnp->n_flag |= NMODIFIED;
1873	if (tattrflag != 0) {
1874		mtx_unlock(&tdnp->n_mtx);
1875		(void) nfscl_loadattrcache(&tdvp, &tnfsva, NULL, NULL, 0, 1);
1876	} else {
1877		tdnp->n_attrstamp = 0;
1878		mtx_unlock(&tdnp->n_mtx);
1879	}
1880	if (error && NFS_ISV4(fdvp))
1881		error = nfscl_maperr(td, error, (uid_t)0, (gid_t)0);
1882	return (error);
1883}
1884
1885/*
1886 * nfs hard link create call
1887 */
1888static int
1889nfs_link(struct vop_link_args *ap)
1890{
1891	struct vnode *vp = ap->a_vp;
1892	struct vnode *tdvp = ap->a_tdvp;
1893	struct componentname *cnp = ap->a_cnp;
1894	struct nfsnode *np, *tdnp;
1895	struct nfsvattr nfsva, dnfsva;
1896	int error = 0, attrflag, dattrflag;
1897
1898	if (vp->v_mount != tdvp->v_mount) {
1899		return (EXDEV);
1900	}
1901
1902	/*
1903	 * Push all writes to the server, so that the attribute cache
1904	 * doesn't get "out of sync" with the server.
1905	 * XXX There should be a better way!
1906	 */
1907	VOP_FSYNC(vp, MNT_WAIT, cnp->cn_thread);
1908
1909	error = nfsrpc_link(tdvp, vp, cnp->cn_nameptr, cnp->cn_namelen,
1910	    cnp->cn_cred, cnp->cn_thread, &dnfsva, &nfsva, &attrflag,
1911	    &dattrflag, NULL);
1912	tdnp = VTONFS(tdvp);
1913	mtx_lock(&tdnp->n_mtx);
1914	tdnp->n_flag |= NMODIFIED;
1915	if (dattrflag != 0) {
1916		mtx_unlock(&tdnp->n_mtx);
1917		(void) nfscl_loadattrcache(&tdvp, &dnfsva, NULL, NULL, 0, 1);
1918	} else {
1919		tdnp->n_attrstamp = 0;
1920		mtx_unlock(&tdnp->n_mtx);
1921	}
1922	if (attrflag)
1923		(void) nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 0, 1);
1924	else {
1925		np = VTONFS(vp);
1926		mtx_lock(&np->n_mtx);
1927		np->n_attrstamp = 0;
1928		mtx_unlock(&np->n_mtx);
1929	}
1930	/*
1931	 * If negative lookup caching is enabled, I might as well
1932	 * add an entry for this node. Not necessary for correctness,
1933	 * but if negative caching is enabled, then the system
1934	 * must care about lookup caching hit rate, so...
1935	 */
1936	if (VFSTONFS(vp->v_mount)->nm_negnametimeo != 0 &&
1937	    (cnp->cn_flags & MAKEENTRY))
1938		cache_enter(tdvp, vp, cnp);
1939	if (error && NFS_ISV4(vp))
1940		error = nfscl_maperr(cnp->cn_thread, error, (uid_t)0,
1941		    (gid_t)0);
1942	return (error);
1943}
1944
1945/*
1946 * nfs symbolic link create call
1947 */
1948static int
1949nfs_symlink(struct vop_symlink_args *ap)
1950{
1951	struct vnode *dvp = ap->a_dvp;
1952	struct vattr *vap = ap->a_vap;
1953	struct componentname *cnp = ap->a_cnp;
1954	struct nfsvattr nfsva, dnfsva;
1955	struct nfsfh *nfhp;
1956	struct nfsnode *np = NULL, *dnp;
1957	struct vnode *newvp = NULL;
1958	int error = 0, attrflag, dattrflag, ret;
1959
1960	vap->va_type = VLNK;
1961	error = nfsrpc_symlink(dvp, cnp->cn_nameptr, cnp->cn_namelen,
1962	    ap->a_target, vap, cnp->cn_cred, cnp->cn_thread, &dnfsva,
1963	    &nfsva, &nfhp, &attrflag, &dattrflag, NULL);
1964	if (nfhp) {
1965		ret = nfscl_nget(dvp->v_mount, dvp, nfhp, cnp, cnp->cn_thread,
1966		    &np, NULL, LK_EXCLUSIVE);
1967		if (!ret)
1968			newvp = NFSTOV(np);
1969		else if (!error)
1970			error = ret;
1971	}
1972	if (newvp != NULL) {
1973		if (attrflag)
1974			(void) nfscl_loadattrcache(&newvp, &nfsva, NULL, NULL,
1975			    0, 1);
1976	} else if (!error) {
1977		/*
1978		 * If we do not have an error and we could not extract the
1979		 * newvp from the response due to the request being NFSv2, we
1980		 * have to do a lookup in order to obtain a newvp to return.
1981		 */
1982		error = nfs_lookitup(dvp, cnp->cn_nameptr, cnp->cn_namelen,
1983		    cnp->cn_cred, cnp->cn_thread, &np);
1984		if (!error)
1985			newvp = NFSTOV(np);
1986	}
1987	if (error) {
1988		if (newvp)
1989			vput(newvp);
1990		if (NFS_ISV4(dvp))
1991			error = nfscl_maperr(cnp->cn_thread, error,
1992			    vap->va_uid, vap->va_gid);
1993	} else {
1994		/*
1995		 * If negative lookup caching is enabled, I might as well
1996		 * add an entry for this node. Not necessary for correctness,
1997		 * but if negative caching is enabled, then the system
1998		 * must care about lookup caching hit rate, so...
1999		 */
2000		if (VFSTONFS(dvp->v_mount)->nm_negnametimeo != 0 &&
2001		    (cnp->cn_flags & MAKEENTRY))
2002			cache_enter(dvp, newvp, cnp);
2003		*ap->a_vpp = newvp;
2004	}
2005
2006	dnp = VTONFS(dvp);
2007	mtx_lock(&dnp->n_mtx);
2008	dnp->n_flag |= NMODIFIED;
2009	if (dattrflag != 0) {
2010		mtx_unlock(&dnp->n_mtx);
2011		(void) nfscl_loadattrcache(&dvp, &dnfsva, NULL, NULL, 0, 1);
2012	} else {
2013		dnp->n_attrstamp = 0;
2014		mtx_unlock(&dnp->n_mtx);
2015	}
2016	return (error);
2017}
2018
2019/*
2020 * nfs make dir call
2021 */
2022static int
2023nfs_mkdir(struct vop_mkdir_args *ap)
2024{
2025	struct vnode *dvp = ap->a_dvp;
2026	struct vattr *vap = ap->a_vap;
2027	struct componentname *cnp = ap->a_cnp;
2028	struct nfsnode *np = NULL, *dnp;
2029	struct vnode *newvp = NULL;
2030	struct vattr vattr;
2031	struct nfsfh *nfhp;
2032	struct nfsvattr nfsva, dnfsva;
2033	int error = 0, attrflag, dattrflag, ret;
2034
2035	if ((error = VOP_GETATTR(dvp, &vattr, cnp->cn_cred)) != 0)
2036		return (error);
2037	vap->va_type = VDIR;
2038	error = nfsrpc_mkdir(dvp, cnp->cn_nameptr, cnp->cn_namelen,
2039	    vap, cnp->cn_cred, cnp->cn_thread, &dnfsva, &nfsva, &nfhp,
2040	    &attrflag, &dattrflag, NULL);
2041	dnp = VTONFS(dvp);
2042	mtx_lock(&dnp->n_mtx);
2043	dnp->n_flag |= NMODIFIED;
2044	if (dattrflag != 0) {
2045		mtx_unlock(&dnp->n_mtx);
2046		(void) nfscl_loadattrcache(&dvp, &dnfsva, NULL, NULL, 0, 1);
2047	} else {
2048		dnp->n_attrstamp = 0;
2049		mtx_unlock(&dnp->n_mtx);
2050	}
2051	if (nfhp) {
2052		ret = nfscl_nget(dvp->v_mount, dvp, nfhp, cnp, cnp->cn_thread,
2053		    &np, NULL, LK_EXCLUSIVE);
2054		if (!ret) {
2055			newvp = NFSTOV(np);
2056			if (attrflag)
2057			   (void) nfscl_loadattrcache(&newvp, &nfsva, NULL,
2058				NULL, 0, 1);
2059		} else if (!error)
2060			error = ret;
2061	}
2062	if (!error && newvp == NULL) {
2063		error = nfs_lookitup(dvp, cnp->cn_nameptr, cnp->cn_namelen,
2064		    cnp->cn_cred, cnp->cn_thread, &np);
2065		if (!error) {
2066			newvp = NFSTOV(np);
2067			if (newvp->v_type != VDIR)
2068				error = EEXIST;
2069		}
2070	}
2071	if (error) {
2072		if (newvp)
2073			vput(newvp);
2074		if (NFS_ISV4(dvp))
2075			error = nfscl_maperr(cnp->cn_thread, error,
2076			    vap->va_uid, vap->va_gid);
2077	} else {
2078		/*
2079		 * If negative lookup caching is enabled, I might as well
2080		 * add an entry for this node. Not necessary for correctness,
2081		 * but if negative caching is enabled, then the system
2082		 * must care about lookup caching hit rate, so...
2083		 */
2084		if (VFSTONFS(dvp->v_mount)->nm_negnametimeo != 0 &&
2085		    (cnp->cn_flags & MAKEENTRY))
2086			cache_enter(dvp, newvp, cnp);
2087		*ap->a_vpp = newvp;
2088	}
2089	return (error);
2090}
2091
2092/*
2093 * nfs remove directory call
2094 */
2095static int
2096nfs_rmdir(struct vop_rmdir_args *ap)
2097{
2098	struct vnode *vp = ap->a_vp;
2099	struct vnode *dvp = ap->a_dvp;
2100	struct componentname *cnp = ap->a_cnp;
2101	struct nfsnode *dnp;
2102	struct nfsvattr dnfsva;
2103	int error, dattrflag;
2104
2105	if (dvp == vp)
2106		return (EINVAL);
2107	error = nfsrpc_rmdir(dvp, cnp->cn_nameptr, cnp->cn_namelen,
2108	    cnp->cn_cred, cnp->cn_thread, &dnfsva, &dattrflag, NULL);
2109	dnp = VTONFS(dvp);
2110	mtx_lock(&dnp->n_mtx);
2111	dnp->n_flag |= NMODIFIED;
2112	if (dattrflag != 0) {
2113		mtx_unlock(&dnp->n_mtx);
2114		(void) nfscl_loadattrcache(&dvp, &dnfsva, NULL, NULL, 0, 1);
2115	} else {
2116		dnp->n_attrstamp = 0;
2117		mtx_unlock(&dnp->n_mtx);
2118	}
2119
2120	cache_purge(dvp);
2121	cache_purge(vp);
2122	if (error && NFS_ISV4(dvp))
2123		error = nfscl_maperr(cnp->cn_thread, error, (uid_t)0,
2124		    (gid_t)0);
2125	/*
2126	 * Kludge: Map ENOENT => 0 assuming that you have a reply to a retry.
2127	 */
2128	if (error == ENOENT)
2129		error = 0;
2130	return (error);
2131}
2132
2133/*
2134 * nfs readdir call
2135 */
2136static int
2137nfs_readdir(struct vop_readdir_args *ap)
2138{
2139	struct vnode *vp = ap->a_vp;
2140	struct nfsnode *np = VTONFS(vp);
2141	struct uio *uio = ap->a_uio;
2142	int tresid, error = 0;
2143	struct vattr vattr;
2144
2145	if (vp->v_type != VDIR)
2146		return(EPERM);
2147
2148	/*
2149	 * First, check for hit on the EOF offset cache
2150	 */
2151	if (np->n_direofoffset > 0 && uio->uio_offset >= np->n_direofoffset &&
2152	    (np->n_flag & NMODIFIED) == 0) {
2153		if (VOP_GETATTR(vp, &vattr, ap->a_cred) == 0) {
2154			mtx_lock(&np->n_mtx);
2155			if ((NFS_ISV4(vp) && np->n_change == vattr.va_filerev) ||
2156			    !NFS_TIMESPEC_COMPARE(&np->n_mtime, &vattr.va_mtime)) {
2157				mtx_unlock(&np->n_mtx);
2158				NFSINCRGLOBAL(newnfsstats.direofcache_hits);
2159				return (0);
2160			} else
2161				mtx_unlock(&np->n_mtx);
2162		}
2163	}
2164
2165	/*
2166	 * Call ncl_bioread() to do the real work.
2167	 */
2168	tresid = uio->uio_resid;
2169	error = ncl_bioread(vp, uio, 0, ap->a_cred);
2170
2171	if (!error && uio->uio_resid == tresid)
2172		NFSINCRGLOBAL(newnfsstats.direofcache_misses);
2173	return (error);
2174}
2175
2176/*
2177 * Readdir rpc call.
2178 * Called from below the buffer cache by ncl_doio().
2179 */
2180int
2181ncl_readdirrpc(struct vnode *vp, struct uio *uiop, struct ucred *cred,
2182    struct thread *td)
2183{
2184	struct nfsvattr nfsva;
2185	nfsuint64 *cookiep, cookie;
2186	struct nfsnode *dnp = VTONFS(vp);
2187	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
2188	int error = 0, eof, attrflag;
2189
2190	KASSERT(uiop->uio_iovcnt == 1 &&
2191	    (uiop->uio_offset & (DIRBLKSIZ - 1)) == 0 &&
2192	    (uiop->uio_resid & (DIRBLKSIZ - 1)) == 0,
2193	    ("nfs readdirrpc bad uio"));
2194
2195	/*
2196	 * If there is no cookie, assume directory was stale.
2197	 */
2198	ncl_dircookie_lock(dnp);
2199	cookiep = ncl_getcookie(dnp, uiop->uio_offset, 0);
2200	if (cookiep) {
2201		cookie = *cookiep;
2202		ncl_dircookie_unlock(dnp);
2203	} else {
2204		ncl_dircookie_unlock(dnp);
2205		return (NFSERR_BAD_COOKIE);
2206	}
2207
2208	if (NFSHASNFSV3(nmp) && !NFSHASGOTFSINFO(nmp))
2209		(void)ncl_fsinfo(nmp, vp, cred, td);
2210
2211	error = nfsrpc_readdir(vp, uiop, &cookie, cred, td, &nfsva,
2212	    &attrflag, &eof, NULL);
2213	if (attrflag)
2214		(void) nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 0, 1);
2215
2216	if (!error) {
2217		/*
2218		 * We are now either at the end of the directory or have filled
2219		 * the block.
2220		 */
2221		if (eof)
2222			dnp->n_direofoffset = uiop->uio_offset;
2223		else {
2224			if (uiop->uio_resid > 0)
2225				ncl_printf("EEK! readdirrpc resid > 0\n");
2226			ncl_dircookie_lock(dnp);
2227			cookiep = ncl_getcookie(dnp, uiop->uio_offset, 1);
2228			*cookiep = cookie;
2229			ncl_dircookie_unlock(dnp);
2230		}
2231	} else if (NFS_ISV4(vp)) {
2232		error = nfscl_maperr(td, error, (uid_t)0, (gid_t)0);
2233	}
2234	return (error);
2235}
2236
2237/*
2238 * NFS V3 readdir plus RPC. Used in place of ncl_readdirrpc().
2239 */
2240int
2241ncl_readdirplusrpc(struct vnode *vp, struct uio *uiop, struct ucred *cred,
2242    struct thread *td)
2243{
2244	struct nfsvattr nfsva;
2245	nfsuint64 *cookiep, cookie;
2246	struct nfsnode *dnp = VTONFS(vp);
2247	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
2248	int error = 0, attrflag, eof;
2249
2250	KASSERT(uiop->uio_iovcnt == 1 &&
2251	    (uiop->uio_offset & (DIRBLKSIZ - 1)) == 0 &&
2252	    (uiop->uio_resid & (DIRBLKSIZ - 1)) == 0,
2253	    ("nfs readdirplusrpc bad uio"));
2254
2255	/*
2256	 * If there is no cookie, assume directory was stale.
2257	 */
2258	ncl_dircookie_lock(dnp);
2259	cookiep = ncl_getcookie(dnp, uiop->uio_offset, 0);
2260	if (cookiep) {
2261		cookie = *cookiep;
2262		ncl_dircookie_unlock(dnp);
2263	} else {
2264		ncl_dircookie_unlock(dnp);
2265		return (NFSERR_BAD_COOKIE);
2266	}
2267
2268	if (NFSHASNFSV3(nmp) && !NFSHASGOTFSINFO(nmp))
2269		(void)ncl_fsinfo(nmp, vp, cred, td);
2270	error = nfsrpc_readdirplus(vp, uiop, &cookie, cred, td, &nfsva,
2271	    &attrflag, &eof, NULL);
2272	if (attrflag)
2273		(void) nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 0, 1);
2274
2275	if (!error) {
2276		/*
2277		 * We are now either at end of the directory or have filled the
2278		 * the block.
2279		 */
2280		if (eof)
2281			dnp->n_direofoffset = uiop->uio_offset;
2282		else {
2283			if (uiop->uio_resid > 0)
2284				ncl_printf("EEK! readdirplusrpc resid > 0\n");
2285			ncl_dircookie_lock(dnp);
2286			cookiep = ncl_getcookie(dnp, uiop->uio_offset, 1);
2287			*cookiep = cookie;
2288			ncl_dircookie_unlock(dnp);
2289		}
2290	} else if (NFS_ISV4(vp)) {
2291		error = nfscl_maperr(td, error, (uid_t)0, (gid_t)0);
2292	}
2293	return (error);
2294}
2295
2296/*
2297 * Silly rename. To make the NFS filesystem that is stateless look a little
2298 * more like the "ufs" a remove of an active vnode is translated to a rename
2299 * to a funny looking filename that is removed by nfs_inactive on the
2300 * nfsnode. There is the potential for another process on a different client
2301 * to create the same funny name between the nfs_lookitup() fails and the
2302 * nfs_rename() completes, but...
2303 */
2304static int
2305nfs_sillyrename(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2306{
2307	struct sillyrename *sp;
2308	struct nfsnode *np;
2309	int error;
2310	short pid;
2311	unsigned int lticks;
2312
2313	cache_purge(dvp);
2314	np = VTONFS(vp);
2315	KASSERT(vp->v_type != VDIR, ("nfs: sillyrename dir"));
2316	MALLOC(sp, struct sillyrename *, sizeof (struct sillyrename),
2317	    M_NEWNFSREQ, M_WAITOK);
2318	sp->s_cred = crhold(cnp->cn_cred);
2319	sp->s_dvp = dvp;
2320	VREF(dvp);
2321
2322	/*
2323	 * Fudge together a funny name.
2324	 * Changing the format of the funny name to accomodate more
2325	 * sillynames per directory.
2326	 * The name is now changed to .nfs.<ticks>.<pid>.4, where ticks is
2327	 * CPU ticks since boot.
2328	 */
2329	pid = cnp->cn_thread->td_proc->p_pid;
2330	lticks = (unsigned int)ticks;
2331	for ( ; ; ) {
2332		sp->s_namlen = sprintf(sp->s_name,
2333				       ".nfs.%08x.%04x4.4", lticks,
2334				       pid);
2335		if (nfs_lookitup(dvp, sp->s_name, sp->s_namlen, sp->s_cred,
2336				 cnp->cn_thread, NULL))
2337			break;
2338		lticks++;
2339	}
2340	error = nfs_renameit(dvp, vp, cnp, sp);
2341	if (error)
2342		goto bad;
2343	error = nfs_lookitup(dvp, sp->s_name, sp->s_namlen, sp->s_cred,
2344		cnp->cn_thread, &np);
2345	np->n_sillyrename = sp;
2346	return (0);
2347bad:
2348	vrele(sp->s_dvp);
2349	crfree(sp->s_cred);
2350	free((caddr_t)sp, M_NEWNFSREQ);
2351	return (error);
2352}
2353
2354/*
2355 * Look up a file name and optionally either update the file handle or
2356 * allocate an nfsnode, depending on the value of npp.
2357 * npp == NULL	--> just do the lookup
2358 * *npp == NULL --> allocate a new nfsnode and make sure attributes are
2359 *			handled too
2360 * *npp != NULL --> update the file handle in the vnode
2361 */
2362static int
2363nfs_lookitup(struct vnode *dvp, char *name, int len, struct ucred *cred,
2364    struct thread *td, struct nfsnode **npp)
2365{
2366	struct vnode *newvp = NULL, *vp;
2367	struct nfsnode *np, *dnp = VTONFS(dvp);
2368	struct nfsfh *nfhp, *onfhp;
2369	struct nfsvattr nfsva, dnfsva;
2370	struct componentname cn;
2371	int error = 0, attrflag, dattrflag;
2372	u_int hash;
2373
2374	error = nfsrpc_lookup(dvp, name, len, cred, td, &dnfsva, &nfsva,
2375	    &nfhp, &attrflag, &dattrflag, NULL);
2376	if (dattrflag)
2377		(void) nfscl_loadattrcache(&dvp, &dnfsva, NULL, NULL, 0, 1);
2378	if (npp && !error) {
2379		if (*npp != NULL) {
2380		    np = *npp;
2381		    vp = NFSTOV(np);
2382		    /*
2383		     * For NFSv4, check to see if it is the same name and
2384		     * replace the name, if it is different.
2385		     */
2386		    if (np->n_v4 != NULL && nfsva.na_type == VREG &&
2387			(np->n_v4->n4_namelen != len ||
2388			 NFSBCMP(name, NFS4NODENAME(np->n_v4), len) ||
2389			 dnp->n_fhp->nfh_len != np->n_v4->n4_fhlen ||
2390			 NFSBCMP(dnp->n_fhp->nfh_fh, np->n_v4->n4_data,
2391			 dnp->n_fhp->nfh_len))) {
2392#ifdef notdef
2393{ char nnn[100]; int nnnl;
2394nnnl = (len < 100) ? len : 99;
2395bcopy(name, nnn, nnnl);
2396nnn[nnnl] = '\0';
2397printf("replace=%s\n",nnn);
2398}
2399#endif
2400			    FREE((caddr_t)np->n_v4, M_NFSV4NODE);
2401			    MALLOC(np->n_v4, struct nfsv4node *,
2402				sizeof (struct nfsv4node) +
2403				dnp->n_fhp->nfh_len + len - 1,
2404				M_NFSV4NODE, M_WAITOK);
2405			    np->n_v4->n4_fhlen = dnp->n_fhp->nfh_len;
2406			    np->n_v4->n4_namelen = len;
2407			    NFSBCOPY(dnp->n_fhp->nfh_fh, np->n_v4->n4_data,
2408				dnp->n_fhp->nfh_len);
2409			    NFSBCOPY(name, NFS4NODENAME(np->n_v4), len);
2410		    }
2411		    hash = fnv_32_buf(nfhp->nfh_fh, nfhp->nfh_len,
2412			FNV1_32_INIT);
2413		    onfhp = np->n_fhp;
2414		    /*
2415		     * Rehash node for new file handle.
2416		     */
2417		    vfs_hash_rehash(vp, hash);
2418		    np->n_fhp = nfhp;
2419		    if (onfhp != NULL)
2420			FREE((caddr_t)onfhp, M_NFSFH);
2421		    newvp = NFSTOV(np);
2422		} else if (NFS_CMPFH(dnp, nfhp->nfh_fh, nfhp->nfh_len)) {
2423		    FREE((caddr_t)nfhp, M_NFSFH);
2424		    VREF(dvp);
2425		    newvp = dvp;
2426		} else {
2427		    cn.cn_nameptr = name;
2428		    cn.cn_namelen = len;
2429		    error = nfscl_nget(dvp->v_mount, dvp, nfhp, &cn, td,
2430			&np, NULL, LK_EXCLUSIVE);
2431		    if (error)
2432			return (error);
2433		    newvp = NFSTOV(np);
2434		}
2435		if (!attrflag && *npp == NULL) {
2436			if (newvp == dvp)
2437				vrele(newvp);
2438			else
2439				vput(newvp);
2440			return (ENOENT);
2441		}
2442		if (attrflag)
2443			(void) nfscl_loadattrcache(&newvp, &nfsva, NULL, NULL,
2444			    0, 1);
2445	}
2446	if (npp && *npp == NULL) {
2447		if (error) {
2448			if (newvp) {
2449				if (newvp == dvp)
2450					vrele(newvp);
2451				else
2452					vput(newvp);
2453			}
2454		} else
2455			*npp = np;
2456	}
2457	if (error && NFS_ISV4(dvp))
2458		error = nfscl_maperr(td, error, (uid_t)0, (gid_t)0);
2459	return (error);
2460}
2461
2462/*
2463 * Nfs Version 3 and 4 commit rpc
2464 */
2465int
2466ncl_commit(struct vnode *vp, u_quad_t offset, int cnt, struct ucred *cred,
2467   struct thread *td)
2468{
2469	struct nfsvattr nfsva;
2470	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
2471	int error, attrflag;
2472	u_char verf[NFSX_VERF];
2473
2474	mtx_lock(&nmp->nm_mtx);
2475	if ((nmp->nm_state & NFSSTA_HASWRITEVERF) == 0) {
2476		mtx_unlock(&nmp->nm_mtx);
2477		return (0);
2478	}
2479	mtx_unlock(&nmp->nm_mtx);
2480	error = nfsrpc_commit(vp, offset, cnt, cred, td, verf, &nfsva,
2481	    &attrflag, NULL);
2482	if (!error) {
2483		if (NFSBCMP((caddr_t)nmp->nm_verf, verf, NFSX_VERF)) {
2484			NFSBCOPY(verf, (caddr_t)nmp->nm_verf, NFSX_VERF);
2485			error = NFSERR_STALEWRITEVERF;
2486		}
2487		if (!error && attrflag)
2488			(void) nfscl_loadattrcache(&vp, &nfsva, NULL, NULL,
2489			    0, 1);
2490	} else if (NFS_ISV4(vp)) {
2491		error = nfscl_maperr(td, error, (uid_t)0, (gid_t)0);
2492	}
2493	return (error);
2494}
2495
2496/*
2497 * Strategy routine.
2498 * For async requests when nfsiod(s) are running, queue the request by
2499 * calling ncl_asyncio(), otherwise just all ncl_doio() to do the
2500 * request.
2501 */
2502static int
2503nfs_strategy(struct vop_strategy_args *ap)
2504{
2505	struct buf *bp = ap->a_bp;
2506	struct ucred *cr;
2507
2508	KASSERT(!(bp->b_flags & B_DONE),
2509	    ("nfs_strategy: buffer %p unexpectedly marked B_DONE", bp));
2510	BUF_ASSERT_HELD(bp);
2511
2512	if (bp->b_iocmd == BIO_READ)
2513		cr = bp->b_rcred;
2514	else
2515		cr = bp->b_wcred;
2516
2517	/*
2518	 * If the op is asynchronous and an i/o daemon is waiting
2519	 * queue the request, wake it up and wait for completion
2520	 * otherwise just do it ourselves.
2521	 */
2522	if ((bp->b_flags & B_ASYNC) == 0 ||
2523	    ncl_asyncio(VFSTONFS(ap->a_vp->v_mount), bp, NOCRED, curthread))
2524		(void) ncl_doio(ap->a_vp, bp, cr, curthread, 1);
2525	return (0);
2526}
2527
2528/*
2529 * fsync vnode op. Just call ncl_flush() with commit == 1.
2530 */
2531/* ARGSUSED */
2532static int
2533nfs_fsync(struct vop_fsync_args *ap)
2534{
2535	return (ncl_flush(ap->a_vp, ap->a_waitfor, NULL, ap->a_td, 1, 0));
2536}
2537
2538/*
2539 * Flush all the blocks associated with a vnode.
2540 * 	Walk through the buffer pool and push any dirty pages
2541 *	associated with the vnode.
2542 * If the called_from_renewthread argument is TRUE, it has been called
2543 * from the NFSv4 renew thread and, as such, cannot block indefinitely
2544 * waiting for a buffer write to complete.
2545 */
2546int
2547ncl_flush(struct vnode *vp, int waitfor, struct ucred *cred, struct thread *td,
2548    int commit, int called_from_renewthread)
2549{
2550	struct nfsnode *np = VTONFS(vp);
2551	struct buf *bp;
2552	int i;
2553	struct buf *nbp;
2554	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
2555	int error = 0, slptimeo = 0, slpflag = 0, retv, bvecpos;
2556	int passone = 1, trycnt = 0;
2557	u_quad_t off, endoff, toff;
2558	struct ucred* wcred = NULL;
2559	struct buf **bvec = NULL;
2560	struct bufobj *bo;
2561#ifndef NFS_COMMITBVECSIZ
2562#define	NFS_COMMITBVECSIZ	20
2563#endif
2564	struct buf *bvec_on_stack[NFS_COMMITBVECSIZ];
2565	int bvecsize = 0, bveccount;
2566
2567	if (called_from_renewthread != 0)
2568		slptimeo = hz;
2569	if (nmp->nm_flag & NFSMNT_INT)
2570		slpflag = NFS_PCATCH;
2571	if (!commit)
2572		passone = 0;
2573	bo = &vp->v_bufobj;
2574	/*
2575	 * A b_flags == (B_DELWRI | B_NEEDCOMMIT) block has been written to the
2576	 * server, but has not been committed to stable storage on the server
2577	 * yet. On the first pass, the byte range is worked out and the commit
2578	 * rpc is done. On the second pass, ncl_writebp() is called to do the
2579	 * job.
2580	 */
2581again:
2582	off = (u_quad_t)-1;
2583	endoff = 0;
2584	bvecpos = 0;
2585	if (NFS_ISV34(vp) && commit) {
2586		if (bvec != NULL && bvec != bvec_on_stack)
2587			free(bvec, M_TEMP);
2588		/*
2589		 * Count up how many buffers waiting for a commit.
2590		 */
2591		bveccount = 0;
2592		BO_LOCK(bo);
2593		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2594			if (!BUF_ISLOCKED(bp) &&
2595			    (bp->b_flags & (B_DELWRI | B_NEEDCOMMIT))
2596				== (B_DELWRI | B_NEEDCOMMIT))
2597				bveccount++;
2598		}
2599		/*
2600		 * Allocate space to remember the list of bufs to commit.  It is
2601		 * important to use M_NOWAIT here to avoid a race with nfs_write.
2602		 * If we can't get memory (for whatever reason), we will end up
2603		 * committing the buffers one-by-one in the loop below.
2604		 */
2605		if (bveccount > NFS_COMMITBVECSIZ) {
2606			/*
2607			 * Release the vnode interlock to avoid a lock
2608			 * order reversal.
2609			 */
2610			BO_UNLOCK(bo);
2611			bvec = (struct buf **)
2612				malloc(bveccount * sizeof(struct buf *),
2613				       M_TEMP, M_NOWAIT);
2614			BO_LOCK(bo);
2615			if (bvec == NULL) {
2616				bvec = bvec_on_stack;
2617				bvecsize = NFS_COMMITBVECSIZ;
2618			} else
2619				bvecsize = bveccount;
2620		} else {
2621			bvec = bvec_on_stack;
2622			bvecsize = NFS_COMMITBVECSIZ;
2623		}
2624		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2625			if (bvecpos >= bvecsize)
2626				break;
2627			if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
2628				nbp = TAILQ_NEXT(bp, b_bobufs);
2629				continue;
2630			}
2631			if ((bp->b_flags & (B_DELWRI | B_NEEDCOMMIT)) !=
2632			    (B_DELWRI | B_NEEDCOMMIT)) {
2633				BUF_UNLOCK(bp);
2634				nbp = TAILQ_NEXT(bp, b_bobufs);
2635				continue;
2636			}
2637			BO_UNLOCK(bo);
2638			bremfree(bp);
2639			/*
2640			 * Work out if all buffers are using the same cred
2641			 * so we can deal with them all with one commit.
2642			 *
2643			 * NOTE: we are not clearing B_DONE here, so we have
2644			 * to do it later on in this routine if we intend to
2645			 * initiate I/O on the bp.
2646			 *
2647			 * Note: to avoid loopback deadlocks, we do not
2648			 * assign b_runningbufspace.
2649			 */
2650			if (wcred == NULL)
2651				wcred = bp->b_wcred;
2652			else if (wcred != bp->b_wcred)
2653				wcred = NOCRED;
2654			vfs_busy_pages(bp, 1);
2655
2656			BO_LOCK(bo);
2657			/*
2658			 * bp is protected by being locked, but nbp is not
2659			 * and vfs_busy_pages() may sleep.  We have to
2660			 * recalculate nbp.
2661			 */
2662			nbp = TAILQ_NEXT(bp, b_bobufs);
2663
2664			/*
2665			 * A list of these buffers is kept so that the
2666			 * second loop knows which buffers have actually
2667			 * been committed. This is necessary, since there
2668			 * may be a race between the commit rpc and new
2669			 * uncommitted writes on the file.
2670			 */
2671			bvec[bvecpos++] = bp;
2672			toff = ((u_quad_t)bp->b_blkno) * DEV_BSIZE +
2673				bp->b_dirtyoff;
2674			if (toff < off)
2675				off = toff;
2676			toff += (u_quad_t)(bp->b_dirtyend - bp->b_dirtyoff);
2677			if (toff > endoff)
2678				endoff = toff;
2679		}
2680		BO_UNLOCK(bo);
2681	}
2682	if (bvecpos > 0) {
2683		/*
2684		 * Commit data on the server, as required.
2685		 * If all bufs are using the same wcred, then use that with
2686		 * one call for all of them, otherwise commit each one
2687		 * separately.
2688		 */
2689		if (wcred != NOCRED)
2690			retv = ncl_commit(vp, off, (int)(endoff - off),
2691					  wcred, td);
2692		else {
2693			retv = 0;
2694			for (i = 0; i < bvecpos; i++) {
2695				off_t off, size;
2696				bp = bvec[i];
2697				off = ((u_quad_t)bp->b_blkno) * DEV_BSIZE +
2698					bp->b_dirtyoff;
2699				size = (u_quad_t)(bp->b_dirtyend
2700						  - bp->b_dirtyoff);
2701				retv = ncl_commit(vp, off, (int)size,
2702						  bp->b_wcred, td);
2703				if (retv) break;
2704			}
2705		}
2706
2707		if (retv == NFSERR_STALEWRITEVERF)
2708			ncl_clearcommit(vp->v_mount);
2709
2710		/*
2711		 * Now, either mark the blocks I/O done or mark the
2712		 * blocks dirty, depending on whether the commit
2713		 * succeeded.
2714		 */
2715		for (i = 0; i < bvecpos; i++) {
2716			bp = bvec[i];
2717			bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
2718			if (retv) {
2719				/*
2720				 * Error, leave B_DELWRI intact
2721				 */
2722				vfs_unbusy_pages(bp);
2723				brelse(bp);
2724			} else {
2725				/*
2726				 * Success, remove B_DELWRI ( bundirty() ).
2727				 *
2728				 * b_dirtyoff/b_dirtyend seem to be NFS
2729				 * specific.  We should probably move that
2730				 * into bundirty(). XXX
2731				 */
2732				bufobj_wref(bo);
2733				bp->b_flags |= B_ASYNC;
2734				bundirty(bp);
2735				bp->b_flags &= ~B_DONE;
2736				bp->b_ioflags &= ~BIO_ERROR;
2737				bp->b_dirtyoff = bp->b_dirtyend = 0;
2738				bufdone(bp);
2739			}
2740		}
2741	}
2742
2743	/*
2744	 * Start/do any write(s) that are required.
2745	 */
2746loop:
2747	BO_LOCK(bo);
2748	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2749		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
2750			if (waitfor != MNT_WAIT || passone)
2751				continue;
2752
2753			error = BUF_TIMELOCK(bp,
2754			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2755			    BO_MTX(bo), "nfsfsync", slpflag, slptimeo);
2756			if (error == 0) {
2757				BUF_UNLOCK(bp);
2758				goto loop;
2759			}
2760			if (error == ENOLCK) {
2761				error = 0;
2762				goto loop;
2763			}
2764			if (called_from_renewthread != 0) {
2765				/*
2766				 * Return EIO so the flush will be retried
2767				 * later.
2768				 */
2769				error = EIO;
2770				goto done;
2771			}
2772			if (newnfs_sigintr(nmp, td)) {
2773				error = EINTR;
2774				goto done;
2775			}
2776			if (slpflag & PCATCH) {
2777				slpflag = 0;
2778				slptimeo = 2 * hz;
2779			}
2780			goto loop;
2781		}
2782		if ((bp->b_flags & B_DELWRI) == 0)
2783			panic("nfs_fsync: not dirty");
2784		if ((passone || !commit) && (bp->b_flags & B_NEEDCOMMIT)) {
2785			BUF_UNLOCK(bp);
2786			continue;
2787		}
2788		BO_UNLOCK(bo);
2789		bremfree(bp);
2790		if (passone || !commit)
2791		    bp->b_flags |= B_ASYNC;
2792		else
2793		    bp->b_flags |= B_ASYNC;
2794		bwrite(bp);
2795		if (newnfs_sigintr(nmp, td)) {
2796			error = EINTR;
2797			goto done;
2798		}
2799		goto loop;
2800	}
2801	if (passone) {
2802		passone = 0;
2803		BO_UNLOCK(bo);
2804		goto again;
2805	}
2806	if (waitfor == MNT_WAIT) {
2807		while (bo->bo_numoutput) {
2808			error = bufobj_wwait(bo, slpflag, slptimeo);
2809			if (error) {
2810			    BO_UNLOCK(bo);
2811			    if (called_from_renewthread != 0) {
2812				/*
2813				 * Return EIO so that the flush will be
2814				 * retried later.
2815				 */
2816				error = EIO;
2817				goto done;
2818			    }
2819			    error = newnfs_sigintr(nmp, td);
2820			    if (error)
2821				goto done;
2822			    if (slpflag & PCATCH) {
2823				slpflag = 0;
2824				slptimeo = 2 * hz;
2825			    }
2826			    BO_LOCK(bo);
2827			}
2828		}
2829		if (bo->bo_dirty.bv_cnt != 0 && commit) {
2830			BO_UNLOCK(bo);
2831			goto loop;
2832		}
2833		/*
2834		 * Wait for all the async IO requests to drain
2835		 */
2836		BO_UNLOCK(bo);
2837		mtx_lock(&np->n_mtx);
2838		while (np->n_directio_asyncwr > 0) {
2839			np->n_flag |= NFSYNCWAIT;
2840			error = newnfs_msleep(td, &np->n_directio_asyncwr,
2841			    &np->n_mtx, slpflag | (PRIBIO + 1),
2842			    "nfsfsync", 0);
2843			if (error) {
2844				if (newnfs_sigintr(nmp, td)) {
2845					mtx_unlock(&np->n_mtx);
2846					error = EINTR;
2847					goto done;
2848				}
2849			}
2850		}
2851		mtx_unlock(&np->n_mtx);
2852	} else
2853		BO_UNLOCK(bo);
2854	mtx_lock(&np->n_mtx);
2855	if (np->n_flag & NWRITEERR) {
2856		error = np->n_error;
2857		np->n_flag &= ~NWRITEERR;
2858	}
2859  	if (commit && bo->bo_dirty.bv_cnt == 0 &&
2860	    bo->bo_numoutput == 0 && np->n_directio_asyncwr == 0)
2861  		np->n_flag &= ~NMODIFIED;
2862	mtx_unlock(&np->n_mtx);
2863done:
2864	if (bvec != NULL && bvec != bvec_on_stack)
2865		free(bvec, M_TEMP);
2866	if (error == 0 && commit != 0 && waitfor == MNT_WAIT &&
2867	    (bo->bo_dirty.bv_cnt != 0 || bo->bo_numoutput != 0 ||
2868	     np->n_directio_asyncwr != 0) && trycnt++ < 5) {
2869		/* try, try again... */
2870		passone = 1;
2871		wcred = NULL;
2872		bvec = NULL;
2873		bvecsize = 0;
2874printf("try%d\n", trycnt);
2875		goto again;
2876	}
2877	return (error);
2878}
2879
2880/*
2881 * NFS advisory byte-level locks.
2882 */
2883static int
2884nfs_advlock(struct vop_advlock_args *ap)
2885{
2886	struct vnode *vp = ap->a_vp;
2887	struct ucred *cred;
2888	struct nfsnode *np = VTONFS(ap->a_vp);
2889	struct proc *p = (struct proc *)ap->a_id;
2890	struct thread *td = curthread;	/* XXX */
2891	struct vattr va;
2892	int ret, error = EOPNOTSUPP;
2893	u_quad_t size;
2894
2895	if (NFS_ISV4(vp) && (ap->a_flags & F_POSIX)) {
2896		cred = p->p_ucred;
2897		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2898		if (vp->v_iflag & VI_DOOMED) {
2899			VOP_UNLOCK(vp, 0);
2900			return (EBADF);
2901		}
2902
2903		/*
2904		 * If this is unlocking a write locked region, flush and
2905		 * commit them before unlocking. This is required by
2906		 * RFC3530 Sec. 9.3.2.
2907		 */
2908		if (ap->a_op == F_UNLCK &&
2909		    nfscl_checkwritelocked(vp, ap->a_fl, cred, td))
2910			(void) ncl_flush(vp, MNT_WAIT, cred, td, 1, 0);
2911
2912		/*
2913		 * Loop around doing the lock op, while a blocking lock
2914		 * must wait for the lock op to succeed.
2915		 */
2916		do {
2917			ret = nfsrpc_advlock(vp, np->n_size, ap->a_op,
2918			    ap->a_fl, 0, cred, td);
2919			if (ret == NFSERR_DENIED && (ap->a_flags & F_WAIT) &&
2920			    ap->a_op == F_SETLK) {
2921				VOP_UNLOCK(vp, 0);
2922				error = nfs_catnap(PZERO | PCATCH, ret,
2923				    "ncladvl");
2924				if (error)
2925					return (EINTR);
2926				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2927				if (vp->v_iflag & VI_DOOMED) {
2928					VOP_UNLOCK(vp, 0);
2929					return (EBADF);
2930				}
2931			}
2932		} while (ret == NFSERR_DENIED && (ap->a_flags & F_WAIT) &&
2933		     ap->a_op == F_SETLK);
2934		if (ret == NFSERR_DENIED) {
2935			VOP_UNLOCK(vp, 0);
2936			return (EAGAIN);
2937		} else if (ret == EINVAL || ret == EBADF || ret == EINTR) {
2938			VOP_UNLOCK(vp, 0);
2939			return (ret);
2940		} else if (ret != 0) {
2941			VOP_UNLOCK(vp, 0);
2942			return (EACCES);
2943		}
2944
2945		/*
2946		 * Now, if we just got a lock, invalidate data in the buffer
2947		 * cache, as required, so that the coherency conforms with
2948		 * RFC3530 Sec. 9.3.2.
2949		 */
2950		if (ap->a_op == F_SETLK) {
2951			if ((np->n_flag & NMODIFIED) == 0) {
2952				np->n_attrstamp = 0;
2953				ret = VOP_GETATTR(vp, &va, cred);
2954			}
2955			if ((np->n_flag & NMODIFIED) || ret ||
2956			    np->n_change != va.va_filerev) {
2957				(void) ncl_vinvalbuf(vp, V_SAVE, td, 1);
2958				np->n_attrstamp = 0;
2959				ret = VOP_GETATTR(vp, &va, cred);
2960				if (!ret) {
2961					np->n_mtime = va.va_mtime;
2962					np->n_change = va.va_filerev;
2963				}
2964			}
2965		}
2966		VOP_UNLOCK(vp, 0);
2967		return (0);
2968	} else if (!NFS_ISV4(vp)) {
2969		error = vn_lock(vp, LK_SHARED);
2970		if (error)
2971			return (error);
2972		if ((VFSTONFS(vp->v_mount)->nm_flag & NFSMNT_NOLOCKD) != 0) {
2973			size = VTONFS(vp)->n_size;
2974			VOP_UNLOCK(vp, 0);
2975			error = lf_advlock(ap, &(vp->v_lockf), size);
2976		} else {
2977			if (nfs_advlock_p != NULL)
2978				error = nfs_advlock_p(ap);
2979			else {
2980				VOP_UNLOCK(vp, 0);
2981				error = ENOLCK;
2982			}
2983		}
2984	}
2985	return (error);
2986}
2987
2988/*
2989 * NFS advisory byte-level locks.
2990 */
2991static int
2992nfs_advlockasync(struct vop_advlockasync_args *ap)
2993{
2994	struct vnode *vp = ap->a_vp;
2995	u_quad_t size;
2996	int error;
2997
2998	if (NFS_ISV4(vp))
2999		return (EOPNOTSUPP);
3000	error = vn_lock(vp, LK_SHARED);
3001	if (error)
3002		return (error);
3003	if ((VFSTONFS(vp->v_mount)->nm_flag & NFSMNT_NOLOCKD) != 0) {
3004		size = VTONFS(vp)->n_size;
3005		VOP_UNLOCK(vp, 0);
3006		error = lf_advlockasync(ap, &(vp->v_lockf), size);
3007	} else {
3008		VOP_UNLOCK(vp, 0);
3009		error = EOPNOTSUPP;
3010	}
3011	return (error);
3012}
3013
3014/*
3015 * Print out the contents of an nfsnode.
3016 */
3017static int
3018nfs_print(struct vop_print_args *ap)
3019{
3020	struct vnode *vp = ap->a_vp;
3021	struct nfsnode *np = VTONFS(vp);
3022
3023	ncl_printf("\tfileid %ld fsid 0x%x",
3024	   np->n_vattr.na_fileid, np->n_vattr.na_fsid);
3025	if (vp->v_type == VFIFO)
3026		fifo_printinfo(vp);
3027	printf("\n");
3028	return (0);
3029}
3030
3031/*
3032 * This is the "real" nfs::bwrite(struct buf*).
3033 * We set B_CACHE if this is a VMIO buffer.
3034 */
3035int
3036ncl_writebp(struct buf *bp, int force __unused, struct thread *td)
3037{
3038	int s;
3039	int oldflags = bp->b_flags;
3040#if 0
3041	int retv = 1;
3042	off_t off;
3043#endif
3044
3045	BUF_ASSERT_HELD(bp);
3046
3047	if (bp->b_flags & B_INVAL) {
3048		brelse(bp);
3049		return(0);
3050	}
3051
3052	bp->b_flags |= B_CACHE;
3053
3054	/*
3055	 * Undirty the bp.  We will redirty it later if the I/O fails.
3056	 */
3057
3058	s = splbio();
3059	bundirty(bp);
3060	bp->b_flags &= ~B_DONE;
3061	bp->b_ioflags &= ~BIO_ERROR;
3062	bp->b_iocmd = BIO_WRITE;
3063
3064	bufobj_wref(bp->b_bufobj);
3065	curthread->td_ru.ru_oublock++;
3066	splx(s);
3067
3068	/*
3069	 * Note: to avoid loopback deadlocks, we do not
3070	 * assign b_runningbufspace.
3071	 */
3072	vfs_busy_pages(bp, 1);
3073
3074	BUF_KERNPROC(bp);
3075	bp->b_iooffset = dbtob(bp->b_blkno);
3076	bstrategy(bp);
3077
3078	if( (oldflags & B_ASYNC) == 0) {
3079		int rtval = bufwait(bp);
3080
3081		if (oldflags & B_DELWRI) {
3082			s = splbio();
3083			reassignbuf(bp);
3084			splx(s);
3085		}
3086		brelse(bp);
3087		return (rtval);
3088	}
3089
3090	return (0);
3091}
3092
3093/*
3094 * nfs special file access vnode op.
3095 * Essentially just get vattr and then imitate iaccess() since the device is
3096 * local to the client.
3097 */
3098static int
3099nfsspec_access(struct vop_access_args *ap)
3100{
3101	struct vattr *vap;
3102	struct ucred *cred = ap->a_cred;
3103	struct vnode *vp = ap->a_vp;
3104	accmode_t accmode = ap->a_accmode;
3105	struct vattr vattr;
3106	int error;
3107
3108	/*
3109	 * Disallow write attempts on filesystems mounted read-only;
3110	 * unless the file is a socket, fifo, or a block or character
3111	 * device resident on the filesystem.
3112	 */
3113	if ((accmode & VWRITE) && (vp->v_mount->mnt_flag & MNT_RDONLY)) {
3114		switch (vp->v_type) {
3115		case VREG:
3116		case VDIR:
3117		case VLNK:
3118			return (EROFS);
3119		default:
3120			break;
3121		}
3122	}
3123	vap = &vattr;
3124	error = VOP_GETATTR(vp, vap, cred);
3125	if (error)
3126		goto out;
3127	error  = vaccess(vp->v_type, vap->va_mode, vap->va_uid, vap->va_gid,
3128	    accmode, cred, NULL);
3129out:
3130	return error;
3131}
3132
3133/*
3134 * Read wrapper for fifos.
3135 */
3136static int
3137nfsfifo_read(struct vop_read_args *ap)
3138{
3139	struct nfsnode *np = VTONFS(ap->a_vp);
3140	int error;
3141
3142	/*
3143	 * Set access flag.
3144	 */
3145	mtx_lock(&np->n_mtx);
3146	np->n_flag |= NACC;
3147	getnanotime(&np->n_atim);
3148	mtx_unlock(&np->n_mtx);
3149	error = fifo_specops.vop_read(ap);
3150	return error;
3151}
3152
3153/*
3154 * Write wrapper for fifos.
3155 */
3156static int
3157nfsfifo_write(struct vop_write_args *ap)
3158{
3159	struct nfsnode *np = VTONFS(ap->a_vp);
3160
3161	/*
3162	 * Set update flag.
3163	 */
3164	mtx_lock(&np->n_mtx);
3165	np->n_flag |= NUPD;
3166	getnanotime(&np->n_mtim);
3167	mtx_unlock(&np->n_mtx);
3168	return(fifo_specops.vop_write(ap));
3169}
3170
3171/*
3172 * Close wrapper for fifos.
3173 *
3174 * Update the times on the nfsnode then do fifo close.
3175 */
3176static int
3177nfsfifo_close(struct vop_close_args *ap)
3178{
3179	struct vnode *vp = ap->a_vp;
3180	struct nfsnode *np = VTONFS(vp);
3181	struct vattr vattr;
3182	struct timespec ts;
3183
3184	mtx_lock(&np->n_mtx);
3185	if (np->n_flag & (NACC | NUPD)) {
3186		getnanotime(&ts);
3187		if (np->n_flag & NACC)
3188			np->n_atim = ts;
3189		if (np->n_flag & NUPD)
3190			np->n_mtim = ts;
3191		np->n_flag |= NCHG;
3192		if (vrefcnt(vp) == 1 &&
3193		    (vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
3194			VATTR_NULL(&vattr);
3195			if (np->n_flag & NACC)
3196				vattr.va_atime = np->n_atim;
3197			if (np->n_flag & NUPD)
3198				vattr.va_mtime = np->n_mtim;
3199			mtx_unlock(&np->n_mtx);
3200			(void)VOP_SETATTR(vp, &vattr, ap->a_cred);
3201			goto out;
3202		}
3203	}
3204	mtx_unlock(&np->n_mtx);
3205out:
3206	return (fifo_specops.vop_close(ap));
3207}
3208
3209/*
3210 * Just call ncl_writebp() with the force argument set to 1.
3211 *
3212 * NOTE: B_DONE may or may not be set in a_bp on call.
3213 */
3214static int
3215nfs_bwrite(struct buf *bp)
3216{
3217
3218	return (ncl_writebp(bp, 1, curthread));
3219}
3220
3221struct buf_ops buf_ops_newnfs = {
3222	.bop_name	=	"buf_ops_nfs",
3223	.bop_write	=	nfs_bwrite,
3224	.bop_strategy	=	bufstrategy,
3225	.bop_sync	=	bufsync,
3226	.bop_bdflush	=	bufbdflush,
3227};
3228
3229/*
3230 * Cloned from vop_stdlock(), and then the ugly hack added.
3231 */
3232static int
3233nfs_lock1(struct vop_lock1_args *ap)
3234{
3235	struct vnode *vp = ap->a_vp;
3236	int error = 0;
3237
3238	/*
3239	 * Since vfs_hash_get() calls vget() and it will no longer work
3240	 * for FreeBSD8 with flags == 0, I can only think of this horrible
3241	 * hack to work around it. I call vfs_hash_get() with LK_EXCLOTHER
3242	 * and then handle it here. All I want for this case is a v_usecount
3243	 * on the vnode to use for recovery, while another thread might
3244	 * hold a lock on the vnode. I have the other threads blocked, so
3245	 * there isn't any race problem.
3246	 */
3247	if ((ap->a_flags & LK_TYPE_MASK) == LK_EXCLOTHER) {
3248		if ((ap->a_flags & LK_INTERLOCK) == 0)
3249			panic("ncllock1");
3250		if ((vp->v_iflag & VI_DOOMED))
3251			error = ENOENT;
3252		VI_UNLOCK(vp);
3253		return (error);
3254	}
3255	return (_lockmgr_args(vp->v_vnlock, ap->a_flags, VI_MTX(vp),
3256	    LK_WMESG_DEFAULT, LK_PRIO_DEFAULT, LK_TIMO_DEFAULT, ap->a_file,
3257	    ap->a_line));
3258}
3259
3260static int
3261nfs_getacl(struct vop_getacl_args *ap)
3262{
3263	int error;
3264
3265	if (ap->a_type != ACL_TYPE_NFS4)
3266		return (EOPNOTSUPP);
3267	error = nfsrpc_getacl(ap->a_vp, ap->a_cred, ap->a_td, ap->a_aclp,
3268	    NULL);
3269	if (error > NFSERR_STALE) {
3270		(void) nfscl_maperr(ap->a_td, error, (uid_t)0, (gid_t)0);
3271		error = EPERM;
3272	}
3273	return (error);
3274}
3275
3276static int
3277nfs_setacl(struct vop_setacl_args *ap)
3278{
3279	int error;
3280
3281	if (ap->a_type != ACL_TYPE_NFS4)
3282		return (EOPNOTSUPP);
3283	error = nfsrpc_setacl(ap->a_vp, ap->a_cred, ap->a_td, ap->a_aclp,
3284	    NULL);
3285	if (error > NFSERR_STALE) {
3286		(void) nfscl_maperr(ap->a_td, error, (uid_t)0, (gid_t)0);
3287		error = EPERM;
3288	}
3289	return (error);
3290}
3291
3292/*
3293 * Return POSIX pathconf information applicable to nfs filesystems.
3294 */
3295static int
3296nfs_pathconf(struct vop_pathconf_args *ap)
3297{
3298	struct nfsv3_pathconf pc;
3299	struct nfsvattr nfsva;
3300	struct vnode *vp = ap->a_vp;
3301	struct thread *td = curthread;
3302	int attrflag, error;
3303
3304	if (NFS_ISV34(vp)) {
3305		error = nfsrpc_pathconf(vp, &pc, td->td_ucred, td, &nfsva,
3306		    &attrflag, NULL);
3307		if (attrflag != 0)
3308			(void) nfscl_loadattrcache(&vp, &nfsva, NULL, NULL, 0,
3309			    1);
3310		if (error != 0)
3311			return (error);
3312	} else {
3313		/* For NFSv2, just fake them. */
3314		pc.pc_linkmax = LINK_MAX;
3315		pc.pc_namemax = NFS_MAXNAMLEN;
3316		pc.pc_notrunc = 1;
3317		pc.pc_chownrestricted = 1;
3318		pc.pc_caseinsensitive = 0;
3319		pc.pc_casepreserving = 1;
3320		error = 0;
3321	}
3322	switch (ap->a_name) {
3323	case _PC_LINK_MAX:
3324		*ap->a_retval = pc.pc_linkmax;
3325		break;
3326	case _PC_NAME_MAX:
3327		*ap->a_retval = pc.pc_namemax;
3328		break;
3329	case _PC_PATH_MAX:
3330		*ap->a_retval = PATH_MAX;
3331		break;
3332	case _PC_PIPE_BUF:
3333		*ap->a_retval = PIPE_BUF;
3334		break;
3335	case _PC_CHOWN_RESTRICTED:
3336		*ap->a_retval = pc.pc_chownrestricted;
3337		break;
3338	case _PC_NO_TRUNC:
3339		*ap->a_retval = pc.pc_notrunc;
3340		break;
3341	case _PC_ACL_EXTENDED:
3342		*ap->a_retval = 0;
3343		break;
3344	case _PC_ACL_NFS4:
3345		if (NFS_ISV4(vp) && nfsrv_useacl != 0 && attrflag != 0 &&
3346		    NFSISSET_ATTRBIT(&nfsva.na_suppattr, NFSATTRBIT_ACL))
3347			*ap->a_retval = 1;
3348		else
3349			*ap->a_retval = 0;
3350		break;
3351	case _PC_ACL_PATH_MAX:
3352		if (NFS_ISV4(vp))
3353			*ap->a_retval = ACL_MAX_ENTRIES;
3354		else
3355			*ap->a_retval = 3;
3356		break;
3357	case _PC_MAC_PRESENT:
3358		*ap->a_retval = 0;
3359		break;
3360	case _PC_ASYNC_IO:
3361		/* _PC_ASYNC_IO should have been handled by upper layers. */
3362		KASSERT(0, ("_PC_ASYNC_IO should not get here"));
3363		error = EINVAL;
3364		break;
3365	case _PC_PRIO_IO:
3366		*ap->a_retval = 0;
3367		break;
3368	case _PC_SYNC_IO:
3369		*ap->a_retval = 0;
3370		break;
3371	case _PC_ALLOC_SIZE_MIN:
3372		*ap->a_retval = vp->v_mount->mnt_stat.f_bsize;
3373		break;
3374	case _PC_FILESIZEBITS:
3375		if (NFS_ISV34(vp))
3376			*ap->a_retval = 64;
3377		else
3378			*ap->a_retval = 32;
3379		break;
3380	case _PC_REC_INCR_XFER_SIZE:
3381		*ap->a_retval = vp->v_mount->mnt_stat.f_iosize;
3382		break;
3383	case _PC_REC_MAX_XFER_SIZE:
3384		*ap->a_retval = -1; /* means ``unlimited'' */
3385		break;
3386	case _PC_REC_MIN_XFER_SIZE:
3387		*ap->a_retval = vp->v_mount->mnt_stat.f_iosize;
3388		break;
3389	case _PC_REC_XFER_ALIGN:
3390		*ap->a_retval = PAGE_SIZE;
3391		break;
3392	case _PC_SYMLINK_MAX:
3393		*ap->a_retval = NFS_MAXPATHLEN;
3394		break;
3395
3396	default:
3397		error = EINVAL;
3398		break;
3399	}
3400	return (error);
3401}
3402
3403