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