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